graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Discover project folders from successful session saves
justrachde0d2f0d2f89
diff --git a/apps/native/app/api/workspace-history/route.ts b/apps/native/app/api/workspace-history/route.tsnew file mode 100644index 00000000..0714b965--- /dev/null+++ b/apps/native/app/api/workspace-history/route.ts@@ -0,0 +1,8 @@+import { NextRequest } from "next/server";+import { discoverWorkspaceHistory } from "@/lib/workspace-history";+import { defaultRoot } from "@/lib/server-root";+export const runtime = "nodejs";+export const dynamic = "force-dynamic";+export async function GET(req: NextRequest) {+ return Response.json({ workspaces: discoverWorkspaceHistory([defaultRoot(), ...req.nextUrl.searchParams.getAll("root").slice(0, 50)]) });+}diff --git a/apps/native/components/primitives/SidebarNav.tsx b/apps/native/components/primitives/SidebarNav.tsxindex de69a187..970b80e2 100644--- a/apps/native/components/primitives/SidebarNav.tsx+++ b/apps/native/components/primitives/SidebarNav.tsx@@ -93,7 +93,7 @@ type SidebarNavProps = {onWorkspaceSettings?: () => void;};-export type SidebarWorkspace = { path: string; name: string; source?: "saved" | "startup" };+export type SidebarWorkspace = { path: string; name: string; source?: "saved" | "startup" | "history" };const SIDEBAR_MOTION = {expandedWidth: 248,diff --git a/apps/native/components/primitives/WorkspaceMenu.tsx b/apps/native/components/primitives/WorkspaceMenu.tsxindex 2e0bd9b7..e5175600 100644--- a/apps/native/components/primitives/WorkspaceMenu.tsx+++ b/apps/native/components/primitives/WorkspaceMenu.tsx@@ -1,15 +1,15 @@'use client';import { useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';-import { monogram } from '@/lib/workspaces';-type Row={path:string;name:string;source?:"saved"|"startup"};+import { monogram, compareWorkspaceActivity, workspaceSourceLabel, type Workspace } from '@/lib/workspaces';+type Row = Workspace;export default function WorkspaceMenu({position,current,rows,onSwitch,onNew,onSettings,onClose}:{position:{top:number;left:number};current?:string;rows:Row[];onSwitch?:(path:string)=>void;onNew?:()=>void;onSettings?:()=>void;onClose:()=>void;}) {const [query,setQuery]=useState('');const input=useRef<HTMLInputElement>(null);const menu=useRef<HTMLDivElement>(null);const close=useRef(onClose);close.current=onClose;useEffect(()=>{const previous=document.activeElement as HTMLElement|null;input.current?.focus();const escape=(e:KeyboardEvent)=>{if(e.key==='Escape'){e.preventDefault();close.current();}};window.addEventListener('keydown',escape);return()=>{window.removeEventListener('keydown',escape);previous?.focus();};},[]);- const list=rows.filter(row=>`${row.name} ${row.path}`.toLowerCase().includes(query.toLowerCase())).sort((a,b)=>Number(b.path===current)-Number(a.path===current)||a.name.localeCompare(b.name));+ const list=rows.filter(row=>`${row.name} ${row.path}`.toLowerCase().includes(query.toLowerCase())).sort((a,b)=>Number(b.path===current)-Number(a.path===current)||compareWorkspaceActivity(a,b));const pick=(action?:()=>void)=>()=>{onClose();action?.();};const top=Math.min(position.top,Math.max(12,window.innerHeight-180));return createPortal(<div ref={menu} data-workspace-menu role="dialog" aria-label="Switch workspace"@@ -25,7 +25,7 @@ export default function WorkspaceMenu({position,current,rows,onSwitch,onNew,onSe{list.map(row=><button type="button" key={row.path} aria-current={row.path===current?'true':undefined} title={row.path} onClick={pick(()=>onSwitch?.(row.path))}className="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left hover:bg-hover focus-visible:bg-hover focus-visible:outline-none"><span aria-hidden className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-field text-xs text-ink-2">{monogram(row.name)}</span>- <span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium text-ink">{row.name}</span><span className="block truncate font-mono text-[10px] text-ink-3">{row.source==='startup'?'Startup folder':'Saved folder'} · {row.path}</span></span>+ <span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium text-ink">{row.name}</span><span className="block truncate font-mono text-[10px] text-ink-3">{workspaceSourceLabel(row)} · {row.path}</span></span>{row.path===current&&<span className="text-xs text-accent">Current</span>}</button>)}{!list.length&&<p className="p-3 text-sm text-ink-3">{query?'No matching workspaces.':'Open a folder to start a workspace.'}</p>}diff --git a/apps/native/components/site/ProjectsPane.tsx b/apps/native/components/site/ProjectsPane.tsxindex e9857206..df8566ba 100644--- a/apps/native/components/site/ProjectsPane.tsx+++ b/apps/native/components/site/ProjectsPane.tsx@@ -1,7 +1,7 @@"use client";import { useState } from "react";import { IconFolder, IconPlusMedium } from "@/lib/icons";-import type { Workspace } from "@/lib/workspaces";+import { compareWorkspaceActivity, workspaceSourceLabel, type Workspace } from "@/lib/workspaces";export default function ProjectsPane({ workspaces, current, onOpen, onContinue, onNewChat, onClose }: {workspaces: Workspace[]; current: string | null; onOpen: () => void;@@ -9,7 +9,7 @@ export default function ProjectsPane({ workspaces, current, onOpen, onContinue,onClose: () => void;}) {const [query, setQuery] = useState("");- const shown = workspaces.filter(w => `${w.name} ${w.path}`.toLowerCase().includes(query.toLowerCase()));+ const shown = workspaces.filter(w => `${w.name} ${w.path}`.toLowerCase().includes(query.toLowerCase())).sort(compareWorkspaceActivity);return <section aria-label="Projects" className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page"><header className="flex flex-wrap items-center justify-between gap-3 border-b border-line px-6 py-5"><div><h1 className="text-xl font-semibold text-ink">Projects</h1><p className="mt-1 text-sm text-ink-3">A project is a folder on your Mac. Your files stay there.</p></div>@@ -20,7 +20,7 @@ export default function ProjectsPane({ workspaces, current, onOpen, onContinue,<div className="grid gap-3 xl:grid-cols-2">{shown.map(w => <article key={w.path} data-project-path={w.path} className="min-w-0 rounded-[14px] border border-line bg-surface p-4"><div className="flex items-center gap-2 text-ink"><IconFolder size={19} /><h2 className="min-w-0 flex-1 truncate font-medium">{w.name}</h2>{w.path === current && <span className="text-xs text-accent">Current</span>}</div>- <p className="my-3 break-all font-mono text-xs text-ink-3">{w.path}</p>+ <p className="my-3 break-all font-mono text-xs text-ink-3">{workspaceSourceLabel(w)} · {w.path}</p><div className="flex flex-wrap gap-2"><button type="button" onClick={() => onContinue(w.path)} className="rounded-control bg-hover-2 px-3 py-2 text-sm text-ink">Continue conversation</button><button type="button" onClick={() => onNewChat(w.path)} className="rounded-control px-3 py-2 text-sm text-ink-2 hover:bg-hover">New chat</button>diff --git a/apps/native/components/site/useHarnessSessions.ts b/apps/native/components/site/useHarnessSessions.tsindex 9e5dd8b3..c6050c13 100644--- a/apps/native/components/site/useHarnessSessions.ts+++ b/apps/native/components/site/useHarnessSessions.ts@@ -4,7 +4,7 @@ import type { AcpCommand } from "@/lib/acp";import type { PromptModel } from "@/components/primitives/PromptBar";import { listSessionsPage, type StoredSession } from "@/lib/sessions";import { restoreProjects, persistProjects } from "@/lib/project-preferences";-import { findWorkspace, restoreWorkspaceSelection, type Workspace } from "@/lib/workspaces";+import { findWorkspace, mergeWorkspaceActivity, restoreWorkspaceSelection, type Workspace } from "@/lib/workspaces";import { newSessionName, type Chat } from "./harness-types";type Ref<T> = MutableRefObject<T>;type Setter<T> = Dispatch<SetStateAction<T>>;@@ -92,7 +92,17 @@ export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, workconst root = h.cwd ?? "";const savedProjects = await restoreProjects(window.localStorage);if (cancelled) return;- const { list, active } = restoreWorkspaceSelection(savedProjects.list, savedProjects.active, root);+ let { list, active } = restoreWorkspaceSelection(savedProjects.list, savedProjects.active, root);+ try {+ const query = new URLSearchParams();+ for (const row of savedProjects.list) query.append("root", row.path);+ const response = await fetch(`/api/workspace-history?${query}`, { signal: AbortSignal.timeout(5000) });+ if (response.ok) {+ const data = await response.json();+ if (Array.isArray(data.workspaces)) list = mergeWorkspaceActivity(list, data.workspaces);+ }+ } catch { /* Saved folder choices still work while history is unavailable. */ }+ if (cancelled) return;workspacesRef.current = list;activePathRef.current = active;setWorkspaces(list);diff --git a/apps/native/electron/frontend-runtime.cjs b/apps/native/electron/frontend-runtime.cjsindex 5938375f..27bd08d7 100644--- a/apps/native/electron/frontend-runtime.cjs+++ b/apps/native/electron/frontend-runtime.cjs@@ -8,6 +8,7 @@ const { installWindowState } = require('./window-state.cjs');const ui = path.resolve(__dirname, '..'), repo = path.resolve(ui, '../..');const output = path.resolve(process.env.GRAFF_FRONTEND_OUTPUT || path.join(repo, 'zig-out/frontend-tests'));const temp = process.argv[2];+const historyTest = process.env.GRAFF_WORKSPACE_HISTORY_TEST === '1';const htmlTool = process.env.GRAFF_HTML_TOOL_TEST === '1';assert.ok(temp, 'Launch through scripts/test-frontend.mjs for watchdog and cleanup');const workspace = path.join(temp, 'workspace');@@ -76,6 +77,7 @@ app.whenReady().then(async () => {{tool:'mcp__codegraff_desktop__create_html',arguments:{title:require('./html-tool-frontend.cjs').title,html:require('./html-tool-frontend.cjs').html}},{text:'Your inline explanation is ready.'},] : [+ ...(historyTest ? [{tool:'bash',arguments:{command:'printf history > terminal-proof.txt'}},{text:'Created terminal-proof.txt.'}] : []),{ tool: 'bash', arguments: { command: 'printf kept > proof.txt' } },{ http_status: 400, error: 'Scripted final request rejected' },{ tool: 'bash', arguments: { command: 'cat proof.txt' } },@@ -87,6 +89,17 @@ app.whenReady().then(async () => {assert.equal(model.exitCode, null, 'Scripted model could not start; port 1234 must be free');return fs.readFileSync(path.join(output, 'model.log'), 'utf8').includes('scripted model on');}, 'scripted model readiness');+ const terminalRoot = path.join(temp, 'terminal-project');+ if (historyTest) {+ fs.mkdirSync(terminalRoot);+ const fd = fs.openSync(path.join(output, 'terminal-session.log'), 'w');+ const terminal = spawn(binary, ['--model', 'lmstudio', '--new', '-p', 'Write history to terminal-proof.txt.'], { cwd: terminalRoot, env, stdio: ['ignore', fd, fd] });+ fs.closeSync(fd); children.push(terminal);+ await until(() => terminal.exitCode !== null, 'real terminal session completion', 25000);+ assert.equal(terminal.exitCode, 0);+ assert.ok(fs.readdirSync(path.join(temp, '.graff/workspace-history')).some(name => JSON.parse(fs.readFileSync(path.join(temp, '.graff/workspace-history', name), 'utf8')).path === fs.realpathSync(terminalRoot)), 'Actual successful terminal save registers its folder');+ fs.cpSync(path.join(terminalRoot, '.graff'), path.join(output, 'terminal-history-evidence'), { recursive: true });+ }const net = require('node:net'), probe = net.createServer();await new Promise(resolve => probe.listen(0, '127.0.0.1', resolve));const port = probe.address().port; await new Promise(resolve => probe.close(resolve));@@ -173,6 +186,16 @@ app.whenReady().then(async () => {await sleep(150);fs.writeFileSync(path.join(output, 'workspace-startup-source.png'), (await wc.capturePage()).toPNG());await click('[data-workspace-trigger]');+ if (historyTest) {+ await click('[data-workspace-trigger]');+ await until(() => js(`document.querySelector('[data-workspace-menu]')?.textContent.includes('terminal-project') && document.querySelector('[data-workspace-menu]')?.textContent.includes('Session history')`), 'terminal project discovered from actual save');+ await js(`new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))`);+ await sleep(150);+ fs.writeFileSync(path.join(output, 'workspace-terminal-history.png'), (await wc.capturePage()).toPNG());+ await click('[data-workspace-trigger]');+ assert.equal((await projects.load())?.list.some(row => row.path === terminalRoot), false, 'History suggestion is not a saved folder choice');+ report.passed.push('actual terminal prompt saves and registers its exact folder; GUI discovers it as session history without persisting a folder choice');+ }report.passed.push('startup workspace stays available with explicit provenance and is absent from durable project preferences');}if(htmlTool) return require('./html-tool-frontend.cjs').runHtmlTool({win,origin,output,temp,workspace,requests,send,click,until,report});@@ -192,7 +215,7 @@ app.whenReady().then(async () => {const saved = fs.readdirSync(path.join(workspace, '.graff/sessions')).filter(name => name.endsWith('.session.json'));assert.ok(saved.some(name => fs.readFileSync(path.join(workspace, '.graff/sessions', name), 'utf8').includes('kept')), 'Real session must preserve tool output');const calls = JSON.parse(fs.readFileSync(requests, 'utf8'));- assert.equal(calls.length, 4, 'Both turns must execute the scripted tool and terminal reply');+ assert.equal(calls.length, historyTest ? 6 : 4, 'Both turns must execute the scripted tool and terminal reply');assert.ok(JSON.stringify(calls.at(-1)).includes('kept'), 'Follow-up must receive retained tool output');fs.writeFileSync(path.join(output, 'follow-up-finished.png'), (await wc.capturePage()).toPNG());report.passed.push('typed follow-up, real saved history, finished status and frozen elapsed time');diff --git a/apps/native/lib/session-store.ts b/apps/native/lib/session-store.tsindex c11c4b41..81865260 100644--- a/apps/native/lib/session-store.ts+++ b/apps/native/lib/session-store.ts@@ -112,7 +112,7 @@ export function recoveredSessionTitle(title: unknown, messages: unknown): string// can be rewritten without changing that prefix (or the file's size).const legacyTitles = new Map<string, { version: string; title: string }>();-export function peekHeader(file: string, size: number): HeaderPeek {+export function peekHeader(file: string, size: number, recoverTitle = true): HeaderPeek {const fd = openSync(file, "r");try {const want = Math.min(size, PEEK_BYTES);@@ -124,7 +124,7 @@ export function peekHeader(file: string, size: number): HeaderPeek {let head = text.slice(0, idx).trimEnd();if (head.endsWith(",")) head = head.slice(0, -1);const header = JSON.parse(`${head}}`) as Header;- if (header.title !== "Untitled session" || size > MAX_FULL_BYTES) return header;+ if (!recoverTitle || header.title !== "Untitled session" || size > MAX_FULL_BYTES) return header;const stat = fstatSync(fd, { bigint: true });const version = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;const cached = legacyTitles.get(file);diff --git a/apps/native/lib/workspace-history.test.ts b/apps/native/lib/workspace-history.test.tsnew file mode 100644index 00000000..44916e9f--- /dev/null+++ b/apps/native/lib/workspace-history.test.ts@@ -0,0 +1,45 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, realpathSync, symlinkSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { createHash } from "node:crypto";+import { discoverWorkspaceHistory } from "./workspace-history";+import { mergeWorkspaceActivity, savedWorkspaceChoices, compareWorkspaceActivity } from "./workspaces";++test("history requires real saves, preserves exact roots, ranks activity and tolerates missing hints", () => {+ const home = realpathSync(mkdtempSync(path.join(os.tmpdir(), "workspace-history-")));+ try {+ const register = (root: string) => {+ mkdirSync(root, { recursive: true });+ const dir = path.join(home, ".graff/workspace-history"); mkdirSync(dir, { recursive: true });+ writeFileSync(path.join(dir, createHash("sha256").update(root).digest("hex") + ".json"), JSON.stringify({ version: 1, path: root }));+ };+ const save = (root: string, updated: number, archive = false) => {+ const dir = path.join(root, ".graff/sessions", archive ? "archived" : ""); mkdirSync(dir, { recursive: true });+ writeFileSync(path.join(dir, "one.session.json"), JSON.stringify({ updated_ms: updated, messages: [{ role: "user", content: "Hello" }] }));+ };+ const older = path.join(home, "repo/nested"), newer = path.join(home, "newer"), unused = path.join(home, "unused");+ register(older); register(newer); register(unused); save(older, 100); save(newer, 200, true);+ writeFileSync(path.join(home, ".graff/workspace-history", "f".repeat(64) + ".json"), "bad json");+ const alias = path.join(home, "alias"); symlinkSync(older, alias);+ assert.deepEqual(discoverWorkspaceHistory([alias], home), [{ path: newer, lastActivityMs: 200 }, { path: alias, lastActivityMs: 100 }]);+ rmSync(newer, { recursive: true });+ assert.deepEqual(discoverWorkspaceHistory([], home), [{ path: older, lastActivityMs: 100 }]);+ const oldKnown = path.join(home, "unregistered"); save(oldKnown, 300);+ assert.equal(discoverWorkspaceHistory([oldKnown], home)[0].path, oldKnown);+ } finally { rmSync(home, { recursive: true, force: true }); }+});++test("suggestions retain saved settings without consuming choices and sort by activity", () => {+ const saved = Array.from({ length: 50 }, (_, i) => ({ path: `/saved/${i}`, name: `Custom ${i}`, yolo: false }));+ const activity = [{ path: "/terminal-only", lastActivityMs: 300 }, { path: "/saved/0", lastActivityMs: 200 }];+ const result = mergeWorkspaceActivity(saved, activity);+ assert.equal(result.length, 51); assert.equal(savedWorkspaceChoices(result).length, 50);+ assert.equal(savedWorkspaceChoices(result)[0].lastActivityMs, undefined);+ assert.equal(result[0].name, "Custom 0"); assert.equal(result[0].yolo, false);+ assert.equal(result.toSorted(compareWorkspaceActivity)[0].path, "/terminal-only");+ assert.equal(result.find(row => row.path === "/terminal-only")?.source, "history");+ assert.equal(mergeWorkspaceActivity(result, activity).length, 51);+ assert.equal(mergeWorkspaceActivity([{ path: "/terminal-only", name: "terminal", source: "startup" }], activity)[0].source, "history");+});diff --git a/apps/native/lib/workspace-history.ts b/apps/native/lib/workspace-history.tsnew file mode 100644index 00000000..1b4fb9a5--- /dev/null+++ b/apps/native/lib/workspace-history.ts@@ -0,0 +1,60 @@+import { lstatSync, opendirSync, readFileSync, realpathSync, statSync } from "node:fs";+import path from "node:path";+import { homeDir, peekHeader, SESSION_EXT, SESSIONS_DIR } from "./session-store";++export type WorkspaceActivity = { path: string; lastActivityMs: number };++function entries(folder: string): string[] {+ const result: string[] = [];+ try {+ const dir = opendirSync(folder);+ try { for (let item; result.length < 4096 && (item = dir.readSync());) result.push(item.name); }+ finally { dir.closeSync(); }+ } catch { /* Missing or inaccessible history is not an app startup failure. */ }+ return result;+}++/** Registry entries are hints. Only an existing, readable session header makes+ * a folder an activity suggestion; never infer a parent repository. */+export function discoverWorkspaceHistory(known: string[] = [], home = homeDir()): WorkspaceActivity[] {+ const roots = new Set<string>();+ const knownNames = new Map<string, string>();+ for (const root of known) {+ try { if (path.isAbsolute(root)) knownNames.set(realpathSync(root), path.normalize(root)); } catch {}+ }+ const add = (value: unknown) => {+ if (typeof value !== "string" || !path.isAbsolute(value)) return;+ try { const canonical = realpathSync(value); if (statSync(canonical).isDirectory()) roots.add(canonical); } catch { /* removed folder */ }+ };+ for (const root of [home, ...known]) add(root);+ const registry = path.join(home, ".graff/workspace-history");+ for (const name of entries(registry)) {+ if (!/^[a-f0-9]{64}\.json$/.test(name)) continue;+ try {+ const file = path.join(registry, name), stat = lstatSync(file);+ if (!stat.isFile() || stat.size > 8192) continue;+ const row = JSON.parse(readFileSync(file, "utf8"));+ if (row.version === 1) add(row.path);+ } catch { /* Partial, obsolete and malformed hints are ignored. */ }+ }+ const rows: WorkspaceActivity[] = [];+ for (const root of roots) {+ let latest = 0;+ for (const folder of [path.join(root, SESSIONS_DIR), path.join(root, SESSIONS_DIR, "archived")]) {+ for (const name of entries(folder)) {+ if (!name.endsWith(SESSION_EXT)) continue;+ try {+ const file = path.join(folder, name), stat = lstatSync(file);+ if (!stat.isFile() || !stat.size) continue;+ const header = peekHeader(file, stat.size, false);+ if (!header) continue;+ const updated = typeof header.updated_ms === "number" && Number.isFinite(header.updated_ms) && header.updated_ms > 0+ ? header.updated_ms : stat.mtimeMs;+ latest = Math.max(latest, updated);+ } catch { /* A concurrent save/delete must not break other projects. */ }+ }+ }+ if (latest > 0) rows.push({ path: knownNames.get(root) ?? root, lastActivityMs: latest });+ }+ return rows.sort((a, b) => b.lastActivityMs - a.lastActivityMs || a.path.localeCompare(b.path));+}diff --git a/apps/native/lib/workspaces.ts b/apps/native/lib/workspaces.tsindex 6cb84fb6..66a4af75 100644--- a/apps/native/lib/workspaces.ts+++ b/apps/native/lib/workspaces.ts@@ -11,7 +11,8 @@ export type Workspace = {/** Absolute directory — the row's identity. */path: string;/** Startup context is visible, but is not a saved folder choice. */- source?: "saved" | "startup";+ source?: "saved" | "startup" | "history";+ lastActivityMs?: number;/** Display name; defaults to the folder's basename. */name: string;/** Model new tabs in this workspace spawn with; unset = the harness pick. */@@ -52,10 +53,10 @@ export function upsertWorkspace(list: readonly Workspace[], ws: Workspace, max =const next: Workspace = { ...ws, path, name };const idx = list.findIndex((w) => w.path === path);const out = idx >= 0 ? list.map((w, i) => (i === idx ? { ...w, ...next } : w)) : [...list, next];- const choices = out.filter(row => row.source !== "startup");+ const choices = out.filter(row => row.source !== "startup" && row.source !== "history");if (choices.length <= max) return out;const keep = new Set(choices.slice(-max).map(row => row.path));- return out.filter(row => row.source === "startup" || keep.has(row.path));+ return out.filter(row => row.source === "startup" || row.source === "history" || keep.has(row.path));}export function removeWorkspace(list: readonly Workspace[], path: string): Workspace[] {@@ -79,7 +80,8 @@ export function restoreWorkspaceSelection(saved: readonly Workspace[], remembere}export function savedWorkspaceChoices(list: readonly Workspace[]): Workspace[] {- return list.filter(row => row.source !== "startup").slice(-WORKSPACES_MAX);+ return list.filter(row => row.source !== "startup" && row.source !== "history").slice(-WORKSPACES_MAX)+ .map(({ lastActivityMs: _activity, ...choice }) => choice);}type ReadStore = Pick<Storage, "getItem">;@@ -134,3 +136,22 @@ export function shellQuote(p: string): string {if (/^[A-Za-z0-9_./~@:+=-]+$/.test(p)) return p;return `'${p.replace(/'/g, "'\\''")}'`;}++/** Suggestions never overwrite deliberate folder names/settings or consume their limit. */+export function mergeWorkspaceActivity(list: readonly Workspace[], activity: readonly { path: string; lastActivityMs: number }[]): Workspace[] {+ const rows = list.map(row => ({ ...row }));+ for (const item of activity) {+ if (!item.path || !Number.isFinite(item.lastActivityMs) || item.lastActivityMs <= 0) continue;+ const path = normalizePath(item.path), existing = rows.find(row => row.path === path);+ if (existing) { existing.lastActivityMs = item.lastActivityMs; if (existing.source === "startup") existing.source = "history"; }+ else rows.push({ path, name: basename(path), source: "history", lastActivityMs: item.lastActivityMs });+ }+ return rows;+}++export function workspaceSourceLabel(row: Pick<Workspace, "source">): string {+ return row.source === "history" ? "Session history" : row.source === "startup" ? "Startup folder" : "Saved folder";+}+export function compareWorkspaceActivity(a: Workspace, b: Workspace): number {+ return (b.lastActivityMs ?? 0) - (a.lastActivityMs ?? 0) || a.name.localeCompare(b.name);+}diff --git a/apps/native/package.json b/apps/native/package.jsonindex 1e642be9..8ea97cc0 100644--- a/apps/native/package.json+++ b/apps/native/package.json@@ -47,7 +47,8 @@"test:html-tool": "GRAFF_HTML_TOOL_TEST=1 bun scripts/test-frontend.mjs","test:cli": "GRAFF_CLI_TEST=1 bun scripts/test-frontend.mjs","install:cli": "bun scripts/install-cli.mjs",- "test:packaged-html": "bun scripts/test-packaged-html.mjs"+ "test:packaged-html": "bun scripts/test-packaged-html.mjs",+ "test:workspace-history": "GRAFF_WORKSPACE_HISTORY_TEST=1 bun scripts/test-frontend.mjs"},"dependencies": {"@streamdown/code": "^1.1.1",diff --git a/docs/adr/0080-desktop-projects-are-folders.md b/docs/adr/0080-desktop-projects-are-folders.mdindex 93a0fc23..05828b2f 100644--- a/docs/adr/0080-desktop-projects-are-folders.md+++ b/docs/adr/0080-desktop-projects-are-folders.md@@ -26,6 +26,15 @@ the saved-list limit. Opening a folder or saving its settings records a choice.Existing preferences without source metadata remain saved entries; theirpresence alone is not evidence of earlier session activity.+Successful session saves also register their exact canonical working folder in+an atomic, private device-local lookup record. The GUI verifies readable session+headers before offering a folder as Session history, ordered by saved activity.+Hints neither promote parent repositories nor authorize deleting any files.+History suggestions and derived activity timestamps do not enter saved choices.+Existing sessions in known folders are checked without a registry record; an+older terminal-only folder outside known roots becomes discoverable on its next+successful save. We do not recursively scan the user's filesystem at startup.+## ValidationThe project-store test covers restart persistence and ordered writes. The offlinediff --git a/src/main.zig b/src/main.zigindex 3d1ac9ca..34c349fb 100644--- a/src/main.zig+++ b/src/main.zig@@ -596,5 +596,5 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("subagent_recovery.zig");_ = @import("acp_agent_activity.zig");_ = @import("read_image.zig");- _ = @import("mcp_names.zig");+ _ = .{ @import("mcp_names.zig"), @import("workspace_history.zig") };}diff --git a/src/session.zig b/src/session.zigindex b2c70487..17962533 100644--- a/src/session.zig+++ b/src/session.zig@@ -360,7 +360,7 @@ fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64// #273: it does that on its own thread, and owns these bytes from here.const path = try root.gpa.dupe(u8, rel);errdefer root.gpa.free(path); // only reachable if toOwnedSlice fails: submit owns both- return session_writer.submit(root.gpa, root.io, dir, path, try aw.toOwnedSlice(), fp);+ return session_writer.submitInHome(root.gpa, root.io, dir, path, try aw.toOwnedSlice(), fp, root.home);}/// Parse the persisted `goal` field into a structured Goal (#223). A bare stringdiff --git a/src/session_fingerprint.zig b/src/session_fingerprint.zignew file mode 100644index 00000000..5c833dbd--- /dev/null+++ b/src/session_fingerprint.zig@@ -0,0 +1,66 @@+//! Content fingerprint shared by the session serializer and writer.+const std = @import("std");+const Value = std.json.Value;++/// A digest of everything the session file records about the conversation.+/// Content-derived, so a skip can never be wrong about "nothing changed" the+/// way a hand-maintained dirty flag can: the history has ~25 production+/// mutation sites (appends, compaction rewrites, in-place repairs), and one+/// missed site would silently drop a turn from disk.+pub const Fingerprint = struct {+ h: std.hash.Wyhash,++ pub fn init() Fingerprint {+ return .{ .h = std.hash.Wyhash.init(0x2735e5510) };+ }++ pub fn num(self: *Fingerprint, v: u64) void {+ var le: [8]u8 = undefined;+ std.mem.writeInt(u64, &le, v, .little);+ self.h.update(&le);+ }++ pub fn signed(self: *Fingerprint, v: i64) void {+ self.num(@bitCast(v));+ }++ pub fn flag(self: *Fingerprint, v: bool) void {+ self.h.update(&[_]u8{@intFromBool(v)});+ }++ /// Length-prefixed: "ab"+"c" must not collide with "a"+"bc".+ pub fn text(self: *Fingerprint, s: []const u8) void {+ self.num(s.len);+ self.h.update(s);+ }++ /// The same tree std.json.Stringify would walk, digested instead of+ /// formatted. Object fields are hashed in insertion order, which is the+ /// order they are serialized in.+ pub fn json(self: *Fingerprint, v: Value) void {+ self.h.update(&[_]u8{@intFromEnum(std.meta.activeTag(v))});+ switch (v) {+ .null => {},+ .bool => |b| self.flag(b),+ .integer => |i| self.signed(i),+ .float => |f| self.num(@bitCast(f)),+ .number_string, .string => |s| self.text(s),+ .array => |a| {+ self.num(a.items.len);+ for (a.items) |item| self.json(item);+ },+ .object => |o| {+ self.num(o.count());+ var it = o.iterator();+ while (it.next()) |e| {+ self.text(e.key_ptr.*);+ self.json(e.value_ptr.*);+ }+ },+ }+ }++ pub fn final(self: *Fingerprint) u64 {+ return self.h.final();+ }+};diff --git a/src/session_writer.zig b/src/session_writer.zigindex 4978d162..ea7453a9 100644--- a/src/session_writer.zig+++ b/src/session_writer.zig@@ -62,68 +62,7 @@ const Value = std.json.Value;const session_lock = @import("session_lock.zig");-/// A digest of everything the session file records about the conversation.-/// Content-derived, so a skip can never be wrong about "nothing changed" the-/// way a hand-maintained dirty flag can: the history has ~25 production-/// mutation sites (appends, compaction rewrites, in-place repairs), and one-/// missed site would silently drop a turn from disk.-pub const Fingerprint = struct {- h: std.hash.Wyhash,-- pub fn init() Fingerprint {- return .{ .h = std.hash.Wyhash.init(0x2735e5510) };- }-- pub fn num(self: *Fingerprint, v: u64) void {- var le: [8]u8 = undefined;- std.mem.writeInt(u64, &le, v, .little);- self.h.update(&le);- }-- pub fn signed(self: *Fingerprint, v: i64) void {- self.num(@bitCast(v));- }-- pub fn flag(self: *Fingerprint, v: bool) void {- self.h.update(&[_]u8{@intFromBool(v)});- }-- /// Length-prefixed: "ab"+"c" must not collide with "a"+"bc".- pub fn text(self: *Fingerprint, s: []const u8) void {- self.num(s.len);- self.h.update(s);- }-- /// The same tree std.json.Stringify would walk, digested instead of- /// formatted. Object fields are hashed in insertion order, which is the- /// order they are serialized in.- pub fn json(self: *Fingerprint, v: Value) void {- self.h.update(&[_]u8{@intFromEnum(std.meta.activeTag(v))});- switch (v) {- .null => {},- .bool => |b| self.flag(b),- .integer => |i| self.signed(i),- .float => |f| self.num(@bitCast(f)),- .number_string, .string => |s| self.text(s),- .array => |a| {- self.num(a.items.len);- for (a.items) |item| self.json(item);- },- .object => |o| {- self.num(o.count());- var it = o.iterator();- while (it.next()) |e| {- self.text(e.key_ptr.*);- self.json(e.value_ptr.*);- }- },- }- }-- pub fn final(self: *Fingerprint) u64 {- return self.h.final();- }-};+pub const Fingerprint = @import("session_fingerprint.zig").Fingerprint;const Job = struct {io: Io,@@ -131,12 +70,14 @@ const Job = struct {path: []u8,data: []u8,fp: u64,+ home: ?[]u8 = null,/// The `submit` that queued this job — see `errorFor`.ticket: u64,fn deinit(job: Job, gpa: Allocator) void {gpa.free(job.path);gpa.free(job.data);+ if (job.home) |home| gpa.free(home);}};@@ -224,6 +165,12 @@ pub fn alreadySaved(io: Io, dir: Io.Dir, path: []const u8, fp: u64) bool {/// The returned ticket identifies THIS save. After `drain()`, `errorFor(ticket)`/// answers for it and for nothing else.pub fn submit(gpa: Allocator, io: Io, dir: Io.Dir, path: []u8, data: []u8, fp: u64) u64 {+ return submitInHome(gpa, io, dir, path, data, fp, "");+}++/// Discovery metadata is optional; session persistence remains authoritative.+pub fn submitInHome(gpa: Allocator, io: Io, dir: Io.Dir, path: []u8, data: []u8, fp: u64, home: []const u8) u64 {+ const saved_home = if (home.len > 0) gpa.dupe(u8, home) catch null else null;writer_io = io; // set before anything can be queued; see writer_iomutex.lockUncancelable(io);if (thread == null and !stopping) thread = std.Thread.spawn(.{}, worker, .{io}) catch null;@@ -235,7 +182,8 @@ pub fn submit(gpa: Allocator, io: Io, dir: Io.Dir, path: []u8, data: []u8, fp: umutex.unlock(io);defer gpa.free(path);defer gpa.free(data);- writeNow(io, dir, path, data, fp, ticket);+ defer if (saved_home) |h| gpa.free(h);+ writeNow(io, dir, path, data, fp, ticket, saved_home);return ticket;}defer mutex.unlock(io);@@ -244,17 +192,18 @@ pub fn submit(gpa: Allocator, io: Io, dir: Io.Dir, path: []u8, data: []u8, fp: usuperseded += 1;}gpa_of_pending = gpa;- pending = .{ .io = io, .dir = dir, .path = path, .data = data, .fp = fp, .ticket = ticket };+ pending = .{ .io = io, .dir = dir, .path = path, .data = data, .fp = fp, .ticket = ticket, .home = saved_home };work.broadcast(io);return ticket;}/// The pre-#273 write, used when threads are unavailable.-fn writeNow(io: Io, dir: Io.Dir, path: []const u8, data: []const u8, fp: u64, ticket: u64) void {+fn writeNow(io: Io, dir: Io.Dir, path: []const u8, data: []const u8, fp: u64, ticket: u64, home: ?[]const u8) void {var failed: ?anyerror = null;session_lock.writeSession(io, dir, path, data) catch |err| {failed = err;};+ if (failed == null) if (home) |h| @import("workspace_history.zig").record(io, dir, h) catch {};const evidence: ?Mark = if (failed == null) observe(io, dir, path, fp) else null;mutex.lockUncancelable(io);defer mutex.unlock(io);@@ -325,6 +274,7 @@ fn worker(io: Io) void {session_lock.writeSession(job.io, job.dir, job.path, job.data) catch |err| {failed = err;};+ if (failed == null) if (job.home) |h| @import("workspace_history.zig").record(job.io, job.dir, h) catch {};const evidence: ?Mark = if (failed == null) observe(job.io, job.dir, job.path, job.fp) else null;mutex.lockUncancelable(io);diff --git a/src/workspace_history.zig b/src/workspace_history.zignew file mode 100644index 00000000..f1c24318--- /dev/null+++ b/src/workspace_history.zig@@ -0,0 +1,119 @@+//! Successful session saves register exact folders for device-local discovery.+//! A marker is a lookup hint, never evidence that a live/saved consumer is gone.+const std = @import("std");+const Io = std.Io;+const gpa = std.heap.page_allocator;+pub const directory = ".graff/workspace-history";+pub const Row = struct { version: u8 = 1, path: []const u8 };++pub fn record(io: Io, workspace: Io.Dir, home: []const u8) !void {+ if (!std.fs.path.isAbsolute(home)) return error.InvalidHome;+ const root = try workspace.realPathFileAlloc(io, ".", gpa);+ defer gpa.free(root);+ var home_dir = try Io.Dir.cwd().openDir(io, home, .{});+ defer home_dir.close(io);+ try home_dir.createDirPath(io, directory);+ var records = try home_dir.openDir(io, directory, .{ .follow_symlinks = false });+ defer records.close(io);+ const private_dir: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) .fromMode(0o700) else .default_dir;+ try records.setPermissions(io, private_dir);+ var digest: [32]u8 = undefined;+ std.crypto.hash.sha2.Sha256.hash(root, &digest, .{});+ const hex = std.fmt.bytesToHex(digest, .lower);+ var name_buf: [69]u8 = undefined;+ const name = try std.fmt.bufPrint(&name_buf, "{s}.json", .{hex});+ const bytes = try std.json.Stringify.valueAlloc(gpa, Row{ .path = root }, .{});+ defer gpa.free(bytes);+ if (records.readFileAlloc(io, name, gpa, .limited(8192)) catch null) |existing| {+ defer gpa.free(existing);+ if (std.mem.eql(u8, existing, bytes)) return;+ }+ // Concurrent saves of a folder write identical data. Separate temporary+ // files and atomic replacement avoid partial records and shared-list races.+ var random: [16]u8 = undefined;+ io.random(&random);+ const suffix = std.fmt.bytesToHex(random, .lower);+ var temporary_buf: [102]u8 = undefined;+ const temporary = try std.fmt.bufPrint(&temporary_buf, "{s}.{s}", .{ name, suffix });+ defer records.deleteFile(io, temporary) catch {};+ {+ const file = try records.createFile(io, temporary, .{+ .exclusive = true,+ .permissions = if (Io.File.Permissions.has_executable_bit) .fromMode(0o600) else .default_file,+ });+ defer file.close(io);+ try file.writeStreamingAll(io, bytes);+ try file.sync(io);+ }+ try records.rename(temporary, records, name, io);+}++test "workspace history registers the exact saved folder without promoting its parent" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ try tmp.dir.createDirPath(io, "home");+ try tmp.dir.createDirPath(io, "project/nested");+ const home = try tmp.dir.realPathFileAlloc(io, "home", std.testing.allocator);+ defer std.testing.allocator.free(home);+ var folder = try tmp.dir.openDir(io, "project/nested", .{});+ defer folder.close(io);+ try record(io, folder, home);+ try record(io, folder, home);+ var index = try tmp.dir.openDir(io, "home/" ++ directory, .{ .iterate = true });+ defer index.close(io);+ var it = index.iterate();+ const entry = (try it.next(io)).?;+ const bytes = try index.readFileAlloc(io, entry.name, std.testing.allocator, .limited(8192));+ defer std.testing.allocator.free(bytes);+ const parsed = try std.json.parseFromSlice(Row, std.testing.allocator, bytes, .{});+ defer parsed.deinit();+ const expected = try folder.realPathFileAlloc(io, ".", std.testing.allocator);+ defer std.testing.allocator.free(expected);+ try std.testing.expectEqualStrings(expected, parsed.value.path);+ try std.testing.expect((try it.next(io)) == null);+}++test "only successful session writes populate workspace discovery" {+ const io = std.testing.io;+ const alloc = std.testing.allocator;+ const writer = @import("session_writer.zig");+ writer.resetForTest();+ defer writer.resetForTest();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ try tmp.dir.createDirPath(io, "home");+ const home = try tmp.dir.realPathFileAlloc(io, "home", alloc);+ defer alloc.free(home);+ try tmp.dir.createDirPath(io, ".graff/sessions/blocked.session.json");+ const failed = writer.submitInHome(alloc, io, tmp.dir, try alloc.dupe(u8, ".graff/sessions/blocked.session.json"), try alloc.dupe(u8, "{}"), 1, home);+ writer.drain();+ try std.testing.expect(writer.errorFor(failed) != null);+ try std.testing.expectError(error.FileNotFound, tmp.dir.openDir(io, "home/" ++ directory, .{}));+ const saved = writer.submitInHome(alloc, io, tmp.dir, try alloc.dupe(u8, ".graff/sessions/saved.session.json"), try alloc.dupe(u8, "{}"), 2, home);+ writer.drain();+ try std.testing.expect(writer.errorFor(saved) == null);+ var index = try tmp.dir.openDir(io, "home/" ++ directory, .{ .iterate = true });+ defer index.close(io);+ var it = index.iterate();+ try std.testing.expect((try it.next(io)) != null);+}++test "unavailable workspace discovery storage does not fail a session save" {+ const io = std.testing.io;+ const alloc = std.testing.allocator;+ const writer = @import("session_writer.zig");+ writer.resetForTest();+ defer writer.resetForTest();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ try tmp.dir.writeFile(io, .{ .sub_path = "not-home", .data = "preserve" });+ const home = try tmp.dir.realPathFileAlloc(io, "not-home", alloc);+ defer alloc.free(home);+ const ticket = writer.submitInHome(alloc, io, tmp.dir, try alloc.dupe(u8, ".graff/sessions/saved.session.json"), try alloc.dupe(u8, "saved"), 3, home);+ writer.drain();+ try std.testing.expect(writer.errorFor(ticket) == null);+ const bytes = try tmp.dir.readFileAlloc(io, ".graff/sessions/saved.session.json", alloc, .limited(32));+ defer alloc.free(bytes);+ try std.testing.expectEqualStrings("saved", bytes);+}