Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Migrate templates to ordinary content docs (#3343)
miles-kt-inkeep05ed67604a6f
diff --git a/.changeset/templates-as-content.md b/.changeset/templates-as-content.mdnew file mode 100644index 000000000..893a13e91--- /dev/null+++ b/.changeset/templates-as-content.md@@ -0,0 +1,18 @@+---+"@inkeep/open-knowledge": minor+---++Templates are now ordinary content files, watched and versioned by the same pipeline as every other document in your project. Nothing moves on disk (a folder's templates still live in `<folder>/.ok/templates/`), and creating, editing, and using templates works exactly as before. What changed is that a template is no longer a special managed object with its own separate watcher, so it inherits everything the regular file pipeline already does.++**Template files now stay live with the rest of your project.** Before, a dedicated watcher covered templates only in folders that already existed when the app started, and only for edits and additions. Now, editing a template file from outside the app (a git pull, a branch switch, an external editor save, a sync merge) reflects live in an open template tab; a template created in a brand-new folder appears without a restart; deleting a template file closes its doc cleanly and the file stays gone; renaming pairs the old and new names instead of showing an unrelated add plus delete; and a template file that picks up merge conflict markers is recognized as conflicted, which pauses writes to it through the templates manager and the API until the conflict is resolved. That last piece is the groundwork for including templates in auto-sync later.++A few deliberate, small changes come with this:++- **Share works on a template tab.** A template has a real path now, so the Share button on its editor tab is available like it is for any other document.+- **Editing a template in an editor tab is recorded in that template's own history, not the folder timeline.** Body and property edits you make in the editor land as ordinary autosave (`wip:`) entries in the template document's history. The folder's activity timeline still shows the create, edit, rename, and delete events for changes made through the templates manager and the API; it just no longer carries your in-editor keystroke saves. This matches how project skills already behave.+- **The tab context menu is honest about what it can do.** For a template tab, Rename, Delete, Duplicate, Hide this file, and Import as template are no longer offered, because those generic file actions never actually worked on a template and belong to the templates manager. Copy relative path stays enabled and now copies the template's real on-disk path for the first time.+- **A template tab left open across the upgrade may reopen empty once.** If you had a template open when you update, that one tab may come back blank on first restore. Reopen the template from the templates manager or the file tree and it is fine, and old bookmarks and links to a template still resolve to it.++**Templates no longer wedge GitHub sync in a local-only-sharing project.** When OpenKnowledge is keeping your project's OK state out of git (a `.ok/` entry in `.git/info/exclude`, written by local-only sharing mode or by `ok clone`), the sync push cycle used to hand your template files to `git add`, which refused them as ignored and failed every push. Sync now skips paths that git ignores and has never tracked, so pushes go through and the templates stay visible and editable in the editor; they simply are not committed. A template that is already tracked in git keeps syncing your edits regardless of ignore rules, matching git's own behavior for tracked files.++Because a template is an ordinary content file now, it also becomes findable the way a hidden `.ok` content file is: a template's name and contents appear in global search (deprioritized so they rank below your regular documents), a template is offered in `[[` and `@` link autocomplete, and a template's own tags and links take part in tag browsing and the backlink graph, so a template can also show up in the orphans list. Project skills already show up in these same places, though they rank normally in search rather than being deprioritized. Templates are still kept out of embeddings and AI semantic retrieval, so they will not surface in generated answers.diff --git a/packages/app/src/components/EditorActivityPool.test.ts b/packages/app/src/components/EditorActivityPool.test.tsindex 091791c48..5c5bac34c 100644--- a/packages/app/src/components/EditorActivityPool.test.ts+++ b/packages/app/src/components/EditorActivityPool.test.ts@@ -22,6 +22,7 @@ import {computeActivityMountList,computeEditorMountGate,computeEffectiveSourceMode,+ computeIsNewDoc,EditorActivityPool,getServerRestartRecoveryView,LARGE_DOC_CHAR_THRESHOLD,@@ -550,6 +551,59 @@ describe('computeEffectiveSourceMode — hidden-entry mode freeze', () => {});});+describe('computeIsNewDoc — create-mode affordance gate', () => {+ test('a doc absent from every surface is a new doc (create-mode draft)', () => {+ expect(computeIsNewDoc({ docName: 'brand-new/idea', pages: new Set(), loading: false })).toBe(+ true,+ );+ });++ test('a doc present in the page index is not new', () => {+ expect(+ computeIsNewDoc({ docName: 'notes/real', pages: new Set(['notes/real']), loading: false }),+ ).toBe(false);+ });++ test('nothing is new while the page list is still loading', () => {+ // The empty-then-populated page list must not flash the create affordance on+ // a doc that simply has not arrived yet.+ expect(computeIsNewDoc({ docName: 'brand-new/idea', pages: new Set(), loading: true })).toBe(+ false,+ );+ });++ test('a freshly created template is not flagged as a new doc during the index-lag window', () => {+ // A template content doc enters `pages` only after the async `files` refetch;+ // keying purely on membership would flash the create-mode affordance for a+ // real template. The structural check suppresses it at both depths even with+ // an empty page set.+ expect(+ computeIsNewDoc({ docName: '.ok/templates/daily', pages: new Set(), loading: false }),+ ).toBe(false);+ expect(+ computeIsNewDoc({ docName: 'docs/.ok/templates/note', pages: new Set(), loading: false }),+ ).toBe(false);+ });++ test('a template already indexed in pages is likewise not new', () => {+ expect(+ computeIsNewDoc({+ docName: 'docs/.ok/templates/note',+ pages: new Set(['docs/.ok/templates/note']),+ loading: false,+ }),+ ).toBe(false);+ });++ test('a managed-artifact doc absent from pages is not new (global skill)', () => {+ // Managed artifacts never appear in `pages`; the create affordance must not+ // fire for them either.+ expect(+ computeIsNewDoc({ docName: '__skill__/global/foo', pages: new Set(), loading: false }),+ ).toBe(false);+ });+});+describe('computeActivityMountList — system doc filtering (DX7 defense-in-depth)', () => {test('__system__ doc filtered out even if present in entries', () => {// ProviderPool.open already rejects system docs at admission, but the helperdiff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsxindex f8ffcc43f..2b9c049c1 100644--- a/packages/app/src/components/EditorActivityPool.tsx+++ b/packages/app/src/components/EditorActivityPool.tsx@@ -38,6 +38,7 @@ import {isEditableTextDocFile,isManagedArtifactDocName,isMermaidDocFile,+ parseTemplateContentDocName,} from '@inkeep/open-knowledge-core';import { t } from '@lingui/core/macro';import { Loader2, RefreshCw } from 'lucide-react';@@ -224,6 +225,35 @@ export function computeEffectiveSourceMode(return isActive ? isSourceMode : lastActiveIsSourceMode;}+/**+ * Whether an Activity entry should render the create-mode "new doc" affordance+ * (empty draft that starts a page on first keystroke). A doc counts as new only+ * when it is genuinely absent from every surface a real doc registers under:+ * the page index, managed artifacts, template content docs, and Mermaid /+ * editable-text docs.+ *+ * Templates and project skills only enter the page list after the async `files`+ * refetch, so a purely `pages`-membership check would flash the create-mode+ * affordance for a freshly created template during that index-lag window. The+ * structural `parseTemplateContentDocName` / `isManagedArtifactDocName` checks+ * suppress that even before the index catches up.+ */+export function computeIsNewDoc(args: {+ docName: string;+ pages: ReadonlySet<string>;+ loading: boolean;+}): boolean {+ const { docName, pages, loading } = args;+ return (+ !loading &&+ !pages.has(docName) &&+ !isManagedArtifactDocName(docName) &&+ parseTemplateContentDocName(docName) === null &&+ !isMermaidDocFile(docName) &&+ !isEditableTextDocFile(docName)+ );+}+/*** Minimum number of editors mounted concurrently inside `<Activity>`* boundaries. Decoupled from `MAX_POOL` (exported from `provider-pool.ts`,@@ -527,13 +557,7 @@ function EditorActivityPoolInner({}isSourceMode={isSourceMode}editorPlaceholder={editorPlaceholder}- isNewDoc={- !loading &&- !pages.has(entry.docName) &&- !isManagedArtifactDocName(entry.docName) &&- !isMermaidDocFile(entry.docName) &&- !isEditableTextDocFile(entry.docName)- }+ isNewDoc={computeIsNewDoc({ docName: entry.docName, pages, loading })}previousDocName={previousDocName}onNavigateBack={onNavigateBack}onRecycle={onRecycle}@@ -1449,7 +1473,8 @@ function ActivityEntry({PropertyPanel (frontmatter table, null when empty). */}{!effectiveIsSourceMode &&(isManagedArtifactDocName(entry.docName) ||- parseProjectSkillContentDocName(entry.docName) ? (+ parseProjectSkillContentDocName(entry.docName) ||+ parseTemplateContentDocName(entry.docName) ? (<Suspense fallback={null}><ManagedArtifactPropertiesdocName={entry.docName}diff --git a/packages/app/src/components/EditorBreadcrumb.tsx b/packages/app/src/components/EditorBreadcrumb.tsxindex 8244d4843..6e2724d5b 100644--- a/packages/app/src/components/EditorBreadcrumb.tsx+++ b/packages/app/src/components/EditorBreadcrumb.tsx@@ -1,4 +1,4 @@-import { parseManagedArtifactName } from '@inkeep/open-knowledge-core';+import { parseManagedArtifactName, parseTemplateContentDocName } from '@inkeep/open-knowledge-core';import { MoreHorizontalIcon } from 'lucide-react';import { Fragment } from 'react';import { UserText } from '@/components/UserText';@@ -64,16 +64,18 @@ type BreadcrumbNode =*/export function EditorBreadcrumb({ docName, className }: EditorBreadcrumbProps) {if (!docName) return null;- // Managed-artifact tabs derive their breadcrumb from the parsed artifact, not- // the raw `__skill__`/`__template__` doc-name prefix: a template shows its- // owning folder path; a skill has no folder hierarchy (its identity lives in- // the property panel + tab badge), so it renders no breadcrumb.- const managed = parseManagedArtifactName(docName);- const segments = managed- ? managed.kind === 'template'- ? managed.folder.split('/').filter(Boolean)- : []- : tabParts(docName, '').prefix.replace(/\/$/, '').split('/').filter(Boolean);+ // A template shows its owning folder path, derived from the content shape and+ // hiding the `.ok/templates/` segment (matching the name-only tab label); a+ // skill has no folder hierarchy (its identity lives in the property panel + tab+ // badge), so it renders no breadcrumb. Everything else derives from `tabParts`+ // so the breadcrumb and tab label split the path through one primitive.+ const template = parseTemplateContentDocName(docName);+ const managed = template ? null : parseManagedArtifactName(docName);+ const segments = template+ ? template.folder.split('/').filter(Boolean)+ : managed+ ? []+ : tabParts(docName, '').prefix.replace(/\/$/, '').split('/').filter(Boolean);if (segments.length === 0) return null;// Stable per-segment key: full prefix slice up to that segment.diff --git a/packages/app/src/components/EditorHeader.tsx b/packages/app/src/components/EditorHeader.tsxindex d8686b73b..4e77ade5e 100644--- a/packages/app/src/components/EditorHeader.tsx+++ b/packages/app/src/components/EditorHeader.tsx@@ -51,11 +51,12 @@ export function EditorHeader({}: EditorHeaderProps) {const { t } = useLingui();const { activeDocName, activeTarget } = useDocumentContext();- // Managed-artifact tabs (skills/templates) are ordinary docs but carry their- // own header treatment: neither skills nor templates are shareable (the- // synthetic doc name isn't a real on-disk path to share), so the ShareButton- // trigger gates on this. The agent-handoff for a skill lives in the Skills- // sidebar (SkillsSidebarSection / skill-actions), not the header.+ // A GLOBAL skill (or an external skill) is a managed-artifact tab whose+ // synthetic doc name has no real on-disk path to share, so the ShareButton+ // trigger gates on this. Templates and project skills are content docs with+ // real paths and share like any doc (`parseManagedArtifactName` returns null+ // for them). The agent-handoff for a skill lives in the Skills sidebar+ // (SkillsSidebarSection / skill-actions), not the header.const managedArtifact = activeDocName ? parseManagedArtifactName(activeDocName) : null;const { state: sidebarState } = useSidebar();// No-project single-file session (`ok <file>`): drop the project chrome@@ -80,8 +81,8 @@ export function EditorHeader({if (activeTarget?.kind === 'folder') {return buildFolderShareInput(activeTarget.folderPath);}- // Managed-artifact tabs aren't shareable — their synthetic doc name has no- // shareable on-disk path.+ // A managed-artifact tab (global/external skill) has no shareable on-disk+ // path; a content doc (ordinary doc, template, or project skill) does.if (activeDocName && !managedArtifact) {return buildDocShareInput(activeDocName);}diff --git a/packages/app/src/components/EditorTabTargetMenuItems.dom.test.tsx b/packages/app/src/components/EditorTabTargetMenuItems.dom.test.tsxnew file mode 100644index 000000000..c41a48bf0--- /dev/null+++ b/packages/app/src/components/EditorTabTargetMenuItems.dom.test.tsx@@ -0,0 +1,184 @@+// @vitest-environment jsdom+/**+ * Tab-context-menu action states for a template DOC tab.+ *+ * A template is a content doc now, so its tab target is an ordinary+ * `{ kind: 'doc' }` whose relative path carries a `.ok/templates/` segment. The+ * menu's mutation gate keys on `hasOkPathSegment(relativePathForTarget(target))`,+ * so those actions disable for template tabs with NO template-aware code — the+ * doc-name shape alone drives it. This renders the real component (its private+ * `relativePathForTarget` + the shared `FileTargetMenuItems` renderer stay live)+ * and asserts which items appear. The ordinary-doc control proves the actions+ * are only withheld because of the `.ok` shape, not because the menu is inert.+ *+ * The heavy context graph is stubbed the way the sibling `EditorTabs.dom` /+ * `FileTargetMenuItems.dom` tests do it — everything except the component under+ * test and the shared renderer is a marker.+ */++import * as actualLinguiMacro from '@lingui/react/macro';+import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';+import type { EditorTabFileTarget } from './EditorTabTargetMenuItems';++const scheduleClipboardWrite = vi.fn(() => Promise.resolve());++vi.doMock('@lingui/react/macro', () => ({+ ...actualLinguiMacro,+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,+ useLingui: () => ({ t: renderLinguiTemplate }),+}));++vi.doMock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++vi.doMock('@/components/ui/context-menu', () => ({+ ContextMenuGroup: ({ children }: { children?: ReactNode }) => <>{children}</>,+ ContextMenuItem: ({+ children,+ disabled,+ onSelect,+ ...props+ }: {+ children?: ReactNode;+ disabled?: boolean;+ onSelect?: () => void;+ [key: string]: unknown;+ }) => (+ <button+ type="button"+ role="menuitem"+ disabled={disabled}+ onClick={() => {+ if (!disabled) onSelect?.();+ }}+ {...props}+ >+ {children}+ </button>+ ),+ ContextMenuSeparator: () => <hr />,+ ContextMenuSub: ({ children }: { children?: ReactNode }) => <>{children}</>,+ ContextMenuSubContent: ({ children }: { children?: ReactNode }) => <>{children}</>,+ ContextMenuSubTrigger: ({+ children,+ disabled,+ ...props+ }: {+ children?: ReactNode;+ disabled?: boolean;+ [key: string]: unknown;+ }) => (+ <button type="button" role="menuitem" disabled={disabled} {...props}>+ {children}+ </button>+ ),+}));++vi.doMock('@/lib/use-workspace', () => ({+ useWorkspace: () => ({ contentDir: '/workspace', pathSeparator: '/' }),+}));++vi.doMock('@/lib/config-provider', () => ({+ useConfigContext: () => ({ okignoreBinding: { current: () => '', patch: vi.fn() } }),+}));++vi.doMock('@/hooks/use-git-sync-status', () => ({+ useGitSyncStatusDetailed: () => ({ status: { hasRemote: true } }),+}));++vi.doMock('@/components/handoff/useHandoffDispatch', () => ({+ useHandoffDispatch: () => ({ dispatch: vi.fn() }),+}));++vi.doMock('@/components/handoff/useInstalledAgents', () => ({+ useInstalledAgents: () => ({ states: {} }),+}));++vi.doMock('@/components/handoff/OpenInAgentEmptySpaceSubmenu', () => ({+ OpenInAgentEmptySpaceSubmenu: () => null,+}));++vi.doMock('@/components/template-menu-rows', () => ({+ TemplateMenuRows: () => null,+}));++vi.doMock('@/lib/share/clipboard-adapter', () => ({ scheduleClipboardWrite }));++vi.doMock('@/lib/file-menu-target-resolvers', () => ({+ buildSendToAiInputForActiveTarget: () => null,+ resolveActiveTargetRelativePath: (target: EditorTabFileTarget) =>+ target.kind === 'folder' ? target.folderPath : ((target as { docName?: string }).docName ?? ''),+}));++const { EditorTabTargetMenuItems } = await import('./EditorTabTargetMenuItems');++function renderMenu(target: EditorTabFileTarget) {+ return render(+ <div role="menu">+ <EditorTabTargetMenuItems target={target} onRename={() => {}} />+ </div>,+ );+}++function docTarget(docName: string): EditorTabFileTarget {+ return { kind: 'doc', target: docName, docName };+}++// The five `.ok`-gated mutation actions that must disappear for a template tab.+const OK_GATED_ACTIONS = ['Import as template', 'Duplicate', 'Rename', 'Hide this file', 'Delete'];++afterEach(() => {+ cleanup();+ scheduleClipboardWrite.mockClear();+});++describe('EditorTabTargetMenuItems — template doc tab', () => {+ test('the five .ok-gated mutation actions are withheld', () => {+ renderMenu(docTarget('docs/.ok/templates/note'));+ for (const label of OK_GATED_ACTIONS) {+ expect(screen.queryByRole('menuitem', { name: label })).toBeNull();+ }+ });++ test('Copy relative path stays enabled and copies the real on-disk path', () => {+ renderMenu(docTarget('docs/.ok/templates/note'));+ const relativePath = screen.getByRole('menuitem', { name: 'Relative path' });+ fireEvent.click(relativePath);+ // The template content doc name is ext-less; the copied path is the real+ // file on disk (the `.md` the doc name elides), not the useless synthetic+ // name the pre-migration tab copied.+ expect(scheduleClipboardWrite).toHaveBeenCalledWith('docs/.ok/templates/note.md');+ });++ test('Share stays available (a template content doc has a real shareable path)', () => {+ renderMenu(docTarget('docs/.ok/templates/note'));+ expect(screen.getByRole('menuitem', { name: 'Share' })).toBeTruthy();+ });++ test('a project-root template tab is gated identically', () => {+ renderMenu(docTarget('.ok/templates/daily'));+ for (const label of OK_GATED_ACTIONS) {+ expect(screen.queryByRole('menuitem', { name: label })).toBeNull();+ }+ expect(screen.getByRole('menuitem', { name: 'Relative path' })).toBeTruthy();+ });+});++describe('EditorTabTargetMenuItems — ordinary doc control', () => {+ test('the same actions DO appear for a non-.ok doc, proving the gate is the .ok shape', () => {+ // Acid test: if these were absent for every doc tab the template assertions+ // above would pass vacuously. An ordinary doc offers the full mutation set.+ renderMenu(docTarget('docs/note'));+ for (const label of OK_GATED_ACTIONS) {+ expect(screen.getByRole('menuitem', { name: label })).toBeTruthy();+ }+ });++ test('Copy relative path on an ordinary doc copies its own on-disk path', () => {+ renderMenu(docTarget('docs/note'));+ fireEvent.click(screen.getByRole('menuitem', { name: 'Relative path' }));+ expect(scheduleClipboardWrite).toHaveBeenCalledWith('docs/note.md');+ });+});diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsxindex ed3a51cad..9f04391b8 100644--- a/packages/app/src/components/FileTree.tsx+++ b/packages/app/src/components/FileTree.tsx@@ -1017,11 +1017,13 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {const docEntry = entries.find((item): item is DocumentEntry => isDocumentEntry(item) && item.docName === action.path,);- // Revealed `.ok` document rows never open the raw editable editor: the- // shared routing sends template files to the template editor, keeps- // indexed skill docs on the normal doc flow (null), and lands everything- // else on the read-only text viewer — same rule the hash resolver's- // doc-open guard applies.+ // Revealed `.ok` document rows never open the raw create-mode editor. The+ // shared routing returns null for the sanctioned content docs — template+ // leaves (matched by shape, so a freshly-created template that lags the page+ // index still routes right) and indexed skill docs (matched by page-list+ // membership) — which fall through to the editable doc open below; every+ // other `.ok` file resolves to the read-only text viewer. Same rule the hash+ // resolver's doc-open guard applies.const okTarget = okContentNavigationTarget(action.path, {pages,docExt: docEntry?.docExt,diff --git a/packages/app/src/components/ManagedArtifactProperties.tsx b/packages/app/src/components/ManagedArtifactProperties.tsxindex 276d3fcef..bcb1e2fad 100644--- a/packages/app/src/components/ManagedArtifactProperties.tsx+++ b/packages/app/src/components/ManagedArtifactProperties.tsx@@ -2,7 +2,9 @@ import type { HocuspocusProvider } from '@hocuspocus/provider';import {isExternalSkillDocName,parseManagedArtifactName,+ parseTemplateContentDocName,type SkillScope,+ templateContentDocName,} from '@inkeep/open-knowledge-core';import { useLingui } from '@lingui/react/macro';import { useState } from 'react';@@ -14,11 +16,7 @@ import { useDocumentContext } from '@/editor/DocumentContext';import { docNameForTabId, isSkillDocName } from '@/editor/editor-tabs';import { hashFromDocName, replaceHashWithoutNavigation } from '@/lib/doc-hash';import { moveTemplate } from '@/lib/folder-config-api';-import {- parseProjectSkillContentDocName,- skillLiveDocName,- templateDocName,-} from '@/lib/managed-artifact-doc-name';+import { parseProjectSkillContentDocName, skillLiveDocName } from '@/lib/managed-artifact-doc-name';import { moveSkill } from '@/lib/skills-api';/**@@ -48,16 +46,6 @@ export function ManagedArtifactProperties({}return <SkillPropertiesPanel provider={provider} scope={parsed.scope} name={parsed.name} />;}- if (parsed?.kind === 'template') {- return (- <TemplatePropertiesPanel- provider={provider}- docName={docName}- folder={parsed.folder}- name={parsed.name}- />- );- }// Project skills open as content docs (`.ok/skills/<name>/SKILL`) rather than// `__skill__/project/...`, but render the SAME identity panel as global// skills so the two scopes aren't a disconnected experience.@@ -67,6 +55,21 @@ export function ManagedArtifactProperties({// managed-artifact doc, but its identity panel is the same one.return <SkillPropertiesPanel provider={provider} scope="project" name={projectSkillName} />;}+ // Templates are content docs (`<folder>/.ok/templates/<name>`) too, dispatched+ // on the content shape rather than a synthetic name. `name` is identity, not+ // free-form frontmatter — committing it relocates the template on disk and+ // re-points the open tab.+ const parsedTemplate = parseTemplateContentDocName(docName);+ if (parsedTemplate) {+ return (+ <TemplatePropertiesPanel+ provider={provider}+ docName={docName}+ folder={parsedTemplate.folder}+ name={parsedTemplate.name}+ />+ );+ }// An editable-unmanaged skill (`__extskill__/<name>`, edited in place) is routed// here by `isManagedArtifactDocName`, but its frontmatter (name/description/// argument-hint) is free-form YAML, not OK-managed identity — there's no scope@@ -218,7 +221,7 @@ function TemplatePropertiesPanel({return;}toast.success(t`Template renamed`);- retarget(docName, templateDocName(folder, next));+ retarget(docName, templateContentDocName(folder, next));}return (diff --git a/packages/app/src/components/TemplateProperties.dom.test.tsx b/packages/app/src/components/TemplateProperties.dom.test.tsxindex a526df8f1..60c2e8aee 100644--- a/packages/app/src/components/TemplateProperties.dom.test.tsx+++ b/packages/app/src/components/TemplateProperties.dom.test.tsx@@ -22,7 +22,7 @@ function makeProvider(source: string): { provider: HocuspocusProvider; ytext: Y.ytext.insert(0, source);const provider = {document,- configuration: { name: '__template__/notes/meeting' },+ configuration: { name: 'notes/.ok/templates/meeting' },on: () => {},off: () => {},} as unknown as HocuspocusProvider;diff --git a/packages/app/src/components/TemplatesCard.tsx b/packages/app/src/components/TemplatesCard.tsxindex fc6c02d25..3290f7e03 100644--- a/packages/app/src/components/TemplatesCard.tsx+++ b/packages/app/src/components/TemplatesCard.tsx@@ -1,3 +1,4 @@+import { templateContentDocName } from '@inkeep/open-knowledge-core';import { Trans } from '@lingui/react/macro';import { Plus } from 'lucide-react';import { useState } from 'react';@@ -15,7 +16,6 @@ import type {FolderConfigSnapshot,TemplateMenuEntry,} from '@/hooks/use-folder-config';-import { templateDocName } from '@/lib/managed-artifact-doc-name';import { openManagedArtifactTab } from '@/lib/open-managed-artifact-tab';interface Props {@@ -109,7 +109,7 @@ export function TemplatesCard({ folderPath, state, onChange, folderConfigHandletemplate={tpl}onCreate={() => setCreateFromTemplate(tpl.name)}onEdit={() =>- openManagedArtifactTab(templateDocName(tpl.source_folder, tpl.name))+ openManagedArtifactTab(templateContentDocName(tpl.source_folder, tpl.name))}onDelete={() => setDeleteTarget(tpl)}badge={@@ -140,7 +140,7 @@ export function TemplatesCard({ folderPath, state, onChange, folderConfigHandleonOpenChange={setNewOpen}onCreated={(createdName) => {onChange();- openManagedArtifactTab(templateDocName(folderPath, createdName));+ openManagedArtifactTab(templateContentDocName(folderPath, createdName));}}/><NewItemDialogdiff --git a/packages/app/src/components/file-tree-selection.test.ts b/packages/app/src/components/file-tree-selection.test.tsindex 542ef5c60..5c93bff15 100644--- a/packages/app/src/components/file-tree-selection.test.ts+++ b/packages/app/src/components/file-tree-selection.test.ts@@ -457,7 +457,7 @@ describe('previewTabIdForTreePath — revealed .ok rows', () => {// the selection action resolves. Deriving the tab id from the action alone// yields an id no pane owns, so the double-click is a silent no-op on exactly// these rows whenever "Show .ok folders" is on.- test('a template row resolves to its managed-artifact doc tab', () => {+ test('a template row resolves to its content doc tab', () => {expect(previewTabIdForTreePath('.ok/templates/meeting.md',@@ -472,7 +472,7 @@ describe('previewTabIdForTreePath — revealed .ok rows', () => {],new Set<string>(),),- ).toBe(docTabId('__template__/meeting'));+ ).toBe(docTabId('.ok/templates/meeting'));});test('a non-page .ok doc row resolves to the read-only asset tab', () => {diff --git a/packages/app/src/components/navigation-targets.test.ts b/packages/app/src/components/navigation-targets.test.tsindex 01644279c..d28066d91 100644--- a/packages/app/src/components/navigation-targets.test.ts+++ b/packages/app/src/components/navigation-targets.test.ts@@ -67,16 +67,38 @@ describe('deriveKnownFolderPaths', () => {describe('resolveNavigationTarget', () => {test('resolves managed-artifact docs as real doc targets (never missing)', () => {- // Global skills + templates live outside the page list, so the membership- // checks would mark them 'missing' — but they're real synthetic docs.- // Resolve directly so hash nav opens them and graph/links aren't broken.- for (const docName of ['__skill__/global/foo', '__template__/notes/daily']) {- expect(resolveNavigationTarget(docName, { pages: new Set() })).toEqual({- kind: 'doc',- target: docName,- docName,- });- }+ // A global skill lives outside the page list, so the membership checks would+ // mark it 'missing' — but it's a real synthetic doc. Resolve directly so hash+ // nav opens it and graph/links aren't broken.+ const docName = '__skill__/global/foo';+ expect(resolveNavigationTarget(docName, { pages: new Set() })).toEqual({+ kind: 'doc',+ target: docName,+ docName,+ });+ });++ test('redirects a stale `__template__/…` deep-link to the content doc', () => {+ // Templates are content docs now; a stale synthetic bookmark must redirect to+ // the live content doc, not open a phantom empty tab. The legacy parser+ // percent-DECODES segments, so an encoded spaced folder lands on the raw name.+ expect(resolveNavigationTarget('__template__/notes/daily', { pages: new Set() })).toEqual({+ kind: 'doc',+ target: 'notes/.ok/templates/daily',+ docName: 'notes/.ok/templates/daily',+ });+ // Root-level legacy name (no folder segment).+ expect(resolveNavigationTarget('__template__/daily', { pages: new Set() })).toEqual({+ kind: 'doc',+ target: '.ok/templates/daily',+ docName: '.ok/templates/daily',+ });+ // Percent-encoded legacy name with a spaced folder.+ expect(resolveNavigationTarget('__template__/My%20Notes/daily', { pages: new Set() })).toEqual({+ kind: 'doc',+ target: 'My Notes/.ok/templates/daily',+ docName: 'My Notes/.ok/templates/daily',+ });});test('resolves a PROJECT skill content doc without page-index membership', () => {@@ -135,7 +157,7 @@ describe('resolveNavigationTarget', () => {});});- test('resolves a skill file-path link as content and a template link to its artifact', () => {+ test('resolves skill and template file-path links as content docs', () => {// Project skills are content docs now: a link to a skill file resolves// through the normal page index, NOT to a synthetic __skill__ artifact doc.const skillDoc = '.ok/skills/open-knowledge-pack-knowledge-base/SKILL';@@ -144,12 +166,31 @@ describe('resolveNavigationTarget', () => {target: skillDoc,docName: skillDoc,});- // Templates remain managed artifacts and still map by their on-disk file path.+ // Templates are content docs too: a link resolves to the content doc name,+ // not the dead `__template__/…` synthetic.expect(resolveNavigationTarget('notes/.ok/templates/daily', { pages: new Set() })).toEqual({kind: 'doc',- target: '__template__/notes/daily',- docName: '__template__/notes/daily',+ target: 'notes/.ok/templates/daily',+ docName: 'notes/.ok/templates/daily',+ });+ });++ test('resolves a template content doc structurally, normalizing a .md link to ext-less', () => {+ // A freshly-created template lags the page index; it must still resolve to the+ // template DOC (structural early-resolve), not the read-only asset viewer. A+ // doc-body link carrying `.md` normalizes to the same ext-less content name.+ expect(resolveNavigationTarget('projects/.ok/templates/plan', { pages: new Set() })).toEqual({+ kind: 'doc',+ target: 'projects/.ok/templates/plan',+ docName: 'projects/.ok/templates/plan',});+ expect(resolveNavigationTarget('projects/.ok/templates/plan.md', { pages: new Set() })).toEqual(+ {+ kind: 'doc',+ target: 'projects/.ok/templates/plan',+ docName: 'projects/.ok/templates/plan',+ },+ );});test('prefers an exact document over folder landing notes', () => {@@ -412,17 +453,15 @@ describe('okContentNavigationTarget (read-only .ok routing)', () => {expect(okContentNavigationTarget('docs/ok/guide', { pages })).toBeNull();});- test('template file paths rewrite to the managed-artifact template editor', () => {- expect(okContentNavigationTarget('.ok/templates/meeting', { pages })).toEqual({- kind: 'doc',- target: '__template__/meeting',- docName: '__template__/meeting',- });- expect(okContentNavigationTarget('team/.ok/templates/spec', { pages })).toEqual({- kind: 'doc',- target: '__template__/team/spec',- docName: '__template__/team/spec',- });+ test('a template content doc keeps the normal doc flow even when it lags the page index', () => {+ // Templates ARE content docs in `/api/pages`, but a freshly-created one lags+ // the page index. This `pages` set omits the template to simulate that+ // index-lag window: the structural SHAPE match must still route a revealed+ // template row to the editable template editor, not the read-only asset+ // viewer. The skills carve-out below leans on membership because skills ship+ // in the page list.+ expect(okContentNavigationTarget('.ok/templates/meeting', { pages })).toBeNull();+ expect(okContentNavigationTarget('team/.ok/templates/spec', { pages })).toBeNull();});test('page-list members stay normal content docs (skills carve-out)', () => {@@ -454,8 +493,9 @@ describe('okContentNavigationTarget (read-only .ok routing)', () => {});test('nested template paths are not template files — they land on the viewer', () => {- // The template rewrite only matches single-segment leaves; a nested path- // must not fall through to an editable resolution.+ // A template is a single-segment leaf under `.ok/templates/`; a nested path is+ // not one, so it gets no structural template resolution and falls to the+ // read-only viewer like any other unindexed `.ok` file.expect(okContentNavigationTarget('.ok/templates/a/b', { pages })).toMatchObject({kind: 'asset',assetPath: '.ok/templates/a/b.md',@@ -541,10 +581,12 @@ describe('resolveNavigationTarget — folder-shaped .ok targets', () => {});test('doc-shaped .ok targets keep their read-only routing', () => {+ // A template content doc resolves structurally to itself even before the page+ // index catches up (it is not in `options.pages` here).expect(resolveNavigationTarget('articles/.ok/templates/meeting', options)).toEqual({kind: 'doc',- target: '__template__/articles/meeting',- docName: '__template__/articles/meeting',+ target: 'articles/.ok/templates/meeting',+ docName: 'articles/.ok/templates/meeting',});expect(resolveNavigationTarget('.ok/skills/writer/SKILL', {@@ -561,12 +603,11 @@ describe('resolveNavigationTarget — folder-shaped .ok targets', () => {});});- test('a trailing-slash template path returns missing, bypassing the rewrite', () => {- // `managedArtifactDocNameFromContentTarget` rejects the slashed form, so- // before the shape gate this reached the fallback, which re-tested the- // slash-stripped path and rewrote it to the template editor. The folder- // shape now wins instead. Pinned so a caller that later emits- // trailing-slash template hashes cannot flip this silently.+ test('a trailing-slash template path returns missing (folder-shaped, not a doc)', () => {+ // The template shape parser rejects the slashed form, so a trailing-slash+ // template path is treated as a folder, not a template doc. Pinned so a caller+ // that later emits trailing-slash template hashes cannot silently flip this+ // into a doc resolution.expect(resolveNavigationTarget('articles/.ok/templates/meeting/', options)).toEqual({kind: 'missing',target: 'articles/.ok/templates/meeting',@@ -596,7 +637,7 @@ describe('resolveNavigationTarget .ok guard', () => {});});- test('sanctioned .ok resolutions are unchanged: skills stay docs, templates rewrite', () => {+ test('sanctioned .ok resolutions: skills and templates both stay content docs', () => {expect(resolveNavigationTarget('.ok/skills/writer/SKILL', options)).toEqual({kind: 'doc',target: '.ok/skills/writer/SKILL',@@ -604,8 +645,8 @@ describe('resolveNavigationTarget .ok guard', () => {});expect(resolveNavigationTarget('.ok/templates/meeting', options)).toEqual({kind: 'doc',- target: '__template__/meeting',- docName: '__template__/meeting',+ target: '.ok/templates/meeting',+ docName: '.ok/templates/meeting',});});diff --git a/packages/app/src/components/navigation-targets.ts b/packages/app/src/components/navigation-targets.tsindex 50dac1834..bdcaa266e 100644--- a/packages/app/src/components/navigation-targets.ts+++ b/packages/app/src/components/navigation-targets.ts@@ -5,11 +5,13 @@ import {isEditableTextDocFile,isManagedArtifactDocName,isMermaidDocFile,- managedArtifactDocNameFromContentTarget,mediaKindForSidebarAssetExtension,+ parseLegacyTemplateDocName,parseManagedArtifactName,+ parseTemplateContentDocName,projectSkillContentDocName,type SkillScope,+ templateContentDocName,toWikiLinkSlug,} from '@inkeep/open-knowledge-core';import { isSkillBundleShapedPath, isSkillDocName } from '@/editor/editor-tabs';@@ -217,12 +219,14 @@ function okReadOnlyAssetPath(docName: string, docExt?: string): string {* construction (persistence has no content-filter gate), so every doc-shaped* resolution of a `.ok` target must land on a sanctioned surface:*- * - Template FILE paths (`[<folder>/].ok/templates/<name>`, single-segment- * leaf) rewrite to their managed-artifact doc — the validating template- * editor. Same rule the wiki-link resolver already applies.- * - Page-list members (the `.ok/skills/**` carve-out) return null: they are- * sanctioned content docs and keep the normal doc flow (the skill editor- * chrome keys off the docName).+ * - Template leaves (`[<folder>/].ok/templates/<name>`) return null by SHAPE:+ * they are sanctioned content docs. Templates DO ship in `/api/pages`, but a+ * freshly-created one lags the page index, and during that window a membership+ * test would misroute the revealed row to the read-only viewer. Matching by+ * shape routes it right regardless of index lag; returning null keeps the+ * normal doc flow (the template editor chrome keys off the docName).+ * - Page-list members (the `.ok/skills/**` carve-out) return null: skills also+ * ship in the page list, and membership is a fine signal for them.* - Everything else resolves to the read-only text viewer on the file's* on-disk path; for a nonexistent file the viewer's error pane is the* non-create "missing" surface.@@ -236,10 +240,13 @@ export function okContentNavigationTarget(options: { pages: ReadonlySet<string>; docExt?: string },): ResolvedContentTarget | null {if (!hasOkPathSegment(docName)) return null;- const artifactDocName = managedArtifactDocNameFromContentTarget(docName);- if (artifactDocName) {- return { kind: 'doc', target: artifactDocName, docName: artifactDocName };- }+ // Templates ARE content docs in `/api/pages`, but a freshly-created template+ // lags the page index, so a membership test (as the skills carve-out below+ // does) would misroute the revealed row to the read-only viewer during that+ // index-lag window. Match by shape instead: the file tree's direct caller+ // opens the editable doc when this returns null, so the row lands in the+ // template editor.+ if (parseTemplateContentDocName(docName)) return null;if (options.pages.has(docName)) return null;const assetPath = okReadOnlyAssetPath(docName, options.docExt);// Serve asymmetry behind this target: text-shaped `.ok` files render fully@@ -265,11 +272,12 @@ export function resolveNavigationTarget(pagesByBasename?: ReadonlyMap<string, string>;},): ResolvedContentTarget {- // Managed-artifact docs (skills/templates) are real docs addressed by their- // exact synthetic name, but they live OUTSIDE the page list — so the- // membership checks below would mark them 'missing'. Resolve them directly as- // a doc target so every consumer (hash nav, graph, links) treats them as real- // instead of broken/uncreated.+ // Managed-artifact docs (skills) are real docs addressed by their exact+ // synthetic name, but they live OUTSIDE the page list — so the membership+ // checks below would mark them 'missing'. Resolve them directly as a doc+ // target so every consumer (hash nav, graph, links) treats them as real+ // instead of broken/uncreated. A stale `__template__/…` name also enters here+ // (still classified managed for the tombstone) and redirects to its content doc.if (isManagedArtifactDocName(target)) {// A GLOBAL skill bundle `.md` REFERENCE (`__skill__/global/<name>/// references/<rel>`) is an EDITABLE managed-artifact live doc (the per-file@@ -280,14 +288,21 @@ export function resolveNavigationTarget(// (they open through the skill-file viewer directly), so only editable `.md`// references reach here.// A project skill is a CONTENT doc (`.ok/skills/<name>/SKILL`), never the- // synthetic `__skill__/project/<name>`. A stale deep-link / bookmark in that- // dead form must redirect to the live content doc rather than open a phantom- // empty tab. (Global skills + templates keep their synthetic name.)+ // synthetic `__skill__/project/<name>`; a template is a content doc at+ // `<folder>/.ok/templates/<name>`, never `__template__/…`. A stale deep-link /+ // bookmark in either dead synthetic form redirects to the live content doc+ // rather than opening a phantom empty tab. (Global + external skills keep+ // their synthetic name and fall through to the `{kind: 'doc'}` return.)const parsed = parseManagedArtifactName(target);if (parsed?.kind === 'skill' && parsed.scope === 'project') {const docName = projectSkillContentDocName(parsed.name);return { kind: 'doc', target: docName, docName };}+ const legacyTemplate = parseLegacyTemplateDocName(target);+ if (legacyTemplate) {+ const docName = templateContentDocName(legacyTemplate.folder, legacyTemplate.name);+ return { kind: 'doc', target: docName, docName };+ }return { kind: 'doc', target, docName: target };}// A PROJECT skill's SKILL.md content doc (`.ok/skills/<name>/SKILL`) is a real@@ -303,13 +318,16 @@ export function resolveNavigationTarget(if (parseProjectSkillContentDocName(target)) {return { kind: 'doc', target, docName: target };}- // A doc that links to a skill/template by its on-disk file path- // (`.ok/skills/<name>/SKILL`, `<folder>/.ok/templates/<name>`) resolves to the- // managed-artifact doc, so clicking the link opens the artifact editor instead- // of offering to "create" a missing page.- const artifactDocName = managedArtifactDocNameFromContentTarget(target);- if (artifactDocName) {- return { kind: 'doc', target: artifactDocName, docName: artifactDocName };+ // A template content doc (`<folder>/.ok/templates/<name>`) resolves directly,+ // like a project skill: it lives OUTSIDE the page index until the async `files`+ // refetch lands, so falling through to the pages-dependent resolution would+ // (transiently) route a freshly-created template to the read-only asset viewer.+ // A doc-body link whose target carries `.md` normalizes to the same ext-less+ // content name here, so a link and a tree-open agree on one key.+ const templateContent = parseTemplateContentDocName(target);+ if (templateContent) {+ const docName = templateContentDocName(templateContent.folder, templateContent.name);+ return { kind: 'doc', target: docName, docName };}const { normalizedTarget, expectsFolder } = normalizeTargetPath(target);if (!normalizedTarget) {diff --git a/packages/app/src/components/settings/TemplatesManagerSection.tsx b/packages/app/src/components/settings/TemplatesManagerSection.tsxindex dae8bbbdd..83595834a 100644--- a/packages/app/src/components/settings/TemplatesManagerSection.tsx+++ b/packages/app/src/components/settings/TemplatesManagerSection.tsx@@ -1,3 +1,4 @@+import { templateContentDocName } from '@inkeep/open-knowledge-core';import { Trans } from '@lingui/react/macro';import { Plus } from 'lucide-react';import { type ReactNode, useState } from 'react';@@ -8,7 +9,6 @@ import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';import { type TemplateMenuEntry, useFolderConfig } from '@/hooks/use-folder-config';-import { templateDocName } from '@/lib/managed-artifact-doc-name';import { openManagedArtifactTab } from '@/lib/open-managed-artifact-tab';import { useSettingsRoute } from '@/lib/use-settings-route';@@ -50,7 +50,7 @@ export function TemplatesManagerSection({ config }: { config: TemplatesManagerCo// Open the template as the active editor tab and close Settings so it's visible.function openTemplateTab(folder: string, name: string) {- openManagedArtifactTab(templateDocName(folder, name));+ openManagedArtifactTab(templateContentDocName(folder, name));settingsRoute.close();}diff --git a/packages/app/src/editor/editor-tabs.test.ts b/packages/app/src/editor/editor-tabs.test.tsindex 96529f811..844d700c8 100644--- a/packages/app/src/editor/editor-tabs.test.ts+++ b/packages/app/src/editor/editor-tabs.test.ts@@ -10,6 +10,8 @@ import {filterOpenTabsForKnownTargets,findLocalSkillPreviewTabId,folderTabId,+ isSkillBundleShapedPath,+ isSkillDocName,isSkillTabId,localTabSessionStorageKey,nextActiveTabAfterClose,@@ -240,20 +242,30 @@ describe('editor tab state', () => {).toEqual(['event_watcher']);});- test('filterOpenTabsForKnownTargets keeps managed-artifact tabs (tree-excluded by design)', () => {- // Skills/templates are real editor tabs but never appear in `pages` (they're- // excluded from the document tree). The filter must keep them regardless, or- // the page-list sync would prune the active skill/template tab — and unlike- // `keepHashDocName`, the protection holds even when the hash points elsewhere- // (so a skill tab survives opening a regular doc).+ test('filterOpenTabsForKnownTargets keeps a managed skill tab and a template content tab', () => {+ // A global skill never appears in `pages` (managed); a template content doc+ // lands in `pages` only after the async `files` refetch. The filter must keep+ // both regardless — and unlike `keepHashDocName`, the protection holds even+ // when the hash points elsewhere, so the tab survives opening a regular doc+ // during the index-lag window.expect(- filterOpenTabsForKnownTargets(['__skill__/project/foo', '__template__/notes/daily', 'gone'], {+ filterOpenTabsForKnownTargets(['__skill__/global/foo', 'notes/.ok/templates/daily', 'gone'], {pages: new Set(),folderPaths: new Set(),assetPaths: new Set(),keepHashDocName: 'some-other-doc',}),- ).toEqual(['__skill__/project/foo', '__template__/notes/daily']);+ ).toEqual(['__skill__/global/foo', 'notes/.ok/templates/daily']);+ });++ test('filterOpenTabsForKnownTargets keeps a template content tab once it lands in pages', () => {+ expect(+ filterOpenTabsForKnownTargets(['docs/.ok/templates/spec'], {+ pages: new Set(['docs/.ok/templates/spec']),+ folderPaths: new Set(),+ assetPaths: new Set(),+ }),+ ).toEqual(['docs/.ok/templates/spec']);});test('filterOpenTabsForKnownTargets drops stale asset tabs', () => {@@ -793,4 +805,43 @@ describe('tabParts — non-`.md` call-site shapes (folder + asset)', () => {prefix: '',});});++ test('template content doc labels name-only, hiding the `.ok/templates/` prefix', () => {+ // Without a template branch the tab would read `docs/.ok/templates/note`;+ // it should read just the template name, like the skill branches.+ expect(tabParts('docs/.ok/templates/note', '.md')).toEqual({+ baseName: 'note',+ extension: '',+ label: 'note',+ prefix: '',+ });+ // Project-root template (no owning folder).+ expect(tabParts('.ok/templates/daily', '.md')).toEqual({+ baseName: 'daily',+ extension: '',+ label: 'daily',+ prefix: '',+ });+ });+});++describe('skill discriminators reject template content shapes', () => {+ // Templates are content docs sharing the `.ok/**` neighbourhood with skills;+ // the skill-only discriminators must not misclassify them, or a template tab+ // would inherit skill chrome / sidebar focus.+ const templateDocs = ['.ok/templates/daily', 'docs/.ok/templates/note', 'a/b/.ok/templates/x'];++ test('isSkillDocName is false for every template content doc', () => {+ for (const doc of templateDocs) expect(isSkillDocName(doc)).toBe(false);+ });++ test('isSkillBundleShapedPath is false for template content docs', () => {+ // The bundle-shaped regex is loose (no `^\.` anchor) but still requires a+ // `skills/<x>/…` segment, which a template path never has.+ for (const doc of templateDocs) expect(isSkillBundleShapedPath(doc)).toBe(false);+ });++ test('isSkillTabId is false for a template content doc tab', () => {+ expect(isSkillTabId(docTabId('docs/.ok/templates/note'))).toBe(false);+ });});diff --git a/packages/app/src/editor/editor-tabs.ts b/packages/app/src/editor/editor-tabs.tsindex fcb67407d..9c68b2349 100644--- a/packages/app/src/editor/editor-tabs.ts+++ b/packages/app/src/editor/editor-tabs.ts@@ -4,6 +4,7 @@ import {parseExternalSkillDocName,parseManagedArtifactName,parseProjectSkillBundleDoc,+ parseTemplateContentDocName,type RenamedAssetMapping,type SkillScope,} from '@inkeep/open-knowledge-core';@@ -241,6 +242,13 @@ export function tabParts(: skillDisplayName(extSkill.name);return { baseName: display, extension: '', label: display, prefix: '' };}+ // A template is a content doc at `<folder>/.ok/templates/<name>`; the tab reads+ // as the bare template NAME (like skills), not the literal `.ok/templates/`+ // path prefix. The owning folder surfaces in the breadcrumb instead.+ const template = parseTemplateContentDocName(docName);+ if (template) {+ return { baseName: template.name, extension: '', label: template.name, prefix: '' };+ }const slash = docName.lastIndexOf('/');const baseName = slash < 0 ? docName : docName.slice(slash + 1);const extension =@@ -563,11 +571,13 @@ export function filterOpenTabsForKnownTargets(return (pages.has(tab.docName) ||(markdownStem !== null && pages.has(markdownStem)) ||- // Managed-artifact docs (skills/templates) are tree-excluded by design, so- // they never appear in `pages` — keep their tabs regardless, otherwise the- // page-list sync would prune the active skill/template tab the moment a- // page-list update fires (e.g. right after opening it).+ // Managed-artifact docs (global skills) are tree-excluded by design and+ // never appear in `pages` — keep their tabs regardless. A template content+ // doc DOES land in `pages`, but only after the async `files` refetch: keep+ // it by content shape too, so a page-list sync in the index-lag window+ // can't prune a template tab the way the managed disjunct used to prevent.isManagedArtifactDocName(tab.docName) ||+ parseTemplateContentDocName(tab.docName) !== null ||tab.docName === keepMissingDocName ||tab.docName === keepHashDocName);diff --git a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts b/packages/app/src/hooks/use-reconcile-skill-tabs.test.tsindex 091f73b07..3c4576aed 100644--- a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts+++ b/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts@@ -52,9 +52,9 @@ describe('parseSkillTabDocName', () => {).toEqual({ scope: 'global', name: 'demo', rel: 'notes' });});- test('rejects a non-skill doc (plain page, template)', () => {+ test('rejects a non-skill doc (plain page, template content doc)', () => {expect(parseSkillTabDocName('notes/standup')).toBeNull();- expect(parseSkillTabDocName('__template__/notes/daily')).toBeNull();+ expect(parseSkillTabDocName('notes/.ok/templates/daily')).toBeNull();});});@@ -231,7 +231,7 @@ describe('computeSkillTabReconcile', () => {});test('ignores non-skill tabs entirely', () => {- const actions = computeSkillTabReconcile(['notes/standup', '__template__/notes/daily'], []);+ const actions = computeSkillTabReconcile(['notes/standup', 'notes/.ok/templates/daily'], []);expect(actions).toEqual([]);});});diff --git a/packages/app/src/lib/doc-hash.test.ts b/packages/app/src/lib/doc-hash.test.tsindex 6429c5b2f..231cc517b 100644--- a/packages/app/src/lib/doc-hash.test.ts+++ b/packages/app/src/lib/doc-hash.test.ts@@ -1,3 +1,4 @@+import { templateContentDocName } from '@inkeep/open-knowledge-core';import { describe, expect, test, vi } from 'vitest';import {anchorFromHash,@@ -22,7 +23,7 @@ import {skillFileFromHash,skillPreviewFromHash,} from './doc-hash';-import { skillLiveDocName, templateDocName } from './managed-artifact-doc-name';+import { skillLiveDocName } from './managed-artifact-doc-name';describe('docNameFromHash', () => {test('returns null for empty hash', () => {@@ -375,11 +376,11 @@ describe('asset hash helpers', () => {});});-// Managed-artifact docs (skills/templates) open as ordinary editor tabs, so-// their `#/…` hashes resolve to their synthetic doc name like any document —-// `skillDocName`/`templateDocName` build the raw key, `hashFromDocName` builds-// the hash, and `docNameFromHash` decodes it back to the same key.-describe('managed-artifact doc names round-trip as documents', () => {+// A global skill's synthetic doc name and a template's content-relative doc name+// both open as ordinary editor tabs, so their `#/…` hashes round-trip like any+// document: the builder makes the raw key, `hashFromDocName` builds the hash, and+// `docNameFromHash` decodes it back to the same key.+describe('skill and template doc names round-trip as documents', () => {test('skill doc name round-trips through the hash', () => {// A GLOBAL skill is the synthetic-doc form (`__skill__/global/<name>`);// a project skill is a content doc, never `__skill__/project/<name>`, so the@@ -390,21 +391,33 @@ describe('managed-artifact doc names round-trip as documents', () => {expect(docNameFromHash(hashFromDocName(docName))).toBe(docName);});- test('template doc name (nested folder) round-trips through the hash', () => {- const docName = templateDocName('a/b/c', 'deep');- expect(docName).toBe('__template__/a/b/c/deep');- expect(hashFromDocName(docName)).toBe('#/__template__/a/b/c/deep');+ test('template CONTENT doc name (nested folder) round-trips through the hash', () => {+ // Templates are content docs now; the doc name is the content-relative path.+ const docName = templateContentDocName('a/b/c', 'deep');+ expect(docName).toBe('a/b/c/.ok/templates/deep');+ expect(hashFromDocName(docName)).toBe('#/a/b/c/.ok/templates/deep');expect(docNameFromHash(hashFromDocName(docName))).toBe(docName);});- test('template at the project root', () => {- expect(templateDocName('', 'daily')).toBe('__template__/daily');- expect(docNameFromHash('#/__template__/daily')).toBe('__template__/daily');+ test('template CONTENT doc at the project root round-trips', () => {+ const docName = templateContentDocName('', 'daily');+ expect(docName).toBe('.ok/templates/daily');+ expect(docNameFromHash(hashFromDocName(docName))).toBe(docName);+ });++ test('a spaced-folder template content name rides the generic hash round-trip', () => {+ // The synthetic namespace percent-encoded segments; the content name is RAW+ // and round-trips the hash like any other spaced doc name (the browser encodes+ // the space, docNameFromHash decodes it per segment).+ const docName = templateContentDocName('My Notes', 'plan');+ expect(docName).toBe('My Notes/.ok/templates/plan');+ expect(docNameFromHash('#/My%20Notes/.ok/templates/plan')).toBe(docName);+ expect(docNameFromHash(hashFromDocName(docName))).toBe(docName);});- test('a percent-encoded URL hash decodes back to the raw doc name', () => {- // The browser percent-encodes the URL hash; docNameFromHash decodes per- // segment so the key matches the raw doc name the tab/provider uses.+ test('a legacy `__template__/…` hash still decodes (input to the navigation redirect)', () => {+ // docNameFromHash decodes the stale synthetic name so resolveNavigationTarget+ // can redirect it to the content doc; new templates never use this form.expect(docNameFromHash('#/__template__/My%20Notes/plan')).toBe('__template__/My Notes/plan');});});diff --git a/packages/app/src/lib/doc-hash.ts b/packages/app/src/lib/doc-hash.tsindex 1cb06cbb1..74874d950 100644--- a/packages/app/src/lib/doc-hash.ts+++ b/packages/app/src/lib/doc-hash.ts@@ -21,10 +21,11 @@ export function docNameFromHash(hash: string): string | null {// A pre-install skill preview (`#/__skill-preview__/…`) is a full-pane viewer// keyed by import coordinates, not a doc — it resolves via `skillPreviewFromHash`.if (hash.startsWith(SKILL_PREVIEW_HASH_PREFIX)) return null;- // Skill (`#/__skill__/…`) and template (`#/__template__/…`) hashes ARE- // documents — they open as ordinary editor tabs, so they resolve to their- // synthetic doc name here like any other `#/<docName>` hash (per-segment- // decode below yields the raw `__skill__/<scope>/<name>` key the tab uses).+ // A global-skill hash (`#/__skill__/…`) and a LEGACY template hash+ // (`#/__template__/…`) decode to their raw name here like any other+ // `#/<docName>` hash; a legacy template name is then redirected to its content+ // doc at navigation resolution. New templates use their content-path hash+ // (`#/<folder>/.ok/templates/<name>`), decoded per-segment like any doc.if (!hash.startsWith('#/')) return null;const rest = hash.slice(2);const delimiter = firstRouteDelimiterIndex(rest);diff --git a/packages/app/src/lib/managed-artifact-doc-name.ts b/packages/app/src/lib/managed-artifact-doc-name.tsindex f931b60f2..f0f4e7886 100644--- a/packages/app/src/lib/managed-artifact-doc-name.ts+++ b/packages/app/src/lib/managed-artifact-doc-name.ts@@ -1,20 +1,18 @@/**- * Builders for managed-artifact doc names — a skill (`__skill__/<scope>/<name>`)- * or a template (`__template__/<folderRel>/<name>`). These are real CRDT doc- * names opened as ordinary editor tabs (via `openDocument`), so they follow the- * SAME convention as document doc names: the canonical key is the raw/decoded- * string. `hashFromDocName` builds the `#/…` hash without encoding (the browser- * encodes the URL); `docNameFromHash` decodes it back — so a builder that- * encoded here would round-trip to a different key than the tab/provider uses.+ * Builders for skill live-doc names. A GLOBAL skill is a managed-artifact doc+ * (`__skill__/global/<name>`); a PROJECT skill is a content doc at its real path+ * (`.ok/skills/<name>/SKILL`). These are real CRDT doc names opened as ordinary+ * editor tabs, so they follow the SAME convention as document doc names: the+ * canonical key is the raw/decoded string. `hashFromDocName` builds the `#/…`+ * hash without encoding (the browser encodes the URL); `docNameFromHash` decodes+ * it back — so a builder that encoded here would round-trip to a different key+ * than the tab/provider uses.*- * Parsing the other direction is `parseManagedArtifactName` from- * `@inkeep/open-knowledge-core` (shared with the server). Skill/template names- * are slash-free by grammar; template folders carry their own `/` separators,- * which are structural and belong in the doc name verbatim.+ * Templates are content docs too — build their doc name with+ * `templateContentDocName` from `@inkeep/open-knowledge-core`, not here.*/import {- MANAGED_ARTIFACT_PREFIX_TEMPLATE,parseProjectSkillBundleDoc,type SkillsListEntry,skillFileLiveDocName,@@ -30,15 +28,6 @@ export { skillLiveDocName };// global → `__skill__/global/<name>`), re-exported above. A bare synthetic// builder opened a phantom empty tab for project skills (round-trip data loss).-/**- * The CRDT doc name for a template — folder-addressed- * (`__template__/<folderRel>/<name>`, `folder` empty for the project root).- */-export function templateDocName(folder: string, name: string): string {- const trimmed = folder.replace(/^\/+|\/+$/g, '');- return `${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${trimmed ? `${trimmed}/` : ''}${name}`;-}-/*** Live CRDT doc name for a skill LIST ENTRY. A project entry is a content doc* at its REAL path (ext-less) — `.ok/skills/<name>/SKILL` for store skills,diff --git a/packages/app/tests/integration/create-page.test.ts b/packages/app/tests/integration/create-page.test.tsindex 3c4a5f5b0..3ba5078be 100644--- a/packages/app/tests/integration/create-page.test.ts+++ b/packages/app/tests/integration/create-page.test.ts@@ -139,6 +139,18 @@ describe('/api/create-page — reserved name (QA-010)', () => {expect(body.type).toBe('urn:ok:error:reserved-doc-name');expect(body.title).toMatch(/reserved/i);});++ test('rejects a raw create into .ok/templates so templates keep their validating route (QA-013)', async () => {+ // Templates are content docs for reading and watching, but the create-page+ // guard must still refuse a raw create into `.ok/templates/` — the `template`+ // verb is the only authoring route. This pins that the read carve-out did not+ // open the create chokepoint.+ const { status, body } = await createPage('.ok/templates/greeting.md');+ expect(status).toBe(400);+ expect(body.type).toBe('urn:ok:error:reserved-doc-name');+ expect(body.title).toMatch(/reserved/i);+ expect(existsSync(join(server.contentDir, '.ok', 'templates', 'greeting.md'))).toBe(false);+ });});describe('/api/create-page — template seeding', () => {diff --git a/packages/app/tests/integration/derived-document-index-lifecycle.test.ts b/packages/app/tests/integration/derived-document-index-lifecycle.test.tsindex d978b01dd..f502bdf2e 100644--- a/packages/app/tests/integration/derived-document-index-lifecycle.test.ts+++ b/packages/app/tests/integration/derived-document-index-lifecycle.test.ts@@ -125,8 +125,17 @@ test('direct create, duplicate, rename, and delete keep links and tags in lockst}),);expect(created.status).toBe(200);- expect(await tagDocuments(server.baseUrl, 'lifecycle')).toEqual(['folder/item']);- expect(await backlinkSources(server.baseUrl, 'target')).toEqual(['folder/item']);+ // The template itself carries `tags: [lifecycle]` and a `[[target]]` link, so+ // as an ordinary content doc it indexes as a tag/backlink SOURCE alongside+ // the doc generated from it (it sorts first — `.` precedes letters).+ expect(await tagDocuments(server.baseUrl, 'lifecycle')).toEqual([+ '.ok/templates/lifecycle',+ 'folder/item',+ ]);+ expect(await backlinkSources(server.baseUrl, 'target')).toEqual([+ '.ok/templates/lifecycle',+ 'folder/item',+ ]);const fileDuplicate = await expectRelationSignalsAfter(relationSignals.signals, () =>postJson(server.baseUrl, '/api/duplicate-path', {@@ -136,6 +145,7 @@ test('direct create, duplicate, rename, and delete keep links and tags in lockst);expect(fileDuplicate.status).toBe(200);expect(await tagDocuments(server.baseUrl, 'lifecycle')).toEqual([+ '.ok/templates/lifecycle','folder/item','folder/item copy',]);@@ -148,6 +158,7 @@ test('direct create, duplicate, rename, and delete keep links and tags in lockst);expect(folderDuplicate.status).toBe(200);expect(await tagDocuments(server.baseUrl, 'lifecycle')).toEqual([+ '.ok/templates/lifecycle','folder copy/item','folder copy/item copy','folder/item',@@ -163,12 +174,14 @@ test('direct create, duplicate, rename, and delete keep links and tags in lockst);expect(renamed.status).toBe(200);expect(await tagDocuments(server.baseUrl, 'lifecycle')).toEqual([+ '.ok/templates/lifecycle','archive/item','archive/item copy','folder/item','folder/item copy',]);expect(await backlinkSources(server.baseUrl, 'target')).toEqual([+ '.ok/templates/lifecycle','archive/item','archive/item copy','folder/item',@@ -182,11 +195,15 @@ test('direct create, duplicate, rename, and delete keep links and tags in lockst}),);expect(deleted.status).toBe(200);+ // The generated docs are gone, but the template SOURCE persists (it was never+ // touched), so it remains under its own tag and as a backlink source.expect(await tagDocuments(server.baseUrl, 'lifecycle')).toEqual([+ '.ok/templates/lifecycle','folder/item','folder/item copy',]);expect(await backlinkSources(server.baseUrl, 'target')).toEqual([+ '.ok/templates/lifecycle','folder/item','folder/item copy',]);diff --git a/packages/app/tests/integration/managed-artifact-doc.test.ts b/packages/app/tests/integration/managed-artifact-doc.test.tsindex a2cd3e7a4..cbca1526d 100644--- a/packages/app/tests/integration/managed-artifact-doc.test.ts+++ b/packages/app/tests/integration/managed-artifact-doc.test.ts@@ -5,12 +5,12 @@ import { afterEach, beforeEach, describe, expect, test } from 'vitest';import { createTestClient, createTestServer, type TestServer } from './test-harness.ts';/**- * End-to-end proof through the real server. Project skills are real content- * docs (`.ok/skills/<name>/SKILL`): admitted by the content index, the observer- * bridge runs, and edits persist verbatim to `.ok/skills/<name>/SKILL.md` via- * the content pipeline. Templates remain managed-artifact (`__template__/...`)- * docs. Global skills keep the dedicated managed-artifact route (not exercised- * here — they live at `<home>/.ok/skills`, outside the test contentDir).+ * End-to-end proof through the real server. Project skills and templates are+ * real content docs (`.ok/skills/<name>/SKILL`, `<folder>/.ok/templates/<name>`):+ * admitted by the content index, the observer bridge runs, and edits persist+ * verbatim to disk via the content pipeline. Global skills keep the dedicated+ * managed-artifact route (not exercised here — they live at `<home>/.ok/skills`,+ * outside the test contentDir).*/describe('skill + template CRDT docs — end to end', () => {let server: TestServer;@@ -153,9 +153,9 @@ describe('skill + template CRDT docs — end to end', () => {await client.cleanup();});- test('a __template__ doc persists folder-addressed to <folder>/.ok/templates/<name>.md', async () => {- // Folder-addressed: __template__/<folderRel>/<name>, root folder here.- const docName = '__template__/daily-note';+ test('a template content doc persists to <folder>/.ok/templates/<name>.md', async () => {+ // Content-addressed: <folderRel>/.ok/templates/<name>, root folder here.+ const docName = '.ok/templates/daily-note';const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });const src = '---\ntitle: Daily Note\ndescription: a daily note\n---\n\n# {{date}}\n\nNotes.\n';@@ -169,7 +169,7 @@ describe('skill + template CRDT docs — end to end', () => {});test('PUT /api/template routes the body through the open CRDT doc (Slice E)', async () => {- const docName = '__template__/notes/meeting';+ const docName = 'notes/.ok/templates/meeting';const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });const res = await fetch(`http://127.0.0.1:${server.port}/api/template`, {@@ -203,28 +203,44 @@ describe('skill + template CRDT docs — end to end', () => {await client.cleanup();});- test('an external template .md disk edit reconciles into the open doc (root folder)', async () => {- // The project root `.ok/templates` is always watched (folder-nested dirs are- // enumerated at boot).- const docName = '__template__/daily';- const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });-+ test('an external template .md disk edit reconciles into the open doc', async () => {+ // Templates are content docs now, so the ordinary content watcher delivers+ // external edits to `.ok/templates/*` — no dedicated watcher. Seed the file+ // BEFORE booting so it is present in the watcher's initial recursive scan:+ // creating the nested `.ok/templates/` subdir AFTER the watcher starts races+ // the OS backend's new-subdir registration (@parcel/watcher drops the+ // subsequent edit), so with the file watched from boot the modify event is+ // delivered deterministically. (The brand-new-folder mid-session case is the+ // watcher-capability suite's job.)+ await server.cleanup();+ const seedDir = mkdtempSync(join(tmpdir(), 'ok-template-reconcile-'));+ mkdirSync(resolve(seedDir, '.ok'), { recursive: true });+ writeFileSync(resolve(seedDir, '.ok', 'config.yml'), '', 'utf-8');+ const tplFile = resolve(seedDir, '.ok', 'templates', 'daily.md');const src = '---\ntitle: Daily\ndescription: initial\n---\n\n# {{date}}\n';- client.doc.transact(() => client.ytext.insert(0, src));- const tplFile = resolve(server.contentDir, '.ok', 'templates', 'daily.md');- expect(await pollFor(tplFile)).toBe(true);+ mkdirSync(resolve(tplFile, '..'), { recursive: true });+ writeFileSync(tplFile, src, 'utf-8');+ server = await createTestServer({ contentDir: seedDir });+ const docName = '.ok/templates/daily';+ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });+ const loadStart = Date.now();+ while (Date.now() - loadStart < 5000 && client.ytext.toString() !== src) {+ await new Promise((r) => setTimeout(r, 100));+ }+ expect(client.ytext.toString()).toBe(src);++ // A hand/CLI edit straight to the now-watched template file. The content+ // file-watcher reconciles it into the open content doc.const edited ='---\ntitle: Daily\ndescription: edited externally\n---\n\n# {{date}}\n\nMore.\n';- mkdirSync(resolve(server.contentDir, '.ok', 'templates'), { recursive: true });- writeFileSync(tplFile, edited, 'utf-8');-const start = Date.now();- while (Date.now() - start < 5000 && client.ytext.toString() !== edited) {- await new Promise((r) => setTimeout(r, 100));+ while (Date.now() - start < 15000 && client.ytext.toString() !== edited) {+ writeFileSync(tplFile, edited, 'utf-8');+ await new Promise((r) => setTimeout(r, 200));}expect(client.ytext.toString()).toBe(edited);await client.cleanup();- });+ }, 30_000);});diff --git a/packages/app/tests/integration/managed-artifact-reconcile-anchor.test.ts b/packages/app/tests/integration/managed-artifact-reconcile-anchor.test.tsdeleted file mode 100644index e7a8b6ae4..000000000--- a/packages/app/tests/integration/managed-artifact-reconcile-anchor.test.ts+++ /dev/null@@ -1,225 +0,0 @@-/**- * The managed-artifact concurrent-writer reconcile as a CONTENT-LOSS site.- *- * `storeManagedArtifactDoc` refuses to clobber a file a second writer changed- * under it: when the pre-write disk read shows `disk !== lkg && disk !== content`- * it imports the disk bytes over the live doc and returns `'reconciled'`. The- * disk-wins decision is correct — another OK window, a hand edit, or a CLI write- * is a real conflict, not a false positive — but the import lands under- * `FILE_WATCHER_ORIGIN`, which the server UndoManager excludes by contract and- * which reaches browsers as a remote update outside any local `trackedOrigins`- * set. Whatever the author had typed into the artifact is gone on both sides.- *- * `'reconciled'` propagates to in-process consumers, so the path is not wholly- * silent, but nothing reaches the loss ring and nothing is restorable. That is- * Gap 2 of the content-loss class sweep, and the same three misses as Gap 1:- * no checkpoint, no kind of its own, no `detect`.- *- * Templates are the versioned managed artifact — they live under the project's- * `.ok/templates/`, inside the shadow repo's reach. Global skills live at- * `<home>/.ok/skills` outside any project shadow, so they are unversioned by- * construction and covered separately at the unit rung.- *- * Fidelity: real boot, real WS client, real `onStoreDocument` managed-artifact- * branch, real file lock, real shadow repo. The divergent write is a plain- * `writeFileSync`. The test invokes the real store hook immediately afterward- * so the managed-artifact watcher cannot consume the same change first and turn- * this into coverage of its separate disk-intake path.- */--import { execFileSync } from 'node:child_process';-import { randomUUID } from 'node:crypto';-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';-import { join, resolve } from 'node:path';-import { parseCheckpoint } from '@inkeep/open-knowledge-core';-import { afterEach, describe, expect, test } from 'vitest';-import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';-import { createTestClient, createTestServer, type TestServer } from './test-harness.ts';--/** What the author had typed into the template and had not yet stored. */-const AUTHOR_PENDING_LINE = 'Zzz author sentence pending when the reconcile fired.';--/** What the concurrent writer put on disk underneath the live doc. */-const FOREIGN_LINE = 'Foreign edit from a second OK window.';--interface LossRingEvent {- event: string;- docName: string;- site?: string;- direction?: string;- lostLen?: number;- digest?: string;- checkpointSha?: string;-}--let server: TestServer | undefined;--afterEach(async () => {- if (server) {- await server.cleanup();- server = undefined;- }-});--function readLossEvents(contentDir: string): LossRingEvent[] {- const path = join(contentDir, '.ok', 'local', 'loss-capture', 'loss-current.jsonl');- if (!existsSync(path)) return [];- return readFileSync(path, 'utf-8')- .split('\n')- .filter((line) => line.length > 0)- .flatMap((line) => {- try {- return [JSON.parse(line) as LossRingEvent];- } catch {- return [];- }- });-}--function shadowGitRaw(s: TestServer, args: string[]): string {- const dir = join(s.contentDir, '.git', 'ok');- if (!existsSync(dir)) {- throw new Error(`shadow repo not found at ${dir}; the rig needs gitEnabled: true`);- }- return execFileSync('git', ['--git-dir', dir, ...args], { encoding: 'utf-8' }).toString();-}--/** Every checkpoint the shadow holds, across all branch namespaces. */-function listCheckpoints(s: TestServer): Array<{ sha: string; kind: string | null }> {- return shadowGitRaw(s, ['for-each-ref', '--format=%(objectname)', 'refs/checkpoints'])- .split('\n')- .map((x) => x.trim())- .filter(Boolean)- .map((sha) => ({- sha,- kind: parseCheckpoint(shadowGitRaw(s, ['log', '-1', '--format=%B', sha]))?.kind ?? null,- }));-}--async function pollUntil(- predicate: () => boolean,- { timeoutMs = 10_000, pollMs = 50 }: { timeoutMs?: number; pollMs?: number } = {},-): Promise<void> {- const deadline = Date.now() + timeoutMs;- while (Date.now() < deadline) {- if (predicate()) return;- await new Promise((r) => setTimeout(r, pollMs));- }- throw new Error(`pollUntil timed out after ${timeoutMs}ms`);-}--async function storeImmediately(rig: TestServer, docName: string): Promise<void> {- const document = rig.instance.hocuspocus.documents.get(docName);- if (!document) throw new Error(`document not loaded: ${docName}`);-- await rig.instance.hocuspocus.hooks('onStoreDocument', {- clientsCount: document.getConnectionsCount(),- document,- lastContext: {},- lastTransactionOrigin: undefined,- documentName: docName,- instance: rig.instance.hocuspocus,- });-}--describe('managed-artifact reconcile-on-divergence — content-loss conventions', () => {- test(- 'the reconcile checkpoints the live artifact and reports the loss before discarding it',- async () => {- server = await createTestServer({ gitEnabled: true, debounce: 150, maxDebounce: 600 });- const name = `tpl-${randomUUID().slice(0, 8)}`;- const docName = `__template__/${name}`;- const tplFile = resolve(server.contentDir, '.ok', 'templates', `${name}.md`);-- const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });-- // v1 authored in the editor and persisted — this is what sets the LKG.- const v1 = `---\ntitle: T\ndescription: d\n---\n\n# Template\n\nv1 body.\n`;- client.doc.transact(() => client.ytext.insert(0, v1));- await pollUntil(() => existsSync(tplFile) && readFileSync(tplFile, 'utf-8') === v1);-- // The author keeps typing. These bytes are live and unstored.- const live = client.ytext.toString();- client.doc.transact(() => client.ytext.insert(live.length, `\n${AUTHOR_PENDING_LINE}\n`));- await pollUntil(() =>- Boolean(- server?.instance.hocuspocus.documents- .get(docName)- ?.getText('source')- .toString()- .includes(AUTHOR_PENDING_LINE),- ),- );-- // A second writer changes the file underneath us. Invoke the real store- // hook in the same turn so this test deterministically reaches the- // concurrent-writer reconcile before the separate template watcher can- // import the file.- mkdirSync(resolve(tplFile, '..'), { recursive: true });- const foreign = `---\ntitle: T\ndescription: d\n---\n\n# Template\n\n${FOREIGN_LINE}\n`;- writeFileSync(tplFile, foreign, 'utf-8');- await storeImmediately(server, docName);-- // The next store reads disk, sees `disk !== lkg && disk !== content`, and- // reconciles: the foreign bytes win and the author's sentence is discarded.- // This premise assertion PASSES on the unfixed tree — it documents the harm.- await pollUntil(- () =>- Boolean(- server?.instance.hocuspocus.documents- .get(docName)- ?.getText('source')- .toString()- .includes(FOREIGN_LINE),- ) &&- !server?.instance.hocuspocus.documents- .get(docName)- ?.getText('source')- .toString()- .includes(AUTHOR_PENDING_LINE),- { timeoutMs: 15_000 },- );-- // (a) checkpoint-before-repair + (b) detection-site-owns-a-kind.- const rig = server;- await pollUntil(- () => listCheckpoints(rig).some((c) => c.kind === 'managed-artifact-reconcile'),- { timeoutMs: 15_000 },- );- const anchors = listCheckpoints(rig).filter((c) => c.kind === 'managed-artifact-reconcile');- expect(anchors).toHaveLength(1);- const anchor = anchors[0];- if (!anchor) throw new Error('unreachable: anchor asserted above');-- // (c) undoability: the anchor is the only way back, so it must hold the- // author's real bytes. The checkpoint is filed under the artifact's TIMELINE- // key (`.ok/templates/<name>`), not the synthetic `__template__/...` doc- // name, so it addresses the same path the history surface reads.- const blob = shadowGitRaw(rig, ['show', `${anchor.sha}:.ok/templates/${name}`]);- expect(blob).toContain(AUTHOR_PENDING_LINE);-- // (d) observable signal.- const ring = readLossEvents(rig.contentDir).filter(- (e) => e.site === 'managed-artifact-reconcile' && e.docName === docName,- );- const trips = ring.filter((e) => e.event === 'detector-trip');- expect(trips).toHaveLength(1);- expect(trips[0]?.lostLen ?? 0).toBeGreaterThanOrEqual(AUTHOR_PENDING_LINE.length);- expect(JSON.stringify(trips[0])).not.toContain(AUTHOR_PENDING_LINE);- // Polled, not asserted once: git creates the checkpoint ref before the write- // promise settles, so the anchor is visible to `for-each-ref` a beat before- // the `.then` records its ring event.- await pollUntil(() =>- readLossEvents(rig.contentDir).some(- (e) =>- e.site === 'managed-artifact-reconcile' &&- e.event === 'checkpoint-write' &&- e.checkpointSha === anchor.sha,- ),- );-- await client.cleanup();- },- HARNESS_BOOT_TIMEOUT_MS + 60_000,- );-});diff --git a/packages/app/tests/integration/showok-reveal.test.ts b/packages/app/tests/integration/showok-reveal.test.tsindex e7a3039a0..7de08411b 100644--- a/packages/app/tests/integration/showok-reveal.test.ts+++ b/packages/app/tests/integration/showok-reveal.test.ts@@ -1,24 +1,37 @@/*** `?showOk=true` tree-listing reveal over the real HTTP API. The flag admits- * `.ok` rows — minus `.ok/worktrees` and `.ok/local` — into the showAll walk- * on both the buffered and NDJSON paths, and ONLY there: with the flag in- * active use, the watcher-index-backed default listing and the search corpus- * must stay `.ok`-free (reveal is a per-request view, never an index rescope),- * and a plain showAll request keeps today's `.ok`-less listing.+ * `.ok` rows — minus `.ok/worktrees` and `.ok/local` — into the showAll walk on+ * both the buffered and NDJSON paths. Reveal is a per-request TREE view, never+ * an index rescope: the default (no-showOk) listing stays `.ok`-free.+ *+ * The search corpus and the `[[` page list are a separate axis. They admit the+ * content `.ok` carve-outs the file index tracks — skills (indexed with+ * skill-aware docs) and folder templates (ordinary content docs, rank-penalized+ * by `isHiddenDocName` like any dot-path) — while `.ok/local`, `.ok/worktrees`,+ * and config stay out everywhere. Templates are searchable-with-penalty and are+ * offered as `[[` link targets; only embeddings + egress exclude them.*/import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { DocumentListSuccessSchema, SearchSuccessSchema } from '@inkeep/open-knowledge-core';+import {+ DocumentListSuccessSchema,+ PagesSuccessSchema,+ SearchSuccessSchema,+} from '@inkeep/open-knowledge-core';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import { createTestServer, type TestServer } from './test-harness';-// Unique body/name tokens so the search-corpus assertions can't false-pass on-// unrelated fixture content: the control token lives in an indexed doc (the-// positive control proving search works), the ok token ONLY under `.ok`.+// Unique tokens so the search-corpus assertions can't false-pass on unrelated+// fixture content: the control token is the ordinary doc's name (positive+// control proving search works), the ok token is the template's name (ONLY under+// `.ok`), and the shared token is the H1 TITLE of BOTH docs, so a single query+// yields a same-strength title match in each and the hidden-path rank penalty+// is the only thing that separates their ranks.const VISIBLE_TOKEN = 'zzcontroltoken';const OK_TOKEN = 'zzoktemplatetoken';+const SHARED_TOKEN = 'zzsharedranktoken';let server: TestServer;function documentsUrl(params: string): string {@@ -37,12 +50,15 @@ function hasOkSegment(p: string): boolean {beforeAll(async () => {const contentDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showok-reveal-')));- writeFileSync(join(contentDir, `${VISIBLE_TOKEN}.md`), `# Control\n\n${VISIBLE_TOKEN} body\n`);+ writeFileSync(+ join(contentDir, `${VISIBLE_TOKEN}.md`),+ `# ${SHARED_TOKEN}\n\n${VISIBLE_TOKEN} body\n`,+ );mkdirSync(join(contentDir, '.ok', 'templates'), { recursive: true });writeFileSync(join(contentDir, '.ok', 'config.yml'), 'content:\n dir: .\n');writeFileSync(join(contentDir, '.ok', 'templates', `${OK_TOKEN}.md`),- `# Template\n\n${OK_TOKEN} body\n`,+ `# ${SHARED_TOKEN}\n\n${OK_TOKEN} body\n`,);mkdirSync(join(contentDir, '.ok', 'worktrees', 'checkout'), { recursive: true });writeFileSync(join(contentDir, '.ok', 'worktrees', 'checkout', 'README.md'), '# checkout\n');@@ -111,8 +127,8 @@ describe('showOk reveal on GET /api/documents', () => {}, 30_000);});-describe('showOk never leaks past the tree listing', () => {- test('with showOk in use, the watcher index keeps non-skill .ok content out', async () => {+describe('showOk is a tree-only reveal; template content docs are searchable and link-target-able', () => {+ test('with showOk in use, the watcher index keeps non-skill/template .ok content out', async () => {// Exercise the reveal first so the flag is genuinely in use before the// index-backed read.await (await fetch(documentsUrl('?showAll=true&showOk=true'))).json();@@ -120,22 +136,29 @@ describe('showOk never leaks past the tree listing', () => {expect(res.ok).toBe(true);const body = DocumentListSuccessSchema.parse(await res.json());const paths = body.documents.map(entryPath);- // The bare `.ok` folder row and `.ok/skills/**` are the pre-existing- // skills-as-content carve-out surface of the default listing (the client- // adapter drops them from the tree); everything else under `.ok` must- // stay out of the index regardless of showOk traffic.- const nonSkillOkPaths = paths.filter(- (p) => hasOkSegment(p) && p !== '.ok' && !p.startsWith('.ok/skills/'),+ // The bare `.ok` folder row plus the `.ok/skills/**` and `.ok/templates/**`+ // content carve-outs are the surfaces the default listing admits (the client+ // adapter drops them from the visible tree); everything else under `.ok` —+ // `.ok/local`, `.ok/worktrees`, `.ok/config.yml` — must stay out of the index+ // regardless of showOk traffic. Template files are content docs now, so their+ // index membership is intended, exactly like the skills carve-out.+ const nonCarveOutOkPaths = paths.filter(+ (p) =>+ hasOkSegment(p) &&+ p !== '.ok' &&+ !p.startsWith('.ok/skills/') &&+ p !== '.ok/templates' &&+ !p.startsWith('.ok/templates/'),);- expect(nonSkillOkPaths).toEqual([]);+ expect(nonCarveOutOkPaths).toEqual([]);// Positive control: the index itself is populated and serving.expect(paths).toContain(VISIBLE_TOKEN);}, 30_000);- test('with showOk in use, the search corpus never sees .ok content', async () => {+ test('a template body token is searchable but ranks below an ordinary doc (rank penalty)', async () => {await (await fetch(documentsUrl('?showAll=true&showOk=true'))).json();// Positive control first: an indexed doc's token IS searchable, so the- // `.ok` negative below can't pass vacuously on a broken corpus.+ // template assertions below can't pass vacuously on a broken corpus.const controlRes = await fetch(`http://127.0.0.1:${server.port}/api/search?query=${VISIBLE_TOKEN}`,);@@ -143,9 +166,41 @@ describe('showOk never leaks past the tree listing', () => {const control = SearchSuccessSchema.parse(await controlRes.json());expect(control.results.length).toBeGreaterThan(0);+ // Templates are ordinary content docs now, so a body token unique to the+ // template IS a search hit — the template joined the lexical corpus.const okRes = await fetch(`http://127.0.0.1:${server.port}/api/search?query=${OK_TOKEN}`);expect(okRes.ok).toBe(true);const okBody = SearchSuccessSchema.parse(await okRes.json());- expect(okBody.results).toEqual([]);+ expect(okBody.results.some((r) => r.path === `.ok/templates/${OK_TOKEN}`)).toBe(true);++ // The rank penalty: both docs carry the token as an identical H1 title, so+ // the only thing separating their ranks is that `isHiddenDocName` halves the+ // template's (title) lexical bracket. `intent=omnibar` uses the tier-dominant+ // score where the bracket is the primary key, so the halved template drops a+ // full tier below the visible control doc — a deterministic ordering.+ const sharedRes = await fetch(+ `http://127.0.0.1:${server.port}/api/search?query=${SHARED_TOKEN}&intent=omnibar`,+ );+ expect(sharedRes.ok).toBe(true);+ const shared = SearchSuccessSchema.parse(await sharedRes.json());+ const paths = shared.results.map((r) => r.path);+ const visibleRank = paths.indexOf(VISIBLE_TOKEN);+ const templateRank = paths.indexOf(`.ok/templates/${OK_TOKEN}`);+ expect(visibleRank).toBeGreaterThanOrEqual(0);+ expect(templateRank).toBeGreaterThanOrEqual(0);+ expect(templateRank).toBeGreaterThan(visibleRank);+ }, 30_000);++ test('the `[[` link-target list (/api/pages) offers a template content doc', async () => {+ const res = await fetch(`http://127.0.0.1:${server.port}/api/pages`);+ expect(res.ok).toBe(true);+ const body = PagesSuccessSchema.parse(await res.json());+ const docNames = body.pages.map((p) => p.docName);+ // Positive control: an ordinary page IS a link target, so the template+ // assertion below can't pass vacuously on an empty page list.+ expect(docNames).toContain(VISIBLE_TOKEN);+ // Templates are ordinary content docs, so they ARE offered as `[[` link+ // targets and `@` mentions — both feed off `/api/pages`.+ expect(docNames).toContain(`.ok/templates/${OK_TOKEN}`);}, 30_000);});diff --git a/packages/app/tests/integration/template-concurrent-write-no-loss.test.ts b/packages/app/tests/integration/template-concurrent-write-no-loss.test.tsnew file mode 100644index 000000000..5b1be3020--- /dev/null+++ b/packages/app/tests/integration/template-concurrent-write-no-loss.test.ts@@ -0,0 +1,184 @@+/**+ * The template concurrent-writer reconcile on the CONTENT branch.+ *+ * Before the templates-as-content migration a template was a versioned managed+ * artifact, and `storeManagedArtifactDoc`'s disk-wins reconcile could discard an+ * author's live edit when a second writer changed the file underneath — a+ * content-loss gap this suite pinned under the synthetic `__template__/…` doc.+ *+ * Templates are ordinary content docs now (`<folder>/.ok/templates/<name>`), so+ * that managed path no longer runs for them. When a second writer changes the+ * file underneath the live doc and the doc is then stored, the content-branch+ * store is doc-authoritative: it writes the live doc to disk rather than+ * importing the divergent disk bytes back into the doc. So the author's pending+ * edit survives, the foreign bytes never replace it in the live doc, and neither+ * the `managed-artifact-reconcile` checkpoint nor its loss-ring site fires. This+ * test verifies that improvement end to end.+ *+ * Fidelity: real boot, real WS client, real `onStoreDocument` content branch,+ * real file lock, real shadow repo. The divergent write is a plain+ * `writeFileSync`; the store hook is invoked in the same turn.+ */++import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { parseCheckpoint } from '@inkeep/open-knowledge-core';+import { afterEach, describe, expect, test } from 'vitest';+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';+import { createTestClient, createTestServer, type TestServer } from './test-harness.ts';++/** What the author had typed into the template and had not yet stored. */+const AUTHOR_PENDING_LINE = 'Zzz author sentence pending when the reconcile fired.';++/** What the concurrent writer put on disk underneath the live doc. */+const FOREIGN_LINE = 'Foreign edit from a second OK window.';++interface LossRingEvent {+ event: string;+ docName: string;+ site?: string;+ direction?: string;+ lostLen?: number;+ digest?: string;+ checkpointSha?: string;+}++let server: TestServer | undefined;++afterEach(async () => {+ if (server) {+ await server.cleanup();+ server = undefined;+ }+});++function readLossEvents(contentDir: string): LossRingEvent[] {+ const path = join(contentDir, '.ok', 'local', 'loss-capture', 'loss-current.jsonl');+ if (!existsSync(path)) return [];+ return readFileSync(path, 'utf-8')+ .split('\n')+ .filter((line) => line.length > 0)+ .flatMap((line) => {+ try {+ return [JSON.parse(line) as LossRingEvent];+ } catch {+ return [];+ }+ });+}++function shadowGitRaw(s: TestServer, args: string[]): string {+ const dir = join(s.contentDir, '.git', 'ok');+ if (!existsSync(dir)) {+ throw new Error(`shadow repo not found at ${dir}; the rig needs gitEnabled: true`);+ }+ return execFileSync('git', ['--git-dir', dir, ...args], { encoding: 'utf-8' }).toString();+}++/** Every checkpoint the shadow holds, across all branch namespaces. */+function listCheckpoints(s: TestServer): Array<{ sha: string; kind: string | null }> {+ return shadowGitRaw(s, ['for-each-ref', '--format=%(objectname)', 'refs/checkpoints'])+ .split('\n')+ .map((x) => x.trim())+ .filter(Boolean)+ .map((sha) => ({+ sha,+ kind: parseCheckpoint(shadowGitRaw(s, ['log', '-1', '--format=%B', sha]))?.kind ?? null,+ }));+}++async function pollUntil(+ predicate: () => boolean,+ { timeoutMs = 10_000, pollMs = 50 }: { timeoutMs?: number; pollMs?: number } = {},+): Promise<void> {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (predicate()) return;+ await new Promise((r) => setTimeout(r, pollMs));+ }+ throw new Error(`pollUntil timed out after ${timeoutMs}ms`);+}++async function storeImmediately(rig: TestServer, docName: string): Promise<void> {+ const document = rig.instance.hocuspocus.documents.get(docName);+ if (!document) throw new Error(`document not loaded: ${docName}`);++ await rig.instance.hocuspocus.hooks('onStoreDocument', {+ clientsCount: document.getConnectionsCount(),+ document,+ lastContext: {},+ lastTransactionOrigin: undefined,+ documentName: docName,+ instance: rig.instance.hocuspocus,+ });+}++describe('template concurrent-write reconcile on the content branch', () => {+ test(+ 'a concurrent external write reconciles without discarding the author live edit',+ async () => {+ server = await createTestServer({ gitEnabled: true, debounce: 150, maxDebounce: 600 });+ const name = `tpl-${randomUUID().slice(0, 8)}`;+ const docName = `.ok/templates/${name}`;+ const tplFile = resolve(server.contentDir, '.ok', 'templates', `${name}.md`);++ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });++ // v1 authored in the editor and persisted — this is what sets the LKG.+ const v1 = `---\ntitle: T\ndescription: d\n---\n\n# Template\n\nv1 body.\n`;+ client.doc.transact(() => client.ytext.insert(0, v1));+ await pollUntil(() => existsSync(tplFile) && readFileSync(tplFile, 'utf-8') === v1);++ // The author keeps typing. These bytes are live and unstored.+ const live = client.ytext.toString();+ client.doc.transact(() => client.ytext.insert(live.length, `\n${AUTHOR_PENDING_LINE}\n`));+ await pollUntil(() =>+ Boolean(+ server?.instance.hocuspocus.documents+ .get(docName)+ ?.getText('source')+ .toString()+ .includes(AUTHOR_PENDING_LINE),+ ),+ );++ // A second writer changes the file underneath us. Force the store in the+ // same turn so the content-branch reconcile runs deterministically.+ mkdirSync(resolve(tplFile, '..'), { recursive: true });+ const foreign = `---\ntitle: T\ndescription: d\n---\n\n# Template\n\n${FOREIGN_LINE}\n`;+ writeFileSync(tplFile, foreign, 'utf-8');+ await storeImmediately(server, docName);++ // The store is doc-authoritative: it writes the live doc to disk and does+ // NOT import the divergent disk bytes back into the doc. So the author's+ // pending line survives and the concurrent writer's foreign line never+ // replaces it in the live doc — the inverse of the retired managed store,+ // whose disk-wins reconcile imported the foreign bytes and discarded the+ // author's edit.+ const rig = server;+ const docSource = rig.instance.hocuspocus.documents+ .get(docName)+ ?.getText('source')+ .toString();+ expect(docSource).toContain(AUTHOR_PENDING_LINE);+ expect(docSource).not.toContain(FOREIGN_LINE);++ // The managed-store disk-wins reconcile never runs for a content doc, so+ // its checkpoint kind and its loss-ring site never fire. (A regression that+ // re-routed templates through the managed store would trip both.)+ expect(+ listCheckpoints(rig).filter((c) => c.kind === 'managed-artifact-reconcile'),+ ).toHaveLength(0);+ expect(+ readLossEvents(rig.contentDir).filter(+ (e) => e.site === 'managed-artifact-reconcile' && e.docName === docName,+ ),+ ).toHaveLength(0);++ await client.cleanup();+ },+ HARNESS_BOOT_TIMEOUT_MS + 60_000,+ );+});diff --git a/packages/app/tests/integration/template-delete-move-import.test.ts b/packages/app/tests/integration/template-delete-move-import.test.tsnew file mode 100644index 000000000..8a0679ac5--- /dev/null+++ b/packages/app/tests/integration/template-delete-move-import.test.ts@@ -0,0 +1,392 @@+/**+ * Behavioral coverage for the three template lifecycle routes whose+ * content-doc handling previously had only source-ordering pins:+ *+ * 1. DELETE tears down the live content doc and marks the content doc name+ * removed, so a stale IDB-cached tab is rejected on reconnect instead of+ * resurrecting the file (parity with ordinary doc deletion).+ * 2. MOVE tears down the FROM content doc and marks the FROM name removed.+ * The move handler records the source as DELETED (not renamed), so a stale+ * connection to the old name is refused, not redirected.+ * 3. IMPORT routes the composed bytes THROUGH the content doc's CRDT Y.Text,+ * not a filesystem-direct write.+ *+ * Everything runs against the real Hocuspocus server, real persistence branch,+ * real removal-redirect auth guard, and real WS clients — no mocks. The removal+ * guard's rejection is observed exactly as production does it: a fresh provider+ * connect fires `authenticationFailed` carrying the typed reason.+ */++import { randomUUID } from 'node:crypto';+import { existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { HocuspocusProvider } from '@hocuspocus/provider';+import { parseAuthRejectionWire } from '@inkeep/open-knowledge-server';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import * as Y from 'yjs';+import {+ createTestClient,+ createTestServer,+ HARNESS_BOOT_TIMEOUT_MS,+ pollUntil,+ type TestServer,+ wait,+} from './test-harness.ts';++let server: TestServer;++beforeAll(async () => {+ server = await createTestServer();+}, HARNESS_BOOT_TIMEOUT_MS);++afterAll(async () => {+ await server.cleanup();+});++function serverDoc(rig: TestServer, docName: string) {+ return rig.instance.hocuspocus.documents.get(docName);+}++function putTemplate(+ port: number,+ folder: string,+ name: string,+ body: string,+ frontmatter: Record<string, unknown>,+): Promise<Response> {+ return fetch(`http://127.0.0.1:${port}/api/template`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ folder, name, body, frontmatter }),+ });+}++function deleteTemplate(port: number, folder: string, name: string): Promise<Response> {+ const qs = new URLSearchParams({ name, folder });+ return fetch(`http://127.0.0.1:${port}/api/template?${qs.toString()}`, { method: 'DELETE' });+}++function moveTemplate(+ port: number,+ body: { fromFolder: string; fromName: string; toFolder: string; toName: string },+): Promise<Response> {+ return fetch(`http://127.0.0.1:${port}/api/template`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+}++function importTemplate(port: number, body: Record<string, unknown>): Promise<Response> {+ return fetch(`http://127.0.0.1:${port}/api/template/import`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+}++/** Write a source doc and wait until it has flushed to disk (import reads the file). */+async function writeSource(+ port: number,+ contentDir: string,+ docName: string,+ markdown: string,+): Promise<void> {+ const res = await fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ markdown, position: 'replace', docName }),+ });+ if (res.status !== 200) throw new Error(`agent-write-md failed for ${docName}: ${res.status}`);+ const filePath = join(contentDir, `${docName}.md`);+ for (let i = 0; i < 100; i++) {+ if (existsSync(filePath)) return;+ await wait(50);+ }+ throw new Error(`source ${docName}.md never flushed to disk`);+}++/**+ * Connect a bare provider expecting the removal-redirect guard to reject it;+ * return the typed rejection. Fails if the connection is admitted (synced)+ * instead. Mirrors the helper in `delete-durability.test.ts`.+ */+async function expectAuthRejection(+ port: number,+ docName: string,+): Promise<ReturnType<typeof parseAuthRejectionWire>> {+ const doc = new Y.Doc();+ const provider = new HocuspocusProvider({+ url: `ws://127.0.0.1:${port}/collab`,+ name: docName,+ document: doc,+ });+ try {+ const reason = await new Promise<string>((resolve, reject) => {+ const timer = setTimeout(+ () => reject(new Error(`authenticationFailed did not fire for ${docName}`)),+ 15_000,+ );+ provider.on('authenticationFailed', (payload: { reason: string }) => {+ clearTimeout(timer);+ resolve(payload.reason);+ });+ provider.on('synced', () => {+ clearTimeout(timer);+ reject(new Error(`connection to ${docName} was unexpectedly admitted`));+ });+ });+ return parseAuthRejectionWire(reason);+ } finally {+ provider.destroy();+ doc.destroy();+ }+}++describe('template delete/move/import — content-doc lifecycle', () => {+ test(+ 'DELETE tears down the open content doc and marks its name removed',+ async () => {+ const rig = server;+ const name = `daily-${randomUUID().slice(0, 8)}`;+ const docName = `.ok/templates/${name}`;++ expect(+ (await putTemplate(rig.port, '', name, '# Daily\n\nv1.\n', { title: 'Daily' })).status,+ ).toBe(200);++ // Open the content doc (a user viewing the template) and HOLD the+ // connection — so the only thing that can unload the doc is the DELETE+ // handler's teardown, not a last-connection-closed unload.+ const client = await createTestClient(rig.port, docName, { skipInvariantWatcher: true });+ try {+ await pollUntil(() => client.ytext.toString().includes('# Daily'), 8000);+ expect(serverDoc(rig, docName)).toBeDefined();++ const del = await deleteTemplate(rig.port, '', name);+ expect(del.status).toBe(200);+ expect((await del.json()).existed).toBe(true);++ // Teardown: the handler awaits captureAndCloseDocuments before+ // responding, so the live doc is unloaded by the time DELETE returns.+ expect(serverDoc(rig, docName)).toBeUndefined();+ expect(existsSync(join(rig.contentDir, '.ok', 'templates', `${name}.md`))).toBe(false);++ // Removal-guard registration: a fresh WS connect to the content doc name+ // is refused as deleted — the production consequence that stops an+ // IDB-cached tab from resurrecting the file. This is what proves+ // setDeleted ran on the CONTENT doc name (not the retired synthetic one).+ expect((await expectAuthRejection(rig.port, docName)).kind).toBe('doc-deleted');+ } finally {+ await client.cleanup();+ }+ },+ HARNESS_BOOT_TIMEOUT_MS + 30_000,+ );++ test(+ 'MOVE tears down the FROM content doc and marks the FROM name removed',+ async () => {+ const rig = server;+ const fromName = `note-${randomUUID().slice(0, 8)}`;+ const toName = `${fromName}-moved`;+ const fromDoc = `.ok/templates/${fromName}`;++ expect(+ (await putTemplate(rig.port, '', fromName, '# Note\n\nv1.\n', { title: 'Note' })).status,+ ).toBe(200);++ const client = await createTestClient(rig.port, fromDoc, { skipInvariantWatcher: true });+ try {+ await pollUntil(() => client.ytext.toString().includes('# Note'), 8000);+ expect(serverDoc(rig, fromDoc)).toBeDefined();++ const move = await moveTemplate(rig.port, {+ fromFolder: '',+ fromName,+ toFolder: '',+ toName,+ });+ expect(move.status).toBe(200);++ // FROM-side teardown: the source doc is torn down before the relocate,+ // so its persistence branch can't re-store at the now-stale path.+ expect(serverDoc(rig, fromDoc)).toBeUndefined();+ expect(existsSync(join(rig.contentDir, '.ok', 'templates', `${fromName}.md`))).toBe(false);+ expect(existsSync(join(rig.contentDir, '.ok', 'templates', `${toName}.md`))).toBe(true);++ // The handler marks the OLD name removed synchronously ("parity with+ // ordinary doc deletion"); the content watcher's rename-pairing may then+ // upgrade that entry to a redirect toward the new name. Either way the+ // old name refuses a fresh connect, so a stale IDB-cached tab cannot+ // resurrect the moved file — the removal-guard parity the move exists for.+ const rejection = await expectAuthRejection(rig.port, fromDoc);+ expect(['doc-deleted', 'rename-redirect']).toContain(rejection.kind);+ } finally {+ await client.cleanup();+ }+ },+ HARNESS_BOOT_TIMEOUT_MS + 30_000,+ );++ test(+ 'IMPORT routes the composed bytes through the content doc, not a fs-direct write',+ async () => {+ const rig = server;+ const marker = `imported-body-${randomUUID().slice(0, 8)}`;+ const sourceName = `src-${randomUUID().slice(0, 8)}`;+ const tplName = `tpl-${randomUUID().slice(0, 8)}`;+ const tplDoc = `.ok/templates/${tplName}`;++ await writeSource(+ rig.port,+ rig.contentDir,+ sourceName,+ `---\ntitle: Source Title\n---\n\n# Heading\n\n${marker}\n`,+ );++ // Open the target content doc BEFORE importing — it does not exist yet, so+ // it opens empty. This is the CRDT-routing discriminator: a fs-direct+ // create of a NEW file records only the disk index (the watcher's create+ // arm never applies to a loaded doc), so it would leave this open doc+ // empty; only a write routed through the content doc fills the client.+ const client = await createTestClient(rig.port, tplDoc, { skipInvariantWatcher: true });+ try {+ expect(client.ytext.toString()).toBe('');++ const imp = await importTemplate(rig.port, {+ sourcePath: sourceName,+ targetFolder: '',+ name: tplName,+ });+ expect(imp.status).toBe(200);++ // The composed bytes arrive in the SAME Y.Doc the client is bound to —+ // proof the import wrote through the content doc. The unique body marker+ // reaching an already-open doc is only possible via the CRDT path.+ await pollUntil(() => client.ytext.toString().includes(marker), 8000);+ const live = client.ytext.toString();+ expect(live).toContain(marker); // imported body+ expect(live).toContain('template:'); // composed identity block+ expect(live).toContain('Source Title'); // title lifted into the template block++ // The persisted file equals the doc content (the flush wrote the doc).+ const tplFile = join(rig.contentDir, '.ok', 'templates', `${tplName}.md`);+ expect(existsSync(tplFile)).toBe(true);+ expect(readFileSync(tplFile, 'utf-8')).toBe(live);+ } finally {+ await client.cleanup();+ }+ },+ HARNESS_BOOT_TIMEOUT_MS + 30_000,+ );++ test(+ 'PUT, import, and move register the template in the file index by the time the response returns',+ async () => {+ const rig = server;++ // All three writes land in a BRAND-NEW `<folder>/.ok/templates/` dir+ // created by the operation itself. That is the watcher's weak spot: on+ // Linux the create event for a file written into a just-created subdir+ // can be dropped outright (the recursive inotify subwatch registers+ // async). The handlers close it by registering the doc synchronously+ // before responding — so a SINGLE un-polled /api/pages read right after+ // the response is the deterministic oracle. A poll loop here would mask+ // a dropped event by letting the eventual watcher path win instead.+ async function pagesHas(docName: string): Promise<boolean> {+ const res = await fetch(`http://127.0.0.1:${rig.port}/api/pages`);+ expect(res.ok).toBe(true);+ const data = (await res.json()) as { pages?: Array<{ docName: string }> };+ return data.pages?.some((p) => p.docName === docName) ?? false;+ }++ const putFolder = `fresh-put-${randomUUID().slice(0, 8)}`;+ const putName = `tpl-${randomUUID().slice(0, 8)}`;+ const put = await putTemplate(rig.port, putFolder, putName, '# Standup\n\nBody.\n', {+ title: 'Standup',+ });+ expect(put.status).toBe(200);+ expect(await pagesHas(`${putFolder}/.ok/templates/${putName}`)).toBe(true);++ const sourceName = `src-idx-${randomUUID().slice(0, 8)}`;+ await writeSource(rig.port, rig.contentDir, sourceName, '# Imported\n\nBody.\n');+ const impFolder = `fresh-imp-${randomUUID().slice(0, 8)}`;+ const impName = `tpl-${randomUUID().slice(0, 8)}`;+ const imp = await importTemplate(rig.port, {+ sourcePath: sourceName,+ targetFolder: impFolder,+ name: impName,+ });+ expect(imp.status).toBe(200);+ expect(await pagesHas(`${impFolder}/.ok/templates/${impName}`)).toBe(true);++ // MOVE into a folder whose `.ok/templates/` did not previously exist —+ // the relocate mkdirs the destination dir, so the same race applies on+ // the same terms as put/import.+ const moveToFolder = `fresh-mov-${randomUUID().slice(0, 8)}`;+ const mov = await moveTemplate(rig.port, {+ fromFolder: putFolder,+ fromName: putName,+ toFolder: moveToFolder,+ toName: putName,+ });+ expect(mov.status).toBe(200);+ expect(await pagesHas(`${moveToFolder}/.ok/templates/${putName}`)).toBe(true);+ },+ HARNESS_BOOT_TIMEOUT_MS + 30_000,+ );++ test(+ 'rejects a `..` folder that escapes the content directory on every mutation route',+ async () => {+ const rig = server;++ // `validateFolderRel` is the sole path-escape guard for the template+ // routes now that `templateAbsPath` (and its path-escape unit test) are+ // gone — the request schema accepts any `folder` string. All four+ // handlers share the guard, so all four call sites are pinned (PUT, both+ // move sides, DELETE, IMPORT) — a future refactor that splits one onto a+ // different validation helper fails loud.+ const put = await putTemplate(rig.port, '../etc', 'evil', '# x\n', { title: 'x' });+ expect(put.status).toBe(400);+ expect((await put.json()).type).toBe('urn:ok:error:invalid-request');++ const moveFrom = await moveTemplate(rig.port, {+ fromFolder: '../etc',+ fromName: 'evil',+ toFolder: '',+ toName: 'safe',+ });+ expect(moveFrom.status).toBe(400);+ expect((await moveFrom.json()).type).toBe('urn:ok:error:invalid-request');++ const moveTo = await moveTemplate(rig.port, {+ fromFolder: '',+ fromName: 'safe',+ toFolder: '../etc',+ toName: 'evil',+ });+ expect(moveTo.status).toBe(400);+ expect((await moveTo.json()).type).toBe('urn:ok:error:invalid-request');++ const del = await deleteTemplate(rig.port, '../etc', 'evil');+ expect(del.status).toBe(400);+ expect((await del.json()).type).toBe('urn:ok:error:invalid-request');++ // Import validates `targetFolder` only after resolving the source, so the+ // pin needs a real source doc — otherwise a source-not-found error would+ // mask a weakened folder guard.+ const escSource = `src-esc-${randomUUID().slice(0, 8)}`;+ await writeSource(rig.port, rig.contentDir, escSource, '# Esc\n\nBody.\n');+ const imp = await importTemplate(rig.port, {+ sourcePath: escSource,+ targetFolder: '../etc',+ name: 'evil',+ });+ expect(imp.status).toBe(400);+ expect((await imp.json()).type).toBe('urn:ok:error:invalid-request');+ },+ HARNESS_BOOT_TIMEOUT_MS + 30_000,+ );+});diff --git a/packages/app/tests/integration/template-handler-contract.test.ts b/packages/app/tests/integration/template-handler-contract.test.tsnew file mode 100644index 000000000..af1d336f7--- /dev/null+++ b/packages/app/tests/integration/template-handler-contract.test.ts@@ -0,0 +1,78 @@+/**+ * Template-handler asymmetry contract — static analysis gate.+ *+ * Mirror of `conflict-gate-coverage.test.ts` / `attribution-sweep-coverage.test.ts`:+ * statically scans the four mutating template handlers in `api-extension.ts` and+ * pins three deliberate asymmetries the templates-as-content cutover preserves.+ * These are properties of the HANDLER source, not of the end-to-end runtime — the+ * `files` derived-view channel also fires from raw disk events, and the CRDT+ * write path's writeTracker suppresses its own self-writes, so the honest thing+ * to pin is which handler emits the signal directly. A future edit that adds a+ * TO-side conflict gate to move, drops a `files` signal, or reorders the move's+ * fs-direct content-edit tail ahead of the source-doc teardown trips this test.+ */++import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, test } from 'vitest';++const API_EXT_PATH = join(import.meta.dirname, '../../../server/src/api-extension.ts');+const source = readFileSync(API_EXT_PATH, 'utf8');++/**+ * Slice one `const handle... = withValidation(` template handler body out of the+ * source, bounded at the next top-level handler / route table — the same+ * extractor shape the sibling meta-tests use.+ */+function extractHandlerBody(handlerName: string): string {+ const start = source.indexOf(`const ${handlerName} = withValidation(`);+ if (start === -1) throw new Error(`${handlerName}: withValidation handler not found in source`);+ const nextConst = source.indexOf('\n const handle', start + 1);+ const nextRoutes = source.indexOf('\n const routes:', start + 1);+ const candidates = [nextConst, nextRoutes].filter((i) => i !== -1);+ const next = candidates.length === 0 ? -1 : Math.min(...candidates);+ return source.slice(start, next === -1 ? source.length : next);+}++const put = extractHandlerBody('handleTemplatePut');+const del = extractHandlerBody('handleTemplateDelete');+const move = extractHandlerBody('handleTemplateMove');+const imp = extractHandlerBody('handleTemplateImport');++describe('template handler asymmetries (FR5)', () => {+ test('move gates the FROM side only — exactly one conflict gate, keyed on fromName', () => {+ const gateCalls = move.match(/checkTemplateConflictGate\(/g) ?? [];+ expect(gateCalls.length).toBe(1);+ // The gate takes the pre-resolved doc name, so from-side keying reads as+ // the doc-name builder over the FROM folder + name.+ expect(+ /checkTemplateConflictGate\(\s*templateDocNameFor\(fromValidated\.folderRel, body\.fromName\)/.test(+ move,+ ),+ ).toBe(true);+ // The TO side is never gated: the destination doc does not exist yet, so+ // there is nothing to be mid-conflict.+ expect(/checkTemplateConflictGate\(\s*templateDocNameFor\(toValidated/.test(move)).toBe(false);+ });++ test("move's optional content-edit tail is fs-direct AFTER the source-doc teardown", () => {+ const teardown = move.indexOf('captureAndCloseDocuments(');+ const fsDirectEdit = move.indexOf('applyTemplateWrite(');+ expect(teardown).toBeGreaterThan(-1);+ expect(fsDirectEdit).toBeGreaterThan(-1);+ // Teardown must precede the fs-direct rewrite: the source doc is closed+ // before the relocated file is edited, so the edit surfaces as a watcher+ // event rather than resurrecting the moved template through a stale store.+ expect(teardown).toBeLessThan(fsDirectEdit);+ });++ test('the files signal fires on move and import but not on put and delete', () => {+ expect(move.includes("signalChannel?.('files')")).toBe(true);+ expect(imp.includes("signalChannel?.('files')")).toBe(true);+ // put/delete route their disk change through the content pipeline (CRDT+ // paired-write / doc teardown); the watcher re-derives the file index, so a+ // handler-level signal would be redundant.+ expect(put.includes("signalChannel?.('files')")).toBe(false);+ expect(del.includes("signalChannel?.('files')")).toBe(false);+ });+});diff --git a/packages/app/tests/integration/template-history-attribution.test.ts b/packages/app/tests/integration/template-history-attribution.test.tsnew file mode 100644index 000000000..59c94d3d4--- /dev/null+++ b/packages/app/tests/integration/template-history-attribution.test.ts@@ -0,0 +1,130 @@+import { randomUUID } from 'node:crypto';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import {+ awaitWipCommits,+ createTestClient,+ createTestServer,+ pollUntil,+ type TestServer,+} from './test-harness.ts';++/**+ * End-to-end proof, through the real server + real shadow git, that a template's+ * attribution stays whole across the cutover and that the content store never+ * mints a typed folder subject.+ *+ * A template is now an ordinary content doc at `<folder>/.ok/templates/<name>`.+ * An HTTP lifecycle write records its contributor under+ * `okArtifactKey('template', folder, name)`, which is byte-identical to that+ * content doc name — so the typed `template-create` folder event and the plain+ * `wip:` doc commits both resolve to the one content-doc identity. Crucially,+ * the persistence store's own commits are `wip:`: the typed `template-*` subject+ * is stamped only by the HTTP route (a folder-timeline event), never by the+ * store as an editor CRDT edit flows through it.+ */+type HistoryEntry = {+ sha: string;+ message: string;+ type: string;+ contributors: Array<{ docs: string[] }>;+};++describe('template history — HTTP typed writes and editor wip edits unify under one key (FR6 / D11)', () => {+ let server: TestServer;++ beforeEach(async () => {+ server = await createTestServer({ gitEnabled: true, commitDebounceMs: 100 });+ });+ afterEach(async () => {+ await server.cleanup();+ });++ async function history(query: string): Promise<HistoryEntry[]> {+ const res = await fetch(`http://127.0.0.1:${server.port}/api/history?${query}`);+ expect(res.status).toBe(200);+ const body = (await res.json()) as { entries: HistoryEntry[] };+ return body.entries;+ }++ const docHistory = (docName: string) =>+ history(`docName=${encodeURIComponent(docName)}&limit=100`);+ const folderTimeline = (folder: string) => history(`folder=${encodeURIComponent(folder)}`);++ test('a typed HTTP write attributes under the content doc name; the store mints wip:, never a typed folder subject', async () => {+ const folder = 'notes';+ const name = `standup-${randomUUID().slice(0, 8)}`;+ const docName = `${folder}/.ok/templates/${name}`;++ // HTTP create routes composed bytes through the template's CRDT doc and+ // stamps a typed `template-create:` folder event, attributed under+ // okArtifactKey('template', folder, name). The agentId makes attribution+ // non-anonymous, so the typed subject is actually recorded (an anonymous+ // write would fall back to a plain wip: subject).+ const putRes = await fetch(`http://127.0.0.1:${server.port}/api/template`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ folder,+ name,+ body: '# Standup\n\nAgenda.\n',+ frontmatter: { title: 'Standup', description: 'Use for standups.' },+ agentId: 'http-writer',+ }),+ });+ expect(putRes.status).toBe(200);+ await awaitWipCommits(server, docName, 1);++ // The typed lifecycle event lives on the FOLDER timeline, attributed under a+ // key byte-identical to the content doc name — this is the attribution+ // identity the editor edits below share.+ const putFolder = await folderTimeline(folder);+ const createEvent = putFolder.find((e) => e.message.startsWith('template-create:'));+ expect(createEvent).toBeDefined();+ expect(createEvent?.contributors.some((c) => c.docs.includes(docName))).toBe(true);++ // The store's OWN commit for the doc content is a plain wip: subject — the+ // typed `template-*` subject is the HTTP route's folder event, not the store's.+ const putDoc = await docHistory(docName);+ expect(putDoc.length).toBeGreaterThanOrEqual(1);+ expect(putDoc.every((e) => /^wip:/i.test(e.message))).toBe(true);+ const putShas = new Set(putDoc.map((e) => e.sha));++ // An editor CRDT edit to the same doc lands as an ordinary content write.+ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });+ await pollUntil(() => client.ytext.toString().includes('Agenda.'), 5000);+ client.doc.transact(() => {+ client.ytext.insert(client.ytext.length, '\nMore agenda.\n');+ });++ // Await the editor edit's OWN commit — a NEW wip: row distinct from the PUT's+ // (flush every poll to drain the L2 debounce deterministically).+ let editDoc: HistoryEntry[] = [];+ let editEntry: HistoryEntry | undefined;+ await pollUntil(+ async () => {+ await fetch(`http://127.0.0.1:${server.port}/api/test-flush-git`, { method: 'POST' }).catch(+ () => null,+ );+ editDoc = await docHistory(docName);+ editEntry = editDoc.find((e) => !putShas.has(e.sha));+ return editEntry !== undefined;+ },+ 20_000,+ 250,+ );+ await client.cleanup();++ // The editor edit is in the template's OWN document history (unifying under+ // the content doc name) and the store minted a wip: subject for it — not a+ // typed template-* subject. A store that started stamping typed template-*+ // subjects on content edits would flip this message; that must never happen.+ expect(editEntry?.message).toMatch(/^wip:/i);+ expect(editDoc.every((e) => /^wip:/i.test(e.message))).toBe(true);++ // The editor CRDT edit produced NO new folder event — the folder timeline+ // still carries exactly the one typed HTTP subject, and no wip: row leaks in.+ const editFolder = await folderTimeline(folder);+ expect(editFolder.filter((e) => e.message.startsWith('template-'))).toHaveLength(1);+ expect(editFolder.every((e) => !/^wip:/i.test(e.message))).toBe(true);+ }, 30_000);+});diff --git a/packages/app/tests/integration/template-tombstone-and-conflict-gate.test.ts b/packages/app/tests/integration/template-tombstone-and-conflict-gate.test.tsnew file mode 100644index 000000000..d878ed646--- /dev/null+++ b/packages/app/tests/integration/template-tombstone-and-conflict-gate.test.ts@@ -0,0 +1,202 @@+/**+ * Two guarantees the templates-as-content cutover must hold at the LIVE server,+ * proven against the real Hocuspocus server + real persistence branch + real OS+ * watcher (not mocks):+ *+ * 1. Tombstone quarantine — a stale `__template__/…` doc name (an old client or+ * a pre-upgrade bookmark) opened against the new server seeds nothing and+ * stores nothing, so it can never become a SECOND CRDT doc for a template+ * file nor write a literal `__template__/…` file. Either would be the+ * double-doc corruption the migration's atomicity rule forbids.+ *+ * 2. Live conflict gate — a template is a content doc now, so a template file+ * bearing merge conflict markers drives its Y.Doc into the conflict+ * lifecycle, and the previously-dead conflict gate refuses every mutating+ * template route (PUT, move, DELETE, and import) until the conflict is+ * resolved.+ *+ * The watcher CLASSIFICATION into the conflict lifecycle is pinned in+ * `template-watcher-capabilities.test.ts`; this suite pins the HTTP gate's+ * refusal on top of that classification. The structural handler asymmetries+ * (which routes signal `files`, move's FROM-side-only gate, the fs-direct+ * content-edit tail) are pinned in `template-handler-contract.test.ts`.+ */++import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import {+ createTestClient,+ createTestServer,+ HARNESS_BOOT_TIMEOUT_MS,+ pollUntil,+ type TestServer,+ wait,+} from './test-harness.ts';++let server: TestServer | undefined;++afterEach(async () => {+ if (server) {+ await server.cleanup();+ server = undefined;+ }+});++/**+ * A content directory pre-seeded with an empty `.ok/config.yml` so `.ok` and its+ * descendants are present in the watcher's initial recursive scan — a template+ * seeded here is watched from boot.+ */+function seedContentDir(): string {+ const dir = mkdtempSync(join(tmpdir(), 'ok-template-gate-'));+ mkdirSync(resolve(dir, '.ok'), { recursive: true });+ writeFileSync(resolve(dir, '.ok', 'config.yml'), '', 'utf-8');+ return dir;+}++function serverDoc(rig: TestServer, docName: string) {+ return rig.instance.hocuspocus.documents.get(docName);+}++function lifecycleStatus(rig: TestServer, docName: string): unknown {+ return serverDoc(rig, docName)?.getMap('lifecycle').get('status');+}++describe('template tombstone quarantine (FR3)', () => {+ test(+ 'a stale __template__ doc opened live seeds nothing, no-ops on write, and creates no file',+ async () => {+ server = await createTestServer({ debounce: 100, maxDebounce: 400 });+ const rig = server;+ const folder = `notes-${randomUUID().slice(0, 8)}`;+ const name = `daily-${randomUUID().slice(0, 8)}`;+ const syntheticName = `__template__/${folder}/${name}`;++ // The tombstone load guard seeds nothing: the synthetic doc opens EMPTY.+ const client = await createTestClient(rig.port, syntheticName, {+ skipInvariantWatcher: true,+ });+ expect(client.ytext.toString()).toBe('');++ // Write to the synthetic doc — proving the store guard is exercised on a+ // dirty, synced doc (not a never-touched one). The store guard no-ops for a+ // `__template__` name, so the debounced store fires and lands nothing.+ client.doc.transact(() =>+ client.ytext.insert(client.ytext.length, 'stale synthetic write\n'),+ );+ await pollUntil(+ () =>+ serverDoc(rig, syntheticName)?.getText('source').toString().includes('stale synthetic') ??+ false,+ 8000,+ );++ // Wait past maxDebounce so any scheduled store has fired-and-no-op'd, then+ // assert the never-creates-file oracle — a bounded negative-window check+ // (there is no positive event to wait on for "a file was not written").+ await wait(700);++ // No literal `__template__/…` file, and nothing leaked to the content+ // branch at the path the synthetic name would map to. Either would be the+ // double-doc corruption the tombstone exists to prevent.+ expect(existsSync(join(rig.contentDir, '__template__', folder, `${name}.md`))).toBe(false);+ expect(existsSync(join(rig.contentDir, folder, '.ok', 'templates', `${name}.md`))).toBe(+ false,+ );+ expect(existsSync(join(rig.contentDir, '__template__'))).toBe(false);++ await client.cleanup();+ },+ HARNESS_BOOT_TIMEOUT_MS + 30_000,+ );+});++describe('template live conflict gate (FR5)', () => {+ test(+ 'conflict markers in a template file make the live gate refuse PUT, move, DELETE, and import (previously dead)',+ async () => {+ const name = `tpl-${randomUUID().slice(0, 8)}`;+ const docName = `.ok/templates/${name}`;+ const contentDir = seedContentDir();+ const tplFile = resolve(contentDir, '.ok', 'templates', `${name}.md`);+ const clean = '---\ntitle: T\ndescription: initial\n---\n\n# Template\n\nv1.\n';+ mkdirSync(resolve(tplFile, '..'), { recursive: true });+ writeFileSync(tplFile, clean, 'utf-8');++ // An ordinary source doc for the import route — import reads the source+ // BEFORE it reaches the target conflict gate, so the source must exist and+ // be loadable; a missing source would 404 short of the gate under test.+ const srcName = `imp-src-${randomUUID().slice(0, 8)}`;+ writeFileSync(resolve(contentDir, `${srcName}.md`), '# Source\n\nimport me.\n', 'utf-8');++ server = await createTestServer({ contentDir, debounce: 100, maxDebounce: 400 });+ const rig = server;++ // Open the doc so the watcher's conflict classification has a loaded target+ // (the disk-event conflict arm returns early when the doc is not loaded).+ const client = await createTestClient(rig.port, docName, { skipInvariantWatcher: true });+ await pollUntil(() => client.ytext.toString() === clean, 8000);++ // A git merge left conflict markers in the file → conflict lifecycle.+ const conflicted =+ '---\ntitle: T\ndescription: initial\n---\n\n# Template\n\n<<<<<<< HEAD\nours.\n=======\ntheirs.\n>>>>>>> branch\n';+ writeFileSync(tplFile, conflicted, 'utf-8');+ await pollUntil(() => lifecycleStatus(rig, docName) === 'conflict', 15000);++ // PUT refuses: the previously-dead conflict gate now looks up the content+ // doc name and finds it mid-conflict — the CRDT paired-write path would+ // otherwise clobber a doc the user is mid-resolving.+ const put = await fetch(`http://127.0.0.1:${rig.port}/api/template`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ folder: '', name, body: '# clobber', frontmatter: { title: 'X' } }),+ });+ expect(put.status).toBe(409);+ expect(put.headers.get('content-type')).toBe('application/problem+json');+ expect(((await put.json()) as { type: string }).type).toBe('urn:ok:error:doc-in-conflict');++ // Move refuses on the FROM side: the move gate keys on `fromName`, so moving+ // the conflicted source refuses before tearing the source doc down.+ const movedName = `${name}moved`;+ const move = await fetch(`http://127.0.0.1:${rig.port}/api/template`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ fromFolder: '', fromName: name, toFolder: '', toName: movedName }),+ });+ expect(move.status).toBe(409);+ expect(((await move.json()) as { type: string }).type).toBe('urn:ok:error:doc-in-conflict');++ // DELETE refuses too (query-param transport): the gate keys on the content+ // doc name, so removing a mid-conflict template is refused before the file+ // is touched. Its call site went live in this migration.+ const del = await fetch(+ `http://127.0.0.1:${rig.port}/api/template?folder=&name=${encodeURIComponent(name)}`,+ { method: 'DELETE' },+ );+ expect(del.status).toBe(409);+ expect(((await del.json()) as { type: string }).type).toBe('urn:ok:error:doc-in-conflict');++ // Import refuses when its TARGET template is mid-conflict: the gate keys on+ // the target (targetFolder, name), so importing over the conflicted+ // template is refused. Its call site went live in this migration too.+ const imp = await fetch(`http://127.0.0.1:${rig.port}/api/template/import`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ sourcePath: srcName, name, targetFolder: '' }),+ });+ expect(imp.status).toBe(409);+ expect(((await imp.json()) as { type: string }).type).toBe('urn:ok:error:doc-in-conflict');++ // No clobber, no move: the file still holds the markers and no moved file+ // was created. All four refusals above left the conflicted template intact.+ expect(readFileSync(tplFile, 'utf-8')).toBe(conflicted);+ expect(existsSync(resolve(contentDir, '.ok', 'templates', `${movedName}.md`))).toBe(false);++ await client.cleanup();+ },+ HARNESS_BOOT_TIMEOUT_MS + 30_000,+ );+});diff --git a/packages/app/tests/integration/template-watcher-capabilities.test.ts b/packages/app/tests/integration/template-watcher-capabilities.test.tsnew file mode 100644index 000000000..ee7c8299e--- /dev/null+++ b/packages/app/tests/integration/template-watcher-capabilities.test.ts@@ -0,0 +1,255 @@+/**+ * The templates-as-content payoff: template files inherit the full content+ * watcher, so external edits, brand-new folders, deletes, renames, and merge+ * conflict markers behave like any other doc — with zero template-specific+ * watcher code. Before the migration a template was watched by a dedicated+ * polling watcher whose roots were frozen at boot (no new-folder rescue, no+ * unlink, no rename pairing, no conflict classification); this suite proves+ * those four capabilities against the real integration harness (real OS+ * watcher, real filesystem, real Hocuspocus server, real WS client).+ *+ * The external-edit reconcile into an open template doc is already pinned in+ * `managed-artifact-doc.test.ts` at the content name; it is not repeated here.+ * The chokidar-backend twins for the new-folder and conflict cases live at the+ * watcher DiskEvent seam in `packages/server/src/file-watcher-chokidar-fallback.test.ts`+ * (the full server harness has no forceBackend knob).+ */++import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import {+ createTestClient,+ createTestServer,+ HARNESS_BOOT_TIMEOUT_MS,+ pollUntil,+ readTestDoc,+ type TestServer,+} from './test-harness.ts';++let server: TestServer | undefined;++afterEach(async () => {+ if (server) {+ await server.cleanup();+ server = undefined;+ }+});++/**+ * A content directory pre-seeded with an empty `.ok/config.yml` so `.ok` and+ * its descendants are present in the watcher's initial recursive scan. Tests+ * that need a template watched from boot seed it here before `createTestServer`.+ */+function seedContentDir(): string {+ const dir = mkdtempSync(join(tmpdir(), 'ok-template-watcher-'));+ mkdirSync(resolve(dir, '.ok'), { recursive: true });+ writeFileSync(resolve(dir, '.ok', 'config.yml'), '', 'utf-8');+ return dir;+}++function serverDoc(rig: TestServer, docName: string) {+ return rig.instance.hocuspocus.documents.get(docName);+}++function lifecycleStatus(rig: TestServer, docName: string): unknown {+ return serverDoc(rig, docName)?.getMap('lifecycle').get('status');+}++/**+ * Poll the watcher's in-memory file index (via `GET /api/pages`, which iterates+ * the full `getFileIndex()` with no hidden-doc filter, so template content docs+ * appear) until `docName` shows up. `/api/documents` is the sidebar view and+ * hides `.ok` rows, so it never surfaces a template; the index is the honest+ * signal that the watcher saw the file (opening a client hydrates from disk via+ * `onLoadDocument` regardless of the index, so client hydration alone would not+ * prove the folder was indexed).+ *+ * One-shot rescan net: on Linux CI `@parcel/watcher` can drop the folder-create+ * for a deep, freshly-created subdir (inotify subwatch registration race). The+ * rescan re-runs the seed walk (NOT a server restart — the server stays up and+ * loaded docs are untouched). On macOS FSEvents delivers the folder-create live,+ * so the rescan never fires; the pure-live folder-create capability is pinned+ * deterministically by the chokidar DiskEvent twin in file-watcher-chokidar-fallback.+ */+async function awaitPageIndexed(+ rig: TestServer,+ docName: string,+ timeoutMs = 45_000,+): Promise<void> {+ const start = Date.now();+ let rescued = false;+ while (Date.now() - start < timeoutMs) {+ const res = await fetch(`http://127.0.0.1:${rig.port}/api/pages`).catch(() => null);+ if (res?.ok) {+ const data = (await res.json()) as { pages?: Array<{ docName: string }> };+ if (data.pages?.some((p) => p.docName === docName)) return;+ }+ if (!rescued && Date.now() - start >= 2_000) {+ rescued = true;+ await fetch(`http://127.0.0.1:${rig.port}/api/test-rescan-files`, { method: 'POST' }).catch(+ () => null,+ );+ }+ await new Promise((r) => setTimeout(r, 50));+ }+ throw new Error(`awaitPageIndexed: ${docName} not indexed within ${timeoutMs}ms`);+}++describe('template watcher capabilities — content pipeline parity (FR4)', () => {+ test(+ 'a template created in a folder that did not exist at boot indexes and reconciles without a restart',+ async () => {+ server = await createTestServer();+ const rig = server;+ // A folder absent at boot. The dedicated template watcher froze its roots at+ // boot, so a template born here was invisible until restart; the content+ // watcher's folder-create rescue indexes it live.+ const folder = `folder-${randomUUID().slice(0, 8)}`;+ const name = `tpl-${randomUUID().slice(0, 8)}`;+ const docName = `${folder}/.ok/templates/${name}`;+ const src =+ '---\ntitle: Standup\ndescription: a standup template\n---\n\n# {{date}}\n\nStandup.\n';++ const tplFile = resolve(rig.contentDir, folder, '.ok', 'templates', `${name}.md`);+ mkdirSync(resolve(tplFile, '..'), { recursive: true });+ writeFileSync(tplFile, src, 'utf-8');++ // Index without restart: the watcher's file index now carries the template.+ await awaitPageIndexed(rig, docName);++ // Reconcile without restart: the freshly-indexed doc opens and hydrates.+ const client = await createTestClient(rig.port, docName, { skipInvariantWatcher: true });+ await pollUntil(() => client.ytext.toString() === src, 8000);+ expect(client.ytext.toString()).toBe(src);++ await client.cleanup();+ },+ HARNESS_BOOT_TIMEOUT_MS + 60_000,+ );++ test(+ 'a template deleted on disk closes the doc cleanly and is not resurrected by a debounced store',+ async () => {+ // Watched from boot; a moderate store debounce keeps the dirty edit below+ // pending so the external delete lands while a store is scheduled — the+ // exact resurrection vector the old managed store left open for templates.+ const name = `tpl-${randomUUID().slice(0, 8)}`;+ const docName = `.ok/templates/${name}`;+ const contentDir = seedContentDir();+ const tplFile = resolve(contentDir, '.ok', 'templates', `${name}.md`);+ const src = '---\ntitle: T\ndescription: d\n---\n\n# Template\n\nv1.\n';+ mkdirSync(resolve(tplFile, '..'), { recursive: true });+ writeFileSync(tplFile, src, 'utf-8');++ server = await createTestServer({ contentDir, debounce: 200, maxDebounce: 800 });+ const rig = server;++ const client = await createTestClient(rig.port, docName, { skipInvariantWatcher: true });+ await pollUntil(() => client.ytext.toString() === src, 8000);++ // Dirty the doc: this edit is live in the server Y.Doc but held off disk by+ // the store debounce.+ client.doc.transact(() => client.ytext.insert(client.ytext.length, 'pending edit\n'));+ await pollUntil(+ () =>+ serverDoc(rig, docName)?.getText('source').toString().includes('pending edit') ?? false,+ 8000,+ );++ // External unlink.+ rmSync(tplFile);++ // Clean unlink: the delete handler force-unloads the doc, which skips the+ // store, so the scheduled debounce cannot re-create the file.+ await pollUntil(() => serverDoc(rig, docName) === undefined, 15000);+ expect(readTestDoc(rig.contentDir, docName)).toBe('');++ // No resurrection: a surviving pending store would flush within maxDebounce.+ // Waiting past it and re-asserting absence is a bounded negative-window+ // check (there is no positive event to wait on for "a file was not written").+ await new Promise((r) => setTimeout(r, 1200));+ expect(readTestDoc(rig.contentDir, docName)).toBe('');+ expect(serverDoc(rig, docName)).toBeUndefined();++ await client.cleanup();+ },+ HARNESS_BOOT_TIMEOUT_MS + 30_000,+ );++ test(+ 'a template renamed on disk is paired as a rename, not an unrelated create plus delete',+ async () => {+ // Both names live in the same boot-watched `.ok/templates/` folder. The+ // watcher pairs the delete+create by content hash within one batch and+ // marks the loaded doc `renamed` (a create+delete would instead mark the+ // old doc `deleted-upstream`), so the lifecycle status is the pairing oracle.+ const from = `a-${randomUUID().slice(0, 8)}`;+ const to = `b-${randomUUID().slice(0, 8)}`;+ const fromDoc = `.ok/templates/${from}`;+ const toDoc = `.ok/templates/${to}`;+ const contentDir = seedContentDir();+ const fromFile = resolve(contentDir, '.ok', 'templates', `${from}.md`);+ const toFile = resolve(contentDir, '.ok', 'templates', `${to}.md`);+ const src = '---\ntitle: T\ndescription: d\n---\n\n# Template\n\nBody.\n';+ mkdirSync(resolve(fromFile, '..'), { recursive: true });+ writeFileSync(fromFile, src, 'utf-8');++ server = await createTestServer({ contentDir, debounce: 100, maxDebounce: 400 });+ const rig = server;++ // Load the doc so `case 'rename'` has a target to stamp.+ const client = await createTestClient(rig.port, fromDoc, { skipInvariantWatcher: true });+ await pollUntil(() => client.ytext.toString() === src, 8000);++ renameSync(fromFile, toFile);++ await pollUntil(() => lifecycleStatus(rig, fromDoc) === 'renamed', 15000);+ expect(lifecycleStatus(rig, fromDoc)).toBe('renamed');+ expect(serverDoc(rig, fromDoc)?.getMap('lifecycle').get('newPath')).toBe(toDoc);++ await client.cleanup();+ },+ HARNESS_BOOT_TIMEOUT_MS + 30_000,+ );++ test(+ 'conflict markers written to a template file classify the open doc into the conflict lifecycle',+ async () => {+ const name = `tpl-${randomUUID().slice(0, 8)}`;+ const docName = `.ok/templates/${name}`;+ const contentDir = seedContentDir();+ const tplFile = resolve(contentDir, '.ok', 'templates', `${name}.md`);+ const clean = '---\ntitle: T\ndescription: initial\n---\n\n# Template\n\nv1.\n';+ mkdirSync(resolve(tplFile, '..'), { recursive: true });+ writeFileSync(tplFile, clean, 'utf-8');++ server = await createTestServer({ contentDir, debounce: 100, maxDebounce: 400 });+ const rig = server;++ // Open the doc so the watcher's conflict classification has a loaded target+ // (`handleDiskEvent` case 'conflict' returns early when the doc is not loaded).+ const client = await createTestClient(rig.port, docName, { skipInvariantWatcher: true });+ await pollUntil(() => client.ytext.toString() === clean, 8000);++ // A git merge left conflict markers in the file. The content watcher's+ // reconciliation classifies marker-laden disk content into the conflict+ // lifecycle rather than ingesting the marker bytes — the previously-dead+ // conflict gate now applies to templates.+ const conflicted =+ '---\ntitle: T\ndescription: initial\n---\n\n# Template\n\n<<<<<<< HEAD\nours.\n=======\ntheirs.\n>>>>>>> branch\n';+ writeFileSync(tplFile, conflicted, 'utf-8');++ await pollUntil(() => lifecycleStatus(rig, docName) === 'conflict', 15000);+ expect(lifecycleStatus(rig, docName)).toBe('conflict');+ expect(serverDoc(rig, docName)?.getMap('lifecycle').get('reason')).toBe('conflict-markers');+ // The marker bytes never enter the CRDT — the doc keeps its clean body.+ expect(client.ytext.toString()).not.toContain('<<<<<<<');++ await client.cleanup();+ },+ HARNESS_BOOT_TIMEOUT_MS + 30_000,+ );+});diff --git a/packages/app/tests/stress/show-ok-folders.e2e.ts b/packages/app/tests/stress/show-ok-folders.e2e.tsindex a4177a4dd..cb4189dd5 100644--- a/packages/app/tests/stress/show-ok-folders.e2e.ts+++ b/packages/app/tests/stress/show-ok-folders.e2e.ts@@ -105,7 +105,9 @@ test('toggle reveals .ok rows, routes clicks to sanctioned surfaces, and keeps rawait expect(page.getByText('MUTATION-ATTEMPT')).toHaveCount(0);await expect(page.getByText(`Raw probe ${stamp}`)).toBeVisible();- // A template file row routes to the managed-artifact template editor.+ // A template file row routes to its content doc (templates are content docs+ // now; the row navigates to the real `.ok/templates/` path, not the retired+ // `__template__/` synthetic name).await folderRow(page, 'templates').click();await fileRow(page, `${templateName}.md`).waitFor({ state: 'visible', timeout: 15_000 });await fileRow(page, `${templateName}.md`).click();@@ -113,7 +115,7 @@ test('toggle reveals .ok rows, routes clicks to sanctioned surfaces, and keeps r.poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {timeout: 15_000,})- .toBe(`#/__template__/${templateName}`);+ .toBe(`#/.ok/templates/${templateName}`);// Restore the worker-shared default from the same popover; the `.ok` rows// retire with the flip.@@ -260,3 +262,34 @@ test('an activated .ok folder row never becomes a mutation target — create falawait toggleShowOkFolders(page);await expect(folderRow(page, '.ok')).toHaveCount(0, { timeout: 15_000 });});++test('a legacy __template__ bookmark redirects to the content doc and opens it', async ({+ page,+ api,+ workerServer,+}) => {+ const stamp = uniqueStamp();+ const anchorDoc = `tmpl-legacy-anchor-${stamp}`;+ const templateName = `legacy-greeting-${stamp}`;+ const bodyMarker = `Legacy redirect ${stamp}`;++ await api.createPage(`${anchorDoc}.md`);+ mkdirSync(join(workerServer.contentDir, '.ok', 'templates'), { recursive: true });+ writeFileSync(+ join(workerServer.contentDir, '.ok', 'templates', `${templateName}.md`),+ `# ${bodyMarker}\n`,+ 'utf-8',+ );++ // Land on an ordinary doc first so the redirect has somewhere to move FROM.+ await page.goto(`/#/${anchorDoc}`);+ await fileRow(page, `${anchorDoc}.md`).waitFor({ state: 'visible', timeout: 15_000 });++ // A pre-migration bookmark of the retired synthetic name resolves at+ // navigation to the content doc, so the template still opens (its body+ // renders) rather than stranding on a phantom empty tab.+ await page.evaluate((name) => {+ window.location.hash = `#/__template__/${name}`;+ }, templateName);+ await expect(page.getByText(bodyMarker)).toBeVisible({ timeout: 15_000 });+});diff --git a/packages/core/src/constants/cc1.test.ts b/packages/core/src/constants/cc1.test.tsindex f74365609..57ba6bd10 100644--- a/packages/core/src/constants/cc1.test.ts+++ b/packages/core/src/constants/cc1.test.ts@@ -1,12 +1,15 @@import { describe, expect, test } from 'vitest';import {- managedArtifactDocNameFromContentTarget,+ isManagedArtifactDocName,parseGlobalSkillBundleDoc,+ parseLegacyTemplateDocName,parseManagedArtifactName,parseProjectSkillBundleDoc,+ parseTemplateContentDocName,resolveSkillBundleWikiTarget,skillFileLiveDocName,skillLiveDocName,+ templateContentDocName,} from './cc1.ts';describe('parseManagedArtifactName — skill name/rel split (per-file editability)', () => {@@ -67,37 +70,27 @@ describe('parseManagedArtifactName — skill name/rel split (per-file editabilit// (click-through + backlinks). Project skills are NOT mapped here — they are// real content docs (`.ok/skills/<name>/SKILL`) and resolve through the normal// page index. These cases pin that contract.-describe('managedArtifactDocNameFromContentTarget', () => {- test('does NOT rewrite project skill file paths — they are content docs', () => {- // Project skills are indexed content now, not synthetic `__skill__/project`- // docs, so a skill-file target falls through to normal page resolution.- expect(managedArtifactDocNameFromContentTarget('.ok/skills/my-skill/SKILL.md')).toBeNull();- expect(managedArtifactDocNameFromContentTarget('.ok/skills/my-skill/SKILL')).toBeNull();- expect(managedArtifactDocNameFromContentTarget('.ok/skills/my-skill/SKILL.mdx')).toBeNull();- expect(managedArtifactDocNameFromContentTarget('some/dir/.ok/skills/deep/SKILL.md')).toBeNull();- });-- test('maps a root-level template to a folderless template doc name', () => {- expect(managedArtifactDocNameFromContentTarget('.ok/templates/note.md')).toBe(- '__template__/note',- );+describe('parseManagedArtifactName — __template__ tombstone', () => {+ test('returns null for a synthetic template name (no live artifact resolves)', () => {+ // The template parse arm is gone: a stale `__template__/…` name must NOT+ // resolve to an artifact, so it can never reach the content branch and mint+ // a literal `__template__/…` file. Templates are content docs.+ expect(parseManagedArtifactName('__template__/note')).toBeNull();+ expect(parseManagedArtifactName('__template__/docs/note')).toBeNull();+ expect(parseManagedArtifactName('__template__/docs/guides/note')).toBeNull();});- test('maps a template under a folder, preserving the folder segment', () => {- expect(managedArtifactDocNameFromContentTarget('docs/.ok/templates/note.md')).toBe(- '__template__/docs/note',- );- expect(managedArtifactDocNameFromContentTarget('docs/guides/.ok/templates/note')).toBe(- '__template__/docs/guides/note',- );+ test('but the prefix still classifies as a managed-artifact name (tombstone)', () => {+ // The reserved-name gates (tree exclusion, create-page refusal, persistence+ // quarantine, the navigation redirect) all key off this classifier, so the+ // prefix survives even though the parser refuses it.+ expect(isManagedArtifactDocName('__template__/note')).toBe(true);+ expect(isManagedArtifactDocName('__template__/docs/note')).toBe(true);});- test('returns null for paths that are not skill/template files', () => {- expect(managedArtifactDocNameFromContentTarget('docs/getting-started.md')).toBeNull();- expect(managedArtifactDocNameFromContentTarget('.ok/skills/my-skill/NOTES.md')).toBeNull();- expect(managedArtifactDocNameFromContentTarget('.ok/config.yml')).toBeNull();- expect(managedArtifactDocNameFromContentTarget('readme')).toBeNull();- expect(managedArtifactDocNameFromContentTarget('')).toBeNull();+ test('a template content name is NOT a managed-artifact name', () => {+ expect(parseManagedArtifactName('docs/.ok/templates/note')).toBeNull();+ expect(isManagedArtifactDocName('docs/.ok/templates/note')).toBe(false);});});@@ -281,3 +274,139 @@ describe('parseGlobalSkillBundleDoc', () => {expect(parseGlobalSkillBundleDoc('notes/index')).toBeNull();});});++// A template's live doc name is its content-relative path. This builder + shape+// parser + legacy parser are the single identity every surface shares; these+// cases pin the raw (unencoded) content shape, the single-leaf-only rule, and+// the percent-decoding the legacy synthetic-name reader must preserve.+describe('templateContentDocName', () => {+ test('builds a root template content doc name (ext-less, raw)', () => {+ expect(templateContentDocName('', 'daily')).toBe('.ok/templates/daily');+ });++ test('builds a single-level folder template content doc name', () => {+ expect(templateContentDocName('docs', 'daily')).toBe('docs/.ok/templates/daily');+ });++ test('builds a nested-folder template content doc name', () => {+ expect(templateContentDocName('a/b', 'daily')).toBe('a/b/.ok/templates/daily');+ });++ test('normalizes leading/trailing slashes on the folder', () => {+ expect(templateContentDocName('/docs/', 'daily')).toBe('docs/.ok/templates/daily');+ });++ test('keeps a spaced folder RAW — no percent-encoding', () => {+ expect(templateContentDocName('My Notes', 'daily')).toBe('My Notes/.ok/templates/daily');+ });+});++describe('parseTemplateContentDocName', () => {+ test('parses a root template leaf', () => {+ expect(parseTemplateContentDocName('.ok/templates/daily')).toEqual({+ folder: '',+ name: 'daily',+ });+ });++ test('parses a template leaf under a folder, preserving the folder segment', () => {+ expect(parseTemplateContentDocName('docs/.ok/templates/daily')).toEqual({+ folder: 'docs',+ name: 'daily',+ });+ expect(parseTemplateContentDocName('a/b/.ok/templates/daily')).toEqual({+ folder: 'a/b',+ name: 'daily',+ });+ });++ test('returns null for a subdirectory under .ok/templates — templates are single leaves', () => {+ expect(parseTemplateContentDocName('.ok/templates/sub/daily')).toBeNull();+ expect(parseTemplateContentDocName('docs/.ok/templates/sub/daily')).toBeNull();+ });++ test('returns null for a non-template .ok path', () => {+ expect(parseTemplateContentDocName('.ok/skills/demo/SKILL')).toBeNull();+ expect(parseTemplateContentDocName('.ok/config.yml')).toBeNull();+ });++ test('returns null for an ordinary content doc name', () => {+ expect(parseTemplateContentDocName('docs/getting-started')).toBeNull();+ expect(parseTemplateContentDocName('readme')).toBeNull();+ expect(parseTemplateContentDocName('')).toBeNull();+ });++ test('strips a `.md` suffix but no other extension — a template IS a `.md` leaf', () => {+ // Mirrors `isTemplateContentFile`, which admits only `.md` under+ // `.ok/templates/`: the two halves of the grammar must agree about what a+ // template is. A `.mdx` (or any other) suffix is not the template file+ // extension, so it stays part of the leaf like any odd character would.+ expect(parseTemplateContentDocName('.ok/templates/daily.md')).toEqual({+ folder: '',+ name: 'daily',+ });+ expect(parseTemplateContentDocName('docs/.ok/templates/daily.mdx')).toEqual({+ folder: 'docs',+ name: 'daily.mdx',+ });+ });++ test('parses by SHAPE only — a name that would fail the template-name grammar still parses', () => {+ // Name validation lives at the HTTP write layer, not in the doc-name grammar,+ // so the shape parser must not reject on the leaf's characters.+ expect(parseTemplateContentDocName('.ok/templates/Has Spaces')).toEqual({+ folder: '',+ name: 'Has Spaces',+ });+ expect(parseTemplateContentDocName('docs/.ok/templates/UPPER_case!')).toEqual({+ folder: 'docs',+ name: 'UPPER_case!',+ });+ });+});++describe('parseLegacyTemplateDocName', () => {+ test('parses a stale synthetic root template name', () => {+ expect(parseLegacyTemplateDocName('__template__/daily')).toEqual({ folder: '', name: 'daily' });+ });++ test('parses a stale synthetic name under a folder (flat and nested)', () => {+ expect(parseLegacyTemplateDocName('__template__/docs/daily')).toEqual({+ folder: 'docs',+ name: 'daily',+ });+ expect(parseLegacyTemplateDocName('__template__/a/b/daily')).toEqual({+ folder: 'a/b',+ name: 'daily',+ });+ });++ test('percent-DECODES each segment so an encoded stale name maps to the raw folder/name', () => {+ expect(parseLegacyTemplateDocName('__template__/My%20Notes/daily')).toEqual({+ folder: 'My Notes',+ name: 'daily',+ });+ });++ test('returns null for a content-shaped name and other non-synthetic names', () => {+ expect(parseLegacyTemplateDocName('docs/.ok/templates/daily')).toBeNull();+ expect(parseLegacyTemplateDocName('docs/getting-started')).toBeNull();+ expect(parseLegacyTemplateDocName('__skill__/global/demo')).toBeNull();+ expect(parseLegacyTemplateDocName('__template__/')).toBeNull();+ expect(parseLegacyTemplateDocName('')).toBeNull();+ });+});++describe('template content name round-trips (build → parse)', () => {+ test.each([+ { label: 'root', folder: '', name: 'daily' },+ { label: 'single-level folder', folder: 'docs', name: 'daily' },+ { label: 'nested folder', folder: 'a/b', name: 'daily' },+ { label: 'spaced folder', folder: 'My Notes', name: 'daily' },+ ])('round-trips a $label', ({ folder, name }) => {+ expect(parseTemplateContentDocName(templateContentDocName(folder, name))).toEqual({+ folder,+ name,+ });+ });+});diff --git a/packages/core/src/constants/cc1.ts b/packages/core/src/constants/cc1.tsindex b51ab9d97..405e0b699 100644--- a/packages/core/src/constants/cc1.ts+++ b/packages/core/src/constants/cc1.ts@@ -51,19 +51,27 @@ export const CONFIG_DOC_NAMES = Object.freeze([export type ConfigDocName = (typeof CONFIG_DOC_NAMES)[number];/**- * Managed-artifact (skill / template) synthetic doc-name namespaces.+ * Managed-artifact synthetic doc-name namespaces.** Unlike config docs (a bounded frozen set), managed-artifact names are OPEN —- * one synthetic doc per skill/template — so membership is PREFIX-based, not- * set-membership. The grammar is identical to the client URL fragment in+ * one synthetic doc per skill — so membership is PREFIX-based, not set-+ * membership. The grammar is identical to the client URL fragment in* `app/src/lib/doc-hash.ts` (`__skill__/<scope>/<name>`) so a deep link and the* server doc name are the same string.*- * Managed-artifact docs are a THIRD doc class distinct from system/config docs:- * they are excluded from the document tree / search / create-page (like- * system+config docs) BUT the observer bridge runs for them (unlike config docs,- * which are Y.Text-only) so they get full WYSIWYG+source editing. See- * `server/src/managed-artifact-persistence.ts`.+ * Live managed-artifact docs (global + external skills) are a THIRD doc class+ * distinct from system/config docs: they are excluded from the document tree /+ * search / create-page (like system+config docs) BUT the observer bridge runs+ * for them (unlike config docs, which are Y.Text-only) so they get full+ * WYSIWYG+source editing. See `server/src/managed-artifact-persistence.ts`.+ *+ * `MANAGED_ARTIFACT_PREFIX_TEMPLATE` is a reserved-name TOMBSTONE, not a live+ * namespace: templates are ordinary content docs at `<folder>/.ok/templates/+ * <name>` now. The prefix is still matched by the classifiers below so a stale+ * `__template__/…` name keeps the reserved-name gates (tree exclusion, create-+ * page refusal, persistence quarantine), but `parseManagedArtifactName`+ * deliberately does NOT resolve it — `parseLegacyTemplateDocName` decodes it+ * only for the navigation redirect to the content doc.*/export const MANAGED_ARTIFACT_PREFIX_SKILL = '__skill__/';export const MANAGED_ARTIFACT_PREFIX_TEMPLATE = '__template__/';@@ -91,10 +99,15 @@ export const MANAGED_ARTIFACT_PREFIX_EXTSKILL = '__extskill__/';export const MANAGED_ARTIFACT_SCOPES = ['project', 'global'] as const;export type ManagedArtifactScope = (typeof MANAGED_ARTIFACT_SCOPES)[number];-/** True when `name` is a skill, template, or editable-unmanaged-skill synthetic- * doc name. All three are managed-artifact-CLASS docs: editable content docs- * hidden from the Files tree, with custom persistence (the observer bridge runs- * so WYSIWYG works). Only `__extskill__/` writes OUTSIDE the project boundary. */+/** True when `name` is a skill, editable-unmanaged-skill, or stale template+ * synthetic doc name. Skills (`__skill__/`, `__extskill__/`) are live managed-+ * artifact-CLASS docs: editable content docs hidden from the Files tree, with+ * custom persistence (the observer bridge runs so WYSIWYG works). Only+ * `__extskill__/` writes OUTSIDE the project boundary. `__template__/` is a+ * reserved-name TOMBSTONE — still matched here so the reserved-name gates hold+ * (tree exclusion, create-page refusal, persistence quarantine), but it no+ * longer resolves (`parseManagedArtifactName` returns null); templates are+ * ordinary content docs. */export function isManagedArtifactDocName(name: string): boolean {return (name.startsWith(MANAGED_ARTIFACT_PREFIX_SKILL) ||@@ -387,18 +400,23 @@ export function skillFileLiveDocName(}/**- * Parsed managed-artifact doc name. The two kinds are addressed DIFFERENTLY:- * - skill: `__skill__/<scope>/<name>` — `scope` ∈ {global, project}; the- * skill folder lives under `<scope-root>/.ok/skills/<name>/`.- * - template: `__template__/<folderRel>/<name>` — `folder` is the- * project-root-relative folder owning the template (`''` = project root,- * may be nested like `notes/sub`); the template lives at- * `<folder>/.ok/templates/<name>.md`. Templates have NO global/project- * scope — they are folder-local with leaf→root inheritance.+ * Parsed managed-artifact doc name. Only skills carry a synthetic managed name:+ * `__skill__/<scope>/<name>` — `scope` ∈ {global, project}; the skill folder+ * lives under `<scope-root>/.ok/skills/<name>/`. `rel` is a bundle-relative file+ * path into the skill dir, or `null` for the bare SKILL.md doc.+ *+ * Templates are ordinary content docs addressed by their content-relative path+ * (`parseTemplateContentDocName`); a stale `__template__/…` name is a reserved+ * tombstone this parser deliberately does NOT resolve, so it can never reach the+ * content branch. `parseLegacyTemplateDocName` decodes such a name for the+ * navigation redirect that forwards an old deep link to its content doc.*/-export type ParsedManagedArtifactName =- | { kind: 'skill'; scope: ManagedArtifactScope; name: string; rel: string | null }- | { kind: 'template'; folder: string; name: string };+export type ParsedManagedArtifactName = {+ kind: 'skill';+ scope: ManagedArtifactScope;+ name: string;+ rel: string | null;+};/** Percent-decode each `/`-separated segment; returns `''` unchanged. */function decodeManagedSegments(encoded: string): string {@@ -414,10 +432,15 @@ function decodeManagedSegments(encoded: string): string {}/**- * Parse `__skill__/<scope>/<name>` or `__template__/<folderRel>/<name>`. Returns- * null when the prefix is unknown, the skill scope is invalid, or the name is- * empty. The client decodes the same names via `docNameFromHash`+ * Parse `__skill__/<scope>/<name>`. Returns null when the prefix is not a skill+ * name (including a `__template__/…` tombstone), the skill scope is invalid, or+ * the name is empty. The client decodes the same names via `docNameFromHash`* (`app/src/lib/doc-hash.ts`) then this parser. Segments are percent-decoded.+ *+ * `__template__/…` intentionally returns null: templates are content docs, so a+ * stale synthetic name must NOT resolve to a live artifact here — that is what+ * keeps it a tombstone. The navigation redirect reads it via+ * `parseLegacyTemplateDocName` instead.*/export function parseManagedArtifactName(name: string): ParsedManagedArtifactName | null {if (name.startsWith(MANAGED_ARTIFACT_PREFIX_SKILL)) {@@ -438,46 +461,80 @@ export function parseManagedArtifactName(name: string): ParsedManagedArtifactNamconst rel = nameEnd < 0 ? null : decoded.slice(nameEnd + 1);return { kind: 'skill', scope, name: skillName, rel };}- if (name.startsWith(MANAGED_ARTIFACT_PREFIX_TEMPLATE)) {- // Folder-addressed: split on the LAST slash — everything before is the- // (possibly empty, possibly nested) folder, the last segment is the name.- const rest = name.slice(MANAGED_ARTIFACT_PREFIX_TEMPLATE.length);- if (!rest) return null;- const lastSlash = rest.lastIndexOf('/');- const encodedName = lastSlash < 0 ? rest : rest.slice(lastSlash + 1);- if (!encodedName) return null;- const encodedFolder = lastSlash < 0 ? '' : rest.slice(0, lastSlash);- return {- kind: 'template',- folder: decodeManagedSegments(encodedFolder),- name: decodeManagedSegments(encodedName),- };- }return null;}// A content link target / doc name that points at a template's file on disk// (`<folder>/.ok/templates/<name>[.md]`); folder = everything before-// `.ok/templates/` (empty at the project root).-const TEMPLATE_FILE_TARGET_RE = /^(?:(.+)\/)?\.ok\/templates\/([^/]+?)(?:\.mdx?)?$/;+// `.ok/templates/` (empty at the project root). Consumed by the content-name+// shape parser below. `.md` only — a template IS a `.md` leaf (the content+// filter admits nothing else under `.ok/templates/`), so a `.mdx`-suffixed+// target is not a template reference and must fall through.+const TEMPLATE_FILE_TARGET_RE = /^(?:(.+)\/)?\.ok\/templates\/([^/]+?)(?:\.md)?$/;++/**+ * A template's identity — its owning folder (project-root-relative, `''` at the+ * project root, may be nested like `notes/sub`) and bare name. The content-name+ * shape parser and the legacy synthetic-name parser both resolve to this.+ */+export type ParsedTemplateName = { folder: string; name: string };/**- * Map a content link target / doc name that points at a template FILE on disk to- * its managed-artifact doc name (`__template__/<folderRel>/<name>`). Returns null- * when the target isn't a template file path. Shared by the client link resolver- * and the server link index, so a doc→template link resolves to the same artifact- * identity in both places (click-through + backlinks).+ * The CONTENT doc name for a folder-local template+ * (`<folderRel>/.ok/templates/<name>`, ext-less). `folderRel` is the+ * project-root-relative owning folder (`''` at the project root, may be nested+ * like `notes/sub`); `name` is the bare template name (the on-disk file is+ * `<name>.md`, but content docs are addressed ext-less).*- * Project skills are NOT rewritten here — they are real content docs- * (`.ok/skills/<name>/SKILL`) and resolve through the normal page index. Global- * skills live under `<home>/.ok/skills`, outside contentDir, unreachable from a- * content link.+ * Names are RAW — no percent-encoding. A folder containing spaces round-trips+ * the generic doc-name hash layer like any other spaced content doc, so the+ * percent-encoding the synthetic `__template__/…` namespace used is unnecessary+ * here.*/-export function managedArtifactDocNameFromContentTarget(target: string): string | null {- const template = TEMPLATE_FILE_TARGET_RE.exec(target);- if (template) {- const folder = (template[1] ?? '').replace(/^\/+|\/+$/g, '');- return `${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${folder ? `${folder}/` : ''}${template[2]}`;- }- return null;+export function templateContentDocName(folderRel: string, name: string): string {+ const folder = folderRel.replace(/^\/+|\/+$/g, '');+ return folder ? `${folder}/.ok/templates/${name}` : `.ok/templates/${name}`;+}++/**+ * Parse a CONTENT doc name that addresses a template leaf+ * (`<folder>/.ok/templates/<name>`) into its owning folder + bare name, or null+ * when the name is not a single-leaf template path. A path with a subdirectory+ * under `.ok/templates/` (e.g. `<folder>/.ok/templates/sub/x`) returns null —+ * templates are single leaves, never nested. The inverse of+ * {@link templateContentDocName}.+ *+ * Shape-only: the leaf is NOT checked against the template-name grammar, so a+ * name that would fail validation still parses. Name validation lives at the+ * HTTP write layer, not in the doc-name grammar.+ */+export function parseTemplateContentDocName(docName: string): ParsedTemplateName | null {+ const match = TEMPLATE_FILE_TARGET_RE.exec(docName);+ if (!match) return null;+ return { folder: (match[1] ?? '').replace(/^\/+|\/+$/g, ''), name: match[2] as string };+}++/**+ * Parse a stale SYNTHETIC template doc name (`__template__/<folderRel>/<name>`)+ * into its folder + name, percent-DECODING each segment, or null when the name+ * is not a synthetic template name (e.g. an ordinary content doc name).+ *+ * The synthetic namespace percent-encoded its segments, so decoding is required+ * to recover the RAW folder/name a content doc uses — a raw-only reader would+ * forward an encoded stale name to a literally-encoded content doc. For the+ * navigation redirect that forwards an old `__template__/…` deep link to its+ * content doc; new code addresses templates by their content name.+ */+export function parseLegacyTemplateDocName(name: string): ParsedTemplateName | null {+ if (!name.startsWith(MANAGED_ARTIFACT_PREFIX_TEMPLATE)) return null;+ const rest = name.slice(MANAGED_ARTIFACT_PREFIX_TEMPLATE.length);+ if (!rest) return null;+ const lastSlash = rest.lastIndexOf('/');+ const encodedName = lastSlash < 0 ? rest : rest.slice(lastSlash + 1);+ if (!encodedName) return null;+ const encodedFolder = lastSlash < 0 ? '' : rest.slice(0, lastSlash);+ return {+ folder: decodeManagedSegments(encodedFolder),+ name: decodeManagedSegments(encodedName),+ };}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 603788a81..6b779f3fa 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -262,14 +262,16 @@ export {MANAGED_ARTIFACT_PREFIX_TEMPLATE,MANAGED_ARTIFACT_SCOPES,type ManagedArtifactScope,- managedArtifactDocNameFromContentTarget,type ParsedGlobalSkillBundleDoc,type ParsedManagedArtifactName,type ParsedProjectSkillBundleDoc,+ type ParsedTemplateName,parseExternalSkillDocName,parseGlobalSkillBundleDoc,+ parseLegacyTemplateDocName,parseManagedArtifactName,parseProjectSkillBundleDoc,+ parseTemplateContentDocName,projectSkillContentDocName,resolveSkillBundleWikiTarget,resolveSkillSlashTarget,@@ -277,6 +279,7 @@ export {skillFileLiveDocName,skillLiveDocName,stripMdExt,+ templateContentDocName,} from './constants/cc1.ts';export { CHROME_BG_DARK, CHROME_BG_LIGHT } from './constants/chrome.ts';export {diff --git a/packages/core/src/util/doc-name.test.ts b/packages/core/src/util/doc-name.test.tsindex 6d6c72bb4..e54e53f51 100644--- a/packages/core/src/util/doc-name.test.ts+++ b/packages/core/src/util/doc-name.test.ts@@ -18,6 +18,14 @@ describe('isHiddenDocName', () => {// at the root and nested.'opencode.json','config/opencode.json',+ // Folder templates live under `.ok` with NO skill-style bundle carve-out, so+ // `isHiddenDocName` treats them like any hidden dot-path: a search rank+ // penalty plus exclusion from embeddings and egress, even though they are+ // content docs on disk. (It is deliberately NOT applied to listings /+ // backlinks / `[[` autocomplete, so templates still surface there.) Contrast+ // the skill-bundle carve-out in the visible list below.+ '.ok/templates/daily-standup',+ 'notes/.ok/templates/meeting',])test(`hidden: ${JSON.stringify(name)}`, () => expect(isHiddenDocName(name)).toBe(true));for (const name of [diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 9f671f424..be14e04d8 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -134,7 +134,6 @@ import {LocalOpOkInitResponseSchema,lintDocument,MANAGED_ARTIFACT_PREFIX_SKILL,- MANAGED_ARTIFACT_PREFIX_TEMPLATE,MarkdownlintRuleWriteRequestSchema,mediaKindForSidebarAssetExtension,OK_DIR,@@ -228,6 +227,7 @@ import {scanHeadingLine,skillLiveDocName,stripFrontmatter,+ TEMPLATE_NAME_REGEX,TemplateDeleteSuccessSchema,TemplateGetSuccessSchema,TemplateImportRequestSchema,@@ -243,6 +243,7 @@ import {TestResetSuccessSchema,TrashCleanupRequestSchema,TrashCleanupSuccessSchema,+ templateContentDocName,UploadAssetSuccessSchema,UploadRequestSchema,unwrapFrontmatterFences,@@ -3384,13 +3385,13 @@ export function createApiExtension(admitted.add(alias);}}- // Managed-artifact docs (skills/templates) are link-axis participants — a- // doc that links to one must resolve it as a known doc (title, not a dead- // link rendered as the raw `__skill__/...` name). They live outside- // getFileIndex() (tree-excluded), so enumerate them from disk here. The- // names match what the backlink index normalizes link targets to via- // `managedArtifactDocNameFromContentTarget`. Best-effort: a scan failure- // just narrows the set, it never fails the link endpoint.+ // Managed skill docs are link-axis participants — a doc that links to one+ // must resolve it as a known doc (title, not a dead link rendered as the raw+ // `__skill__/...` name). They live outside getFileIndex() (tree-excluded), so+ // enumerate them from disk here. The names match what the backlink index+ // normalizes link targets to. Templates need no enumeration: they are content+ // docs now, so getFileIndex() already carries them. Best-effort: a scan+ // failure just narrows the set, it never fails the link endpoint.try {for (const scope of ['project', 'global'] as const) {const skillsRoot =@@ -3401,9 +3402,6 @@ export function createApiExtension(admitted.add(`${MANAGED_ARTIFACT_PREFIX_SKILL}${scope}/${skill.name}`);}}- for (const tpl of (await resolveProjectTemplates(resolve(contentDir))).templates) {- admitted.add(templateDocNameFor(tpl.source_folder, tpl.name));- }} catch (err) {log.warn({ err }, '[collectAdmittedDocNames] managed-artifact enumeration failed');}@@ -12311,9 +12309,8 @@ export function createApiExtension(return { folderRel, resolvedContentDir };}- const TEMPLATE_NAME_RE = /^[A-Za-z0-9_-]+$/;function validateTemplateName(name: string, res: ServerResponse, handler = 'template'): boolean {- if (!name || !TEMPLATE_NAME_RE.test(name)) {+ if (!name || !TEMPLATE_NAME_REGEX.test(name)) {errorResponse(res,400,@@ -12526,27 +12523,21 @@ export function createApiExtension();/**- * Conflict-aware refusal helper for the template handlers. Templates- * write to `<folder>/.ok/templates/<name>.md`, under `.ok/`, which the- * watcher excludes from the CRDT document index — so the target path- * cannot carry a `lifecycle.status` Y.Map in production. The check is- * kept structural so (a) any future loosening that loads- * `.ok/templates/*` into Y.Docs inherits the refusal contract for free,- * (b) the meta-test sees an explicit `respondDocInConflict` site at- * the handler boundary. Returns `true` when the gate fired (caller- * short-circuits); `false` when the mutation may proceed.+ * Conflict-aware refusal helper for the template handlers. A template is a+ * content doc now (`<folder>/.ok/templates/<name>`), so its live Y.Doc carries+ * a `lifecycle.status` Y.Map — a mutation against one mid-conflict must refuse+ * exactly like the sibling content-write handlers, whose paired-write path+ * (`composeAndWriteRawBody`) would otherwise clobber a doc the user is+ * mid-resolving. Takes the pre-resolved content doc name — same shape as the+ * sibling `checkSkillDocConflictGate`, so the two gates read as one pattern.+ * Returns `true` when the gate fired (caller short-circuits); `false` when+ * the mutation may proceed.*/function checkTemplateConflictGate(- folder: string,- name: string,+ templateDocName: string,handler: 'template-put' | 'template-delete' | 'template-move' | 'template-import',res: ServerResponse,): boolean {- if (!name) return false;- const templateDocName =- folder === ''- ? `.ok/templates/${name}`- : `${folder.replace(/\/$/, '')}/.ok/templates/${name}`;const doc = hocuspocus.documents.get(templateDocName);if (doc && isDocInConflict(doc)) {respondDocInConflict(res, new DocInConflictError({ file: `${templateDocName}.md` }), handler);@@ -12728,11 +12719,19 @@ export function createApiExtension(if (!validated) return;// Conflict-aware refusal. See `checkTemplateConflictGate`.- if (checkTemplateConflictGate(validated.folderRel, name, 'template-put', res)) return;+ if (+ checkTemplateConflictGate(+ templateDocNameFor(validated.folderRel, name),+ 'template-put',+ res,+ )+ )+ return;// Compose + validate the `.md` bytes server-side, then route the body// through the template's CRDT doc (precedent #24 / #38) — same shape as- // skill-put. The managed-artifact persistence branch writes the file.+ // skill-put. Templates are content docs, so the ordinary content+ // persistence path (not the managed-artifact branch) writes the file.const composed = composeTemplateContent({name,body: typeof body.body === 'string' ? body.body : '',@@ -12783,6 +12782,12 @@ export function createApiExtension(return;}+ // Close the dropped-FSEvent gap at the source (see helper): the flush+ // may have just created this folder's `.ok/templates/` dir — exactly+ // the brand-new-subdir race where the watcher's create event can be+ // lost. Same net as the sibling agent-write handlers.+ registerWrittenDocInFileIndex(templateDocName, composed.content);+attributeOkArtifactWrite(actor,okArtifactKey('template', validated.folderRel, name),@@ -12836,12 +12841,19 @@ export function createApiExtension(}// Conflict-aware refusal. See `checkTemplateConflictGate`.- if (checkTemplateConflictGate(validated.folderRel, name, 'template-delete', res)) return;+ if (+ checkTemplateConflictGate(+ templateDocNameFor(validated.folderRel, name),+ 'template-delete',+ res,+ )+ )+ return;- // Tear down the live `__template__` doc (if open) BEFORE removing the- // file, so the managed-artifact persistence branch can't re-store- // (resurrect) it on a later unload. Same spine doc-delete + skill-delete- // use; no-op when the doc was never opened.+ // Tear down the live template content doc (if open) BEFORE removing the+ // file, so its debounced content store can't re-store (resurrect) it on+ // a later unload. Same spine doc-delete + skill-delete use; no-op when+ // the doc was never opened.await captureAndCloseDocuments([templateDocNameFor(validated.folderRel, name)],'deleted-upstream',@@ -12879,6 +12891,9 @@ export function createApiExtension(`template-delete: ${result.path}`,);await commitOkArtifactWrite('template-delete');+ // Mark the content doc removed so a stale tab redirects instead of+ // offering to resurrect it (parity with ordinary doc deletion).+ recentlyRemovedDocs?.setDeleted(templateDocNameFor(validated.folderRel, name));}successResponse(res,@@ -12923,14 +12938,19 @@ export function createApiExtension(// Refuse moving a source whose target doc is in an unresolved conflict.if (- checkTemplateConflictGate(fromValidated.folderRel, body.fromName, 'template-move', res)+ checkTemplateConflictGate(+ templateDocNameFor(fromValidated.folderRel, body.fromName),+ 'template-move',+ res,+ )) {return;}- // Tear down the live source `__template__` doc (if open) BEFORE the- // git-mv relocates the file — otherwise its persistence branch would- // re-store at the now-stale from-path, resurrecting the moved template.+ // Tear down the live source template content doc (if open) BEFORE the+ // git-mv relocates the file — otherwise its debounced content store+ // would re-store at the now-stale from-path, resurrecting the moved+ // template.await captureAndCloseDocuments([templateDocNameFor(fromValidated.folderRel, body.fromName)],'renamed',@@ -13000,6 +13020,11 @@ export function createApiExtension(return;}+ // Mark the source content doc removed (the move relocated its file) so a+ // stale tab on the old name redirects instead of offering to resurrect+ // it (parity with ordinary doc deletion).+ recentlyRemovedDocs?.setDeleted(templateDocNameFor(fromValidated.folderRel, body.fromName));+// Optional atomic move+edit: rewrite the relocated template's content.// The move already succeeded and persisted the original content, so any// failure here is captured and reported AFTER the move is attributed —@@ -13040,6 +13065,22 @@ export function createApiExtension(}}+ // Close the dropped-FSEvent gap for the DESTINATION (parity with+ // put/import): the relocate may have just created `toFolder`'s+ // `.ok/templates/` dir — the brand-new-subdir race where the watcher's+ // create event can be lost. Read the final on-disk bytes (post the+ // optional edit above) so the index entry matches what landed.+ // Best-effort like the helper itself: on a read failure the CRDT/disk+ // copy exists regardless and a rescan re-seeds the index.+ try {+ registerWrittenDocInFileIndex(+ templateDocNameFor(toValidated.folderRel, body.toName),+ readFileSync(resolve(toValidated.resolvedContentDir, result.toPath), 'utf-8'),+ );+ } catch {+ // Unreadable destination — leave index membership to the watcher.+ }+// The move succeeded — attribute + commit + signal regardless of the// optional content edit's outcome, so the rename is never lost when the// edit step fails.@@ -13216,7 +13257,14 @@ export function createApiExtension(const validated = validateFolderRel(body.targetFolder, res, 'folder', 'template-import');if (!validated) return;- if (checkTemplateConflictGate(validated.folderRel, name, 'template-import', res)) return;+ if (+ checkTemplateConflictGate(+ templateDocNameFor(validated.folderRel, name),+ 'template-import',+ res,+ )+ )+ return;// Parse existing frontmatter of the source file to extract the title/description/tagsconst { frontmatter: sourceFmText, body: sourceBody } = stripFrontmatter(sourceContent);@@ -13303,6 +13351,12 @@ export function createApiExtension(return;}+ // Close the dropped-FSEvent gap at the source (see helper): the flush+ // may have just created the target folder's `.ok/templates/` dir —+ // exactly the brand-new-subdir race where the watcher's create event+ // can be lost. Same net as the sibling agent-write handlers.+ registerWrittenDocInFileIndex(templateDocName, composed.content);+attributeOkArtifactWrite(actor,okArtifactKey('template', validated.folderRel, name),@@ -13830,14 +13884,13 @@ export function createApiExtension(}/**- * Build the folder-addressed `__template__/<folderRel>/<name>` CRDT doc name.- * Each path segment is percent-encoded so `parseManagedArtifactName` decodes- * back to the exact folder/name (folders may carry spaces/unicode). `''`- * folder → `__template__/<name>` (project root).+ * The CRDT doc name a template opens/persists under — its content-relative path+ * (`<folderRel>/.ok/templates/<name>`, ext-less, RAW). Delegates to the core+ * builder so server handlers, the client open path, and the properties panel+ * share one identity. `''` folder → `.ok/templates/<name>` (project root).*/function templateDocNameFor(folderRel: string, name: string): string {- const segs = folderRel ? folderRel.split('/').filter(Boolean).map(encodeURIComponent) : [];- return `${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...segs, encodeURIComponent(name)].join('/')}`;+ return templateContentDocName(folderRel, name);}function parseSearchRanking(value: unknown): WorkspaceSearchRanking | undefined {diff --git a/packages/server/src/api-search.test.ts b/packages/server/src/api-search.test.tsindex ab73efaa8..bf1d87ba7 100644--- a/packages/server/src/api-search.test.ts+++ b/packages/server/src/api-search.test.ts@@ -806,8 +806,11 @@ describe('GET /api/search — operational budget (D15)', () => {// from the search corpus by `isHiddenDocName`. The predicate split admits them to// SEARCH (rank-deprioritized in core) while keeping them out of the embedding /// egress path. System + config synthetic docs (`__config__/project`) stay out of-// both. `.ok/` never reaches the index at all (ContentFilter excludes it upstream-// of this harness, so it is not exercised here).+// both. `.ok/` content the ContentFilter admits (skills index with skill-aware+// docs; templates index as ordinary content docs, rank-deprioritized by+// `isHiddenDocName` like the other hidden dot-paths above) is covered in+// dedicated suites; this dot-path harness seeds none of it, so it is not+// exercised here.describe('GET /api/search — dot-path searchability', () => {test('a tracked dot-path markdown is searchable (AC3)', async () => {diff --git a/packages/server/src/backlink-index.test.ts b/packages/server/src/backlink-index.test.tsindex 52813c1b0..e2c890948 100644--- a/packages/server/src/backlink-index.test.ts+++ b/packages/server/src/backlink-index.test.ts@@ -251,7 +251,7 @@ describe('BacklinkIndex', () => {}});- test('normalizes skill file links to the content doc and template links to the artifact', () => {+ test('skill and template file links resolve to their content docs, not synthetic names', () => {const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-artifact-'));const contentDir = join(projectDir, 'content');mkdirSync(contentDir, { recursive: true });@@ -262,17 +262,17 @@ describe('BacklinkIndex', () => {'work-log','Touched [the skill](.ok/skills/my-skill/SKILL.md) and [the tpl](notes/.ok/templates/daily.md).\n',);- // Project skills are content docs: a link to `.ok/skills/<name>/SKILL.md`- // resolves to the content doc, NOT the dead `__skill__/project/<name>`.- // Templates are still managed artifacts.+ // Both are content docs now: a link resolves to the content doc name, NOT a+ // dead `__skill__/project/<name>` or `__template__/<folder>/<name>`.expect(index.getBacklinks('.ok/skills/my-skill/SKILL')).toEqual([expect.objectContaining({ source: 'work-log' }),]);- expect(index.getBacklinks('__template__/notes/daily')).toEqual([+ expect(index.getBacklinks('notes/.ok/templates/daily')).toEqual([expect.objectContaining({ source: 'work-log' }),]);- // The phantom managed-artifact path is NOT a target for a project skill.+ // The phantom synthetic paths are NOT targets.expect(index.getBacklinks('__skill__/project/my-skill')).toEqual([]);+ expect(index.getBacklinks('__template__/notes/daily')).toEqual([]);} finally {rmSync(projectDir, { recursive: true, force: true });}@@ -589,18 +589,19 @@ describe('BacklinkIndex', () => {}});- test('a pre-position backlinks cache loads and serves entries without positions', async () => {+ test('a current-version cache with corrupt positions degrades them to "position unknown"', async () => {const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-dead-link-legacy-'));const contentDir = join(projectDir, 'content');mkdirSync(contentDir, { recursive: true });try {- // The exact on-disk shape older servers wrote: backward entries carry only- // {source, anchor, snippet}.+ // A hand-edited or corrupt cache at the CURRENT version: backward entries+ // may omit positions or carry garbage ones.const cacheDir = join(projectDir, '.ok', LOCAL_DIR, 'cache', 'main');mkdirSync(cacheDir, { recursive: true });writeFileSync(join(cacheDir, 'backlinks.json'),JSON.stringify({+ version: 1,backward: {ghost: [{ source: 'alpha', anchor: null, snippet: 'See ghost.' }],// Invalid positions (hand-edited or corrupt cache) must degrade to@@ -647,6 +648,58 @@ describe('BacklinkIndex', () => {}});+ test('a versionless pre-upgrade cache is rejected so boot cold-rebuilds instead of serving stale keys', async () => {+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-version-guard-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(contentDir, { recursive: true });+ try {+ // The exact hazard SNAPSHOT_VERSION exists for: a cache written before+ // the version field existed, keying a doc→template edge under the+ // retired `__template__/…` namespace. Served as-is, that key satisfies+ // neither the admitted set nor `state.forward`, so it would surface as a+ // false dead link while the real template doc reads as a false orphan —+ // and the mtime reconcile never heals it while the source is untouched.+ const templateDoc = 'notes/.ok/templates/daily';+ mkdirSync(join(contentDir, 'notes', '.ok', 'templates'), { recursive: true });+ writeFileSync(+ join(contentDir, 'alpha.md'),+ '# Alpha\n\nSee [[notes/.ok/templates/daily]].\n',+ );+ writeFileSync(join(contentDir, 'notes', '.ok', 'templates', 'daily.md'), '# Daily\n');++ const cacheDir = join(projectDir, '.ok', LOCAL_DIR, 'cache', 'main');+ mkdirSync(cacheDir, { recursive: true });+ writeFileSync(+ join(cacheDir, 'backlinks.json'),+ JSON.stringify({+ backward: {+ '__template__/notes/daily': [{ source: 'alpha', anchor: null, snippet: 'See daily.' }],+ },+ forward: { alpha: ['__template__/notes/daily'] },+ externalForward: {},+ // An mtime snapshot matching disk would make the reconcile a no-op —+ // the exact condition under which the stale key would persist.+ mtimes: {},+ }),+ 'utf-8',+ );++ const index = new BacklinkIndex({ projectDir, contentDir });+ expect(await index.loadFromDisk()).toBe(false);++ // The caller's fallback on a rejected load: a clean cold rebuild keys the+ // edge under the live content name, with no residue of the retired one.+ await index.rebuildFromDisk();+ expect(index.getBacklinks(templateDoc)).toEqual([+ expect.objectContaining({ source: 'alpha' }),+ ]);+ expect(index.getDeadLinks(['alpha', templateDoc])).toEqual([]);+ expect(index.getOrphans(['alpha', templateDoc])).not.toContain(templateDoc);+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });+test('rebuilds from disk and persists cache per branch', async () => {const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-project-'));const contentDir = join(projectDir, 'content');diff --git a/packages/server/src/backlink-index.ts b/packages/server/src/backlink-index.tsindex 7f6dedbdd..59fc1df08 100644--- a/packages/server/src/backlink-index.ts+++ b/packages/server/src/backlink-index.ts@@ -9,7 +9,6 @@ import {getWikiLinkText,isOrphanMode,MANAGED_ARTIFACT_PREFIX_SKILL,- managedArtifactDocNameFromContentTarget,ORPHAN_MODES,type OrphanMode,parseGlobalSkillBundleDoc,@@ -144,7 +143,19 @@ interface BranchGraphState {skillRefs: Map<string, Set<string>>;}+/**+ * On-disk cache format version. A mismatch (including the versionless caches+ * written before the field existed) rejects the load, and the caller falls+ * back to a full cold rebuild. Bump when the meaning of a persisted key+ * changes — e.g. v1 retired the `__template__/…` link-target namespace, and a+ * pre-v1 cache carrying an edge under that key would otherwise surface a false+ * dead link (`getDeadLinks`) and a false orphan (`getOrphans`) until the+ * source doc happened to be re-parsed.+ */+const SNAPSHOT_VERSION = 1;+interface SerializedBranchGraphState {+ version?: number;backward: Record<string, Array<BacklinkEntry>>;forward: Record<string, string[]>;externalForward: Record<@@ -1299,15 +1310,11 @@ export class BacklinkIndex {for (const link of links) {if (!link.target) continue;- // Normalize a link to a skill/template FILE path to the artifact's- // identity so the edge connects to the skill/template entity (backlinks)- // rather than a (missing) raw `.ok/...` file path.- const target = managedArtifactDocNameFromContentTarget(link.target) ?? link.target;- nextTargets.add(target);- let sources = state.backward.get(target);+ nextTargets.add(link.target);+ let sources = state.backward.get(link.target);if (!sources) {sources = new Map();- state.backward.set(target, sources);+ state.backward.set(link.target, sources);}sources.set(docName,@@ -1769,18 +1776,24 @@ export class BacklinkIndex {const state = this.getState(branch);const mtimes = this.mtimesByBranch.get(branch);const data: SerializedBranchGraphState = {+ version: SNAPSHOT_VERSION,...serializeState(state),...(mtimes ? { mtimes: Object.fromEntries(mtimes) } : {}),};await writeFile(filePath, JSON.stringify(data, null, 2), 'utf-8');}+ // A version mismatch (or a versionless pre-SNAPSHOT_VERSION cache) rejects+ // the load so the caller cold-rebuilds. The mtime reconcile that follows a+ // successful load re-parses only CHANGED docs, so it cannot heal a stale key+ // written under a retired link-target format — see SNAPSHOT_VERSION.async loadFromDisk(branch = this.activeBranch): Promise<boolean> {const filePath = this.cachePath(branch);if (!existsSync(filePath)) return false;try {const raw = await readFile(filePath, 'utf-8');const parsed = JSON.parse(raw) as SerializedBranchGraphState;+ if (parsed.version !== SNAPSHOT_VERSION) return false;this.states.set(branch, deserializeState(parsed));if (parsed.mtimes) {this.mtimesByBranch.set(branch, new Map(Object.entries(parsed.mtimes)));@@ -1868,14 +1881,11 @@ export class BacklinkIndex {state.externalForward.set(docName, externalTargets);for (const link of links) {if (!link.target) continue;- // Normalize skill/template file-path targets to artifact identity (see- // updateDocument) so doc→skill/template edges resolve to the entity.- const target = managedArtifactDocNameFromContentTarget(link.target) ?? link.target;- targets.add(target);- let sources = state.backward.get(target);+ targets.add(link.target);+ let sources = state.backward.get(link.target);if (!sources) {sources = new Map();- state.backward.set(target, sources);+ state.backward.set(link.target, sources);}sources.set(docName,diff --git a/packages/server/src/cc1-broadcast.test.ts b/packages/server/src/cc1-broadcast.test.tsindex 83272280a..5121c7d56 100644--- a/packages/server/src/cc1-broadcast.test.ts+++ b/packages/server/src/cc1-broadcast.test.ts@@ -593,11 +593,17 @@ describe('isLinkIndexExcludedDoc', () => {}});- test('admits managed-artifact docs — they participate in the link index', () => {- // The two-axis split: isReservedForUserTree keeps skills/templates out of- // the document TREE, but the link index admits them so their outgoing- // links, backlinks, and tags resolve like documents.+ test('admits managed-artifact skills and template content docs as link-index sources', () => {+ // Skills and folder-local templates both participate in the link graph:+ // their outgoing links, backlinks, and authored tags index like ordinary+ // documents. Only system + config docs are excluded here — the tree axis+ // (which hides skills and `.ok` paths) is deliberately separate.expect(isLinkIndexExcludedDoc('__skill__/project/my-skill')).toBe(false);+ expect(isLinkIndexExcludedDoc('.ok/templates/daily')).toBe(false);+ expect(isLinkIndexExcludedDoc('docs/.ok/templates/meeting')).toBe(false);+ expect(isLinkIndexExcludedDoc('a/b/c/.ok/templates/note')).toBe(false);+ // The stale synthetic tombstone never reaches the file index, so it is never+ // a link-index source; it is kept out of the TREE by isReservedForUserTree.expect(isLinkIndexExcludedDoc('__template__/docs/my-template')).toBe(false);});diff --git a/packages/server/src/cc1-broadcast.ts b/packages/server/src/cc1-broadcast.tsindex 3714d3018..f44069ee7 100644--- a/packages/server/src/cc1-broadcast.ts+++ b/packages/server/src/cc1-broadcast.ts@@ -67,11 +67,13 @@ export function isConfigDoc(documentName: string): boolean {}/**- * True for managed-artifact docs — skills (`__skill__/<scope>/<name>`) and- * templates (`__template__/<folderRel>/<name>`). A THIRD doc class distinct from- * system/config docs: like them it is excluded from the document tree / search /- * create-page, but UNLIKE config docs the observer bridge RUNS for it (so the- * full WYSIWYG+source document editor works.+ * True for managed-artifact docs — live skills (`__skill__/<scope>/<name>`) plus+ * the stale template tombstone (`__template__/…`). A THIRD doc class distinct+ * from system/config docs: like them it is excluded from the document tree /+ * search / create-page, but UNLIKE config docs the observer bridge RUNS for a+ * live skill (so the full WYSIWYG+source document editor works). `__template__/`+ * matches only to keep the reserved-name gates — templates are content docs now,+ * so no `__template__/…` doc is ever seeded or stored.** Gate discipline: tree/index/create-page sites short-circuit on* `isReservedForUserTree` (system || config || managed-artifact); bridge /@@ -129,11 +131,13 @@ export function isReservedForUserTree(documentName: string): boolean {}/**- * True when a doc name must be excluded from the link / graph / backlink INDEX —- * system + config docs only. Managed-artifact docs (skills/templates) ARE- * indexed: they participate in the link graph like documents (outgoing links,- * backlinks, broken-link resolution) even though `isReservedForUserTree` keeps- * them out of the document TREE. The two axes are deliberately separate.+ * True when a doc name must be excluded from the link / graph / backlink / tag+ * INDEX as a SOURCE — system + config docs only. Everything else that reaches+ * the file index is link-indexed like a document (outgoing links, backlinks,+ * authored tags): skills (`__skill__/<scope>/<name>`, tree-excluded by+ * `isReservedForUserTree` yet link-indexed) and folder-local template content+ * docs (`<folder>/.ok/templates/<name>`, ordinary content docs on disk) both+ * participate. The index axis and the tree axis are deliberately separate.*/export function isLinkIndexExcludedDoc(documentName: string): boolean {return isSystemDoc(documentName) || isConfigDoc(documentName);@@ -143,8 +147,9 @@ export function isLinkIndexExcludedDoc(documentName: string): boolean {* True when a doc name is excluded from the markdown L1 store spine* (`storeDocumentNow`) because its persistence flows through a dedicated* store/load path: system docs (never persisted), config docs (config- * persistence + validation hook), managed artifacts (skill/template- * persistence), Mermaid docs, and editable text docs (both Y.Text-only+ * persistence + validation hook), managed artifacts (skill persistence; a+ * `__template__/…` tombstone is quarantined — its store/load guards no-op),+ * Mermaid docs, and editable text docs (both Y.Text-only* persistence). Shared by* `PersistenceHandle.forceStore` and the staleness watchdog so the two* gates cannot drift. The debounced `onStoreDocument` hook dispatches eachdiff --git a/packages/server/src/content-filter.test.ts b/packages/server/src/content-filter.test.tsindex 29ebec8b6..e5d88d002 100644--- a/packages/server/src/content-filter.test.ts+++ b/packages/server/src/content-filter.test.ts@@ -572,16 +572,17 @@ describe('ContentFilter', () => {});test('excludes BUILTIN_SKIP_DIRS at any path depth, not just top segment (FR-CF1)', () => {- // nested `.ok/`- // directories carry per-folder metadata + templates. Without this fix, a- // path like `meetings/.ok/templates/foo.md` slipped past `isDirExcluded`- // (topSegment was `meetings`, not in BUILTIN_SKIP_DIRS) and got indexed as- // ordinary content. Collateral fix for nested node_modules/, dist/, etc.+ // A skip-dir segment at ANY depth prunes the path (the top segment can be+ // an ordinary folder). Nested `node_modules/`, `dist/`, etc. all prune.+ // The `.ok` case is nuanced: `<folder>/.ok` and `<folder>/.ok/templates`+ // stay descendable via the templates-as-content carve-out, but every other+ // `.ok` child (`.ok/local`, config, an unrecognized `.ok/<x>`) still prunes.const filter = createContentFilter({ projectDir, contentDir: projectDir });- // Nested .ok/- expect(filter.isDirExcluded('meetings/.ok')).toBe(true);- expect(filter.isDirExcluded('meetings/.ok/templates')).toBe(true);+ // Nested .ok/ — descendable only down the templates carve-out.+ expect(filter.isDirExcluded('meetings/.ok')).toBe(false);+ expect(filter.isDirExcluded('meetings/.ok/templates')).toBe(false);+ expect(filter.isDirExcluded('meetings/.ok/local')).toBe(true);expect(filter.isDirExcluded('a/b/c/.ok/d')).toBe(true);// Nested node_modules/ — latent bug fixed as collateral@@ -634,21 +635,19 @@ describe('ContentFilter', () => {expect(filter.isExcluded('.ok/AGENTS.md')).toBe(true);});- test('isExcluded rejects supported docs born inside BUILTIN_SKIP_DIRS', () => {- // Watcher events fire for files created inside `.ok/` after boot- // (e.g. MCP `write_template` writing `<folder>/.ok/templates/foo.md`).- // classifyEvents only consults `isExcluded` per-event — without the- // BUILTIN_SKIP_DIRS gate here the file slipped past the supported-- // extension fast-path and landed in the file index, surfacing the- // template `.md` and its parent `.ok/templates/` folder in the file- // tree. Mirrors `isDirExcluded`'s segment-wise check.+ test('isExcluded rejects supported docs born inside BUILTIN_SKIP_DIRS except the templates carve-out', () => {+ // Watcher events fire for files created inside `.ok/` after boot.+ // classifyEvents consults `isExcluded` per-event. Non-carve-out `.ok`+ // children (folder-defaults, config) and other BUILTIN_SKIP_DIRS+ // (node_modules, build output) stay rejected so they never leak into the+ // file index. The one exception is a `.md` template leaf under+ // `.ok/templates/`, which the carve-out admits as a content doc.const filter = createContentFilter({ projectDir, contentDir: projectDir });- // Top-level `.ok/templates/<name>.md` (project-root scope template).- expect(filter.isExcluded('.ok/templates/daily.md')).toBe(true);- // Nested folder-scope template.- expect(filter.isExcluded('meetings/.ok/templates/standup.md')).toBe(true);- // Folder-defaults file in the same hidden dir.+ // Template leaves ARE admitted — root scope and nested folder scope.+ expect(filter.isExcluded('.ok/templates/daily.md')).toBe(false);+ expect(filter.isExcluded('meetings/.ok/templates/standup.md')).toBe(false);+ // A non-template file in the same hidden dir stays excluded.expect(filter.isExcluded('meetings/.ok/frontmatter.yml.md')).toBe(true);// Other BUILTIN_SKIP_DIRS at any depth — collateral coverage.expect(filter.isExcluded('node_modules/some-pkg/README.md')).toBe(true);@@ -660,6 +659,272 @@ describe('ContentFilter', () => {});});+ describe('templates-as-content admission', () => {+ // Tracer for the segment-shaped carve-out: a `.md` template leaf under any+ // `<folder>/.ok/templates/` is admitted as a content doc, at the root and at+ // any nesting depth, in BOTH filter factories. The exhaustive matrix+ // (secret-floor precedence, single-file scope, boot-index walk) lives with+ // the dedicated carve-out suite.+ function assertTemplateAdmission(filter: ContentFilter) {+ // File admission: root + nested `.md` leaves.+ expect(filter.isExcluded('.ok/templates/daily.md')).toBe(false);+ expect(filter.isExcluded('meetings/.ok/templates/standup.md')).toBe(false);+ expect(filter.isExcluded('a/b/.ok/templates/note.md')).toBe(false);+ // Dir descendability so the normal walk reaches those leaves.+ expect(filter.isDirExcluded('meetings/.ok')).toBe(false);+ expect(filter.isDirExcluded('meetings/.ok/templates')).toBe(false);+ // `.md` ONLY — a `.mdx` (or other ext) under `.ok/templates` is not a+ // template and stays excluded.+ expect(filter.isExcluded('.ok/templates/daily.mdx')).toBe(true);+ // A subdirectory under `.ok/templates` is not descendable, and a leaf+ // inside it is not admitted — templates are flat.+ expect(filter.isDirExcluded('.ok/templates/sub')).toBe(true);+ expect(filter.isExcluded('.ok/templates/sub/x.md')).toBe(true);+ // Servable content via the ungated `isPathIgnored` carve-out.+ expect(filter.isPathIgnored('.ok/templates/daily.md')).toBe(false);+ }++ test('sync factory (createContentFilter)', () => {+ const filter = createContentFilter({ projectDir, contentDir: projectDir });+ assertTemplateAdmission(filter);+ });++ test('async factory (createContentFilterAsync) mirrors admission', async () => {+ const filter = await createContentFilterAsync({ projectDir, contentDir: projectDir });+ assertTemplateAdmission(filter);+ });+ });++ describe('templates-as-content carve-out matrix (FR1)', () => {+ // The systematic sync+async twin matrix the admission tracer defers to.+ // Every case runs against BOTH factories: createContentFilterAsync is a full+ // structural copy of createContentFilter, not a wrapper, so a predicate+ // edited in one factory but not the other is the named dual-factory risk —+ // an async twin is the only thing that catches a half-edit. (The bypass /+ // Show All Files posture is pinned by the always-skip floor + showOk+ // describes above and is not re-asserted here.)++ // Secret-bearing floor wins over the carve-out. A credential adopted into a+ // `.ok/templates/` dir is never indexed (isExcluded) nor served+ // (isPathIgnored), even though `.md` leaves in the same dir are content.+ // `.key` is both a secret suffix and an Apple-Keynote extension, so the+ // ordering is load-bearing: the floor must run before the carve-out at every+ // consultation site.+ function assertSecretFloorWins(filter: ContentFilter) {+ for (const secret of [+ '.ok/templates/server.key',+ '.ok/templates/server.pem',+ 'meetings/.ok/templates/id_rsa',+ ]) {+ expect(filter.isExcluded(secret), secret).toBe(true);+ expect(filter.isPathIgnored(secret), secret).toBe(true);+ }+ // A secret directory adopted under templates is pruned at the dir boundary:+ // the secret-dir floor precedes the template ancestor carve-out.+ expect(filter.isDirExcluded('.ok/templates/.ssh')).toBe(true);+ // Control: the sibling `.md` leaf IS admitted, proving the rejection is the+ // secret floor rather than a blanket `.ok/templates` exclusion.+ expect(filter.isExcluded('.ok/templates/daily.md')).toBe(false);+ }++ test('secret floor wins over the carve-out (sync)', () => {+ const filter = createContentFilter({ projectDir, contentDir: projectDir });+ assertSecretFloorWins(filter);+ });+ test('secret floor wins over the carve-out (async)', async () => {+ const filter = await createContentFilterAsync({ projectDir, contentDir: projectDir });+ assertSecretFloorWins(filter);+ });++ // The carve-out is narrow: admitting template `.md` leaves must NOT re-admit+ // the rest of `.ok/`. Non-template `.ok` children (config, folder-defaults,+ // and the repo-scale `.ok/local` / `.ok/worktrees` dirs) stay excluded at the+ // same depths a template is admitted, at root and nested.+ function assertCarveOutIsNarrow(filter: ContentFilter) {+ expect(filter.isExcluded('.ok/templates/daily.md')).toBe(false);+ expect(filter.isExcluded('meetings/.ok/templates/standup.md')).toBe(false);+ // Excluded siblings under the same `.ok`.+ expect(filter.isExcluded('.ok/config.yml')).toBe(true);+ expect(filter.isExcluded('.ok/AGENTS.md')).toBe(true);+ expect(filter.isExcluded('meetings/.ok/frontmatter.yml.md')).toBe(true);+ expect(filter.isExcluded('.ok/local/cache/notes.md')).toBe(true);+ // Repo-scale `.ok` children stay pruned as directories so the walk stays+ // bounded even though `.ok` itself is descendable.+ expect(filter.isDirExcluded('.ok/local')).toBe(true);+ expect(filter.isDirExcluded('.ok/worktrees')).toBe(true);+ expect(filter.isDirExcluded('meetings/.ok/local')).toBe(true);+ }++ test('carve-out does not over-admit other .ok children (sync)', () => {+ const filter = createContentFilter({ projectDir, contentDir: projectDir });+ assertCarveOutIsNarrow(filter);+ });+ test('carve-out does not over-admit other .ok children (async)', async () => {+ const filter = await createContentFilterAsync({ projectDir, contentDir: projectDir });+ assertCarveOutIsNarrow(filter);+ });++ // Folder-index descendability: `<folder>/.ok` and `<folder>/.ok/templates`+ // stay descendable at any depth so the normal walk reaches the leaves,+ // matching the root `.ok` skills precedent. A subdirectory under+ // `.ok/templates` is NOT an ancestor (templates are flat), so the walk stops+ // there and the descent stays bounded.+ function assertFolderIndexDescendable(filter: ContentFilter) {+ // Root `.ok` precedent + its template child.+ expect(filter.isDirExcluded('.ok')).toBe(false);+ expect(filter.isDirExcluded('.ok/templates')).toBe(false);+ // Nested one and two levels deep.+ expect(filter.isDirExcluded('meetings/.ok')).toBe(false);+ expect(filter.isDirExcluded('meetings/.ok/templates')).toBe(false);+ expect(filter.isDirExcluded('a/b/.ok')).toBe(false);+ expect(filter.isDirExcluded('a/b/.ok/templates')).toBe(false);+ // Bounded: no descent past the flat template dir.+ expect(filter.isDirExcluded('.ok/templates/sub')).toBe(true);+ expect(filter.isDirExcluded('meetings/.ok/templates/sub')).toBe(true);+ }++ test('folder-index keeps nested .ok/templates descendable (sync)', () => {+ const filter = createContentFilter({ projectDir, contentDir: projectDir });+ assertFolderIndexDescendable(filter);+ });+ test('folder-index keeps nested .ok/templates descendable (async)', async () => {+ const filter = await createContentFilterAsync({ projectDir, contentDir: projectDir });+ assertFolderIndexDescendable(filter);+ });++ // Boot-index-walk admission (no-server seeding): a template written to disk+ // before any server runs — via `ok seed` or desktop create-new-project —+ // pre-exists the next boot. The boot index walk consults exactly these+ // predicates (ancestors descendable + leaf included), so a real pre-existing+ // file is reached and admitted. The end-to-end indexes-and-appears proof is+ // the integration tier's; this pins the filter contract that walk stands on,+ // against a real file rather than a synthetic path string.+ async function assertBootWalkAdmits(makeFilter: () => ContentFilter | Promise<ContentFilter>) {+ mkdirSync(join(projectDir, 'meetings', '.ok', 'templates'), { recursive: true });+ writeFileSync(join(projectDir, 'meetings', '.ok', 'templates', 'standup.md'), '# Standup\n');+ const filter = await makeFilter();+ expect(filter.isDirExcluded('meetings')).toBe(false);+ expect(filter.isDirExcluded('meetings/.ok')).toBe(false);+ expect(filter.isDirExcluded('meetings/.ok/templates')).toBe(false);+ expect(filter.isExcluded('meetings/.ok/templates/standup.md')).toBe(false);+ }++ test('pre-existing template on disk is admitted by the walk (sync)', async () => {+ await assertBootWalkAdmits(() => createContentFilter({ projectDir, contentDir: projectDir }));+ });+ test('pre-existing template on disk is admitted by the walk (async)', async () => {+ await assertBootWalkAdmits(() =>+ createContentFilterAsync({ projectDir, contentDir: projectDir }),+ );+ });++ // Single-file mode (`?docPath=`) serves ONLY the target doc. The template+ // file predicate re-asserts that scope: without the re-assertion the+ // carve-out's unconditional admit would leak every template into single-file+ // mode. `isPathIgnored` is deliberately unaffected — the asset-serve path is+ // never single-file-scoped (referenced siblings still resolve), matching the+ // skills and sibling-asset posture.+ function assertSingleFileScope(filter: ContentFilter) {+ expect(filter.isExcluded('notes.md')).toBe(false); // the one target doc+ expect(filter.isExcluded('.ok/templates/daily.md')).toBe(true);+ expect(filter.isExcluded('meetings/.ok/templates/standup.md')).toBe(true);+ // Serve path stays open for the leaf, like skills / sibling assets.+ expect(filter.isPathIgnored('.ok/templates/daily.md')).toBe(false);+ }++ test('single-file scope excludes templates (sync)', () => {+ const filter = createContentFilter({+ projectDir,+ contentDir: projectDir,+ singleDocRelPath: 'notes.md',+ });+ assertSingleFileScope(filter);+ });+ test('single-file scope excludes templates (async)', async () => {+ const filter = await createContentFilterAsync({+ projectDir,+ contentDir: projectDir,+ singleDocRelPath: 'notes.md',+ });+ assertSingleFileScope(filter);+ });++ // The watcher-ignore glob strip drops the four blanket `.ok` forms so the+ // @parcel/watcher backend (which consults globs, not the function predicates)+ // still delivers external edits under `<folder>/.ok/templates/`. The rename+ // of the strip helper kept this exact set; a more specific `.ok/local` glob+ // does not block the carve-out trees and is preserved, as are unrelated+ // ignores.+ function assertGlobStripSet(filter: ContentFilter) {+ const globs = filter.getWatcherIgnoreGlobs();+ for (const blanket of ['.ok', '.ok/**', '**/.ok', '**/.ok/**']) {+ expect(globs, blanket).not.toContain(blanket);+ }+ expect(globs).toContain('.ok/local');+ expect(globs).toContain('dist/');+ expect(globs).toContain('node_modules/');+ }++ test('watcher glob strip drops blanket .ok, keeps the rest (sync)', () => {+ writeFileSync(+ join(projectDir, '.gitignore'),+ 'dist/\nnode_modules/\n.ok\n.ok/**\n**/.ok\n**/.ok/**\n.ok/local\n',+ );+ const filter = createContentFilter({ projectDir, contentDir: projectDir });+ assertGlobStripSet(filter);+ });+ test('watcher glob strip drops blanket .ok, keeps the rest (async)', async () => {+ writeFileSync(+ join(projectDir, '.gitignore'),+ 'dist/\nnode_modules/\n.ok\n.ok/**\n**/.ok\n**/.ok/**\n.ok/local\n',+ );+ const filter = await createContentFilterAsync({ projectDir, contentDir: projectDir });+ assertGlobStripSet(filter);+ });+ });++ describe('templates-as-content carve-out stays below the skip-dir floor', () => {+ // The segment-shaped template carve-out runs BEFORE the always-skip floor and+ // the configurable-rules floor, so a template-shaped tail vendored inside a+ // dependency or build-output tree must not be admitted just because its last+ // three segments match `.ok/templates/<name>.md`. `isExcluded` /+ // `isPathIgnored` are consulted directly per raw watcher event on the full+ // path (not only via the top-down walk that prunes the skip-dir root first),+ // so the bound has to live in the predicate. Legitimate templates the user+ // owns at any depth stay admitted.+ function assertSkipDirAncestorExcluded(filter: ContentFilter) {+ for (const vendored of [+ 'node_modules/pkg/.ok/templates/x.md',+ 'dist/.ok/templates/x.md',+ 'vendor/lib/.ok/templates/note.md',+ ]) {+ // Admission (isExcluded) and the ungated serve path (isPathIgnored).+ expect(filter.isExcluded(vendored), vendored).toBe(true);+ expect(filter.isPathIgnored(vendored), vendored).toBe(true);+ }+ // The bound is the skip-dir ANCESTOR, not depth: a template the user owns+ // at any nesting stays admitted — the fix must not regress the carve-out.+ expect(filter.isExcluded('docs/.ok/templates/x.md')).toBe(false);+ expect(filter.isExcluded('a/b/c/.ok/templates/x.md')).toBe(false);+ expect(filter.isPathIgnored('docs/.ok/templates/x.md')).toBe(false);+ // Dir predicate is bounded too: a `.ok` (or `.ok/templates`) under a+ // skip-dir tree is not a descendable template ancestor. The walk already+ // prunes the skip-dir root top-down, but the direct/per-event callers stay+ // consistent with the file predicates.+ expect(filter.isDirExcluded('node_modules/pkg/.ok')).toBe(true);+ expect(filter.isDirExcluded('dist/.ok/templates')).toBe(true);+ }++ test('skip-dir ancestor excluded from admission and serve path (sync)', () => {+ const filter = createContentFilter({ projectDir, contentDir: projectDir });+ assertSkipDirAncestorExcluded(filter);+ });+ test('skip-dir ancestor excluded from admission and serve path (async)', async () => {+ const filter = await createContentFilterAsync({ projectDir, contentDir: projectDir });+ assertSkipDirAncestorExcluded(filter);+ });+ });+describe('always-skip floor survives bypassFilters (Show All Files OOM guard)', () => {// `?showAll=true` bypasses Git/build filters while preserving `.okignore`.// The floor remains the hard limit on that bypass: `.git/`, `node_modules/`,@@ -935,15 +1200,19 @@ describe('ContentFilter', () => {expect(filter.isExcluded('__config__/project.md', REVEAL)).toBe(true);expect(filter.isExcluded('__local__/project.md', REVEAL)).toBe(true);- // `isPathIgnored` keeps the absolute floor — showOk widens the listing- // walk only, never asset serving.+ // `isPathIgnored` keeps the absolute floor for non-carve-out `.ok`+ // content (config), but the skills/templates carve-outs are ungated here,+ // so a template `.md` leaf is servable content like a skill file.expect(filter.isPathIgnored('.ok/config.yml', REVEAL)).toBe(true);- expect(filter.isPathIgnored('.ok/templates/daily.md', REVEAL)).toBe(true);-- // showOk lifts only the always-skip floor: without bypassFilters the- // configurable BUILTIN_SKIP_DIRS rule still hides non-skill `.ok`- // content, so a stray showOk on a normal-mode caller reveals nothing.- expect(filter.isDirExcluded('.ok/templates', { showOk: true })).toBe(true);+ expect(filter.isPathIgnored('.ok/templates/daily.md', REVEAL)).toBe(false);++ // showOk lifts the always-skip floor; the templates/skills carve-outs+ // reach the index in normal + showOk mode (both non-bypass), so a template+ // dir stays descendable. A non-carve-out `.ok` child still hides without+ // bypass — the configurable BUILTIN_SKIP_DIRS rule catches it past the+ // lifted floor.+ expect(filter.isDirExcluded('.ok/templates', { showOk: true })).toBe(false);+ expect(filter.isDirExcluded('.ok/local', { showOk: true })).toBe(true);expect(filter.isExcluded('.ok/config.yml', { showOk: true })).toBe(true);}diff --git a/packages/server/src/content-filter.ts b/packages/server/src/content-filter.tsindex 263146e57..e8bdf7715 100644--- a/packages/server/src/content-filter.ts+++ b/packages/server/src/content-filter.ts@@ -216,7 +216,8 @@ function isSkillContentFile(relativePath: string): boolean {* True for the directories that must stay DESCENDABLE so a tree walk reaches* skill files: `.ok` itself (to get to `.ok/skills`), `.ok/skills`, and anything* under it. `.ok` is descendable but does NOT admit its other children — the- * file-level predicates still exclude `.ok/local`, `.ok/templates`, etc.+ * file-level predicates still exclude `.ok/local`, config, etc. (Templates under+ * `.ok/templates` are admitted, but by their own segment-shaped carve-out.)*/function isSkillContentAncestorDir(relativePath: string): boolean {return (@@ -228,23 +229,92 @@ function isSkillContentAncestorDir(relativePath: string): boolean {/*** True for a watcher-ignore glob that would stop the OS file-watcher from- * seeing `.ok/skills/**`. The watcher-ignore list is glob-derived from- * `.gitignore` / `.okignore` / `.git/info/exclude` (e.g. clone appends `.ok/`),- * and the @parcel/watcher backend consults THESE globs — not the function- * predicates (`isDirExcluded` / `isExcluded`) that carry the skills-as-content- * carve-out and that the chokidar backend uses. So a blanket `.ok` ignore glob+ * seeing `.ok/` content the carve-outs admit: `.ok/skills/**` and the template+ * leaves under any `<folder>/.ok/templates/`. The watcher-ignore list is+ * glob-derived from `.gitignore` / `.okignore` / `.git/info/exclude` (e.g. clone+ * appends `.ok/`), and the @parcel/watcher backend consults THESE globs — not+ * the function predicates (`isDirExcluded` / `isExcluded`) that carry the+ * carve-outs and that the chokidar backend uses. So a blanket `.ok` ignore glob* makes parcel (the default backend on Linux) never deliver external edits to- * project skills. Dropping the blanket-`.ok` globs lets the watcher reach- * `.ok/skills`; the non-skill `.ok` children (`.ok/local`, `.ok/templates`, …)- * are still pruned downstream by the function predicates in `handleRawEvents`,- * so they never reach the index. A more specific glob like `.ok/local` does NOT- * block the skill tree and is kept.+ * project skills or templates. Dropping the blanket-`.ok` globs lets the watcher+ * reach them; the non-carve-out `.ok` children (`.ok/local`, config, …) are+ * still pruned downstream by the function predicates in `handleRawEvents`, so+ * they never reach the index. A more specific glob like `.ok/local` does NOT+ * block the carve-out trees and is kept.*/-function globBlocksSkillContent(pattern: string): boolean {+function globBlocksOkContent(pattern: string): boolean {const p = pattern.replace(/^\/+/, '').replace(/\/+$/, '').trim();return p === '.ok' || p === '.ok/**' || p === '**/.ok' || p === '**/.ok/**';}+/*+ * Template carve-out family (the three predicates below). Templates are+ * ordinary content docs at `<folder>/.ok/templates/<name>.md` for any folder+ * depth, so — unlike the root-anchored `.ok/skills` carve-out — the predicates+ * are SEGMENT-shaped: a `.ok` segment immediately followed by `templates`. A+ * `startsWith` twin would silently miss every nested-folder template. The shape+ * match alone is NOT sufficient: these predicates run before the always-skip and+ * configurable-rules floors, and `isExcluded` / `isPathIgnored` are consulted+ * per raw watcher event on the full path (not only via the top-down walk that+ * prunes skip-dir roots first), so a template tail vendored under+ * `node_modules` / `dist` / a gitignored tree would leak in.+ * `templateFolderPrefixIsSkipped` bounds the carve-out below the skip-dir floor.+ */++/**+ * True when a template-shaped path sits under a `BUILTIN_SKIP_DIRS` ancestor.+ * Only the folder prefix strictly above the template's `.ok` is checked — the+ * `.ok` segment is itself a skip dir by design and must not self-reject the+ * template. `okIndex` is the position of that `.ok` segment.+ */+function templateFolderPrefixIsSkipped(segments: string[], okIndex: number): boolean {+ for (let i = 0; i < okIndex; i++) {+ if (BUILTIN_SKIP_DIRS.has(segments[i])) return true;+ }+ return false;+}++/**+ * True for a single `.md` template leaf directly under any+ * `<folder>/.ok/templates/`. `.md` ONLY — a `.mdx` (or any other extension)+ * under `.ok/templates` is not a template and stays excluded. A leaf inside a+ * subdirectory (`.ok/templates/sub/x.md`) is rejected: templates are flat, one+ * leaf per dir.+ */+function isTemplateContentFile(relativePath: string): boolean {+ const segments = relativePath.split('/');+ const n = segments.length;+ if (n < 3) return false;+ if (+ segments[n - 3] !== OK_DIR ||+ segments[n - 2] !== 'templates' ||+ extname(segments[n - 1]) !== '.md'+ ) {+ return false;+ }+ return !templateFolderPrefixIsSkipped(segments, n - 3);+}++/**+ * True for the directories that must stay DESCENDABLE so the normal index walk+ * reaches template leaves at any depth: a `<folder>/.ok` (to reach its+ * `templates` child) and a `<folder>/.ok/templates` (to reach the leaves). A+ * subdirectory under `.ok/templates` is NOT an ancestor — templates are flat,+ * so it falls through to the always-skip floor and stays pruned, keeping the+ * walk bounded.+ */+function isTemplateContentAncestorDir(relativePath: string): boolean {+ const segments = relativePath.split('/');+ const n = segments.length;+ if (segments[n - 1] === OK_DIR) {+ return !templateFolderPrefixIsSkipped(segments, n - 1);+ }+ if (n >= 2 && segments[n - 1] === 'templates' && segments[n - 2] === OK_DIR) {+ return !templateFolderPrefixIsSkipped(segments, n - 2);+ }+ return false;+}+/*** In-place skill admission (spec: in-place skill versioning). Unlike the* `.ok/skills` carve-out (a fixed prefix), in-place skills live in the various@@ -863,7 +933,7 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {// Skip negation (!) and comment (#) lines — they aren't directly usable// as fast-path globs for the OS watcher.const newWatcherGlobs = newRootPatterns.filter(- (p) => p.length > 0 && !p.startsWith('!') && !p.startsWith('#') && !globBlocksSkillContent(p),+ (p) => p.length > 0 && !p.startsWith('!') && !p.startsWith('#') && !globBlocksOkContent(p),);// Atomic swap.@@ -934,9 +1004,11 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {function isRejectedByConfigurableRules(relativePath: string): boolean {// BUILTIN_SKIP_DIRS — must mirror isDirExcluded. The seed walk skips// these dirs at boot, but watcher events for files born inside them- // (e.g. MCP `write({ template })` creating `<folder>/.ok/templates/foo.md`)- // reach classifyEvents and must be rejected here, otherwise they leak- // into the file index and surface in the file tree.+ // (e.g. a file written into `node_modules/`, or a non-carve-out `.ok`+ // child like `.ok/local/`) reach classifyEvents and must be rejected here,+ // otherwise they leak into the file index and surface in the file tree.+ // The `.ok/skills` and `.ok/templates` carve-outs run earlier in+ // `isExcluded`, so admitted skill/template leaves never reach this check.for (const segment of relativePath.split('/')) {if (BUILTIN_SKIP_DIRS.has(segment)) return true;}@@ -993,6 +1065,18 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {return !LINKABLE_ASSET_EXTENSIONS.has(ext);}+ // (0b') Template-as-content carve-out — a `.md` template leaf under any+ // `<folder>/.ok/templates/` is a content doc. Unlike skills, ONLY the+ // `.md` leaf is admitted (no linkable assets, no subdirectories). Same+ // `!bypassFilters` gate as the skills carve-out so Show All Files defers+ // to the always-skip floor; the single-file scope obligation is inherited+ // (omitting it would admit every template under `?docPath=`). Must precede+ // the always-skip floor, which prunes any `.ok` segment.+ if (!opts?.bypassFilters && isTemplateContentFile(relativePath)) {+ if (singleDocRelPath !== undefined) return relativePath !== singleDocRelPath;+ return false;+ }+// (0c) Always-skip floor — VCS / dependency / OK-state dirs stay// excluded even under bypass. Defense-in-depth: the showAll walk gates// directories via `isDirExcluded`, but any caller enumerating files@@ -1049,15 +1133,17 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {// skills carve-out: a secret dir nested under a skill (`.ok/skills/x/.ssh`)// would otherwise be kept descendable by the ancestor carve-out.if (pathHasSecretBearingDirSegment(relativePath)) return true;- // Skills-as-content: keep `.ok`, `.ok/skills`, and `.ok/skills/**`- // descendable so the NORMAL index walk reaches skill files; the file-level- // predicates keep the rest of `.ok/` excluded. Gated on `!bypassFilters`:- // under Show All Files the always-skip floor below must still prune `.ok`- // (it's an internal dir, not user content — surfacing it as a folder broke- // the showAll folder-listing contract and the hasFolders gate).+ // Skills- and templates-as-content: keep `.ok`, `.ok/skills[/**]`, and+ // any `<folder>/.ok/templates` descendable so the NORMAL index walk+ // reaches skill + template leaves; the file-level predicates keep the rest+ // of `.ok/` excluded. Gated on `!bypassFilters`: under Show All Files the+ // always-skip floor below must still prune `.ok` (it's an internal dir,+ // not user content — surfacing it as a folder broke the showAll+ // folder-listing contract and the hasFolders gate).if (!opts?.bypassFilters &&(isSkillContentAncestorDir(relativePath) ||+ isTemplateContentAncestorDir(relativePath) ||isInPlaceSkillAncestorDir(relativePath, inPlaceSkillDirs)))return false;@@ -1122,6 +1208,10 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {(isInPlaceSkillFile(relativePath, inPlaceSkillDirs) && !isIgnored(relativePath)))return false;+ // Templates-as-content: a `.md` template leaf is servable content too.+ // Ungated (like the skills carve-out here) and admitted before the `.ok`+ // always-skip floor.+ if (isTemplateContentFile(relativePath)) return false;if (pathHasAlwaysSkipSegment(relativePath)) return true;if (isAlwaysSkipFile(relativePath)) return true;if (opts?.bypassFilters) return false;@@ -1617,7 +1707,7 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Promig = newIg;okignoreIg = newOkignoreIg;watcherIgnoreGlobs = newRootPatterns.filter(- (p) => p.length > 0 && !p.startsWith('!') && !p.startsWith('#') && !globBlocksSkillContent(p),+ (p) => p.length > 0 && !p.startsWith('!') && !p.startsWith('#') && !globBlocksOkContent(p),);dirCount.clear();for (const [k, v] of newDirCount) dirCount.set(k, v);@@ -1650,6 +1740,13 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Promconst skillExt = extname(relativePath).slice(1).toLowerCase();return !LINKABLE_ASSET_EXTENSIONS.has(skillExt);}+ // Template-as-content carve-out — a `.md` template leaf under any+ // `<folder>/.ok/templates/` is a content doc (see sync variant, incl. the+ // `!bypassFilters` gate and the inherited single-file scope obligation).+ if (!opts?.bypassFilters && isTemplateContentFile(relativePath)) {+ if (singleDocRelPath !== undefined) return relativePath !== singleDocRelPath;+ return false;+ }// Always-skip floor — survives bypass; `showOk` re-admits `.ok` minus// `worktrees`/`local` (see sync variant for rationale).if (pathHasAlwaysSkipSegment(relativePath, opts?.showOk)) return true;@@ -1676,12 +1773,14 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom// MUST precede the skills carve-out so a secret dir nested under a skill// (`.ok/skills/x/.ssh`) isn't kept descendable by the ancestor carve-out.if (pathHasSecretBearingDirSegment(relativePath)) return true;- // Skills-as-content: keep `.ok` / `.ok/skills` / `.ok/skills/**`- // descendable for the NORMAL index walk only (see sync variant); under- // bypass the always-skip floor below keeps `.ok` pruned.+ // Skills- and templates-as-content: keep `.ok` / `.ok/skills[/**]` and any+ // `<folder>/.ok/templates` descendable for the NORMAL index walk only (see+ // sync variant); under bypass the always-skip floor below keeps `.ok`+ // pruned.if (!opts?.bypassFilters &&(isSkillContentAncestorDir(relativePath) ||+ isTemplateContentAncestorDir(relativePath) ||isInPlaceSkillAncestorDir(relativePath, inPlaceSkillDirs)))return false;@@ -1727,6 +1826,9 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom(isInPlaceSkillFile(relativePath, inPlaceSkillDirs) && !isIgnored(relativePath)))return false;+ // Templates-as-content: a `.md` template leaf is servable content too+ // (ungated, see sync variant).+ if (isTemplateContentFile(relativePath)) return false;if (pathHasAlwaysSkipSegment(relativePath)) return true;if (isAlwaysSkipFile(relativePath)) return true;if (opts?.bypassFilters) return false;diff --git a/packages/server/src/content/templates-resolver.ts b/packages/server/src/content/templates-resolver.tsindex ca95952a6..03c4d38a6 100644--- a/packages/server/src/content/templates-resolver.ts+++ b/packages/server/src/content/templates-resolver.ts@@ -127,8 +127,9 @@ export interface ProjectTemplatesResult {** Every call re-walks, deliberately. Templates reach disk through two* unrelated substrates (the filesystem writers in `templates-write.ts` and- * the CRDT managed-artifact persistence path behind `PUT /api/template`) as- * well as plain external edits, so any memo here has to be invalidated from+ * the CRDT content persistence path behind `PUT /api/template` — a template is+ * a content doc, so the managed-artifact store no-ops its name) as well as+ * plain external edits, so any memo here has to be invalidated from* each of them — a completeness obligation that is easy to violate silently,* and whose failure mode is a template the user just created not appearing.* The async walk is what removes the latency harm; caching on top boughtdiff --git a/packages/server/src/file-watcher-chokidar-fallback.test.ts b/packages/server/src/file-watcher-chokidar-fallback.test.tsindex 050378911..71dea9702 100644--- a/packages/server/src/file-watcher-chokidar-fallback.test.ts+++ b/packages/server/src/file-watcher-chokidar-fallback.test.ts@@ -185,3 +185,90 @@ describe('chokidar backend — live subfolder watching (forceBackend)', () => {}});});++/**+ * Templates-as-content on the chokidar backend. Templates enter the ordinary+ * content pipeline, so the carve-out that admits `<folder>/.ok/templates/<name>.md`+ * must hold on the chokidar path too — the packaged desktop build has no+ * @parcel/watcher and runs entirely on chokidar. These pin the two capabilities+ * the dedicated template watcher lacked (new-folder rescue, conflict-marker+ * classification) for a template path on this backend; the sync/async filter+ * carve-out itself is unit-pinned in content-filter.test.ts, and the full-server+ * parcel-backend twins live in the app integration suite.+ */+describe('chokidar backend — templates-as-content watching (forceBackend)', () => {+ let tmpDir: string;+ let contentDir: string;++ beforeEach(async () => {+ tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-chokidar-template-'));+ contentDir = resolve(tmpDir, 'content');+ mkdirSync(contentDir, { recursive: true });+ lastKnownHash.clear();+ writeTracker.clear();+ });++ afterEach(async () => {+ await rm(tmpDir, { recursive: true, force: true });+ });++ async function until(predicate: () => boolean, timeoutMs = 6000): Promise<boolean> {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (predicate()) return true;+ await new Promise((r) => setTimeout(r, 40));+ }+ return predicate();+ }++ test('a template created in a brand-new .ok/templates folder dispatches a DiskEvent', async () => {+ const filter = createContentFilter({ projectDir: tmpDir, contentDir });+ const events: DiskEvent[] = [];+ const handle = await startWatcher(contentDir, async (e) => void events.push(e), filter, {+ forceBackend: 'chokidar',+ });+ try {+ const target = resolve(contentDir, 'notes', '.ok', 'templates', 'standup.md');+ mkdirSync(resolve(target, '..'), { recursive: true });+ const src = '---\ntitle: Standup\ndescription: a standup template\n---\n\n# {{date}}\n';+ // The folder was absent at watch start; chokidar arms the subwatch on its+ // addDir handler. Re-emit until the armed subwatch catches a write — the+ // deterministic form of the brand-new-folder rescue on this backend.+ expect(+ await until(() => {+ writeFileSync(target, src);+ return events.some(+ (e) =>+ (e.kind === 'create' || e.kind === 'update') &&+ e.docName === 'notes/.ok/templates/standup',+ );+ }),+ ).toBe(true);+ } finally {+ await handle.unsubscribe();+ }+ });++ test('conflict markers in a template file dispatch a conflict DiskEvent', async () => {+ // Seed the templates folder so it is watched from the initial scan — this+ // isolates conflict classification from the new-folder subwatch-arming race.+ mkdirSync(resolve(contentDir, '.ok', 'templates'), { recursive: true });+ const filter = createContentFilter({ projectDir: tmpDir, contentDir });+ const events: DiskEvent[] = [];+ const handle = await startWatcher(contentDir, async (e) => void events.push(e), filter, {+ forceBackend: 'chokidar',+ });+ try {+ const target = resolve(contentDir, '.ok', 'templates', 'daily.md');+ const conflicted = '# Daily\n\n<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> branch\n';+ writeFileSync(target, conflicted);+ expect(+ await until(() =>+ events.some((e) => e.kind === 'conflict' && e.docName === '.ok/templates/daily'),+ ),+ ).toBe(true);+ } finally {+ await handle.unsubscribe();+ }+ });+});diff --git a/packages/server/src/managed-artifact-persistence.test.ts b/packages/server/src/managed-artifact-persistence.test.tsindex c889313d4..56d8f485a 100644--- a/packages/server/src/managed-artifact-persistence.test.ts+++ b/packages/server/src/managed-artifact-persistence.test.ts@@ -142,28 +142,20 @@ describe('managedArtifactAbsPath', () => {);});- test('templates resolve folder-addressed under <folder>/.ok/templates/<name>.md', () => {+ test('rejects every __template__ name — templates never resolve through the managed disk path', () => {+ // Templates are content docs now; a `__template__/…` name is a tombstone+ // that must never resolve to a disk path. The load/store guards short-circuit+ // before this resolver, so a throw here is defense-in-depth — a well-formed+ // template name is rejected exactly like a malformed one.const ctx = makeCtx();- // Root template (empty folder).- expect(managedArtifactAbsPath('__template__/daily-note', ctx)).toBe(- resolve(projectDir, '.ok', 'templates', 'daily-note.md'),- );- // Nested-folder template.- expect(managedArtifactAbsPath('__template__/notes/sub/meeting', ctx)).toBe(- resolve(projectDir, 'notes', 'sub', '.ok', 'templates', 'meeting.md'),- );- });-- test('rejects template path-escape + malformed names (security)', () => {- const ctx = makeCtx();- for (const bad of [+ for (const name of [+ '__template__/daily-note', // well-formed — still rejected+ '__template__/notes/sub/meeting','__template__/', // empty'__template__/../evil', // folder escape- '__template__/notes/../../etc/passwd',- '__template__/notes/bad.name', // dot in name'__template__/notes/bad name', // space in name]) {- expect(() => managedArtifactAbsPath(bad, ctx)).toThrow();+ expect(() => managedArtifactAbsPath(name, ctx)).toThrow();}});});@@ -239,6 +231,40 @@ describe('store/load round-trip', () => {expect(fresh.getXmlFragment('default').length).toBe(0);});+ test('__template__ synthetic doc is INERT in load + store (tombstone, never creates a file)', async () => {+ // Templates are content docs now (`<folder>/.ok/templates/<name>`). A stale+ // `__template__/…` name from an old client or bookmark is a tombstone: the+ // load guard seeds nothing and the store guard no-ops, so the synthetic name+ // can never become a SECOND CRDT doc for the same file (double-doc+ // corruption) nor write a literal `__template__/…` file. `managedArtifactAbsPath`+ // throws for every `__template__` name (its template arm was deleted), so the+ // tombstone disk paths are hardcoded here — and a MISSING load guard would+ // surface as that throw, which is exactly what `not.toThrow()` pins.+ const ctx = makeCtx();+ const templateDocName = '__template__/notes/daily';++ // store: a populated doc must NOT persist under the synthetic template name.+ const doc = new Y.Doc();+ doc.transact(() => doc.getText('source').insert(0, SRC), 'agent');+ expect(await storeManagedArtifactDoc(doc, templateDocName, 'agent', ctx)).toBe('no-op');++ // load: the guard returns BEFORE `managedArtifactAbsPath` (which throws for a+ // `__template__` name), so a well-formed synthetic name seeds an EMPTY doc+ // without throwing and mints no lineage epoch — the observable proof the+ // tombstone guard fires ahead of the resolver.+ const fresh = new Y.Doc();+ expect(() => loadManagedArtifactDoc(fresh, templateDocName, ctx)).not.toThrow();+ expect(fresh.getText('source').toString()).toBe('');+ expect(fresh.getXmlFragment('default').length).toBe(0);+ expect(fresh.getMap('lifecycle').get(LINEAGE_EPOCH_KEY)).toBeUndefined();++ // Never-creates-file: neither a literal `__template__/…` path nor the+ // content-relative path the name would map to exists on disk after both+ // guards short-circuit.+ expect(existsSync(join(projectDir, '__template__', 'notes', 'daily.md'))).toBe(false);+ expect(existsSync(join(projectDir, 'notes', '.ok', 'templates', 'daily.md'))).toBe(false);+ });+test('store is a no-op when content equals LKG', async () => {const ctx = makeCtx();const doc = new Y.Doc();@@ -351,13 +377,16 @@ describe('concurrent-writer reconcile', () => {});/**- * Global skills are the reconcile arm's primary reachable case — project- * skills return 'no-op' before it, so the reachable set is global skills plus- * templates. They also live outside any project shadow repo, which makes them- * the unanchorable half of the site: the hook still has to run so the counter- * and the ring breadcrumb fire, even though there is nowhere to file an- * anchor. The booted template test pins the anchored half; this pins the hand-- * off, which is what tells the anchored half it will ever be reached.+ * Global skills (this test's subject) reach the reconcile arm; project skills+ * and templates both return 'no-op' before it, since both persist through the+ * content path now. Global skills live outside any project shadow repo, which+ * makes them the unanchorable half of the site: the hook still has to run so+ * the counter and the ring breadcrumb fire, even though there is nowhere to+ * file an anchor. The anchored half — a versioned managed artifact that writes+ * an actual checkpoint — is currently UNREACHABLE: templates were the last+ * versioned artifact that reached this arm, and they are content docs now, so+ * no production path writes the `managed-artifact-reconcile` checkpoint. This+ * test pins the reachable, unanchored path only.*/test('reconcile invokes beforeReconcileDivergence with the live and disk content', async () => {const calls: Array<{ docName: string; live: string; disk: string }> = [];@@ -481,40 +510,29 @@ describe('managedArtifactDocNameForPath (reverse resolver)', () => {).toBeNull();});- test('maps a template .md leaf back to its folder-addressed doc name', () => {+ test('round-trips with managedArtifactAbsPath (global skills)', () => {const ctx = makeCtx();- // Root template.- expect(managedArtifactDocNameForPath(resolve(projectDir, '.ok/templates/daily.md'), ctx)).toBe(- '__template__/daily',- );- // Nested-folder template.- expect(- managedArtifactDocNameForPath(resolve(projectDir, 'notes/sub/.ok/templates/meeting.md'), ctx),- ).toBe('__template__/notes/sub/meeting');- });-- test('round-trips with managedArtifactAbsPath (skills + templates)', () => {- const ctx = makeCtx();- // Project skills omitted — they are content docs, so their disk path does- // not round-trip through the managed-artifact reverse resolver anymore.+ // Project skills + templates omitted — they are content docs, so their disk+ // path does not round-trip through the managed-artifact reverse resolver.for (const name of ['__skill__/global/beta-2','__skill__/global/beta-2/references/patterns', // per-file bundle doc- '__template__/daily',- '__template__/notes/sub/meeting',]) {expect(managedArtifactDocNameForPath(managedArtifactAbsPath(name, ctx), ctx)).toBe(name);}});- test('rejects malformed / false-match template paths', () => {+ test('template disk paths never reverse-map to a managed doc name (content docs now)', () => {+ // A `<folder>/.ok/templates/<name>.md` leaf is an ordinary content doc, so+ // the managed-artifact reverse resolver returns null for it — even a+ // well-formed leaf — leaving the disk→doc mapping to the content pipeline.const ctx = makeCtx();- for (const bad of [+ for (const path of [+ resolve(projectDir, '.ok/templates/daily.md'), // well-formed root leaf+ resolve(projectDir, 'notes/sub/.ok/templates/meeting.md'), // nested leafresolve(projectDir, '.ok/templates/a/b.md'), // nested below templates dir- resolve(projectDir, '.ok/templates/Bad Name.md'), // space in name- resolve(projectDir, 'x.ok/templates/t.md'), // `.ok/templates` not a clean boundary]) {- expect(managedArtifactDocNameForPath(bad, ctx)).toBeNull();+ expect(managedArtifactDocNameForPath(path, ctx)).toBeNull();}});@@ -546,15 +564,11 @@ describe('managedArtifactContributorAttribution (editor-edit versioning)', () =>expect(managedArtifactContributorAttribution('__skill__/global/notes')).toBeNull();});- test('templates → folder-addressed .ok/templates key + template- subject', () => {- expect(managedArtifactContributorAttribution('__template__/daily')).toEqual({- docKey: '.ok/templates/daily',- subject: 'template-edit: .ok/templates/daily.md',- });- expect(managedArtifactContributorAttribution('__template__/notes/sub/meeting')).toEqual({- docKey: 'notes/sub/.ok/templates/meeting',- subject: 'template-edit: notes/sub/.ok/templates/meeting.md',- });+ test('template name → null (content doc — attributed on its own path by the content store)', () => {+ // A `__template__/…` name resolves to no managed docKey: templates are+ // content docs, versioned on their real path by the content store, not here.+ expect(managedArtifactContributorAttribution('__template__/daily')).toBeNull();+ expect(managedArtifactContributorAttribution('__template__/notes/sub/meeting')).toBeNull();});test('non-managed-artifact name → null', () => {@@ -589,21 +603,6 @@ describe('managedArtifactTimelinePaths', () => {});});- test('template → versioned, folder-addressed key + <name>.md leaf', () => {- expect(managedArtifactTimelinePaths('__template__/docs/guides/note')).toEqual({- managed: true,- versioned: true,- docKey: 'docs/guides/.ok/templates/note',- filePath: 'docs/guides/.ok/templates/note.md',- });- expect(managedArtifactTimelinePaths('__template__/note')).toEqual({- managed: true,- versioned: true,- docKey: '.ok/templates/note',- filePath: '.ok/templates/note.md',- });- });-test('global skill → managed but unversioned (no shadow history)', () => {expect(managedArtifactTimelinePaths('__skill__/global/my-skill')).toEqual({managed: true,@@ -775,7 +774,7 @@ describe('a skill doc never RESURRECTS a bundle that is gone', () => {});});-describe('the liveness rule covers external skills too, but never templates', () => {+describe('the liveness rule covers external skills too', () => {// The container is lost through a different door per skill class, but the// failure is identical: a stale autosave rebuilds it around a single file.function editLive(doc: Y.Doc, text: string): void {@@ -786,21 +785,6 @@ describe('the liveness rule covers external skills too, but never templates', ()}, 'agent');}- test('a template still CREATES `.ok/templates`, because that is how templates are written', async () => {- // Deliberately not bounded: `PUT /api/template` routes the composed bytes- // through the template's CRDT doc and leaves the file write to persistence,- // so requiring the dir up front would break every template create.- const ctx = makeCtx();- const docName = '__template__//weekly-note';- const filePath = managedArtifactAbsPath(docName, ctx);- const doc = new Y.Doc();- loadManagedArtifactDoc(doc, docName, ctx);-- editLive(doc, '# Weekly note\n');- expect(await storeManagedArtifactDoc(doc, docName, 'agent', ctx)).toBe('persisted');- expect(readFileSync(filePath, 'utf-8')).toBe('# Weekly note\n');- });-test('an external skill deleted by its harness is not rebuilt under the harness root', async () => {// Registration is in-memory and `unregisterExternalSkill` never runs outside// tests, so the registry outlives a harness-side delete. Without thediff --git a/packages/server/src/managed-artifact-persistence.ts b/packages/server/src/managed-artifact-persistence.tsindex da970d2ce..d21486042 100644--- a/packages/server/src/managed-artifact-persistence.ts+++ b/packages/server/src/managed-artifact-persistence.ts@@ -1,7 +1,10 @@/**- * Persistence for managed-artifact docs — skills (`__skill__/<scope>/<name>`)- * and templates (`__template__/<folderRel>/<name>`). The CRDT amendment- * makes these first-class CRDT documents that persist to `.ok/`.+ * Persistence for managed-artifact docs — skills (`__skill__/<scope>/<name>`).+ * The CRDT amendment makes these first-class CRDT documents that persist to+ * `.ok/`. Templates are ordinary content docs now (`<folder>/.ok/templates/<name>`,+ * hydrated by the content persistence path); the retired `__template__/…`+ * synthetic name survives here only as a load/store tombstone so a stale client+ * name never seeds a second doc or writes a literal `__template__/…` file.** Shape: a HYBRID of the two existing persistence branches.* - LOAD/STORE BODY mirrors the *document* branch (`persistence.ts`@@ -35,7 +38,6 @@ import {parseExternalSkillDocName,parseManagedArtifactName,SKILL_NAME_REGEX,- TEMPLATE_NAME_REGEX,} from '@inkeep/open-knowledge-core';import {atomicWriteFile,@@ -116,47 +118,44 @@ export function homeFor(ctx: Pick<ManagedArtifactCtx, 'homedirOverride'>): strin}/**- * The `.ok/` artifact key + shadow-commit subject for a managed-artifact doc, so- * an EDITOR-driven CRDT edit can be attributed + versioned exactly like the HTTP+ * The `.ok/` artifact key + shadow-commit subject for a managed skill doc, so an+ * EDITOR-driven CRDT edit can be attributed + versioned exactly like the HTTP* `write`/`edit` path does via `attributeOkArtifactWrite`. The key must match the- * timeline query's doc-key (`.ok/skills/<name>` / `<folder>/.ok/templates/<name>`,- * NOT the synthetic `__skill__/...` doc name) and the subject must carry the- * `skill-`/`template-` action prefix the timeline filters on.+ * timeline query's doc-key (`.ok/skills/<name>`, NOT the synthetic+ * `__skill__/...` doc name) and the subject carries the `skill-` action prefix+ * the timeline filters on.*- * Returns `null` for unversioned artifacts: global skills live outside any- * project shadow repo, so there is nothing to version.+ * Returns `null` for anything unversioned: global skills live outside any+ * project shadow repo, and templates are content docs attributed on their own+ * path by the content store — neither resolves to a managed docKey here.*/export function managedArtifactContributorAttribution(documentName: string,): { docKey: string; subject: string } | null {const parsed = parseManagedArtifactName(documentName);- if (parsed === null) return null;- if (parsed.kind === 'skill') {- if (parsed.scope !== 'project') return null; // global = unversioned- return {- docKey: `${LEGACY_SKILL_STORE_ROOT}/${parsed.name}`,- subject: `skill-edit: ${parsed.name}/SKILL.md`,- };- }- const folder = parsed.folder.replace(/\/$/, '');- const docKey = `${folder ? `${folder}/` : ''}.ok/templates/${parsed.name}`;- return { docKey, subject: `template-edit: ${docKey}.md` };+ if (parsed === null || parsed.kind !== 'skill' || parsed.scope !== 'project') return null;+ return {+ docKey: `${LEGACY_SKILL_STORE_ROOT}/${parsed.name}`,+ subject: `skill-edit: ${parsed.name}/SKILL.md`,+ };}/**- * The shadow-repo paths for a managed-artifact doc, derived once so every+ * The shadow-repo paths for a managed skill doc, derived once so every* timeline-family subsystem (history pathspec + OkActor filter, version read,* diff, rollback) addresses the same key the write path commits under. The- * synthetic `__skill__/...` / `__template__/...` doc name the editor uses never- * matches on disk — this is the single translation point that bridges it.+ * synthetic `__skill__/...` doc name the editor uses never matches on disk —+ * this is the single translation point that bridges it. Templates resolve to+ * `{ managed: false }` here: their doc name IS their real committed content path,+ * so the ordinary `pathFor` translation applies with no managed detour.** - `{ managed: false }` — not a managed-artifact name (ordinary doc)* - `{ managed: true, versioned: false }` — global skill: lives outside any* project shadow repo, so there is no version history to address- * - `{ managed: true, versioned: true, docKey, filePath }` — project skill /- * template: `docKey` (`.ok/skills/<name>` / `<folder>/.ok/templates/<name>`)- * drives OkActor matching; `filePath` (the SKILL.md / `<name>.md` leaf) is- * the content-root-relative git path commits actually touch.+ * - `{ managed: true, versioned: true, docKey, filePath }` — project skill:+ * `docKey` (`.ok/skills/<name>`) drives OkActor matching; `filePath` (the+ * bundle's `SKILL.md` leaf) is the content-root-relative git path commits+ * actually touch.*/export function managedArtifactTimelinePaths(documentName: string,@@ -166,10 +165,16 @@ export function managedArtifactTimelinePaths(| { managed: true; versioned: true; docKey: string; filePath: string } {const parsed = parseManagedArtifactName(documentName);if (!parsed) return { managed: false };+ // `attr` is non-null only for a project skill (global skills are unversioned+ // above), whose committed leaf is the bundle's `SKILL.md`.const attr = managedArtifactContributorAttribution(documentName);if (!attr) return { managed: true, versioned: false };- const filePath = parsed.kind === 'skill' ? `${attr.docKey}/SKILL.md` : `${attr.docKey}.md`;- return { managed: true, versioned: true, docKey: attr.docKey, filePath };+ return {+ managed: true,+ versioned: true,+ docKey: attr.docKey,+ filePath: `${attr.docKey}/SKILL.md`,+ };}/**@@ -185,17 +190,15 @@ export function managedArtifactSkillsRoots(ctx: ManagedArtifactCtx): string[] {}/**- * Resolve the on-disk path for a managed-artifact doc name.+ * Resolve the on-disk path for a managed skill doc name.** Security: the name segment is OPEN (one per artifact), unlike the bounded* config-doc set, so the resolver guards on (1) the name slug grammar- * (`SKILL_NAME_REGEX` / `TEMPLATE_NAME_REGEX`), (2) for templates, a folder that- * stays under `projectDir` (no `..`), and (3) the resolved path staying within- * the expected `.ok/{skills,templates}` root. Any failure throws — a malformed- * name/folder must never write outside `.ok/`.+ * (`SKILL_NAME_REGEX`), and (2) the resolved path staying within the expected+ * `.ok/skills` root. Any failure throws — a malformed name must never write+ * outside `.ok/`.*- * - skill → `<scope-root>/.ok/skills/<name>/SKILL.md`- * - template → `<projectDir>/<folder>/.ok/templates/<name>.md`+ * - skill → `<scope-root>/.ok/skills/<name>/SKILL.md`*//** Bind an ext-less skill bundle-file base path to the real file on disk: `.md`* preferred, `.mdx` fallback, default `.md` for a not-yet-created file. Shared@@ -270,14 +273,8 @@ function managedSkillBundleDir(* worst place to get this wrong: the resurrected dir lands under a harness root* (`~/.claude/skills/…`) that OK does not own.*- * Templates are deliberately NOT bounded. `PUT /api/template` composes the- * bytes, routes them through the template's CRDT doc, and leaves the file write- * to persistence — so creating `.ok/templates` here is how a template gets- * created, not evidence of a stale doc, and the container alone cannot tell the- * two apart.- *- * Null means "nothing to bound" (a template, or an unparsable / unregistered- * doc name); the latter are already short-circuited upstream.+ * Null means "nothing to bound" (an unparsable / unregistered doc name); those+ * are already short-circuited upstream.*/function managedArtifactContainerDir(documentName: string,@@ -311,11 +308,8 @@ export function managedArtifactAbsPath(documentName: string, ctx: ManagedArtifacreturn ext.rel === null ? abs : resolveBundleFileOnDisk(abs);}const parsed = parseManagedArtifactName(documentName);- if (parsed === null) {- throw new Error(`managedArtifactAbsPath: not a managed-artifact doc name: ${documentName}`);- }- if (parsed.kind === 'template') {- return templateAbsPath(parsed.folder, parsed.name, ctx, documentName);+ if (parsed === null || parsed.kind !== 'skill') {+ throw new Error(`managedArtifactAbsPath: not a managed skill doc name: ${documentName}`);}const skillDir = managedSkillBundleDir(parsed.scope, parsed.name, ctx);let abs: string;@@ -334,55 +328,19 @@ export function managedArtifactAbsPath(documentName: string, ctx: ManagedArtifac// Guard 2: containment on the resolved path. Cheap defense-in-depth — the slug// grammar in `managedSkillBundleDir` (guard 1, which now runs a call earlier)// plus the `..` reject above already forbid escape, so this only fires if that- // grammar is ever weakened. (Mirrors templateAbsPath.)+ // grammar is ever weakened.if (!abs.startsWith(skillDir + sep)) {throw new Error(`managedArtifactAbsPath: path escape for ${documentName}`);}return abs;}-/** Normalize a project-root-relative folder (strip leading/trailing slashes). */-function normalizeTemplateFolder(folder: string): string {- return folder.replace(/^\/+/, '').replace(/\/+$/, '');-}--/**- * Resolve `<projectDir>/<folder>/.ok/templates/<name>.md` with escape guards.- * `folder` is project-root-relative (`''` = root, may be nested); `name` is the- * `.md`-less filename.- */-function templateAbsPath(- folder: string,- name: string,- ctx: Pick<ManagedArtifactCtx, 'projectDir'>,- documentName: string,-): string {- if (!TEMPLATE_NAME_REGEX.test(name) || name.length > 64) {- throw new Error(`managedArtifactAbsPath: invalid template name: ${JSON.stringify(name)}`);- }- const folderRel = normalizeTemplateFolder(folder);- if (folderRel.split('/').includes('..')) {- throw new Error(`managedArtifactAbsPath: template folder escape for ${documentName}`);- }- const projectAbs = resolve(ctx.projectDir);- const folderAbs = folderRel ? resolve(projectAbs, folderRel) : projectAbs;- if (folderAbs !== projectAbs && !folderAbs.startsWith(projectAbs + sep)) {- throw new Error(`managedArtifactAbsPath: template folder escape for ${documentName}`);- }- const templatesDir = resolve(folderAbs, '.ok', 'templates');- const abs = resolve(templatesDir, `${name}.md`);- if (!abs.startsWith(templatesDir + sep)) {- throw new Error(`managedArtifactAbsPath: path escape for ${documentName}`);- }- return abs;-}-/*** Reverse of {@link managedArtifactAbsPath}: map an on-disk leaf path back to its- * `__skill__/<scope>/<name>` or `__template__/<folderRel>/<name>` doc name, or- * `null` when the path is not a well-formed managed-artifact leaf. Used by the- * file-watcher (`.ok/` is watcher-excluded by default, so disk edits reach a- * live doc only via the explicit managed-artifact watch).+ * `__skill__/<scope>/<name>` doc name, or `null` when the path is not a+ * well-formed managed skill leaf. Used by the global-skills watcher (`<home>/.ok/`+ * is watcher-excluded, so disk edits reach a live global-skill doc only via the+ * explicit managed-artifact watch).** Applies the same slug grammar as the forward resolver so a path with an* invalid name segment is rejected rather than routed to a malformed doc name.@@ -421,30 +379,6 @@ export function managedArtifactDocNameForPath(}return null; // under a global skills root but not an editable md doc}- // Template: `<projectDir>/<folderRel>/.ok/templates/<name>.md`.- if (norm.endsWith('.md')) {- const projectAbs = resolve(ctx.projectDir);- if (norm !== projectAbs && !norm.startsWith(projectAbs + sep)) return null;- const rel = norm === projectAbs ? '' : norm.slice(projectAbs.length + 1);- const marker = `.ok${sep}templates${sep}`;- const idx = rel.indexOf(marker);- if (idx < 0) return null;- // `.ok/templates/` must be a clean path boundary: at the start, or preceded- // by a separator (so `x.ok/templates` can't false-match).- if (idx > 0 && rel[idx - 1] !== sep) return null;- const after = rel.slice(idx + marker.length);- if (after.includes(sep) || !after.endsWith('.md')) return null; // single .md leaf- const name = after.slice(0, -3);- if (!TEMPLATE_NAME_REGEX.test(name) || name.length > 64) return null;- const folderRel = idx === 0 ? '' : rel.slice(0, idx - 1);- const folderEncoded = folderRel- ? folderRel- .split(sep)- .map((s) => encodeURIComponent(s))- .join('/')- : '';- return `${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${folderEncoded ? `${folderEncoded}/` : ''}${encodeURIComponent(name)}`;- }return null;}@@ -466,6 +400,13 @@ export function loadManagedArtifactDoc(const parsed = parseManagedArtifactName(documentName);if (parsed?.kind === 'skill' && parsed.scope === 'project') return;+ // Templates are content docs now (`<folder>/.ok/templates/<name>`), hydrated+ // via the normal content persistence path. The retired `__template__/...`+ // synthetic name is a tombstone — refuse to seed it so a stale client name+ // never becomes a SECOND CRDT doc competing with the content doc for one file+ // (double-doc corruption), and never mints a lineage epoch for a dead name.+ if (documentName.startsWith(MANAGED_ARTIFACT_PREFIX_TEMPLATE)) return;+// Editable-unmanaged skill whose external dir was never registered (e.g. a// server restart dropped the in-memory registry): nothing to seed, no-op —// don't let `managedArtifactAbsPath` throw out of `onLoadDocument`.@@ -592,6 +533,11 @@ export async function storeManagedArtifactDoc(const parsedStore = parseManagedArtifactName(documentName);if (parsedStore?.kind === 'skill' && parsedStore.scope === 'project') return 'no-op';+ // Templates persist through the content path; never write the retired+ // `__template__/...` synthetic doc back to disk (see load guard) — that would+ // create a literal `__template__/...` file.+ if (documentName.startsWith(MANAGED_ARTIFACT_PREFIX_TEMPLATE)) return 'no-op';+// Editable-unmanaged skill whose external dir isn't registered: nothing to// write back to (see load guard).const extStore = parseExternalSkillDocName(documentName);diff --git a/packages/server/src/managed-artifact-watcher.test.ts b/packages/server/src/managed-artifact-watcher.test.tsindex ce5d958b1..fd540a46e 100644--- a/packages/server/src/managed-artifact-watcher.test.ts+++ b/packages/server/src/managed-artifact-watcher.test.ts@@ -64,7 +64,6 @@ describe.skipIf(RUNNING_IN_CI)('startManagedArtifactWatcher', () => {cleanup = await startManagedArtifactWatcher([skillsRoot],(p) => changed.push(p),- undefined,(p) => unlinked.push(p),);diff --git a/packages/server/src/managed-artifact-watcher.ts b/packages/server/src/managed-artifact-watcher.tsindex b178c1f79..04f25e70e 100644--- a/packages/server/src/managed-artifact-watcher.ts+++ b/packages/server/src/managed-artifact-watcher.ts@@ -33,37 +33,15 @@ import { getLogger } from './logger.ts';/** Cleanup function returned by `startManagedArtifactWatcher`. Idempotent. */export type ManagedArtifactWatcherUnsubscribe = () => Promise<void>;-export interface ManagedArtifactWatchOptions {- /**- * chokidar `depth` for the watched roots. Skills nest one level- * (`<name>/SKILL.md`, depth 1); templates are flat (`<name>.md` directly in- * the watched `.ok/templates` dir, depth 0).- */- depth: number;- /** True for a path that is a managed-artifact leaf (e.g. `SKILL.md` / `*.md`). */- acceptLeaf: (absPath: string) => boolean;-}--/** Skills: nested `<name>/SKILL.md` (the default). */-const SKILL_WATCH_OPTIONS: ManagedArtifactWatchOptions = {- depth: 1,- acceptLeaf: (p) => basename(p) === 'SKILL.md',-};--/** Templates: flat `<name>.md` directly in a `.ok/templates` dir. */-export const TEMPLATE_WATCH_OPTIONS: ManagedArtifactWatchOptions = {- depth: 0,- // Skip atomic-write temp files (`<name>.md.tmp.<pid>.<ts>`) — they end in a- // numeric suffix, not `.md`.- acceptLeaf: (p) => basename(p).endsWith('.md'),-};+/** True for a managed-artifact leaf we reconcile: the `SKILL.md` file. */+const isSkillLeaf = (absPath: string): boolean => basename(absPath) === 'SKILL.md';/*** Watch one or more managed-artifact root directories for leaf-file changes.* Resolves once chokidar's initial scan completes (`ready`), so callers/tests* can write immediately without racing the first event.*- * On `add` / `change` of a leaf (per `opts.acceptLeaf`): reads the file and+ * On `add` / `change` of a leaf (per `isSkillLeaf`): reads the file and* fires `onChange(absPath, content)`. `unlink` does NOT fire `onChange` (the* live doc retains its current state — deletion of live content is a separate,* explicit surface) but DOES fire the optional `onUnlink(absPath)`, so callers@@ -74,7 +52,6 @@ export const TEMPLATE_WATCH_OPTIONS: ManagedArtifactWatchOptions = {export async function startManagedArtifactWatcher(roots: ReadonlyArray<string>,onChange: (absPath: string, content: string) => void,- opts: ManagedArtifactWatchOptions = SKILL_WATCH_OPTIONS,onUnlink?: (absPath: string) => void,): Promise<ManagedArtifactWatcherUnsubscribe> {const log = getLogger('managed-artifact-watcher');@@ -96,10 +73,11 @@ export async function startManagedArtifactWatcher(}// Leaf filtering happens in the handler (atomic-write `.tmp.<uuid>` siblings- // are dropped by `acceptLeaf`).+ // are dropped by `isSkillLeaf`).const watcher = watch(watchRoots, {ignoreInitial: true,- depth: opts.depth,+ // Skills nest one level under the root: `<name>/SKILL.md`.+ depth: 1,usePolling: true,interval: 200,awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 },@@ -112,7 +90,7 @@ export async function startManagedArtifactWatcher(const lastContent = new Map<string, string | null>();const handlePath = (path: string): void => {- if (!opts.acceptLeaf(path)) return;+ if (!isSkillLeaf(path)) return;let content: string;try {content = readFileSync(path, 'utf-8');@@ -138,7 +116,7 @@ export async function startManagedArtifactWatcher(watcher.on('add', handler);watcher.on('change', handler);watcher.on('unlink', (path) => {- if (!opts.acceptLeaf(path)) return;+ if (!isSkillLeaf(path)) return;lastContent.delete(path);log.debug({ path }, 'managed-artifact leaf unlinked; live doc retained at current state');if (onUnlink) {diff --git a/packages/server/src/mcp/tools/shared.test.ts b/packages/server/src/mcp/tools/shared.test.tsindex fa7ed63dc..55a662b95 100644--- a/packages/server/src/mcp/tools/shared.test.ts+++ b/packages/server/src/mcp/tools/shared.test.ts@@ -898,6 +898,26 @@ describe('okReservedPathRedirect', () => {expect(okReservedPathRedirect('.ok/templates/note')).toContain('`template` target');});+ test('a raw document write into .ok/templates is refused, not admitted as a content doc (D7)', () => {+ // Templates became ordinary content docs (the content filter admits+ // `.ok/templates` for reading and watching), but the raw-write refusal is a+ // separate chokepoint that must stay closed: the `template` verb is the only+ // authoring route. `normalizeDocName` must still reject the dot-segment path+ // so `write` / `edit` surface the teaching redirect in place of the generic+ // error — the read carve-out must not leak into the write path.+ const path = '.ok/templates/standup';+ expect(normalizeDocName(path).ok).toBe(false);+ expect(okReservedPathRedirect(path)).toContain('`template` target');++ // The carve-out is segment-shaped — templates live at arbitrary depth — so+ // the refusal must hold for a nested folder's templates dir too, not just+ // the project-root form. (The teaching redirect stays root-anchored; the+ // nested form surfaces the generic dot-segment error instead.)+ const nested = 'notes/.ok/templates/standup';+ expect(normalizeDocName(nested).ok).toBe(false);+ expect(okReservedPathRedirect(nested)).toBeNull();+ });+test('other .ok/ path → generic .ok redirect', () => {expect(okReservedPathRedirect('.ok/config/whatever')).toContain('not addressable as documents');});diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.tsindex 86658729a..f9a5f7131 100644--- a/packages/server/src/persistence.ts+++ b/packages/server/src/persistence.ts@@ -1484,12 +1484,19 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis* live in this closure and importing them into the artifact module would* close a cycle.*- * The anchor is filed under the artifact's TIMELINE key- * (`.ok/skills/<name>` / `<folder>/.ok/templates/<name>`), not the synthetic- * `__skill__` / `__template__` doc name, so it addresses the same path the+ * The anchor is filed under the artifact's TIMELINE key (`.ok/skills/<name>`),+ * not the synthetic `__skill__` doc name, so it addresses the same path the* history surface reads. Global skills live outside any project shadow repo* and are unversioned by construction — they get the ring breadcrumb and the* detector, but no anchor, because there is nowhere to file one.+ *+ * The anchored (versioned) branch below — the one that writes an actual+ * `managed-artifact-reconcile` checkpoint — is currently UNREACHABLE: the only+ * artifacts that reach this hook are global + external skills, both+ * unversioned, so the `!paths.versioned` early return always wins. Templates+ * were the last versioned artifact routed here; they are ordinary content docs+ * now, reconciled on the content path. Re-add an anchor-writing regression test+ * if a new versioned managed-artifact class is ever introduced.*/function checkpointBeforeManagedArtifactReconcile(document: Y.Doc,@@ -2829,8 +2836,9 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis);// Version editor-driven CRDT edits exactly like a regular doc: an// attributed shadow commit per edit, recorded under the `.ok/` artifact- // key + `skill-`/`template-` subject the timeline filters on (so the edit- // surfaces in skill history / the folder timeline). This is the SAME+ // key + `skill-` subject the timeline filters on (so the edit surfaces+ // in skill history). Templates are content docs and never reach this+ // managed branch. This is the SAME// safety-net `storeDocumentNow` uses for browser writes: MCP `write`/// `edit` go through agent sessions and are attributed by the// api-extension handler (rich actor + summary), so the store skips agentdiff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex 6a7df9c17..04741f7f6 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -88,7 +88,6 @@ import {createConflictLifecycleSeedExtension,entryMatchesDocName,} from './conflict-lifecycle-seed.ts';-import { resolveProjectTemplates } from './content/templates-resolver.ts';import { type ContentFilter, createContentFilter } from './content-filter.ts';import { isWithinContentDir, safeContentPath } from './content-path.ts';import { dropPendingDocs, recordContributor } from './contributor-tracker.ts';@@ -149,7 +148,7 @@ import {managedArtifactDocNameForPath,managedArtifactSkillsRoots,} from './managed-artifact-persistence.ts';-import { startManagedArtifactWatcher, TEMPLATE_WATCH_OPTIONS } from './managed-artifact-watcher.ts';+import { startManagedArtifactWatcher } from './managed-artifact-watcher.ts';import { recoverPendingManagedRename } from './managed-rename-journal.ts';import { mdManager, schema } from './md-manager.ts';import {@@ -3541,7 +3540,6 @@ export function createServer(options: ServerOptions): ServerInstance {const skillsCleanup = await startManagedArtifactWatcher(skillsRoots,reconcileManagedArtifactDisk,- undefined,handleManagedArtifactUnlink,);configFileWatcherCleanups.push({ docName: '__skill-files__', cleanup: skillsCleanup });@@ -3575,38 +3573,6 @@ export function createServer(options: ServerOptions): ServerInstance {log.warn({ err }, '[skill-state-watcher] failed to start');degraded.push('skill-state-watcher');}-- // Template watcher. Templates live in any folder's `.ok/templates/`, so the- // watch roots are enumerated from the existing templates at boot (plus the- // project root). Bounded — a template created in a BRAND-NEW folder mid-- // session is reconciled only after a restart; the common case (editing a- // template that existed at boot) is covered.- try {- const templateFolders = new Set<string>(['']);- try {- for (const t of (await resolveProjectTemplates(projectDir)).templates) {- templateFolders.add(t.source_folder);- }- } catch (err) {- log.warn({ err }, '[managed-artifact-watcher] template enumeration failed; root only');- }- const templateRoots = [...templateFolders].map((f) =>- f ? resolve(projectDir, f, '.ok', 'templates') : resolve(projectDir, '.ok', 'templates'),- );- const templateCleanup = await startManagedArtifactWatcher(- templateRoots,- reconcileManagedArtifactDisk,- TEMPLATE_WATCH_OPTIONS,- );- configFileWatcherCleanups.push({ docName: '__template-files__', cleanup: templateCleanup });- log.info(- { rootCount: templateRoots.length },- '[managed-artifact-watcher] templates started',- );- } catch (err) {- log.warn({ err }, '[managed-artifact-watcher] templates failed to start');- degraded.push('managed-artifact-watcher:templates');- }}// Multi-path ignore-file watcher: root `.okignore` + root `.gitignore`.diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.tsindex 91592d86b..845e5d7b4 100644--- a/packages/server/src/sync-engine.test.ts+++ b/packages/server/src/sync-engine.test.ts@@ -1528,6 +1528,107 @@ describe('SyncEngine push cycle with non-ASCII filenames', () => {});});+describe('SyncEngine push cycle vs gitignored content (precedent #55 at the staging boundary)', () => {+ // Content admission is broader than git sync scope for managed artifacts:+ // the content filter admits `<folder>/.ok/templates/*.md` even when a+ // local-only-sharing project excludes `.ok/` via `.git/info/exclude`.+ // Naming such a path in `git add` fatals with `addIgnoredFile`, which used+ // to wedge every push cycle. The stub filter admits everything, standing in+ // for that carve-out.+ const templatePath = join('trips', '.ok', 'templates', 'article.md');+ const templateRel = 'trips/.ok/templates/article.md';++ async function initRepoWithBareRemote() {+ const git = simpleGit(projectDir);+ await git.init(['--initial-branch=main']);+ await git.raw('config', 'user.name', 'Test');+ await git.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(projectDir, 'README.md'), '# Test\n');+ await git.add('.');+ await git.commit('Initial');++ const bareDir = join(tmpDir, 'bare.git');+ mkdirSync(bareDir, { recursive: true });+ await simpleGit(bareDir).init(true);+ await git.addRemote('origin', bareDir);+ await git.push(['--set-upstream', 'origin', 'main']);+ return git;+ }++ function makePushEngine() {+ return new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ syncEnabled: true,+ });+ }++ test('skips untracked ignored paths instead of failing the whole push cycle', async () => {+ const git = await initRepoWithBareRemote();+ writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.ok/\n');++ mkdirSync(join(projectDir, 'trips', '.ok', 'templates'), { recursive: true });+ writeFileSync(join(projectDir, templatePath), '# Template\n');+ writeFileSync(join(projectDir, 'note.md'), 'new note\n');++ const engine = makePushEngine();+ try {+ await engine.start();+ await engine.trigger('push');++ const status = engine.getStatus();+ expect(status.pushError).toBeUndefined();+ expect(status.consecutiveFailures).toBe(0);++ const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);+ expect(headPaths).toContain('note.md');+ expect(headPaths).not.toContain(templateRel);++ const remoteHead = (await git.revparse(['origin/main'])).trim();+ expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());+ } finally {+ await engine.destroy();+ }+ });++ test('keeps syncing edits to a tracked file that an ignore rule also matches', async () => {+ // git's ignore rules never apply to tracked files, so a template that was+ // committed while the project was in shared mode must keep syncing after a+ // switch to local-only. This also pins the deletion-set pairing: a filter+ // consulting an unseeded index would misread the file as untracked, skip+ // it, and commit its HEAD entry as a deletion.+ const git = await initRepoWithBareRemote();+ mkdirSync(join(projectDir, 'trips', '.ok', 'templates'), { recursive: true });+ writeFileSync(join(projectDir, templatePath), '# Template v1\n');+ await git.add('.');+ await git.commit('add template while shared');+ await git.push(['origin', 'main']);++ writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.ok/\n');+ writeFileSync(join(projectDir, templatePath), '# Template v2\n');++ const engine = makePushEngine();+ try {+ await engine.start();+ await engine.trigger('push');++ const status = engine.getStatus();+ expect(status.pushError).toBeUndefined();++ const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);+ expect(headPaths).toContain(templateRel);+ const blob = await git.raw(['show', `HEAD:${templateRel}`]);+ expect(blob).toBe('# Template v2\n');++ const remoteHead = (await git.revparse(['origin/main'])).trim();+ expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());+ } finally {+ await engine.destroy();+ }+ });+});+describe('SyncEngine per-operation error isolation', () => {// Regression: a single shared error field let a successful fetch clear a// failed push's error, so the sync popover flashed the push error for adiff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.tsindex bb998e0c7..c2ede02d4 100644--- a/packages/server/src/sync-engine.ts+++ b/packages/server/src/sync-engine.ts@@ -21,6 +21,7 @@ import { join, relative, resolve } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';import { promisify } from 'node:util';import {+ OK_DIR,type PullOutcome,type SyncMode,type SyncModeChangeSource,@@ -2429,16 +2430,11 @@ export class SyncEngine {const headContentSet = await this.listHeadContentPaths(handle, headSha);// ── 4. Stage working-tree content files into isolated index ────────────- if (contentFiles.length > 0) {- const BATCH = 100; // avoid ARG_MAX- for (let i = 0; i < contentFiles.length; i += BATCH) {- const batch = contentFiles.slice(i, i + BATCH).map((f) => f.projectRelPath);- await handle.git.raw(['add', '--', ...batch]);- }- }+ // After the read-tree seed above, so trackedness reflects HEAD.+ const staged = await this.stageContentFiles(handle, contentFiles);// ── 5. Remove deleted content files from isolated index ────────────────- const onDiskSet = new Set(contentFiles.map((f) => f.projectRelPath));+ const onDiskSet = new Set(staged.map((f) => f.projectRelPath));const deleted = [...headContentSet].filter((f) => !onDiskSet.has(f));await this.removePathsFromIndex(handle, deleted);@@ -2721,12 +2717,9 @@ export class SyncEngine {const isoHandle = this.gitHandle(tmpIndex);try {await isoHandle.git.raw(['read-tree', headSha]);- const BATCH = 100;- for (let i = 0; i < contentFiles.length; i += BATCH) {- const batch = contentFiles.slice(i, i + BATCH).map((f) => f.projectRelPath);- await isoHandle.git.raw(['add', '--', ...batch]);- }- const onDiskSet = new Set(contentFiles.map((f) => f.projectRelPath));+ // After the read-tree seed, so trackedness reflects HEAD.+ const staged = await this.stageContentFiles(isoHandle, contentFiles);+ const onDiskSet = new Set(staged.map((f) => f.projectRelPath));const deleted = [...headContentSet].filter((f) => !onDiskSet.has(f));await this.removePathsFromIndex(isoHandle, deleted);const newTreeSha = (await isoHandle.git.raw(['write-tree'])).trim();@@ -2894,6 +2887,76 @@ export class SyncEngine {}}+ /**+ * Stage content files into the handle's index, dropping ignored-AND-untracked+ * paths first. Content scope is broader than git scope: the content filter+ * admits `<folder>/.ok/templates/*.md` regardless of ignore state so templates+ * stay visible in the editor, but a local-only-sharing project excludes `.ok/`+ * in `.git/info/exclude`, and naming such a path in `git add` fatals with+ * `addIgnoredFile`, wedging every push cycle. Precedent #55 (walker and+ * `git add` agree on scope) is enforced here rather than in content admission.+ *+ * Tracked files are exempt from ignore rules and must keep syncing, but+ * `git add` (Apple git 2.39.5) still refuses a named path under an ignored+ * directory even when tracked — so paths carrying a `.ok/` segment (the only+ * carve-out shape content admission holds above git scope) are added with+ * `-f`. Everything else keeps the plain fail-loud `add`: if the probe and the+ * add ever disagree (a future git version, a `.gitattributes` edge), an+ * unexpected refusable path surfaces as an error instead of being silently+ * force-added. On probe failure, stage unfiltered WITHOUT `-f` and let the+ * old error surface.+ *+ * Call only after the caller's `read-tree` seed: against an empty index a+ * tracked-but-ignored file reads as refusable and its HEAD entry would be+ * committed as a deletion. Returns the staged files for deletion-set pairing.+ */+ private async stageContentFiles(+ handle: GitHandle,+ files: ContentFileEntry[],+ ): Promise<ContentFileEntry[]> {+ if (files.length === 0) return files;+ const BATCH = 100; // avoid ARG_MAX+ const refused = new Set<string>();+ let probeOk = true;+ for (let i = 0; i < files.length; i += BATCH) {+ const batch = files.slice(i, i + BATCH).map((f) => f.projectRelPath);+ try {+ const ignored = await listNames(handle.git, [+ 'ls-files',+ '--others',+ '--ignored',+ '--exclude-standard',+ '--',+ ...batch,+ ]);+ for (const p of ignored) refused.add(p);+ } catch (err) {+ probeOk = false;+ log.warn({ err }, '[sync] ignored-path probe failed — staging unfiltered without -f');+ }+ }+ if (refused.size > 0) {+ log.info(+ { count: refused.size, sample: [...refused].slice(0, 5) },+ '[sync] skipping gitignored untracked path(s) — in content scope but excluded from git',+ );+ }+ const stageable = probeOk ? files.filter((f) => !refused.has(f.projectRelPath)) : files;+ const hasOkSegment = (p: string) => p.startsWith(`${OK_DIR}/`) || p.includes(`/${OK_DIR}/`);+ const forced = probeOk ? stageable.filter((f) => hasOkSegment(f.projectRelPath)) : [];+ const plain = probeOk ? stageable.filter((f) => !hasOkSegment(f.projectRelPath)) : stageable;+ for (const [addArgs, group] of [+ [['add', '--'], plain],+ [['add', '-f', '--'], forced],+ ] as const) {+ for (let i = 0; i < group.length; i += BATCH) {+ const batch = group.slice(i, i + BATCH).map((f) => f.projectRelPath);+ await handle.git.raw([...addArgs, ...batch]);+ }+ }+ return stageable;+ }+/*** Recursively walk contentDir and return all files that pass ContentFilter.* Uses synchronous FS because this runs under the parentGitMutex.diff --git a/packages/server/src/timeline-query.test.ts b/packages/server/src/timeline-query.test.tsindex 5b6522987..ea9e810a5 100644--- a/packages/server/src/timeline-query.test.ts+++ b/packages/server/src/timeline-query.test.ts@@ -2,7 +2,8 @@ import { execFileSync } from 'node:child_process';import { mkdirSync, rmSync, writeFileSync } from 'node:fs';import { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';-import { resolve } from 'node:path';+import { dirname, resolve } from 'node:path';+import { templateContentDocName } from '@inkeep/open-knowledge-core';import { formatOkActor, type OkActorEntry } from '@inkeep/open-knowledge-core/shadow-repo-layout';import simpleGit from 'simple-git';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';@@ -27,7 +28,7 @@ import {saveVersion,type WriterIdentity,} from './shadow-repo';-import { getDocumentHistory, historyWalkCap } from './timeline-query';+import { getDocumentHistory, getFolderTimeline, historyWalkCap } from './timeline-query';let tmpDir: string;@@ -1101,3 +1102,199 @@ describe('depth-bound history walk (PRD-6972 FR3 / D14)', () => {expect(result.entries).toHaveLength(10);}, 60_000);});++describe('getDocumentHistory + getFolderTimeline — templates as content (FR6 / D11)', () => {+ // A template is now an ordinary content doc at `<folder>/.ok/templates/<name>`.+ // Every lifecycle write — HTTP typed writes AND editor CRDT edits — attributes+ // under that one content-relative key (byte-equal to okArtifactKey('template',+ // …) and to the client's doc name), which is why the timeline stays whole.+ // These helpers hand-build that shared-key shadow history so the query+ // behavior can be pinned deterministically without the full server.+ const httpWriter: WriterIdentity = {+ id: 'agent-11111111-1111-4111-1111-111111111111',+ name: 'template-http',+ email: '[email protected]',+ };++ function increasingDates() {+ let t = Date.parse('2026-07-01T12:00:00.000Z');+ return () => {+ t += 1000;+ return new Date(t).toISOString();+ };+ }++ /**+ * Commit `body` at the template's real content path with a hand-formatted+ * ok-actor declaring the content-doc key in `docs[]` — the exact shape the+ * attribution path records. `commitWip` writes the message (subject ++ * ok-actor) verbatim, so the caller controls the subject a lifecycle write+ * would stamp.+ */+ async function commitTemplate(+ shadow: ShadowHandle,+ contentDir: string,+ folderRel: string,+ name: string,+ subject: string,+ body: string,+ date: string,+ writer: WriterIdentity = httpWriter,+ ): Promise<string> {+ const docKey = templateContentDocName(folderRel, name);+ const abs = resolve(contentDir, `${docKey}.md`);+ mkdirSync(dirname(abs), { recursive: true });+ writeFileSync(abs, body);+ const actor: OkActorEntry = {+ v: 1,+ writer_id: writer.id,+ principal: null,+ agent_session: writer.id.startsWith('agent-') ? writer.id.slice(6) : null,+ agent_type: null,+ client_name: writer.name,+ client_version: null,+ label: null,+ display_name: writer.name,+ color_seed: writer.id,+ docs: [docKey],+ };+ const message = `${subject}\n\n${formatOkActor(actor)}`;+ return commitWip(shadow, writer, 'content/docs', message, 'main', { date });+ }++ test('doc history is one continuous chain across typed lifecycle writes and wip editor edits', async () => {+ const { contentDir, shadow } = await setup();+ const next = increasingDates();+ const docName = templateContentDocName('notes', 'standup'); // notes/.ok/templates/standup++ // Two HTTP lifecycle writes stamped typed template-* subjects (what the+ // create/edit routes emit), keyed on the content path.+ const createSha = await commitTemplate(+ shadow,+ contentDir,+ 'notes',+ 'standup',+ 'template-create: notes/.ok/templates/standup',+ '---\ntemplate:\n title: Standup\n---\n# v1\n',+ next(),+ );+ const editSha = await commitTemplate(+ shadow,+ contentDir,+ 'notes',+ 'standup',+ 'template-edit: notes/.ok/templates/standup',+ '---\ntemplate:\n title: Standup\n---\n# v2\n',+ next(),+ );++ // The same file is an ordinary content doc, so an editor CRDT edit lands as a+ // raw wip: commit under the SAME key — a different writer, same doc.+ const wipSha = await commitTemplate(+ shadow,+ contentDir,+ 'notes',+ 'standup',+ 'wip: notes/.ok/templates/standup',+ '---\ntemplate:\n title: Standup\n---\n# v3 edited in the editor\n',+ next(),+ human,+ );++ const result = await getDocumentHistory(shadow, { docName }, 'content/docs');+ const shas = result.entries.map((e) => e.sha);+ // All three rows — typed and wip — are returned for the one content-doc name.+ // Nothing splits the timeline at the cutover and no fan-out noise leaks in.+ expect(new Set(shas)).toEqual(new Set([createSha, editSha, wipSha]));++ // Each row attributes under the byte-identical content-doc key; that shared+ // key is precisely why the typed and wip rows unify into one history.+ for (const entry of result.entries) {+ expect(entry.contributors.some((c) => c.docs.includes(docName))).toBe(true);+ }+ });++ test('folder timeline keeps the four typed lifecycle subjects and drops import + wip', async () => {+ const { contentDir, shadow } = await setup();+ const next = increasingDates();+ const docName = templateContentDocName('notes', 'standup');++ const createSha = await commitTemplate(+ shadow,+ contentDir,+ 'notes',+ 'standup',+ 'template-create: notes/.ok/templates/standup',+ '# create\n',+ next(),+ );+ const editSha = await commitTemplate(+ shadow,+ contentDir,+ 'notes',+ 'standup',+ 'template-edit: notes/.ok/templates/standup',+ '# edit\n',+ next(),+ );+ const renameSha = await commitTemplate(+ shadow,+ contentDir,+ 'notes',+ 'standup',+ 'template-rename: notes/.ok/templates/scrum -> notes/.ok/templates/standup',+ '# rename\n',+ next(),+ );+ const deleteSha = await commitTemplate(+ shadow,+ contentDir,+ 'notes',+ 'standup',+ 'template-delete: notes/.ok/templates/standup',+ '# delete\n',+ next(),+ );+ // The import route stamps `template-import:`, but the folder subject filter+ // omits `import` — minted-but-never-surfaced. A pre-existing gap this+ // migration preserves unchanged (the filter also carries a `template-move`+ // alternation that no route mints, since moves stamp `template-rename`).+ const importSha = await commitTemplate(+ shadow,+ contentDir,+ 'notes',+ 'standup',+ 'template-import: notes/.ok/templates/standup',+ '# import\n',+ next(),+ );+ // An editor CRDT edit stamps a raw wip: subject — a real edit, but not a+ // typed folder event.+ const wipSha = await commitTemplate(+ shadow,+ contentDir,+ 'notes',+ 'standup',+ 'wip: notes/.ok/templates/standup',+ '# editor edit\n',+ next(),+ human,+ );++ const folder = await getFolderTimeline(shadow, 'notes', 'content/docs');+ const folderShas = folder.entries.map((e) => e.sha);+ expect(folderShas).toContain(createSha);+ expect(folderShas).toContain(editSha);+ expect(folderShas).toContain(renameSha);+ expect(folderShas).toContain(deleteSha);+ expect(folderShas).not.toContain(importSha);+ expect(folderShas).not.toContain(wipSha);+ // Exactly the four typed lifecycle subjects — nothing else is a folder event.+ expect(folder.entries).toHaveLength(4);++ // The wip editor edit still belongs to the template's OWN document history:+ // it is a real edit, just not something the folder card surfaces.+ const doc = await getDocumentHistory(shadow, { docName }, 'content/docs');+ expect(doc.entries.map((e) => e.sha)).toContain(wipSha);+ });+});