Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

OK: template move/rename, attribution & folder timeline (PRD-6933) (#1641)

tim-inkeep9ae060c98bed
diff --git a/packages/app/package.json b/packages/app/package.json
index fec02e2ba..1a35d7a65 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -43,7 +43,7 @@
{
"name": "main app bundle (gzipped)",
"path": "dist/assets/index-*.js",
- "limit": "395 kB",
+ "limit": "400 kB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/components/FolderOverview.tsx b/packages/app/src/components/FolderOverview.tsx
index 839b739bd..e9311ebc1 100644
--- a/packages/app/src/components/FolderOverview.tsx
+++ b/packages/app/src/components/FolderOverview.tsx
@@ -3,6 +3,7 @@ import { Trans, useLingui } from '@lingui/react/macro';
import { ArrowDown, ArrowUp, ArrowUpDown, File, Folder, FolderOpen, Plus } from 'lucide-react';
import { useState } from 'react';
import { FolderPropertiesCard } from '@/components/FolderPropertiesCard';
+import { FolderTimelineCard } from '@/components/FolderTimelineCard';
import {
buildFolderOverviewData,
type FolderOverviewEntry,
@@ -186,6 +187,7 @@ export function FolderOverview({ folderPath }: { folderPath: string }) {
onChange={refreshFolderConfig}
folderConfigHandle={folderConfigHandle}
/>
+ <FolderTimelineCard folderPath={folderPath} />
<div className="rounded-lg border">
<Table>
<TableHeader>
diff --git a/packages/app/src/components/FolderTimelineCard.tsx b/packages/app/src/components/FolderTimelineCard.tsx
new file mode 100644
index 000000000..4519b3ad7
--- /dev/null
+++ b/packages/app/src/components/FolderTimelineCard.tsx
@@ -0,0 +1,166 @@
+import type { TimelineEntry } from '@inkeep/open-knowledge-core';
+import { t } from '@lingui/core/macro';
+import { Trans } from '@lingui/react/macro';
+import {
+ ArrowLeftRight,
+ FilePlus,
+ FolderCog,
+ History,
+ type LucideIcon,
+ Pencil,
+ Trash2,
+ User,
+} from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { Badge } from '@/components/ui/badge';
+import { Skeleton } from '@/components/ui/skeleton';
+import { subscribeToTemplatesChanged } from '@/lib/documents-events';
+
+function formatRelative(iso: string): string {
+ const diffSec = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
+ if (diffSec < 60) return t`just now`;
+ if (diffSec < 3600) return t`${Math.floor(diffSec / 60)}m ago`;
+ if (diffSec < 86400) return t`${Math.floor(diffSec / 3600)}h ago`;
+ if (diffSec < 86400 * 7) return t`${Math.floor(diffSec / 86400)}d ago`;
+ return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+}
+
+function leafName(path: string): string {
+ return (path.split('/').pop() ?? path).replace(/\.md$/, '');
+}
+
+function describeEntry(entry: TimelineEntry): { Icon: LucideIcon; label: string; detail: string } {
+ const message = entry.message;
+ const idx = message.indexOf(': ');
+ const prefix = idx === -1 ? message : message.slice(0, idx);
+ const rest = idx === -1 ? '' : message.slice(idx + 2);
+ switch (prefix) {
+ case 'template-create':
+ return { Icon: FilePlus, label: t`created template`, detail: leafName(rest) };
+ case 'template-edit':
+ return { Icon: Pencil, label: t`edited template`, detail: leafName(rest) };
+ case 'template-delete':
+ return { Icon: Trash2, label: t`deleted template`, detail: leafName(rest) };
+ case 'template-rename':
+ case 'template-move': {
+ const [from, to] = rest.split(' -> ');
+ return {
+ Icon: ArrowLeftRight,
+ label: t`moved template`,
+ detail: `${leafName(from ?? '')} → ${leafName(to ?? rest)}`,
+ };
+ }
+ case 'folder-frontmatter-edit':
+ return { Icon: FolderCog, label: t`updated folder properties`, detail: '' };
+ case 'folder-frontmatter-delete':
+ return { Icon: FolderCog, label: t`cleared folder properties`, detail: '' };
+ case 'folder-create':
+ return { Icon: FolderCog, label: t`created folder`, detail: '' };
+ default:
+ return { Icon: History, label: prefix.replace(/-/g, ' '), detail: leafName(rest) };
+ }
+}
+
+function authorName(entry: TimelineEntry): string {
+ if (entry.contributors.length > 0) return entry.contributors[0].name;
+ if (entry.author === 'openknowledge-service' || entry.author === 'server') return t`Auto-save`;
+ return entry.author || t`Unknown`;
+}
+
+export function FolderTimelineCard({ folderPath }: { folderPath: string }) {
+ const [entries, setEntries] = useState<TimelineEntry[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ async function load() {
+ try {
+ const res = await fetch(`/api/history?folder=${encodeURIComponent(folderPath)}&limit=50`);
+ if (cancelled) return;
+ if (!res.ok) {
+ setError(true);
+ setLoading(false);
+ return;
+ }
+ const data = (await res.json()) as { entries?: TimelineEntry[] };
+ if (cancelled) return;
+ setEntries(data.entries ?? []);
+ setError(false);
+ setLoading(false);
+ } catch (err) {
+ if (!cancelled) {
+ console.warn('[FolderTimelineCard] failed to load folder timeline:', err);
+ setError(true);
+ setLoading(false);
+ }
+ }
+ }
+ setLoading(true);
+ load();
+ const unsubscribe = subscribeToTemplatesChanged(load);
+ return () => {
+ cancelled = true;
+ unsubscribe();
+ };
+ }, [folderPath]);
+
+ if (error) return null;
+ if (!loading && entries.length === 0) return null;
+
+ return (
+ <section className="rounded-lg border bg-card" data-testid="folder-timeline-card">
+ <div className="flex items-center gap-2 border-b border-border px-3 py-1">
+ <h2 className="text-xs font-semibold uppercase font-mono tracking-wider text-muted-foreground">
+ <Trans>Activity</Trans>
+ </h2>
+ {entries.length > 0 ? (
+ <Badge className="text-xs" variant="secondary">
+ {entries.length}
+ </Badge>
+ ) : null}
+ </div>
+ <div className="px-3 py-2.5">
+ {loading ? (
+ <div className="space-y-2" role="status" aria-busy="true">
+ <Skeleton className="h-8 w-full" />
+ <Skeleton className="h-8 w-full" />
+ </div>
+ ) : (
+ <ul className="space-y-1">
+ {entries.map((entry) => {
+ const { Icon, label, detail } = describeEntry(entry);
+ return (
+ <li
+ key={entry.sha}
+ className="flex items-center gap-2.5 rounded-md px-2 py-1.5 text-sm"
+ >
+ <Icon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden />
+ <span className="min-w-0 flex-1 truncate">
+ <span className="text-foreground">{label}</span>
+ {detail ? (
+ <code className="ml-1.5 font-mono text-xs text-muted-foreground">
+ {detail}
+ </code>
+ ) : null}
+ </span>
+ <span className="flex shrink-0 items-center gap-1 text-xs text-muted-foreground">
+ <User className="size-3" aria-hidden />
+ {authorName(entry)}
+ </span>
+ <time
+ className="shrink-0 text-xs text-muted-foreground/80"
+ dateTime={entry.timestamp}
+ title={new Date(entry.timestamp).toLocaleString()}
+ >
+ {formatRelative(entry.timestamp)}
+ </time>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/packages/app/src/components/TemplateEditDialog.tsx b/packages/app/src/components/TemplateEditDialog.tsx
index b6eff2b14..471ab34c3 100644
--- a/packages/app/src/components/TemplateEditDialog.tsx
+++ b/packages/app/src/components/TemplateEditDialog.tsx
@@ -119,6 +119,7 @@ function TemplateEditForm({
const form = useTemplateForm({
mode: 'edit',
folderPath: detail.folder,
+ scope: detail.scope,
initial: {
name: detail.name,
title: typeof fm.title === 'string' ? fm.title : '',
diff --git a/packages/app/src/components/TemplateForm.tsx b/packages/app/src/components/TemplateForm.tsx
index 1927fb81c..aab5db02e 100644
--- a/packages/app/src/components/TemplateForm.tsx
+++ b/packages/app/src/components/TemplateForm.tsx
@@ -7,7 +7,7 @@ import { Button } from '@/components/ui/button';
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
-import { saveTemplate } from '@/lib/folder-config-api';
+import { moveTemplate, saveTemplate } from '@/lib/folder-config-api';
const NAME_RE = /^[A-Za-z0-9_-]+$/;
@@ -40,6 +40,7 @@ interface TemplateFormInitial {
interface UseTemplateFormArgs {
mode: 'create' | 'edit';
folderPath: string;
+ scope?: 'local' | 'inherited';
initial: TemplateFormInitial;
existingNames?: ReadonlySet<string>;
onCommitted: () => void;
@@ -64,12 +65,14 @@ export interface TemplateFormState {
slugShadows: boolean;
trimmedSlug: string;
fixedName: string;
+ canRename: boolean;
submit: () => Promise<void>;
}
export function useTemplateForm({
mode,
folderPath,
+ scope = 'local',
initial,
existingNames,
onCommitted,
@@ -94,10 +97,13 @@ export function useTemplateForm({
setSlugManuallyEdited(true);
}
+ const canRename = mode === 'edit' && scope === 'local';
+ const slugEditable = mode === 'create' || canRename;
+
const trimmedTitle = title.trim();
const trimmedSlug = slug.trim();
const titleInvalid = trimmedTitle === '';
- const slugInvalid = mode === 'create' && (trimmedSlug === '' || !NAME_RE.test(trimmedSlug));
+ const slugInvalid = slugEditable && (trimmedSlug === '' || !NAME_RE.test(trimmedSlug));
const slugShadows =
mode === 'create' && !slugInvalid && (existingNames?.has(trimmedSlug) ?? false);
const canSubmit = !saving && !titleInvalid && !slugInvalid;
@@ -108,12 +114,23 @@ export function useTemplateForm({
return;
}
setSaving(true);
- const result = await saveTemplate({
- folder: folderPath,
- name: mode === 'create' ? trimmedSlug : initial.name,
- frontmatter: buildTemplateFrontmatter({ title, description }),
- body,
- });
+ const frontmatter = buildTemplateFrontmatter({ title, description });
+ const renaming = canRename && trimmedSlug !== initial.name;
+ const result = renaming
+ ? await moveTemplate({
+ fromFolder: folderPath,
+ fromName: initial.name,
+ toFolder: folderPath,
+ toName: trimmedSlug,
+ frontmatter,
+ body,
+ })
+ : await saveTemplate({
+ folder: folderPath,
+ name: mode === 'create' ? trimmedSlug : initial.name,
+ frontmatter,
+ body,
+ });
setSaving(false);
if (!result.ok) {
const { error } = result;
@@ -124,7 +141,9 @@ export function useTemplateForm({
);
return;
}
- if (result.warnings.length > 0) {
+ if (renaming) {
+ toast.success(t`Template renamed`);
+ } else if ('warnings' in result && result.warnings.length > 0) {
toast.warning(result.warnings.join(' '));
} else if (mode === 'create') {
toast.success(t`Template "${trimmedTitle}" created`);
@@ -153,6 +172,7 @@ export function useTemplateForm({
slugShadows,
trimmedSlug,
fixedName: initial.name,
+ canRename,
submit,
};
}
@@ -195,12 +215,21 @@ export function TemplateFormFields({
</Field>
{form.mode === 'create' ? (
<DerivedFilename form={form} />
+ ) : form.canRename ? (
+ <EditFilename form={form} />
) : (
- <p className="text-xs text-muted-foreground">
- <Trans>
- File: <code className="font-mono">{fixedName}.md</code>
- </Trans>
- </p>
+ <>
+ <p className="text-xs text-muted-foreground">
+ <Trans>
+ File: <code className="font-mono">{fixedName}.md</code>
+ </Trans>
+ </p>
+ <p className="text-xs text-muted-foreground">
+ <Trans>
+ Inherited templates can't be renamed here — rename it in the folder that owns it.
+ </Trans>
+ </p>
+ </>
)}
<Field>
<FieldLabel htmlFor={descriptionId}>
@@ -291,3 +320,41 @@ function DerivedFilename({ form }: { form: TemplateFormState }) {
</Field>
);
}
+
+function EditFilename({ form }: { form: TemplateFormState }) {
+ const { t } = useLingui();
+ const slugId = useId();
+ return (
+ <Field>
+ <FieldLabel htmlFor={slugId}>
+ <Trans>Filename</Trans>
+ </FieldLabel>
+ <Input
+ id={slugId}
+ value={form.slug}
+ onChange={(e) => form.setSlug(e.target.value)}
+ placeholder={t`blog-post`}
+ disabled={form.isSaving}
+ spellCheck={false}
+ autoCapitalize="off"
+ autoCorrect="off"
+ aria-invalid={form.slugInvalid}
+ className="font-mono"
+ />
+ {form.slugInvalid ? (
+ <FieldError>
+ <Trans>
+ Use letters, digits, <code className="font-mono">-</code> or{' '}
+ <code className="font-mono">_</code> only.
+ </Trans>
+ </FieldError>
+ ) : (
+ <FieldDescription>
+ <Trans>
+ Renaming changes the file on disk and the id agents use to pick this template.
+ </Trans>
+ </FieldDescription>
+ )}
+ </Field>
+ );
+}
diff --git a/packages/app/src/lib/folder-config-api.ts b/packages/app/src/lib/folder-config-api.ts
index 0fc55393d..88804b308 100644
--- a/packages/app/src/lib/folder-config-api.ts
+++ b/packages/app/src/lib/folder-config-api.ts
@@ -79,3 +79,28 @@ export async function deleteTemplate(
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
+
+export async function moveTemplate(input: {
+ fromFolder: string;
+ fromName: string;
+ toFolder: string;
+ toName: string;
+ frontmatter?: TemplateFrontmatterFields;
+ body?: string;
+}): Promise<{ ok: true; committed: boolean } | { ok: false; error: string }> {
+ try {
+ const res = await fetch('/api/template', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(input),
+ });
+ if (!res.ok) {
+ return { ok: false, error: await readErrorBody(res) };
+ }
+ const payload = (await res.json().catch(() => null)) as { committed?: boolean } | null;
+ emitTemplatesChanged();
+ return { ok: true, committed: payload?.committed ?? false };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index ac2ba3c88..67074598f 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -14,6 +14,7 @@
"-KCZ6n": [
"Mark a block as the source of truth. Mirror references elsewhere render this content read-only and update live as you edit here."
],
+ "-LHLx7": ["edited template"],
"-Q7TT9": ["That folder isn't an Open Knowledge project yet. Initialize it and open?"],
"-QCLWk": ["Templates available"],
"-Qw-1t": ["GitHub authentication failed. Try signing in again."],
@@ -77,6 +78,7 @@
"Switching to <0>local-only</0> will refuse until they're untracked via<1> git rm --cached</1>."
],
"1ZpfyB": ["Open with AI ", ["displayName"], ", ", ["hint"]],
+ "1ZwmkP": ["template"],
"1aPxWt": ["New blank field name"],
"1bDVu5": ["Workspace Command Palette"],
"1d1F11": ["Select all files and folders"],
@@ -518,6 +520,7 @@
"EcM3k7": ["Failed to clean up pending ", ["kind"]],
"EcR0fl": ["Checking for installed agents"],
"EeRZnZ": ["Expand burst ", ["burstNumber"], " diff"],
+ "Ef7StM": ["Unknown"],
"EhDLBx": ["You modified <0>", ["filePath"], "</0> locally, but it was deleted upstream."],
"Ehkru0": ["Open, navigate, accept, or dismiss CodeMirror completion suggestions."],
"EiVgl5": ["You don't have permission to push to this repo."],
@@ -551,6 +554,7 @@
"FjkaiT": ["Zoom out"],
"FnMkli": ["Sync disabled — you don't have permission to push"],
"Fqr8BP": ["Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."],
+ "FvMSms": ["Renaming changes the file on disk and the id agents use to pick this template."],
"FvpFSZ": ["Reveal in Finder, ", ["hint"]],
"Fxf4jq": ["Description (optional)"],
"FyW0WO": ["Authorize in browser"],
@@ -679,6 +683,7 @@
"KDuPiY": ["Uploading ", ["fileName"]],
"KDw4GX": ["Try again"],
"KFdXwz": ["Show panel (", ["panelShortcut"], ")"],
+ "KPW5WC": ["moved template"],
"KRJ6xh": ["No tags yet. Continue typing to create one."],
"KWL_Ih": ["Blog post"],
"KX1MZR": ["Your repositories"],
@@ -866,6 +871,7 @@
"QI4KgP": [["fileLabel"], " · ", ["folderLabel"]],
"QJX5AO": ["Sharing"],
"QQghPu": ["Install in Claude Desktop"],
+ "QR5SP1": ["created template"],
"QWT-Z9": ["Read the <0>docs<1> ↗</1></0> for details."],
"QWks14": ["A short line shown under the name in the template list."],
"QcpeeE": ["Navigate to ", ["docName"]],
@@ -1039,6 +1045,7 @@
"X9VpsP": ["Loading folder contents"],
"XDzAnp": ["Opens in a new tab"],
"XH30C4": ["document"],
+ "XJOV1Y": ["Activity"],
"XPJ0sN": [["settingsDescriptorLabel"], " properties"],
"XPqe3B": ["Create new tag #", ["tagValue"]],
"XRuL0i": ["Create page"],
@@ -1071,6 +1078,7 @@
"YC6_wP": ["Edit ", ["keyName"]],
"YEP3X2": ["Delete a table when the active table cell selection covers the full table."],
"YGIi_c": ["Reinstall"],
+ "YKLP_-": ["Template renamed"],
"YPFBfr": [["detail"], " - ", ["kind"], " \"", ["createdPath"], "\" still exists on disk"],
"YSFv5w": ["No git repository — config sharing does not apply here."],
"YTLmTM": ["Remove the parent <0>.git</0> folder"],
@@ -1107,11 +1115,13 @@
"ZBt4rI": ["Instruction for the AI"],
"ZLQol-": ["You can turn this on later in <0>Settings → Sync</0>."],
"ZNK2Tq": ["root"],
+ "ZQLDTl": ["created folder"],
"ZU8VV_": ["Remove failed: ", ["error"]],
"ZWgr0b": ["In a subfolder"],
"ZWolSV": [
"You picked the filesystem root (/). Scaffolding here will scan every file on this machine — make sure that's what you want."
],
+ "ZWxfrc": ["cleared folder properties"],
"ZWyHmq": ["This project"],
"ZhhOwV": ["Quote"],
"ZjtgI-": ["Command palette"],
@@ -1154,8 +1164,10 @@
"_TDESN": ["Network error - ", ["kind"], " \"", ["createdPath"], "\" still exists on disk"],
"_TF8ep": ["Failed to render PDF"],
"_VRtd7": ["Couldn't send the selection — please try again."],
+ "_gkGSK": ["deleted template"],
"_qD6mn": ["Pick the folder where you've cloned it."],
"_rP3HI": [["minutes"], "m ago"],
+ "_tekeB": ["updated folder properties"],
"a-cKXz": ["Select all source"],
"a4_eNe": [
"Branch switched but the document could not be opened — try navigating to it manually."
@@ -1419,6 +1431,7 @@
],
"jPUPvG": ["Couldn't resolve the conflict for ", ["filePath"], "."],
"jRHdCz": ["Failed to load PDF"],
+ "jSO1X5": ["Inherited templates can't be renamed here — rename it in the folder that owns it."],
"jSY41h": ["\"", ["docName"], "\" took too long. Check your connection."],
"jTLWxh": ["Embed an external page in an inline iframe (docs, demos, Figma, CodeSandbox)."],
"jZ_E5M": ["Fetch failed — check the server logs for details."],
@@ -1470,6 +1483,7 @@
"ky9Tuc": ["Edit ", ["0"], " source"],
"l17ab4": ["Could not write project files. Try a different location."],
"l1aQKz": ["Visual editor table"],
+ "l1l8sj": [["0"], "d ago"],
"l3mSlL": ["Append-only timeline"],
"l6OXqI": ["No installed agents found"],
"l6zqhi": ["Branch switch failed — try opening the doc manually."],
@@ -1586,6 +1600,7 @@
"opEayO": [
"<0>.ok/</0>, <1>.mcp.json</1> (and per-editor variants), project skills, and <2>.claude/launch.json</2>. Switch later via Settings → Sharing or <3>ok sharing share|unshare</3>."
],
+ "optX0N": [["0"], "h ago"],
"oqB2ez": ["Previous match"],
"ot5BRK": ["Duplicate selected file or folder"],
"otE4aj": ["Show external URL nodes"],
@@ -1628,6 +1643,7 @@
"pzutoc": ["Italic"],
"q2kXMG": ["Inline Math"],
"q6-JVU": ["Loading pages"],
+ "q6IUff": ["Renaming moves the file on disk (a git mv) and changes the id agents use."],
"q7zsRM": ["Couldn't save version — try again"],
"qAQVSD": ["Page headings response was not JSON"],
"qAhFeg": [
@@ -1698,6 +1714,7 @@
"s-XOaI": ["File name"],
"s1c0ja": ["Bullet List"],
"s3caR3": ["Deleting"],
+ "s8XlGV": ["activity"],
"sE7R19": [
"Could not load templates: ",
["templatesError"],
@@ -1746,6 +1763,7 @@
"tgWuMB": ["Modified"],
"tiWX6q": ["Source editor"],
"tjXez2": ["blog-post"],
+ "tp15x4": ["folder properties"],
"u-9fWA": ["See <0>Architecture</0> for the system overview."],
"u0iUdo": [
"Chrome and the page use this to select text or page content. Open Knowledge only handles it when the Files sidebar has focus."
@@ -1924,6 +1942,7 @@
"zaXlhf": [
"The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."
],
+ "zbymaY": [["0"], "m ago"],
"zd00pH": ["Copy Path"],
"zgSFyG": ["External link"],
"zkWs-l": ["Sharing mode unchanged — see message below."],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 327d68904..e2d1caad2 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -121,6 +121,21 @@ msgstr "{0}/{1} — {2}"
msgid "{0}/{1} {2}"
msgstr "{0}/{1} {2}"
+#. placeholder {0}: Math.floor(diffSec / 86400)
+#: src/components/FolderTimelineCard.tsx
+msgid "{0}d ago"
+msgstr "{0}d ago"
+
+#. placeholder {0}: Math.floor(diffSec / 3600)
+#: src/components/FolderTimelineCard.tsx
+msgid "{0}h ago"
+msgstr "{0}h ago"
+
+#. placeholder {0}: Math.floor(diffSec / 60)
+#: src/components/FolderTimelineCard.tsx
+msgid "{0}m ago"
+msgstr "{0}m ago"
+
#: src/components/SyncStatusBadge.tsx
msgid "{ahead, plural, one {# commit ahead} other {# commits ahead}}"
msgstr "{ahead, plural, one {# commit ahead} other {# commits ahead}}"
@@ -480,6 +495,14 @@ msgstr "Active"
msgid "Active panel content for the selected tab shows here."
msgstr "Active panel content for the selected tab shows here."
+#: src/components/FolderTimelineCard.tsx
+#~ msgid "activity"
+#~ msgstr "activity"
+
+#: src/components/FolderTimelineCard.tsx
+msgid "Activity"
+msgstr "Activity"
+
#. Primary button that writes MCP config for the selected AI tools
#: src/components/FrontmatterRow.tsx
#: src/components/McpConsentDialogBody.tsx
@@ -660,6 +683,7 @@ msgstr "Authoritative content; mirrored verbatim everywhere it's referenced."
msgid "Authorize in browser"
msgstr "Authorize in browser"
+#: src/components/FolderTimelineCard.tsx
#: src/components/TimelinePanel.tsx
msgid "Auto-save"
msgstr "Auto-save"
@@ -996,6 +1020,10 @@ msgstr "Claude Desktop"
msgid "Clear {keyName}"
msgstr "Clear {keyName}"
+#: src/components/FolderTimelineCard.tsx
+msgid "cleared folder properties"
+msgstr "cleared folder properties"
+
#: src/components/EditorActivityPool.tsx
msgid "Clearing local collaboration data for \"{docName}\" before reconnecting."
msgstr "Clearing local collaboration data for \"{docName}\" before reconnecting."
@@ -1659,10 +1687,18 @@ msgstr "Create template"
msgid "Create your first file"
msgstr "Create your first file"
+#: src/components/FolderTimelineCard.tsx
+msgid "created folder"
+msgstr "created folder"
+
#: src/components/SeedDialog.tsx
msgid "Created if missing; reused if it exists."
msgstr "Created if missing; reused if it exists."
+#: src/components/FolderTimelineCard.tsx
+msgid "created template"
+msgstr "created template"
+
#: src/components/CreateProjectDialog.tsx
#: src/components/NewItemDialog.tsx
#: src/components/NewTemplateDialog.tsx
@@ -1748,6 +1784,10 @@ msgstr "Delete selected items"
msgid "Delete selected table"
msgstr "Delete selected table"
+#: src/components/FolderTimelineCard.tsx
+msgid "deleted template"
+msgstr "deleted template"
+
#: src/components/DeleteConfirmationDialog.tsx
#: src/components/TrashFailureModal.tsx
msgid "Deleting"
@@ -1975,6 +2015,10 @@ msgstr "Edit wiki link"
msgid "Edit with AI"
msgstr "Edit with AI"
+#: src/components/FolderTimelineCard.tsx
+msgid "edited template"
+msgstr "edited template"
+
#: src/presence/PresenceBar.tsx
msgid "editing [[{realCurrentDoc}]]"
msgstr "editing [[{realCurrentDoc}]]"
@@ -2437,6 +2481,10 @@ msgstr "Folder name"
msgid "Folder name: {detail}"
msgstr "Folder name: {detail}"
+#: src/components/FolderTimelineCard.tsx
+#~ msgid "folder properties"
+#~ msgstr "folder properties"
+
#: src/components/FolderPropertiesCard.tsx
msgid "Folder properties"
msgstr "Folder properties"
@@ -2731,6 +2779,10 @@ msgstr "Inherited — set a value here to replace it."
msgid "Inherited from {path}"
msgstr "Inherited from {path}"
+#: src/components/TemplateForm.tsx
+msgid "Inherited templates can't be renamed here — rename it in the folder that owns it."
+msgstr "Inherited templates can't be renamed here — rename it in the folder that owns it."
+
#: src/components/SeedDialog.tsx
msgid "Initialize"
msgstr "Initialize"
@@ -2860,6 +2912,7 @@ msgid "Jump to page {pageNumber}"
msgstr "Jump to page {pageNumber}"
#: src/components/FolderOverview.tsx
+#: src/components/FolderTimelineCard.tsx
#: src/components/SyncStatusBadge.tsx
#: src/components/TimelinePanel.tsx
msgid "just now"
@@ -3237,6 +3290,10 @@ msgstr "Move to the previous visual-editor find result."
msgid "Move up"
msgstr "Move up"
+#: src/components/FolderTimelineCard.tsx
+msgid "moved template"
+msgstr "moved template"
+
#: src/editor/slash-command/component-items.tsx
msgid "Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."
msgstr "Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."
@@ -4516,6 +4573,14 @@ msgstr "Rename succeeded but the sidebar may be out of date — refresh to resyn
msgid "Rename succeeded but the tabstrip may be out of date — refresh to resync"
msgstr "Rename succeeded but the tabstrip may be out of date — refresh to resync"
+#: src/components/TemplateForm.tsx
+msgid "Renaming changes the file on disk and the id agents use to pick this template."
+msgstr "Renaming changes the file on disk and the id agents use to pick this template."
+
+#: src/components/TemplateForm.tsx
+#~ msgid "Renaming moves the file on disk (a git mv) and changes the id agents use."
+#~ msgstr "Renaming moves the file on disk (a git mv) and changes the id agents use."
+
#: src/components/EditorActivityPool.tsx
msgid "Reopening \"{docName}\" with a fresh local collaboration cache."
msgstr "Reopening \"{docName}\" with a fresh local collaboration cache."
@@ -5383,6 +5448,10 @@ msgstr "Task list"
msgid "Task List"
msgstr "Task List"
+#: src/components/FolderTimelineCard.tsx
+#~ msgid "template"
+#~ msgstr "template"
+
#: src/components/TemplateEditDialog.tsx
msgid "Template"
msgstr "Template"
@@ -5403,6 +5472,10 @@ msgstr "Template \"{trimmedTitle}\" created"
msgid "Template list"
msgstr "Template list"
+#: src/components/TemplateForm.tsx
+msgid "Template renamed"
+msgstr "Template renamed"
+
#: src/components/TemplateForm.tsx
msgid "Template saved"
msgstr "Template saved"
@@ -5770,6 +5843,10 @@ msgstr "Undone all edits on {docName}"
msgid "Unified diff"
msgstr "Unified diff"
+#: src/components/FolderTimelineCard.tsx
+msgid "Unknown"
+msgstr "Unknown"
+
#: src/editor/extensions/JsxComponentView.tsx
msgid "Unknown component: {componentName} — source editable below"
msgstr "Unknown component: {componentName} — source editable below"
@@ -5807,6 +5884,10 @@ msgstr "Unrecognized wiki link"
msgid "Update the destination and optional section anchor."
msgstr "Update the destination and optional section anchor."
+#: src/components/FolderTimelineCard.tsx
+msgid "updated folder properties"
+msgstr "updated folder properties"
+
#: src/components/PageHeaderWidgets.tsx
msgid "Upload {keyName}"
msgstr "Upload {keyName}"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 0951b25f8..5c0aa1812 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -14,6 +14,7 @@
"-KCZ6n": [
"Ḿàŕķ à ƀĺōćķ àś ţĥē śōũŕćē ōƒ ţŕũţĥ. Ḿĩŕŕōŕ ŕēƒēŕēńćēś ēĺśēŵĥēŕē ŕēńďēŕ ţĥĩś ćōńţēńţ ŕēàď-ōńĺŷ àńď ũƥďàţē ĺĩvē àś ŷōũ ēďĩţ ĥēŕē."
],
+ "-LHLx7": ["ēďĩţēď ţēḿƥĺàţē"],
"-Q7TT9": ["Ţĥàţ ƒōĺďēŕ ĩśń'ţ àń Ōƥēń Ķńōŵĺēďĝē ƥŕōĴēćţ ŷēţ. Ĩńĩţĩàĺĩźē ĩţ àńď ōƥēń?"],
"-QCLWk": ["Ţēḿƥĺàţēś àvàĩĺàƀĺē"],
"-Qw-1t": ["ĜĩţĤũƀ àũţĥēńţĩćàţĩōń ƒàĩĺēď. Ţŕŷ śĩĝńĩńĝ ĩń àĝàĩń."],
@@ -77,6 +78,7 @@
"Śŵĩţćĥĩńĝ ţō <0>ĺōćàĺ-ōńĺŷ</0> ŵĩĺĺ ŕēƒũśē ũńţĩĺ ţĥēŷ'ŕē ũńţŕàćķēď vĩà<1> ĝĩţ ŕḿ --ćàćĥēď</1>."
],
"1ZpfyB": ["Ōƥēń ŵĩţĥ ÀĨ ", ["displayName"], ", ", ["hint"]],
+ "1ZwmkP": ["ţēḿƥĺàţē"],
"1aPxWt": ["Ńēŵ ƀĺàńķ ƒĩēĺď ńàḿē"],
"1bDVu5": ["Ŵōŕķśƥàćē Ćōḿḿàńď Ƥàĺēţţē"],
"1d1F11": ["Śēĺēćţ àĺĺ ƒĩĺēś àńď ƒōĺďēŕś"],
@@ -518,6 +520,7 @@
"EcM3k7": ["Ƒàĩĺēď ţō ćĺēàń ũƥ ƥēńďĩńĝ ", ["kind"]],
"EcR0fl": ["Ćĥēćķĩńĝ ƒōŕ ĩńśţàĺĺēď àĝēńţś"],
"EeRZnZ": ["Ēxƥàńď ƀũŕśţ ", ["burstNumber"], " ďĩƒƒ"],
+ "Ef7StM": ["Ũńķńōŵń"],
"EhDLBx": ["Ŷōũ ḿōďĩƒĩēď <0>", ["filePath"], "</0> ĺōćàĺĺŷ, ƀũţ ĩţ ŵàś ďēĺēţēď ũƥśţŕēàḿ."],
"Ehkru0": ["Ōƥēń, ńàvĩĝàţē, àććēƥţ, ōŕ ďĩśḿĩśś ĆōďēḾĩŕŕōŕ ćōḿƥĺēţĩōń śũĝĝēśţĩōńś."],
"EiVgl5": ["Ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō."],
@@ -551,6 +554,7 @@
"FjkaiT": ["Źōōḿ ōũţ"],
"FnMkli": ["Śŷńć ďĩśàƀĺēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ"],
"Fqr8BP": ["Ḿũĺţĩ-ƥàĝē ƤĎƑ vĩēŵēŕ ŵĩţĥ ţōōĺƀàŕ ćōńţŕōĺś (ţĥũḿƀńàĩĺś, ƥàĝē ńàv, źōōḿ)."],
+ "FvMSms": ["Ŕēńàḿĩńĝ ćĥàńĝēś ţĥē ƒĩĺē ōń ďĩśķ àńď ţĥē ĩď àĝēńţś ũśē ţō ƥĩćķ ţĥĩś ţēḿƥĺàţē."],
"FvpFSZ": ["Ŕēvēàĺ ĩń Ƒĩńďēŕ, ", ["hint"]],
"Fxf4jq": ["Ďēśćŕĩƥţĩōń (ōƥţĩōńàĺ)"],
"FyW0WO": ["Àũţĥōŕĩźē ĩń ƀŕōŵśēŕ"],
@@ -679,6 +683,7 @@
"KDuPiY": ["Ũƥĺōàďĩńĝ ", ["fileName"]],
"KDw4GX": ["Ţŕŷ àĝàĩń"],
"KFdXwz": ["Śĥōŵ ƥàńēĺ (", ["panelShortcut"], ")"],
+ "KPW5WC": ["ḿōvēď ţēḿƥĺàţē"],
"KRJ6xh": ["Ńō ţàĝś ŷēţ. Ćōńţĩńũē ţŷƥĩńĝ ţō ćŕēàţē ōńē."],
"KWL_Ih": ["ßĺōĝ ƥōśţ"],
"KX1MZR": ["Ŷōũŕ ŕēƥōśĩţōŕĩēś"],
@@ -866,6 +871,7 @@
"QI4KgP": [["fileLabel"], " · ", ["folderLabel"]],
"QJX5AO": ["Śĥàŕĩńĝ"],
"QQghPu": ["Ĩńśţàĺĺ ĩń Ćĺàũďē Ďēśķţōƥ"],
+ "QR5SP1": ["ćŕēàţēď ţēḿƥĺàţē"],
"QWT-Z9": ["Ŕēàď ţĥē <0>ďōćś<1> ↗</1></0> ƒōŕ ďēţàĩĺś."],
"QWks14": ["À śĥōŕţ ĺĩńē śĥōŵń ũńďēŕ ţĥē ńàḿē ĩń ţĥē ţēḿƥĺàţē ĺĩśţ."],
"QcpeeE": ["Ńàvĩĝàţē ţō ", ["docName"]],
@@ -1039,6 +1045,7 @@
"X9VpsP": ["Ĺōàďĩńĝ ƒōĺďēŕ ćōńţēńţś"],
"XDzAnp": ["Ōƥēńś ĩń à ńēŵ ţàƀ"],
"XH30C4": ["ďōćũḿēńţ"],
+ "XJOV1Y": ["Àćţĩvĩţŷ"],
"XPJ0sN": [["settingsDescriptorLabel"], " ƥŕōƥēŕţĩēś"],
"XPqe3B": ["Ćŕēàţē ńēŵ ţàĝ #", ["tagValue"]],
"XRuL0i": ["Ćŕēàţē ƥàĝē"],
@@ -1071,6 +1078,7 @@
"YC6_wP": ["Ēďĩţ ", ["keyName"]],
"YEP3X2": ["Ďēĺēţē à ţàƀĺē ŵĥēń ţĥē àćţĩvē ţàƀĺē ćēĺĺ śēĺēćţĩōń ćōvēŕś ţĥē ƒũĺĺ ţàƀĺē."],
"YGIi_c": ["Ŕēĩńśţàĺĺ"],
+ "YKLP_-": ["Ţēḿƥĺàţē ŕēńàḿēď"],
"YPFBfr": [["detail"], " - ", ["kind"], " \"", ["createdPath"], "\" śţĩĺĺ ēxĩśţś ōń ďĩśķ"],
"YSFv5w": ["Ńō ĝĩţ ŕēƥōśĩţōŕŷ — ćōńƒĩĝ śĥàŕĩńĝ ďōēś ńōţ àƥƥĺŷ ĥēŕē."],
"YTLmTM": ["Ŕēḿōvē ţĥē ƥàŕēńţ <0>.ĝĩţ</0> ƒōĺďēŕ"],
@@ -1107,11 +1115,13 @@
"ZBt4rI": ["Ĩńśţŕũćţĩōń ƒōŕ ţĥē ÀĨ"],
"ZLQol-": ["Ŷōũ ćàń ţũŕń ţĥĩś ōń ĺàţēŕ ĩń <0>Śēţţĩńĝś → Śŷńć</0>."],
"ZNK2Tq": ["ŕōōţ"],
+ "ZQLDTl": ["ćŕēàţēď ƒōĺďēŕ"],
"ZU8VV_": ["Ŕēḿōvē ƒàĩĺēď: ", ["error"]],
"ZWgr0b": ["Ĩń à śũƀƒōĺďēŕ"],
"ZWolSV": [
"Ŷōũ ƥĩćķēď ţĥē ƒĩĺēśŷśţēḿ ŕōōţ (/). Śćàƒƒōĺďĩńĝ ĥēŕē ŵĩĺĺ śćàń ēvēŕŷ ƒĩĺē ōń ţĥĩś ḿàćĥĩńē — ḿàķē śũŕē ţĥàţ'ś ŵĥàţ ŷōũ ŵàńţ."
],
+ "ZWxfrc": ["ćĺēàŕēď ƒōĺďēŕ ƥŕōƥēŕţĩēś"],
"ZWyHmq": ["Ţĥĩś ƥŕōĴēćţ"],
"ZhhOwV": ["Ǫũōţē"],
"ZjtgI-": ["Ćōḿḿàńď ƥàĺēţţē"],
@@ -1154,8 +1164,10 @@
"_TDESN": ["Ńēţŵōŕķ ēŕŕōŕ - ", ["kind"], " \"", ["createdPath"], "\" śţĩĺĺ ēxĩśţś ōń ďĩśķ"],
"_TF8ep": ["Ƒàĩĺēď ţō ŕēńďēŕ ƤĎƑ"],
"_VRtd7": ["Ćōũĺďń'ţ śēńď ţĥē śēĺēćţĩōń — ƥĺēàśē ţŕŷ àĝàĩń."],
+ "_gkGSK": ["ďēĺēţēď ţēḿƥĺàţē"],
"_qD6mn": ["Ƥĩćķ ţĥē ƒōĺďēŕ ŵĥēŕē ŷōũ'vē ćĺōńēď ĩţ."],
"_rP3HI": [["minutes"], "ḿ àĝō"],
+ "_tekeB": ["ũƥďàţēď ƒōĺďēŕ ƥŕōƥēŕţĩēś"],
"a-cKXz": ["Śēĺēćţ àĺĺ śōũŕćē"],
"a4_eNe": [
"ßŕàńćĥ śŵĩţćĥēď ƀũţ ţĥē ďōćũḿēńţ ćōũĺď ńōţ ƀē ōƥēńēď — ţŕŷ ńàvĩĝàţĩńĝ ţō ĩţ ḿàńũàĺĺŷ."
@@ -1419,6 +1431,7 @@
],
"jPUPvG": ["Ćōũĺďń'ţ ŕēśōĺvē ţĥē ćōńƒĺĩćţ ƒōŕ ", ["filePath"], "."],
"jRHdCz": ["Ƒàĩĺēď ţō ĺōàď ƤĎƑ"],
+ "jSO1X5": ["Ĩńĥēŕĩţēď ţēḿƥĺàţēś ćàń'ţ ƀē ŕēńàḿēď ĥēŕē — ŕēńàḿē ĩţ ĩń ţĥē ƒōĺďēŕ ţĥàţ ōŵńś ĩţ."],
"jSY41h": ["\"", ["docName"], "\" ţōōķ ţōō ĺōńĝ. Ćĥēćķ ŷōũŕ ćōńńēćţĩōń."],
"jTLWxh": ["Ēḿƀēď àń ēxţēŕńàĺ ƥàĝē ĩń àń ĩńĺĩńē ĩƒŕàḿē (ďōćś, ďēḿōś, Ƒĩĝḿà, ĆōďēŚàńďƀōx)."],
"jZ_E5M": ["Ƒēţćĥ ƒàĩĺēď — ćĥēćķ ţĥē śēŕvēŕ ĺōĝś ƒōŕ ďēţàĩĺś."],
@@ -1470,6 +1483,7 @@
"ky9Tuc": ["Ēďĩţ ", ["0"], " śōũŕćē"],
"l17ab4": ["Ćōũĺď ńōţ ŵŕĩţē ƥŕōĴēćţ ƒĩĺēś. Ţŕŷ à ďĩƒƒēŕēńţ ĺōćàţĩōń."],
"l1aQKz": ["Vĩśũàĺ ēďĩţōŕ ţàƀĺē"],
+ "l1l8sj": [["0"], "ď àĝō"],
"l3mSlL": ["Àƥƥēńď-ōńĺŷ ţĩḿēĺĩńē"],
"l6OXqI": ["Ńō ĩńśţàĺĺēď àĝēńţś ƒōũńď"],
"l6zqhi": ["ßŕàńćĥ śŵĩţćĥ ƒàĩĺēď — ţŕŷ ōƥēńĩńĝ ţĥē ďōć ḿàńũàĺĺŷ."],
@@ -1586,6 +1600,7 @@
"opEayO": [
"<0>.ōķ/</0>, <1>.ḿćƥ.Ĵśōń</1> (àńď ƥēŕ-ēďĩţōŕ vàŕĩàńţś), ƥŕōĴēćţ śķĩĺĺś, àńď <2>.ćĺàũďē/ĺàũńćĥ.Ĵśōń</2>. Śŵĩţćĥ ĺàţēŕ vĩà Śēţţĩńĝś → Śĥàŕĩńĝ ōŕ <3>ōķ śĥàŕĩńĝ śĥàŕē|ũńśĥàŕē</3>."
],
+ "optX0N": [["0"], "ĥ àĝō"],
"oqB2ez": ["Ƥŕēvĩōũś ḿàţćĥ"],
"ot5BRK": ["Ďũƥĺĩćàţē śēĺēćţēď ƒĩĺē ōŕ ƒōĺďēŕ"],
"otE4aj": ["Śĥōŵ ēxţēŕńàĺ ŨŔĹ ńōďēś"],
@@ -1628,6 +1643,7 @@
"pzutoc": ["Ĩţàĺĩć"],
"q2kXMG": ["Ĩńĺĩńē Ḿàţĥ"],
"q6-JVU": ["Ĺōàďĩńĝ ƥàĝēś"],
+ "q6IUff": ["Ŕēńàḿĩńĝ ḿōvēś ţĥē ƒĩĺē ōń ďĩśķ (à ĝĩţ ḿv) àńď ćĥàńĝēś ţĥē ĩď àĝēńţś ũśē."],
"q7zsRM": ["Ćōũĺďń'ţ śàvē vēŕśĩōń — ţŕŷ àĝàĩń"],
"qAQVSD": ["Ƥàĝē ĥēàďĩńĝś ŕēśƥōńśē ŵàś ńōţ ĵŚŌŃ"],
"qAhFeg": [
@@ -1698,6 +1714,7 @@
"s-XOaI": ["Ƒĩĺē ńàḿē"],
"s1c0ja": ["ßũĺĺēţ Ĺĩśţ"],
"s3caR3": ["Ďēĺēţĩńĝ"],
+ "s8XlGV": ["àćţĩvĩţŷ"],
"sE7R19": [
"Ćōũĺď ńōţ ĺōàď ţēḿƥĺàţēś: ",
["templatesError"],
@@ -1746,6 +1763,7 @@
"tgWuMB": ["Ḿōďĩƒĩēď"],
"tiWX6q": ["Śōũŕćē ēďĩţōŕ"],
"tjXez2": ["ƀĺōĝ-ƥōśţ"],
+ "tp15x4": ["ƒōĺďēŕ ƥŕōƥēŕţĩēś"],
"u-9fWA": ["Śēē <0>Àŕćĥĩţēćţũŕē</0> ƒōŕ ţĥē śŷśţēḿ ōvēŕvĩēŵ."],
"u0iUdo": [
"Ćĥŕōḿē àńď ţĥē ƥàĝē ũśē ţĥĩś ţō śēĺēćţ ţēxţ ōŕ ƥàĝē ćōńţēńţ. Ōƥēń Ķńōŵĺēďĝē ōńĺŷ ĥàńďĺēś ĩţ ŵĥēń ţĥē Ƒĩĺēś śĩďēƀàŕ ĥàś ƒōćũś."
@@ -1924,6 +1942,7 @@
"zaXlhf": [
"Ţĥē ƥŕōƥēŕţĩēś ƀĺōćķ àţ ţĥē ţōƥ ōƒ ţĥĩś ďōć ĥàś à ƒōŕḿàţţĩńĝ ēŕŕōŕ. Śŵĩţćĥ ţō śōũŕćē ḿōďē ţō ƒĩx ĩţ."
],
+ "zbymaY": [["0"], "ḿ àĝō"],
"zd00pH": ["Ćōƥŷ Ƥàţĥ"],
"zgSFyG": ["Ēxţēŕńàĺ ĺĩńķ"],
"zkWs-l": ["Śĥàŕĩńĝ ḿōďē ũńćĥàńĝēď — śēē ḿēśśàĝē ƀēĺōŵ."],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index a4398063f..6b6630474 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -121,6 +121,21 @@ msgstr ""
msgid "{0}/{1} {2}"
msgstr ""
+#. placeholder {0}: Math.floor(diffSec / 86400)
+#: src/components/FolderTimelineCard.tsx
+msgid "{0}d ago"
+msgstr ""
+
+#. placeholder {0}: Math.floor(diffSec / 3600)
+#: src/components/FolderTimelineCard.tsx
+msgid "{0}h ago"
+msgstr ""
+
+#. placeholder {0}: Math.floor(diffSec / 60)
+#: src/components/FolderTimelineCard.tsx
+msgid "{0}m ago"
+msgstr ""
+
#: src/components/SyncStatusBadge.tsx
msgid "{ahead, plural, one {# commit ahead} other {# commits ahead}}"
msgstr ""
@@ -475,6 +490,14 @@ msgstr ""
msgid "Active panel content for the selected tab shows here."
msgstr ""
+#: src/components/FolderTimelineCard.tsx
+#~ msgid "activity"
+#~ msgstr ""
+
+#: src/components/FolderTimelineCard.tsx
+msgid "Activity"
+msgstr ""
+
#. Primary button that writes MCP config for the selected AI tools
#: src/components/FrontmatterRow.tsx
#: src/components/McpConsentDialogBody.tsx
@@ -655,6 +678,7 @@ msgstr ""
msgid "Authorize in browser"
msgstr ""
+#: src/components/FolderTimelineCard.tsx
#: src/components/TimelinePanel.tsx
msgid "Auto-save"
msgstr ""
@@ -991,6 +1015,10 @@ msgstr ""
msgid "Clear {keyName}"
msgstr ""
+#: src/components/FolderTimelineCard.tsx
+msgid "cleared folder properties"
+msgstr ""
+
#: src/components/EditorActivityPool.tsx
msgid "Clearing local collaboration data for \"{docName}\" before reconnecting."
msgstr ""
@@ -1654,10 +1682,18 @@ msgstr ""
msgid "Create your first file"
msgstr ""
+#: src/components/FolderTimelineCard.tsx
+msgid "created folder"
+msgstr ""
+
#: src/components/SeedDialog.tsx
msgid "Created if missing; reused if it exists."
msgstr ""
+#: src/components/FolderTimelineCard.tsx
+msgid "created template"
+msgstr ""
+
#: src/components/CreateProjectDialog.tsx
#: src/components/NewItemDialog.tsx
#: src/components/NewTemplateDialog.tsx
@@ -1743,6 +1779,10 @@ msgstr ""
msgid "Delete selected table"
msgstr ""
+#: src/components/FolderTimelineCard.tsx
+msgid "deleted template"
+msgstr ""
+
#: src/components/DeleteConfirmationDialog.tsx
#: src/components/TrashFailureModal.tsx
msgid "Deleting"
@@ -1970,6 +2010,10 @@ msgstr ""
msgid "Edit with AI"
msgstr ""
+#: src/components/FolderTimelineCard.tsx
+msgid "edited template"
+msgstr ""
+
#: src/presence/PresenceBar.tsx
msgid "editing [[{realCurrentDoc}]]"
msgstr ""
@@ -2432,6 +2476,10 @@ msgstr ""
msgid "Folder name: {detail}"
msgstr ""
+#: src/components/FolderTimelineCard.tsx
+#~ msgid "folder properties"
+#~ msgstr ""
+
#: src/components/FolderPropertiesCard.tsx
msgid "Folder properties"
msgstr ""
@@ -2726,6 +2774,10 @@ msgstr ""
msgid "Inherited from {path}"
msgstr ""
+#: src/components/TemplateForm.tsx
+msgid "Inherited templates can't be renamed here — rename it in the folder that owns it."
+msgstr ""
+
#: src/components/SeedDialog.tsx
msgid "Initialize"
msgstr ""
@@ -2855,6 +2907,7 @@ msgid "Jump to page {pageNumber}"
msgstr ""
#: src/components/FolderOverview.tsx
+#: src/components/FolderTimelineCard.tsx
#: src/components/SyncStatusBadge.tsx
#: src/components/TimelinePanel.tsx
msgid "just now"
@@ -3232,6 +3285,10 @@ msgstr ""
msgid "Move up"
msgstr ""
+#: src/components/FolderTimelineCard.tsx
+msgid "moved template"
+msgstr ""
+
#: src/editor/slash-command/component-items.tsx
msgid "Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."
msgstr ""
@@ -4511,6 +4568,14 @@ msgstr ""
msgid "Rename succeeded but the tabstrip may be out of date — refresh to resync"
msgstr ""
+#: src/components/TemplateForm.tsx
+msgid "Renaming changes the file on disk and the id agents use to pick this template."
+msgstr ""
+
+#: src/components/TemplateForm.tsx
+#~ msgid "Renaming moves the file on disk (a git mv) and changes the id agents use."
+#~ msgstr ""
+
#: src/components/EditorActivityPool.tsx
msgid "Reopening \"{docName}\" with a fresh local collaboration cache."
msgstr ""
@@ -5378,6 +5443,10 @@ msgstr ""
msgid "Task List"
msgstr ""
+#: src/components/FolderTimelineCard.tsx
+#~ msgid "template"
+#~ msgstr ""
+
#: src/components/TemplateEditDialog.tsx
msgid "Template"
msgstr ""
@@ -5398,6 +5467,10 @@ msgstr ""
msgid "Template list"
msgstr ""
+#: src/components/TemplateForm.tsx
+msgid "Template renamed"
+msgstr ""
+
#: src/components/TemplateForm.tsx
msgid "Template saved"
msgstr ""
@@ -5765,6 +5838,10 @@ msgstr ""
msgid "Unified diff"
msgstr ""
+#: src/components/FolderTimelineCard.tsx
+msgid "Unknown"
+msgstr ""
+
#: src/editor/extensions/JsxComponentView.tsx
msgid "Unknown component: {componentName} — source editable below"
msgstr ""
@@ -5802,6 +5879,10 @@ msgstr ""
msgid "Update the destination and optional section anchor."
msgstr ""
+#: src/components/FolderTimelineCard.tsx
+msgid "updated folder properties"
+msgstr ""
+
#: src/components/PageHeaderWidgets.tsx
msgid "Upload {keyName}"
msgstr ""
diff --git a/packages/app/tests/integration/api-error-envelope/template.test.ts b/packages/app/tests/integration/api-error-envelope/template.test.ts
index 3dc44cbcb..9780d5ddf 100644
--- a/packages/app/tests/integration/api-error-envelope/template.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/template.test.ts
@@ -152,10 +152,10 @@ describe('template envelope (RFC 9457)', () => {
expect(body.existed).toBe(true);
});
- test('method-not-allowed on PATCH emits problem+json with Allow: GET, PUT, DELETE', async () => {
+ test('method-not-allowed on PATCH emits problem+json with Allow: GET, PUT, POST, DELETE', async () => {
const res = await fetch(`http://127.0.0.1:${server.port}/api/template`, { method: 'PATCH' });
expect(res.status).toBe(405);
- expect(res.headers.get('allow')).toBe('GET, PUT, DELETE');
+ expect(res.headers.get('allow')).toBe('GET, PUT, POST, DELETE');
const body = await res.json();
const parsed = ProblemDetailsSchema.safeParse(body);
diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.ts
index ad3545fc5..ca2677fa6 100644
--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts
+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts
@@ -17,6 +17,7 @@ const REQUIRED_HANDLERS = [
'handleTemplate',
'handleTemplatePut',
'handleTemplateDelete',
+ 'handleTemplateMove',
];
const EXEMPT_HANDLERS = new Set([
@@ -138,7 +139,9 @@ describe('conflict-gate coverage (FR9)', () => {
const spineRouting =
body.includes('applyAgentMarkdownWrite(') || body.includes('applyAgentUndo(');
const dispatcherRouting =
- body.includes('handleTemplatePut(') || body.includes('handleTemplateDelete(');
+ body.includes('handleTemplatePut(') ||
+ body.includes('handleTemplateDelete(') ||
+ body.includes('handleTemplateMove(');
if (!directGate && !spineRouting && !dispatcherRouting) {
failures.push(
`${handler}: missing conflict gate — must call respondDocInConflict(...) directly, route through applyAgentMarkdownWrite/applyAgentUndo, or dispatch to a gated sub-handler`,
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 8532d869d..38ce197bf 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -752,6 +752,10 @@ export {
TemplateFrontmatterSchema,
type TemplateGetSuccess,
TemplateGetSuccessSchema,
+ type TemplateMoveRequest,
+ TemplateMoveRequestSchema,
+ type TemplateMoveSuccess,
+ TemplateMoveSuccessSchema,
type TemplatePayload,
TemplatePayloadSchema,
type TemplatePutRequest,
diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.ts
index c5dcb3d55..70cad26ea 100644
--- a/packages/core/src/schemas/api/tags-search.ts
+++ b/packages/core/src/schemas/api/tags-search.ts
@@ -1,5 +1,6 @@
import type { StandardSchemaV1 } from '@standard-schema/spec';
import { z } from 'zod';
+import { agentIdentityFields, summaryField } from './_shared.ts';
export const TagSummaryEntrySchema = z
.object({
@@ -107,6 +108,8 @@ export const TemplatePutRequestSchema = z
name: z.string(),
body: z.string().optional(),
frontmatter: TemplateFrontmatterSchema.optional(),
+ ...agentIdentityFields,
+ summary: summaryField,
})
.strict() satisfies StandardSchemaV1;
export type TemplatePutRequest = z.infer<typeof TemplatePutRequestSchema>;
@@ -128,6 +131,29 @@ export const TemplateDeleteSuccessSchema = z
.strict() satisfies StandardSchemaV1;
export type TemplateDeleteSuccess = z.infer<typeof TemplateDeleteSuccessSchema>;
+export const TemplateMoveRequestSchema = z
+ .object({
+ fromFolder: z.string(),
+ fromName: z.string(),
+ toFolder: z.string(),
+ toName: z.string(),
+ body: z.string().optional(),
+ frontmatter: TemplateFrontmatterSchema.optional(),
+ ...agentIdentityFields,
+ summary: summaryField,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type TemplateMoveRequest = z.infer<typeof TemplateMoveRequestSchema>;
+
+export const TemplateMoveSuccessSchema = z
+ .object({
+ from: z.string().min(1),
+ to: z.string().min(1),
+ committed: z.boolean(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type TemplateMoveSuccess = z.infer<typeof TemplateMoveSuccessSchema>;
+
export const SearchRequestSchema = z
.object({
query: z.string().optional(),
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index e9c4363fb..86109d18d 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -154,6 +154,8 @@ import {
TagsListSuccessSchema,
TemplateDeleteSuccessSchema,
TemplateGetSuccessSchema,
+ TemplateMoveRequestSchema,
+ TemplateMoveSuccessSchema,
TemplatePutRequestSchema,
TemplatePutSuccessSchema,
TemplatesListSuccessSchema,
@@ -207,6 +209,7 @@ import {
} from './content/templates-resolver.ts';
import {
applyTemplateDelete,
+ applyTemplateMove,
applyTemplateWrite,
type TemplateFrontmatter,
} from './content/templates-write.ts';
@@ -434,7 +437,7 @@ import { SuggestLinksTargetNotFoundError, suggestLinks } from './suggest-links.t
import type { SyncEngine } from './sync-engine.ts';
import type { TagIndex } from './tag-index.ts';
import { getMeter, getTracer, withSpan, withSpanSync } from './telemetry.ts';
-import { getDocumentHistory } from './timeline-query.ts';
+import { getDocumentHistory, getFolderTimeline } from './timeline-query.ts';
let _httpDurationHist: ReturnType<ReturnType<typeof getMeter>['createHistogram']> | null = null;
function httpDurationHist(): ReturnType<ReturnType<typeof getMeter>['createHistogram']> {
@@ -2983,6 +2986,50 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
}
+ function okArtifactKey(
+ kind: 'template' | 'folder-frontmatter' | 'folder',
+ folder: string,
+ name?: string,
+ ): string {
+ const base = folder.replace(/\/$/, '');
+ const prefix = base === '' ? '' : `${base}/`;
+ if (kind === 'template') return `${prefix}.ok/templates/${name}`;
+ if (kind === 'folder-frontmatter') return `${prefix}.ok/frontmatter`;
+ return base === '' ? '.' : base;
+ }
+
+ function attributeOkArtifactWrite(
+ actor: ReturnType<typeof extractActorIdentity>,
+ artifactKey: string,
+ subject: string,
+ previousPaths?: Array<{ from: string; to: string }>,
+ ): void {
+ if (actor.kind !== 'agent' && actor.kind !== 'principal') return;
+ const summaryFields = summaryResponseFields(actor.summary);
+ recordContributor(
+ artifactKey,
+ actor.writerId,
+ actor.displayName,
+ actor.colorSeed,
+ subject,
+ actor.actor,
+ summaryFields.stored,
+ previousPaths,
+ );
+ }
+
+ async function commitOkArtifactWrite(context: string): Promise<void> {
+ if (!flushContributors) return;
+ try {
+ await flushContributors();
+ } catch (flushErr) {
+ console.warn(
+ `[${context}] flushContributors failed; attribution stays queued for the next flush:`,
+ flushErr,
+ );
+ }
+ }
+
const handleAgentWrite = withValidation(
AgentWriteRequestSchema,
async (_req, res, body) => {
@@ -5121,13 +5168,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
const docName = url.searchParams.get('docName') ?? '';
+ const folderParam = url.searchParams.get('folder');
const branch = url.searchParams.get('branch') ?? getCurrentBranch?.() ?? 'main';
- if (!docName) {
+ if (!docName && folderParam === null) {
errorResponse(
res,
400,
'urn:ok:error:invalid-request',
- 'docName query parameter is required.',
+ 'A docName or folder query parameter is required.',
{ handler: 'history' },
);
return;
@@ -5140,6 +5188,22 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return;
}
+ if (folderParam !== null && !docName) {
+ const validated = validateFolderRel(folderParam, res, 'folder', 'history');
+ if (!validated) return;
+ const rawFolderLimit = Number(url.searchParams.get('limit') ?? '50');
+ const folderLimit = Math.min(200, Number.isFinite(rawFolderLimit) ? rawFolderLimit : 50);
+ const rawFolderOffset = Number(url.searchParams.get('offset') ?? '0');
+ const folderOffset = Math.max(0, Number.isFinite(rawFolderOffset) ? rawFolderOffset : 0);
+ const result = await getFolderTimeline(shadow, validated.folderRel, contentRoot ?? '.', {
+ branch,
+ limit: folderLimit,
+ offset: folderOffset,
+ });
+ successResponse(res, 200, HistorySuccessSchema, { ...result }, { handler: 'history' });
+ return;
+ }
+
const resolvedContentRoot = contentRoot ?? '.';
const docPathResult = safeDocPath(docName, resolvedContentRoot);
if ('error' in docPathResult) {
@@ -9478,6 +9542,34 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return true;
}
+ function findTemplateLeafToRoot(
+ resolvedContentDir: string,
+ folderRel: string,
+ name: string,
+ ): { abs: string; folder: string; scope: 'local' | 'inherited' } | null {
+ const segments = folderRel === '' ? [] : folderRel.split('/');
+ for (let depth = segments.length; depth >= 0; depth--) {
+ const ancestorFolder = depth === 0 ? '' : segments.slice(0, depth).join('/');
+ const ancestorAbs =
+ ancestorFolder === '' ? resolvedContentDir : resolve(resolvedContentDir, ancestorFolder);
+ if (
+ ancestorAbs !== resolvedContentDir &&
+ !ancestorAbs.startsWith(`${resolvedContentDir}${sep}`)
+ ) {
+ continue;
+ }
+ const candidate = resolve(ancestorAbs, '.ok', 'templates', `${name}.md`);
+ if (existsSync(candidate)) {
+ return {
+ abs: candidate,
+ folder: ancestorFolder,
+ scope: depth === segments.length ? 'local' : 'inherited',
+ };
+ }
+ }
+ return null;
+ }
+
function pickFrontmatterFields(raw: unknown): Record<string, unknown> {
const out: Record<string, unknown> = {};
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
@@ -9562,6 +9654,16 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
FolderConfigPutRequestSchema,
async (_req, res, body) => {
try {
+ const actor = extractActorIdentity(
+ body as unknown as Record<string, unknown>,
+ getPrincipal,
+ );
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'folder-config-put',
+ });
+ return;
+ }
const validated = validateFolderRel(body.path, res, 'path', 'folder-config-put');
if (!validated) return;
@@ -9587,6 +9689,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return;
}
allApplied.push({ path: result.path, action: result.action });
+ if (result.action !== 'noop') {
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('folder-frontmatter', validated.folderRel),
+ `folder-frontmatter-${result.action === 'deleted' ? 'delete' : 'edit'}: ${result.path}`,
+ );
+ await commitOkArtifactWrite('folder-config-put');
+ }
}
successResponse(
@@ -9612,7 +9722,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
function checkTemplateConflictGate(
folder: string,
name: string,
- handler: 'template-put' | 'template-delete',
+ handler: 'template-put' | 'template-delete' | 'template-move',
res: ServerResponse,
): boolean {
if (!name) return false;
@@ -9662,12 +9772,15 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
if (req.method === 'PUT') {
return handleTemplatePut(req, res);
}
+ if (req.method === 'POST') {
+ return handleTemplateMove(req, res);
+ }
if (req.method === 'DELETE') {
return handleTemplateDelete(req, res);
}
errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {
handler: 'template',
- extraHeaders: { Allow: 'GET, PUT, DELETE' },
+ extraHeaders: { Allow: 'GET, PUT, POST, DELETE' },
});
}
@@ -9707,39 +9820,15 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
if (!validated) return;
const { folderRel, resolvedContentDir } = validated;
- const segments = folderRel === '' ? [] : folderRel.split('/');
- let foundAbs: string | null = null;
- let foundFolder: string | null = null;
- let foundScope: 'local' | 'inherited' | null = null;
-
- for (let depth = segments.length; depth >= 0; depth--) {
- const ancestorFolder = depth === 0 ? '' : segments.slice(0, depth).join('/');
- const ancestorAbs =
- ancestorFolder === ''
- ? resolvedContentDir
- : resolve(resolvedContentDir, ancestorFolder);
- if (
- ancestorAbs !== resolvedContentDir &&
- !ancestorAbs.startsWith(`${resolvedContentDir}${sep}`)
- ) {
- continue;
- }
- const candidate = resolve(ancestorAbs, '.ok', 'templates', `${name}.md`);
- if (existsSync(candidate)) {
- foundAbs = candidate;
- foundFolder = ancestorFolder;
- foundScope = depth === segments.length ? 'local' : 'inherited';
- break;
- }
- }
-
- if (!foundAbs || foundFolder === null || foundScope === null) {
+ const found = findTemplateLeafToRoot(resolvedContentDir, folderRel, name);
+ if (!found) {
errorResponse(res, 404, 'urn:ok:error:template-not-found', 'Template not found.', {
handler: 'template-get',
detail: `Template "${name}" not found for folder "${folderRel || '.'}". Walked leaf → root.`,
});
return;
}
+ const { abs: foundAbs, folder: foundFolder, scope: foundScope } = found;
const raw = await readFile(foundAbs, 'utf-8');
const { frontmatter, body } = parseTemplateFile(raw);
@@ -9779,6 +9868,16 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
TemplatePutRequestSchema,
async (_req, res, body) => {
try {
+ const actor = extractActorIdentity(
+ body as unknown as Record<string, unknown>,
+ getPrincipal,
+ );
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'template-put',
+ });
+ return;
+ }
const name = body.name;
if (!validateTemplateName(name, res, 'template-put')) return;
const validated = validateFolderRel(body.folder, res, 'folder', 'template-put');
@@ -9809,6 +9908,12 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
});
return;
}
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('template', validated.folderRel, name),
+ `${result.created ? 'template-create' : 'template-edit'}: ${result.path}`,
+ );
+ await commitOkArtifactWrite('template-put');
successResponse(
res,
200,
@@ -9845,6 +9950,26 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
if (!validated) return;
+ const sp = url.searchParams;
+ const actor = extractActorIdentity(
+ {
+ agentId: sp.get('agentId') ?? undefined,
+ agentName: sp.get('agentName') ?? undefined,
+ colorSeed: sp.get('colorSeed') ?? undefined,
+ clientName: sp.get('clientName') ?? undefined,
+ clientVersion: sp.get('clientVersion') ?? undefined,
+ label: sp.get('label') ?? undefined,
+ summary: sp.get('summary') ?? undefined,
+ },
+ getPrincipal,
+ );
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'template-delete',
+ });
+ return;
+ }
+
if (checkTemplateConflictGate(validated.folderRel, name, 'template-delete', res)) return;
const deleteInput: Parameters<typeof applyTemplateDelete>[0] = {
@@ -9870,6 +9995,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
});
return;
}
+ if (result.existed) {
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('template', validated.folderRel, name),
+ `template-delete: ${result.path}`,
+ );
+ await commitOkArtifactWrite('template-delete');
+ }
successResponse(
res,
200,
@@ -9890,6 +10023,166 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'template-delete', method: 'DELETE', skipBodyParse: true },
);
+ const handleTemplateMove = withValidation(
+ TemplateMoveRequestSchema,
+ async (_req, res, body) => {
+ try {
+ const actor = extractActorIdentity(
+ body as unknown as Record<string, unknown>,
+ getPrincipal,
+ );
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'template-move',
+ });
+ return;
+ }
+ if (!validateTemplateName(body.fromName, res, 'template-move')) return;
+ if (!validateTemplateName(body.toName, res, 'template-move')) return;
+ const fromValidated = validateFolderRel(body.fromFolder, res, 'folder', 'template-move');
+ if (!fromValidated) return;
+ const toValidated = validateFolderRel(body.toFolder, res, 'folder', 'template-move');
+ if (!toValidated) return;
+
+ if (
+ checkTemplateConflictGate(fromValidated.folderRel, body.fromName, 'template-move', res)
+ ) {
+ return;
+ }
+
+ const result = await applyTemplateMove({
+ projectDir: fromValidated.resolvedContentDir,
+ fromFolder: fromValidated.folderRel,
+ fromName: body.fromName,
+ toFolder: toValidated.folderRel,
+ toName: body.toName,
+ relocate: async (fromAbs, toAbs) => {
+ const movedWithGit = await renameTrackedPathInGit(projectDir, fromAbs, toAbs);
+ if (!movedWithGit) renamePathOnDisk(fromAbs, toAbs);
+ return movedWithGit;
+ },
+ });
+
+ if (!result.ok) {
+ if (result.error.code === 'TEMPLATE_NOT_FOUND') {
+ const found = findTemplateLeafToRoot(
+ fromValidated.resolvedContentDir,
+ fromValidated.folderRel,
+ body.fromName,
+ );
+ if (found?.scope === 'inherited') {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ `Template "${body.fromName}" is inherited from "${found.folder || '(root)'}", not local to "${fromValidated.folderRel || '(root)'}". Move it from the folder that owns it, or create a local copy here first (then move that).`,
+ { handler: 'template-move', detail: 'TEMPLATE_INHERITED' },
+ );
+ return;
+ }
+ errorResponse(res, 404, 'urn:ok:error:template-not-found', 'Template not found.', {
+ handler: 'template-move',
+ detail: result.error.message,
+ });
+ return;
+ }
+ if (result.error.code === 'TEMPLATE_EXISTS') {
+ errorResponse(res, 409, 'urn:ok:error:doc-already-exists', result.error.message, {
+ handler: 'template-move',
+ detail: result.error.code,
+ });
+ return;
+ }
+ const status =
+ result.error.code === 'WRITE_ERROR' || result.error.code === 'MOVE_FAILED' ? 500 : 400;
+ errorResponse(
+ res,
+ status,
+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
+ status === 500 ? 'Failed to move template.' : 'Invalid template move request.',
+ {
+ handler: 'template-move',
+ detail: result.error.code,
+ cause: new Error(result.error.message),
+ },
+ );
+ return;
+ }
+
+ let contentEditError: { code: string; message: string } | null = null;
+ if (body.body !== undefined || body.frontmatter !== undefined) {
+ let writeBody: string | null;
+ if (typeof body.body === 'string') {
+ writeBody = body.body;
+ } else {
+ try {
+ writeBody = parseTemplateFile(
+ readFileSync(resolve(toValidated.resolvedContentDir, result.toPath), 'utf-8'),
+ ).body;
+ } catch {
+ writeBody = null;
+ }
+ }
+ if (writeBody === null) {
+ contentEditError = {
+ code: 'READ_FAILED',
+ message:
+ 'could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit',
+ };
+ } else {
+ const writeResult = applyTemplateWrite({
+ projectDir: toValidated.resolvedContentDir,
+ folder: toValidated.folderRel,
+ name: body.toName,
+ body: writeBody,
+ frontmatter: pickFrontmatterFields(body.frontmatter) satisfies TemplateFrontmatter,
+ });
+ if (!writeResult.ok) contentEditError = writeResult.error;
+ }
+ }
+
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('template', toValidated.folderRel, body.toName),
+ `template-rename: ${result.fromPath} -> ${result.toPath}`,
+ [{ from: result.fromPath, to: result.toPath }],
+ );
+ await commitOkArtifactWrite('template-move');
+ signalChannel?.('files');
+
+ if (contentEditError) {
+ const isServerError =
+ contentEditError.code === 'WRITE_ERROR' || contentEditError.code === 'READ_FAILED';
+ errorResponse(
+ res,
+ isServerError ? 500 : 400,
+ isServerError ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
+ `Template moved to "${result.toPath}", but updating its content failed.`,
+ {
+ handler: 'template-move',
+ detail: contentEditError.code,
+ cause: new Error(contentEditError.message),
+ },
+ );
+ return;
+ }
+ successResponse(
+ res,
+ 200,
+ TemplateMoveSuccessSchema,
+ { from: result.fromPath, to: result.toPath, committed: result.committed },
+ { handler: 'template-move' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to move template.', {
+ handler: 'template-move',
+ cause: e,
+ });
+ }
+ },
+ { handler: 'template-move', method: 'POST' },
+ );
+
function deriveFolderSearchDocuments(
pages: readonly WorkspaceSearchDocument[],
): WorkspaceSearchDocument[] {
diff --git a/packages/server/src/content/templates-write.test.ts b/packages/server/src/content/templates-write.test.ts
index a58d67abf..781c816b0 100644
--- a/packages/server/src/content/templates-write.test.ts
+++ b/packages/server/src/content/templates-write.test.ts
@@ -1,9 +1,9 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { applyTemplateDelete, applyTemplateWrite } from './templates-write.ts';
+import { applyTemplateDelete, applyTemplateMove, applyTemplateWrite } from './templates-write.ts';
describe('applyTemplateWrite', () => {
let projectDir: string;
@@ -281,3 +281,140 @@ describe('applyTemplateDelete', () => {
expect(existsSync(join(projectDir, 'sentinel'))).toBe(true);
});
});
+
+describe('applyTemplateMove', () => {
+ let projectDir: string;
+
+ beforeEach(async () => {
+ projectDir = await mkdtemp(join(tmpdir(), 'tpl-move-'));
+ });
+
+ afterEach(async () => {
+ await rm(projectDir, { recursive: true, force: true });
+ });
+
+ const fsRelocate = async (from: string, to: string) => {
+ renameSync(from, to);
+ return false;
+ };
+
+ function seed(folder: string, name: string, body = '# T') {
+ applyTemplateWrite({ projectDir, folder, name, body, frontmatter: { title: 'T' } });
+ }
+ const tplPath = (folder: string, name: string) =>
+ join(projectDir, folder, '.ok', 'templates', `${name}.md`);
+
+ test('renames within the same folder', async () => {
+ seed('research', 'a', '# A');
+ const result = await applyTemplateMove({
+ projectDir,
+ fromFolder: 'research',
+ fromName: 'a',
+ toFolder: 'research',
+ toName: 'b',
+ relocate: fsRelocate,
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.committed).toBe(false);
+ expect(existsSync(tplPath('research', 'a'))).toBe(false);
+ expect(existsSync(tplPath('research', 'b'))).toBe(true);
+ expect(readFileSync(tplPath('research', 'b'), 'utf-8')).toContain('# A');
+ });
+
+ test('moves across folders and auto-cleans the emptied source .ok/', async () => {
+ seed('research', 'scorecard');
+ const result = await applyTemplateMove({
+ projectDir,
+ fromFolder: 'research',
+ fromName: 'scorecard',
+ toFolder: 'projects',
+ toName: 'scorecard',
+ relocate: fsRelocate,
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(existsSync(tplPath('projects', 'scorecard'))).toBe(true);
+ expect(result.cleanedEmpty.templatesDir).toBe(true);
+ expect(result.cleanedEmpty.okDir).toBe(true);
+ expect(existsSync(join(projectDir, 'research', '.ok'))).toBe(false);
+ });
+
+ test('propagates committed=true from a git-mv relocator', async () => {
+ seed('research', 'a');
+ const result = await applyTemplateMove({
+ projectDir,
+ fromFolder: 'research',
+ fromName: 'a',
+ toFolder: 'research',
+ toName: 'b',
+ relocate: async (from, to) => {
+ renameSync(from, to);
+ return true;
+ },
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.committed).toBe(true);
+ });
+
+ test('404s when the source is absent (exact folder; inherited not resolved here)', async () => {
+ seed('research', 'a'); // ancestor copy only
+ const result = await applyTemplateMove({
+ projectDir,
+ fromFolder: 'research/sub',
+ fromName: 'a',
+ toFolder: 'research/sub',
+ toName: 'b',
+ relocate: fsRelocate,
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('TEMPLATE_NOT_FOUND');
+ });
+
+ test('409s when the destination already exists', async () => {
+ seed('research', 'a');
+ seed('research', 'b');
+ const result = await applyTemplateMove({
+ projectDir,
+ fromFolder: 'research',
+ fromName: 'a',
+ toFolder: 'research',
+ toName: 'b',
+ relocate: fsRelocate,
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('TEMPLATE_EXISTS');
+ });
+
+ test('rejects a no-op move (same path)', async () => {
+ seed('research', 'a');
+ const result = await applyTemplateMove({
+ projectDir,
+ fromFolder: 'research',
+ fromName: 'a',
+ toFolder: 'research',
+ toName: 'a',
+ relocate: fsRelocate,
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('NOOP');
+ });
+
+ test('rejects a traversal-escaping name', async () => {
+ const result = await applyTemplateMove({
+ projectDir,
+ fromFolder: 'research',
+ fromName: '../escape',
+ toFolder: 'research',
+ toName: 'b',
+ relocate: fsRelocate,
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('BAD_NAME');
+ });
+});
diff --git a/packages/server/src/content/templates-write.ts b/packages/server/src/content/templates-write.ts
index 6e8b84168..629862161 100644
--- a/packages/server/src/content/templates-write.ts
+++ b/packages/server/src/content/templates-write.ts
@@ -151,6 +151,18 @@ export function applyTemplateDelete(input: DeleteTemplateInput): TemplateDeleteR
}
}
+ return {
+ ok: true,
+ path: relPathOf(input.projectDir, filePath),
+ existed,
+ cleanedEmpty: cleanEmptyOkDirs(templatesDir, okDir),
+ };
+}
+
+function cleanEmptyOkDirs(
+ templatesDir: string,
+ okDir: string,
+): { templatesDir: boolean; okDir: boolean } {
let templatesCleaned = false;
let okCleaned = false;
if (existsSync(templatesDir) && isEmpty(templatesDir)) {
@@ -165,12 +177,98 @@ export function applyTemplateDelete(input: DeleteTemplateInput): TemplateDeleteR
okCleaned = true;
} catch {}
}
+ return { templatesDir: templatesCleaned, okDir: okCleaned };
+}
+
+interface MoveTemplateInput {
+ projectDir: string;
+ fromFolder: string;
+ fromName: string;
+ toFolder: string;
+ toName: string;
+ relocate: (fromAbs: string, toAbs: string) => Promise<boolean>;
+}
+
+type TemplateMoveResult =
+ | {
+ ok: true;
+ fromPath: string;
+ toPath: string;
+ committed: boolean;
+ cleanedEmpty: { templatesDir: boolean; okDir: boolean };
+ }
+ | {
+ ok: false;
+ error: { code: string; message: string };
+ };
+
+export async function applyTemplateMove(input: MoveTemplateInput): Promise<TemplateMoveResult> {
+ const fromValidation = validateInputs(input.projectDir, input.fromFolder, input.fromName);
+ if (!fromValidation.ok) return { ok: false, error: fromValidation.error };
+ const toValidation = validateInputs(input.projectDir, input.toFolder, input.toName);
+ if (!toValidation.ok) return { ok: false, error: toValidation.error };
+
+ const from = templatePaths(input.projectDir, fromValidation.folderRel, input.fromName);
+ const to = templatePaths(input.projectDir, toValidation.folderRel, input.toName);
+
+ if (from.filePath === to.filePath) {
+ return {
+ ok: false,
+ error: { code: 'NOOP', message: 'Source and destination are the same template.' },
+ };
+ }
+ if (!existsSync(from.filePath)) {
+ return {
+ ok: false,
+ error: {
+ code: 'TEMPLATE_NOT_FOUND',
+ message: `No template at ${relPathOf(input.projectDir, from.filePath)}.`,
+ },
+ };
+ }
+ if (existsSync(to.filePath)) {
+ return {
+ ok: false,
+ error: {
+ code: 'TEMPLATE_EXISTS',
+ message: `A template already exists at ${relPathOf(input.projectDir, to.filePath)}.`,
+ },
+ };
+ }
+
+ try {
+ mkdirSync(to.templatesDir, { recursive: true });
+ } catch (err) {
+ return {
+ ok: false,
+ error: {
+ code: 'WRITE_ERROR',
+ message: `Failed to create destination template directory at ${relPathOf(input.projectDir, to.templatesDir)}: ${(err as Error).message}`,
+ },
+ };
+ }
+
+ let committed: boolean;
+ try {
+ committed = await input.relocate(from.filePath, to.filePath);
+ } catch (err) {
+ return {
+ ok: false,
+ error: {
+ code: 'MOVE_FAILED',
+ message: `Failed to move template: ${(err as Error).message}`,
+ },
+ };
+ }
+
+ const cleanedEmpty = cleanEmptyOkDirs(from.templatesDir, from.okDir);
return {
ok: true,
- path: relPathOf(input.projectDir, filePath),
- existed,
- cleanedEmpty: { templatesDir: templatesCleaned, okDir: okCleaned },
+ fromPath: relPathOf(input.projectDir, from.filePath),
+ toPath: relPathOf(input.projectDir, to.filePath),
+ committed,
+ cleanedEmpty,
};
}
diff --git a/packages/server/src/mcp/tools/delete.ts b/packages/server/src/mcp/tools/delete.ts
index ad35a09d0..8a6d3013c 100644
--- a/packages/server/src/mcp/tools/delete.ts
+++ b/packages/server/src/mcp/tools/delete.ts
@@ -1,11 +1,11 @@
import { z } from 'zod';
-import { applyTemplateDelete } from '../../content/templates-write.ts';
import type { AgentIdentity } from '../agent-identity.ts';
import { resolvePreviewUrlForTool } from './preview-url.ts';
import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
import {
agentIdentityFields,
HOCUSPOCUS_NOT_RUNNING_ERROR,
+ httpDelete,
httpPost,
looseObjectArray,
normalizeDocName,
@@ -23,7 +23,7 @@ const BASE_DESCRIPTION = [
'',
'- `document` — Doc path(s) to delete (a single path or an array). Inbound links become redlinks. Irreversible. [Requires: Hocuspocus server]',
'- `folder` — Folder path to delete (recursive). [Requires: Hocuspocus server]',
- '- `template` — `{ path: "<folder>/<name>" }` — a template to delete (fs-direct; auto-cleans empty `.ok/`).',
+ '- `template` — `{ path: "<folder>/<name>" }` — a template to delete (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]',
'- `asset` — `{ path: "<folder>/<file.ext>" }` — a binary asset to delete. [Requires: Hocuspocus server]',
'',
'Call `links({ kind: "backlinks", document })` BEFORE deleting a doc to see what links here.',
@@ -182,13 +182,19 @@ export function register(server: ServerInstance, deps: DeleteDeps): void {
const resolved = resolveTemplatePath(args.template.path);
if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
const { folder, name } = resolved;
- const result = applyTemplateDelete({ projectDir: cwd, folder, name });
- if (!result.ok) return textResult(`Error: ${result.error.message}`, true);
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ const params = new URLSearchParams({ folder, name });
+ for (const [key, value] of Object.entries(agentIdentityFields(deps.identityRef?.current))) {
+ if (typeof value === 'string' && value.length > 0) params.set(key, value);
+ }
+ const result = await httpDelete(url, `/api/template?${params.toString()}`);
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ const existed = result.existed === true;
return textPlusStructured(
- result.existed
+ existed
? `Deleted template "${name}" from ${folder || '(root)'}.`
: `Template "${name}" did not exist in ${folder || '(root)'} — nothing to delete.`,
- { template: { ok: true, existed: result.existed } },
+ { template: { ok: true, existed } },
);
}
diff --git a/packages/server/src/mcp/tools/edit.ts b/packages/server/src/mcp/tools/edit.ts
index 92cb4042b..b534e81ed 100644
--- a/packages/server/src/mcp/tools/edit.ts
+++ b/packages/server/src/mcp/tools/edit.ts
@@ -3,9 +3,8 @@ import { renderInventoryFooter, stripFrontmatter } from '@inkeep/open-knowledge-
import { parse as parseYaml } from 'yaml';
import { z } from 'zod';
import { resolveContentDir, resolveLockDir } from '../../config/paths.ts';
-import { applyFolderFrontmatterPatch } from '../../content/folder-frontmatter-write.ts';
import { mergePatch } from '../../content/frontmatter-merge.ts';
-import { applyTemplateWrite, type TemplateFrontmatter } from '../../content/templates-write.ts';
+import type { TemplateFrontmatter } from '../../content/templates-write.ts';
import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
import type { AgentIdentity } from '../agent-identity.ts';
import { formatContentDivergenceLine, parseContentDivergence } from './content-divergence.ts';
@@ -17,6 +16,7 @@ import {
documentResultBaseShape,
HOCUSPOCUS_NOT_RUNNING_ERROR,
httpPost,
+ httpPut,
nestDocResult,
normalizeDocName,
outputSchemaWithText,
@@ -43,8 +43,8 @@ const BASE_DESCRIPTION = [
'',
'- `document` — Edit a doc [Requires: Hocuspocus server]. Body: `{ path, find, replace, occurrence? }` (occurrence = which match, 1 = first). Metadata: `{ path, frontmatter }` (merge-patch; `null` deletes a key). Body find/replace is body-only; frontmatter-intersecting finds are rejected.',
'- `folder` — Edit a folder (folders have no body): `{ path, frontmatter }` (merge-patch).',
- '- `template` — Edit a template (fs-direct): `{ path: "<folder>/<name>", ... }`; body `find`/`replace`/`occurrence?` or metadata `frontmatter`.',
- '- `summary` — Optional one-line user-outcome (≤80 chars) for the timeline, recorded for DOCUMENT edits only (folder and template edits are fs-direct git rewrites and do not record a timeline summary). Avoid secrets or PII — persisted to git history.',
+ '- `template` — Edit a template: `{ path: "<folder>/<name>", ... }`; body `find`/`replace`/`occurrence?` or metadata `frontmatter`.',
+ '- `summary` — Optional one-line user-outcome (≤80 chars) recorded in the timeline for any `document`, `folder`, or `template` edit. Avoid secrets or PII — persisted to git history.',
'',
'Responses may include `structuredContent.document.contentDivergence` when the converged Y.Text doesn\'t match the bytes your edit composed to. The edit still landed; re-read the doc with `exec("cat <path>")` to see what converged.',
].join('\n');
@@ -300,7 +300,7 @@ function parseTemplateFrontmatter(raw: string): TemplateFrontmatter {
};
}
-function handleTemplate(
+async function handleTemplate(
template: {
path: string;
find?: string;
@@ -308,7 +308,10 @@ function handleTemplate(
occurrence?: number;
frontmatter?: FrontmatterPatch;
},
+ summary: string | undefined,
cwd: string,
+ url: string | undefined,
+ deps: EditDeps,
) {
const teaching = bodyOrFrontmatterError(template, 'template');
if (teaching) return textResult(`Error: ${teaching}`, true);
@@ -317,6 +320,7 @@ function handleTemplate(
if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
const { folder, name } = resolved;
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
const filePath = templateFilePath(cwd, folder, name);
if (!filePath.ok || !existsSync(filePath.abs)) {
return textResult(
@@ -338,11 +342,22 @@ function handleTemplate(
existingFm as Record<string, unknown>,
template.frontmatter as Record<string, unknown>,
) as TemplateFrontmatter;
- const result = applyTemplateWrite({ projectDir: cwd, folder, name, body, frontmatter: merged });
- if (!result.ok) return textResult(`Error: ${result.error.message}`, true);
- return textPlusStructured(`Patched template "${name}" frontmatter (${result.path}).`, {
- template: { ok: true, path: result.path },
+ const result = await httpPut(url, '/api/template', {
+ folder,
+ name,
+ body,
+ frontmatter: merged,
+ ...(summary !== undefined ? { summary } : {}),
+ ...agentIdentityFields(deps.identityRef?.current),
});
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ const path = typeof result.path === 'string' ? result.path : undefined;
+ return textPlusStructured(
+ `Patched template "${name}" frontmatter${path ? ` (${path})` : ''}.`,
+ {
+ template: { ok: true, path },
+ },
+ );
}
const occurrence = template.occurrence ?? 1;
@@ -357,30 +372,41 @@ function handleTemplate(
body.slice(0, idx) +
(template.replace as string) +
body.slice(idx + (template.find as string).length);
- const result = applyTemplateWrite({
- projectDir: cwd,
+ const result = await httpPut(url, '/api/template', {
folder,
name,
body: newBody,
frontmatter: existingFm,
+ ...(summary !== undefined ? { summary } : {}),
+ ...agentIdentityFields(deps.identityRef?.current),
});
- if (!result.ok) return textResult(`Error: ${result.error.message}`, true);
- return textPlusStructured(`Edited template "${name}" (${result.path}).`, {
- template: { ok: true, path: result.path },
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ const path = typeof result.path === 'string' ? result.path : undefined;
+ return textPlusStructured(`Edited template "${name}"${path ? ` (${path})` : ''}.`, {
+ template: { ok: true, path },
});
}
-function handleFolder(folder: { path: string; frontmatter: FrontmatterPatch }, contentDir: string) {
- const result = applyFolderFrontmatterPatch({
- anchorDir: contentDir,
- folderRel: folder.path,
- patch: folder.frontmatter as Record<string, unknown>,
+async function handleFolder(
+ folder: { path: string; frontmatter: FrontmatterPatch },
+ summary: string | undefined,
+ url: string | undefined,
+ deps: EditDeps,
+) {
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ const result = await httpPut(url, '/api/folder-config', {
+ path: folder.path,
+ frontmatter: folder.frontmatter,
+ ...(summary !== undefined ? { summary } : {}),
+ ...agentIdentityFields(deps.identityRef?.current),
});
- if (!result.ok) return textResult(`Error: ${result.error.message}`, true);
- const verb =
- result.action === 'deleted' ? 'Cleared' : result.action === 'noop' ? 'No change to' : 'Updated';
- return textPlusStructured(`${verb} folder properties for ${folder.path} (${result.path}).`, {
- folder: { ok: true, path: result.path, action: result.action },
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ const applied = Array.isArray(result.applied) ? result.applied : [];
+ const entry = (applied[0] ?? {}) as { path?: string; action?: string };
+ const action = entry.action ?? 'written';
+ const verb = action === 'deleted' ? 'Cleared' : action === 'noop' ? 'No change to' : 'Updated';
+ return textPlusStructured(`${verb} folder properties for ${folder.path}.`, {
+ folder: { ok: true, path: entry.path ?? `${folder.path}/.ok/frontmatter.yml`, action },
});
}
@@ -509,8 +535,14 @@ export function register(server: ServerInstance, deps: EditDeps): void {
}
return handleDocBody(args.document, args, cwd, contentDir, url, deps, autoOpen);
}
- if (args.folder !== undefined) return handleFolder(args.folder, contentDir);
- return handleTemplate(args.template as NonNullable<typeof args.template>, cwd);
+ if (args.folder !== undefined) return handleFolder(args.folder, args.summary, url, deps);
+ return handleTemplate(
+ args.template as NonNullable<typeof args.template>,
+ args.summary,
+ cwd,
+ url,
+ deps,
+ );
},
);
}
diff --git a/packages/server/src/mcp/tools/history.ts b/packages/server/src/mcp/tools/history.ts
index a102b25db..79bd3f821 100644
--- a/packages/server/src/mcp/tools/history.ts
+++ b/packages/server/src/mcp/tools/history.ts
@@ -38,12 +38,13 @@ const HistoryEntryOutputSchema = z.object({
});
export const DESCRIPTION = [
- '[Requires: Hocuspocus server] List version history for a document.',
+ '[Requires: Hocuspocus server] List version history for a document, or the activity timeline for a folder.',
'Returns timeline entries from the shadow repo, sorted by timestamp descending.',
'Each entry carries a `version` (40-char commit SHA) you pass straight to `restore_version({ document, version })` — same field name on both sides.',
'',
- '**Parameters:**',
+ '**Parameters (pass EXACTLY ONE of `document` / `folder`):**',
'- `document` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.',
+ '- `folder` — Folder path for the FOLDER timeline: attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter) — who created / edited / renamed / moved / deleted them, when. `""` = project root.',
'- `branch` (optional) — Branch name (default: current branch)',
'- `limit` (optional) — Maximum entries to return (default 50, max 200)',
'- `offset` (optional) — Number of entries to skip for pagination (default 0)',
@@ -64,7 +65,16 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
{
description: DESCRIPTION,
inputSchema: {
- document: z.string().describe('Document name to query history for'),
+ document: z
+ .string()
+ .optional()
+ .describe('Document name to query history for. Mutually exclusive with `folder`.'),
+ folder: z
+ .string()
+ .optional()
+ .describe(
+ 'Folder path to query the FOLDER timeline for — attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter): created / edited / renamed / moved / deleted, by whom, when. Mutually exclusive with `document`. Use `""` for the project root.',
+ ),
branch: z.string().optional().describe('Branch name (default: current branch)'),
limit: z
.number()
@@ -108,7 +118,8 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
}),
},
async (args: {
- document: string;
+ document?: string;
+ folder?: string;
branch?: string;
limit?: number;
offset?: number;
@@ -127,11 +138,21 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
const { cwd, url } = context;
if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
- const normalized = normalizeDocName(args.document);
- if (!normalized.ok) return textResult(normalized.error, true);
+ const isFolder = args.folder !== undefined;
+ if (isFolder === (args.document !== undefined)) {
+ return textResult('Error: pass EXACTLY ONE of `document` or `folder`.', true);
+ }
const params = new URLSearchParams();
- params.set('docName', normalized.docName);
+ let previewDocName: string | null = null;
+ if (isFolder) {
+ params.set('folder', args.folder ?? '');
+ } else {
+ const normalized = normalizeDocName(args.document as string);
+ if (!normalized.ok) return textResult(normalized.error, true);
+ params.set('docName', normalized.docName);
+ previewDocName = normalized.docName;
+ }
if (args.branch) params.set('branch', args.branch);
if (args.limit != null) params.set('limit', String(args.limit));
if (args.offset != null) params.set('offset', String(args.offset));
@@ -162,14 +183,13 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
const total = (data as { total?: unknown }).total;
const hasMore = (data as { hasMore?: unknown }).hasMore;
- const preview = await resolvePreviewUrlForTool(
- normalized.docName,
- {
- config: deps.config,
- resolveCwd: deps.resolveCwd,
- },
- cwd,
- );
+ const preview = previewDocName
+ ? await resolvePreviewUrlForTool(
+ previewDocName,
+ { config: deps.config, resolveCwd: deps.resolveCwd },
+ cwd,
+ )
+ : null;
const projected = {
entries,
...(typeof total === 'number' ? { total } : {}),
diff --git a/packages/server/src/mcp/tools/move.ts b/packages/server/src/mcp/tools/move.ts
index f73e95c8f..3280e5223 100644
--- a/packages/server/src/mcp/tools/move.ts
+++ b/packages/server/src/mcp/tools/move.ts
@@ -23,6 +23,7 @@ import {
textPlusStructured,
textResult,
} from './shared.ts';
+import { resolveTemplatePath } from './verb-schemas.ts';
export const DESCRIPTION = [
'[Requires: Hocuspocus server] Move or rename a document, folder, or asset through the managed flow at `POST /api/rename-path`. Works for all three — the tool probes the content directory to decide. Inbound wiki-links plus supported inline Markdown links are rewritten across affected docs; renamed assets are reported.',
@@ -30,6 +31,7 @@ export const DESCRIPTION = [
'**Parameters:**',
'- `from` — Current path. Doc: docName (trailing `.md`/`.mdx` stripped). Folder: relative path, no leading/trailing slash. Asset: the file path incl. extension.',
'- `to` — New path. Same shape as `from`.',
+ '- `template` — Move/rename a TEMPLATE instead of a doc/folder/asset: `{ from: "<folder>/<name>", to: "<folder>/<name>" }` (nested — a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc). Mutually exclusive with flat `from`/`to`. Inherited templates are not moved (move the local copy / the owning folder); templates carry no inbound links, so nothing is rewritten.',
'- `summary` — Optional one-line user-outcome (≤80 chars). If omitted, defaults to "Renamed X → Y". Avoid secrets or PII — persisted to git history.',
'',
'**Errors:** 400 — invalid path / excluded by `.gitignore`/`.okignore`; 404 — source does not exist; 409 — destination already exists (`colliding[]` returned).',
@@ -56,8 +58,9 @@ export interface MoveDeps {
}
interface MoveArgs {
- from: string;
- to: string;
+ from?: string;
+ to?: string;
+ template?: { from: string; to: string };
summary?: string;
cwd?: string;
}
@@ -132,10 +135,20 @@ export function register(server: ServerInstance, deps: MoveDeps): void {
{
description: DESCRIPTION,
inputSchema: {
- from: z.string().describe('Current path of a document, folder, or asset.'),
+ from: z
+ .string()
+ .optional()
+ .describe('Current path of a document, folder, or asset (auto-detected).'),
to: z
.string()
+ .optional()
.describe('New path. All inbound wiki-links + inline links are rewritten automatically.'),
+ template: z
+ .object({ from: z.string(), to: z.string() })
+ .optional()
+ .describe(
+ 'Move/rename a TEMPLATE instead: `{ from: "<folder>/<name>", to: "<folder>/<name>" }`. Nested because a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc. Mutually exclusive with flat `from`/`to`.',
+ ),
summary: summaryArgSchema.describe(
'Optional one-line user-outcome (≤80 chars). Defaults to "Renamed X → Y". Persisted to git history.',
),
@@ -144,9 +157,17 @@ export function register(server: ServerInstance, deps: MoveDeps): void {
outputSchema: outputSchemaWithText({
ok: z.boolean().describe('Whether the move succeeded.'),
kind: z
- .enum(['file', 'folder', 'asset'])
+ .enum(['file', 'folder', 'asset', 'template'])
+ .optional()
+ .describe(
+ 'What was moved (`file`/`folder`/`asset` auto-detected from `from`; `template` when the `template` target was used).',
+ ),
+ committed: z
+ .boolean()
.optional()
- .describe('What was moved, as auto-detected from `from`.'),
+ .describe(
+ 'Template move only: `true` = tracked `git mv` (history preserved), `false` = plain disk rename (untracked / local-only `.ok/`).',
+ ),
renamed: z
.array(z.object({ fromDocName: z.string(), toDocName: z.string() }))
.optional()
@@ -181,9 +202,62 @@ export function register(server: ServerInstance, deps: MoveDeps): void {
const { cwd, config, url } = context;
if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ if (args.template !== undefined) {
+ if (args.from !== undefined || args.to !== undefined) {
+ return textResult(
+ 'Error: pass EITHER flat `from`/`to` (document/folder/asset) OR `template: { from, to }` — not both.',
+ true,
+ );
+ }
+ const rf = resolveTemplatePath(args.template.from);
+ if (!rf.ok) return textResult(`Error: ${rf.error}`, true);
+ const rt = resolveTemplatePath(args.template.to);
+ if (!rt.ok) return textResult(`Error: ${rt.error}`, true);
+ const result = await httpPost(url, '/api/template', {
+ fromFolder: rf.folder,
+ fromName: rf.name,
+ toFolder: rt.folder,
+ toName: rt.name,
+ ...(args.summary !== undefined ? { summary: args.summary } : {}),
+ ...agentIdentityFields(deps.identityRef?.current),
+ });
+ if (!result.ok) {
+ const error = typeof result.error === 'string' ? result.error : 'Template move failed';
+ return textPlusStructured(
+ `Error: ${error}`,
+ { ok: false, kind: 'template', error },
+ true,
+ );
+ }
+ const committed = result.committed === true;
+ const fromLabel = typeof result.from === 'string' ? result.from : args.template.from;
+ const toLabel = typeof result.to === 'string' ? result.to : args.template.to;
+ return textPlusStructured(
+ `${committed ? 'Renamed' : 'Moved'} template ${fromLabel} → ${toLabel}.${committed ? '' : ' (Untracked `.ok/` — moved on disk without git history.)'}`,
+ { ok: true, kind: 'template', committed },
+ );
+ }
+
+ if (args.from === undefined || args.to === undefined) {
+ return textResult(
+ 'Error: provide both `from` and `to` (or use `template: { from, to }` to move a template).',
+ true,
+ );
+ }
+
const contentDir = join(cwd, config.content.dir);
const kind = resolveMoveKind(contentDir, args.from);
if (kind === null) {
+ const split = resolveTemplatePath(args.from);
+ if (
+ split.ok &&
+ existsSync(join(contentDir, split.folder, '.ok', 'templates', `${split.name}.md`))
+ ) {
+ return textResult(
+ `Error: \`${args.from}\` is a template, not a doc/folder/asset. Move it with \`move({ template: { from: "${args.from}", to: "<folder>/<newName>" } })\`.`,
+ true,
+ );
+ }
return textResult(
`Error: \`${args.from}\` does not exist as a doc, folder, or asset under the content directory.`,
true,
diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.ts
index a659e0439..9cf198fbc 100644
--- a/packages/server/src/mcp/tools/shared.ts
+++ b/packages/server/src/mcp/tools/shared.ts
@@ -338,7 +338,8 @@ export async function httpGet(
return normalizeResponse(res, body);
}
-export async function httpPost(
+async function httpSend(
+ method: 'POST' | 'PUT' | 'DELETE',
baseUrl: string,
path: string,
body?: Record<string, unknown>,
@@ -357,8 +358,8 @@ export async function httpPost(
let res: Response;
try {
res = await fetch(`${baseUrl}${path}`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ method,
+ headers: serializedBody !== undefined ? { 'Content-Type': 'application/json' } : undefined,
body: serializedBody,
signal: AbortSignal.timeout(30_000),
});
@@ -384,6 +385,29 @@ export async function httpPost(
return normalizeResponse(res, parsed);
}
+export function httpPost(
+ baseUrl: string,
+ path: string,
+ body?: Record<string, unknown>,
+): Promise<{ ok: boolean; [key: string]: unknown }> {
+ return httpSend('POST', baseUrl, path, body);
+}
+
+export function httpPut(
+ baseUrl: string,
+ path: string,
+ body?: Record<string, unknown>,
+): Promise<{ ok: boolean; [key: string]: unknown }> {
+ return httpSend('PUT', baseUrl, path, body);
+}
+
+export function httpDelete(
+ baseUrl: string,
+ path: string,
+): Promise<{ ok: boolean; [key: string]: unknown }> {
+ return httpSend('DELETE', baseUrl, path);
+}
+
export interface RenameCollisionPair {
existing: string;
incoming: string;
diff --git a/packages/server/src/mcp/tools/verb-tools.test.ts b/packages/server/src/mcp/tools/verb-tools.test.ts
index c5814009f..1c6988285 100644
--- a/packages/server/src/mcp/tools/verb-tools.test.ts
+++ b/packages/server/src/mcp/tools/verb-tools.test.ts
@@ -3,7 +3,6 @@ import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync } from 'no
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { parse as parseYaml } from 'yaml';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { register as registerDelete } from './delete.ts';
import { register as registerEdit } from './edit.ts';
@@ -96,87 +95,38 @@ describe('delete — exactly-one-target teaching error', () => {
});
});
-describe('edit({ folder }) — fs-direct round-trip to <folder>/.ok/frontmatter.yml', () => {
- test('sets, then merge-patches, then clears the folder frontmatter file', async () => {
- const cwd = newProject();
- const edit = capture(registerEdit, cwd);
- const fmPath = join(cwd, 'meetings', '.ok', 'frontmatter.yml');
-
- let r = await edit({
+describe('edit({ folder }) frontmatter — server-routed for attribution (PRD-6933 P2)', () => {
+ test('requires a running server (attribution lives server-side)', async () => {
+ const edit = capture(registerEdit, newProject());
+ const r = await edit({
folder: { path: 'meetings', frontmatter: { title: 'Meetings', tags: ['m'] } },
});
- expect(r.isError).toBeUndefined();
- expect(existsSync(fmPath)).toBe(true);
- expect(parseYaml(readFileSync(fmPath, 'utf-8'))).toEqual({ title: 'Meetings', tags: ['m'] });
-
- r = await edit({ folder: { path: 'meetings', frontmatter: { description: 'All-hands' } } });
- expect(r.isError).toBeUndefined();
- expect(parseYaml(readFileSync(fmPath, 'utf-8'))).toEqual({
- title: 'Meetings',
- tags: ['m'],
- description: 'All-hands',
- });
-
- r = await edit({ folder: { path: 'meetings', frontmatter: { tags: null } } });
- expect(r.isError).toBeUndefined();
- expect(parseYaml(readFileSync(fmPath, 'utf-8'))).toEqual({
- title: 'Meetings',
- description: 'All-hands',
- });
-
- r = await edit({ folder: { path: 'meetings', frontmatter: {} } });
- expect(r.isError).toBeUndefined();
- expect(existsSync(fmPath)).toBe(false);
- });
-
- test('the on-disk shape has no glob/match key (the fossil is gone)', async () => {
- const cwd = newProject();
- const edit = capture(registerEdit, cwd);
- await edit({ folder: { path: 'specs', frontmatter: { title: 'Specs' } } });
- const parsed = parseYaml(readFileSync(join(cwd, 'specs', '.ok', 'frontmatter.yml'), 'utf-8'));
- expect(parsed).not.toHaveProperty('match');
- expect(parsed).not.toHaveProperty('rules');
+ expect(r.isError).toBe(true);
+ expect(textOf(r)).toContain('Hocuspocus server is not running');
});
});
-describe('write/edit/delete({ template }) — fs-direct round-trip', () => {
- test('create → body edit → frontmatter patch → delete', async () => {
+describe('write/edit/delete({ template }) — server-routed for attribution (PRD-6933 P2)', () => {
+ test('mutations require a running server (attribution lives server-side)', async () => {
const cwd = newProject();
const write = capture(registerWrite, cwd);
const edit = capture(registerEdit, cwd);
const del = capture(registerDelete, cwd);
- const tplPath = join(cwd, 'fishing-log', '.ok', 'templates', 'trip-log.md');
-
- let r = await write({
- template: {
- path: 'fishing-log/trip-log',
- content: '# {{date}}\n\nCatch: \n',
- frontmatter: { title: 'Trip Log' },
- },
- });
- expect(r.isError).toBeUndefined();
- expect(existsSync(tplPath)).toBe(true);
- expect(readFileSync(tplPath, 'utf-8')).toContain('Catch:');
-
- r = await edit({
- template: { path: 'fishing-log/trip-log', find: 'Catch:', replace: 'Total catch:' },
- });
- expect(r.isError).toBeUndefined();
- expect(readFileSync(tplPath, 'utf-8')).toContain('Total catch:');
- expect(readFileSync(tplPath, 'utf-8')).toContain('Trip Log');
-
- r = await edit({
- template: {
- path: 'fishing-log/trip-log',
- frontmatter: { description: 'one per trip' },
- },
- });
- expect(r.isError).toBeUndefined();
- expect(readFileSync(tplPath, 'utf-8')).toContain('description: one per trip');
-
- r = await del({ template: { path: 'fishing-log/trip-log' } });
- expect(r.isError).toBeUndefined();
- expect(existsSync(tplPath)).toBe(false);
+ const results = [
+ await write({
+ template: {
+ path: 'fishing-log/trip-log',
+ content: '# x',
+ frontmatter: { title: 'Trip Log' },
+ },
+ }),
+ await edit({ template: { path: 'fishing-log/trip-log', find: 'x', replace: 'y' } }),
+ await del({ template: { path: 'fishing-log/trip-log' } }),
+ ];
+ for (const r of results) {
+ expect(r.isError).toBe(true);
+ expect(textOf(r)).toContain('Hocuspocus server is not running');
+ }
});
test('invalid template name is rejected by the name grammar', async () => {
diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.ts
index 4838165f3..9cdff07cf 100644
--- a/packages/server/src/mcp/tools/write.ts
+++ b/packages/server/src/mcp/tools/write.ts
@@ -8,12 +8,10 @@ import {
import { stringify as stringifyYaml } from 'yaml';
import { z } from 'zod';
import { resolveContentDir, resolveLockDir } from '../../config/paths.ts';
-import { applyFolderFrontmatterPatch } from '../../content/folder-frontmatter-write.ts';
import { dropEmpties } from '../../content/frontmatter-merge.ts';
import { parentFolderOf } from '../../content/nested-folder-rules.ts';
import { applySubstitution, todayIsoUtc } from '../../content/substitution.ts';
import { resolveTemplatesAvailable } from '../../content/templates-resolver.ts';
-import { applyTemplateWrite } from '../../content/templates-write.ts';
import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
import type { AgentIdentity } from '../agent-identity.ts';
import {
@@ -29,6 +27,7 @@ import {
documentResultBaseShape,
HOCUSPOCUS_NOT_RUNNING_ERROR,
httpPost,
+ httpPut,
looseObjectArray,
nestDocResult,
normalizeDocName,
@@ -59,7 +58,7 @@ const BASE_DESCRIPTION = [
'',
'- `document` — Create or overwrite a doc via the CRDT layer [Requires: Hocuspocus server]. `{ path, content }`, or `{ path, template }` to instantiate from a folder template (mutually exclusive with `content`). Optional `frontmatter` (its own YAML) and `position` (`replace` default for a new doc; required for an existing one) — note supplying `frontmatter` alongside literal `content` forces `position: replace` (the only position that persists a YAML block), overriding an explicit `append`/`prepend`. Example: `{ document: { path: "meetings/standup", content: "# Standup\\n..." } }`.',
'- `folder` — Create a NEW folder (optionally with its own properties) [Requires: Hocuspocus server]. `{ path, frontmatter? }`. To change an EXISTING folder use `edit`. Example: `{ folder: { path: "ideas" } }`.',
- '- `template` — Create a reusable starting shape for new docs in a folder (fs-direct). `{ path: "<folder>/<name>", content, frontmatter: { title, description?, tags? } }`.',
+ '- `template` — Create a reusable starting shape for new docs in a folder. `{ path: "<folder>/<name>", content, frontmatter: { title, description?, tags? } }`.',
'- `asset` — Upload a binary (image/file) via the media route [Requires: Hocuspocus server]. `{ path: "<folder>/<file.ext>", content(base64) | source(local path) }`.',
'- `documents` — Batch: `[{ path, content?|template?, frontmatter?, position?, summary? }, ...]` written in order; the response reports each.',
'- `summary` — Optional one-line user-outcome (≤80 chars) for the timeline, for a single `document`/`folder`/`template`/`asset` write. For a `documents` batch, give each entry its own `summary` instead (a top-level `summary` is ignored on the batch path). Avoid secrets or PII — persisted to git history.',
@@ -281,7 +280,6 @@ async function writeOneDoc(
async function handleFolder(
folder: { path: string; frontmatter?: FrontmatterPatch },
summary: string | undefined,
- contentDir: string,
url: string | undefined,
deps: WriteDeps,
) {
@@ -303,35 +301,38 @@ async function handleFolder(
const lines = [`Created folder ${folder.path}.`];
if (folder.frontmatter !== undefined && Object.keys(folder.frontmatter).length > 0) {
- const fm = applyFolderFrontmatterPatch({
- anchorDir: contentDir,
- folderRel: folder.path,
- patch: folder.frontmatter as Record<string, unknown>,
+ const fm = await httpPut(url, '/api/folder-config', {
+ path: folder.path,
+ frontmatter: folder.frontmatter,
+ ...(summary !== undefined ? { summary } : {}),
+ ...agentIdentityFields(identity),
});
if (!fm.ok) {
return textPlusStructured(
- `Created folder ${folder.path}, but writing its properties failed: ${fm.error.message}. Use edit({ folder: { path: "${folder.path}", frontmatter } }) to retry the properties.`,
- { folder: { ok: true, path: folder.path, frontmatterError: fm.error.message } },
+ `Created folder ${folder.path}, but writing its properties failed: ${fm.error}. Use edit({ folder: { path: "${folder.path}", frontmatter } }) to retry the properties.`,
+ { folder: { ok: true, path: folder.path, frontmatterError: String(fm.error) } },
);
}
- if (fm.action === 'written') lines.push(`Set folder properties (${fm.path}).`);
+ lines.push(`Set folder properties (${folder.path}/.ok/frontmatter.yml).`);
}
return textPlusStructured(lines.join('\n'), { folder: { ok: true, path: folder.path } });
}
-function handleTemplate(
+async function handleTemplate(
template: {
path: string;
content: string;
frontmatter: { title: string } & Record<string, unknown>;
},
- cwd: string,
+ summary: string | undefined,
+ url: string | undefined,
+ deps: WriteDeps,
) {
const resolved = resolveTemplatePath(template.path);
if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
const { folder, name } = resolved;
- const result = applyTemplateWrite({
- projectDir: cwd,
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ const result = await httpPut(url, '/api/template', {
folder,
name,
body: template.content,
@@ -344,13 +345,17 @@ function handleTemplate(
? { tags: template.frontmatter.tags as string[] }
: {}),
},
+ ...(summary !== undefined ? { summary } : {}),
+ ...agentIdentityFields(deps.identityRef?.current),
});
if (!result.ok) {
- return textResult(`Error: ${result.error.message}`, true);
+ return textResult(`Error: ${result.error}`, true);
}
+ const created = result.created === true;
+ const path = typeof result.path === 'string' ? result.path : undefined;
return textPlusStructured(
- `${result.created ? 'Created' : 'Updated'} template "${name}" in ${folder || '(root)'} (${result.path}).`,
- { template: { ok: true, path: result.path, created: result.created } },
+ `${created ? 'Created' : 'Updated'} template "${name}" in ${folder || '(root)'}${path ? ` (${path})` : ''}.`,
+ { template: { ok: true, path, created } },
);
}
@@ -764,9 +769,9 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
autoOpen,
);
}
- if (args.folder !== undefined)
- return handleFolder(args.folder, args.summary, contentDir, url, deps);
- if (args.template !== undefined) return handleTemplate(args.template, cwd);
+ if (args.folder !== undefined) return handleFolder(args.folder, args.summary, url, deps);
+ if (args.template !== undefined)
+ return handleTemplate(args.template, args.summary, url, deps);
return handleAsset(args.asset as NonNullable<typeof args.asset>, cwd, url, deps);
},
);
diff --git a/packages/server/src/timeline-query.ts b/packages/server/src/timeline-query.ts
index b8966aa39..ed5a48618 100644
--- a/packages/server/src/timeline-query.ts
+++ b/packages/server/src/timeline-query.ts
@@ -43,6 +43,12 @@ const GIT_LOG_FORMAT = '%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e';
const EMPTY: HistoryResult = { entries: [], total: 0, hasMore: false };
+const FOLDER_ARTIFACT_SUBJECT_RE =
+ /^(template-(create|edit|rename|move|delete)|folder-frontmatter-(edit|delete)|folder-create): /;
+function isFolderArtifactSubject(message: string): boolean {
+ return FOLDER_ARTIFACT_SUBJECT_RE.test(message);
+}
+
function classifyType(subject: string): EntryType {
if (subject.startsWith('checkpoint:')) return 'checkpoint';
if (subject.startsWith('import:') || subject.startsWith('upstream:')) return 'upstream';
@@ -509,3 +515,69 @@ export async function getDocumentHistory(
return EMPTY;
}
}
+
+export async function getFolderTimeline(
+ shadow: ShadowHandle,
+ folderRel: string,
+ contentRoot = '.',
+ options?: { branch?: string; limit?: number; offset?: number },
+): Promise<HistoryResult> {
+ if (!existsSync(shadow.workTree) || !existsSync(shadow.gitDir)) return EMPTY;
+ if (folderRel.includes('..') || folderRel.includes('\0')) return EMPTY;
+
+ const branch = options?.branch ?? 'main';
+ const limit = Math.max(1, options?.limit ?? 50);
+ const offset = Math.max(0, options?.offset ?? 0);
+
+ const normalizedRoot = contentRoot === '.' ? '' : contentRoot.replace(/^\.\//, '');
+ const base = folderRel.replace(/^\.?\/+/, '').replace(/\/+$/, '');
+ const okPath = [normalizedRoot, base, '.ok'].filter(Boolean).join('/');
+
+ const sg = shadowGit(shadow);
+ try {
+ const startRefs: string[] = [];
+ for (const refNs of [`refs/wip/${branch}/`, `refs/checkpoints/${branch}/`]) {
+ try {
+ const refs = (await sg.raw('for-each-ref', '--format=%(refname)', refNs))
+ .trim()
+ .split('\n')
+ .filter(Boolean);
+ startRefs.push(...refs);
+ } catch {}
+ }
+ if (startRefs.length === 0) return EMPTY;
+
+ const raw = await sg.raw(
+ 'log',
+ '--full-history',
+ '--author-date-order',
+ `--format=${GIT_LOG_FORMAT}`,
+ ...startRefs,
+ '--',
+ okPath,
+ );
+ const okDocPrefix = base ? `${base}/.ok/` : '.ok/';
+ const seen = new Set<string>();
+ const entries: TimelineEntry[] = [];
+ for (const parsed of parseGitLogOutput(raw)) {
+ if (seen.has(parsed.sha)) continue;
+ if (!isFolderArtifactSubject(parsed.message)) continue;
+ const touchesFolderArtifact = parsed.contributors.some((c) =>
+ c.docs.some((doc) => doc.startsWith(okDocPrefix)),
+ );
+ if (!touchesFolderArtifact) continue;
+ seen.add(parsed.sha);
+ const { rawBody: _rawBody, ...entry } = parsed;
+ entries.push(entry);
+ }
+ const total = entries.length;
+ return {
+ entries: entries.slice(offset, offset + limit),
+ total,
+ hasMore: offset + limit < total,
+ };
+ } catch (e) {
+ console.warn('[timeline] getFolderTimeline failed, returning empty result:', e);
+ return EMPTY;
+ }
+}