graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Add folder sorting and creation; list available RLM from the first turn
justrach8a4923d1c00a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 129f3e87..1405eb5f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,8 @@ current is part of cutting a release.## Unreleased+- The folder picker can sort by name or modification time, filter Git repositories, and create folders.+- Available `rlm` tools are listed from the first turn rather than waiting for a batch or context threshold (ADR 0140).- Desktop fonts are bundled locally; syntax highlighting, diagrams, and secondary panes load when needed.- Desktop appearance notes no longer alter slash commands. Clipboard image staging retries absolute paths through their parent directory when needed.- Resuming a saved conversation restores its persisted session identity even if startup already generated one.diff --git a/apps/native/app/api/workspaces/route.ts b/apps/native/app/api/workspaces/route.tsindex 438b9840..8a76d986 100644--- a/apps/native/app/api/workspaces/route.ts+++ b/apps/native/app/api/workspaces/route.ts@@ -1,8 +1,8 @@-import { existsSync, readdirSync, statSync } from "node:fs";+import { existsSync, mkdirSync, readdirSync, statSync } from "node:fs";import os from "node:os";import path from "node:path";import { NextRequest } from "next/server";-import { displayDirPath, joinDir } from "@/lib/folder-picker";+import { displayDirPath, folderNameError, HIDDEN_FOLDER_NAMES, joinDir } from "@/lib/folder-picker";import { defaultRoot, expandHome } from "@/lib/server-root";export const runtime = "nodejs";@@ -10,18 +10,19 @@ export const dynamic = "force-dynamic";/** Folder browser behind the "New workspace" picker: one directory level* at a time, folders only. Dot-folders and dependency trees are hidden —- * nobody makes `node_modules` a workspace — and git roots are marked so a- * repo stands out among its siblings. */+ * nobody makes `node_modules` a workspace — and git roots plus mtime are+ * marked so the client can sort by name, recency, or repos. */-const HIDDEN = new Set(["node_modules", "zig-out", "target", "__pycache__"]);+const HIDDEN = HIDDEN_FOLDER_NAMES;-export type FolderEntry = { name: string; path: string; git: boolean };+export type FolderEntry = { name: string; path: string; git: boolean; mtime: number };-function isDir(p: string): boolean {+function dirMtime(p: string): number | null {try {- return statSync(p).isDirectory();+ const st = statSync(p);+ return st.isDirectory() ? Math.round(st.mtimeMs) : null;} catch {- return false;+ return null;}}@@ -29,14 +30,21 @@ export async function GET(req: NextRequest) {const raw = req.nextUrl.searchParams.get("path");const home = os.homedir();const target = path.resolve(expandHome(raw && raw.trim() ? raw.trim() : home));- if (!isDir(target)) return Response.json({ error: `not a directory: ${target}` }, { status: 404 });+ if (dirMtime(target) == null) return Response.json({ error: `not a directory: ${target}` }, { status: 404 });try {const entries: FolderEntry[] = [];for (const entry of readdirSync(target, { withFileTypes: true })) {if (entry.name.startsWith(".") || HIDDEN.has(entry.name)) continue;+ if (entry.isFile()) continue;const full = path.join(target, entry.name);- if (!(entry.isDirectory() || (entry.isSymbolicLink() && isDir(full)))) continue;- entries.push({ name: entry.name, path: joinDir(target, entry.name), git: existsSync(path.join(full, ".git")) });+ const mtime = dirMtime(full);+ if (mtime == null) continue;+ entries.push({+ name: entry.name,+ path: joinDir(target, entry.name),+ git: existsSync(path.join(full, ".git")),+ mtime,+ });}entries.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));const parent = path.dirname(target);@@ -53,3 +61,37 @@ export async function GET(req: NextRequest) {return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 });}}++/** Create one folder in the listing currently on screen. */+export async function POST(req: NextRequest) {+ let body: { path?: unknown; name?: unknown };+ try {+ body = (await req.json()) as { path?: unknown; name?: unknown };+ } catch {+ return Response.json({ error: "expected json" }, { status: 400 });+ }+ if (!body || typeof body !== "object" || Array.isArray(body)) {+ return Response.json({ error: "expected an object" }, { status: 400 });+ }+ const name = typeof body.name === "string" ? body.name : "";+ const reason = folderNameError(name);+ if (reason) return Response.json({ error: reason }, { status: 400 });+ const label = name.trim();+ const parentRaw = typeof body.path === "string" ? body.path.trim() : "";+ const parent = path.resolve(expandHome(parentRaw || os.homedir()));+ if (dirMtime(parent) == null) return Response.json({ error: `not a directory: ${parent}` }, { status: 404 });+ const full = path.join(parent, label);+ if (path.dirname(full) !== parent) return Response.json({ error: "A folder name can't contain /." }, { status: 400 });+ if (existsSync(full)) return Response.json({ error: `already exists: ${label}` }, { status: 409 });+ try {+ mkdirSync(full);+ } catch (err) {+ const code = err && typeof err === "object" && "code" in err ? String((err as { code: unknown }).code) : "";+ if (code === "EEXIST") return Response.json({ error: `already exists: ${label}` }, { status: 409 });+ if (code === "EACCES" || code === "EPERM") {+ return Response.json({ error: `not allowed to create a folder here` }, { status: 403 });+ }+ return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 });+ }+ return Response.json({ ok: true, path: joinDir(parent, label), parent: displayDirPath(parent) });+}diff --git a/apps/native/components/site/FolderPicker.tsx b/apps/native/components/site/FolderPicker.tsxnew file mode 100644index 00000000..c1cb9913--- /dev/null+++ b/apps/native/components/site/FolderPicker.tsx@@ -0,0 +1,382 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import {+ cycleFolderSort,+ displayDirPath,+ folderNameError,+ formatFolderAge,+ formatFolderModified,+ loadFolderView,+ presentFolderEntries,+ sameBrowse,+ sameDir,+ saveFolderView,+ splitFolderQuery,+ uniqueFolderName,+ type FolderSort,+ type FolderView,+} from "@/lib/folder-picker";+import { browseFolders, createFolder, type FolderListing } from "@/lib/fs-client";+import { IconFolder, IconPlusMedium } from "@/lib/icons";+import { basename } from "@/lib/workspaces";++const FIELD =+ "h-8 w-full rounded-control bg-field px-2.5 text-[13px] text-ink shadow-hairline outline-none placeholder:text-ink-3 focus:bg-hover";++function Chip({+ active,+ onClick,+ children,+ title,+ pressed,+}: {+ active?: boolean;+ onClick: () => void;+ children: ReactNode;+ title?: string;+ pressed?: boolean;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ title={title}+ aria-pressed={pressed ?? active}+ className={`h-6 shrink-0 rounded-full px-2 text-[11.5px] font-medium transition-colors ${+ active ? "bg-hover-2 text-ink" : "bg-field text-ink-2 shadow-hairline hover:bg-hover hover:text-ink"+ }`}+ >+ {children}+ </button>+ );+}++function GitBadge() {+ return <span className="shrink-0 rounded-full bg-field px-1.5 font-mono text-[10px] text-ink-2 shadow-hairline">git</span>;+}++function sortTitle(sort: FolderSort, view: FolderView): string {+ if (sort === "name") {+ if (view.sort !== "name") return "Sort by name";+ return view.reverse ? "Sorted Z to A. Click for A to Z." : "Sorted A to Z. Click for Z to A.";+ }+ if (view.sort !== "modified") return "Sort by date modified";+ return view.reverse ? "Oldest first. Click for newest." : "Newest first. Click for oldest.";+}++export function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPick: (path: string) => void; onClose: () => void }) {+ const [listing, setListing] = useState<FolderListing | null>(null);+ const [typed, setTyped] = useState(displayDirPath(startPath ?? "~"));+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const [view, setView] = useState<FolderView>(() => loadFolderView(typeof localStorage === "undefined" ? null : localStorage));+ const [creating, setCreating] = useState<string | null>(null);+ // Only the newest navigation may land: a slow listing of a big folder+ // must not overwrite the one the user has already moved on to.+ const seq = useRef(0);+ const pickRef = useRef(onPick);+ pickRef.current = onPick;+ const creatingRef = useRef(false);+ const go = useCallback(async (target: string, opts: { pick?: boolean; refresh?: boolean } = {}) => {+ const n = (seq.current += 1);+ const refresh = opts.refresh === true;+ if (!refresh) setBusy(true);+ setError(null);+ try {+ const next = await browseFolders(target);+ if (n !== seq.current) return;+ setListing(next);+ if (!refresh) setTyped(displayDirPath(next.path));+ setError(null);+ if (opts.pick) pickRef.current(next.path);+ } catch (err) {+ if (n !== seq.current) return;+ if (!refresh) setError(err instanceof Error ? err.message : String(err));+ } finally {+ if (n === seq.current) setBusy(false);+ }+ }, []);+ useEffect(() => {+ void go(startPath ?? "~");+ return () => { seq.current++; };+ }, [go, startPath]);+ useEffect(() => {+ saveFolderView(typeof localStorage === "undefined" ? null : localStorage, view);+ }, [view]);++ const parsed = splitFolderQuery(typed, listing?.path);+ const listingPath = listing?.path ?? null;+ const listingHome = listing?.home ?? null;+ useEffect(() => {+ if (!listingPath || !parsed.browse) return;+ if (sameBrowse(parsed.browse, listingPath, listingHome)) return;+ void go(parsed.browse, { refresh: true });+ const request = seq.current;+ return () => { if (seq.current === request) seq.current++; };+ }, [go, listingHome, listingPath, parsed.browse]);+ useEffect(() => {+ setCreating(null);+ }, [listingPath]);+ const shown = useMemo(+ () => (listing ? presentFolderEntries(listing.entries, parsed.needle, view) : []),+ [listing, parsed.needle, view],+ );++ const crumbs = listing ? listing.path.split("/").filter(Boolean) : [];+ const crumbPath = (i: number) => `/${crumbs.slice(0, i + 1).join("/")}`;+ const home = listing?.home;+ const repo = listing?.default;++ const beginCreate = () => {+ if (!listing) return;+ const needle = parsed.needle.trim();+ const base = needle && folderNameError(needle) == null ? needle : "untitled folder";+ setView((current) => (current.gitOnly ? { ...current, gitOnly: false } : current));+ setCreating(uniqueFolderName(listing.entries.map((entry) => entry.name), base));+ setError(null);+ };++ const submitCreate = async () => {+ if (!listing || creating == null || creatingRef.current) return;+ const reason = folderNameError(creating);+ if (reason) {+ setError(reason);+ return;+ }+ creatingRef.current = true;+ setError(null);+ try {+ await createFolder(listing.path, creating);+ setCreating(null);+ await go(listing.path, { refresh: true });+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ creatingRef.current = false;+ }+ };++ return (+ <>+ <div className="flex shrink-0 flex-col gap-2 border-b border-line px-4 py-3">+ <form+ className="flex items-center gap-2"+ onSubmit={(event) => {+ event.preventDefault();+ void go(typed);+ }}+ >+ <span className="flex size-5 shrink-0 items-center justify-center text-ink-2">+ <IconFolder size={16} />+ </span>+ <input+ value={typed}+ onChange={(event) => {+ // Editing an explicit lookup retires it and makes the new path+ // actionable immediately, even if the old folder is still loading.+ if (busy) { seq.current++; setBusy(false); }+ setTyped(event.target.value); setError(null);+ }}+ spellCheck={false}+ autoFocus+ aria-label="Folder path"+ placeholder="/path/to/project"+ className={`${FIELD} font-mono text-[12.5px]`}+ />+ <button+ type="submit"+ className="h-8 shrink-0 rounded-[8px] bg-hover-2 px-3 text-[12.5px] font-medium text-ink transition-colors hover:bg-line-strong"+ >+ Go+ </button>+ </form>+ <div className="flex flex-wrap items-center gap-1.5 text-[11.5px] text-ink-3">+ <Chip onClick={() => void go("~")} active={sameDir(listing?.path, home)}>+ Home+ </Chip>+ {repo && (+ <Chip onClick={() => void go(repo)} active={sameDir(listing?.path, repo)}>+ {basename(repo)}+ </Chip>+ )}+ <span className="min-w-0 flex-1" />+ <div role="group" aria-label="Sort folders" className="flex items-center gap-1.5">+ <Chip+ active={view.sort === "name"}+ title={sortTitle("name", view)}+ onClick={() => setView((current) => cycleFolderSort(current, "name"))}+ >+ Name+ </Chip>+ <Chip+ active={view.sort === "modified"}+ title={sortTitle("modified", view)}+ onClick={() => setView((current) => cycleFolderSort(current, "modified"))}+ >+ Modified+ </Chip>+ </div>+ <Chip+ active={view.gitOnly}+ pressed={view.gitOnly}+ title={view.gitOnly ? "Showing git repositories. Click to show every folder." : "Only git repositories"}+ onClick={() => setView((current) => ({ ...current, gitOnly: !current.gitOnly }))}+ >+ Git+ </Chip>+ </div>+ </div>++ <div className="flex h-9 shrink-0 items-center gap-1 overflow-x-auto border-b border-line px-3 text-[12px] whitespace-nowrap text-ink-3 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">+ <button type="button" onClick={() => void go("/")} className="rounded px-1 py-0.5 font-medium transition-colors hover:bg-hover hover:text-ink">+ /+ </button>+ {crumbs.map((seg, i) => (+ <span key={crumbPath(i)} className="flex items-center gap-1">+ {i > 0 && <span className="text-line-strong">/</span>}+ <button+ type="button"+ onClick={() => void go(crumbPath(i))}+ className={`rounded px-1 py-0.5 transition-colors hover:bg-hover hover:text-ink ${i === crumbs.length - 1 ? "font-medium text-ink" : ""}`}+ >+ {seg}+ </button>+ </span>+ ))}+ {listing?.git && (+ <span className="ml-1">+ <GitBadge />+ </span>+ )}+ </div>++ <div className="min-h-0 flex-1 overflow-y-auto" style={{ minHeight: 200 }}>+ {busy && <p role="status" className="px-4 py-3 text-[12.5px] text-ink-3">Reading folder…</p>}+ {error && <p role="alert" className="px-4 py-3 text-[12.5px] text-red">{error}</p>}+ {!listing && !busy && !error && <p className="px-4 py-3 text-[12.5px] text-ink-3">Press Enter to browse, or open this folder directly.</p>}+ {listing && (+ <div className="flex flex-col px-2 py-1.5">+ {listing.parent && (+ <button+ type="button"+ onClick={() => void go(listing.parent as string)}+ className="flex h-8 items-center gap-2 rounded-[7px] px-2 text-left text-[13px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"+ >+ <span className="flex size-4 shrink-0 items-center justify-center">…</span>+ <span>Up one level</span>+ </button>+ )}+ {creating == null ? (+ <button+ type="button"+ disabled={busy}+ onClick={beginCreate}+ className="flex h-8 items-center gap-2 rounded-[7px] px-2 text-left text-[13px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink disabled:opacity-50"+ >+ <span className="flex size-4 shrink-0 items-center justify-center">+ <IconPlusMedium size={14} />+ </span>+ <span>New folder</span>+ </button>+ ) : (+ <form+ className="flex h-8 items-center gap-2 rounded-[7px] bg-hover px-2"+ onSubmit={(event) => {+ event.preventDefault();+ void submitCreate();+ }}+ >+ <span className="flex size-4 shrink-0 items-center justify-center text-ink-3">+ <IconFolder size={14} />+ </span>+ <input+ value={creating}+ onChange={(event) => {+ setCreating(event.target.value);+ setError(null);+ }}+ onKeyDown={(event) => {+ if (event.key !== "Escape") return;+ event.preventDefault();+ event.stopPropagation();+ setCreating(null);+ setError(null);+ }}+ onFocus={(event) => event.currentTarget.select()}+ onBlur={() => {+ if (!creatingRef.current) {+ setCreating(null);+ setError(null);+ }+ }}+ spellCheck={false}+ autoFocus+ aria-label="New folder name"+ className={`${FIELD} h-7 font-mono text-[12.5px]`}+ />+ </form>+ )}+ {shown.map((entry) => (+ <div+ key={entry.path}+ className="group flex h-8 items-center gap-2 rounded-[7px] px-2 transition-colors duration-100 hover:bg-hover"+ >+ <button+ type="button"+ onClick={() => void go(entry.path)}+ title={entry.path}+ className="flex min-w-0 flex-1 items-center gap-2 text-left"+ >+ <span className={`flex size-4 shrink-0 items-center justify-center ${entry.git ? "text-accent-ink" : "text-ink-3"}`}>+ <IconFolder size={14} />+ </span>+ <span className="min-w-0 flex-1 truncate text-[13px] text-ink">{entry.name}</span>+ </button>+ {view.sort === "modified" && entry.mtime > 0 && (+ <span className="shrink-0 font-mono text-[11px] text-ink-3 tabular-nums" title={formatFolderModified(entry.mtime)}>+ {formatFolderAge(entry.mtime)}+ </span>+ )}+ {entry.git && <GitBadge />}+ <button+ type="button"+ onClick={() => onPick(entry.path)}+ className="h-6 shrink-0 rounded-[6px] px-1.5 text-[11.5px] font-medium text-ink-3 opacity-0 transition-[opacity,background-color,color] duration-100 group-hover:opacity-100 hover:bg-hover-2 hover:text-ink focus:opacity-100"+ >+ Use+ </button>+ </div>+ ))}+ {shown.length === 0 && creating == null && (+ <p className="px-2 py-2 text-[12.5px] text-ink-3">+ {parsed.needle ? "No folders match this name." : view.gitOnly ? "No git folders here" : "No folders here"}+ </p>+ )}+ </div>+ )}+ </div>++ <div className="flex shrink-0 items-center gap-2 border-t border-line px-4 py-3">+ <span className="min-w-0 flex-1 truncate font-mono text-[11.5px] text-ink-3" title={listing ? displayDirPath(listing.path) : ""}>+ {listing ? displayDirPath(listing.path) : ""}+ </span>+ <button+ type="button"+ onClick={onClose}+ className="h-8 rounded-full px-3 text-[12.5px] font-medium text-ink-2 transition-colors hover:bg-hover hover:text-ink"+ >+ Cancel+ </button>+ <button+ type="button"+ disabled={!typed.trim() || busy}+ onClick={() => void go(typed, { pick: true })}+ className="h-8 rounded-full bg-ink px-3.5 text-[12.5px] font-medium text-canvas transition-opacity hover:opacity-90 disabled:opacity-50"+ >+ Open folder+ </button>+ </div>+ </>+ );+}diff --git a/apps/native/components/site/WorkspaceDialog.tsx b/apps/native/components/site/WorkspaceDialog.tsxindex 6a738872..bd18f9ac 100644--- a/apps/native/components/site/WorkspaceDialog.tsx+++ b/apps/native/components/site/WorkspaceDialog.tsx@@ -1,22 +1,22 @@"use client";-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { useLayoutEffect, useRef, useState, type ReactNode } from "react";import { createPortal } from "react-dom";import { Switch } from "@/components/atoms/Switch";import type { PromptModel } from "@/components/primitives/PromptBar";-import { displayDirPath, rankFolderEntries, sameBrowse, sameDir, splitFolderQuery } from "@/lib/folder-picker";-import { browseFolders, fsReveal, type FolderListing } from "@/lib/fs-client";-import { IconCrossSmall, IconFolder } from "@/lib/icons";+import { FolderPicker } from "@/components/site/FolderPicker";+import { fsReveal } from "@/lib/fs-client";+import { IconCrossSmall } from "@/lib/icons";import { basename, type Workspace } from "@/lib/workspaces";/* ─────────────────────────────────────────────────────────* WORKSPACE DIALOG* The two faces of the sidebar's workspace menu. "New workspace" walks* the machine's folders one level at a time (typed paths stay listed and- * fuzzy-ranked like /model) and hands back the folder graff should run in.- * "Workspace settings" edits- * how new tabs in a workspace spawn: its name, default model and whether- * tools are auto-approved.+ * fuzzy-ranked like /model; Name / Modified / Git chips reorder or hide+ * the list; New folder creates one in place) and hands back the folder+ * graff should run in. "Workspace settings" edits how new tabs in a+ * workspace spawn: its name, default model and whether tools are auto-approved.* ───────────────────────────────────────────────────────── */type Props = {@@ -100,7 +100,7 @@ function Frame({ title, onClose, children }: { title: string; onClose: () => voitabIndex={-1}aria-modal="true"aria-label={title}- className="flex w-full max-w-[560px] flex-col overflow-hidden rounded-[14px] bg-surface shadow-overlay"+ className="flex w-full max-w-[560px] flex-col overflow-hidden rounded-window bg-surface shadow-overlay"style={{ maxHeight: "min(680px, calc(100dvh - 32px))", animation: "pop-in 180ms cubic-bezier(0.23,1,0.32,1) both" }}><div className="flex h-11 shrink-0 items-center gap-2 border-b border-line px-4">@@ -121,221 +121,6 @@ function Frame({ title, onClose, children }: { title: string; onClose: () => voi);}-function Chip({ active, onClick, children }: { active?: boolean; onClick: () => void; children: ReactNode }) {- return (- <button- type="button"- onClick={onClick}- className={`h-6 shrink-0 rounded-full px-2 text-[11.5px] font-medium transition-colors ${- active ? "bg-hover-2 text-ink" : "bg-field text-ink-2 shadow-hairline hover:bg-hover hover:text-ink"- }`}- >- {children}- </button>- );-}--function GitBadge() {- return <span className="shrink-0 rounded-full bg-field px-1.5 font-mono text-[10px] text-ink-2 shadow-hairline">git</span>;-}--function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPick: (path: string) => void; onClose: () => void }) {- const [listing, setListing] = useState<FolderListing | null>(null);- const [typed, setTyped] = useState(displayDirPath(startPath ?? "~"));- const [error, setError] = useState<string | null>(null);- const [busy, setBusy] = useState(false);- // Only the newest navigation may land: a slow listing of a big folder- // must not overwrite the one the user has already moved on to.- const seq = useRef(0);- const pickRef = useRef(onPick);- pickRef.current = onPick;- const go = useCallback(async (target: string, opts: { pick?: boolean; refresh?: boolean } = {}) => {- const n = (seq.current += 1);- const refresh = opts.refresh === true;- if (!refresh) setBusy(true);- setError(null);- try {- const next = await browseFolders(target);- if (n !== seq.current) return;- setListing(next);- if (!refresh) setTyped(displayDirPath(next.path));- setError(null);- if (opts.pick) pickRef.current(next.path);- } catch (err) {- if (n !== seq.current) return;- if (!refresh) setError(err instanceof Error ? err.message : String(err));- } finally {- if (n === seq.current) setBusy(false);- }- }, []);- useEffect(() => {- void go(startPath ?? "~");- return () => { seq.current++; };- }, [go, startPath]);-- const parsed = splitFolderQuery(typed, listing?.path);- const listingPath = listing?.path ?? null;- const listingHome = listing?.home ?? null;- useEffect(() => {- if (!listingPath || !parsed.browse) return;- if (sameBrowse(parsed.browse, listingPath, listingHome)) return;- void go(parsed.browse, { refresh: true });- const request = seq.current;- return () => { if (seq.current === request) seq.current++; };- }, [go, listingHome, listingPath, parsed.browse]);- const shown = useMemo(- () => (listing ? rankFolderEntries(listing.entries, parsed.needle) : []),- [listing, parsed.needle],- );-- const crumbs = listing ? listing.path.split("/").filter(Boolean) : [];- const crumbPath = (i: number) => `/${crumbs.slice(0, i + 1).join("/")}`;- const home = listing?.home;- const repo = listing?.default;-- return (- <>- <div className="flex shrink-0 flex-col gap-2 border-b border-line px-4 py-3">- <form- className="flex items-center gap-2"- onSubmit={(event) => {- event.preventDefault();- void go(typed);- }}- >- <span className="flex size-5 shrink-0 items-center justify-center text-ink-2">- <IconFolder size={16} />- </span>- <input- value={typed}- onChange={(event) => {- // Editing an explicit lookup retires it and makes the new path- // actionable immediately, even if the old folder is still loading.- if (busy) { seq.current++; setBusy(false); }- setTyped(event.target.value); setError(null);- }}- spellCheck={false}- autoFocus- aria-label="Folder path"- placeholder="/path/to/project"- className={`${FIELD} font-mono text-[12.5px]`}- />- <button- type="submit"- className="h-8 shrink-0 rounded-[8px] bg-hover-2 px-3 text-[12.5px] font-medium text-ink transition-colors hover:bg-line-strong"- >- Go- </button>- </form>- <div className="flex items-center gap-1.5 text-[11.5px] text-ink-3">- <Chip onClick={() => void go("~")} active={sameDir(listing?.path, home)}>- Home- </Chip>- {repo && (- <Chip onClick={() => void go(repo)} active={sameDir(listing?.path, repo)}>- {basename(repo)}- </Chip>- )}- <span className="ml-1 min-w-0 flex-1 truncate">Pick the folder graff should read and edit.</span>- </div>- </div>-- <div className="flex h-9 shrink-0 items-center gap-1 overflow-x-auto border-b border-line px-3 text-[12px] whitespace-nowrap text-ink-3 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">- <button type="button" onClick={() => void go("/")} className="rounded px-1 py-0.5 font-medium transition-colors hover:bg-hover hover:text-ink">- /- </button>- {crumbs.map((seg, i) => (- <span key={crumbPath(i)} className="flex items-center gap-1">- {i > 0 && <span className="text-line-strong">/</span>}- <button- type="button"- onClick={() => void go(crumbPath(i))}- className={`rounded px-1 py-0.5 transition-colors hover:bg-hover hover:text-ink ${i === crumbs.length - 1 ? "font-medium text-ink" : ""}`}- >- {seg}- </button>- </span>- ))}- {listing?.git && (- <span className="ml-1">- <GitBadge />- </span>- )}- </div>-- <div className="min-h-0 flex-1 overflow-y-auto" style={{ minHeight: 200 }}>- {busy && <p role="status" className="px-4 py-3 text-[12.5px] text-ink-3">Reading folder…</p>}- {error && <p role="alert" className="px-4 py-3 text-[12.5px] text-red">{error}</p>}- {!listing && !busy && !error && <p className="px-4 py-3 text-[12.5px] text-ink-3">Press Enter to browse, or open this folder directly.</p>}- {listing && (- <div className="flex flex-col px-2 py-1.5">- {listing.parent && (- <button- type="button"- onClick={() => void go(listing.parent as string)}- className="flex h-8 items-center gap-2 rounded-[7px] px-2 text-left text-[13px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"- >- <span className="flex size-4 shrink-0 items-center justify-center">…</span>- <span>Up one level</span>- </button>- )}- {shown.map((entry) => (- <div- key={entry.path}- className="group flex h-8 items-center gap-2 rounded-[7px] px-2 transition-colors duration-100 hover:bg-hover"- >- <button- type="button"- onClick={() => void go(entry.path)}- title={entry.path}- className="flex min-w-0 flex-1 items-center gap-2 text-left"- >- <span className={`flex size-4 shrink-0 items-center justify-center ${entry.git ? "text-accent-ink" : "text-ink-3"}`}>- <IconFolder size={14} />- </span>- <span className="min-w-0 flex-1 truncate text-[13px] text-ink">{entry.name}</span>- </button>- {entry.git && <GitBadge />}- <button- type="button"- onClick={() => onPick(entry.path)}- className="h-6 shrink-0 rounded-[6px] px-1.5 text-[11.5px] font-medium text-ink-3 opacity-0 transition-[opacity,background-color,color] duration-100 group-hover:opacity-100 hover:bg-hover-2 hover:text-ink focus:opacity-100"- >- Use- </button>- </div>- ))}- {shown.length === 0 && (- <p className="px-2 py-2 text-[12.5px] text-ink-3">{parsed.needle ? "No folders match this name." : "No folders here"}</p>- )}- </div>- )}- </div>-- <div className="flex shrink-0 items-center gap-2 border-t border-line px-4 py-3">- <span className="min-w-0 flex-1 truncate font-mono text-[11.5px] text-ink-3" title={listing ? displayDirPath(listing.path) : ""}>- {listing ? displayDirPath(listing.path) : ""}- </span>- <button- type="button"- onClick={onClose}- className="h-8 rounded-full px-3 text-[12.5px] font-medium text-ink-2 transition-colors hover:bg-hover hover:text-ink"- >- Cancel- </button>- <button- type="button"- disabled={!typed.trim() || busy}- onClick={() => void go(typed, { pick: true })}- className="h-8 rounded-full bg-ink px-3.5 text-[12.5px] font-medium text-canvas transition-opacity hover:opacity-90 disabled:opacity-50"- >- Open folder- </button>- </div>- </>- );-}-function Field({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) {return (<label className="flex flex-col gap-1.5">diff --git a/apps/native/lib/folder-picker-route.test.ts b/apps/native/lib/folder-picker-route.test.tsnew file mode 100644index 00000000..46abdb7e--- /dev/null+++ b/apps/native/lib/folder-picker-route.test.ts@@ -0,0 +1,30 @@+import { test, expect } from "bun:test";+import { mkdtemp, mkdir, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { NextRequest } from "next/server";+import { GET, POST } from "../app/api/workspaces/route";++const create = (body: unknown) => POST(new NextRequest("http://localhost/api/workspaces", {+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),+}));++test("folder picker creates a directory, lists metadata, and refuses collisions and invalid names", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "folder-picker-route-"));+ try {+ const response = await create({ path: root, name: "new folder" });+ expect(response.status).toBe(200);+ expect((await response.json()).path).toBe(path.join(root, "new folder"));+ await mkdir(path.join(root, "new folder", ".git"));+ const listing = await GET(new NextRequest(`http://localhost/api/workspaces?${new URLSearchParams({ path: root })}`));+ const entry = (await listing.json()).entries[0];+ expect(entry.name).toBe("new folder");+ expect(entry.git).toBe(true);+ expect(entry.mtime).toBeGreaterThan(0);+ expect((await create({ path: root, name: "new folder" })).status).toBe(409);+ for (const name of ["", " ", "..", "../escape", "a/b", "a\\b", ".hidden", "node_modules"]) {+ expect((await create({ path: root, name })).status).toBe(400);+ }+ for (const body of [null, [], "folder"]) expect((await create(body)).status).toBe(400);+ } finally { await rm(root, { recursive: true, force: true }); }+});diff --git a/apps/native/lib/folder-picker.test.ts b/apps/native/lib/folder-picker.test.tsindex 9b7df9eb..782c2ad3 100644--- a/apps/native/lib/folder-picker.test.ts+++ b/apps/native/lib/folder-picker.test.ts@@ -1,6 +1,23 @@import { describe, it } from "node:test";import assert from "node:assert/strict";-import { displayDirPath, joinDir, rankFolderEntries, sameBrowse, sameDir, splitFolderQuery } from "./folder-picker.ts";+import {+ cycleFolderSort,+ DEFAULT_FOLDER_VIEW,+ displayDirPath,+ FOLDER_VIEW_KEY,+ folderNameError,+ formatFolderAge,+ joinDir,+ loadFolderView,+ parseFolderView,+ presentFolderEntries,+ rankFolderEntries,+ sameBrowse,+ sameDir,+ saveFolderView,+ splitFolderQuery,+ uniqueFolderName,+} from "./folder-picker.ts";describe("displayDirPath", () => {it("adds a single trailing separator and leaves root alone", () => {@@ -80,3 +97,101 @@ describe("rankFolderEntries", () => {assert.deepEqual(rankFolderEntries(entries, "zzz"), []);});});++describe("presentFolderEntries", () => {+ const entries = [+ { name: "zeta", path: "/demo/zeta", git: false, mtime: 400 },+ { name: "alpha", path: "/demo/alpha", git: true, mtime: 100 },+ { name: "beta", path: "/demo/beta", git: true, mtime: 300 },+ ];+ it("sorts by name or newest-modified, and git-only hides the rest", () => {+ assert.deepEqual(+ presentFolderEntries(entries, "", { sort: "name", reverse: false, gitOnly: false }).map((e) => e.name),+ ["alpha", "beta", "zeta"],+ );+ assert.deepEqual(+ presentFolderEntries(entries, "", { sort: "name", reverse: true, gitOnly: false }).map((e) => e.name),+ ["zeta", "beta", "alpha"],+ );+ assert.deepEqual(+ presentFolderEntries(entries, "", { sort: "modified", reverse: false, gitOnly: false }).map((e) => e.name),+ ["zeta", "beta", "alpha"],+ );+ assert.deepEqual(+ presentFolderEntries(entries, "", { sort: "modified", reverse: true, gitOnly: false }).map((e) => e.name),+ ["alpha", "beta", "zeta"],+ );+ assert.deepEqual(+ presentFolderEntries(entries, "", { sort: "name", reverse: false, gitOnly: true }).map((e) => e.name),+ ["alpha", "beta"],+ );+ });+ it("keeps fuzzy rank when a name is typed, still honoring git-only", () => {+ assert.deepEqual(+ presentFolderEntries(entries, "a", { sort: "modified", reverse: false, gitOnly: false }).map((e) => e.name),+ ["alpha", "zeta", "beta"],+ );+ assert.deepEqual(+ presentFolderEntries(entries, "a", { sort: "modified", reverse: false, gitOnly: true }).map((e) => e.name),+ ["alpha", "beta"],+ );+ });+});++describe("cycleFolderSort / folder view persistence", () => {+ it("selects a sort, then reverses on a second click", () => {+ const modified = cycleFolderSort(DEFAULT_FOLDER_VIEW, "modified");+ assert.deepEqual(modified, { sort: "modified", reverse: false, gitOnly: false });+ assert.deepEqual(cycleFolderSort(modified, "modified"), { sort: "modified", reverse: true, gitOnly: false });+ assert.deepEqual(cycleFolderSort(modified, "name"), { sort: "name", reverse: false, gitOnly: false });+ });+ it("loads a saved view and ignores junk", () => {+ const store = new Map<string, string>();+ const storage = {+ getItem: (k: string) => store.get(k) ?? null,+ setItem: (k: string, v: string) => void store.set(k, v),+ };+ assert.deepEqual(loadFolderView(storage), DEFAULT_FOLDER_VIEW);+ saveFolderView(storage, { sort: "modified", reverse: true, gitOnly: true });+ assert.equal(store.get(FOLDER_VIEW_KEY), JSON.stringify({ sort: "modified", reverse: true, gitOnly: true }));+ assert.deepEqual(loadFolderView(storage), { sort: "modified", reverse: true, gitOnly: true });+ assert.deepEqual(parseFolderView({ sort: "nope", reverse: "yes", gitOnly: 1 }), DEFAULT_FOLDER_VIEW);+ store.set(FOLDER_VIEW_KEY, "{");+ assert.deepEqual(loadFolderView(storage), DEFAULT_FOLDER_VIEW);+ });+});++describe("formatFolderAge", () => {+ const now = Date.parse("2026-04-01T12:00:00Z");+ it("prints a compact age and blanks missing timestamps", () => {+ assert.equal(formatFolderAge(now, now), "now");+ assert.equal(formatFolderAge(now - 12 * 60_000, now), "12m");+ assert.equal(formatFolderAge(now - 3 * 60 * 60_000, now), "3h");+ assert.equal(formatFolderAge(now - 2 * 24 * 60 * 60_000, now), "2d");+ assert.equal(formatFolderAge(now - 3 * 7 * 24 * 60 * 60_000, now), "3w");+ assert.equal(formatFolderAge(now - 5 * 30 * 24 * 60 * 60_000, now), "5mo");+ assert.equal(formatFolderAge(now - 2 * 365 * 24 * 60 * 60_000, now), "2y");+ assert.equal(formatFolderAge(0, now), "");+ });+});++describe("folderNameError / uniqueFolderName", () => {+ it("rejects empty, dot, path, hidden, and overlong names", () => {+ assert.equal(folderNameError(" "), "Name this folder.");+ assert.equal(folderNameError("."), "That name isn't allowed.");+ assert.equal(folderNameError(".."), "That name isn't allowed.");+ assert.equal(folderNameError("a/b"), "A folder name can't contain /.");+ assert.equal(folderNameError("a\\b"), "A folder name can't contain /.");+ assert.equal(folderNameError(".hidden"), "Dot-folders stay hidden in this list.");+ assert.equal(folderNameError("node_modules"), "That name stays hidden in this list.");+ assert.equal(folderNameError("ok"), null);+ assert.equal(folderNameError(" src "), null);+ assert.equal(folderNameError("x".repeat(256)), "That name is too long.");+ });+ it("adds a number when the default name is taken, case-insensitively", () => {+ assert.equal(uniqueFolderName([]), "untitled folder");+ assert.equal(uniqueFolderName(["untitled folder"]), "untitled folder 2");+ assert.equal(uniqueFolderName(["Untitled Folder", "untitled folder 2"]), "untitled folder 3");+ assert.equal(uniqueFolderName(["alpha"], "alpha"), "alpha 2");+ });+});diff --git a/apps/native/lib/folder-picker.ts b/apps/native/lib/folder-picker.tsindex febca8c9..586f40f1 100644--- a/apps/native/lib/folder-picker.ts+++ b/apps/native/lib/folder-picker.ts@@ -1,7 +1,8 @@-/** Path display and query-aware ranking for the Open a folder picker.+/** Path display, ranking and sort for the Open a folder picker.* Identity paths stay slash-stripped (`workspaces.normalizePath`); the field* and footer show a directory with a trailing `/` so the next segment is- * obvious. Ranking is the `/model` fuzzy score. */+ * obvious. Typing a name still ranks like `/model`; with an empty needle the+ * list follows Name / Modified (and an optional git-only filter). */import { fuzzyScore } from "./fuzzy.ts";@@ -66,9 +67,23 @@ export function splitFolderQuery(typed: string, current?: string | null): Folderreturn { browse: browse || "/", needle: t.slice(slash + 1) };}-export type RankableFolder = { name: string; path: string };+export type RankableFolder = { name: string; path: string; git?: boolean; mtime?: number };-/** Keep alpha order when the needle is empty; otherwise closest `/model`+export type FolderSort = "name" | "modified";++export type FolderView = {+ sort: FolderSort;+ /** Name: Z–A; Modified: oldest first. */+ reverse: boolean;+ gitOnly: boolean;+};++export const DEFAULT_FOLDER_VIEW: FolderView = { sort: "name", reverse: false, gitOnly: false };+export const FOLDER_VIEW_KEY = "graff.native.folder-picker.view";++const NAME_COLLATOR = { sensitivity: "base" } as const;++/** Keep directory order when the needle is empty; otherwise closest `/model`* match first. Non-matches drop out. */export function rankFolderEntries<T extends RankableFolder>(entries: readonly T[], needle: string): T[] {const q = needle.trim();@@ -83,3 +98,111 @@ export function rankFolderEntries<T extends RankableFolder>(entries: readonly T[scored.sort((a, b) => b.score - a.score || a.idx - b.idx);return scored.map((row) => row.item);}++export function parseFolderView(raw: unknown): FolderView {+ if (!raw || typeof raw !== "object") return { ...DEFAULT_FOLDER_VIEW };+ const rec = raw as Record<string, unknown>;+ return {+ sort: rec.sort === "modified" ? "modified" : "name",+ reverse: rec.reverse === true,+ gitOnly: rec.gitOnly === true,+ };+}++export function loadFolderView(storage: Pick<Storage, "getItem"> | null | undefined): FolderView {+ try {+ const raw = storage?.getItem(FOLDER_VIEW_KEY);+ if (!raw) return { ...DEFAULT_FOLDER_VIEW };+ return parseFolderView(JSON.parse(raw) as unknown);+ } catch {+ return { ...DEFAULT_FOLDER_VIEW };+ }+}++export function saveFolderView(storage: Pick<Storage, "setItem"> | null | undefined, view: FolderView): void {+ try {+ storage?.setItem(FOLDER_VIEW_KEY, JSON.stringify(view));+ } catch {+ /* private mode / full quota — the in-memory pick still applies this session */+ }+}++/** Cycle Name ↔ Modified; a second click on the active sort reverses it. */+export function cycleFolderSort(view: FolderView, sort: FolderSort): FolderView {+ if (view.sort === sort) return { ...view, reverse: !view.reverse };+ return { ...view, sort, reverse: false };+}++export function sortFolderEntries<T extends RankableFolder>(entries: readonly T[], sort: FolderSort): T[] {+ const out = [...entries];+ if (sort === "modified") {+ out.sort((a, b) => (b.mtime ?? 0) - (a.mtime ?? 0) || a.name.localeCompare(b.name, undefined, NAME_COLLATOR));+ } else {+ out.sort((a, b) => a.name.localeCompare(b.name, undefined, NAME_COLLATOR));+ }+ return out;+}++/** Git filter, then fuzzy rank when typing, else Name / Modified. */+export function presentFolderEntries<T extends RankableFolder>(+ entries: readonly T[],+ needle: string,+ view: FolderView,+): T[] {+ const filtered = view.gitOnly ? entries.filter((entry) => entry.git) : entries;+ if (needle.trim()) return rankFolderEntries(filtered, needle);+ const sorted = sortFolderEntries(filtered, view.sort);+ return view.reverse ? sorted.reverse() : sorted;+}++const MIN = 60_000;+const HOUR = 60 * MIN;+const DAY = 24 * HOUR;+const WEEK = 7 * DAY;+const MONTH = 30 * DAY;+const YEAR = 365 * DAY;++/** Compact age for the Modified column: `now`, `12m`, `3h`, `2d`, `3w`, `5mo`, `2y`. */+export function formatFolderAge(mtime: number, now = Date.now()): string {+ if (!Number.isFinite(mtime) || mtime <= 0) return "";+ const age = Math.max(0, now - mtime);+ if (age < MIN) return "now";+ if (age < HOUR) return `${Math.round(age / MIN)}m`;+ if (age < DAY) return `${Math.round(age / HOUR)}h`;+ if (age < WEEK) return `${Math.round(age / DAY)}d`;+ if (age < MONTH) return `${Math.round(age / WEEK)}w`;+ if (age < YEAR) return `${Math.round(age / MONTH)}mo`;+ return `${Math.round(age / YEAR)}y`;+}++export function formatFolderModified(mtime: number): string {+ if (!Number.isFinite(mtime) || mtime <= 0) return "";+ return new Date(mtime).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });+}++/** Names the folder list already hides — creating one would look like a no-op. */+export const HIDDEN_FOLDER_NAMES = new Set(["node_modules", "zig-out", "target", "__pycache__"]);++/** Why this can't be a new folder name, or `null` when it can. */+export function folderNameError(raw: string): string | null {+ const name = raw.trim();+ if (!name) return "Name this folder.";+ if (name === "." || name === "..") return "That name isn't allowed.";+ if (/[/\\]/.test(name) || name.includes("\0")) return "A folder name can't contain /.";+ if (name.startsWith(".")) return "Dot-folders stay hidden in this list.";+ if (HIDDEN_FOLDER_NAMES.has(name)) return "That name stays hidden in this list.";+ if (name.length > 255) return "That name is too long.";+ return null;+}++/** Finder-style `untitled folder`, `untitled folder 2`, … avoiding collisions. */+export function uniqueFolderName(existing: readonly string[], base = "untitled folder"): string {+ const seed = base.trim() || "untitled folder";+ const taken = new Set(existing.map((name) => name.toLowerCase()));+ if (!taken.has(seed.toLowerCase())) return seed;+ for (let n = 2; n < 1000; n += 1) {+ const name = `${seed} ${n}`;+ if (!taken.has(name.toLowerCase())) return name;+ }+ return `${seed} ${Date.now()}`;+}diff --git a/apps/native/lib/fs-client.test.ts b/apps/native/lib/fs-client.test.tsindex ca68630e..671f1583 100644--- a/apps/native/lib/fs-client.test.ts+++ b/apps/native/lib/fs-client.test.ts@@ -1,6 +1,6 @@import { test } from "node:test";import assert from "node:assert/strict";-import { fsOpen, fsReveal } from "./fs-client.ts";+import { createFolder, fsOpen, fsReveal } from "./fs-client.ts";async function withFetch(fetcher: typeof fetch, check: () => Promise<void>) {const original = globalThis.fetch;@@ -34,3 +34,20 @@ test("file actions report non-JSON HTTP failures and network failures", async ()await assert.rejects(fsOpen("notes.md"), /Connection lost/);});});++test("createFolder posts the parent and name and returns the new path", async () => {+ await withFetch(async (url, options) => {+ assert.equal(String(url), "/api/workspaces");+ assert.equal(options?.method, "POST");+ assert.deepEqual(JSON.parse(String(options?.body)), { path: "/Users/demo/", name: "untitled folder" });+ return new Response(JSON.stringify({ ok: true, path: "/Users/demo/untitled folder" }), { status: 200 });+ }, async () => {+ assert.deepEqual(await createFolder("/Users/demo/", "untitled folder"), { path: "/Users/demo/untitled folder" });+ });+});++test("createFolder surfaces the server explanation", async () => {+ await withFetch(async () => new Response(JSON.stringify({ error: "already exists: src" }), { status: 409 }), async () => {+ await assert.rejects(createFolder("/demo", "src"), /already exists: src/);+ });+});diff --git a/apps/native/lib/fs-client.ts b/apps/native/lib/fs-client.tsindex 87485103..8f8c45d4 100644--- a/apps/native/lib/fs-client.ts+++ b/apps/native/lib/fs-client.ts@@ -88,7 +88,7 @@ export async function gitFileDiff(path: string, root?: string): Promise<string>/* ── folder browser (New workspace) ── */-export type FolderEntry = { name: string; path: string; git: boolean };+export type FolderEntry = { name: string; path: string; git: boolean; mtime: number };export type FolderListing = {path: string;@@ -106,3 +106,16 @@ export async function browseFolders(path: string): Promise<FolderListing> {if (!res.ok) throw new Error(body.error ?? `workspaces ${res.status}`);return body;}++/** Create a folder inside `parent` (the listing currently on screen). */+export async function createFolder(parent: string, name: string): Promise<{ path: string }> {+ const res = await fetch("/api/workspaces", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ path: parent, name }),+ });+ const body = (await res.json().catch(() => null)) as { path?: string; error?: string } | null;+ if (!res.ok) throw new Error(body?.error ?? `Could not create this folder (${res.status}).`);+ if (!body?.path) throw new Error("Could not create this folder.");+ return { path: body.path };+}diff --git a/docs/adr/0030-rlm-late-showcase.md b/docs/adr/0030-rlm-late-showcase.mdindex 13f955dd..411011ed 100644--- a/docs/adr/0030-rlm-late-showcase.md+++ b/docs/adr/0030-rlm-late-showcase.md@@ -1,6 +1,6 @@# 0030. Hide `rlm` on small turns; showcase later (sPTC rides unfold)-Status: accepted 2026-08-25+Status: superseded 2026-09-12 by [0140](0140-rlm-is-listed-when-available.md)## Contextdiff --git a/docs/adr/0140-rlm-is-listed-when-available.md b/docs/adr/0140-rlm-is-listed-when-available.mdnew file mode 100644index 00000000..660e1434--- /dev/null+++ b/docs/adr/0140-rlm-is-listed-when-available.md@@ -0,0 +1,40 @@+# 0140. `rlm` is listed whenever it is available++Status: accepted++Supersedes [0030](0030-rlm-late-showcase.md).++## Context++ADR 0022 made `rlm` the default loop (`--old` restores structured-only).+ADR 0030 then hid it on small turns and only advertised it after `--rlm`,+a ≥4 native batch (`read_file` / `codedb` / `bash` / `webfetch`), context+≥50% of `compactAt`, or an explicit load.++The gate prevents first-turn discovery of the default loop and encourages+serial tool calls before batching is available. A batch-size check cannot+be how a default loop is discovered. ADR 0030 already named that failure+mode as the revisit condition.++#868 already put the spec on the catalog head when available. The leftover+0030 gates (`listed`, `noticeWideNative`, `noticeContext`) still treated+it as hidden. This record kills those gates.++## Decision++When `rlm` is available, it is on the root catalog from turn one — full+schema, no ≥N tool gate, no compactAt gate. `--old` / `--no-rlm` /+`GRAFF_OLD=1` / `GRAFF_RLM=0` still hide it. Do not splice+`rlm_spec.system_note` onto the prefix (ADR 0011). MCP fan-out still+does not change listing.++`noticeWideNative` and `noticeContext` remain as no-op call sites so+agent_tools / agent.zig do not churn; they must not be reintroduced as+gates.++## Consequences++First-turn catalogs already include the `rlm` spec (#868). One-shots can+call it without a warmup batch. Linear MCP structured paths still work;+they are not forced into `each()`. Do not hide `rlm` again because a+short task did not need it.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 5bb37ff7..93fb3fbb 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -40,7 +40,7 @@ record only when you need the evidence or the edge cases.| [0027](0027-kimi-identity-is-graff.md) | Kimi Coding User-Agent is `graff/<version>`, not a spoofed `kimi-code-cli` token. X-Msh device fields follow kimi-code's shapes. || [0028](0028-codex-session-id-is-the-cache-key.md) | Codex HTTP/WS `session_id` is the `prompt_cache_key` (openai/codex ModelClient default), not a per-process random UUID. || [0029](0029-mcp-inside-rlm-and-return-shapes.md) | Loaded MCP tools are rlm host functions; persist return shapes on the load result, never the prefix; fat MCP results auto-slim; default `-p` connects `.mcp.json` (folded, not skipped). |-| [0030](0030-rlm-late-showcase.md) | Small turns hide `rlm` (and sPTC). Showcase on `--rlm`, a ≥4 native batch, context ≥50% of compactAt, or an explicit load — never on MCP fan-out or the prefix. |+| [0030](0030-rlm-late-showcase.md) | Superseded by [0140](0140-rlm-is-listed-when-available.md). Late showcase hid `rlm` on small turns; that gate is gone. || [0031](0031-xai-hosted-x-search.md) | xAI Responses splices hosted `x_search` onto tools turns. It is not a catalog function; `GRAFF_XAI_X_SEARCH=0` opts out. || [0032](0032-acp-streams-mid-turn.md) | `graff acp` streams thought / tool / text `session/update`s mid-turn. The native app is an ACP client; it does not need `graff serve`. || [0033](0033-user-can-retire-a-standing-constraint.md) | Only the user retires a standing constraint: TTY `/never` picker (two confirms), ACP/`rm`, or an explicit override. The model cannot. |@@ -159,6 +159,7 @@ record only when you need the evidence or the edge cases.| [0137](0137-desktop-appearance-is-a-turn-note.md) | Desktop appearance tokens for `render_html` ride the turn, never the prefix or tool catalog; drawn HTML uses them unless the user named colors. || [0138](0138-unselected-splits-use-glass-overlay.md) | Unselected split panes keep their transcript under a light wash; the focused pane stays the working surface. || [0139](0139-bounced-answers-stay-turn-local.md) | Retain a bounced answer only in the current turn, before unfinished-work reconciliation; never recover it from persisted history. |+| [0140](0140-rlm-is-listed-when-available.md) | `rlm` is on the catalog whenever it is available. No batch-size or compactAt gate. `--old` still hides it. |## When to write onediff --git a/src/native_fold.zig b/src/native_fold.zigindex 897c81fd..b86ce916 100644--- a/src/native_fold.zig+++ b/src/native_fold.zig@@ -55,9 +55,9 @@ pub const folded = [_][]const u8{"agent_output","skill","webfetch",- // ADR 0022 / 0030: isFolded is false under --old so the structured-only- // load_tool_schemas listing stays byte-stable. The name stays hidden- // until listed() — small turns do not advertise rlm or sPTC.+ // ADR 0022 / 0140: isFolded is false under --old so the structured-only+ // catalog stays byte-stable. While available, rlm is on the catalog+ // from turn one — no batch-size or compactAt gate."rlm",};@@ -72,9 +72,8 @@ pub fn isFolded(name: []const u8) bool {return false;}-/// Session-discovered rlm (wide native batch or context threshold). `--rlm`-/// sets `g_cli_forced` so /new does not hide it again. Never set this-/// because MCP slims or a fat first payload.+/// `--rlm` sets `g_cli_forced` so /new keeps the schema loaded. Listing+/// itself follows `available` (ADR 0140), not a batch or compactAt gate.var g_showcased: bool = false;var g_cli_forced: bool = false;@@ -136,14 +135,10 @@ pub fn contextThreshold(compact_at: u64) ?u64 {return compact_at * pct / 100;}-/// True when this sample newly showcased rlm (caller rebuilds the catalog).-pub fn noticeContext(tokens: u64, compact_at: u64) bool {- if (listed() or !@import("rlm_spec.zig").available) return false;- const threshold = contextThreshold(compact_at) orelse return false;- if (tokens < threshold) return false;- showcaseRlm();- markLoaded("rlm");- return true;+/// Kept so callers in agent.zig still compile. ADR 0140: compactAt never+/// gates listing — rlm is already advertised when available.+pub fn noticeContext(_: u64, _: u64) bool {+ return false;}/// Lean/small turns hide rlm until a showcase. An explicit request for the@@ -165,9 +160,9 @@ pub fn noticeExplicit(text: []const u8) bool {return true;}-/// Folded-native listing and catalog discovery: hidden on small turns.+/// Folded-native listing: advertised whenever rlm is on (ADR 0140).pub fn listed() bool {- return g_showcased or isLoaded("rlm");+ return @import("rlm_spec.zig").available;}pub fn showcaseRlm() void {@@ -208,26 +203,10 @@ fn unmark(name: []const u8) void {}}-/// Host tools sPTC can overlap. MCP fan-out (Linear comments) must not-/// showcase — that re-invites the each() footgun (ADR 0029).-const wide_native = [_][]const u8{ "read_file", "codedb", "bash", "webfetch" };--/// True when this batch newly showcased rlm (caller rebuilds the catalog).-pub fn noticeWideNative(names: []const []const u8) bool {- if (listed() or !@import("rlm_spec.zig").available) return false;- var n: usize = 0;- for (names) |name| {- for (wide_native) |w| {- if (std.mem.eql(u8, name, w)) {- n += 1;- break;- }- }- }- if (n < 4) return false;- showcaseRlm();- markLoaded("rlm");- return true;+/// Kept so callers in agent_tools still compile. ADR 0140: a native batch+/// never gates listing — rlm is already advertised when available.+pub fn noticeWideNative(_: []const []const u8) bool {+ return false;}/// Whether the fold is live at all — hiddenSpec consults this so@@ -312,8 +291,8 @@ pub fn renderLoadedTail(s: *std.json.Stringify, kind: @import("provider.zig").Pr/// cache the mode exists to protect, #476).pub fn catalogSkips(name: []const u8) bool {if (!enabled) return false;- // #868: when rlm is on, keep it on the catalog so lean/explicit tasks can- // discover it without waiting for a 4-wide batch or --rlm. --old still hides.+ // ADR 0140: when rlm is on, keep it on the catalog so the first turn+ // can use it. --old still hides. No batch-size or compactAt gate.if (std.mem.eql(u8, name, "rlm") and @import("rlm_spec.zig").available) return false;if (mcp_schema_gate.g_stable_catalog) return isFolded(name);return blocked(name);@@ -541,3 +520,7 @@ test "explicit native loads rebuild the active provider catalog (#492)" {try std.testing.expectEqual(@as(usize, 1), agent.invalidations);try std.testing.expectEqual(@as(usize, 1), agent.rebuilds);}++test {+ _ = @import("native_fold_rlm.zig");+}diff --git a/src/native_fold_rlm.zig b/src/native_fold_rlm.zigindex 1787a194..dd416c45 100644--- a/src/native_fold_rlm.zig+++ b/src/native_fold_rlm.zig@@ -1,5 +1,5 @@-//! Late-showcase tests for folded `rlm` (ADR 0030). Split out of-//! native_fold.zig so that file stays under the 600-line ceiling.+//! Catalog tests for default `rlm` (ADR 0140). Split out of native_fold.zig+//! so that file stays under the 600-line ceiling.const std = @import("std");const fold = @import("native_fold.zig");@@ -27,9 +27,11 @@ test "rlm joins the fold only while available (off under --old)" {rlm_spec.available = false;try std.testing.expect(!fold.isFolded("rlm"));try std.testing.expect(!fold.blocked("rlm"));+ try std.testing.expect(!fold.listed());rlm_spec.available = true;try std.testing.expect(fold.isFolded("rlm"));+ try std.testing.expect(fold.listed());try std.testing.expect(fold.blocked("rlm"));fold.markLoaded("rlm");try std.testing.expect(fold.isLoaded("rlm"));@@ -70,6 +72,7 @@ test "folded rlm stays off the catalog when rlm is off; on lists it" {rlm.available = true;rlm.sync();try std.testing.expect(fold.isFolded("rlm"));+ try std.testing.expect(fold.listed());try std.testing.expect(!fold.catalogSkips("rlm"));const shown = try schema_mod.renderRootTools(arena, .openai, &with_rlm, &.{});try std.testing.expect(std.mem.indexOf(u8, shown, "rlm") != null);@@ -95,6 +98,7 @@ test "lean still lists rlm when it is available" {rlm.available = true;rlm.sync();try std.testing.expect(fold.isFolded("rlm"));+ try std.testing.expect(fold.listed());try std.testing.expect(!fold.catalogSkips("rlm"));var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);@@ -108,7 +112,7 @@ test "lean still lists rlm when it is available" {try std.testing.expect(std.mem.indexOf(u8, shown, rlm.tool_schema) != null);}-test "wide native batch showcases rlm; MCP fan-out does not" {+test "a four-wide native batch is not required to list rlm" {const saved_spec = rlm_spec.available;defer {rlm_spec.available = saved_spec;@@ -116,86 +120,46 @@ test "wide native batch showcases rlm; MCP fan-out does not" {}isolate();rlm_spec.available = true;-- try std.testing.expect(!fold.noticeWideNative(&.{ "read_file", "codedb", "bash" }));- try std.testing.expect(!fold.listed());- try std.testing.expect(!fold.noticeWideNative(&.{- "mcp__linear__list_comments",- "mcp__linear__list_comments",- "mcp__linear__list_comments",- "mcp__linear__list_comments",- }));- try std.testing.expect(!fold.listed());-- try std.testing.expect(fold.noticeWideNative(&.{ "read_file", "codedb", "bash", "webfetch" }));try std.testing.expect(fold.listed());- try std.testing.expect(fold.isLoaded("rlm"));-- fold.resetSession();- try std.testing.expect(!fold.listed());- try std.testing.expect(!fold.isLoaded("rlm"));-- fold.showcaseFromCli();- fold.resetSession();+ try std.testing.expect(!fold.noticeWideNative(&.{ "read_file", "codedb", "bash" }));+ try std.testing.expect(!fold.noticeWideNative(&.{ "read_file", "codedb", "bash", "webfetch" }));try std.testing.expect(fold.listed());}-test "context below 50% of compactAt does not showcase; crossing it does" {+test "MCP fan-out does not hide an available rlm" {const saved_spec = rlm_spec.available;defer {rlm_spec.available = saved_spec;fold.resetRlmDiscovery();- fold.resetContextKnob();}isolate();rlm_spec.available = true;-- // Default: 50% of compactAt. compactAt=8000 → threshold 4000.- try std.testing.expectEqual(@as(?u64, 4000), fold.contextThreshold(8000));- try std.testing.expect(!fold.noticeContext(0, 8000));- try std.testing.expect(!fold.noticeContext(3999, 8000));- try std.testing.expect(!fold.listed());-- try std.testing.expect(fold.noticeContext(4000, 8000));try std.testing.expect(fold.listed());- try std.testing.expect(fold.isLoaded("rlm"));- try std.testing.expect(!fold.noticeContext(8000, 8000)); // already showcased-- fold.resetSession();- try std.testing.expect(!fold.listed());- try std.testing.expect(!fold.isLoaded("rlm"));-- fold.g_context_off = true;- try std.testing.expect(!fold.noticeContext(8000, 8000));- try std.testing.expect(!fold.listed());+ try std.testing.expect(!fold.noticeWideNative(&.{+ "mcp__linear__list_comments",+ "mcp__linear__list_comments",+ "mcp__linear__list_comments",+ "mcp__linear__list_comments",+ }));+ try std.testing.expect(fold.listed());}-test "lean first turn and MCP fan-out stay below the context trigger" {+test "crossing 50% of compactAt does not change listing" {const saved_spec = rlm_spec.available;- const saved_lean = no_local.lean;defer {rlm_spec.available = saved_spec;- no_local.lean = saved_lean;fold.resetRlmDiscovery();fold.resetContextKnob();}isolate();rlm_spec.available = true;- no_local.lean = true;-- // A small -p prompt is nowhere near 50% of a real compactAt.- try std.testing.expect(!fold.noticeContext(800, 160_000));- try std.testing.expect(!fold.listed());- try std.testing.expect(!fold.noticeWideNative(&.{- "mcp__linear__list_comments",- "mcp__linear__list_comments",- "mcp__linear__list_comments",- "mcp__linear__list_comments",- }));- try std.testing.expect(!fold.listed());+ try std.testing.expect(fold.listed());+ try std.testing.expect(!fold.noticeContext(0, 8000));+ try std.testing.expect(!fold.noticeContext(4000, 8000));+ try std.testing.expect(fold.listed());}-test "showcasing rlm keeps the tools head bytes; schema rides the tail" {+test "available rlm stays in the catalog head without a late tail append" {const saved_avail = rlm.available;const saved_spec = rlm_spec.available;const saved_stable = mcp_schema_gate.g_stable_catalog;@@ -225,26 +189,25 @@ test "showcasing rlm keeps the tools head bytes; schema rides the tail" {.{ .name = rlm.tool_name, .desc = rlm.tool_desc, .schema = rlm.tool_schema },};- const before = try schema_mod.renderRootTools(arena, .openai, &specs, &.{});- try std.testing.expect(std.mem.indexOf(u8, before, "rlm") != null);- try std.testing.expect(std.mem.indexOf(u8, before, rlm.tool_schema) != null);-- try std.testing.expect(fold.noticeContext(50_000, 80_000));- const after = try schema_mod.renderRootTools(arena, .openai, &specs, &.{});- try std.testing.expectEqualStrings(before, after);-- fold.resetSession();- try std.testing.expect(!fold.listed());+ const first = try schema_mod.renderRootTools(arena, .openai, &specs, &.{});+ try std.testing.expect(std.mem.indexOf(u8, first, "rlm") != null);+ try std.testing.expect(std.mem.indexOf(u8, first, rlm.tool_schema) != null);+ try std.testing.expect(!fold.noticeContext(50_000, 80_000));+ const again = try schema_mod.renderRootTools(arena, .openai, &specs, &.{});+ try std.testing.expectEqualStrings(first, again);}-test "explicit rlm wording showcases without a context threshold" {- fold.resetRlmDiscovery();- defer fold.resetRlmDiscovery();+test "explicit rlm wording is not required to list rlm" {+ const saved_avail = rlm.available;+ defer {+ rlm.available = saved_avail;+ rlm.sync();+ fold.resetRlmDiscovery();+ }+ isolate();rlm.available = true;rlm.sync();+ try std.testing.expect(fold.listed());try std.testing.expect(!fold.noticeExplicit("summarize the architecture"));- try std.testing.expect(!fold.listed());- try std.testing.expect(fold.noticeExplicit("Keep persistent RLM bindings across two calls"));try std.testing.expect(fold.listed());- try std.testing.expect(fold.isLoaded("rlm"));}diff --git a/src/rlm.zig b/src/rlm.zigindex f64a497e..48d5bf4f 100644--- a/src/rlm.zig+++ b/src/rlm.zig@@ -64,10 +64,8 @@ pub fn feedLive(ctx: ToolCtx, delta: []const u8) void {rlm_spec.feedLive(ctx, delta);}-/// Append `rlm` after the lean/no-local filters so a later showcase can-/// put the spec on the catalog tail. Folded and unlisted until `--rlm`,-/// a wide native batch, context ≥50% of compactAt, or an explicit load-/// (ADR 0030). No-op when `--old` or embedder mode stripped host tools.+/// Append `rlm` after the lean/no-local filters. On by default from turn+/// one (ADR 0140). No-op when `--old` or embedder mode stripped host tools.pub fn maybeAppend(comptime Spec: type, arena: Allocator, specs: []const Spec) ![]const Spec {sync();if (!available or no_local_tools.enabled) return specs;diff --git a/src/session_catalog.zig b/src/session_catalog.zigindex 183b18bb..1f0390e6 100644--- a/src/session_catalog.zig+++ b/src/session_catalog.zig@@ -77,7 +77,7 @@ test "#867 session save load preserves the loaded catalog and clears legacy seletry tmp.dir.writeFile(io, .{ .sub_path = ".graff/sessions/catalog-legacy-867.session.json", .data = "{\"provider\":\"anthropic\",\"model\":\"sonnet\",\"messages\":[]}" });try session.loadSession(&root, &keys, arena, "catalog-legacy-867");try std.testing.expectEqual(@as(usize, 0), native.loadedNames().len);- try std.testing.expect(!native.listed());+ try std.testing.expectEqual(@import("rlm_spec.zig").available, native.listed());try std.testing.expect(!gate.isLoaded(tools[0].qualified_name));try std.testing.expect(!gate.isLoaded(tools[1].qualified_name));}@@ -127,7 +127,7 @@ test "#867 malformed catalog state resets selections and validates saved names"const saved = try std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{});try restore(&root, saved.object);try std.testing.expectEqual(@as(usize, 0), native.loadedNames().len);- try std.testing.expect(!native.listed());+ try std.testing.expectEqual(@import("rlm_spec.zig").available, native.listed());try std.testing.expectEqualStrings("", root.tools_anthropic);try std.testing.expect(!gate.isLoaded("mcp__missing__tool"));try std.testing.expect(!gate.isLoaded(tools[0].qualified_name));