Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Support nested frontmatter objects + inline editor (PRD-6947) (#1766)

tim-inkeep9d2aa7e30a1f
diff --git a/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx b/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx
index e8fbd1234..aed73576b 100644
--- a/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx
+++ b/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx
@@ -12,9 +12,12 @@ const TYPE_PICKER_LABEL: Record<FrontmatterType, string> = {
boolean: 'Checkbox',
date: 'Date',
list: 'List',
+ object: 'Object',
};
-const ALL_TYPE_PICKS = Object.entries(TYPE_PICKER_LABEL) as Array<[FrontmatterType, string]>;
+const ALL_TYPE_PICKS = (
+ Object.entries(TYPE_PICKER_LABEL) as Array<[FrontmatterType, string]>
+).filter(([type]) => type !== 'object');
function PropertyPanelHarness({
initialType = 'text' as FrontmatterType,
diff --git a/packages/app/src/components/ArrayOfObjectsWidget.tsx b/packages/app/src/components/ArrayOfObjectsWidget.tsx
new file mode 100644
index 000000000..dc373f2f5
--- /dev/null
+++ b/packages/app/src/components/ArrayOfObjectsWidget.tsx
@@ -0,0 +1,420 @@
+import {
+ closestCenter,
+ DndContext,
+ type DragEndEvent,
+ KeyboardSensor,
+ PointerSensor,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core';
+import {
+ SortableContext,
+ sortableKeyboardCoordinates,
+ useSortable,
+ verticalListSortingStrategy,
+} from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import type { FrontmatterValue } from '@inkeep/open-knowledge-core';
+import { Plural, Trans, useLingui } from '@lingui/react/macro';
+import { ChevronRight, GripVertical, Plus, Trash2 } from 'lucide-react';
+import { type CSSProperties, useState } from 'react';
+import { useFrontmatterBinding } from '@/components/FrontmatterBindingContext';
+import { describeError } from '@/components/frontmatter-error-utils';
+import { ObjectWidget } from '@/components/ObjectWidget';
+import { Button } from '@/components/ui/button';
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
+
+type ObjectItem = { [key: string]: FrontmatterValue };
+
+interface ArrayOfObjectsWidgetProps {
+ keyName: string;
+ value: ReadonlyArray<ObjectItem>;
+ path: ReadonlyArray<string | number>;
+ depth?: number;
+}
+
+export function ArrayOfObjectsWidget({
+ keyName,
+ value,
+ path,
+ depth = 0,
+}: ArrayOfObjectsWidgetProps) {
+ const { t } = useLingui();
+ const binding = useFrontmatterBinding();
+ const [open, setOpen] = useState(depth === 0);
+ const [itemErrors, setItemErrors] = useState<Record<number, string>>({});
+ const [addError, setAddError] = useState<string | null>(null);
+
+ const triggerLabel = open ? t`Collapse ${keyName}` : t`Expand ${keyName}`;
+ const readOnly = binding === null;
+
+ function pathOfItem(idx: number): ReadonlyArray<string | number> {
+ return [...path, idx];
+ }
+
+ function clearItemError(idx: number) {
+ setItemErrors((prev) => {
+ if (!Object.hasOwn(prev, idx)) return prev;
+ const next = { ...prev };
+ delete next[idx];
+ return next;
+ });
+ }
+
+ function applyItemError(idx: number, message: string) {
+ setItemErrors((prev) => ({ ...prev, [idx]: message }));
+ }
+
+ function removeItem(idx: number) {
+ if (!binding) return;
+ clearItemError(idx);
+ const result =
+ value.length <= 1 ? binding.deletePath(path) : binding.deletePath(pathOfItem(idx));
+ if (result.ok) {
+ setItemErrors({});
+ return;
+ }
+ const message = describeError(result.error, String(idx), t`Failed to delete item`);
+ applyItemError(idx, message);
+ }
+
+ function addItem() {
+ if (!binding) return;
+ setAddError(null);
+ const result = binding.patchPath(pathOfItem(value.length), {});
+ if (result.ok) return;
+ const message = describeError(result.error, String(value.length), t`Failed to add item`);
+ setAddError(message);
+ }
+
+ function sortableItemId(idx: number): string {
+ return `${path.join('.')}::item::${idx}`;
+ }
+
+ function handleDragEnd(event: DragEndEvent): void {
+ if (!binding) return;
+ const activeId = String(event.active.id);
+ const overId = event.over ? String(event.over.id) : null;
+ if (!overId || activeId === overId) return;
+
+ const ids = value.map((_, i) => sortableItemId(i));
+ const oldIndex = ids.indexOf(activeId);
+ const newIndex = ids.indexOf(overId);
+ if (oldIndex < 0 || newIndex < 0) return;
+
+ const want = value.map((_, i) => i);
+ const [moved] = want.splice(oldIndex, 1);
+ if (moved === undefined) return;
+ want.splice(newIndex, 0, moved);
+
+ const result = binding.reorderSeqPath(path, want);
+ if (result.ok) {
+ setItemErrors({});
+ return;
+ }
+ const message = describeError(result.error, String(oldIndex), t`Failed to reorder`);
+ applyItemError(oldIndex, message);
+ }
+
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ );
+
+ return (
+ <div
+ data-testid="array-of-objects-widget"
+ data-key={keyName}
+ data-depth={depth}
+ data-read-only={readOnly || undefined}
+ className="w-full min-w-0"
+ >
+ <Collapsible open={open} onOpenChange={setOpen}>
+ <CollapsibleTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ data-testid="array-of-objects-widget-trigger"
+ data-key={keyName}
+ data-state-open={open ? 'true' : 'false'}
+ aria-label={triggerLabel}
+ className="h-7 w-full justify-start gap-1 px-2 font-normal hover:bg-muted"
+ >
+ <ChevronRight
+ data-expanded={open}
+ aria-hidden="true"
+ className="size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ease-out data-[expanded=true]:rotate-90"
+ />
+ <span className="truncate text-xs text-muted-foreground">
+ {value.length === 0 ? (
+ <Trans>empty</Trans>
+ ) : (
+ <Plural value={value.length} one="# item" other="# items" />
+ )}
+ </span>
+ </Button>
+ </CollapsibleTrigger>
+ <CollapsibleContent className="overflow-hidden data-[state=open]:animate-[collapsible-down_150ms_ease-out] data-[state=closed]:animate-[collapsible-up_150ms_ease-in]">
+ <div
+ data-testid="array-of-objects-widget-children"
+ data-key={keyName}
+ className="mt-0.5 ml-2 border-l border-border/60 pl-2"
+ >
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handleDragEnd}
+ >
+ <SortableContext
+ items={value.map((_, i) => sortableItemId(i))}
+ strategy={verticalListSortingStrategy}
+ >
+ {value.map((item, idx) => (
+ <ArrayItemRow
+ /* biome-ignore lint/suspicious/noArrayIndexKey: items are addressed by index across the binding path API; remount-on-reorder is correct. */
+ key={idx}
+ sortableId={readOnly ? undefined : sortableItemId(idx)}
+ arrayKey={keyName}
+ index={idx}
+ value={item}
+ path={pathOfItem(idx)}
+ error={itemErrors[idx] ?? null}
+ onRemove={readOnly ? undefined : () => removeItem(idx)}
+ />
+ ))}
+ </SortableContext>
+ </DndContext>
+ {readOnly ? null : (
+ <div className="mt-1 flex items-center gap-1">
+ <span aria-hidden className="h-7 w-4 shrink-0" />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ data-testid="array-of-objects-widget-add-trigger"
+ data-key={keyName}
+ onClick={addItem}
+ aria-label={t`Add item to ${keyName}`}
+ className="flex items-center gap-1.5 rounded px-2 py-1 text-xs font-medium hover:bg-muted/50 hover:text-foreground"
+ >
+ <Plus className="size-3.5" />
+ <span>
+ <Trans>Add item</Trans>
+ </span>
+ </Button>
+ {addError ? (
+ <span
+ role="alert"
+ data-testid="array-of-objects-add-error"
+ data-key={keyName}
+ className="text-[10px] text-destructive"
+ >
+ {addError}
+ </span>
+ ) : null}
+ </div>
+ )}
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
+ );
+}
+
+interface ArrayItemRowProps {
+ sortableId: string | undefined;
+ arrayKey: string;
+ index: number;
+ value: ObjectItem;
+ path: ReadonlyArray<string | number>;
+ error: string | null;
+ onRemove: (() => void) | undefined;
+}
+
+function ArrayItemRow({
+ sortableId,
+ arrayKey,
+ index,
+ value,
+ path,
+ error,
+ onRemove,
+}: ArrayItemRowProps) {
+ if (sortableId) {
+ return (
+ <SortableItemShell
+ sortableId={sortableId}
+ arrayKey={arrayKey}
+ index={index}
+ value={value}
+ path={path}
+ error={error}
+ onRemove={onRemove}
+ />
+ );
+ }
+ return (
+ <StaticItemShell
+ arrayKey={arrayKey}
+ index={index}
+ value={value}
+ path={path}
+ error={error}
+ onRemove={onRemove}
+ />
+ );
+}
+
+function SortableItemShell({
+ sortableId,
+ arrayKey,
+ index,
+ value,
+ path,
+ error,
+ onRemove,
+}: ArrayItemRowProps & { sortableId: string }) {
+ const { t } = useLingui();
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
+ id: sortableId,
+ });
+ const style: CSSProperties = {
+ transform: CSS.Transform.toString(transform),
+ transition,
+ opacity: isDragging ? 0.5 : undefined,
+ zIndex: isDragging ? 1 : undefined,
+ };
+ const dragHandle = (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ data-testid="array-item-drag-handle"
+ data-key={arrayKey}
+ data-index={index}
+ aria-label={t`Drag item ${index + 1} to reorder`}
+ {...attributes}
+ {...listeners}
+ className="h-7 w-4 shrink-0 cursor-grab touch-none px-0 text-muted-foreground/0 hover:text-foreground focus-visible:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing group-hover:text-muted-foreground/60"
+ >
+ <GripVertical className="size-3.5" />
+ </Button>
+ );
+ return (
+ <div
+ ref={setNodeRef}
+ style={style}
+ className="group mt-1 rounded border border-border/40 p-1"
+ data-testid="array-item"
+ data-key={arrayKey}
+ data-index={index}
+ data-dragging={isDragging || undefined}
+ data-error={error ?? undefined}
+ >
+ <ArrayItemBody
+ dragHandle={dragHandle}
+ arrayKey={arrayKey}
+ index={index}
+ value={value}
+ path={path}
+ error={error}
+ onRemove={onRemove}
+ />
+ </div>
+ );
+}
+
+function StaticItemShell({
+ arrayKey,
+ index,
+ value,
+ path,
+ error,
+ onRemove,
+}: Omit<ArrayItemRowProps, 'sortableId'>) {
+ return (
+ <div
+ className="group mt-1 rounded border border-border/40 p-1"
+ data-testid="array-item"
+ data-key={arrayKey}
+ data-index={index}
+ data-error={error ?? undefined}
+ >
+ <ArrayItemBody
+ dragHandle={null}
+ arrayKey={arrayKey}
+ index={index}
+ value={value}
+ path={path}
+ error={error}
+ onRemove={onRemove}
+ />
+ </div>
+ );
+}
+
+function ArrayItemBody({
+ dragHandle,
+ arrayKey,
+ index,
+ value,
+ path,
+ error,
+ onRemove,
+}: {
+ dragHandle: React.ReactNode;
+ arrayKey: string;
+ index: number;
+ value: ObjectItem;
+ path: ReadonlyArray<string | number>;
+ error: string | null;
+ onRemove: (() => void) | undefined;
+}) {
+ const { t } = useLingui();
+ const indexLabel = t`Item ${index + 1}`;
+ return (
+ <>
+ <div className="flex items-center gap-1">
+ {dragHandle}
+ <span
+ data-testid="array-item-label"
+ data-key={arrayKey}
+ data-index={index}
+ className="flex-1 truncate text-xs font-medium text-muted-foreground"
+ >
+ {indexLabel}
+ </span>
+ {onRemove ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ data-testid="array-item-remove"
+ data-key={arrayKey}
+ data-index={index}
+ aria-label={t`Remove item ${index + 1}`}
+ onClick={onRemove}
+ className="shrink-0 rounded text-muted-foreground/0 hover:bg-muted hover:text-foreground focus-visible:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover:text-muted-foreground"
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ ) : null}
+ </div>
+ <div className="mt-0.5">
+ <ObjectWidget keyName={`${arrayKey}[${index}]`} value={value} path={path} depth={0} />
+ </div>
+ {error ? (
+ <div
+ role="alert"
+ data-testid="array-item-error"
+ data-key={arrayKey}
+ data-index={index}
+ className="pl-2 text-[10px] text-destructive"
+ >
+ {error}
+ </div>
+ ) : null}
+ </>
+ );
+}
diff --git a/packages/app/src/components/FrontmatterBindingContext.tsx b/packages/app/src/components/FrontmatterBindingContext.tsx
new file mode 100644
index 000000000..683a5f11c
--- /dev/null
+++ b/packages/app/src/components/FrontmatterBindingContext.tsx
@@ -0,0 +1,17 @@
+import type { FrontmatterBinding } from '@inkeep/open-knowledge-core';
+import { createContext, type ReactNode, use } from 'react';
+
+const FrontmatterBindingContext = createContext<FrontmatterBinding | null>(null);
+
+interface ProviderProps {
+ binding: FrontmatterBinding | null;
+ children: ReactNode;
+}
+
+export function FrontmatterBindingProvider({ binding, children }: ProviderProps) {
+ return <FrontmatterBindingContext value={binding}>{children}</FrontmatterBindingContext>;
+}
+
+export function useFrontmatterBinding(): FrontmatterBinding | null {
+ return use(FrontmatterBindingContext);
+}
diff --git a/packages/app/src/components/FrontmatterRow.tsx b/packages/app/src/components/FrontmatterRow.tsx
index 02d65c7ca..0a7e57cdb 100644
--- a/packages/app/src/components/FrontmatterRow.tsx
+++ b/packages/app/src/components/FrontmatterRow.tsx
@@ -9,10 +9,16 @@ import { Trans, useLingui } from '@lingui/react/macro';
import { AlertTriangle, GripVertical, Trash2, X } from 'lucide-react';
import type { CSSProperties, ReactNode } from 'react';
import { useRef } from 'react';
+import { ArrayOfObjectsWidget } from '@/components/ArrayOfObjectsWidget';
+import { ObjectWidget } from '@/components/ObjectWidget';
import { PageCoverWidget, PageIconWidget } from '@/components/PageHeaderWidgets';
import {
BooleanWidget,
+ ComplexValueWidget,
DateWidget,
+ isArrayOfObjectsValue,
+ isComplexValue,
+ isPlainObjectValue,
ListWidget,
NumberWidget,
TextWidget,
@@ -30,6 +36,8 @@ export interface AddDraft {
error: string | null;
}
+const ADD_ROW_PATH: ReadonlyArray<string | number> = ['__add__'] as const;
+
export interface RenameDraft {
key: string;
draft: string;
@@ -55,6 +63,7 @@ interface FrontmatterRowProps {
isDuplicate?: boolean;
badge?: ReactNode;
isPlaceholder?: boolean;
+ path?: ReadonlyArray<string | number>;
onCommit: (next: FrontmatterValue) => void;
onChangeType: (next: FrontmatterType) => void;
onRemove?: () => void;
@@ -71,11 +80,14 @@ export function FrontmatterRow({
isDuplicate = false,
badge,
isPlaceholder = false,
+ path,
onCommit,
onChangeType,
onRemove,
}: FrontmatterRowProps) {
const { t } = useLingui();
+ const isComplex = isComplexValue(value);
+ const rowPath: ReadonlyArray<string | number> = path ?? [keyName];
return (
<SortableShell
sortableId={sortableId}
@@ -84,6 +96,7 @@ export function FrontmatterRow({
error={error}
isDuplicate={isDuplicate}
isPlaceholder={isPlaceholder}
+ isComplex={isComplex}
>
{(dragHandle) => (
<>
@@ -105,7 +118,11 @@ export function FrontmatterRow({
<PlaceholderIdentity keyName={keyName} type={declared} />
) : (
<>
- <TypeIconButton keyName={keyName} type={declared} onChangeType={onChangeType} />
+ {isComplex ? (
+ <ComplexValueTypeIcon keyName={keyName} type={declared} />
+ ) : (
+ <TypeIconButton keyName={keyName} type={declared} onChangeType={onChangeType} />
+ )}
<div className="w-32 shrink-0 @max-[26rem]/prow:w-auto">
{rename?.state ? (
<RenameInput
@@ -143,6 +160,7 @@ export function FrontmatterRow({
keyName={keyName}
value={value}
widgetType={declared}
+ path={rowPath}
onCommit={onCommit}
/>
</div>
@@ -185,6 +203,7 @@ function SortableShell({
error,
isDuplicate,
isPlaceholder,
+ isComplex,
children,
}: {
sortableId: string | undefined;
@@ -193,6 +212,7 @@ function SortableShell({
error?: string | null;
isDuplicate: boolean;
isPlaceholder: boolean;
+ isComplex: boolean;
children: (dragHandle: ReactNode) => ReactNode;
}) {
if (sortableId) {
@@ -203,6 +223,7 @@ function SortableShell({
declared={declared}
error={error}
isDuplicate={isDuplicate}
+ isComplex={isComplex}
>
{children}
</SortableRowBody>
@@ -217,6 +238,7 @@ function SortableShell({
data-widget-type={declared}
data-error={error ?? undefined}
data-duplicate={isDuplicate || undefined}
+ data-complex-value={isComplex || undefined}
>
{children(dragHandleSlot)}
</div>
@@ -229,6 +251,7 @@ function SortableRowBody({
declared,
error,
isDuplicate,
+ isComplex,
children,
}: {
sortableId: string;
@@ -236,6 +259,7 @@ function SortableRowBody({
declared: FrontmatterType;
error?: string | null;
isDuplicate: boolean;
+ isComplex: boolean;
children: (dragHandle: ReactNode) => ReactNode;
}) {
const { t } = useLingui();
@@ -273,6 +297,7 @@ function SortableRowBody({
data-widget-type={declared}
data-error={error ?? undefined}
data-duplicate={isDuplicate || undefined}
+ data-complex-value={isComplex || undefined}
data-dragging={isDragging || undefined}
>
{children(dragHandle)}
@@ -280,6 +305,23 @@ function SortableRowBody({
);
}
+function ComplexValueTypeIcon({ keyName, type }: { keyName: string; type: FrontmatterType }) {
+ const { t } = useLingui();
+ const Icon = TYPE_ICON[type];
+ return (
+ <span
+ role="img"
+ data-testid="type-icon-static"
+ data-key={keyName}
+ data-type={type}
+ aria-label={t`${keyName} type: complex value (nested; read-only)`}
+ className="flex size-7 shrink-0 items-center justify-center rounded text-muted-foreground"
+ >
+ <Icon className="size-3.5" aria-hidden="true" />
+ </span>
+ );
+}
+
interface RenameInputProps {
keyName: string;
draft: string;
@@ -449,6 +491,7 @@ export function AddPropertyRow({
keyName="__add__"
value={draft.value}
widgetType={draft.type}
+ path={ADD_ROW_PATH}
onCommit={onChangeValue}
/>
</div>
@@ -493,10 +536,11 @@ interface WidgetProps {
keyName: string;
value: FrontmatterValue;
widgetType: FrontmatterType;
+ path: ReadonlyArray<string | number>;
onCommit: (next: FrontmatterValue) => void;
}
-function Widget({ keyName, value, widgetType, onCommit }: WidgetProps) {
+function Widget({ keyName, value, widgetType, path, onCommit }: WidgetProps) {
if (keyName === 'icon') {
const str = typeof value === 'string' ? value : '';
return <PageIconWidget keyName={keyName} value={str} onCommit={onCommit} />;
@@ -505,8 +549,21 @@ function Widget({ keyName, value, widgetType, onCommit }: WidgetProps) {
const str = typeof value === 'string' ? value : '';
return <PageCoverWidget keyName={keyName} value={str} onCommit={onCommit} />;
}
+ if (isPlainObjectValue(value)) {
+ return <ObjectWidget keyName={keyName} value={value} path={path} depth={path.length - 1} />;
+ }
+ if (isArrayOfObjectsValue(value)) {
+ return (
+ <ArrayOfObjectsWidget keyName={keyName} value={value} path={path} depth={path.length - 1} />
+ );
+ }
+ if (isComplexValue(value)) {
+ return <ComplexValueWidget keyName={keyName} value={value} />;
+ }
if (widgetType === 'list') {
- const arr = Array.isArray(value) ? value : [];
+ const arr = Array.isArray(value)
+ ? value.filter((entry): entry is string => typeof entry === 'string')
+ : [];
return <ListWidget keyName={keyName} value={arr} onCommit={onCommit} />;
}
if (widgetType === 'boolean') {
diff --git a/packages/app/src/components/ObjectWidget.tsx b/packages/app/src/components/ObjectWidget.tsx
new file mode 100644
index 000000000..ba91de5a8
--- /dev/null
+++ b/packages/app/src/components/ObjectWidget.tsx
@@ -0,0 +1,347 @@
+import {
+ closestCenter,
+ DndContext,
+ type DragEndEvent,
+ KeyboardSensor,
+ PointerSensor,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core';
+import {
+ SortableContext,
+ sortableKeyboardCoordinates,
+ verticalListSortingStrategy,
+} from '@dnd-kit/sortable';
+import {
+ type FrontmatterType,
+ type FrontmatterValue,
+ frontmatterValuesEqual,
+ inferType,
+ RESERVED_FRONTMATTER_KEY,
+} from '@inkeep/open-knowledge-core';
+import { Plural, Trans, useLingui } from '@lingui/react/macro';
+import { ChevronRight, Plus } from 'lucide-react';
+import { useState } from 'react';
+import { useFrontmatterBinding } from '@/components/FrontmatterBindingContext';
+import {
+ type AddDraft,
+ AddPropertyRow,
+ FrontmatterRow,
+ type RenameDraft,
+} from '@/components/FrontmatterRow';
+import { describeError } from '@/components/frontmatter-error-utils';
+import { coerceValue, DEFAULT_VALUE_FOR_TYPE } from '@/components/PropertyWidgets';
+import { Button } from '@/components/ui/button';
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
+
+interface ObjectWidgetProps {
+ keyName: string;
+ value: { [key: string]: FrontmatterValue };
+ path: ReadonlyArray<string | number>;
+ depth?: number;
+}
+
+export function ObjectWidget({ keyName, value, path, depth = 0 }: ObjectWidgetProps) {
+ const { t } = useLingui();
+ const binding = useFrontmatterBinding();
+ const [open, setOpen] = useState(depth === 0);
+ const [renaming, setRenaming] = useState<RenameDraft | null>(null);
+ const [adding, setAdding] = useState<AddDraft | null>(null);
+ const [errors, setErrors] = useState<Record<string, string>>({});
+ const [resetCounters, setResetCounters] = useState<Record<string, number>>({});
+
+ const entries = Object.entries(value);
+ const triggerLabel = open ? t`Collapse ${keyName}` : t`Expand ${keyName}`;
+ const readOnly = binding === null;
+
+ function clearError(key: string) {
+ setErrors((prev) => {
+ if (!Object.hasOwn(prev, key)) return prev;
+ const next = { ...prev };
+ delete next[key];
+ return next;
+ });
+ }
+
+ function applyError(key: string, message: string) {
+ setErrors((prev) => ({ ...prev, [key]: message }));
+ setResetCounters((prev) => ({ ...prev, [key]: (prev[key] ?? 0) + 1 }));
+ }
+
+ function pathOf(childKey: string): ReadonlyArray<string | number> {
+ return [...path, childKey];
+ }
+
+ function commitChild(childKey: string, nextValue: FrontmatterValue) {
+ if (!binding) return;
+ clearError(childKey);
+ const result = binding.patchPath(pathOf(childKey), nextValue);
+ if (result.ok) return;
+ const message = describeError(result.error, childKey, t`Failed to update property`);
+ applyError(childKey, message);
+ }
+
+ function removeChild(childKey: string) {
+ if (!binding) return;
+ clearError(childKey);
+ const result = binding.deletePath(pathOf(childKey));
+ if (result.ok) return;
+ const message = describeError(result.error, childKey, t`Failed to delete property`);
+ applyError(childKey, message);
+ }
+
+ function changeChildType(childKey: string, nextType: FrontmatterType) {
+ if (!binding) return;
+ const current = value[childKey];
+ if (current === undefined) return;
+ const coerced = coerceValue(current, nextType);
+ if (frontmatterValuesEqual(current, coerced)) return;
+ commitChild(childKey, coerced);
+ }
+
+ function beginChildRename(childKey: string) {
+ setRenaming({ key: childKey, draft: childKey, error: null });
+ }
+
+ function changeRenameDraft(draft: string) {
+ setRenaming((prev) => (prev ? { ...prev, draft, error: null } : prev));
+ }
+
+ function cancelRename() {
+ setRenaming(null);
+ }
+
+ function commitRename() {
+ if (!renaming || !binding) return;
+ const trimmed = renaming.draft.trim();
+ if (!trimmed) {
+ setRenaming(null);
+ return;
+ }
+ if (trimmed === renaming.key) {
+ setRenaming(null);
+ return;
+ }
+ if (Object.hasOwn(value, trimmed)) {
+ setRenaming({ ...renaming, error: t`Property "${trimmed}" already exists` });
+ return;
+ }
+ const result = binding.renamePath(pathOf(renaming.key), trimmed);
+ if (result.ok) {
+ clearError(renaming.key);
+ setRenaming(null);
+ return;
+ }
+ const message = describeError(result.error, trimmed, t`Failed to rename property`);
+ setRenaming({ ...renaming, error: message });
+ }
+
+ function beginAdd() {
+ setAdding({ name: '', type: 'text', value: '', error: null });
+ }
+
+ function changeAddName(name: string) {
+ setAdding((prev) => (prev ? { ...prev, name, error: null } : prev));
+ }
+
+ function changeAddType(nextType: FrontmatterType) {
+ setAdding((prev) => {
+ if (!prev) return prev;
+ const defaultValue =
+ nextType === 'date'
+ ? new Date().toISOString().slice(0, 10)
+ : DEFAULT_VALUE_FOR_TYPE[nextType];
+ return { ...prev, type: nextType, value: defaultValue, error: null };
+ });
+ }
+
+ function changeAddValue(next: FrontmatterValue) {
+ setAdding((prev) => (prev ? { ...prev, value: next } : prev));
+ }
+
+ function commitAdd() {
+ if (!adding || !binding) return;
+ const trimmed = adding.name.trim();
+ if (!trimmed) {
+ setAdding({ ...adding, error: t`Name is required` });
+ return;
+ }
+ if (trimmed === RESERVED_FRONTMATTER_KEY && path.length === 0) {
+ setAdding({ ...adding, error: t`"frontmatter" is a reserved property name` });
+ return;
+ }
+ if (Object.hasOwn(value, trimmed)) {
+ setAdding({ ...adding, error: t`Property "${trimmed}" already exists` });
+ return;
+ }
+ const result = binding.patchPath(pathOf(trimmed), adding.value);
+ if (result.ok) {
+ setAdding(null);
+ return;
+ }
+ const message = describeError(result.error, trimmed, t`Failed to add property`);
+ setAdding({ ...adding, error: message });
+ }
+
+ function cancelAdd() {
+ setAdding(null);
+ }
+
+ function nestedRowId(childKey: string, idx: number): string {
+ return `${path.join('.')}::${childKey}::${idx}`;
+ }
+
+ function handleDragEnd(event: DragEndEvent): void {
+ if (!binding) return;
+ const activeId = String(event.active.id);
+ const overId = event.over ? String(event.over.id) : null;
+ if (!overId || activeId === overId) return;
+
+ const childKeys = entries.map(([k]) => k);
+ const ids = childKeys.map((k, i) => nestedRowId(k, i));
+ const oldIndex = ids.indexOf(activeId);
+ const newIndex = ids.indexOf(overId);
+ if (oldIndex < 0 || newIndex < 0) return;
+
+ const next = childKeys.slice();
+ const [moved] = next.splice(oldIndex, 1);
+ if (!moved) return;
+ next.splice(newIndex, 0, moved);
+
+ const result = binding.reorderPath(path, next);
+ if (result.ok) {
+ clearError(moved);
+ return;
+ }
+ const message = describeError(result.error, moved, t`Failed to reorder`);
+ applyError(moved, message);
+ }
+
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ );
+
+ const dupCount = new Map<string, number>();
+ for (const [k] of entries) dupCount.set(k, (dupCount.get(k) ?? 0) + 1);
+
+ return (
+ <div
+ data-testid="object-widget"
+ data-key={keyName}
+ data-depth={depth}
+ data-read-only={readOnly || undefined}
+ className="w-full min-w-0"
+ >
+ <Collapsible open={open} onOpenChange={setOpen}>
+ <CollapsibleTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ data-testid="object-widget-trigger"
+ data-key={keyName}
+ data-state-open={open ? 'true' : 'false'}
+ aria-label={triggerLabel}
+ className="h-7 w-full justify-start gap-1 px-2 font-normal hover:bg-muted"
+ >
+ <ChevronRight
+ data-expanded={open}
+ aria-hidden="true"
+ className="size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ease-out data-[expanded=true]:rotate-90"
+ />
+ <span className="truncate text-xs text-muted-foreground">
+ {entries.length === 0 ? (
+ <Trans>empty</Trans>
+ ) : (
+ <Plural value={entries.length} one="# key" other="# keys" />
+ )}
+ </span>
+ </Button>
+ </CollapsibleTrigger>
+ <CollapsibleContent className="overflow-hidden data-[state=open]:animate-[collapsible-down_150ms_ease-out] data-[state=closed]:animate-[collapsible-up_150ms_ease-in]">
+ <div
+ data-testid="object-widget-children"
+ data-key={keyName}
+ className="mt-0.5 ml-2 border-l border-border/60 pl-2"
+ >
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handleDragEnd}
+ >
+ <SortableContext
+ items={entries.map(([k], i) => nestedRowId(k, i))}
+ strategy={verticalListSortingStrategy}
+ >
+ {entries.map(([childKey, childValue], idx) => {
+ const declared = inferType(childValue);
+ const renameState = renaming?.key === childKey ? renaming : null;
+ const isDuplicate = (dupCount.get(childKey) ?? 0) > 1;
+ const childPath = pathOf(childKey);
+ return (
+ <FrontmatterRow
+ // biome-ignore lint/suspicious/noArrayIndexKey: position-aware key for dup-name rows.
+ key={`${childKey}-${idx}`}
+ sortableId={readOnly ? undefined : nestedRowId(childKey, idx)}
+ keyName={childKey}
+ value={childValue}
+ declared={declared}
+ error={errors[childKey] ?? null}
+ resetCounter={resetCounters[childKey] ?? 0}
+ isDuplicate={isDuplicate}
+ path={childPath}
+ rename={
+ readOnly
+ ? undefined
+ : {
+ state: renameState,
+ onBegin: () => beginChildRename(childKey),
+ onChangeDraft: changeRenameDraft,
+ onCommit: commitRename,
+ onCancel: cancelRename,
+ }
+ }
+ onCommit={(v) => commitChild(childKey, v)}
+ onChangeType={(nextType) => changeChildType(childKey, nextType)}
+ onRemove={readOnly ? undefined : () => removeChild(childKey)}
+ />
+ );
+ })}
+ </SortableContext>
+ </DndContext>
+ {readOnly ? null : adding ? (
+ <AddPropertyRow
+ draft={adding}
+ onChangeName={changeAddName}
+ onChangeType={changeAddType}
+ onChangeValue={changeAddValue}
+ onCommit={commitAdd}
+ onCancel={cancelAdd}
+ />
+ ) : (
+ <div className="mt-1 flex items-center gap-1">
+ <span aria-hidden className="h-7 w-4 shrink-0" />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ data-testid="object-widget-add-trigger"
+ data-key={keyName}
+ onClick={beginAdd}
+ aria-label={t`Add property to ${keyName}`}
+ className="flex items-center gap-1.5 rounded px-2 py-1 text-xs font-medium hover:bg-muted/50 hover:text-foreground"
+ >
+ <Plus className="size-3.5" />
+ <span>
+ <Trans>Add</Trans>
+ </span>
+ </Button>
+ </div>
+ )}
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/PropertyPanel.nested-crud.dom.test.tsx b/packages/app/src/components/PropertyPanel.nested-crud.dom.test.tsx
new file mode 100644
index 000000000..7e2893567
--- /dev/null
+++ b/packages/app/src/components/PropertyPanel.nested-crud.dom.test.tsx
@@ -0,0 +1,409 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { HocuspocusProvider } from '@hocuspocus/provider';
+import { readFmMap } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { PropertyProvider } from './PropertyContext';
+import { PropertyPanel } from './PropertyPanel';
+
+const DUMMY_WS = 'ws://localhost:1/collab';
+
+const providers: HocuspocusProvider[] = [];
+
+function makeProvider(docName: string): HocuspocusProvider {
+ const p = new HocuspocusProvider({ url: DUMMY_WS, name: docName });
+ providers.push(p);
+ return p;
+}
+
+function seedYTextFm(provider: HocuspocusProvider, fenced: string): void {
+ const ytext = provider.document.getText('source');
+ provider.document.transact(() => {
+ ytext.delete(0, ytext.length);
+ ytext.insert(0, fenced);
+ });
+}
+
+function readPanelMap(provider: HocuspocusProvider): Record<string, unknown> {
+ return readFmMap(provider.document.getText('source').toString()) as Record<string, unknown>;
+}
+
+function renderPanel(provider: HocuspocusProvider) {
+ return render(
+ <TooltipProvider>
+ <PropertyProvider>
+ <PropertyPanel provider={provider} />
+ </PropertyProvider>
+ </TooltipProvider>,
+ );
+}
+
+afterEach(() => {
+ cleanup();
+ for (const p of providers.splice(0)) {
+ try {
+ p.destroy();
+ } catch {}
+ }
+});
+
+describe('PropertyPanel — nested CRUD (US-007)', () => {
+ async function findInputByKey(testid: string, key: string): Promise<HTMLElement> {
+ return waitFor(() => {
+ const el = document.querySelector(
+ `[data-testid="${testid}"][data-key="${key}"]`,
+ ) as HTMLElement | null;
+ if (!el) throw new Error(`element not found: [data-testid="${testid}"][data-key="${key}"]`);
+ return el;
+ });
+ }
+
+ test('editing a nested scalar leaf commits via binding.patchPath and persists', async () => {
+ const provider = makeProvider('nested-edit-leaf-doc');
+ seedYTextFm(
+ provider,
+ '---\nname: skill\nmetadata:\n version: "1.0.0"\n author: Inkeep\n---\n',
+ );
+ renderPanel(provider);
+
+ const versionInput = (await findInputByKey(
+ 'text-widget',
+ 'version',
+ )) as HTMLTextAreaElement | null;
+ expect(versionInput).not.toBeNull();
+ if (!versionInput) return;
+
+ const user = userEvent.setup();
+ await user.click(versionInput);
+ await user.clear(versionInput);
+ await user.type(versionInput, '2.0.0');
+ await user.tab(); // blur — commits the typed draft via the binding.
+
+ const map = readPanelMap(provider);
+ expect(map).toEqual({
+ name: 'skill',
+ metadata: { version: '2.0.0', author: 'Inkeep' },
+ });
+ });
+
+ test('deleting a nested key removes ONLY that leaf and preserves siblings', async () => {
+ const provider = makeProvider('nested-delete-leaf-doc');
+ seedYTextFm(
+ provider,
+ '---\nmetadata:\n version: "1.0.0"\n author: Inkeep\n license: MIT\n---\n',
+ );
+ renderPanel(provider);
+
+ const versionRemove = document.querySelector(
+ 'button[data-testid="property-remove-button"][data-key="version"]',
+ ) as HTMLButtonElement | null;
+ expect(versionRemove).not.toBeNull();
+ if (!versionRemove) return;
+
+ const user = userEvent.setup();
+ await user.click(versionRemove);
+
+ const map = readPanelMap(provider);
+ expect(map).toEqual({
+ metadata: { author: 'Inkeep', license: 'MIT' },
+ });
+ });
+
+ test('renaming a nested key uses binding.renamePath (preserves source position)', async () => {
+ const provider = makeProvider('nested-rename-leaf-doc');
+ seedYTextFm(
+ provider,
+ '---\nmetadata:\n version: "1.0.0"\n author: Inkeep\n license: MIT\n---\n',
+ );
+ renderPanel(provider);
+
+ const authorNameButton = document.querySelector(
+ 'button[data-testid="property-name-button"][data-key="author"]',
+ ) as HTMLButtonElement | null;
+ expect(authorNameButton).not.toBeNull();
+ if (!authorNameButton) return;
+
+ const user = userEvent.setup();
+ await user.click(authorNameButton);
+
+ const renameInput = await screen.findByTestId('property-name-rename-input');
+ expect(renameInput.getAttribute('data-key')).toBe('author');
+
+ await user.clear(renameInput);
+ await user.type(renameInput, 'maintainer');
+ await user.keyboard('{Enter}');
+
+ const map = readPanelMap(provider);
+ expect(map).toEqual({
+ metadata: { version: '1.0.0', maintainer: 'Inkeep', license: 'MIT' },
+ });
+ const fenced = provider.document.getText('source').toString();
+ const versionIdx = fenced.indexOf('version:');
+ const maintainerIdx = fenced.indexOf('maintainer:');
+ const licenseIdx = fenced.indexOf('license:');
+ expect(versionIdx).toBeLessThan(maintainerIdx);
+ expect(maintainerIdx).toBeLessThan(licenseIdx);
+ });
+
+ test('adding a nested key uses binding.patchPath (preserves siblings)', async () => {
+ const provider = makeProvider('nested-add-leaf-doc');
+ seedYTextFm(provider, '---\nmetadata:\n version: "1.0.0"\n author: Inkeep\n---\n');
+ renderPanel(provider);
+
+ const addTrigger = document.querySelector(
+ 'button[data-testid="object-widget-add-trigger"][data-key="metadata"]',
+ ) as HTMLButtonElement | null;
+ expect(addTrigger).not.toBeNull();
+ if (!addTrigger) return;
+
+ const user = userEvent.setup();
+ await user.click(addTrigger);
+
+ const nameInput = await screen.findByTestId('add-property-name-input');
+ await user.type(nameInput, 'license');
+ const addValueInput = document.querySelector(
+ 'textarea[data-testid="text-widget"][data-key="__add__"]',
+ ) as HTMLTextAreaElement | null;
+ expect(addValueInput).not.toBeNull();
+ if (!addValueInput) return;
+ await user.click(addValueInput);
+ await user.type(addValueInput, 'MIT');
+ const addCommit = await screen.findByTestId('add-property-commit');
+ await user.click(addCommit);
+
+ const map = readPanelMap(provider);
+ expect(map).toEqual({
+ metadata: { version: '1.0.0', author: 'Inkeep', license: 'MIT' },
+ });
+ });
+
+ test('adding a duplicate nested key surfaces an inline error and does not commit', async () => {
+ const provider = makeProvider('nested-add-dup-doc');
+ seedYTextFm(provider, '---\nmetadata:\n version: "1.0.0"\n---\n');
+ renderPanel(provider);
+
+ const addTrigger = document.querySelector(
+ 'button[data-testid="object-widget-add-trigger"][data-key="metadata"]',
+ ) as HTMLButtonElement | null;
+ expect(addTrigger).not.toBeNull();
+ if (!addTrigger) return;
+
+ const user = userEvent.setup();
+ await user.click(addTrigger);
+
+ const nameInput = await screen.findByTestId('add-property-name-input');
+ await user.type(nameInput, 'version');
+ const valueInput = document.querySelector(
+ 'textarea[data-testid="text-widget"][data-key="__add__"]',
+ ) as HTMLTextAreaElement | null;
+ expect(valueInput).not.toBeNull();
+ if (!valueInput) return;
+ await user.click(valueInput);
+ await user.type(valueInput, 'whatever');
+ const addCommit = await screen.findByTestId('add-property-commit');
+ await user.click(addCommit);
+
+ const errorEl = await screen.findByTestId('add-property-error');
+ expect(errorEl.textContent ?? '').toContain('version');
+ expect(readPanelMap(provider)).toEqual({ metadata: { version: '1.0.0' } });
+ });
+
+ test('editing a deeply nested leaf (depth 2) commits via the path API', async () => {
+ const provider = makeProvider('nested-edit-depth2-doc');
+ seedYTextFm(provider, '---\nouter:\n inner:\n leaf: "old"\n other: keep\n---\n');
+ renderPanel(provider);
+
+ const innerTrigger = (await findInputByKey(
+ 'object-widget-trigger',
+ 'inner',
+ )) as HTMLButtonElement | null;
+ expect(innerTrigger).not.toBeNull();
+ if (!innerTrigger) return;
+ const user = userEvent.setup();
+ await user.click(innerTrigger);
+
+ const targetLeaf = (await findInputByKey('text-widget', 'leaf')) as HTMLTextAreaElement | null;
+ expect(targetLeaf).not.toBeNull();
+ if (!targetLeaf) return;
+
+ await user.click(targetLeaf);
+ await user.clear(targetLeaf);
+ await user.type(targetLeaf, 'new');
+ await user.tab();
+
+ const map = readPanelMap(provider);
+ expect(map).toEqual({
+ outer: { inner: { leaf: 'new', other: 'keep' } },
+ });
+ });
+
+ test('nested rename to an existing sibling shows duplicate-name error and does not mutate', async () => {
+ const provider = makeProvider('nested-rename-dup-doc');
+ seedYTextFm(provider, '---\nmetadata:\n version: "1.0.0"\n author: Inkeep\n---\n');
+ renderPanel(provider);
+
+ const versionNameButton = document.querySelector(
+ 'button[data-testid="property-name-button"][data-key="version"]',
+ ) as HTMLButtonElement | null;
+ expect(versionNameButton).not.toBeNull();
+ if (!versionNameButton) return;
+
+ const user = userEvent.setup();
+ await user.click(versionNameButton);
+
+ const renameInput = await screen.findByTestId('property-name-rename-input');
+ await user.clear(renameInput);
+ await user.type(renameInput, 'author');
+ await user.keyboard('{Enter}');
+
+ const errorEl = await screen.findByTestId('property-name-rename-error');
+ expect(errorEl.textContent ?? '').toContain('author');
+ const map = readPanelMap(provider);
+ expect(map).toEqual({
+ metadata: { version: '1.0.0', author: 'Inkeep' },
+ });
+ });
+});
+
+describe('PropertyPanel — array-of-objects CRUD (US-008)', () => {
+ async function findAddItemTrigger(arrayKey: string): Promise<HTMLButtonElement | null> {
+ for (let i = 0; i < 20; i++) {
+ const el = document.querySelector(
+ `button[data-testid="array-of-objects-widget-add-trigger"][data-key="${arrayKey}"]`,
+ ) as HTMLButtonElement | null;
+ if (el) return el;
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ return null;
+ }
+
+ test('adding an item appends an empty object at end via binding.patchPath', async () => {
+ const provider = makeProvider('aoo-add-doc');
+ seedYTextFm(provider, '---\nauthors:\n - name: A\n - name: B\n---\n');
+ renderPanel(provider);
+
+ const addTrigger = await findAddItemTrigger('authors');
+ expect(addTrigger).not.toBeNull();
+ if (!addTrigger) return;
+ const user = userEvent.setup();
+ await user.click(addTrigger);
+
+ const map = readPanelMap(provider);
+ expect(map).toEqual({ authors: [{ name: 'A' }, { name: 'B' }, {}] });
+ });
+
+ test('removing an item splices the sequence and renumbers remaining indices', async () => {
+ const provider = makeProvider('aoo-remove-doc');
+ seedYTextFm(provider, '---\nauthors:\n - name: A\n - name: B\n - name: C\n---\n');
+ renderPanel(provider);
+
+ let removeBtn: HTMLButtonElement | null = null;
+ for (let i = 0; i < 20; i++) {
+ removeBtn = document.querySelector(
+ 'button[data-testid="array-item-remove"][data-key="authors"][data-index="0"]',
+ ) as HTMLButtonElement | null;
+ if (removeBtn) break;
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ expect(removeBtn).not.toBeNull();
+ if (!removeBtn) return;
+
+ const user = userEvent.setup();
+ await user.click(removeBtn);
+
+ const map = readPanelMap(provider);
+ expect(map).toEqual({ authors: [{ name: 'B' }, { name: 'C' }] });
+ });
+
+ test('removing the last item drops the property (no bare-[] scalar-list dead-end)', async () => {
+ const provider = makeProvider('aoo-last-remove-doc');
+ seedYTextFm(provider, '---\nauthors:\n - name: Solo\n---\n');
+ renderPanel(provider);
+
+ let removeBtn: HTMLButtonElement | null = null;
+ for (let i = 0; i < 20; i++) {
+ removeBtn = document.querySelector(
+ 'button[data-testid="array-item-remove"][data-key="authors"][data-index="0"]',
+ ) as HTMLButtonElement | null;
+ if (removeBtn) break;
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ expect(removeBtn).not.toBeNull();
+ if (!removeBtn) return;
+
+ const user = userEvent.setup();
+ await user.click(removeBtn);
+
+ const map = readPanelMap(provider);
+ expect(map.authors).toBeUndefined();
+ });
+
+ test('a successful item delete leaves no array-item-error markers', async () => {
+ const provider = makeProvider('aoo-error-clear-doc');
+ seedYTextFm(provider, '---\nauthors:\n - name: A\n - name: B\n---\n');
+ renderPanel(provider);
+
+ let removeBtn: HTMLButtonElement | null = null;
+ for (let i = 0; i < 20; i++) {
+ removeBtn = document.querySelector(
+ 'button[data-testid="array-item-remove"][data-key="authors"][data-index="0"]',
+ ) as HTMLButtonElement | null;
+ if (removeBtn) break;
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ if (!removeBtn) return;
+ const user = userEvent.setup();
+ await user.click(removeBtn);
+
+ expect(document.querySelectorAll('[data-testid="array-item-error"]').length).toBe(0);
+ });
+
+ test('editing a field within an item commits at item-index path', async () => {
+ const provider = makeProvider('aoo-edit-doc');
+ seedYTextFm(provider, '---\nauthors:\n - name: A\n - name: B\n---\n');
+ renderPanel(provider);
+
+ let nameInput: HTMLTextAreaElement | null = null;
+ for (let i = 0; i < 20; i++) {
+ const inputs = document.querySelectorAll(
+ 'textarea[data-testid="text-widget"][data-key="name"]',
+ );
+ if (inputs.length >= 2) {
+ nameInput = inputs[1] as HTMLTextAreaElement;
+ break;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ expect(nameInput).not.toBeNull();
+ if (!nameInput) return;
+
+ const user = userEvent.setup();
+ await user.click(nameInput);
+ await user.clear(nameInput);
+ await user.type(nameInput, 'Bee');
+ await user.tab();
+
+ const map = readPanelMap(provider);
+ expect(map).toEqual({ authors: [{ name: 'A' }, { name: 'Bee' }] });
+ });
+
+ test('scalar arrays still render via the chip ListWidget (no regression)', async () => {
+ const provider = makeProvider('aoo-scalar-regression-doc');
+ seedYTextFm(provider, '---\ntags:\n - alpha\n - beta\n---\n');
+ renderPanel(provider);
+
+ let listWidget: HTMLElement | null = null;
+ for (let i = 0; i < 20; i++) {
+ listWidget = document.querySelector(
+ '[data-testid="list-widget"][data-key="tags"]',
+ ) as HTMLElement | null;
+ if (listWidget) break;
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ expect(listWidget).not.toBeNull();
+ expect(
+ document.querySelector('[data-testid="array-of-objects-widget"][data-key="tags"]'),
+ ).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/PropertyPanel.test.tsx b/packages/app/src/components/PropertyPanel.test.tsx
index c98eb8297..7f3a5b435 100644
--- a/packages/app/src/components/PropertyPanel.test.tsx
+++ b/packages/app/src/components/PropertyPanel.test.tsx
@@ -280,6 +280,172 @@ describe('PropertyPanel malformed YAML banner (FR9)', () => {
});
});
+describe('PropertyPanel nested-value rendering', () => {
+ test('skill-shaped nested frontmatter renders every top-level row + no banner', () => {
+ const provider = makeProvider('nested-skill-doc');
+ seedYTextFm(
+ provider,
+ '---\nname: my-skill\ndescription: A skill\nmetadata:\n version: "1.0"\n author: Inkeep\n repository: github.com/inkeep/x\n---\n',
+ );
+ const html = renderPanel(provider);
+ expect(html).not.toContain('data-testid="property-panel-yaml-error"');
+ expect(html).toContain('data-key="name"');
+ expect(html).toContain('data-key="description"');
+ expect(html).toContain('data-key="metadata"');
+ });
+
+ test('nested object value renders ObjectWidget (not the text widget)', () => {
+ const provider = makeProvider('nested-object-doc');
+ seedYTextFm(
+ provider,
+ '---\nname: my-skill\nmetadata:\n version: "1.0"\n author: Inkeep\n---\n',
+ );
+ const html = renderPanel(provider);
+ expect(html).toContain('data-testid="object-widget"');
+ expect(html).toMatch(/data-key="metadata"[^>]*data-complex-value="true"/);
+ expect(html).toMatch(/data-testid="object-widget"[^>]*data-key="metadata"/);
+ expect(html).not.toMatch(
+ /data-testid="text-widget"[^>]*data-key="metadata"|data-key="metadata"[^>]*data-testid="text-widget"/,
+ );
+ expect(html).not.toMatch(/data-testid="complex-value-widget"[^>]*data-key="metadata"/);
+ expect(html).toContain('version');
+ expect(html).toContain('author');
+ });
+
+ test('sibling scalar keys around a nested value still render their interactive widgets', () => {
+ const provider = makeProvider('nested-skill-siblings-doc');
+ seedYTextFm(
+ provider,
+ '---\nname: my-skill\ndescription: A skill\nmetadata:\n version: "1.0"\n---\n',
+ );
+ const html = renderPanel(provider);
+ expect(html).toContain('data-testid="text-widget"');
+ expect(html).toContain('data-key="name"');
+ expect(html).toContain('data-key="description"');
+ expect(html).toContain('aria-label="name type: Text. Click to change."');
+ expect(html).toContain('aria-label="description type: Text. Click to change."');
+ });
+
+ test('nested row carries a static (non-dropdown) type icon — no coercion footgun', () => {
+ const provider = makeProvider('nested-static-icon-doc');
+ seedYTextFm(provider, '---\nmetadata:\n version: "1.0"\n---\n');
+ const html = renderPanel(provider);
+ expect(html).toMatch(
+ /data-testid="type-icon-static"[^>]*data-key="metadata"[^>]*data-type="object"/,
+ );
+ expect(html).not.toMatch(/data-testid="type-icon-button"[^>]*data-key="metadata"/);
+ });
+
+ test('array-of-objects value renders as indexed ArrayOfObjectsWidget (not the read-only complex preview)', () => {
+ const provider = makeProvider('array-of-objects-doc');
+ seedYTextFm(
+ provider,
+ '---\nplugins:\n - name: a\n version: 1\n - name: b\n version: 2\n---\n',
+ );
+ const html = renderPanel(provider);
+ expect(html).not.toContain('data-testid="property-panel-yaml-error"');
+ expect(html).toMatch(
+ /data-testid="array-of-objects-widget"[^>]*data-key="plugins"|data-key="plugins"[^>]*data-testid="array-of-objects-widget"/,
+ );
+ expect(html).toContain('2 items');
+ expect(html).not.toMatch(/data-testid="complex-value-widget"[^>]*data-key="plugins"/);
+ });
+
+ test('nested row keeps the delete affordance — user can still remove the key', () => {
+ const provider = makeProvider('nested-delete-doc');
+ seedYTextFm(provider, '---\nname: x\nmetadata:\n version: "1.0"\n---\n');
+ const html = renderPanel(provider);
+ expect(html).toContain('aria-label="Remove metadata"');
+ });
+});
+
+describe('PropertyPanel ObjectWidget recursive rendering', () => {
+ test('object value renders an expandable Collapsible with an accessible trigger', () => {
+ const provider = makeProvider('object-widget-trigger-doc');
+ seedYTextFm(provider, '---\nmetadata:\n version: "1.0"\n author: Inkeep\n---\n');
+ const html = renderPanel(provider);
+ expect(html).toMatch(/data-testid="object-widget-trigger"[^>]*data-key="metadata"/);
+ expect(html).toMatch(
+ /data-testid="object-widget-trigger"[^>]*data-key="metadata"[^>]*aria-expanded="true"|data-key="metadata"[^>]*data-testid="object-widget-trigger"[^>]*aria-expanded="true"/,
+ );
+ expect(html).toMatch(/aria-label="Collapse metadata"|aria-label="Expand metadata"/);
+ });
+
+ test('expanded object widget renders child rows for every nested key', () => {
+ const provider = makeProvider('object-widget-children-doc');
+ seedYTextFm(
+ provider,
+ '---\nmetadata:\n version: "1.0"\n author: Inkeep\n repository: github.com/x\n---\n',
+ );
+ const html = renderPanel(provider);
+ expect(html).toMatch(/data-testid="property-row"[^>]*data-key="version"/);
+ expect(html).toMatch(/data-testid="property-row"[^>]*data-key="author"/);
+ expect(html).toMatch(/data-testid="property-row"[^>]*data-key="repository"/);
+ expect(html).toMatch(/data-testid="object-widget-children"[^>]*data-key="metadata"/);
+ });
+
+ test('scalar leaves at depth 1 render via the existing scalar widgets per inferType', () => {
+ const provider = makeProvider('object-widget-scalar-leaves-doc');
+ seedYTextFm(provider, '---\nmetadata:\n version: "1.0"\n count: 42\n active: true\n---\n');
+ const html = renderPanel(provider);
+ expect(html).toMatch(/data-testid="text-widget"[^>]*data-key="version"/);
+ expect(html).toMatch(/data-testid="number-widget"[^>]*data-key="count"/);
+ expect(html).toMatch(/data-testid="boolean-widget"[^>]*data-key="active"/);
+ });
+
+ test('nested object at depth 2 renders its own ObjectWidget recursively', () => {
+ const provider = makeProvider('object-widget-recursive-doc');
+ seedYTextFm(
+ provider,
+ '---\nmetadata:\n version: "1.0"\n details:\n license: MIT\n notes: hello\n---\n',
+ );
+ const html = renderPanel(provider);
+ expect(html).toMatch(/data-testid="object-widget"[^>]*data-key="metadata"[^>]*data-depth="0"/);
+ expect(html).toMatch(/data-testid="object-widget"[^>]*data-key="details"[^>]*data-depth="1"/);
+ expect(html).toMatch(/data-testid="property-row"[^>]*data-key="details"/);
+ });
+
+ test('depth>=1 ObjectWidgets default to collapsed (avoid drowning the panel)', () => {
+ const provider = makeProvider('object-widget-depth-default-doc');
+ seedYTextFm(
+ provider,
+ '---\nmetadata:\n details:\n license: MIT\n repo: github.com/x\n---\n',
+ );
+ const html = renderPanel(provider);
+ expect(html).toMatch(
+ /data-testid="object-widget-trigger"[^>]*data-key="metadata"[^>]*aria-expanded="true"|data-key="metadata"[^>]*data-testid="object-widget-trigger"[^>]*aria-expanded="true"/,
+ );
+ expect(html).toMatch(
+ /data-testid="object-widget-trigger"[^>]*data-key="details"[^>]*aria-expanded="false"|data-key="details"[^>]*data-testid="object-widget-trigger"[^>]*aria-expanded="false"/,
+ );
+ });
+
+ test('nested scalar rows carry interactive type-icon-button (live picker) per leaf', () => {
+ const provider = makeProvider('nested-icon-types-doc');
+ seedYTextFm(provider, '---\nmetadata:\n version: "1.0"\n count: 42\n active: true\n---\n');
+ const html = renderPanel(provider);
+ expect(html).toMatch(
+ /data-testid="type-icon-button"[^>]*data-key="version"[^>]*data-type="text"/,
+ );
+ expect(html).toMatch(
+ /data-testid="type-icon-button"[^>]*data-key="count"[^>]*data-type="number"/,
+ );
+ expect(html).toMatch(
+ /data-testid="type-icon-button"[^>]*data-key="active"[^>]*data-type="boolean"/,
+ );
+ });
+
+ test('empty object {} renders an ObjectWidget with no child rows', () => {
+ const provider = makeProvider('empty-object-doc');
+ seedYTextFm(provider, '---\nmetadata: {}\n---\n');
+ const html = renderPanel(provider);
+ expect(html).toMatch(/data-testid="object-widget"[^>]*data-key="metadata"/);
+ expect(html).toMatch(
+ /data-testid="object-widget-children"[^>]*data-key="metadata"[^>]*><\/div>/,
+ );
+ });
+});
+
describe('PropertyPanel error rendering', () => {
test('rows render with no error subline by default', () => {
const provider = makeProvider('no-error-doc');
diff --git a/packages/app/src/components/PropertyPanel.tsx b/packages/app/src/components/PropertyPanel.tsx
index a433dab7c..13d1a403f 100644
--- a/packages/app/src/components/PropertyPanel.tsx
+++ b/packages/app/src/components/PropertyPanel.tsx
@@ -21,6 +21,7 @@ import {
type FrontmatterType,
type FrontmatterValue,
fieldErrorsFromError,
+ frontmatterValuesEqual,
inferType,
readFmKeys,
readFmRegionWithError,
@@ -28,6 +29,7 @@ import {
import { Trans, useLingui } from '@lingui/react/macro';
import { AlertTriangle, ChevronRight, Plus } from 'lucide-react';
import { useEffect, useState } from 'react';
+import { FrontmatterBindingProvider } from '@/components/FrontmatterBindingContext';
import {
type AddDraft,
AddPropertyRow,
@@ -196,7 +198,7 @@ export function PropertyPanel({ provider }: PropertyPanelProps) {
if (current === undefined) return;
setOverrides((prev) => ({ ...prev, [key]: nextType }));
const coerced = coerceValue(current, nextType);
- if (!Object.hasOwn(map, key) || !sameValue(current, coerced)) {
+ if (!Object.hasOwn(map, key) || !frontmatterValuesEqual(current, coerced)) {
commitProperty(key, coerced);
}
}
@@ -323,85 +325,86 @@ export function PropertyPanel({ provider }: PropertyPanelProps) {
if (renderKeys.length === 0 && !adding && !parseError) return null;
return (
- <div
- className="property-panel editor-content-aligned pt-4 pb-4 text-sm"
- data-testid="property-panel"
- >
- <Collapsible open={!collapsed} onOpenChange={(open) => setCollapsed(!open)}>
- <CollapsibleTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- className="mb-1.5 flex h-auto w-fit bg-transparent! items-center gap-1 px-1 py-0.5 text-base font-medium text-foreground hover:bg-transparent hover:text-foreground"
- >
- <ChevronRight
- data-expanded={!collapsed}
- className="size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ease-out data-[expanded=true]:rotate-90"
- />
- <span>
- <Trans>Properties</Trans>
- </span>
- </Button>
- </CollapsibleTrigger>
- <CollapsibleContent className="overflow-hidden data-[state=open]:animate-[collapsible-down_150ms_ease-out] data-[state=closed]:animate-[collapsible-up_150ms_ease-in]">
- {parseError ? (
- <div
- role="alert"
- data-testid="property-panel-yaml-error"
- className="mb-1 flex items-start gap-1.5 rounded border border-destructive/30 bg-destructive/5 px-2 py-1.5 text-[11px] text-destructive"
+ <FrontmatterBindingProvider binding={binding}>
+ <div
+ className="property-panel editor-content-aligned pt-4 pb-4 text-sm"
+ data-testid="property-panel"
+ >
+ <Collapsible open={!collapsed} onOpenChange={(open) => setCollapsed(!open)}>
+ <CollapsibleTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ className="mb-1.5 flex h-auto w-fit bg-transparent! items-center gap-1 px-1 py-0.5 text-base font-medium text-foreground hover:bg-transparent hover:text-foreground"
>
- <AlertTriangle className="size-3.5 shrink-0 mt-0.5" />
- <div>
- <Trans>
- The properties block at the top of this doc has a formatting error. Switch to
- source mode to fix it.
- </Trans>
- <span className="block text-[10px] opacity-80">{parseError}</span>
+ <ChevronRight
+ data-expanded={!collapsed}
+ className="size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ease-out data-[expanded=true]:rotate-90"
+ />
+ <span>
+ <Trans>Properties</Trans>
+ </span>
+ </Button>
+ </CollapsibleTrigger>
+ <CollapsibleContent className="overflow-hidden data-[state=open]:animate-[collapsible-down_150ms_ease-out] data-[state=closed]:animate-[collapsible-up_150ms_ease-in]">
+ {parseError ? (
+ <div
+ role="alert"
+ data-testid="property-panel-yaml-error"
+ className="mb-1 flex items-start gap-1.5 rounded border border-destructive/30 bg-destructive/5 px-2 py-1.5 text-[11px] text-destructive"
+ >
+ <AlertTriangle className="size-3.5 shrink-0 mt-0.5" />
+ <div>
+ <Trans>
+ The properties block at the top of this doc has a formatting error. Switch to
+ source mode to fix it.
+ </Trans>
+ <span className="block text-[10px] opacity-80">{parseError}</span>
+ </div>
</div>
- </div>
- ) : null}
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- onDragEnd={handleDragEnd}
- >
- <SortableContext
- items={renderKeys.map((k, i) => rowId(k, i))}
- strategy={verticalListSortingStrategy}
+ ) : null}
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handleDragEnd}
>
- {renderKeys.map((key, idx) => {
- const value = map[key];
- if (value === undefined) return null;
- const declared = overrides[key] ?? inferType(value);
- const renameState = renaming?.key === key ? renaming : null;
- const isDuplicate = (dupCount.get(key) ?? 0) > 1;
- return (
- <FrontmatterRow
- // biome-ignore lint/suspicious/noArrayIndexKey: position-aware key for dup-name rows.
- key={`${key}-${idx}`}
- sortableId={rowId(key, idx)}
- keyName={key}
- value={value}
- declared={declared}
- error={errors[key] ?? null}
- resetCounter={resetCounters[key] ?? 0}
- isDuplicate={isDuplicate}
- rename={{
- state: renameState,
- onBegin: () => beginRename(key),
- onChangeDraft: changeRenameDraft,
- onCommit: commitRename,
- onCancel: cancelRename,
- }}
- onCommit={(v) => commitProperty(key, v)}
- onChangeType={(t) => setType(key, t)}
- onRemove={() => removeProperty(key)}
- />
- );
- })}
- </SortableContext>
- </DndContext>
- {/*
+ <SortableContext
+ items={renderKeys.map((k, i) => rowId(k, i))}
+ strategy={verticalListSortingStrategy}
+ >
+ {renderKeys.map((key, idx) => {
+ const value = map[key];
+ if (value === undefined) return null;
+ const declared = overrides[key] ?? inferType(value);
+ const renameState = renaming?.key === key ? renaming : null;
+ const isDuplicate = (dupCount.get(key) ?? 0) > 1;
+ return (
+ <FrontmatterRow
+ // biome-ignore lint/suspicious/noArrayIndexKey: position-aware key for dup-name rows.
+ key={`${key}-${idx}`}
+ sortableId={rowId(key, idx)}
+ keyName={key}
+ value={value}
+ declared={declared}
+ error={errors[key] ?? null}
+ resetCounter={resetCounters[key] ?? 0}
+ isDuplicate={isDuplicate}
+ rename={{
+ state: renameState,
+ onBegin: () => beginRename(key),
+ onChangeDraft: changeRenameDraft,
+ onCommit: commitRename,
+ onCancel: cancelRename,
+ }}
+ onCommit={(v) => commitProperty(key, v)}
+ onChangeType={(t) => setType(key, t)}
+ onRemove={() => removeProperty(key)}
+ />
+ );
+ })}
+ </SortableContext>
+ </DndContext>
+ {/*
Tags discoverability affordance — render an empty, pinned-at-
end `tags` row when the key is absent from the file YAML
(`map`). The first commit from this virtual row writes the YAML
@@ -411,50 +414,51 @@ export function PropertyPanel({ provider }: PropertyPanelProps) {
the virtual row is purely for "this doc has no tags field yet,
but you can add one here."
*/}
- {!Object.hasOwn(map, 'tags') ? (
- <FrontmatterRow
- key="virtual-tags"
- keyName="tags"
- value={[]}
- declared="list"
- error={errors.tags ?? null}
- resetCounter={resetCounters.tags ?? 0}
- isPlaceholder
- onCommit={(v) => commitProperty('tags', v)}
- onChangeType={() => {}}
- />
- ) : null}
- {adding ? (
- <AddPropertyRow
- draft={adding}
- onChangeName={changeAddName}
- onChangeType={changeAddType}
- onChangeValue={changeAddValue}
- onCommit={commitAdd}
- onCancel={cancelAdd}
- />
- ) : (
- <div className="mt-1 flex items-center gap-1">
- <span aria-hidden className="h-7 w-4 shrink-0" />
- <Button
- type="button"
- variant="ghost"
- size="sm"
- data-testid="add-property-trigger"
- onClick={beginAdd}
- aria-label={t`Add property`}
- className="flex items-center gap-1.5 rounded px-2 py-1 font-medium text-sm hover:bg-muted/50 hover:text-foreground"
- >
- <Plus className="size-3.5" />
- <span>
- <Trans>Add</Trans>
- </span>
- </Button>
- </div>
- )}
- </CollapsibleContent>
- </Collapsible>
- </div>
+ {!Object.hasOwn(map, 'tags') ? (
+ <FrontmatterRow
+ key="virtual-tags"
+ keyName="tags"
+ value={[]}
+ declared="list"
+ error={errors.tags ?? null}
+ resetCounter={resetCounters.tags ?? 0}
+ isPlaceholder
+ onCommit={(v) => commitProperty('tags', v)}
+ onChangeType={() => {}}
+ />
+ ) : null}
+ {adding ? (
+ <AddPropertyRow
+ draft={adding}
+ onChangeName={changeAddName}
+ onChangeType={changeAddType}
+ onChangeValue={changeAddValue}
+ onCommit={commitAdd}
+ onCancel={cancelAdd}
+ />
+ ) : (
+ <div className="mt-1 flex items-center gap-1">
+ <span aria-hidden className="h-7 w-4 shrink-0" />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ data-testid="add-property-trigger"
+ onClick={beginAdd}
+ aria-label={t`Add property`}
+ className="flex items-center gap-1.5 rounded px-2 py-1 font-medium text-sm hover:bg-muted/50 hover:text-foreground"
+ >
+ <Plus className="size-3.5" />
+ <span>
+ <Trans>Add</Trans>
+ </span>
+ </Button>
+ </div>
+ )}
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
+ </FrontmatterBindingProvider>
);
}
@@ -463,11 +467,3 @@ interface PatchResult {
error?: string;
fieldErrors?: Record<string, string>;
}
-
-function sameValue(a: FrontmatterValue, b: FrontmatterValue): boolean {
- if (Array.isArray(a) && Array.isArray(b)) {
- if (a.length !== b.length) return false;
- return a.every((item, i) => item === b[i]);
- }
- return a === b;
-}
diff --git a/packages/app/src/components/PropertyWidgets.tsx b/packages/app/src/components/PropertyWidgets.tsx
index 864eb054a..fe7a90e1a 100644
--- a/packages/app/src/components/PropertyWidgets.tsx
+++ b/packages/app/src/components/PropertyWidgets.tsx
@@ -11,7 +11,16 @@ import type { MessageDescriptor } from '@lingui/core';
import { msg } from '@lingui/core/macro';
import { Trans, useLingui } from '@lingui/react/macro';
import { format, parse, parseISO } from 'date-fns';
-import { Calendar as CalendarIcon, Hash, List, Pencil, SquareCheck, Type, X } from 'lucide-react';
+import {
+ Braces,
+ Calendar as CalendarIcon,
+ Hash,
+ List,
+ Pencil,
+ SquareCheck,
+ Type,
+ X,
+} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
@@ -471,6 +480,7 @@ export const TYPE_ICON: Record<FrontmatterType, typeof Type> = {
boolean: SquareCheck,
date: CalendarIcon,
list: List,
+ object: Braces,
};
const TYPE_LABEL: Record<FrontmatterType, MessageDescriptor> = {
@@ -479,6 +489,7 @@ const TYPE_LABEL: Record<FrontmatterType, MessageDescriptor> = {
boolean: msg`Checkbox`,
date: msg`Date`,
list: msg`List`,
+ object: msg`Object`,
};
export const DEFAULT_VALUE_FOR_TYPE: Record<FrontmatterType, FrontmatterValue> = {
@@ -487,6 +498,7 @@ export const DEFAULT_VALUE_FOR_TYPE: Record<FrontmatterType, FrontmatterValue> =
boolean: false,
date: '',
list: [],
+ object: {},
};
interface TypeIconButtonProps {
@@ -552,20 +564,22 @@ export function TypeIconButton({
value={type}
onValueChange={(next) => onChangeType(next as FrontmatterType)}
>
- {(Object.keys(TYPE_ICON) as FrontmatterType[]).map((typeKey) => {
- const ItemIcon = TYPE_ICON[typeKey];
- return (
- <DropdownMenuRadioItem
- key={typeKey}
- value={typeKey}
- data-testid="type-picker-item"
- data-type={typeKey}
- >
- <ItemIcon className="size-3.5 text-muted-foreground" />
- <span>{t(TYPE_LABEL[typeKey])}</span>
- </DropdownMenuRadioItem>
- );
- })}
+ {(Object.keys(TYPE_ICON) as FrontmatterType[])
+ .filter((typeKey) => typeKey !== 'object')
+ .map((typeKey) => {
+ const ItemIcon = TYPE_ICON[typeKey];
+ return (
+ <DropdownMenuRadioItem
+ key={typeKey}
+ value={typeKey}
+ data-testid="type-picker-item"
+ data-type={typeKey}
+ >
+ <ItemIcon className="size-3.5 text-muted-foreground" />
+ <span>{t(TYPE_LABEL[typeKey])}</span>
+ </DropdownMenuRadioItem>
+ );
+ })}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
@@ -576,19 +590,24 @@ export function coerceValue(value: FrontmatterValue, target: FrontmatterType): F
switch (target) {
case 'text': {
if (Array.isArray(value)) return value.join(', ');
+ if (typeof value === 'object' && value !== null) return '';
return String(value);
}
case 'number': {
if (typeof value === 'number') return value;
- const candidate = Array.isArray(value) ? value[0] : String(value);
- const parsed = Number.parseFloat(candidate ?? '');
+ if (typeof value === 'object' && value !== null) return 0;
+ const head = Array.isArray(value) ? value[0] : value;
+ const candidate = typeof head === 'string' ? head : head == null ? '' : String(head);
+ const parsed = Number.parseFloat(candidate);
return Number.isFinite(parsed) ? parsed : 0;
}
case 'boolean': {
if (typeof value === 'boolean') return value;
if (typeof value === 'number') return value !== 0;
- const s = Array.isArray(value) ? value[0] : String(value);
- return (s ?? '').toLowerCase() === 'true';
+ if (typeof value === 'object' && value !== null) return false;
+ const head = Array.isArray(value) ? value[0] : value;
+ const candidate = typeof head === 'string' ? head : head == null ? '' : String(head);
+ return candidate.toLowerCase() === 'true';
}
case 'date': {
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
@@ -597,9 +616,14 @@ export function coerceValue(value: FrontmatterValue, target: FrontmatterType): F
}
case 'list': {
if (Array.isArray(value)) return value;
+ if (typeof value === 'object' && value !== null) return [];
const s = String(value);
return s ? [s] : [];
}
+ case 'object': {
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) return value;
+ return {};
+ }
}
}
@@ -608,7 +632,70 @@ export function resolveWidgetType(
declared: FrontmatterType,
): FrontmatterType {
if (Array.isArray(value)) return 'list';
+ if (typeof value === 'object' && value !== null) return 'object';
if (typeof value === 'boolean') return 'boolean';
if (typeof value === 'number') return 'number';
- return declared === 'list' ? 'text' : declared;
+ if (declared === 'list' || declared === 'object') return 'text';
+ return declared;
+}
+
+export function isComplexValue(value: FrontmatterValue): boolean {
+ if (Array.isArray(value)) {
+ return value.some((entry) => typeof entry === 'object' && entry !== null);
+ }
+ return typeof value === 'object' && value !== null;
+}
+
+export function isPlainObjectValue(
+ value: FrontmatterValue,
+): value is { [key: string]: FrontmatterValue } {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+export function isArrayOfObjectsValue(
+ value: FrontmatterValue,
+): value is Array<{ [key: string]: FrontmatterValue }> {
+ if (!Array.isArray(value) || value.length === 0) return false;
+ return value.every((entry) => isPlainObjectValue(entry as FrontmatterValue));
+}
+
+interface ComplexValueWidgetProps {
+ keyName: string;
+ value: FrontmatterValue;
+}
+
+export function ComplexValueWidget({ keyName, value }: ComplexValueWidgetProps) {
+ const summary = summarizeComplexValue(value);
+ const isArray = Array.isArray(value);
+ return (
+ <div
+ data-testid="complex-value-widget"
+ data-key={keyName}
+ data-shape={isArray ? 'array' : 'object'}
+ className="flex min-h-7 w-full min-w-0 items-center px-2 py-1"
+ >
+ <span className="truncate font-mono text-xs text-muted-foreground" title={summary}>
+ {summary}
+ </span>
+ <span className="ml-2 shrink-0 text-2xs text-muted-foreground/70">
+ <Trans>(read-only — edit in source mode for now)</Trans>
+ </span>
+ </div>
+ );
+}
+
+const COMPLEX_PREVIEW_KEY_LIMIT = 4;
+
+function summarizeComplexValue(value: FrontmatterValue): string {
+ if (Array.isArray(value)) {
+ return value.length === 1 ? '[1 item]' : `[${value.length} items]`;
+ }
+ if (typeof value === 'object' && value !== null) {
+ const keys = Object.keys(value);
+ if (keys.length === 0) return '{}';
+ const head = keys.slice(0, COMPLEX_PREVIEW_KEY_LIMIT).join(', ');
+ const more = keys.length > COMPLEX_PREVIEW_KEY_LIMIT ? `, …` : '';
+ return `{${head}${more}}`;
+ }
+ return String(value);
}
diff --git a/packages/app/src/components/frontmatter-error-utils.ts b/packages/app/src/components/frontmatter-error-utils.ts
new file mode 100644
index 000000000..2af0c6534
--- /dev/null
+++ b/packages/app/src/components/frontmatter-error-utils.ts
@@ -0,0 +1,12 @@
+import { type FrontmatterValidationError, fieldErrorsFromError } from '@inkeep/open-knowledge-core';
+
+export function describeError(
+ error: FrontmatterValidationError,
+ key: string,
+ fallback: string,
+): string {
+ if (error.code === 'WRITE_ERROR') return error.detail;
+ const fieldErrors = fieldErrorsFromError(error);
+ if (fieldErrors[key]) return fieldErrors[key];
+ return error.issues[0]?.message ?? fallback;
+}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index fee575191..b93b790a5 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -174,6 +174,7 @@
"54Y6Fg": ["Could not load templates. Try again later."],
"56WWtu": ["Couldn't load starter packs: ", ["error"]],
"56xUL1": ["Property name"],
+ "57fiu8": ["(read-only — edit in source mode for now)"],
"5ALjdr": ["Move through visual-editor find results from the find field."],
"5Ajb15": ["The formula <0>c = √(a² + b²)</0> renders inline."],
"5ClEAu": ["Inline hashtag for cross-doc grouping."],
@@ -247,6 +248,7 @@
"6gRgw8": ["Retry"],
"6hfDJr": ["Server error: ", ["status"]],
"6ibbCg": ["Create your first file"],
+ "6ki7F2": [["0", "plural", { "one": ["#", " item"], "other": ["#", " items"] }]],
"6m_7We": ["Open this settings dialog."],
"6q0rnH": ["writing"],
"6u9LvN": [["days", "plural", { "one": ["#", " day ago"], "other": ["#", " days ago"] }]],
@@ -427,6 +429,7 @@
"C_cPoW": ["Your GitHub session expired — sign in again to verify push access."],
"ChAtFg": ["You don't have permission to push to this repo"],
"Ck9XRt": ["Couldn't save the key — please try again."],
+ "CmeH9S": ["Add property to ", ["keyName"]],
"CvsD6Y": ["via ", ["viaTags"]],
"D4H2N6": ["Remove ", ["tag"]],
"D8OV7J": ["Only collaborators"],
@@ -594,6 +597,7 @@
"J2MgzQ": ["Undo all edits on ", ["docName"]],
"J2Mv98": ["Name (e.g. ", ["login"], ")"],
"J2eKUI": ["File"],
+ "J3HzPL": ["Collapse ", ["keyName"]],
"J6N5MX": ["Couldn't construct the share URL. Try Done and re-share."],
"JCxGEX": [
"No disconnected pages. Pages appear here only when they have no incoming and no outgoing graph edges."
@@ -713,6 +717,7 @@
"NKkZXl": ["Initialize and open"],
"NOHyEE": ["Retry push"],
"NORKZU": ["Pattern warnings: ", ["summary"]],
+ "NQ8llq": ["Add item"],
"NRSLBe": [["diffMin"], "m ago"],
"NSnIUP": ["Two-page (even)"],
"NUr4kz": ["A reusable starting point for new documents in this folder."],
@@ -752,11 +757,13 @@
]
],
"OLBz-_": ["Mermaid diagram failed to render."],
+ "OLIKgw": ["Drag item ", ["0"], " to reorder"],
"ONPvOb": ["Loading agent activity"],
"ONgEZF": ["Loading headings for ", ["pageTarget"]],
"OTF92M": ["Label <0>(optional display text)</0>"],
"OX2Neh": ["Inline code"],
"OYnx7O": ["Path cannot start with \"/\""],
+ "OdmsFg": ["Failed to delete item"],
"OiHJdA": [
"Move through slash, wiki-link, tag, and path suggestions; accept or dismiss the active suggestion."
],
@@ -797,6 +804,7 @@
"Q8A-U_": ["Connected to"],
"QDZbvN": [["diffDays"], "d ago"],
"QI4KgP": [["fileLabel"], " · ", ["folderLabel"]],
+ "QOINDn": ["empty"],
"QQghPu": ["Install in Claude Desktop"],
"QR5SP1": ["created template"],
"QWks14": ["A short line shown under the name in the template list."],
@@ -846,6 +854,7 @@
"SCzAbA": [["phase"], " — ", ["pct"], "%"],
"SEYWYq": ["Undo all edits on this file?"],
"SFN6dN": ["Heading 3"],
+ "STTOnz": [["keyName"], " type: complex value (nested; read-only)"],
"SUOoXn": ["Failed to open project."],
"SYfHmN": ["Unpin tab"],
"Sc1bKE": [
@@ -929,6 +938,7 @@
"VuxVSP": ["Start source completion"],
"VvS_k_": ["Config sharing is now local-only."],
"W-ntoW": ["heading-slug"],
+ "W0i24j": ["Object"],
"W1qRuM": ["This document is already active in the editor. Use Open to collapse the graph."],
"W5A0Ly": ["An unexpected error occurred."],
"W8uemY": ["Pick a starter pack to scaffold folders, templates, and AI-readable rules."],
@@ -1150,6 +1160,7 @@
["rawName"],
"</0> can't be used as a project identifier — it has no characters left after sanitization. Click Browse to pick a folder whose name contains at least one alphanumeric character."
],
+ "cEoyWz": ["Add item to ", ["keyName"]],
"cF9DyA": ["Reconnecting after server restart"],
"cIptmH": ["In the Claude Desktop App"],
"cKjLuT": ["(project + user)"],
@@ -1198,6 +1209,7 @@
"eBIT9h": ["Paste failed.", ["restoreSuffix"]],
"eFJkVt": ["Clone failed: ", ["cloneError"]],
"eG8Jsg": ["Toggle source tab focus mode"],
+ "eKThTQ": ["Failed to reorder"],
"eNQGRb": ["Inline LaTeX math rendered with KaTeX."],
"ePK91l": ["Edit"],
"eSu2Xn": [
@@ -1249,6 +1261,7 @@
],
"gUlRQj": ["Orphans"],
"gYz2ep": ["Expires in ", ["timeLabel"]],
+ "gbHcbI": ["Failed to delete property"],
"gcV0dI": ["The folders and templates are in place; there's nothing left to scaffold."],
"gg3Rpy": ["Restore this version?"],
"ggm6JX": [
@@ -1443,6 +1456,7 @@
],
"mNY1G6": ["Undo all edits"],
"mSJ3Rn": ["Computing scaffold plan"],
+ "mU3j1b": ["Remove item ", ["0"]],
"mWVJRX": ["Collapsible section with a clickable summary."],
"mYGY3B": ["Date"],
"mYLRjR": ["You picked ~/Desktop. Open Knowledge will index everything on your desktop."],
@@ -1616,6 +1630,7 @@
"s-MGs7": ["Resources"],
"s-XOaI": ["File name"],
"s0IDhW": ["This file could not be found."],
+ "s0J_k9": [["0", "plural", { "one": ["#", " key"], "other": ["#", " keys"] }]],
"s1c0ja": ["Bullet List"],
"s3caR3": ["Deleting"],
"sE7R19": [
@@ -1792,8 +1807,10 @@
"yLq4w4": ["Separator"],
"yMgL_E": ["Find field navigation"],
"yQE2r9": ["Loading"],
+ "yUxR-Q": ["Expand ", ["keyName"]],
"yWWThY": ["Asset reference"],
"yYR6za": ["Display text"],
+ "y_5CE8": ["Item ", ["0"]],
"yf5r22": [
["keyName"],
" type: ",
@@ -1853,6 +1870,7 @@
"zkz0Fg": ["Set up syncing"],
"zlErBl": ["Page headings error response did not match RFC 9457"],
"zo3Dl7": ["Toggle thumbnails"],
+ "ztKII6": ["Failed to add item"],
"zwBp5t": ["Private"]
}
}
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 93cae5d6e..352cc87df 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -41,6 +41,7 @@ msgstr "\"{docName}\" took too long. Check your connection."
msgid "\"{trimmed}\" already exists here"
msgstr "\"{trimmed}\" already exists here"
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "\"frontmatter\" is a reserved property name"
msgstr "\"frontmatter\" is a reserved property name"
@@ -71,6 +72,10 @@ msgstr "(opens in new tab)"
msgid "(project + user)"
msgstr "(project + user)"
+#: src/components/PropertyWidgets.tsx
+msgid "(read-only — edit in source mode for now)"
+msgstr "(read-only — edit in source mode for now)"
+
#: src/components/NewItemDialog.tsx
msgid "(root)"
msgstr "(root)"
@@ -89,6 +94,16 @@ msgstr "(user-level only)"
msgid "{0, plural, one {# doc} other {# docs}}"
msgstr "{0, plural, one {# doc} other {# docs}}"
+#. placeholder {0}: value.length
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "{0, plural, one {# item} other {# items}}"
+msgstr "{0, plural, one {# item} other {# items}}"
+
+#. placeholder {0}: entries.length
+#: src/components/ObjectWidget.tsx
+msgid "{0, plural, one {# key} other {# keys}}"
+msgstr "{0, plural, one {# key} other {# keys}}"
+
#. placeholder {0}: blocked.length
#: src/editor/components/PreviewBlockedNotice.tsx
msgid "{0, plural, one {# request blocked by the preview's security policy} other {# requests blocked by the preview's security policy}}"
@@ -261,6 +276,10 @@ msgstr "{keyName} type: {typeLabel} (inherited from folder properties; not edita
msgid "{keyName} type: {typeLabel}. Click to change."
msgstr "{keyName} type: {typeLabel}. Click to change."
+#: src/components/FrontmatterRow.tsx
+msgid "{keyName} type: complex value (nested; read-only)"
+msgstr "{keyName} type: complex value (nested; read-only)"
+
#: src/components/PageHeaderWidgets.tsx
#: src/components/PropertyWidgets.tsx
msgid "{keyName} value"
@@ -489,6 +508,7 @@ msgstr "Activity"
#. Primary button that writes MCP config for the selected AI tools
#: src/components/FrontmatterRow.tsx
#: src/components/McpConsentDialogBody.tsx
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "Add"
msgstr "Add"
@@ -513,6 +533,14 @@ msgstr "Add another pattern"
msgid "Add cursors or select matching occurrences through CodeMirror."
msgstr "Add cursors or select matching occurrences through CodeMirror."
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Add item"
+msgstr "Add item"
+
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Add item to {keyName}"
+msgstr "Add item to {keyName}"
+
#: src/components/settings/SearchSection.tsx
msgid "Add meaning-based ranking to search so conceptually-related pages surface even when they share no keywords. This setting applies only to this computer."
msgstr "Add meaning-based ranking to search so conceptually-related pages surface even when they share no keywords. This setting applies only to this computer."
@@ -533,6 +561,10 @@ msgstr "Add properties"
msgid "Add property"
msgstr "Add property"
+#: src/components/ObjectWidget.tsx
+msgid "Add property to {keyName}"
+msgstr "Add property to {keyName}"
+
#: src/editor/components/Tabs.tsx
msgid "Add tab"
msgstr "Add tab"
@@ -1094,6 +1126,11 @@ msgstr "Collapse"
msgid "Collapse {docName}"
msgstr "Collapse {docName}"
+#: src/components/ArrayOfObjectsWidget.tsx
+#: src/components/ObjectWidget.tsx
+msgid "Collapse {keyName}"
+msgstr "Collapse {keyName}"
+
#: src/components/FileSidebar.tsx
msgid "Collapse all"
msgstr "Collapse all"
@@ -1851,6 +1888,11 @@ msgstr "Drag {keyName} to reorder"
msgid "Drag {patternText} to reorder"
msgstr "Drag {patternText} to reorder"
+#. placeholder {0}: index + 1
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Drag item {0} to reorder"
+msgstr "Drag item {0} to reorder"
+
#: src/components/FileTree.tsx
msgid "Duplicate"
msgstr "Duplicate"
@@ -1984,6 +2026,11 @@ msgstr "Embeddings are computed only when a search runs and are cached locally u
msgid "Embeddings provider key"
msgstr "Embeddings provider key"
+#: src/components/ArrayOfObjectsWidget.tsx
+#: src/components/ObjectWidget.tsx
+msgid "empty"
+msgstr "empty"
+
#: src/components/PropertyWidgets.tsx
msgid "Empty"
msgstr "Empty"
@@ -2037,6 +2084,11 @@ msgstr "Exit merge"
msgid "Expand {docName}"
msgstr "Expand {docName}"
+#: src/components/ArrayOfObjectsWidget.tsx
+#: src/components/ObjectWidget.tsx
+msgid "Expand {keyName}"
+msgstr "Expand {keyName}"
+
#: src/components/FileSidebar.tsx
msgid "Expand all"
msgstr "Expand all"
@@ -2074,6 +2126,11 @@ msgstr "External link"
msgid "External wiki link"
msgstr "External wiki link"
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Failed to add item"
+msgstr "Failed to add item"
+
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "Failed to add property"
msgstr "Failed to add property"
@@ -2102,10 +2159,18 @@ msgstr "Failed to create folder"
msgid "Failed to create page"
msgstr "Failed to create page"
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Failed to delete item"
+msgstr "Failed to delete item"
+
#: src/components/FileTree.tsx
msgid "Failed to delete path"
msgstr "Failed to delete path"
+#: src/components/ObjectWidget.tsx
+msgid "Failed to delete property"
+msgstr "Failed to delete property"
+
#: src/components/settings/SearchSection.tsx
msgid "Failed to disable semantic search — {detail}"
msgstr "Failed to disable semantic search — {detail}"
@@ -2244,6 +2309,7 @@ msgstr "Failed to rename"
msgid "Failed to rename path"
msgstr "Failed to rename path"
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "Failed to rename property"
msgstr "Failed to rename property"
@@ -2252,6 +2318,12 @@ msgstr "Failed to rename property"
msgid "Failed to render PDF"
msgstr "Failed to render PDF"
+#: src/components/ArrayOfObjectsWidget.tsx
+#: src/components/ObjectWidget.tsx
+msgid "Failed to reorder"
+msgstr "Failed to reorder"
+
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "Failed to update property"
msgstr "Failed to update property"
@@ -2816,6 +2888,11 @@ msgstr "Invalid patch payload"
msgid "Italic"
msgstr "Italic"
+#. placeholder {0}: index + 1
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Item {0}"
+msgstr "Item {0}"
+
#: src/components/CreatedItemsList.tsx
msgid "Items to be created"
msgstr "Items to be created"
@@ -3232,6 +3309,7 @@ msgid "Name cannot be empty"
msgstr "Name cannot be empty"
#: src/components/FolderPropertiesCard.tsx
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "Name is required"
msgstr "Name is required"
@@ -3586,6 +3664,10 @@ msgstr "Number"
msgid "Numbered list of items."
msgstr "Numbered list of items."
+#: src/components/PropertyWidgets.tsx
+msgid "Object"
+msgstr "Object"
+
#: src/editor/components/Pdf.tsx
msgid "of {totalPages}"
msgstr "of {totalPages}"
@@ -4226,6 +4308,7 @@ msgstr "Project-level pages with no outgoing graph edges."
msgid "Properties"
msgstr "Properties"
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "Property \"{trimmed}\" already exists"
msgstr "Property \"{trimmed}\" already exists"
@@ -4398,6 +4481,11 @@ msgstr "Remove failed: {error}"
msgid "Remove from recent projects"
msgstr "Remove from recent projects"
+#. placeholder {0}: index + 1
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Remove item {0}"
+msgstr "Remove item {0}"
+
#: src/editor/bubble-menu/LinkEditPopover.tsx
msgid "Remove link"
msgstr "Remove link"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index b34499b5f..ce7c8c6c3 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -174,6 +174,7 @@
"54Y6Fg": ["Ćōũĺď ńōţ ĺōàď ţēḿƥĺàţēś. Ţŕŷ àĝàĩń ĺàţēŕ."],
"56WWtu": ["Ćōũĺďń'ţ ĺōàď śţàŕţēŕ ƥàćķś: ", ["error"]],
"56xUL1": ["Ƥŕōƥēŕţŷ ńàḿē"],
+ "57fiu8": ["(ŕēàď-ōńĺŷ — ēďĩţ ĩń śōũŕćē ḿōďē ƒōŕ ńōŵ)"],
"5ALjdr": ["Ḿōvē ţĥŕōũĝĥ vĩśũàĺ-ēďĩţōŕ ƒĩńď ŕēśũĺţś ƒŕōḿ ţĥē ƒĩńď ƒĩēĺď."],
"5Ajb15": ["Ţĥē ƒōŕḿũĺà <0>ć = √(ಠ+ ƀ²)</0> ŕēńďēŕś ĩńĺĩńē."],
"5ClEAu": ["Ĩńĺĩńē ĥàśĥţàĝ ƒōŕ ćŕōśś-ďōć ĝŕōũƥĩńĝ."],
@@ -247,6 +248,7 @@
"6gRgw8": ["Ŕēţŕŷ"],
"6hfDJr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"]],
"6ibbCg": ["Ćŕēàţē ŷōũŕ ƒĩŕśţ ƒĩĺē"],
+ "6ki7F2": [["0", "plural", { "one": ["#", " ĩţēḿ"], "other": ["#", " ĩţēḿś"] }]],
"6m_7We": ["Ōƥēń ţĥĩś śēţţĩńĝś ďĩàĺōĝ."],
"6q0rnH": ["ŵŕĩţĩńĝ"],
"6u9LvN": [["days", "plural", { "one": ["#", " ďàŷ àĝō"], "other": ["#", " ďàŷś àĝō"] }]],
@@ -427,6 +429,7 @@
"C_cPoW": ["Ŷōũŕ ĜĩţĤũƀ śēśśĩōń ēxƥĩŕēď — śĩĝń ĩń àĝàĩń ţō vēŕĩƒŷ ƥũśĥ àććēśś."],
"ChAtFg": ["Ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō"],
"Ck9XRt": ["Ćōũĺďń'ţ śàvē ţĥē ķēŷ — ƥĺēàśē ţŕŷ àĝàĩń."],
+ "CmeH9S": ["Àďď ƥŕōƥēŕţŷ ţō ", ["keyName"]],
"CvsD6Y": ["vĩà ", ["viaTags"]],
"D4H2N6": ["Ŕēḿōvē ", ["tag"]],
"D8OV7J": ["Ōńĺŷ ćōĺĺàƀōŕàţōŕś"],
@@ -594,6 +597,7 @@
"J2MgzQ": ["Ũńďō àĺĺ ēďĩţś ōń ", ["docName"]],
"J2Mv98": ["Ńàḿē (ē.ĝ. ", ["login"], ")"],
"J2eKUI": ["Ƒĩĺē"],
+ "J3HzPL": ["Ćōĺĺàƥśē ", ["keyName"]],
"J6N5MX": ["Ćōũĺďń'ţ ćōńśţŕũćţ ţĥē śĥàŕē ŨŔĹ. Ţŕŷ Ďōńē àńď ŕē-śĥàŕē."],
"JCxGEX": [
"Ńō ďĩśćōńńēćţēď ƥàĝēś. Ƥàĝēś àƥƥēàŕ ĥēŕē ōńĺŷ ŵĥēń ţĥēŷ ĥàvē ńō ĩńćōḿĩńĝ àńď ńō ōũţĝōĩńĝ ĝŕàƥĥ ēďĝēś."
@@ -713,6 +717,7 @@
"NKkZXl": ["Ĩńĩţĩàĺĩźē àńď ōƥēń"],
"NOHyEE": ["Ŕēţŕŷ ƥũśĥ"],
"NORKZU": ["Ƥàţţēŕń ŵàŕńĩńĝś: ", ["summary"]],
+ "NQ8llq": ["Àďď ĩţēḿ"],
"NRSLBe": [["diffMin"], "ḿ àĝō"],
"NSnIUP": ["Ţŵō-ƥàĝē (ēvēń)"],
"NUr4kz": ["À ŕēũśàƀĺē śţàŕţĩńĝ ƥōĩńţ ƒōŕ ńēŵ ďōćũḿēńţś ĩń ţĥĩś ƒōĺďēŕ."],
@@ -752,11 +757,13 @@
]
],
"OLBz-_": ["Ḿēŕḿàĩď ďĩàĝŕàḿ ƒàĩĺēď ţō ŕēńďēŕ."],
+ "OLIKgw": ["Ďŕàĝ ĩţēḿ ", ["0"], " ţō ŕēōŕďēŕ"],
"ONPvOb": ["Ĺōàďĩńĝ àĝēńţ àćţĩvĩţŷ"],
"ONgEZF": ["Ĺōàďĩńĝ ĥēàďĩńĝś ƒōŕ ", ["pageTarget"]],
"OTF92M": ["Ĺàƀēĺ <0>(ōƥţĩōńàĺ ďĩśƥĺàŷ ţēxţ)</0>"],
"OX2Neh": ["Ĩńĺĩńē ćōďē"],
"OYnx7O": ["Ƥàţĥ ćàńńōţ śţàŕţ ŵĩţĥ \"/\""],
+ "OdmsFg": ["Ƒàĩĺēď ţō ďēĺēţē ĩţēḿ"],
"OiHJdA": [
"Ḿōvē ţĥŕōũĝĥ śĺàśĥ, ŵĩķĩ-ĺĩńķ, ţàĝ, àńď ƥàţĥ śũĝĝēśţĩōńś; àććēƥţ ōŕ ďĩśḿĩśś ţĥē àćţĩvē śũĝĝēśţĩōń."
],
@@ -797,6 +804,7 @@
"Q8A-U_": ["Ćōńńēćţēď ţō"],
"QDZbvN": [["diffDays"], "ď àĝō"],
"QI4KgP": [["fileLabel"], " · ", ["folderLabel"]],
+ "QOINDn": ["ēḿƥţŷ"],
"QQghPu": ["Ĩńśţàĺĺ ĩń Ćĺàũďē Ďēśķţōƥ"],
"QR5SP1": ["ćŕēàţēď ţēḿƥĺàţē"],
"QWks14": ["À śĥōŕţ ĺĩńē śĥōŵń ũńďēŕ ţĥē ńàḿē ĩń ţĥē ţēḿƥĺàţē ĺĩśţ."],
@@ -846,6 +854,7 @@
"SCzAbA": [["phase"], " — ", ["pct"], "%"],
"SEYWYq": ["Ũńďō àĺĺ ēďĩţś ōń ţĥĩś ƒĩĺē?"],
"SFN6dN": ["Ĥēàďĩńĝ 3"],
+ "STTOnz": [["keyName"], " ţŷƥē: ćōḿƥĺēx vàĺũē (ńēśţēď; ŕēàď-ōńĺŷ)"],
"SUOoXn": ["Ƒàĩĺēď ţō ōƥēń ƥŕōĴēćţ."],
"SYfHmN": ["Ũńƥĩń ţàƀ"],
"Sc1bKE": [
@@ -929,6 +938,7 @@
"VuxVSP": ["Śţàŕţ śōũŕćē ćōḿƥĺēţĩōń"],
"VvS_k_": ["Ćōńƒĩĝ śĥàŕĩńĝ ĩś ńōŵ ĺōćàĺ-ōńĺŷ."],
"W-ntoW": ["ĥēàďĩńĝ-śĺũĝ"],
+ "W0i24j": ["ŌƀĴēćţ"],
"W1qRuM": ["Ţĥĩś ďōćũḿēńţ ĩś àĺŕēàďŷ àćţĩvē ĩń ţĥē ēďĩţōŕ. Ũśē Ōƥēń ţō ćōĺĺàƥśē ţĥē ĝŕàƥĥ."],
"W5A0Ly": ["Àń ũńēxƥēćţēď ēŕŕōŕ ōććũŕŕēď."],
"W8uemY": ["Ƥĩćķ à śţàŕţēŕ ƥàćķ ţō śćàƒƒōĺď ƒōĺďēŕś, ţēḿƥĺàţēś, àńď ÀĨ-ŕēàďàƀĺē ŕũĺēś."],
@@ -1150,6 +1160,7 @@
["rawName"],
"</0> ćàń'ţ ƀē ũśēď àś à ƥŕōĴēćţ ĩďēńţĩƒĩēŕ — ĩţ ĥàś ńō ćĥàŕàćţēŕś ĺēƒţ àƒţēŕ śàńĩţĩźàţĩōń. Ćĺĩćķ ßŕōŵśē ţō ƥĩćķ à ƒōĺďēŕ ŵĥōśē ńàḿē ćōńţàĩńś àţ ĺēàśţ ōńē àĺƥĥàńũḿēŕĩć ćĥàŕàćţēŕ."
],
+ "cEoyWz": ["Àďď ĩţēḿ ţō ", ["keyName"]],
"cF9DyA": ["Ŕēćōńńēćţĩńĝ àƒţēŕ śēŕvēŕ ŕēśţàŕţ"],
"cIptmH": ["Ĩń ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ"],
"cKjLuT": ["(ƥŕōĴēćţ + ũśēŕ)"],
@@ -1198,6 +1209,7 @@
"eBIT9h": ["Ƥàśţē ƒàĩĺēď.", ["restoreSuffix"]],
"eFJkVt": ["Ćĺōńē ƒàĩĺēď: ", ["cloneError"]],
"eG8Jsg": ["Ţōĝĝĺē śōũŕćē ţàƀ ƒōćũś ḿōďē"],
+ "eKThTQ": ["Ƒàĩĺēď ţō ŕēōŕďēŕ"],
"eNQGRb": ["Ĩńĺĩńē ĹàŢēX ḿàţĥ ŕēńďēŕēď ŵĩţĥ ĶàŢēX."],
"ePK91l": ["Ēďĩţ"],
"eSu2Xn": [
@@ -1249,6 +1261,7 @@
],
"gUlRQj": ["Ōŕƥĥàńś"],
"gYz2ep": ["Ēxƥĩŕēś ĩń ", ["timeLabel"]],
+ "gbHcbI": ["Ƒàĩĺēď ţō ďēĺēţē ƥŕōƥēŕţŷ"],
"gcV0dI": ["Ţĥē ƒōĺďēŕś àńď ţēḿƥĺàţēś àŕē ĩń ƥĺàćē; ţĥēŕē'ś ńōţĥĩńĝ ĺēƒţ ţō śćàƒƒōĺď."],
"gg3Rpy": ["Ŕēśţōŕē ţĥĩś vēŕśĩōń?"],
"ggm6JX": [
@@ -1443,6 +1456,7 @@
],
"mNY1G6": ["Ũńďō àĺĺ ēďĩţś"],
"mSJ3Rn": ["Ćōḿƥũţĩńĝ śćàƒƒōĺď ƥĺàń"],
+ "mU3j1b": ["Ŕēḿōvē ĩţēḿ ", ["0"]],
"mWVJRX": ["Ćōĺĺàƥśĩƀĺē śēćţĩōń ŵĩţĥ à ćĺĩćķàƀĺē śũḿḿàŕŷ."],
"mYGY3B": ["Ďàţē"],
"mYLRjR": ["Ŷōũ ƥĩćķēď ~/Ďēśķţōƥ. Ōƥēń Ķńōŵĺēďĝē ŵĩĺĺ ĩńďēx ēvēŕŷţĥĩńĝ ōń ŷōũŕ ďēśķţōƥ."],
@@ -1616,6 +1630,7 @@
"s-MGs7": ["Ŕēśōũŕćēś"],
"s-XOaI": ["Ƒĩĺē ńàḿē"],
"s0IDhW": ["Ţĥĩś ƒĩĺē ćōũĺď ńōţ ƀē ƒōũńď."],
+ "s0J_k9": [["0", "plural", { "one": ["#", " ķēŷ"], "other": ["#", " ķēŷś"] }]],
"s1c0ja": ["ßũĺĺēţ Ĺĩśţ"],
"s3caR3": ["Ďēĺēţĩńĝ"],
"sE7R19": [
@@ -1792,8 +1807,10 @@
"yLq4w4": ["Śēƥàŕàţōŕ"],
"yMgL_E": ["Ƒĩńď ƒĩēĺď ńàvĩĝàţĩōń"],
"yQE2r9": ["Ĺōàďĩńĝ"],
+ "yUxR-Q": ["Ēxƥàńď ", ["keyName"]],
"yWWThY": ["Àśśēţ ŕēƒēŕēńćē"],
"yYR6za": ["Ďĩśƥĺàŷ ţēxţ"],
+ "y_5CE8": ["Ĩţēḿ ", ["0"]],
"yf5r22": [
["keyName"],
" ţŷƥē: ",
@@ -1853,6 +1870,7 @@
"zkz0Fg": ["Śēţ ũƥ śŷńćĩńĝ"],
"zlErBl": ["Ƥàĝē ĥēàďĩńĝś ēŕŕōŕ ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ŔƑĆ 9457"],
"zo3Dl7": ["Ţōĝĝĺē ţĥũḿƀńàĩĺś"],
+ "ztKII6": ["Ƒàĩĺēď ţō àďď ĩţēḿ"],
"zwBp5t": ["Ƥŕĩvàţē"]
}
}
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index c1147879e..f757182ab 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -41,6 +41,7 @@ msgstr ""
msgid "\"{trimmed}\" already exists here"
msgstr ""
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "\"frontmatter\" is a reserved property name"
msgstr ""
@@ -71,6 +72,10 @@ msgstr ""
msgid "(project + user)"
msgstr ""
+#: src/components/PropertyWidgets.tsx
+msgid "(read-only — edit in source mode for now)"
+msgstr ""
+
#: src/components/NewItemDialog.tsx
msgid "(root)"
msgstr ""
@@ -89,6 +94,16 @@ msgstr ""
msgid "{0, plural, one {# doc} other {# docs}}"
msgstr ""
+#. placeholder {0}: value.length
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "{0, plural, one {# item} other {# items}}"
+msgstr ""
+
+#. placeholder {0}: entries.length
+#: src/components/ObjectWidget.tsx
+msgid "{0, plural, one {# key} other {# keys}}"
+msgstr ""
+
#. placeholder {0}: blocked.length
#: src/editor/components/PreviewBlockedNotice.tsx
msgid "{0, plural, one {# request blocked by the preview's security policy} other {# requests blocked by the preview's security policy}}"
@@ -261,6 +276,10 @@ msgstr ""
msgid "{keyName} type: {typeLabel}. Click to change."
msgstr ""
+#: src/components/FrontmatterRow.tsx
+msgid "{keyName} type: complex value (nested; read-only)"
+msgstr ""
+
#: src/components/PageHeaderWidgets.tsx
#: src/components/PropertyWidgets.tsx
msgid "{keyName} value"
@@ -484,6 +503,7 @@ msgstr ""
#. Primary button that writes MCP config for the selected AI tools
#: src/components/FrontmatterRow.tsx
#: src/components/McpConsentDialogBody.tsx
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "Add"
msgstr ""
@@ -508,6 +528,14 @@ msgstr ""
msgid "Add cursors or select matching occurrences through CodeMirror."
msgstr ""
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Add item"
+msgstr ""
+
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Add item to {keyName}"
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Add meaning-based ranking to search so conceptually-related pages surface even when they share no keywords. This setting applies only to this computer."
msgstr ""
@@ -528,6 +556,10 @@ msgstr ""
msgid "Add property"
msgstr ""
+#: src/components/ObjectWidget.tsx
+msgid "Add property to {keyName}"
+msgstr ""
+
#: src/editor/components/Tabs.tsx
msgid "Add tab"
msgstr ""
@@ -1089,6 +1121,11 @@ msgstr ""
msgid "Collapse {docName}"
msgstr ""
+#: src/components/ArrayOfObjectsWidget.tsx
+#: src/components/ObjectWidget.tsx
+msgid "Collapse {keyName}"
+msgstr ""
+
#: src/components/FileSidebar.tsx
msgid "Collapse all"
msgstr ""
@@ -1846,6 +1883,11 @@ msgstr ""
msgid "Drag {patternText} to reorder"
msgstr ""
+#. placeholder {0}: index + 1
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Drag item {0} to reorder"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Duplicate"
msgstr ""
@@ -1979,6 +2021,11 @@ msgstr ""
msgid "Embeddings provider key"
msgstr ""
+#: src/components/ArrayOfObjectsWidget.tsx
+#: src/components/ObjectWidget.tsx
+msgid "empty"
+msgstr ""
+
#: src/components/PropertyWidgets.tsx
msgid "Empty"
msgstr ""
@@ -2032,6 +2079,11 @@ msgstr ""
msgid "Expand {docName}"
msgstr ""
+#: src/components/ArrayOfObjectsWidget.tsx
+#: src/components/ObjectWidget.tsx
+msgid "Expand {keyName}"
+msgstr ""
+
#: src/components/FileSidebar.tsx
msgid "Expand all"
msgstr ""
@@ -2069,6 +2121,11 @@ msgstr ""
msgid "External wiki link"
msgstr ""
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Failed to add item"
+msgstr ""
+
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "Failed to add property"
msgstr ""
@@ -2097,10 +2154,18 @@ msgstr ""
msgid "Failed to create page"
msgstr ""
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Failed to delete item"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Failed to delete path"
msgstr ""
+#: src/components/ObjectWidget.tsx
+msgid "Failed to delete property"
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Failed to disable semantic search — {detail}"
msgstr ""
@@ -2239,6 +2304,7 @@ msgstr ""
msgid "Failed to rename path"
msgstr ""
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "Failed to rename property"
msgstr ""
@@ -2247,6 +2313,12 @@ msgstr ""
msgid "Failed to render PDF"
msgstr ""
+#: src/components/ArrayOfObjectsWidget.tsx
+#: src/components/ObjectWidget.tsx
+msgid "Failed to reorder"
+msgstr ""
+
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "Failed to update property"
msgstr ""
@@ -2811,6 +2883,11 @@ msgstr ""
msgid "Italic"
msgstr ""
+#. placeholder {0}: index + 1
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Item {0}"
+msgstr ""
+
#: src/components/CreatedItemsList.tsx
msgid "Items to be created"
msgstr ""
@@ -3227,6 +3304,7 @@ msgid "Name cannot be empty"
msgstr ""
#: src/components/FolderPropertiesCard.tsx
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "Name is required"
msgstr ""
@@ -3581,6 +3659,10 @@ msgstr ""
msgid "Numbered list of items."
msgstr ""
+#: src/components/PropertyWidgets.tsx
+msgid "Object"
+msgstr ""
+
#: src/editor/components/Pdf.tsx
msgid "of {totalPages}"
msgstr ""
@@ -4221,6 +4303,7 @@ msgstr ""
msgid "Properties"
msgstr ""
+#: src/components/ObjectWidget.tsx
#: src/components/PropertyPanel.tsx
msgid "Property \"{trimmed}\" already exists"
msgstr ""
@@ -4393,6 +4476,11 @@ msgstr ""
msgid "Remove from recent projects"
msgstr ""
+#. placeholder {0}: index + 1
+#: src/components/ArrayOfObjectsWidget.tsx
+msgid "Remove item {0}"
+msgstr ""
+
#: src/editor/bubble-menu/LinkEditPopover.tsx
msgid "Remove link"
msgstr ""
diff --git a/packages/app/tests/fidelity/frontmatter-region-roundtrip.test.ts b/packages/app/tests/fidelity/frontmatter-region-roundtrip.test.ts
index d24362751..5b771db34 100644
--- a/packages/app/tests/fidelity/frontmatter-region-roundtrip.test.ts
+++ b/packages/app/tests/fidelity/frontmatter-region-roundtrip.test.ts
@@ -1,11 +1,14 @@
import { describe, expect, test } from 'bun:test';
import {
applyPatchToFm,
+ applyPathReorderToFm,
+ applyPathSetToFm,
applyRenameToFm,
applyReorderToFm,
parseFencedFmRegion,
} from '@inkeep/open-knowledge-core';
import * as fc from 'fast-check';
+import { Document as YamlDocument } from 'yaml';
const MAX_KEY_BYTES = 32;
const MAX_VALUE_BYTES = 64;
@@ -157,3 +160,188 @@ describe('frontmatter-region — round-trip invariants', () => {
expect(result.nextFenced).toContain('status: published');
});
});
+
+const scalarArbitrary = fc.oneof(stringValue, numberValue, booleanValue);
+const scalarListArbitrary = fc.array(stringValue, { minLength: 1, maxLength: 3 });
+
+function nestedMapArbitraryAtDepth(depth: number): fc.Arbitrary<Record<string, unknown>> {
+ return fc.uniqueArray(safeKey, { minLength: 1, maxLength: 3 }).chain((keys) =>
+ fc.tuple(...keys.map(() => nestedValueArbitraryAtDepth(depth))).map((values) => {
+ const map: Record<string, unknown> = {};
+ keys.forEach((k, i) => {
+ map[k] = values[i];
+ });
+ return map;
+ }),
+ );
+}
+
+function nestedValueArbitraryAtDepth(depth: number): fc.Arbitrary<unknown> {
+ if (depth <= 0) return fc.oneof(scalarArbitrary, scalarListArbitrary);
+ return fc.oneof(
+ { arbitrary: scalarArbitrary, weight: 4 },
+ { arbitrary: scalarListArbitrary, weight: 2 },
+ { arbitrary: nestedMapArbitraryAtDepth(depth - 1), weight: 2 },
+ {
+ arbitrary: fc.array(nestedMapArbitraryAtDepth(depth - 1), { minLength: 1, maxLength: 2 }),
+ weight: 1,
+ },
+ );
+}
+
+const nestedFmMapArbitrary = fc.uniqueArray(safeKey, { minLength: 1, maxLength: 4 }).chain((keys) =>
+ fc.tuple(...keys.map(() => nestedValueArbitraryAtDepth(2))).map((values) => {
+ const map: Record<string, unknown> = {};
+ keys.forEach((k, i) => {
+ map[k] = values[i];
+ });
+ return { keys, map };
+ }),
+);
+
+function buildNestedFenced(map: Record<string, unknown>): string {
+ const doc = new YamlDocument(map);
+ const body = doc.toString({ defaultKeyType: 'PLAIN', lineWidth: 0 });
+ return `---\n${body}---\n`;
+}
+
+describe('frontmatter-region — nested round-trip invariants (PRD-6947)', () => {
+ test('I-rt-7: parse → serialize → parse is fixed-point at depth (nested maps + arrays of objects)', () => {
+ fc.assert(
+ fc.property(nestedFmMapArbitrary, ({ map }) => {
+ const fenced = buildNestedFenced(map);
+ const { doc, map: parsed1 } = parseFencedFmRegion(fenced);
+ if (parsed1 === null) return;
+ const reSer = doc.toString({ defaultKeyType: 'PLAIN', lineWidth: 0 });
+ const { map: parsed2 } = parseFencedFmRegion(`---\n${reSer}---\n`);
+ expect(parsed2).toEqual(parsed1);
+ }),
+ { numRuns: 40 },
+ );
+ });
+
+ test('I-rt-8: applyPatchToFm with {} is parse-stable at depth', () => {
+ fc.assert(
+ fc.property(nestedFmMapArbitrary, ({ map }) => {
+ const fenced = buildNestedFenced(map);
+ const { map: parsedOrig } = parseFencedFmRegion(fenced);
+ if (parsedOrig === null) return;
+ const result = applyPatchToFm(fenced, {});
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ const { map: parsedNext } = parseFencedFmRegion(result.nextFenced);
+ expect(parsedNext).toEqual(parsedOrig);
+ }),
+ { numRuns: 40 },
+ );
+ });
+
+ test('I-rt-9: whole-subtree replacement is byte-stable on second application (idempotence at depth)', () => {
+ fc.assert(
+ fc.property(
+ nestedFmMapArbitrary.filter(({ keys }) => keys.length >= 1),
+ nestedValueArbitraryAtDepth(2),
+ ({ keys, map }, newValue) => {
+ const target = keys[0];
+ if (!target) return;
+ const fenced = buildNestedFenced(map);
+ const first = applyPatchToFm(fenced, { [target]: newValue as never });
+ if (!first.ok) return;
+ const second = applyPatchToFm(first.nextFenced, { [target]: newValue as never });
+ expect(second.ok).toBe(true);
+ if (!second.ok) return;
+ expect(second.nextFenced).toBe(first.nextFenced);
+ },
+ ),
+ { numRuns: 30 },
+ );
+ });
+
+ test('I-rt-10: whole-subtree replacement preserves untouched sibling top-level keys', () => {
+ fc.assert(
+ fc.property(
+ nestedFmMapArbitrary.filter(({ keys }) => keys.length >= 2),
+ nestedValueArbitraryAtDepth(2),
+ ({ keys, map }, newValue) => {
+ const target = keys[0];
+ if (!target) return;
+ const fenced = buildNestedFenced(map);
+ const result = applyPatchToFm(fenced, { [target]: newValue as never });
+ if (!result.ok) return;
+ const { map: parsedNext } = parseFencedFmRegion(result.nextFenced);
+ if (parsedNext === null) return;
+ for (const sibling of keys.slice(1)) {
+ expect(parsedNext[sibling]).toEqual(map[sibling] as never);
+ }
+ },
+ ),
+ { numRuns: 30 },
+ );
+ });
+
+ test('I-rt-11: applyPathSetToFm at a nested leaf preserves siblings at every level (Q-T9 local API)', () => {
+ fc.assert(
+ fc.property(
+ fc
+ .tuple(
+ fc.uniqueArray(safeKey, { minLength: 2, maxLength: 3 }),
+ fc.uniqueArray(safeKey, { minLength: 2, maxLength: 3 }),
+ scalarArbitrary,
+ scalarArbitrary,
+ )
+ .map(([topKeys, nestedKeys, siblingValue, leafValue]) => ({
+ topKeys,
+ nestedKeys,
+ siblingValue,
+ leafValue,
+ })),
+ ({ topKeys, nestedKeys, siblingValue, leafValue }) => {
+ const [parentKey, siblingTop] = topKeys;
+ const [targetNested, siblingNested] = nestedKeys;
+ if (!parentKey || !siblingTop || !targetNested || !siblingNested) return;
+ const nested: Record<string, unknown> = {};
+ for (const k of nestedKeys) nested[k] = siblingValue;
+ const map: Record<string, unknown> = { [parentKey]: nested, [siblingTop]: siblingValue };
+ const fenced = buildNestedFenced(map);
+ const result = applyPathSetToFm(fenced, [parentKey, targetNested], leafValue);
+ if (!result.ok) return;
+ const { map: parsedNext } = parseFencedFmRegion(result.nextFenced);
+ if (parsedNext === null) return;
+ expect(parsedNext[siblingTop]).toEqual(siblingValue);
+ const reparsedNested = parsedNext[parentKey] as Record<string, unknown>;
+ expect(reparsedNested[siblingNested]).toEqual(siblingValue);
+ expect(reparsedNested[targetNested]).toEqual(leafValue);
+ },
+ ),
+ { numRuns: 30 },
+ );
+ });
+
+ test('I-rt-12: applyPathReorderToFm with identity permutation at depth is parse-stable', () => {
+ fc.assert(
+ fc.property(
+ fc.tuple(
+ fc.uniqueArray(safeKey, { minLength: 1, maxLength: 2 }),
+ fc.uniqueArray(safeKey, { minLength: 2, maxLength: 4 }),
+ scalarArbitrary,
+ ),
+ ([topKeys, nestedKeys, value]) => {
+ const parentKey = topKeys[0];
+ if (!parentKey || nestedKeys.length < 2) return;
+ const nested: Record<string, unknown> = {};
+ for (const k of nestedKeys) nested[k] = value;
+ const map: Record<string, unknown> = { [parentKey]: nested };
+ const fenced = buildNestedFenced(map);
+ const result = applyPathReorderToFm(fenced, [parentKey], nestedKeys);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ const { map: parsedNext } = parseFencedFmRegion(result.nextFenced);
+ if (parsedNext === null) return;
+ const reparsedNested = parsedNext[parentKey] as Record<string, unknown>;
+ expect(Object.keys(reparsedNested)).toEqual(nestedKeys);
+ },
+ ),
+ { numRuns: 30 },
+ );
+ });
+});
diff --git a/packages/app/tests/integration/c12-nested-frontmatter.test.ts b/packages/app/tests/integration/c12-nested-frontmatter.test.ts
new file mode 100644
index 000000000..f2c542910
--- /dev/null
+++ b/packages/app/tests/integration/c12-nested-frontmatter.test.ts
@@ -0,0 +1,277 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { setTimeout as wait } from 'node:timers/promises';
+import {
+ bindFrontmatterDoc,
+ type FrontmatterBinding,
+ type FrontmatterDocProvider,
+ normalizeBridge,
+ prependFrontmatter,
+ readFmMap,
+ stripFrontmatter,
+} from '@inkeep/open-knowledge-core';
+import * as Y from 'yjs';
+import {
+ createTestClients,
+ createTestServer,
+ pollUntil,
+ serializeFragment,
+ type TestClient,
+ type TestServer,
+} from './test-harness';
+
+let server: TestServer;
+
+beforeAll(async () => {
+ server = await createTestServer();
+});
+
+afterAll(async () => {
+ await server.cleanup();
+});
+
+function seedSource(client: TestClient, source: string): void {
+ client.doc.transact(() => {
+ client.ytext.insert(0, source);
+ });
+}
+
+function appendParagraph(client: TestClient, text: string): void {
+ const paragraph = new Y.XmlElement('paragraph');
+ const ytext = new Y.XmlText();
+ ytext.applyDelta([{ insert: text }]);
+ paragraph.insert(0, [ytext]);
+ client.fragment.push([paragraph]);
+}
+
+function makeFmProvider(client: TestClient): FrontmatterDocProvider {
+ return {
+ document: client.doc,
+ on: (event, listener) => {
+ client.provider.on(event, listener);
+ },
+ off: (event, listener) => {
+ client.provider.off(event, listener);
+ },
+ };
+}
+
+function attachBinding(client: TestClient): { binding: FrontmatterBinding; dispose: () => void } {
+ const binding = bindFrontmatterDoc(makeFmProvider(client));
+ return {
+ binding,
+ dispose: () => binding.dispose(),
+ };
+}
+
+function assertNestedBridgeInvariant(client: TestClient): void {
+ const ytextStr = client.ytext.toString();
+ const fm = stripFrontmatter(ytextStr).frontmatter;
+ const fragBody = serializeFragment(client.fragment);
+ const reconstituted = prependFrontmatter(fm, fragBody);
+ const ytextNorm = normalizeBridge(ytextStr);
+ const fragNorm = normalizeBridge(reconstituted);
+ if (ytextNorm !== fragNorm) {
+ throw new Error(
+ `Nested bridge invariant violated.\n Y.Text: ${ytextNorm.slice(0, 400)}\n Reconstituted: ${fragNorm.slice(0, 400)}`,
+ );
+ }
+}
+
+async function assertConvergedAtDepth(
+ clients: TestClient[],
+ ytextMarkers: string[],
+): Promise<void> {
+ for (const marker of ytextMarkers) {
+ for (let i = 0; i < clients.length; i++) {
+ await pollUntil(() => clients[i].ytext.toString().includes(marker), 5000);
+ }
+ }
+ await wait(500);
+
+ const ytexts = clients.map((c) => c.ytext.toString());
+ for (let i = 1; i < ytexts.length; i++) {
+ expect(ytexts[i]).toBe(ytexts[0]);
+ }
+ const fragMds = clients.map((c) => serializeFragment(c.fragment));
+ for (let i = 1; i < fragMds.length; i++) {
+ expect(fragMds[i]).toBe(fragMds[0]);
+ }
+
+ for (const c of clients) {
+ assertNestedBridgeInvariant(c);
+ }
+}
+
+const SKILL_SHAPED_FM = [
+ '---',
+ 'name: c12-skill',
+ 'description: a sample skill',
+ 'metadata:',
+ ' version: 1.0.0',
+ ' author: original',
+ '---',
+ '# C12 Body',
+ '',
+ 'Body content for c12.',
+ '',
+].join('\n');
+
+const ARRAY_OF_OBJECTS_FM = [
+ '---',
+ 'name: c12-array',
+ 'plugins:',
+ ' - name: alpha',
+ ' version: 1',
+ ' - name: beta',
+ ' version: 2',
+ '---',
+ '# C12 array body',
+ '',
+].join('\n');
+
+describe('C12: multi-client nested frontmatter convergence', () => {
+ test('nested leaf edit on client A propagates to client B; bridge invariant holds at depth', async () => {
+ const clients = await createTestClients(server.port, {
+ count: 2,
+ perClientOptions: { skipInvariantWatcher: true },
+ });
+ try {
+ seedSource(clients[0], SKILL_SHAPED_FM);
+ await pollUntil(() => clients[1].ytext.toString().includes('version: 1.0.0'), 5000);
+ await wait(200);
+
+ const a = attachBinding(clients[0]);
+ try {
+ const result = a.binding.patchPath(['metadata', 'version'], '2.0.0');
+ expect(result.ok).toBe(true);
+ } finally {
+ a.dispose();
+ }
+
+ await assertConvergedAtDepth(clients, ['version: 2.0.0', 'author: original', '# C12 Body']);
+
+ const b = attachBinding(clients[1]);
+ try {
+ const snapshot = b.binding.current();
+ expect(snapshot.parseError).toBeUndefined();
+ expect(snapshot.map.metadata).toEqual({ version: '2.0.0', author: 'original' });
+ expect(snapshot.map.name).toBe('c12-skill');
+ } finally {
+ b.dispose();
+ }
+ } finally {
+ for (const c of clients) await c.cleanup();
+ }
+ });
+
+ test('sibling nested key edits from two clients converge under whole-subtree merge', async () => {
+ const clients = await createTestClients(server.port, {
+ count: 2,
+ perClientOptions: { skipInvariantWatcher: true },
+ });
+ try {
+ seedSource(clients[0], SKILL_SHAPED_FM);
+ await pollUntil(() => clients[1].ytext.toString().includes('version: 1.0.0'), 5000);
+ await wait(200);
+
+ const a = attachBinding(clients[0]);
+ const b = attachBinding(clients[1]);
+ try {
+ const aRes = a.binding.patchPath(['metadata', 'version'], '2.0.0');
+ expect(aRes.ok).toBe(true);
+
+ await pollUntil(() => clients[1].ytext.toString().includes('version: 2.0.0'), 5000);
+ await wait(200);
+
+ const bRes = b.binding.patchPath(['metadata', 'author'], 'Bob');
+ expect(bRes.ok).toBe(true);
+
+ await assertConvergedAtDepth(clients, ['version: 2.0.0', 'author: Bob', '# C12 Body']);
+
+ const aSnapshot = a.binding.current();
+ const bSnapshot = b.binding.current();
+ expect(aSnapshot.map.metadata).toEqual({ version: '2.0.0', author: 'Bob' });
+ expect(bSnapshot.map.metadata).toEqual({ version: '2.0.0', author: 'Bob' });
+ expect(aSnapshot.map.name).toBe('c12-skill');
+ expect(bSnapshot.map.name).toBe('c12-skill');
+ } finally {
+ a.dispose();
+ b.dispose();
+ }
+ } finally {
+ for (const c of clients) await c.cleanup();
+ }
+ });
+
+ test('body edit + nested-FM edit on two clients converge with bridge invariant at depth', async () => {
+ const clients = await createTestClients(server.port, {
+ count: 2,
+ perClientOptions: { skipInvariantWatcher: true },
+ });
+ try {
+ seedSource(clients[0], SKILL_SHAPED_FM);
+ await pollUntil(() => clients[1].ytext.toString().includes('version: 1.0.0'), 5000);
+ await wait(200);
+
+ appendParagraph(clients[0], 'C12-WYSIWYG-FROM-A');
+
+ const b = attachBinding(clients[1]);
+ try {
+ const res = b.binding.patchPath(['metadata', 'version'], '3.0.0');
+ expect(res.ok).toBe(true);
+ } finally {
+ b.dispose();
+ }
+
+ await assertConvergedAtDepth(clients, [
+ 'version: 3.0.0',
+ 'author: original',
+ '# C12 Body',
+ 'C12-WYSIWYG-FROM-A',
+ ]);
+
+ const fragMd = serializeFragment(clients[0].fragment);
+ expect(fragMd).toContain('C12-WYSIWYG-FROM-A');
+ } finally {
+ for (const c of clients) await c.cleanup();
+ }
+ });
+
+ test('array-of-objects item append on client A propagates and converges at depth', async () => {
+ const clients = await createTestClients(server.port, {
+ count: 2,
+ perClientOptions: { skipInvariantWatcher: true },
+ });
+ try {
+ seedSource(clients[0], ARRAY_OF_OBJECTS_FM);
+ await pollUntil(() => clients[1].ytext.toString().includes('name: beta'), 5000);
+ await wait(200);
+
+ const a = attachBinding(clients[0]);
+ try {
+ const seeded = a.binding.current();
+ const plugins = seeded.map.plugins;
+ expect(Array.isArray(plugins)).toBe(true);
+ const length = (plugins as unknown[]).length;
+ expect(length).toBe(2);
+
+ const result = a.binding.patchPath(['plugins', length], {
+ name: 'gamma',
+ version: 3,
+ });
+ expect(result.ok).toBe(true);
+ } finally {
+ a.dispose();
+ }
+
+ await assertConvergedAtDepth(clients, ['name: gamma', 'name: alpha', 'name: beta']);
+
+ const map = readFmMap(clients[1].ytext.toString());
+ const plugins = map.plugins as Array<{ name: string; version: number }>;
+ expect(plugins).toHaveLength(3);
+ expect(plugins[2]).toEqual({ name: 'gamma', version: 3 });
+ } finally {
+ for (const c of clients) await c.cleanup();
+ }
+ });
+});
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.test.ts b/packages/core/src/bridge/bind-frontmatter-doc.test.ts
index 73035b081..cf84cab12 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.test.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.test.ts
@@ -95,7 +95,7 @@ describe('bindFrontmatterDoc — patch()', () => {
const binding = bindFrontmatterDoc(provider);
binding.patch({ title: 'Hello' });
- const result = binding.patch({ count: { nested: true } as unknown as number });
+ const result = binding.patch({ count: Symbol('nope') as unknown as number });
expect(result.ok).toBe(false);
if (!result.ok) {
@@ -104,6 +104,23 @@ describe('bindFrontmatterDoc — patch()', () => {
expect(readFmMap(provider.document.getText('source').toString())).toEqual({ title: 'Hello' });
});
+ test('nested object value is accepted and round-trips through Y.Text', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+
+ const result = binding.patch({
+ name: 'skill',
+ metadata: { version: '1.0.0', author: 'Inkeep' },
+ });
+
+ expect(result.ok).toBe(true);
+ const map = readFmMap(provider.document.getText('source').toString());
+ expect(map).toEqual({
+ name: 'skill',
+ metadata: { version: '1.0.0', author: 'Inkeep' },
+ });
+ });
+
test('reserved key "frontmatter" is rejected', () => {
const provider = makeProvider();
const binding = bindFrontmatterDoc(provider);
@@ -238,6 +255,396 @@ describe('bindFrontmatterDoc — reorder()', () => {
});
});
+describe('bindFrontmatterDoc — patchPath() / deletePath() (Q-T9 local addressing)', () => {
+ test('patchPath sets a nested leaf, preserving sibling top-level keys', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({
+ name: 'skill',
+ description: 'd',
+ metadata: { version: '1.0', author: 'Inkeep' },
+ });
+
+ const result = binding.patchPath(['metadata', 'version'], '2.0');
+
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.path).toEqual(['metadata', 'version']);
+ }
+ expect(binding.current().map).toEqual({
+ name: 'skill',
+ description: 'd',
+ metadata: { version: '2.0', author: 'Inkeep' },
+ });
+ });
+
+ test('patchPath preserves sibling nested keys at the same depth (single-leaf set)', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({
+ metadata: { version: '1.0', author: 'A', license: 'MIT' },
+ });
+
+ const result = binding.patchPath(['metadata', 'version'], '2.0');
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({
+ metadata: { version: '2.0', author: 'A', license: 'MIT' },
+ });
+ });
+
+ test('patchPath creates missing intermediate maps', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ name: 'skill' });
+
+ const result = binding.patchPath(['metadata', 'version'], '1.0');
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({
+ name: 'skill',
+ metadata: { version: '1.0' },
+ });
+ });
+
+ test('patchPath at depth >=3 creates parent chain', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+
+ const result = binding.patchPath(['a', 'b', 'c', 'd'], 'leaf');
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({
+ a: { b: { c: { d: 'leaf' } } },
+ });
+ });
+
+ test('patchPath single-element path reduces to a top-level set (append on new key)', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ title: 'Hello' });
+
+ const result = binding.patchPath(['cluster'], 'X');
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({ title: 'Hello', cluster: 'X' });
+ expect(binding.current().keys).toEqual(['title', 'cluster']);
+ });
+
+ test('patchPath single-element path updates in place (no reorder on update)', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ title: 'Hello', cluster: 'X' });
+
+ binding.patchPath(['title'], 'World');
+
+ expect(binding.current().keys).toEqual(['title', 'cluster']);
+ expect(binding.current().map.title).toBe('World');
+ });
+
+ test('patchPath sets an array leaf value', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ name: 'doc' });
+
+ const result = binding.patchPath(['tags'], ['alpha', 'beta']);
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({ name: 'doc', tags: ['alpha', 'beta'] });
+ });
+
+ test('patchPath sets nested object leaf value (whole-subtree replace at leaf)', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ metadata: { version: '1.0', author: 'A' } });
+
+ const result = binding.patchPath(['metadata'], { version: '2.0' });
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({ metadata: { version: '2.0' } });
+ });
+
+ test('patchPath into an existing seq item by index', () => {
+ const provider = makeProvider('---\nauthors:\n - name: A\n - name: B\n---\n');
+ const binding = bindFrontmatterDoc(provider);
+
+ const result = binding.patchPath(['authors', 0, 'role'], 'lead');
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({
+ authors: [{ name: 'A', role: 'lead' }, { name: 'B' }],
+ });
+ });
+
+ test('patchPath through a scalar intermediate returns parse_failed (WRITE_ERROR)', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ a: 'string-value' });
+
+ const result = binding.patchPath(['a', 'b'], 'x');
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.error.code).toBe('WRITE_ERROR');
+ }
+ expect(binding.current().map).toEqual({ a: 'string-value' });
+ });
+
+ test('patchPath empty path is rejected with SCHEMA_INVALID / invalid_path', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+
+ const result = binding.patchPath([], 'x');
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.error.code).toBe('SCHEMA_INVALID');
+ if (result.error.code === 'SCHEMA_INVALID') {
+ expect(result.error.issues[0]?.issueCode).toBe('invalid_path');
+ }
+ }
+ });
+
+ test('patchPath rejects reserved top-level key "frontmatter"', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+
+ const result = binding.patchPath(['frontmatter', 'nested'], 'x');
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.error.code).toBe('SCHEMA_INVALID');
+ if (result.error.code === 'SCHEMA_INVALID') {
+ expect(result.error.issues[0]?.issueCode).toBe('reserved_key');
+ }
+ }
+ });
+
+ test('patchPath admits nested "frontmatter" key (only top-level slot is reserved)', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+
+ const result = binding.patchPath(['metadata', 'frontmatter'], 'allowed');
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({ metadata: { frontmatter: 'allowed' } });
+ });
+
+ test('patchPath invalid leaf value (Symbol) returns SCHEMA_INVALID without mutating Y.Text', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ metadata: { version: '1.0' } });
+
+ const result = binding.patchPath(['metadata', 'count'], Symbol('nope') as unknown as number);
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.error.code).toBe('SCHEMA_INVALID');
+ }
+ expect(binding.current().map).toEqual({ metadata: { version: '1.0' } });
+ });
+
+ test('patchPath stamps writes with FORM_WRITE_ORIGIN', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+
+ let observedOrigin: unknown = null;
+ provider.document.getText('source').observe((_event, transaction) => {
+ observedOrigin = transaction.origin;
+ });
+
+ binding.patchPath(['metadata', 'version'], '1.0');
+
+ expect(observedOrigin).toBe(FORM_WRITE_ORIGIN);
+ });
+
+ test('patchPath preserves flow style on nested map subtree replace', () => {
+ const provider = makeProvider('---\nmetadata: {version: 1.0, author: A}\n---\n');
+ const binding = bindFrontmatterDoc(provider);
+
+ const result = binding.patchPath(['metadata'], { version: '2.0', author: 'B' });
+
+ expect(result.ok).toBe(true);
+ const fenced = readYTextFm(provider);
+ expect(fenced).toContain('{ version: "2.0"');
+ expect(fenced).toContain('author: B }');
+ });
+
+ test('patchPath preserves sibling comments inside the nested map (single-leaf set)', () => {
+ const provider = makeProvider(
+ '---\nname: hello\nmetadata:\n # version comment\n version: 1.0\n author: A\n---\n',
+ );
+ const binding = bindFrontmatterDoc(provider);
+
+ const result = binding.patchPath(['metadata', 'author'], 'B');
+
+ expect(result.ok).toBe(true);
+ const fenced = readYTextFm(provider);
+ expect(fenced).toContain('# version comment');
+ expect(fenced).toContain('version: 1.0');
+ expect(fenced).toContain('author: B');
+ });
+
+ test('patchPath disposed binding returns WRITE_ERROR', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.dispose();
+
+ const result = binding.patchPath(['metadata', 'version'], '1.0');
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.error.code).toBe('WRITE_ERROR');
+ }
+ });
+
+ test('deletePath removes a single nested leaf, leaves sibling siblings + parent map', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({
+ name: 'skill',
+ metadata: { version: '1.0', author: 'A', license: 'MIT' },
+ });
+
+ const result = binding.deletePath(['metadata', 'author']);
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({
+ name: 'skill',
+ metadata: { version: '1.0', license: 'MIT' },
+ });
+ });
+
+ test('deletePath does NOT prune emptied parent maps (documented rule)', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ metadata: { version: '1.0' } });
+
+ const result = binding.deletePath(['metadata', 'version']);
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({ metadata: {} });
+ });
+
+ test('deletePath single-element path removes a top-level key', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ title: 'Hello', cluster: 'X' });
+
+ const result = binding.deletePath(['cluster']);
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({ title: 'Hello' });
+ expect(binding.current().keys).toEqual(['title']);
+ });
+
+ test('deletePath on absent leaf is an idempotent no-op (Result.ok)', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ metadata: { version: '1.0' } });
+
+ const result = binding.deletePath(['metadata', 'absent']);
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({ metadata: { version: '1.0' } });
+ });
+
+ test('deletePath through a scalar intermediate is an idempotent no-op (getIn returns undefined)', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ a: 'string-value' });
+
+ const result = binding.deletePath(['a', 'b']);
+
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({ a: 'string-value' });
+ });
+
+ test('deletePath empty path is rejected with SCHEMA_INVALID', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+
+ const result = binding.deletePath([]);
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.error.code).toBe('SCHEMA_INVALID');
+ }
+ });
+
+ test('deletePath rejects reserved top-level key "frontmatter"', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+
+ const result = binding.deletePath(['frontmatter']);
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.error.code).toBe('SCHEMA_INVALID');
+ if (result.error.code === 'SCHEMA_INVALID') {
+ expect(result.error.issues[0]?.issueCode).toBe('reserved_key');
+ }
+ }
+ });
+
+ test('deletePath stamps writes with FORM_WRITE_ORIGIN', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ metadata: { version: '1.0' } });
+
+ let observedOrigin: unknown = null;
+ provider.document.getText('source').observe((_event, transaction) => {
+ observedOrigin = transaction.origin;
+ });
+
+ binding.deletePath(['metadata', 'version']);
+
+ expect(observedOrigin).toBe(FORM_WRITE_ORIGIN);
+ });
+
+ test('deletePath disposed binding returns WRITE_ERROR', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.dispose();
+
+ const result = binding.deletePath(['metadata', 'version']);
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.error.code).toBe('WRITE_ERROR');
+ }
+ });
+
+ test('patchPath then deletePath round-trip leaves an empty parent map (not pruned)', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+
+ binding.patchPath(['metadata', 'version'], '1.0');
+ expect(binding.current().map).toEqual({ metadata: { version: '1.0' } });
+
+ binding.deletePath(['metadata', 'version']);
+ expect(binding.current().map).toEqual({ metadata: {} });
+
+ binding.deletePath(['metadata']);
+ expect(binding.current().map).toEqual({});
+ });
+
+ test('patchPath updates do NOT touch siblings or trailing comments (depth-2 leaf set)', () => {
+ const provider = makeProvider(
+ '---\nname: hello\nmetadata:\n version: 1.0\n author: A\n# trailing\n---\nbody\n',
+ );
+ const binding = bindFrontmatterDoc(provider);
+
+ binding.patchPath(['metadata', 'version'], '2.0');
+
+ const fenced = readYTextFm(provider);
+ expect(fenced).toContain('# trailing');
+ expect(fenced).toContain('author: A');
+ expect(fenced).toContain('version: "2.0"');
+ expect(fenced).toContain('name: hello');
+ });
+});
+
describe('bindFrontmatterDoc — current()', () => {
test('returns empty snapshot when there is no FM region', () => {
const provider = makeProvider();
@@ -312,6 +719,23 @@ describe('bindFrontmatterDoc — subscribe()', () => {
expect(calls).toBe(callsBefore);
});
+ test('content-equality bailout: body-only edits do not fire with NESTED frontmatter', () => {
+ const provider = makeProvider(
+ '---\nname: skill\nmetadata:\n version: 1.0.0\n author: Inkeep\n---\nbody\n',
+ );
+ const binding = bindFrontmatterDoc(provider);
+ let calls = 0;
+ binding.subscribe(() => {
+ calls += 1;
+ });
+ const callsBefore = calls;
+
+ const ytext = provider.document.getText('source');
+ ytext.insert(ytext.length, '\nmore body\n');
+
+ expect(calls).toBe(callsBefore);
+ });
+
test('listener fires on provider synced', () => {
const provider = makeProvider();
const binding = bindFrontmatterDoc(provider);
@@ -549,6 +973,360 @@ describe('bindFrontmatterDoc — no-FM body-edit perf bailout', () => {
});
});
+describe('bindFrontmatterDoc — renamePath()', () => {
+ function seedNested(): {
+ provider: ReturnType<typeof makeProvider>;
+ binding: ReturnType<typeof bindFrontmatterDoc>;
+ } {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({
+ name: 'skill',
+ metadata: { version: '1.0.0', author: 'Inkeep', license: 'MIT' },
+ });
+ return { provider, binding };
+ }
+
+ test('renames a nested key preserving sibling nested keys + top-level keys', () => {
+ const { provider, binding } = seedNested();
+ const result = binding.renamePath(['metadata', 'version'], 'semver');
+ expect(result.ok).toBe(true);
+ const fenced = readYTextFm(provider);
+ expect(fenced).toContain('semver: 1.0.0');
+ expect(fenced).toContain('author: Inkeep');
+ expect(fenced).toContain('license: MIT');
+ expect(fenced).toContain('name: skill');
+ expect(fenced).not.toContain('version: 1.0.0');
+ binding.dispose();
+ });
+
+ test('single-element path renames a top-level key (matches rename())', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ name: 'skill', description: 'hello' });
+
+ const result = binding.renamePath(['name'], 'title');
+ expect(result.ok).toBe(true);
+ expect(readFmMap(provider.document.getText('source').toString())).toEqual({
+ title: 'skill',
+ description: 'hello',
+ });
+ binding.dispose();
+ });
+
+ test('preserves nested source position so siblings keep their order', () => {
+ const { provider, binding } = seedNested();
+ binding.renamePath(['metadata', 'author'], 'maintainer');
+ const fenced = readYTextFm(provider);
+ const versionIdx = fenced.indexOf('version:');
+ const maintainerIdx = fenced.indexOf('maintainer:');
+ const licenseIdx = fenced.indexOf('license:');
+ expect(versionIdx).toBeLessThan(maintainerIdx);
+ expect(maintainerIdx).toBeLessThan(licenseIdx);
+ binding.dispose();
+ });
+
+ test('unknown nested key returns SCHEMA_INVALID with unknown_key', () => {
+ const { binding } = seedNested();
+ const result = binding.renamePath(['metadata', 'missing'], 'x');
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('SCHEMA_INVALID');
+ if (result.error.code === 'SCHEMA_INVALID') {
+ expect(result.error.issues[0]?.issueCode).toBe('unknown_key');
+ }
+ binding.dispose();
+ });
+
+ test('nested target collision returns SCHEMA_INVALID with duplicate_target', () => {
+ const { binding } = seedNested();
+ const result = binding.renamePath(['metadata', 'version'], 'author');
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('SCHEMA_INVALID');
+ if (result.error.code === 'SCHEMA_INVALID') {
+ expect(result.error.issues[0]?.issueCode).toBe('duplicate_target');
+ }
+ binding.dispose();
+ });
+
+ test('allowDuplicate admits a nested colliding rename', () => {
+ const { binding } = seedNested();
+ const result = binding.renamePath(['metadata', 'version'], 'author', {
+ allowDuplicate: true,
+ });
+ expect(result.ok).toBe(true);
+ binding.dispose();
+ });
+
+ test('rejects numeric last segment (sequence index) as invalid_path', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ items: ['a', 'b'] });
+
+ const result = binding.renamePath(['items', 0], 'x');
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('SCHEMA_INVALID');
+ if (result.error.code === 'SCHEMA_INVALID') {
+ expect(result.error.issues[0]?.issueCode).toBe('invalid_path');
+ }
+ binding.dispose();
+ });
+
+ test('empty path rejected with invalid_path', () => {
+ const { binding } = seedNested();
+ const result = binding.renamePath([], 'x');
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('SCHEMA_INVALID');
+ binding.dispose();
+ });
+
+ test('top-level rename to reserved frontmatter key rejected', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ name: 'skill' });
+
+ const result = binding.renamePath(['name'], 'frontmatter');
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('SCHEMA_INVALID');
+ if (result.error.code === 'SCHEMA_INVALID') {
+ expect(result.error.issues[0]?.issueCode).toBe('reserved_key');
+ }
+ binding.dispose();
+ });
+
+ test('writes are stamped with FORM_WRITE_ORIGIN', () => {
+ const { provider, binding } = seedNested();
+
+ let observedOrigin: unknown = null;
+ provider.document.getText('source').observe((_event, transaction) => {
+ observedOrigin = transaction.origin;
+ });
+
+ binding.renamePath(['metadata', 'version'], 'semver');
+ expect(observedOrigin).toBe(FORM_WRITE_ORIGIN);
+ binding.dispose();
+ });
+
+ test('disposed binding rejects further renamePath calls', () => {
+ const { binding } = seedNested();
+ binding.dispose();
+
+ const result = binding.renamePath(['metadata', 'version'], 'semver');
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('WRITE_ERROR');
+ });
+});
+
+describe('bindFrontmatterDoc — reorderPath()', () => {
+ function seedNested(): {
+ provider: ReturnType<typeof makeProvider>;
+ binding: ReturnType<typeof bindFrontmatterDoc>;
+ } {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({
+ name: 'skill',
+ metadata: { version: '1.0.0', author: 'Inkeep', license: 'MIT' },
+ });
+ return { provider, binding };
+ }
+
+ test('reorders nested children preserving sibling top-level keys', () => {
+ const { provider, binding } = seedNested();
+ const result = binding.reorderPath(['metadata'], ['license', 'author', 'version']);
+ expect(result.ok).toBe(true);
+ const fenced = readYTextFm(provider);
+ const licenseIdx = fenced.indexOf('license:');
+ const authorIdx = fenced.indexOf('author:');
+ const versionIdx = fenced.indexOf('version:');
+ expect(licenseIdx).toBeLessThan(authorIdx);
+ expect(authorIdx).toBeLessThan(versionIdx);
+ expect(fenced).toContain('name: skill');
+ binding.dispose();
+ });
+
+ test('empty path reorders top-level keys (matches reorder())', () => {
+ const { provider, binding } = seedNested();
+ const result = binding.reorderPath([], ['metadata', 'name']);
+ expect(result.ok).toBe(true);
+ const fenced = readYTextFm(provider);
+ const metaIdx = fenced.indexOf('metadata:');
+ const nameIdx = fenced.indexOf('name:');
+ expect(metaIdx).toBeLessThan(nameIdx);
+ binding.dispose();
+ });
+
+ test('rejects non-permutation with WRITE_ERROR (reorder_mismatch)', () => {
+ const { binding } = seedNested();
+ const result = binding.reorderPath(['metadata'], ['version', 'missing']);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('WRITE_ERROR');
+ binding.dispose();
+ });
+
+ test('rejects when target is not a map (e.g. scalar leaf)', () => {
+ const { binding } = seedNested();
+ const result = binding.reorderPath(['name'], ['x']);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('SCHEMA_INVALID');
+ binding.dispose();
+ });
+
+ test('writes are stamped with FORM_WRITE_ORIGIN', () => {
+ const { provider, binding } = seedNested();
+
+ let observedOrigin: unknown = null;
+ provider.document.getText('source').observe((_event, transaction) => {
+ observedOrigin = transaction.origin;
+ });
+
+ binding.reorderPath(['metadata'], ['author', 'version', 'license']);
+ expect(observedOrigin).toBe(FORM_WRITE_ORIGIN);
+ binding.dispose();
+ });
+
+ test('disposed binding rejects further reorderPath calls', () => {
+ const { binding } = seedNested();
+ binding.dispose();
+
+ const result = binding.reorderPath(['metadata'], ['version', 'author', 'license']);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('WRITE_ERROR');
+ });
+});
+
+describe('bindFrontmatterDoc — reorderSeqPath()', () => {
+ function seedAuthors(): {
+ provider: ReturnType<typeof makeProvider>;
+ binding: ReturnType<typeof bindFrontmatterDoc>;
+ } {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({
+ title: 'doc',
+ authors: [
+ { name: 'A', role: 'lead' },
+ { name: 'B', role: 'review' },
+ { name: 'C', role: 'author' },
+ ],
+ });
+ return { provider, binding };
+ }
+
+ test('permutes sequence items at path; sibling top-level keys survive', () => {
+ const { binding } = seedAuthors();
+ const result = binding.reorderSeqPath(['authors'], [2, 0, 1]);
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({
+ title: 'doc',
+ authors: [
+ { name: 'C', role: 'author' },
+ { name: 'A', role: 'lead' },
+ { name: 'B', role: 'review' },
+ ],
+ });
+ binding.dispose();
+ });
+
+ test('rejects non-permutation as WRITE_ERROR (reorder_mismatch)', () => {
+ const { binding } = seedAuthors();
+ const result = binding.reorderSeqPath(['authors'], [0, 1]);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('WRITE_ERROR');
+ binding.dispose();
+ });
+
+ test('rejects when target is not a sequence (map at path)', () => {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ metadata: { version: '1.0', author: 'X' } });
+ const result = binding.reorderSeqPath(['metadata'], [0, 1]);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('SCHEMA_INVALID');
+ binding.dispose();
+ });
+
+ test('writes are stamped with FORM_WRITE_ORIGIN', () => {
+ const { provider, binding } = seedAuthors();
+ let observedOrigin: unknown = null;
+ provider.document.getText('source').observe((_event, transaction) => {
+ observedOrigin = transaction.origin;
+ });
+ binding.reorderSeqPath(['authors'], [2, 1, 0]);
+ expect(observedOrigin).toBe(FORM_WRITE_ORIGIN);
+ binding.dispose();
+ });
+
+ test('identity permutation is a no-op without Y.Text mutation', () => {
+ const { provider, binding } = seedAuthors();
+ const before = provider.document.getText('source').toString();
+ const result = binding.reorderSeqPath(['authors'], [0, 1, 2]);
+ expect(result.ok).toBe(true);
+ const after = provider.document.getText('source').toString();
+ expect(after).toBe(before);
+ binding.dispose();
+ });
+
+ test('disposed binding rejects further reorderSeqPath calls', () => {
+ const { binding } = seedAuthors();
+ binding.dispose();
+ const result = binding.reorderSeqPath(['authors'], [2, 0, 1]);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.code).toBe('WRITE_ERROR');
+ });
+});
+
+describe('bindFrontmatterDoc — array-of-objects item CRUD via patchPath/deletePath', () => {
+ function seedAuthors(): {
+ provider: ReturnType<typeof makeProvider>;
+ binding: ReturnType<typeof bindFrontmatterDoc>;
+ } {
+ const provider = makeProvider();
+ const binding = bindFrontmatterDoc(provider);
+ binding.patch({ authors: [{ name: 'A' }, { name: 'B' }] });
+ return { provider, binding };
+ }
+
+ test('add item appends a new empty object at end via patchPath at index = length', () => {
+ const { binding } = seedAuthors();
+ const result = binding.patchPath(['authors', 2], {});
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({
+ authors: [{ name: 'A' }, { name: 'B' }, {}],
+ });
+ binding.dispose();
+ });
+
+ test('delete item splices the sequence (length decreases)', () => {
+ const { binding } = seedAuthors();
+ const result = binding.deletePath(['authors', 0]);
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({ authors: [{ name: 'B' }] });
+ binding.dispose();
+ });
+
+ test('edit a field within an item leaves siblings intact', () => {
+ const { binding } = seedAuthors();
+ const result = binding.patchPath(['authors', 1, 'role'], 'editor');
+ expect(result.ok).toBe(true);
+ expect(binding.current().map).toEqual({
+ authors: [{ name: 'A' }, { name: 'B', role: 'editor' }],
+ });
+ binding.dispose();
+ });
+});
+
describe('bindFrontmatterDoc — multi-client convergence', () => {
test('two clients editing different keys (with shared baseline) converge via Y.Text', () => {
const providerA = makeProvider();
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index edf6653de..ac20bc4a1 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -5,9 +5,17 @@ import {
type FrontmatterMap,
type FrontmatterPatch,
FrontmatterPatchSchema,
+ type FrontmatterValue,
+ frontmatterValuesEqual,
+ RESERVED_FRONTMATTER_KEY,
} from '../frontmatter/schema.ts';
import {
applyPatchToFm,
+ applyPathDeleteToFm,
+ applyPathRenameToFm,
+ applyPathReorderSeqToFm,
+ applyPathReorderToFm,
+ applyPathSetToFm,
applyRenameToFm,
applyReorderToFm,
detectFmRegion,
@@ -24,8 +32,6 @@ export const FORM_WRITE_ORIGIN = Object.freeze({
context: Object.freeze({ origin: 'form-write' as const }),
});
-const RESERVED_FRONTMATTER_KEY = 'frontmatter';
-
export interface FrontmatterDocProvider {
document: Y.Doc;
/** Subscribe to provider events. We only use `'synced'` for the
@@ -62,6 +68,15 @@ export type FrontmatterBindingReorderResult = Result<
FrontmatterValidationError
>;
+export interface FrontmatterBindingPathSuccess {
+ path: ReadonlyArray<string | number>;
+}
+
+export type FrontmatterBindingPathResult = Result<
+ FrontmatterBindingPathSuccess,
+ FrontmatterValidationError
+>;
+
export type Unsubscribe = () => void;
export interface FrontmatterSnapshot {
@@ -79,6 +94,24 @@ export interface FrontmatterBinding {
options?: { allowDuplicate?: boolean },
): FrontmatterBindingRenameResult;
reorder(orderedKeys: readonly string[]): FrontmatterBindingReorderResult;
+ patchPath(
+ path: ReadonlyArray<string | number>,
+ value: FrontmatterValue,
+ ): FrontmatterBindingPathResult;
+ deletePath(path: ReadonlyArray<string | number>): FrontmatterBindingPathResult;
+ renamePath(
+ path: ReadonlyArray<string | number>,
+ newKey: string,
+ options?: { allowDuplicate?: boolean },
+ ): FrontmatterBindingPathResult;
+ reorderPath(
+ path: ReadonlyArray<string | number>,
+ orderedKeys: readonly string[],
+ ): FrontmatterBindingPathResult;
+ reorderSeqPath(
+ path: ReadonlyArray<string | number>,
+ oldIndicesInNewOrder: readonly number[],
+ ): FrontmatterBindingPathResult;
subscribe(listener: (snapshot: FrontmatterSnapshot) => void): Unsubscribe;
dispose(): void;
}
@@ -99,6 +132,10 @@ function okReorder(value: FrontmatterBindingReorderSuccess): Ok<FrontmatterBindi
return { ok: true, ...value };
}
+function okPath(value: FrontmatterBindingPathSuccess): Ok<FrontmatterBindingPathSuccess> {
+ return { ok: true, ...value };
+}
+
function fmEditErrorToValidation(e: FmEditError): FrontmatterValidationError {
switch (e.kind) {
case 'unknown_key':
@@ -154,6 +191,17 @@ function fmEditErrorToValidation(e: FmEditError): FrontmatterValidationError {
code: 'WRITE_ERROR',
detail: `Frontmatter YAML is malformed; fix in source mode to commit (${e.reason})`,
};
+ case 'invalid_path':
+ return {
+ code: 'SCHEMA_INVALID',
+ issues: [
+ {
+ path: [...e.path],
+ message: e.reason,
+ issueCode: 'invalid_path',
+ },
+ ],
+ };
}
}
@@ -169,16 +217,6 @@ function snapshotsEqual(a: FrontmatterSnapshot, b: FrontmatterSnapshot): boolean
return true;
}
-function frontmatterValuesEqual(a: unknown, b: unknown): boolean {
- if (a === b) return true;
- if (Array.isArray(a) && Array.isArray(b)) {
- if (a.length !== b.length) return false;
- for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
- return true;
- }
- return false;
-}
-
const FM_OPEN_FENCE_MIN_BYTES = 5;
function readSnapshotFromYText(ytext: Y.Text): { snapshot: FrontmatterSnapshot; raw: string } {
@@ -337,6 +375,80 @@ export function bindFrontmatterDoc(provider: FrontmatterDocProvider): Frontmatte
return okReorder({ orderedKeys: [...orderedKeys] });
}
+ function patchPathInner(
+ path: ReadonlyArray<string | number>,
+ value: FrontmatterValue,
+ ): FrontmatterBindingPathResult {
+ if (disposed) {
+ return err({ code: 'WRITE_ERROR', detail: 'FrontmatterBinding has been disposed' });
+ }
+ const result = commitFmEdit((currentFenced) => applyPathSetToFm(currentFenced, path, value));
+ if (!result.ok) {
+ return err(fmEditErrorToValidation(result.error));
+ }
+ return okPath({ path: [...path] });
+ }
+
+ function deletePathInner(path: ReadonlyArray<string | number>): FrontmatterBindingPathResult {
+ if (disposed) {
+ return err({ code: 'WRITE_ERROR', detail: 'FrontmatterBinding has been disposed' });
+ }
+ const result = commitFmEdit((currentFenced) => applyPathDeleteToFm(currentFenced, path));
+ if (!result.ok) {
+ return err(fmEditErrorToValidation(result.error));
+ }
+ return okPath({ path: [...path] });
+ }
+
+ function renamePathInner(
+ path: ReadonlyArray<string | number>,
+ newKey: string,
+ options: { allowDuplicate?: boolean } = {},
+ ): FrontmatterBindingPathResult {
+ if (disposed) {
+ return err({ code: 'WRITE_ERROR', detail: 'FrontmatterBinding has been disposed' });
+ }
+ const result = commitFmEdit((currentFenced) =>
+ applyPathRenameToFm(currentFenced, path, newKey, options),
+ );
+ if (!result.ok) {
+ return err(fmEditErrorToValidation(result.error));
+ }
+ return okPath({ path: [...path] });
+ }
+
+ function reorderPathInner(
+ path: ReadonlyArray<string | number>,
+ orderedKeys: readonly string[],
+ ): FrontmatterBindingPathResult {
+ if (disposed) {
+ return err({ code: 'WRITE_ERROR', detail: 'FrontmatterBinding has been disposed' });
+ }
+ const result = commitFmEdit((currentFenced) =>
+ applyPathReorderToFm(currentFenced, path, orderedKeys),
+ );
+ if (!result.ok) {
+ return err(fmEditErrorToValidation(result.error));
+ }
+ return okPath({ path: [...path] });
+ }
+
+ function reorderSeqPathInner(
+ path: ReadonlyArray<string | number>,
+ oldIndicesInNewOrder: readonly number[],
+ ): FrontmatterBindingPathResult {
+ if (disposed) {
+ return err({ code: 'WRITE_ERROR', detail: 'FrontmatterBinding has been disposed' });
+ }
+ const result = commitFmEdit((currentFenced) =>
+ applyPathReorderSeqToFm(currentFenced, path, oldIndicesInNewOrder),
+ );
+ if (!result.ok) {
+ return err(fmEditErrorToValidation(result.error));
+ }
+ return okPath({ path: [...path] });
+ }
+
return {
current(): FrontmatterSnapshot {
return readSnapshotFromYText(ytext).snapshot;
@@ -358,6 +470,39 @@ export function bindFrontmatterDoc(provider: FrontmatterDocProvider): Frontmatte
return reorderInner(orderedKeys);
},
+ patchPath(
+ path: ReadonlyArray<string | number>,
+ value: FrontmatterValue,
+ ): FrontmatterBindingPathResult {
+ return patchPathInner(path, value);
+ },
+
+ deletePath(path: ReadonlyArray<string | number>): FrontmatterBindingPathResult {
+ return deletePathInner(path);
+ },
+
+ renamePath(
+ path: ReadonlyArray<string | number>,
+ newKey: string,
+ options?: { allowDuplicate?: boolean },
+ ): FrontmatterBindingPathResult {
+ return renamePathInner(path, newKey, options);
+ },
+
+ reorderPath(
+ path: ReadonlyArray<string | number>,
+ orderedKeys: readonly string[],
+ ): FrontmatterBindingPathResult {
+ return reorderPathInner(path, orderedKeys);
+ },
+
+ reorderSeqPath(
+ path: ReadonlyArray<string | number>,
+ oldIndicesInNewOrder: readonly number[],
+ ): FrontmatterBindingPathResult {
+ return reorderSeqPathInner(path, oldIndicesInNewOrder);
+ },
+
subscribe(listener: (snapshot: FrontmatterSnapshot) => void): Unsubscribe {
listeners.add(listener);
return () => {
diff --git a/packages/core/src/bridge/frontmatter-region.test.ts b/packages/core/src/bridge/frontmatter-region.test.ts
index e1f8b2125..502f0ce98 100644
--- a/packages/core/src/bridge/frontmatter-region.test.ts
+++ b/packages/core/src/bridge/frontmatter-region.test.ts
@@ -1,5 +1,13 @@
import { describe, expect, test } from 'bun:test';
-import { applyPatchToFm, parseFmRegion } from './frontmatter-region.ts';
+import {
+ applyPatchToFm,
+ applyPathDeleteToFm,
+ applyPathRenameToFm,
+ applyPathReorderSeqToFm,
+ applyPathReorderToFm,
+ applyPathSetToFm,
+ parseFmRegion,
+} from './frontmatter-region.ts';
describe('parseFmRegion — mixed-scalar array coercion', () => {
test('flow array with integer element coerces to string and surfaces no parseError', () => {
@@ -67,6 +75,44 @@ describe('parseFmRegion — mixed-scalar array coercion', () => {
});
});
+describe('parseFmRegion — recursive value contract (nested objects + arrays of objects)', () => {
+ test('nested mapping parses into a populated map with no parseError', () => {
+ const yaml = 'name: skill\nmetadata:\n version: 1.0.0\n author: Inkeep\n';
+ const result = parseFmRegion(yaml);
+ expect(result.parseError).toBeUndefined();
+ expect(result.map).toEqual({
+ name: 'skill',
+ metadata: { version: '1.0.0', author: 'Inkeep' },
+ });
+ });
+
+ test('array-of-objects parses without parseError; object elements are not String-coerced', () => {
+ const yaml = 'items:\n - title: a\n - title: b\n';
+ const result = parseFmRegion(yaml);
+ expect(result.parseError).toBeUndefined();
+ expect(result.map?.items).toEqual([{ title: 'a' }, { title: 'b' }]);
+ });
+
+ test('arbitrarily deep nesting (map in list in map) survives the recursive schema', () => {
+ const yaml = 'outer:\n inner:\n - leaf: ok\n';
+ const result = parseFmRegion(yaml);
+ expect(result.parseError).toBeUndefined();
+ expect(result.map).toEqual({ outer: { inner: [{ leaf: 'ok' }] } });
+ });
+
+ test('genuinely malformed YAML still sets parseError (yaml@2 parse error)', () => {
+ const result = parseFmRegion('title: foo: bar');
+ expect(result.parseError).toBeDefined();
+ expect(result.map).toBeNull();
+ });
+
+ test('non-mapping top-level value still sets parseError', () => {
+ const result = parseFmRegion('- one\n- two');
+ expect(result.parseError).toBeDefined();
+ expect(result.map).toBeNull();
+ });
+});
+
describe('applyPatchToFm — array style preservation', () => {
test('flow-style input preserves flow style when patch replaces the array', () => {
const fenced = '---\ntags: [travel, spain, 2026]\n---\n';
@@ -84,3 +130,485 @@ describe('applyPatchToFm — array style preservation', () => {
expect(result.nextFenced).toMatch(/tags:\s*\n\s*-\s/);
});
});
+
+describe('applyPatchToFm — nested write semantics (whole-subtree merge)', () => {
+ test('nested object value replaces the subtree, preserving sibling top-level keys', () => {
+ const fenced =
+ '---\nname: skill\nmetadata:\n version: 1.0.0\n author: Inkeep\ndescription: hello\n---\n';
+ const result = applyPatchToFm(fenced, {
+ metadata: { version: '2.0.0', author: 'Inkeep' },
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(parseFmRegion(result.nextFenced.replace(/^---\n|---\n$/g, '')).map).toEqual({
+ name: 'skill',
+ metadata: { version: '2.0.0', author: 'Inkeep' },
+ description: 'hello',
+ });
+ });
+
+ test('null deletes a nested-object subtree key', () => {
+ const fenced =
+ '---\nname: skill\nmetadata:\n version: 1.0.0\n author: Inkeep\ndescription: hello\n---\n';
+ const result = applyPatchToFm(fenced, { metadata: null });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).not.toContain('metadata');
+ expect(result.nextFenced).toContain('name: skill');
+ expect(result.nextFenced).toContain('description: hello');
+ });
+
+ test('non-object scalar replaces an existing object subtree (whole-subtree replace)', () => {
+ const fenced = '---\nmetadata:\n version: 1.0.0\n author: Inkeep\n---\n';
+ const result = applyPatchToFm(fenced, { metadata: 'inline' });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toMatch(/metadata:\s*inline/);
+ });
+
+ test('nested object replaces an existing scalar', () => {
+ const fenced = '---\nname: skill\n---\n';
+ const result = applyPatchToFm(fenced, {
+ name: { kind: 'skill', detail: 'x' },
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(parseFmRegion(result.nextFenced.replace(/^---\n|---\n$/g, '')).map).toEqual({
+ name: { kind: 'skill', detail: 'x' },
+ });
+ });
+
+ test('arbitrarily-deep nested set builds the full subtree at any depth', () => {
+ const fenced = '---\nname: skill\n---\n';
+ const result = applyPatchToFm(fenced, {
+ outer: { inner: { leaf: 'ok' } },
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(parseFmRegion(result.nextFenced.replace(/^---\n|---\n$/g, '')).map).toEqual({
+ name: 'skill',
+ outer: { inner: { leaf: 'ok' } },
+ });
+ });
+
+ test('preserves comments on untouched sibling keys when editing a nested subtree', () => {
+ const fenced =
+ '---\n# leading comment\nname: skill\n# metadata block\nmetadata:\n version: 1.0.0\n# trailing comment on description\ndescription: hello\n---\n';
+ const result = applyPatchToFm(fenced, {
+ metadata: { version: '2.0.0' },
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toContain('# leading comment');
+ expect(result.nextFenced).toContain('# trailing comment on description');
+ expect(result.nextFenced).toContain('name: skill');
+ expect(result.nextFenced).toContain('description: hello');
+ });
+
+ test('flow-style nested map survives a whole-subtree replacement', () => {
+ const fenced = '---\nmetadata: {version: 1.0, author: Inkeep}\n---\n';
+ const result = applyPatchToFm(fenced, {
+ metadata: { version: '2.0', author: 'Inkeep' },
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toContain('metadata: {');
+ });
+
+ test('block-style nested map stays in block style on replacement', () => {
+ const fenced = '---\nmetadata:\n version: 1.0\n author: Inkeep\n---\n';
+ const result = applyPatchToFm(fenced, {
+ metadata: { version: '2.0', author: 'Inkeep' },
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toMatch(/metadata:\s*\n\s+version:/);
+ });
+
+ test('idempotence: applying the same nested patch twice is byte-stable', () => {
+ const fenced = '---\nname: skill\nmetadata:\n version: 1.0.0\n author: Inkeep\n---\n';
+ const first = applyPatchToFm(fenced, {
+ metadata: { version: '2.0.0', author: 'Inkeep' },
+ });
+ expect(first.ok).toBe(true);
+ if (!first.ok) return;
+ const second = applyPatchToFm(first.nextFenced, {
+ metadata: { version: '2.0.0', author: 'Inkeep' },
+ });
+ expect(second.ok).toBe(true);
+ if (!second.ok) return;
+ expect(second.nextFenced).toBe(first.nextFenced);
+ });
+
+ test('total function: pathological nested input returns a parse_failed error, never throws', () => {
+ const fenced = '---\nname: skill\n---\n';
+ const result = applyPatchToFm(fenced, {
+ metadata: { stamp: new Date() as unknown as string },
+ });
+ expect(result.ok).toBe(false);
+ });
+});
+
+describe('applyPathRenameToFm — path-addressed nested rename', () => {
+ test('renames a top-level key when path has one element', () => {
+ const fenced = '---\nname: skill\ndescription: hello\n---\n';
+ const result = applyPathRenameToFm(fenced, ['name'], 'title');
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toContain('title: skill');
+ expect(result.nextFenced).toContain('description: hello');
+ expect(result.nextFenced).not.toContain('name:');
+ });
+
+ test('renames a nested leaf preserving sibling nested keys + comments', () => {
+ const fenced =
+ '---\nname: skill\nmetadata:\n # before version\n version: 1.0.0\n author: Inkeep\n repository: https://example.com\n---\n';
+ const result = applyPathRenameToFm(fenced, ['metadata', 'version'], 'semver');
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toContain('semver: 1.0.0');
+ expect(result.nextFenced).toContain('author: Inkeep');
+ expect(result.nextFenced).toContain('repository: https://example.com');
+ expect(result.nextFenced).toContain('# before version');
+ expect(result.nextFenced).not.toContain('version: 1.0.0');
+ });
+
+ test('renames a deeply nested leaf at depth 3', () => {
+ const fenced = '---\nouter:\n inner:\n leaf: ok\n other: keep\n---\n';
+ const result = applyPathRenameToFm(fenced, ['outer', 'inner', 'leaf'], 'tip');
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toContain('tip: ok');
+ expect(result.nextFenced).toContain('other: keep');
+ });
+
+ test('preserves source position of the renamed Pair (siblings stay in order)', () => {
+ const fenced = '---\nmetadata:\n version: 1.0.0\n author: Inkeep\n license: MIT\n---\n';
+ const result = applyPathRenameToFm(fenced, ['metadata', 'author'], 'maintainer');
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ const versionIdx = result.nextFenced.indexOf('version:');
+ const maintainerIdx = result.nextFenced.indexOf('maintainer:');
+ const licenseIdx = result.nextFenced.indexOf('license:');
+ expect(versionIdx).toBeLessThan(maintainerIdx);
+ expect(maintainerIdx).toBeLessThan(licenseIdx);
+ });
+
+ test('rejects rename when last path segment is numeric (sequence index)', () => {
+ const fenced = '---\nitems:\n - a\n - b\n---\n';
+ const result = applyPathRenameToFm(fenced, ['items', 0], 'x');
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('invalid_path');
+ });
+
+ test('rejects unknown leaf', () => {
+ const fenced = '---\nmetadata:\n version: 1.0.0\n---\n';
+ const result = applyPathRenameToFm(fenced, ['metadata', 'missing'], 'x');
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('unknown_key');
+ });
+
+ test('rejects nested target collision by default', () => {
+ const fenced = '---\nmetadata:\n version: 1.0.0\n author: Inkeep\n---\n';
+ const result = applyPathRenameToFm(fenced, ['metadata', 'version'], 'author');
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('duplicate_target');
+ });
+
+ test('allowDuplicate admits a colliding rename', () => {
+ const fenced = '---\nmetadata:\n version: 1.0.0\n author: Inkeep\n---\n';
+ const result = applyPathRenameToFm(fenced, ['metadata', 'version'], 'author', {
+ allowDuplicate: true,
+ });
+ expect(result.ok).toBe(true);
+ });
+
+ test('top-level rename to reserved "frontmatter" is rejected', () => {
+ const fenced = '---\nname: skill\n---\n';
+ const result = applyPathRenameToFm(fenced, ['name'], 'frontmatter');
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('reserved_key');
+ });
+
+ test('nested rename to "frontmatter" is allowed (only the top-level slot is reserved)', () => {
+ const fenced = '---\nmetadata:\n version: 1.0.0\n---\n';
+ const result = applyPathRenameToFm(fenced, ['metadata', 'version'], 'frontmatter');
+ expect(result.ok).toBe(true);
+ });
+
+ test('renaming through a scalar intermediate fails with unknown_key', () => {
+ const fenced = '---\nname: skill\n---\n';
+ const result = applyPathRenameToFm(fenced, ['name', 'child'], 'x');
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('unknown_key');
+ });
+
+ test('empty path is rejected', () => {
+ const fenced = '---\nname: skill\n---\n';
+ const result = applyPathRenameToFm(fenced, [], 'x');
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('invalid_path');
+ });
+
+ test('no-op rename to same key returns the input unchanged', () => {
+ const fenced = '---\nmetadata:\n version: 1.0.0\n---\n';
+ const result = applyPathRenameToFm(fenced, ['metadata', 'version'], 'version');
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toBe(fenced);
+ });
+});
+
+describe('applyPathReorderToFm — path-addressed nested reorder', () => {
+ test('reorders top-level keys when path is empty (delegates to applyReorderToFm)', () => {
+ const fenced = '---\nname: skill\ndescription: hello\nmetadata: {}\n---\n';
+ const result = applyPathReorderToFm(fenced, [], ['metadata', 'name', 'description']);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ const metaIdx = result.nextFenced.indexOf('metadata:');
+ const nameIdx = result.nextFenced.indexOf('name:');
+ const descIdx = result.nextFenced.indexOf('description:');
+ expect(metaIdx).toBeLessThan(nameIdx);
+ expect(nameIdx).toBeLessThan(descIdx);
+ });
+
+ test('reorders nested keys preserving sibling top-level keys', () => {
+ const fenced =
+ '---\nname: skill\nmetadata:\n version: 1.0.0\n author: Inkeep\n license: MIT\n---\n';
+ const result = applyPathReorderToFm(fenced, ['metadata'], ['license', 'author', 'version']);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ const licenseIdx = result.nextFenced.indexOf('license:');
+ const authorIdx = result.nextFenced.indexOf('author:');
+ const versionIdx = result.nextFenced.indexOf('version:');
+ expect(licenseIdx).toBeLessThan(authorIdx);
+ expect(authorIdx).toBeLessThan(versionIdx);
+ expect(result.nextFenced).toContain('name: skill');
+ });
+
+ test('reorders deeply nested children', () => {
+ const fenced = '---\nouter:\n inner:\n a: 1\n b: 2\n c: 3\n---\n';
+ const result = applyPathReorderToFm(fenced, ['outer', 'inner'], ['c', 'a', 'b']);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ const cIdx = result.nextFenced.indexOf('c:');
+ const aIdx = result.nextFenced.indexOf('a:');
+ const bIdx = result.nextFenced.indexOf('b:');
+ expect(cIdx).toBeLessThan(aIdx);
+ expect(aIdx).toBeLessThan(bIdx);
+ });
+
+ test('rejects a non-permutation of current keys', () => {
+ const fenced = '---\nmetadata:\n version: 1.0.0\n author: Inkeep\n---\n';
+ const result = applyPathReorderToFm(fenced, ['metadata'], ['version', 'missing']);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('reorder_mismatch');
+ });
+
+ test('rejects when target is not a map', () => {
+ const fenced = '---\nname: skill\n---\n';
+ const result = applyPathReorderToFm(fenced, ['name'], ['x']);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('invalid_path');
+ });
+
+ test('rejects reorder targeting a sequence (not a map)', () => {
+ const fenced = '---\nitems:\n - a\n - b\n---\n';
+ const result = applyPathReorderToFm(fenced, ['items'], ['a', 'b']);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('invalid_path');
+ });
+
+ test('idempotent reorder to the same order is byte-stable', () => {
+ const fenced = '---\nmetadata:\n version: 1.0.0\n author: Inkeep\n---\n';
+ const result = applyPathReorderToFm(fenced, ['metadata'], ['version', 'author']);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toBe(fenced);
+ });
+
+ test('preserves comments on the reordered map', () => {
+ const fenced =
+ '---\nmetadata:\n # before version\n version: 1.0.0\n # before author\n author: Inkeep\n---\n';
+ const result = applyPathReorderToFm(fenced, ['metadata'], ['author', 'version']);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toContain('# before version');
+ expect(result.nextFenced).toContain('# before author');
+ });
+});
+
+describe('applyPathReorderSeqToFm — array-of-objects reorder semantics', () => {
+ test('permutes items at the array path; sibling keys + per-item content survive', () => {
+ const fenced =
+ '---\ntitle: doc\ncontributors:\n - name: A\n role: lead\n - name: B\n role: review\n - name: C\n role: author\n---\n';
+ const result = applyPathReorderSeqToFm(fenced, ['contributors'], [2, 0, 1]);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ const parsed = parseFmRegion(result.nextFenced.replace(/^---\n/, '').replace(/---\n$/, ''));
+ expect(parsed.parseError).toBeUndefined();
+ expect(parsed.map?.contributors).toEqual([
+ { name: 'C', role: 'author' },
+ { name: 'A', role: 'lead' },
+ { name: 'B', role: 'review' },
+ ]);
+ expect(parsed.map?.title).toBe('doc');
+ });
+
+ test('identity permutation is a no-op (byte-stable)', () => {
+ const fenced = '---\nlist:\n - { x: 1 }\n - { x: 2 }\n---\n';
+ const result = applyPathReorderSeqToFm(fenced, ['list'], [0, 1]);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toBe(fenced);
+ });
+
+ test('preserves per-item line comments after reorder', () => {
+ const fenced = '---\nitems:\n # before A\n - name: A\n # before B\n - name: B\n---\n';
+ const result = applyPathReorderSeqToFm(fenced, ['items'], [1, 0]);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toContain('# before A');
+ expect(result.nextFenced).toContain('# before B');
+ });
+
+ test('rejects non-permutation (wrong length)', () => {
+ const fenced = '---\nlist:\n - { x: 1 }\n - { x: 2 }\n - { x: 3 }\n---\n';
+ const result = applyPathReorderSeqToFm(fenced, ['list'], [0, 1]);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('reorder_mismatch');
+ });
+
+ test('rejects non-permutation (duplicate index)', () => {
+ const fenced = '---\nlist:\n - { x: 1 }\n - { x: 2 }\n---\n';
+ const result = applyPathReorderSeqToFm(fenced, ['list'], [0, 0]);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('reorder_mismatch');
+ });
+
+ test('rejects non-permutation (out-of-range index)', () => {
+ const fenced = '---\nlist:\n - { x: 1 }\n - { x: 2 }\n---\n';
+ const result = applyPathReorderSeqToFm(fenced, ['list'], [0, 2]);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('reorder_mismatch');
+ });
+
+ test('rejects when target at path is not a sequence (map instead)', () => {
+ const fenced = '---\nmetadata:\n version: 1.0\n---\n';
+ const result = applyPathReorderSeqToFm(fenced, ['metadata'], [0]);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('invalid_path');
+ });
+
+ test('rejects when target at path is missing (parent does not exist)', () => {
+ const fenced = '---\ntitle: doc\n---\n';
+ const result = applyPathReorderSeqToFm(fenced, ['nope'], [0]);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('invalid_path');
+ });
+
+ test('rejects empty path (whole document)', () => {
+ const fenced = '---\ntitle: doc\n---\n';
+ const result = applyPathReorderSeqToFm(fenced, [], [0]);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.error.kind).toBe('invalid_path');
+ });
+
+ test('reorder of a deeply-nested array preserves siblings at every depth', () => {
+ const fenced =
+ '---\nproject:\n name: ok\n authors:\n - name: A\n - name: B\n release: alpha\n---\n';
+ const result = applyPathReorderSeqToFm(fenced, ['project', 'authors'], [1, 0]);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ const parsed = parseFmRegion(result.nextFenced.replace(/^---\n/, '').replace(/---\n$/, ''));
+ expect(parsed.map?.project).toEqual({
+ name: 'ok',
+ authors: [{ name: 'B' }, { name: 'A' }],
+ release: 'alpha',
+ });
+ });
+
+ test('reorder result re-applied (twice) is byte-stable (idempotence)', () => {
+ const fenced = '---\nlist:\n - { x: 1 }\n - { x: 2 }\n - { x: 3 }\n---\n';
+ const once = applyPathReorderSeqToFm(fenced, ['list'], [2, 0, 1]);
+ expect(once.ok).toBe(true);
+ if (!once.ok) return;
+ const twice = applyPathReorderSeqToFm(once.nextFenced, ['list'], [0, 1, 2]);
+ expect(twice.ok).toBe(true);
+ if (!twice.ok) return;
+ expect(twice.nextFenced).toBe(once.nextFenced);
+ });
+});
+
+describe('applyPathSetToFm / applyPathDeleteToFm — path validation + value errors', () => {
+ const fenced = '---\nname: skill\nitems:\n - a\n - b\n---\n';
+
+ test('empty path is rejected as invalid_path', () => {
+ const result = applyPathSetToFm(fenced, [], 'x');
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error.kind).toBe('invalid_path');
+ });
+
+ test('negative integer index is rejected as invalid_path', () => {
+ const result = applyPathSetToFm(fenced, ['items', -1], 'x');
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error.kind).toBe('invalid_path');
+ });
+
+ test('non-integer (float) index is rejected as invalid_path', () => {
+ const result = applyPathSetToFm(fenced, ['items', 1.5], 'x');
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error.kind).toBe('invalid_path');
+ });
+
+ test('reserved top-level key is rejected as reserved_key', () => {
+ const result = applyPathSetToFm(fenced, ['frontmatter'], 'x');
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error.kind).toBe('reserved_key');
+ });
+
+ test('a structurally-valid path with a non-conforming value reports invalid_value (not invalid_path)', () => {
+ const result = applyPathSetToFm(fenced, ['name'], Symbol('nope') as unknown as string);
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.error.kind).toBe('invalid_value');
+ if (result.error.kind === 'invalid_value') expect(result.error.key).toBe('name');
+ }
+ });
+
+ test('valid nested set adds the leaf and preserves the sibling', () => {
+ const result = applyPathSetToFm('---\nmeta:\n a: 1\n---\n', ['meta', 'b'], 'two');
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.nextFenced).toContain('a: 1');
+ expect(result.nextFenced).toContain('b: two');
+ });
+
+ test('deletePath validates the path the same way', () => {
+ expect(applyPathDeleteToFm(fenced, []).ok).toBe(false);
+ const neg = applyPathDeleteToFm(fenced, ['items', -1]);
+ expect(neg.ok).toBe(false);
+ if (!neg.ok) expect(neg.error.kind).toBe('invalid_path');
+ });
+
+ test('deletePath on an absent leaf is an idempotent no-op', () => {
+ const result = applyPathDeleteToFm(fenced, ['nope']);
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(result.nextFenced).toBe(fenced);
+ });
+});
diff --git a/packages/core/src/bridge/frontmatter-region.ts b/packages/core/src/bridge/frontmatter-region.ts
index 017b2d2fd..a5ad8f5f9 100644
--- a/packages/core/src/bridge/frontmatter-region.ts
+++ b/packages/core/src/bridge/frontmatter-region.ts
@@ -1,5 +1,6 @@
import {
Document,
+ isMap,
isSeq,
type Pair,
parseDocument,
@@ -13,8 +14,9 @@ import {
FrontmatterMapSchema,
type FrontmatterValue,
FrontmatterValueSchema,
+ RESERVED_FRONTMATTER_KEY,
} from '../frontmatter/schema.ts';
-import { STRINGIFY_OPTIONS, withFences } from '../frontmatter/yaml-codec.ts';
+import { buildValueNode, STRINGIFY_OPTIONS, withFences } from '../frontmatter/yaml-codec.ts';
export const MAX_FM_REGION_BYTES = 65536;
@@ -29,11 +31,9 @@ export function detectFmRegion(ytextSnapshot: string): FmRegion {
return { fenced: match[0], body: ytextSnapshot.slice(match[0].length) };
}
-export interface ParsedFmRegion {
- doc: Document;
- map: FrontmatterMap | null;
- parseError?: string;
-}
+export type ParsedFmRegion =
+ | { doc: Document; map: FrontmatterMap; parseError?: never }
+ | { doc: Document; map: null; parseError: string };
export function parseFmRegion(yamlBody: string): ParsedFmRegion {
if (yamlBody.trim() === '') {
@@ -150,12 +150,11 @@ export type FmEditError =
| { kind: 'reserved_key'; key: string }
| { kind: 'reorder_mismatch'; expected: string[]; got: string[] }
| { kind: 'region_too_large'; bytes: number; limit: number }
- | { kind: 'parse_failed'; reason: string };
+ | { kind: 'parse_failed'; reason: string }
+ | { kind: 'invalid_path'; path: ReadonlyArray<string | number>; reason: string };
export type FmEditResult = { ok: true; nextFenced: string } | { ok: false; error: FmEditError };
-const RESERVED_FRONTMATTER_KEY = 'frontmatter';
-
function ensureContents(doc: Document): YAMLMap {
if (doc.contents == null || !('items' in (doc.contents as object))) {
const empty = doc.createNode({}) as YAMLMap;
@@ -181,6 +180,13 @@ function checkRegionSize(fenced: string): FmEditError | null {
return null;
}
+function finalizeFenced(doc: Document): FmEditResult {
+ const next = stringify(doc);
+ const sizeErr = checkRegionSize(next);
+ if (sizeErr) return { ok: false, error: sizeErr };
+ return { ok: true, nextFenced: next };
+}
+
export function applyPatchToFm(
currentFenced: string,
patch: Record<string, FrontmatterValue | null>,
@@ -213,21 +219,10 @@ export function applyPatchToFm(
},
};
}
- if (Array.isArray(parsed.data)) {
- const existing = doc.get(key, true);
- const existingFlow = isSeq(existing) ? (existing as YAMLSeq).flow : undefined;
- const newNode = doc.createNode(parsed.data) as YAMLSeq;
- if (existingFlow !== undefined) newNode.flow = existingFlow;
- doc.set(key, newNode);
- continue;
- }
- doc.set(key, parsed.data);
+ doc.set(key, buildValueNode(doc, doc.get(key, true), parsed.data));
}
- const next = stringify(doc);
- const sizeErr = checkRegionSize(next);
- if (sizeErr) return { ok: false, error: sizeErr };
- return { ok: true, nextFenced: next };
+ return finalizeFenced(doc);
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
return { ok: false, error: { kind: 'parse_failed', reason: `yaml@2 threw: ${reason}` } };
@@ -277,10 +272,7 @@ export function applyRenameToFm(
try {
setPairKey(sourcePair, newKey);
- const next = stringify(doc);
- const sizeErr = checkRegionSize(next);
- if (sizeErr) return { ok: false, error: sizeErr };
- return { ok: true, nextFenced: next };
+ return finalizeFenced(doc);
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
return { ok: false, error: { kind: 'parse_failed', reason: `yaml@2 threw: ${reason}` } };
@@ -333,10 +325,7 @@ export function applyReorderToFm(
}
contents.items = next;
- const nextFenced = stringify(doc);
- const sizeErr = checkRegionSize(nextFenced);
- if (sizeErr) return { ok: false, error: sizeErr };
- return { ok: true, nextFenced };
+ return finalizeFenced(doc);
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
return { ok: false, error: { kind: 'parse_failed', reason: `yaml@2 threw: ${reason}` } };
@@ -354,3 +343,300 @@ function permutationOf(a: readonly string[], b: readonly string[]): boolean {
for (const v of counts.values()) if (v !== 0) return false;
return true;
}
+
+function validatePath(path: ReadonlyArray<string | number>): FmEditError | null {
+ if (path.length === 0) {
+ return { kind: 'invalid_path', path: [...path], reason: 'path must have at least one segment' };
+ }
+ for (let i = 0; i < path.length; i++) {
+ const seg = path[i];
+ if (typeof seg !== 'string' && typeof seg !== 'number') {
+ return {
+ kind: 'invalid_path',
+ path: [...path],
+ reason: `path segment at index ${i} must be string or number`,
+ };
+ }
+ if (typeof seg === 'number' && (!Number.isInteger(seg) || seg < 0)) {
+ return {
+ kind: 'invalid_path',
+ path: [...path],
+ reason: `numeric path segment at index ${i} must be a non-negative integer`,
+ };
+ }
+ }
+ if (path[0] === RESERVED_FRONTMATTER_KEY) {
+ return { kind: 'reserved_key', key: RESERVED_FRONTMATTER_KEY };
+ }
+ return null;
+}
+
+export function applyPathSetToFm(
+ currentFenced: string,
+ path: ReadonlyArray<string | number>,
+ value: FrontmatterValue,
+): FmEditResult {
+ const pathErr = validatePath(path);
+ if (pathErr) return { ok: false, error: pathErr };
+
+ const { doc, map } = parseFencedFmRegion(currentFenced);
+ if (map === null) {
+ return { ok: false, error: { kind: 'parse_failed', reason: 'fm region unparseable' } };
+ }
+
+ const parsed = FrontmatterValueSchema.safeParse(value);
+ if (!parsed.success) {
+ return {
+ ok: false,
+ error: {
+ kind: 'invalid_value',
+ key: String(path[path.length - 1]),
+ reason: parsed.error.issues[0]?.message ?? 'invalid value',
+ },
+ };
+ }
+
+ try {
+ ensureContents(doc);
+ doc.setIn(path as unknown[], buildValueNode(doc, doc.getIn(path, true), parsed.data));
+ return finalizeFenced(doc);
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : String(err);
+ return { ok: false, error: { kind: 'parse_failed', reason: `yaml@2 threw: ${reason}` } };
+ }
+}
+
+export function applyPathDeleteToFm(
+ currentFenced: string,
+ path: ReadonlyArray<string | number>,
+): FmEditResult {
+ const pathErr = validatePath(path);
+ if (pathErr) return { ok: false, error: pathErr };
+
+ const { doc, map } = parseFencedFmRegion(currentFenced);
+ if (map === null) {
+ return { ok: false, error: { kind: 'parse_failed', reason: 'fm region unparseable' } };
+ }
+
+ try {
+ if (doc.getIn(path as unknown[], true) === undefined) {
+ return { ok: true, nextFenced: currentFenced };
+ }
+ doc.deleteIn(path as unknown[]);
+
+ return finalizeFenced(doc);
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : String(err);
+ return { ok: false, error: { kind: 'parse_failed', reason: `yaml@2 threw: ${reason}` } };
+ }
+}
+
+function resolveParentMap(
+ doc: Document,
+ parentPath: ReadonlyArray<string | number>,
+): YAMLMap | null {
+ if (parentPath.length === 0) {
+ const contents = doc.contents as YAMLMap | null | undefined;
+ return isMap(contents) ? contents : null;
+ }
+ const node = doc.getIn(parentPath, true);
+ return isMap(node) ? node : null;
+}
+
+export function applyPathRenameToFm(
+ currentFenced: string,
+ path: ReadonlyArray<string | number>,
+ newKey: string,
+ options: { allowDuplicate?: boolean } = {},
+): FmEditResult {
+ const pathErr = validatePath(path);
+ if (pathErr) return { ok: false, error: pathErr };
+
+ const lastSeg = path[path.length - 1];
+ if (typeof lastSeg !== 'string') {
+ return {
+ ok: false,
+ error: {
+ kind: 'invalid_path',
+ path: [...path],
+ reason: 'cannot rename: last path segment must be a string (map key)',
+ },
+ };
+ }
+ if (path.length === 1 && newKey === RESERVED_FRONTMATTER_KEY) {
+ return { ok: false, error: { kind: 'reserved_key', key: RESERVED_FRONTMATTER_KEY } };
+ }
+
+ const { doc, map } = parseFencedFmRegion(currentFenced);
+ if (map === null) {
+ return { ok: false, error: { kind: 'parse_failed', reason: 'fm region unparseable' } };
+ }
+
+ if (lastSeg === newKey) {
+ return { ok: true, nextFenced: currentFenced };
+ }
+
+ const parent = resolveParentMap(doc, path.slice(0, -1));
+ if (!parent) {
+ return { ok: false, error: { kind: 'unknown_key', key: lastSeg } };
+ }
+
+ const sourcePair = parent.items.find(
+ (item): item is Pair => isPair(item) && pairKey(item) === lastSeg,
+ );
+ if (!sourcePair) {
+ return { ok: false, error: { kind: 'unknown_key', key: lastSeg } };
+ }
+
+ if (!options.allowDuplicate) {
+ const collides = parent.items.some(
+ (item) => isPair(item) && item !== sourcePair && pairKey(item) === newKey,
+ );
+ if (collides) {
+ return { ok: false, error: { kind: 'duplicate_target', key: newKey } };
+ }
+ }
+
+ try {
+ setPairKey(sourcePair, newKey);
+ return finalizeFenced(doc);
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : String(err);
+ return { ok: false, error: { kind: 'parse_failed', reason: `yaml@2 threw: ${reason}` } };
+ }
+}
+
+export function applyPathReorderToFm(
+ currentFenced: string,
+ path: ReadonlyArray<string | number>,
+ orderedKeys: readonly string[],
+): FmEditResult {
+ if (path.length === 0) return applyReorderToFm(currentFenced, orderedKeys);
+
+ const pathErr = validatePath(path);
+ if (pathErr) return { ok: false, error: pathErr };
+
+ const { doc, map } = parseFencedFmRegion(currentFenced);
+ if (map === null) {
+ return { ok: false, error: { kind: 'parse_failed', reason: 'fm region unparseable' } };
+ }
+
+ const target = doc.getIn(path, true);
+ if (!isMap(target)) {
+ return {
+ ok: false,
+ error: {
+ kind: 'invalid_path',
+ path: [...path],
+ reason: 'cannot reorder: target is not a map',
+ },
+ };
+ }
+
+ const currentKeys: string[] = [];
+ for (const item of target.items) {
+ if (!isPair(item)) continue;
+ const k = pairKey(item);
+ if (k !== null) currentKeys.push(k);
+ }
+
+ if (currentKeys.length !== orderedKeys.length || !permutationOf(currentKeys, orderedKeys)) {
+ return {
+ ok: false,
+ error: {
+ kind: 'reorder_mismatch',
+ expected: currentKeys,
+ got: [...orderedKeys],
+ },
+ };
+ }
+
+ try {
+ const remaining: Pair[] = target.items.filter(isPair);
+ const next: Pair[] = [];
+ for (const key of orderedKeys) {
+ const idx = remaining.findIndex((p) => pairKey(p) === key);
+ if (idx === -1) {
+ return {
+ ok: false,
+ error: {
+ kind: 'reorder_mismatch',
+ expected: currentKeys,
+ got: [...orderedKeys],
+ },
+ };
+ }
+ const [picked] = remaining.splice(idx, 1);
+ if (picked) next.push(picked);
+ }
+ target.items = next;
+
+ return finalizeFenced(doc);
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : String(err);
+ return { ok: false, error: { kind: 'parse_failed', reason: `yaml@2 threw: ${reason}` } };
+ }
+}
+
+export function applyPathReorderSeqToFm(
+ currentFenced: string,
+ path: ReadonlyArray<string | number>,
+ oldIndicesInNewOrder: readonly number[],
+): FmEditResult {
+ const pathErr = validatePath(path);
+ if (pathErr) return { ok: false, error: pathErr };
+
+ const { doc, map } = parseFencedFmRegion(currentFenced);
+ if (map === null) {
+ return { ok: false, error: { kind: 'parse_failed', reason: 'fm region unparseable' } };
+ }
+
+ const target = doc.getIn(path, true);
+ if (!isSeq(target)) {
+ return {
+ ok: false,
+ error: {
+ kind: 'invalid_path',
+ path: [...path],
+ reason: 'cannot reorder: target is not a sequence',
+ },
+ };
+ }
+
+ const seq = target as YAMLSeq;
+ const n = seq.items.length;
+ const currentIndices = Array.from({ length: n }, (_, i) => i);
+ const want = [...oldIndicesInNewOrder];
+ if (!isIndexPermutation(want, n)) {
+ return {
+ ok: false,
+ error: {
+ kind: 'reorder_mismatch',
+ expected: currentIndices.map(String),
+ got: want.map(String),
+ },
+ };
+ }
+
+ try {
+ const original = seq.items.slice();
+ const next = want.map((idx) => original[idx]);
+ seq.items = next;
+
+ return finalizeFenced(doc);
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : String(err);
+ return { ok: false, error: { kind: 'parse_failed', reason: `yaml@2 threw: ${reason}` } };
+ }
+}
+
+function isIndexPermutation(want: readonly number[], n: number): boolean {
+ if (want.length !== n) return false;
+ const seen = new Array<boolean>(n).fill(false);
+ for (const idx of want) {
+ if (!Number.isInteger(idx) || idx < 0 || idx >= n) return false;
+ if (seen[idx]) return false;
+ seen[idx] = true;
+ }
+ return true;
+}
diff --git a/packages/core/src/bridge/index.ts b/packages/core/src/bridge/index.ts
index d96ecc3aa..8024ca5af 100644
--- a/packages/core/src/bridge/index.ts
+++ b/packages/core/src/bridge/index.ts
@@ -5,6 +5,8 @@ export {
type FrontmatterBinding,
type FrontmatterBindingPatchResult,
type FrontmatterBindingPatchSuccess,
+ type FrontmatterBindingPathResult,
+ type FrontmatterBindingPathSuccess,
type FrontmatterBindingRenameResult,
type FrontmatterBindingRenameSuccess,
type FrontmatterBindingReorderResult,
@@ -24,6 +26,11 @@ export {
export { type DiffChange, diffLinesFast } from './diff-lines.ts';
export {
applyPatchToFm,
+ applyPathDeleteToFm,
+ applyPathRenameToFm,
+ applyPathReorderSeqToFm,
+ applyPathReorderToFm,
+ applyPathSetToFm,
applyRenameToFm,
applyReorderToFm,
detectFmRegion,
diff --git a/packages/core/src/frontmatter/schema.test.ts b/packages/core/src/frontmatter/schema.test.ts
index 3715b92dd..9163dd7f2 100644
--- a/packages/core/src/frontmatter/schema.test.ts
+++ b/packages/core/src/frontmatter/schema.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, test } from 'bun:test';
-import { isFrontmatterValueEmpty } from './schema.ts';
+import {
+ FRONTMATTER_TYPES,
+ frontmatterValuesEqual,
+ inferType,
+ isFrontmatterValueEmpty,
+} from './schema.ts';
describe('isFrontmatterValueEmpty', () => {
test('treats null, empty string, and empty array as empty', () => {
@@ -24,3 +29,96 @@ describe('isFrontmatterValueEmpty', () => {
expect(isFrontmatterValueEmpty(true)).toBe(false);
});
});
+
+describe('FRONTMATTER_TYPES', () => {
+ test('includes object for nested mapping support', () => {
+ expect(FRONTMATTER_TYPES).toContain('object');
+ });
+});
+
+describe('inferType', () => {
+ test('returns object for a plain mapping', () => {
+ expect(inferType({})).toBe('object');
+ expect(inferType({ version: '1.0' })).toBe('object');
+ expect(inferType({ a: { b: 'c' } })).toBe('object');
+ });
+
+ test('returns list for arrays regardless of element shape', () => {
+ expect(inferType([])).toBe('list');
+ expect(inferType(['a', 'b'])).toBe('list');
+ expect(inferType([{ k: 'v' }])).toBe('list');
+ expect(inferType([{ a: 1 }, { b: 2 }])).toBe('list');
+ });
+
+ test('preserves scalar inference (boolean, number, date, text)', () => {
+ expect(inferType(true)).toBe('boolean');
+ expect(inferType(42)).toBe('number');
+ expect(inferType('2026-06-09')).toBe('date');
+ expect(inferType('hello')).toBe('text');
+ });
+});
+
+describe('frontmatterValuesEqual', () => {
+ test('scalars compare by value', () => {
+ expect(frontmatterValuesEqual('a', 'a')).toBe(true);
+ expect(frontmatterValuesEqual(1, 1)).toBe(true);
+ expect(frontmatterValuesEqual(true, true)).toBe(true);
+ expect(frontmatterValuesEqual('a', 'b')).toBe(false);
+ expect(frontmatterValuesEqual(1, 2)).toBe(false);
+ });
+
+ test('structurally-equal nested objects are equal across references', () => {
+ expect(
+ frontmatterValuesEqual(
+ { version: '1.0.0', author: 'Inkeep' },
+ { version: '1.0.0', author: 'Inkeep' },
+ ),
+ ).toBe(true);
+ expect(frontmatterValuesEqual({ a: 1, b: 2 }, { b: 2, a: 1 })).toBe(true);
+ });
+
+ test('differing nested leaf is unequal', () => {
+ expect(frontmatterValuesEqual({ version: '1.0.0' }, { version: '2.0.0' })).toBe(false);
+ });
+
+ test('extra key in either side is unequal', () => {
+ expect(frontmatterValuesEqual({ a: 1 }, { a: 1, b: 2 })).toBe(false);
+ expect(frontmatterValuesEqual({ a: 1, b: 2 }, { a: 1 })).toBe(false);
+ });
+
+ test('arrays recurse into element structure (not reference)', () => {
+ expect(frontmatterValuesEqual(['a', 'b'], ['a', 'b'])).toBe(true);
+ expect(frontmatterValuesEqual([{ k: 1 }], [{ k: 1 }])).toBe(true);
+ expect(frontmatterValuesEqual([{ k: 1 }], [{ k: 2 }])).toBe(false);
+ expect(frontmatterValuesEqual(['a'], ['a', 'b'])).toBe(false);
+ });
+
+ test('deeply nested structures compare structurally', () => {
+ expect(
+ frontmatterValuesEqual(
+ { meta: { tags: ['x'], nested: { n: 1 } } },
+ { meta: { tags: ['x'], nested: { n: 1 } } },
+ ),
+ ).toBe(true);
+ expect(
+ frontmatterValuesEqual({ meta: { nested: { n: 1 } } }, { meta: { nested: { n: 2 } } }),
+ ).toBe(false);
+ });
+
+ test('cross-type mismatches are unequal', () => {
+ expect(frontmatterValuesEqual({}, [])).toBe(false);
+ expect(frontmatterValuesEqual('1', 1)).toBe(false);
+ expect(frontmatterValuesEqual({ a: 1 }, 'a')).toBe(false);
+ });
+
+ test('null is handled by the guard path (only equal to itself)', () => {
+ expect(frontmatterValuesEqual(null, null)).toBe(true);
+ expect(frontmatterValuesEqual(null, {})).toBe(false);
+ expect(frontmatterValuesEqual({}, null)).toBe(false);
+ expect(frontmatterValuesEqual(null, 'a')).toBe(false);
+ });
+
+ test('same key count but different key set is unequal (Object.hasOwn guard)', () => {
+ expect(frontmatterValuesEqual({ a: 1, b: 2 }, { a: 1, c: 2 })).toBe(false);
+ });
+});
diff --git a/packages/core/src/frontmatter/schema.ts b/packages/core/src/frontmatter/schema.ts
index a407dee26..2b1a17a96 100644
--- a/packages/core/src/frontmatter/schema.ts
+++ b/packages/core/src/frontmatter/schema.ts
@@ -1,17 +1,38 @@
import { z } from 'zod';
-export const FRONTMATTER_TYPES = ['text', 'number', 'boolean', 'date', 'list'] as const;
+export const RESERVED_FRONTMATTER_KEY = 'frontmatter';
+
+export const FRONTMATTER_TYPES = ['text', 'number', 'boolean', 'date', 'list', 'object'] as const;
export type FrontmatterType = (typeof FRONTMATTER_TYPES)[number];
export const FrontmatterTypeSchema = z.enum(FRONTMATTER_TYPES);
-export const FrontmatterValueSchema = z.union([
- z.string(),
- z.number(),
- z.boolean(),
- z.array(z.union([z.string(), z.number(), z.boolean()]).transform((v) => String(v))),
-]);
-export type FrontmatterValue = z.infer<typeof FrontmatterValueSchema>;
+export type FrontmatterValue =
+ | string
+ | number
+ | boolean
+ | FrontmatterValue[]
+ | { [key: string]: FrontmatterValue };
+
+const FrontmatterScalarLeafSchema = z.union([z.string(), z.number(), z.boolean()]);
+
+const FrontmatterArrayElementSchema: z.ZodType<FrontmatterValue> = z.lazy(() =>
+ z.union([
+ FrontmatterScalarLeafSchema.transform((v) => String(v)),
+ z.record(z.string(), FrontmatterValueSchema),
+ z.array(FrontmatterArrayElementSchema),
+ ]),
+);
+
+export const FrontmatterValueSchema: z.ZodType<FrontmatterValue> = z.lazy(() =>
+ z.union([
+ z.string(),
+ z.number(),
+ z.boolean(),
+ z.array(FrontmatterArrayElementSchema),
+ z.record(z.string(), FrontmatterValueSchema),
+ ]),
+);
const ISO_8601_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
export function isIsoDateString(value: unknown): value is string {
@@ -20,6 +41,7 @@ export function isIsoDateString(value: unknown): value is string {
export function inferType(value: FrontmatterValue): FrontmatterType {
if (Array.isArray(value)) return 'list';
+ if (typeof value === 'object' && value !== null) return 'object';
if (typeof value === 'boolean') return 'boolean';
if (typeof value === 'number') return 'number';
if (isIsoDateString(value)) return 'date';
@@ -27,13 +49,13 @@ export function inferType(value: FrontmatterValue): FrontmatterType {
}
export const FrontmatterMapSchema = z.record(z.string(), FrontmatterValueSchema);
-export type FrontmatterMap = z.infer<typeof FrontmatterMapSchema>;
+export type FrontmatterMap = Record<string, FrontmatterValue>;
export const FrontmatterPatchSchema = z.record(
z.string(),
z.union([FrontmatterValueSchema, z.null()]),
);
-export type FrontmatterPatch = z.infer<typeof FrontmatterPatchSchema>;
+export type FrontmatterPatch = Record<string, FrontmatterValue | null>;
export function isFrontmatterValueEmpty(value: FrontmatterValue | null): boolean {
if (value === null) return true;
@@ -41,3 +63,39 @@ export function isFrontmatterValueEmpty(value: FrontmatterValue | null): boolean
if (Array.isArray(value) && value.length === 0) return true;
return false;
}
+
+export function frontmatterValuesEqual(a: unknown, b: unknown): boolean {
+ if (a === b) return true;
+ if (Array.isArray(a) && Array.isArray(b)) {
+ if (a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) {
+ if (!frontmatterValuesEqual(a[i], b[i])) return false;
+ }
+ return true;
+ }
+ if (
+ a !== null &&
+ b !== null &&
+ typeof a === 'object' &&
+ typeof b === 'object' &&
+ !Array.isArray(a) &&
+ !Array.isArray(b)
+ ) {
+ const aKeys = Object.keys(a);
+ const bKeys = Object.keys(b);
+ if (aKeys.length !== bKeys.length) return false;
+ for (const key of aKeys) {
+ if (!Object.hasOwn(b, key)) return false;
+ if (
+ !frontmatterValuesEqual(
+ (a as Record<string, unknown>)[key],
+ (b as Record<string, unknown>)[key],
+ )
+ ) {
+ return false;
+ }
+ }
+ return true;
+ }
+ return false;
+}
diff --git a/packages/core/src/frontmatter/tags.test.ts b/packages/core/src/frontmatter/tags.test.ts
index fe9aef757..ba54e4900 100644
--- a/packages/core/src/frontmatter/tags.test.ts
+++ b/packages/core/src/frontmatter/tags.test.ts
@@ -74,6 +74,16 @@ describe('extractFrontmatterTags', () => {
test('returns empty when tags is null', () => {
expect(extractFrontmatterTags('tags: null\n')).toEqual([]);
});
+
+ test('drops object array elements rather than stringifying them', () => {
+ const yaml = 'tags:\n - valid\n - {nested: "object"}\n - alsoValid\n';
+ expect(extractFrontmatterTags(yaml)).toEqual(['valid', 'alsoValid']);
+ });
+
+ test('drops nested-array elements rather than stringifying them', () => {
+ const yaml = 'tags:\n - valid\n - [inner, list]\n - alsoValid\n';
+ expect(extractFrontmatterTags(yaml)).toEqual(['valid', 'alsoValid']);
+ });
});
describe('isValidFrontmatterTagValue', () => {
diff --git a/packages/core/src/frontmatter/yaml-codec.test.ts b/packages/core/src/frontmatter/yaml-codec.test.ts
index f7e7eb1f8..09125328b 100644
--- a/packages/core/src/frontmatter/yaml-codec.test.ts
+++ b/packages/core/src/frontmatter/yaml-codec.test.ts
@@ -60,9 +60,43 @@ describe('parseFrontmatterYaml', () => {
expect(parseFrontmatterYaml('"just a string"').map).toBeNull();
});
- test('returns null map when a value violates the shape schema (nested object)', () => {
- const { map } = parseFrontmatterYaml('nested:\n inner: bad\n');
+ test('parses nested objects into a populated map with no parseError', () => {
+ const yaml = 'name: skill\nmetadata:\n version: 1.0.0\n author: Inkeep\n';
+ const { map, parseError } = parseFrontmatterYaml(yaml);
+ expect(parseError).toBeUndefined();
+ expect(map).toEqual({
+ name: 'skill',
+ metadata: { version: '1.0.0', author: 'Inkeep' },
+ });
+ });
+
+ test('parses arbitrarily deep nesting + arrays of objects with no parseError', () => {
+ const yaml =
+ 'name: skill\n' +
+ 'items:\n' +
+ ' - title: a\n' +
+ ' nested:\n' +
+ ' deep: ok\n' +
+ ' - title: b\n';
+ const { map, parseError } = parseFrontmatterYaml(yaml);
+ expect(parseError).toBeUndefined();
+ expect(map).toEqual({
+ name: 'skill',
+ items: [{ title: 'a', nested: { deep: 'ok' } }, { title: 'b' }],
+ });
+ });
+
+ test('object array elements are NOT String-coerced (scalar-only coercion)', () => {
+ const yaml = 'items:\n - {a: 1}\n - tag\n - 2026\n';
+ const { map, parseError } = parseFrontmatterYaml(yaml);
+ expect(parseError).toBeUndefined();
+ expect(map?.items).toEqual([{ a: 1 }, 'tag', '2026']);
+ });
+
+ test('returns null map on genuinely malformed YAML (yaml@2 parse error)', () => {
+ const { map, parseError } = parseFrontmatterYaml('title: foo: bar');
expect(map).toBeNull();
+ expect(parseError).toBeDefined();
});
test('coerces non-string scalars in array values to strings', () => {
@@ -216,6 +250,103 @@ describe('applyPatchToDocument', () => {
const out = applyPatchToDocument(doc, { tags: ['a', 'b', 'c'] });
expect(out).toMatch(/tags:\s*\n\s*-\s/);
});
+
+ test('nested object patch replaces the subtree, preserving sibling top-level keys', () => {
+ const { doc } = parseFrontmatterYaml(
+ 'name: skill\nmetadata:\n version: 1.0.0\n author: Inkeep\ndescription: hello\n',
+ );
+ const out = applyPatchToDocument(doc, {
+ metadata: { version: '2.0.0', author: 'Inkeep' },
+ });
+ const reparsed = parseFrontmatterYaml(out).map;
+ expect(reparsed).toEqual({
+ name: 'skill',
+ metadata: { version: '2.0.0', author: 'Inkeep' },
+ description: 'hello',
+ });
+ });
+
+ test('null deletes a nested-object subtree key', () => {
+ const { doc } = parseFrontmatterYaml(
+ 'name: skill\nmetadata:\n version: 1.0.0\ndescription: hello\n',
+ );
+ const out = applyPatchToDocument(doc, { metadata: null });
+ expect(out).not.toContain('metadata');
+ expect(out).toContain('name: skill');
+ expect(out).toContain('description: hello');
+ });
+
+ test('non-object value replaces an existing object subtree', () => {
+ const { doc } = parseFrontmatterYaml(
+ 'name: skill\nmetadata:\n version: 1.0.0\n author: Inkeep\n',
+ );
+ const out = applyPatchToDocument(doc, { metadata: 'inline-value' });
+ expect(parseFrontmatterYaml(out).map).toEqual({
+ name: 'skill',
+ metadata: 'inline-value',
+ });
+ });
+
+ test('nested object value replaces an existing scalar key', () => {
+ const { doc } = parseFrontmatterYaml('name: skill\n');
+ const out = applyPatchToDocument(doc, {
+ name: { kind: 'skill', detail: 'x' },
+ });
+ expect(parseFrontmatterYaml(out).map).toEqual({
+ name: { kind: 'skill', detail: 'x' },
+ });
+ });
+
+ test('arbitrarily-deep nested set builds the full subtree', () => {
+ const { doc } = parseFrontmatterYaml('name: skill\n');
+ const out = applyPatchToDocument(doc, {
+ outer: { inner: { leaf: 'ok' } },
+ });
+ expect(parseFrontmatterYaml(out).map).toEqual({
+ name: 'skill',
+ outer: { inner: { leaf: 'ok' } },
+ });
+ });
+
+ test('preserves comments on untouched sibling keys across a nested-subtree edit', () => {
+ const yaml =
+ '# leading comment\nname: skill\n# metadata block\nmetadata:\n version: 1.0.0\n# trailing comment on description\ndescription: hello\n';
+ const { doc } = parseFrontmatterYaml(yaml);
+ const out = applyPatchToDocument(doc, {
+ metadata: { version: '2.0.0' },
+ });
+ expect(out).toContain('# leading comment');
+ expect(out).toContain('# trailing comment on description');
+ expect(out).toContain('name: skill');
+ expect(out).toContain('description: hello');
+ });
+
+ test('preserves flow-style nested map when replacing the subtree', () => {
+ const { doc } = parseFrontmatterYaml('metadata: {version: 1.0, author: Inkeep}\n');
+ const out = applyPatchToDocument(doc, {
+ metadata: { version: '2.0', author: 'Inkeep' },
+ });
+ expect(out).toContain('metadata: {');
+ });
+
+ test('preserves block-style nested map when replacing the subtree', () => {
+ const { doc } = parseFrontmatterYaml('metadata:\n version: 1.0\n author: Inkeep\n');
+ const out = applyPatchToDocument(doc, {
+ metadata: { version: '2.0', author: 'Inkeep' },
+ });
+ expect(out).toMatch(/metadata:\s*\n\s+version:/);
+ });
+
+ test('round-trip is idempotent: applying the same nested patch twice is byte-stable', () => {
+ const baseYaml = 'name: skill\nmetadata:\n version: 1.0.0\n author: Inkeep\n';
+ const first = applyPatchToDocument(parseFrontmatterYaml(baseYaml).doc, {
+ metadata: { version: '2.0.0', author: 'Inkeep' },
+ });
+ const second = applyPatchToDocument(parseFrontmatterYaml(first).doc, {
+ metadata: { version: '2.0.0', author: 'Inkeep' },
+ });
+ expect(second).toBe(first);
+ });
});
describe('withFences', () => {
diff --git a/packages/core/src/frontmatter/yaml-codec.ts b/packages/core/src/frontmatter/yaml-codec.ts
index 4292e608c..d29a8c7ef 100644
--- a/packages/core/src/frontmatter/yaml-codec.ts
+++ b/packages/core/src/frontmatter/yaml-codec.ts
@@ -1,9 +1,11 @@
import {
Document,
+ isMap,
isSeq,
type Pair,
parseDocument,
type ToStringOptions,
+ type YAMLMap,
type YAMLSeq,
} from 'yaml';
import { type FrontmatterMap, FrontmatterMapSchema, FrontmatterValueSchema } from './schema.ts';
@@ -14,11 +16,9 @@ export const STRINGIFY_OPTIONS: ToStringOptions = {
lineWidth: 0,
};
-export type ParsedFrontmatter = {
- doc: Document;
- map: FrontmatterMap | null;
- parseError?: string;
-};
+export type ParsedFrontmatter =
+ | { doc: Document; map: FrontmatterMap; parseError?: never }
+ | { doc: Document; map: null; parseError: string };
export function parseFrontmatterYaml(yaml: string): ParsedFrontmatter {
if (yaml.trim() === '') {
@@ -76,19 +76,31 @@ export function applyPatchToDocument(doc: Document, patch: Record<string, unknow
if (!result.success) {
throw new Error(`Invalid frontmatter value for "${key}": ${result.error.message}`);
}
- if (Array.isArray(result.data)) {
- const existing = doc.get(key, true);
- const existingFlow = isSeq(existing) ? (existing as YAMLSeq).flow : undefined;
- const newNode = doc.createNode(result.data) as YAMLSeq;
- if (existingFlow !== undefined) newNode.flow = existingFlow;
- doc.set(key, newNode);
- continue;
- }
- doc.set(key, result.data);
+ doc.set(key, buildValueNode(doc, doc.get(key, true), result.data));
}
return doc.toString(STRINGIFY_OPTIONS);
}
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+export function buildValueNode(doc: Document, existing: unknown, data: unknown): unknown {
+ if (Array.isArray(data)) {
+ const node = doc.createNode(data) as YAMLSeq;
+ const flow = isSeq(existing) ? (existing as YAMLSeq).flow : undefined;
+ if (flow !== undefined) node.flow = flow;
+ return node;
+ }
+ if (isPlainObject(data)) {
+ const node = doc.createNode(data) as YAMLMap;
+ const flow = isMap(existing) ? (existing as YAMLMap).flow : undefined;
+ if (flow !== undefined) node.flow = flow;
+ return node;
+ }
+ return data;
+}
+
export function withFences(yamlBody: string): string {
if (yamlBody === '') return '';
const trimmed = yamlBody.endsWith('\n') ? yamlBody.slice(0, -1) : yamlBody;
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5d97a741b..c55155a7b 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -3,6 +3,11 @@ export {
applyFastDiff,
applyIncrementalDiff,
applyPatchToFm,
+ applyPathDeleteToFm,
+ applyPathRenameToFm,
+ applyPathReorderSeqToFm,
+ applyPathReorderToFm,
+ applyPathSetToFm,
applyRenameToFm,
applyReorderToFm,
assertContentPreservation,
@@ -31,6 +36,8 @@ export {
type FrontmatterBinding,
type FrontmatterBindingPatchResult,
type FrontmatterBindingPatchSuccess,
+ type FrontmatterBindingPathResult,
+ type FrontmatterBindingPathSuccess,
type FrontmatterBindingRenameResult,
type FrontmatterBindingRenameSuccess,
type FrontmatterBindingReorderResult,
@@ -298,9 +305,11 @@ export {
FrontmatterTypeSchema,
type FrontmatterValue,
FrontmatterValueSchema,
+ frontmatterValuesEqual,
inferType,
isFrontmatterValueEmpty,
isIsoDateString,
+ RESERVED_FRONTMATTER_KEY,
} from './frontmatter/schema.ts';
export {
extractFrontmatterTags,
diff --git a/packages/server/src/api-agent-frontmatter.test.ts b/packages/server/src/api-agent-frontmatter.test.ts
index cc5db54a4..5142b4db8 100644
--- a/packages/server/src/api-agent-frontmatter.test.ts
+++ b/packages/server/src/api-agent-frontmatter.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, spyOn, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
@@ -827,3 +827,585 @@ describe('POST /api/agent-write-md (write_document) — malformed-FM refusal (PR
}
});
});
+
+describe('POST /api/agent-write-md (write_document) — nested frontmatter acceptance (PRD-6947)', () => {
+ test('replace with nested `metadata:` map succeeds; Y.Text reflects the nested structure', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ const skillFile = [
+ '---',
+ 'name: example-skill',
+ 'description: a one-line description',
+ 'metadata:',
+ ' version: 1.0.0',
+ ' author: Inkeep',
+ ' repository: https://github.com/example/repo',
+ '---',
+ '',
+ '# Body',
+ '',
+ ].join('\n');
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/agent-write-md',
+ { docName: 'test-doc', markdown: skillFile, position: 'replace' },
+ );
+
+ expect(response.status).toBe(200);
+ expect(fmMap(session.dc.document)).toEqual({
+ name: 'example-skill',
+ description: 'a one-line description',
+ metadata: {
+ version: '1.0.0',
+ author: 'Inkeep',
+ repository: 'https://github.com/example/repo',
+ },
+ });
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('replace with arbitrarily deep nesting succeeds', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ const deep = [
+ '---',
+ 'title: Deep',
+ 'metadata:',
+ ' outer:',
+ ' inner:',
+ ' leaf: deep-value',
+ '---',
+ '',
+ '# Body',
+ '',
+ ].join('\n');
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/agent-write-md',
+ { docName: 'test-doc', markdown: deep, position: 'replace' },
+ );
+
+ expect(response.status).toBe(200);
+ expect(fmMap(session.dc.document)).toEqual({
+ title: 'Deep',
+ metadata: { outer: { inner: { leaf: 'deep-value' } } },
+ });
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('replace with array-of-objects frontmatter succeeds', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ const arrayOfObjects = [
+ '---',
+ 'title: With Plugins',
+ 'plugins:',
+ ' - name: alpha',
+ ' version: 1.0',
+ ' - name: beta',
+ ' version: 2.0',
+ '---',
+ '',
+ '# Body',
+ '',
+ ].join('\n');
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/agent-write-md',
+ { docName: 'test-doc', markdown: arrayOfObjects, position: 'replace' },
+ );
+
+ expect(response.status).toBe(200);
+ expect(fmMap(session.dc.document)).toEqual({
+ title: 'With Plugins',
+ plugins: [
+ { name: 'alpha', version: 1.0 },
+ { name: 'beta', version: 2.0 },
+ ],
+ });
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('replace that adds a nested key to an existing doc succeeds (gate accepts the change)', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ session.dc.document.transact(() => {
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ '---\ntitle: Flat Start\n---\n# Body\n',
+ 'replace',
+ );
+ }, AGENT_WRITE_ORIGIN);
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/agent-write-md',
+ {
+ docName: 'test-doc',
+ markdown: '---\ntitle: Flat Start\nmetadata:\n version: 2.0\n---\n# Body\n',
+ position: 'replace',
+ },
+ );
+
+ expect(response.status).toBe(200);
+ expect(fmMap(session.dc.document)).toEqual({
+ title: 'Flat Start',
+ metadata: { version: 2.0 },
+ });
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('genuinely malformed YAML still returns the RFC-9457 envelope (PRD-6781 case preserved)', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/agent-write-md',
+ {
+ docName: 'test-doc',
+ markdown: '---\ntitle: The End of 3% Mortgages: Why the Lock-In Is Fading\n---\n# Body\n',
+ position: 'replace',
+ },
+ );
+
+ expect(response.status).toBe(400);
+ const parsed = JSON.parse(response.body);
+ expect(parsed.type).toBe('urn:ok:error:frontmatter-malformed');
+ expect(session.dc.document.getText('source').toString()).toBe('');
+ } finally {
+ await cleanup();
+ }
+ });
+});
+
+describe('POST /api/agent-write-md — telemetry refusal-class split (PRD-6947, Q-X7)', () => {
+ function collectRefusalEvents(
+ spy: ReturnType<typeof spyOn<typeof console, 'warn'>>,
+ ): Array<Record<string, unknown>> {
+ return spy.mock.calls
+ .map((call) => call[0])
+ .filter((arg): arg is string => typeof arg === 'string')
+ .map((arg) => {
+ try {
+ return JSON.parse(arg) as Record<string, unknown>;
+ } catch {
+ return null;
+ }
+ })
+ .filter(
+ (parsed): parsed is Record<string, unknown> =>
+ parsed !== null && parsed.event === 'frontmatter-malformed-write-refused',
+ );
+ }
+
+ test('yaml@2 parse error (PRD-6781 unquoted-colon) classifies as `yaml-parse-error`', async () => {
+ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ await sessionManager.getSession('test-doc');
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/agent-write-md',
+ {
+ docName: 'test-doc',
+ markdown: '---\ntitle: Foo: bar\n---\n# Body\n',
+ position: 'replace',
+ },
+ );
+
+ expect(response.status).toBe(400);
+ const events = collectRefusalEvents(warnSpy);
+ expect(events.length).toBe(1);
+ expect(events[0]?.class).toBe('yaml-parse-error');
+ expect(events[0]?.handler).toBe('agent-write-md');
+ } finally {
+ warnSpy.mockRestore();
+ await cleanup();
+ }
+ });
+
+ test('top-level array FM classifies as `non-mapping-top-level`', async () => {
+ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ await sessionManager.getSession('test-doc');
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/agent-write-md',
+ {
+ docName: 'test-doc',
+ markdown: '---\n- one\n- two\n---\n# Body\n',
+ position: 'replace',
+ },
+ );
+
+ expect(response.status).toBe(400);
+ const events = collectRefusalEvents(warnSpy);
+ expect(events.length).toBe(1);
+ expect(events[0]?.class).toBe('non-mapping-top-level');
+ } finally {
+ warnSpy.mockRestore();
+ await cleanup();
+ }
+ });
+
+ test('nested-but-valid frontmatter does NOT fire the refusal event (retired bucket)', async () => {
+ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ await sessionManager.getSession('test-doc');
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/agent-write-md',
+ {
+ docName: 'test-doc',
+ markdown:
+ '---\ntitle: Nested Skill\nmetadata:\n version: 1.0.0\n author: Inkeep\n---\n# Body\n',
+ position: 'replace',
+ },
+ );
+
+ expect(response.status).toBe(200);
+ const events = collectRefusalEvents(warnSpy);
+ expect(events.length).toBe(0);
+ } finally {
+ warnSpy.mockRestore();
+ await cleanup();
+ }
+ });
+});
+
+describe('POST /api/frontmatter-patch — nested value acceptance (PRD-6947)', () => {
+ test('nested-object patch value sets the subtree on a fresh doc; Y.Text reflects the nested YAML', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ session.dc.document.transact(() => {
+ applyAgentMarkdownWrite(session.dc.document, '# Body\n', 'replace');
+ }, AGENT_WRITE_ORIGIN);
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/frontmatter-patch',
+ {
+ docName: 'test-doc',
+ patch: { metadata: { version: '1.0.0', author: 'Inkeep' } },
+ },
+ );
+
+ expect(response.status).toBe(200);
+ const parsed = JSON.parse(response.body);
+ expect(parsed.appliedKeys).toEqual(['metadata']);
+ expect(fmMap(session.dc.document)).toEqual({
+ metadata: { version: '1.0.0', author: 'Inkeep' },
+ });
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('nested-object patch REPLACES the existing subtree at the top-level key (whole-subtree merge)', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ session.dc.document.transact(() => {
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ '---\ntitle: Skill\nmetadata:\n version: 1.0.0\n author: Inkeep\n license: MIT\n---\n# Body\n',
+ 'replace',
+ );
+ }, AGENT_WRITE_ORIGIN);
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/frontmatter-patch',
+ {
+ docName: 'test-doc',
+ patch: { metadata: { version: '2.0.0', author: 'Inkeep' } },
+ },
+ );
+
+ expect(response.status).toBe(200);
+ expect(fmMap(session.dc.document)).toEqual({
+ title: 'Skill',
+ metadata: { version: '2.0.0', author: 'Inkeep' },
+ });
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('top-level null deletes the nested subtree; sibling top-level keys preserved', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ session.dc.document.transact(() => {
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ '---\ntitle: Skill\nmetadata:\n version: 1.0.0\n author: Inkeep\n---\n# Body\n',
+ 'replace',
+ );
+ }, AGENT_WRITE_ORIGIN);
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/frontmatter-patch',
+ { docName: 'test-doc', patch: { metadata: null } },
+ );
+
+ expect(response.status).toBe(200);
+ expect(fmMap(session.dc.document)).toEqual({ title: 'Skill' });
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('array-of-objects patch value sets the array; per-item objects round-trip into Y.Text', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ session.dc.document.transact(() => {
+ applyAgentMarkdownWrite(session.dc.document, '# Body\n', 'replace');
+ }, AGENT_WRITE_ORIGIN);
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/frontmatter-patch',
+ {
+ docName: 'test-doc',
+ patch: {
+ plugins: [
+ { name: 'alpha', version: '1.0' },
+ { name: 'beta', version: '2.0' },
+ ],
+ },
+ },
+ );
+
+ expect(response.status).toBe(200);
+ expect(fmMap(session.dc.document)).toEqual({
+ plugins: [
+ { name: 'alpha', version: '1.0' },
+ { name: 'beta', version: '2.0' },
+ ],
+ });
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('arbitrarily deep nesting (map in map in map) is accepted and round-trips', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ session.dc.document.transact(() => {
+ applyAgentMarkdownWrite(session.dc.document, '# Body\n', 'replace');
+ }, AGENT_WRITE_ORIGIN);
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/frontmatter-patch',
+ {
+ docName: 'test-doc',
+ patch: { metadata: { outer: { inner: { leaf: 'deep-value' } } } },
+ },
+ );
+
+ expect(response.status).toBe(200);
+ expect(fmMap(session.dc.document)).toEqual({
+ metadata: { outer: { inner: { leaf: 'deep-value' } } },
+ });
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('flat patch behaves exactly as before (regression guard for the existing contract)', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ session.dc.document.transact(() => {
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ '---\ntitle: Original\n---\n# Body\n',
+ 'replace',
+ );
+ }, AGENT_WRITE_ORIGIN);
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/frontmatter-patch',
+ { docName: 'test-doc', patch: { title: 'Updated', tags: ['planning', 'q3'] } },
+ );
+
+ expect(response.status).toBe(200);
+ expect(fmMap(session.dc.document)).toEqual({
+ title: 'Updated',
+ tags: ['planning', 'q3'],
+ });
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('mixed flat + nested keys in one patch apply atomically', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ session.dc.document.transact(() => {
+ applyAgentMarkdownWrite(session.dc.document, '# Body\n', 'replace');
+ }, AGENT_WRITE_ORIGIN);
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/frontmatter-patch',
+ {
+ docName: 'test-doc',
+ patch: {
+ title: 'Skill',
+ tags: ['demo'],
+ metadata: { version: '1.0.0', author: 'Inkeep' },
+ },
+ },
+ );
+
+ expect(response.status).toBe(200);
+ expect(fmMap(session.dc.document)).toEqual({
+ title: 'Skill',
+ tags: ['demo'],
+ metadata: { version: '1.0.0', author: 'Inkeep' },
+ });
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('nested null inside a subtree (a deep-leaf delete) is rejected with per-key fieldErrors; Y.Doc untouched', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ session.dc.document.transact(() => {
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ '---\ntitle: Skill\nmetadata:\n version: 1.0.0\n author: Inkeep\n---\n# Body\n',
+ 'replace',
+ );
+ }, AGENT_WRITE_ORIGIN);
+
+ const beforeFm = ytextFm(session.dc.document);
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/frontmatter-patch',
+ {
+ docName: 'test-doc',
+ patch: { metadata: { version: null } },
+ },
+ );
+
+ expect(response.status).toBe(400);
+ const parsed = JSON.parse(response.body);
+ expect(parsed.type).toBe('urn:ok:error:invalid-request');
+ expect(ytextFm(session.dc.document)).toBe(beforeFm);
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('invalid nested leaf (function value) is rejected with per-key fieldErrors; Y.Doc untouched', async () => {
+ const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
+ try {
+ const session = await sessionManager.getSession('test-doc');
+
+ session.dc.document.transact(() => {
+ applyAgentMarkdownWrite(session.dc.document, '---\ntitle: Skill\n---\n# Body\n', 'replace');
+ }, AGENT_WRITE_ORIGIN);
+
+ const beforeFm = ytextFm(session.dc.document);
+
+ const response = await callApi(
+ hocuspocus,
+ sessionManager,
+ contentDir,
+ '/api/frontmatter-patch',
+ {
+ docName: 'test-doc',
+ patch: { frontmatter: { not: 'allowed' } },
+ },
+ );
+
+ expect(response.status).toBe(400);
+ const parsed = JSON.parse(response.body);
+ expect(parsed.type).toBe('urn:ok:error:invalid-frontmatter-patch');
+ expect(parsed.fieldErrors).toBeDefined();
+ expect(parsed.fieldErrors.frontmatter).toContain('reserved');
+ expect(ytextFm(session.dc.document)).toBe(beforeFm);
+ } finally {
+ await cleanup();
+ }
+ });
+});
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 7c9327acd..ec0dba032 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -1787,7 +1787,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const category = typeof map.category === 'string' ? map.category : undefined;
let tags: string[] | undefined;
if (Array.isArray(map.tags)) {
- tags = map.tags.length > 0 ? map.tags : undefined;
+ const stringTags = map.tags.filter(
+ (entry): entry is string => typeof entry === 'string',
+ );
+ tags = stringTags.length > 0 ? stringTags : undefined;
} else if (typeof map.tags === 'string' && map.tags) {
tags = [map.tags];
}
@@ -3521,6 +3524,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
case 'parse_failed':
fieldErrors = { __region__: `frontmatter region unparseable: ${editError.reason}` };
break;
+ case 'invalid_path':
+ fieldErrors = {
+ [editError.path.map(String).join('.') || '__path__']: editError.reason,
+ };
+ break;
default: {
const _exhaustive: never = editError;
fieldErrors = {
diff --git a/packages/server/src/frontmatter-malformed-error.test.ts b/packages/server/src/frontmatter-malformed-error.test.ts
new file mode 100644
index 000000000..d9eac38c3
--- /dev/null
+++ b/packages/server/src/frontmatter-malformed-error.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, test } from 'bun:test';
+import { classifyParseError } from './frontmatter-malformed-error.ts';
+
+describe('classifyParseError — bounded-cardinality refusal class', () => {
+ test('top-level non-mapping bucket', () => {
+ expect(classifyParseError('top-level value is not a mapping')).toBe('non-mapping-top-level');
+ });
+
+ test('schema rejection at a path', () => {
+ expect(classifyParseError('value at "metadata" failed schema: Invalid input')).toBe(
+ 'schema-rejection',
+ );
+ expect(classifyParseError('value at "" failed schema: Expected string')).toBe(
+ 'schema-rejection',
+ );
+ });
+
+ test('schema rejection at root', () => {
+ expect(classifyParseError('schema validation failed: Invalid input')).toBe('schema-rejection');
+ });
+
+ test('parse threw — bytes failed yaml@2 parse', () => {
+ expect(classifyParseError('parse threw: Unexpected token')).toBe('yaml-parse-error');
+ });
+
+ test('toJS threw — pathological document', () => {
+ expect(classifyParseError('toJS threw: circular reference')).toBe('yaml-parse-error');
+ });
+
+ test('yaml@2 free-form line/column message — unquoted-colon class (PRD-6781)', () => {
+ expect(
+ classifyParseError('Nested mappings are not allowed in compact mappings at line 2, column 7'),
+ ).toBe('yaml-parse-error');
+ expect(classifyParseError('Map keys must be unique at line 4, column 1')).toBe(
+ 'yaml-parse-error',
+ );
+ });
+
+ test('unknown fallback for the sentinel string', () => {
+ expect(classifyParseError('unknown YAML parse error')).toBe('unknown');
+ });
+
+ test('unknown fallback for the empty string', () => {
+ expect(classifyParseError('')).toBe('unknown');
+ });
+
+ test('classification is a bounded-cardinality enum (no path/byte content leaks)', () => {
+ const classes = new Set<string>();
+ for (const sample of [
+ 'top-level value is not a mapping',
+ 'value at "metadata.version" failed schema: Invalid',
+ 'value at "a.b.c.d.e.f.g.h" failed schema: Invalid',
+ 'schema validation failed: Invalid',
+ 'parse threw: anything',
+ 'toJS threw: anything',
+ 'Nested mappings are not allowed in compact mappings at line 9999, column 9999',
+ 'unknown YAML parse error',
+ '',
+ ]) {
+ classes.add(classifyParseError(sample));
+ }
+ expect(classes.size).toBeLessThanOrEqual(4);
+ for (const c of classes) {
+ expect([
+ 'yaml-parse-error',
+ 'non-mapping-top-level',
+ 'schema-rejection',
+ 'unknown',
+ ]).toContain(c);
+ }
+ });
+});
diff --git a/packages/server/src/frontmatter-malformed-error.ts b/packages/server/src/frontmatter-malformed-error.ts
index 262f42af3..bd376fed5 100644
--- a/packages/server/src/frontmatter-malformed-error.ts
+++ b/packages/server/src/frontmatter-malformed-error.ts
@@ -3,7 +3,7 @@ import { stripDocExtension } from './doc-extensions.ts';
import { errorResponse } from './http/error-response.ts';
const FIX_HINT =
- 'Frontmatter must be a flat mapping where each value is a string, number, boolean, or array of scalars. Quote string values containing YAML-significant characters (`:`, `#`, leading `-`), e.g. `title: "Foo: bar"`.';
+ 'Frontmatter must be a top-level YAML mapping. Quote string values containing YAML-significant characters (`:`, `#`, leading `-`), e.g. `title: "Foo: bar"`.';
export class FrontmatterMalformedError extends Error {
readonly file: string;
@@ -17,15 +17,37 @@ export class FrontmatterMalformedError extends Error {
}
}
+export type FrontmatterMalformedClass =
+ | 'yaml-parse-error'
+ | 'non-mapping-top-level'
+ | 'schema-rejection'
+ | 'unknown';
+
+export function classifyParseError(parseError: string): FrontmatterMalformedClass {
+ if (parseError === 'top-level value is not a mapping') return 'non-mapping-top-level';
+ if (parseError.startsWith('value at "') || parseError.startsWith('schema validation failed:')) {
+ return 'schema-rejection';
+ }
+ if (parseError.startsWith('parse threw:') || parseError.startsWith('toJS threw:')) {
+ return 'yaml-parse-error';
+ }
+ if (parseError.length > 0 && parseError !== 'unknown YAML parse error') {
+ return 'yaml-parse-error';
+ }
+ return 'unknown';
+}
+
export function respondFrontmatterMalformed(
res: ServerResponse,
err: FrontmatterMalformedError,
handler: string,
): void {
+ const refusalClass = classifyParseError(err.parseError);
console.warn(
JSON.stringify({
event: 'frontmatter-malformed-write-refused',
handler,
+ class: refusalClass,
'doc.name': stripDocExtension(err.file),
parseError: err.parseError,
}),
diff --git a/packages/server/src/mcp/tools/edit.ts b/packages/server/src/mcp/tools/edit.ts
index b534e81ed..ae06c7220 100644
--- a/packages/server/src/mcp/tools/edit.ts
+++ b/packages/server/src/mcp/tools/edit.ts
@@ -1,5 +1,9 @@
import { existsSync, readFileSync } from 'node:fs';
-import { renderInventoryFooter, stripFrontmatter } from '@inkeep/open-knowledge-core';
+import {
+ type FrontmatterPatch,
+ renderInventoryFooter,
+ stripFrontmatter,
+} from '@inkeep/open-knowledge-core';
import { parse as parseYaml } from 'yaml';
import { z } from 'zod';
import { resolveContentDir, resolveLockDir } from '../../config/paths.ts';
@@ -36,8 +40,6 @@ import {
TEMPLATE_PATH_DESCRIBE,
} from './verb-schemas.ts';
-type FrontmatterPatch = Record<string, string | number | boolean | string[] | null>;
-
const BASE_DESCRIPTION = [
'Edit one thing in place. Pass EXACTLY ONE of `document`, `folder`, or `template`. Within each: a body edit (`find` + `replace`) OR a `frontmatter` merge-patch — not both in one call.',
'',
diff --git a/packages/server/src/mcp/tools/verb-schemas.test.ts b/packages/server/src/mcp/tools/verb-schemas.test.ts
new file mode 100644
index 000000000..955873769
--- /dev/null
+++ b/packages/server/src/mcp/tools/verb-schemas.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, test } from 'bun:test';
+import { FrontmatterArg } from './verb-schemas.ts';
+
+describe('FrontmatterArg — recursive value contract (PRD-6947)', () => {
+ test('flat scalar values still parse (regression guard for the pre-PRD-6947 contract)', () => {
+ const result = FrontmatterArg.safeParse({
+ title: 'Q3 Planning',
+ done: true,
+ score: 0.95,
+ tags: ['planning', 'q3'],
+ });
+ expect(result.success).toBe(true);
+ });
+
+ test('nested-object value at a top-level key parses', () => {
+ const result = FrontmatterArg.safeParse({
+ metadata: { version: '1.0.0', author: 'Inkeep' },
+ });
+ expect(result.success).toBe(true);
+ });
+
+ test('arbitrarily deep nesting (map in map in map) parses', () => {
+ const result = FrontmatterArg.safeParse({
+ metadata: { outer: { inner: { leaf: 'deep' } } },
+ });
+ expect(result.success).toBe(true);
+ });
+
+ test('array-of-objects value parses; element objects pass through unchanged (NOT String()-coerced)', () => {
+ const input = {
+ plugins: [
+ { name: 'alpha', version: '1.0' },
+ { name: 'beta', version: '2.0' },
+ ],
+ };
+ const result = FrontmatterArg.safeParse(input);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data).toEqual(input);
+ }
+ });
+
+ test('top-level null parses (RFC 7396 delete sentinel preserved)', () => {
+ const result = FrontmatterArg.safeParse({ metadata: null });
+ expect(result.success).toBe(true);
+ });
+
+ test('nested null INSIDE a subtree is rejected (D9: wire stays additive, no path syntax)', () => {
+ const result = FrontmatterArg.safeParse({ metadata: { version: null } });
+ expect(result.success).toBe(false);
+ });
+
+ test('mixed flat + nested keys in one patch parse together', () => {
+ const result = FrontmatterArg.safeParse({
+ title: 'Skill',
+ tags: ['demo'],
+ metadata: { version: '1.0.0', author: 'Inkeep' },
+ });
+ expect(result.success).toBe(true);
+ });
+
+ test('description text reflects recursive value contract (no stale "flat mapping" claim)', () => {
+ const description = FrontmatterArg.description ?? '';
+ expect(description).toContain('nested');
+ expect(description).not.toContain('flat key→value');
+ });
+});
diff --git a/packages/server/src/mcp/tools/verb-schemas.ts b/packages/server/src/mcp/tools/verb-schemas.ts
index 9db368965..4fcec9287 100644
--- a/packages/server/src/mcp/tools/verb-schemas.ts
+++ b/packages/server/src/mcp/tools/verb-schemas.ts
@@ -6,9 +6,11 @@ const FrontmatterPatchValue = z.union([FrontmatterValueSchema, z.null()]);
export const FrontmatterArg = z
.record(z.string(), FrontmatterPatchValue)
.describe(
- 'Metadata as a flat key→value map (string | number | boolean | string[]). ' +
- 'Merge-patch: include a key to set it, set a key to null to delete it; keys you omit are unchanged. ' +
- 'Example: { title: "Q3 Planning", tags: ["planning"], status: "draft" }.',
+ 'Metadata as a key→value map. Values may be a scalar (string | number | boolean), a scalar array, ' +
+ 'a nested object, or an array of objects. Merge-patch: include a top-level key to set it, set a ' +
+ 'top-level key to null to delete it; keys you omit are unchanged. A nested object REPLACES the ' +
+ 'existing subtree at that key (send the full subtree you want). ' +
+ 'Example: { title: "Q3 Planning", tags: ["planning"], metadata: { version: "1.0", author: "Inkeep" } }.',
);
const POSITIONS = ['append', 'prepend', 'replace'] as const;
diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.ts
index 9cdff07cf..97c547310 100644
--- a/packages/server/src/mcp/tools/write.ts
+++ b/packages/server/src/mcp/tools/write.ts
@@ -1,6 +1,7 @@
import { existsSync, readFileSync } from 'node:fs';
import { resolve as resolvePath } from 'node:path';
import {
+ type FrontmatterPatch,
normalizeBridge,
renderInventoryFooter,
stripFrontmatter,
@@ -51,8 +52,6 @@ import {
TEMPLATE_PATH_DESCRIBE,
} from './verb-schemas.ts';
-type FrontmatterPatch = Record<string, string | number | boolean | string[] | null>;
-
const BASE_DESCRIPTION = [
'Create or replace one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, or `asset` (or `documents` for a batch of docs).',
'',
diff --git a/packages/server/src/page-identity.test.ts b/packages/server/src/page-identity.test.ts
index ca65fa48f..9073504a6 100644
--- a/packages/server/src/page-identity.test.ts
+++ b/packages/server/src/page-identity.test.ts
@@ -226,4 +226,9 @@ describe('extractPageIcon', () => {
const content = `---\nicon: ${exactlyAtCap}\n---\n`;
expect(extractPageIcon(content)).toBe(exactlyAtCap);
});
+
+ test('returns undefined when icon holds a nested map (graceful degradation)', () => {
+ const content = '---\nicon:\n url: https://example.com/img.png\n alt: example\n---\n';
+ expect(extractPageIcon(content)).toBeUndefined();
+ });
});