Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Require an explicit successful result for generated chat titles

justrach427fc8d1375c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 649ae4c0..14a5691e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -85,6 +85,9 @@ jobs:
python3 scripts/eval-tier2.py --only repository-scoped-claim-release
python3 scripts/eval-tier2.py --only draft-cannot-waive-pr-completion --only base-failure-cannot-waive-pr-completion --only user-authorized-draft-handoff --only draft-scope-does-not-waive-ready-pr-ci --only user-can-require-verified-pr-again --only current-head-passing-pr-completes
+ - name: Title command result contract
+ run: python3 scripts/test-title-result.py
+
- name: Observed local checks before publication
run: python3 scripts/test-pr-local-checks.py --graff zig-out/bin/graff --evidence /tmp/pr-local-checks
diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml
index 631a7ad3..a59f568c 100644
--- a/.github/workflows/desktop.yml
+++ b/.github/workflows/desktop.yml
@@ -95,6 +95,11 @@ jobs:
env:
GRAFF_ELECTRON_FOREGROUND: '1'
GRAFF_FRONTEND_OS_INPUT: '1'
+ - name: Title failure fallback and successful recovery
+ if: ${{ !cancelled() && steps.worker.conclusion == 'success' }}
+ run: GRAFF_TITLE_RESULT_TEST=1 bun scripts/test-frontend.mjs
+ env:
+ GRAFF_FRONTEND_OUTPUT: ../../zig-out/title-result
- name: Narrow-window navigation and saved chat actions
if: ${{ !cancelled() && steps.worker.conclusion == 'success' }}
run: bun run test:narrow-navigation
diff --git a/apps/native/app/api/title/route.ts b/apps/native/app/api/title/route.ts
index 7f7e9933..97596c64 100644
--- a/apps/native/app/api/title/route.ts
+++ b/apps/native/app/api/title/route.ts
@@ -1,4 +1,4 @@
-import { spawn } from "node:child_process";
+import { generateTitle } from "@/lib/generate-title";
import { existsSync } from "node:fs";
import path from "node:path";
import { NextRequest } from "next/server";
@@ -22,59 +22,7 @@ function graffBin(): string {
return "graff";
}
-const TIMEOUT_MS = 20_000;
const MAX_PROMPT = 2_000;
-const MAX_TITLE = 60;
-
-/** graff prints the title on stdout and can print allocator warnings after
- * it; the first non-empty line is the answer. */
-function firstLine(out: string): string | null {
- for (const raw of out.split("\n")) {
- const line = raw.trim();
- if (!line) continue;
- if (line.startsWith("error(") || line.startsWith("warning:")) return null;
- return line.replace(/^["'`]|["'`]$/g, "").slice(0, MAX_TITLE);
- }
- return null;
-}
-
-function titleFor(prompt: string, cwd: string): Promise<string | null> {
- return new Promise((resolve) => {
- let child: ReturnType<typeof spawn>;
- try {
- child = spawn(graffBin(), ["title", prompt], { cwd, stdio: ["ignore", "pipe", "ignore"], env: process.env });
- } catch {
- resolve(null);
- return;
- }
- let out = "";
- let done = false;
- const finish = (value: string | null) => {
- if (done) return;
- done = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => {
- child.kill("SIGKILL");
- finish(null);
- }, TIMEOUT_MS);
- child.stdout?.on("data", (chunk: Buffer) => {
- out += chunk.toString();
- // The title is one line: stop as soon as it is complete rather than
- // waiting for the process to wind down.
- if (out.includes("\n")) {
- const line = firstLine(out);
- if (line) {
- child.kill("SIGKILL");
- finish(line);
- }
- }
- });
- child.on("error", () => finish(null));
- child.on("close", () => finish(firstLine(out)));
- });
-}
export async function POST(req: NextRequest) {
let body: { prompt?: unknown; cwd?: unknown };
@@ -88,6 +36,6 @@ export async function POST(req: NextRequest) {
const cwdParam = typeof body.cwd === "string" && body.cwd.trim() ? body.cwd : undefined;
const resolved = resolveRoot(cwdParam);
if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
- const title = await titleFor(prompt, cwdParam ? resolved.root : defaultRoot());
+ const title = await generateTitle(graffBin(), prompt, cwdParam ? resolved.root : defaultRoot());
return Response.json({ title });
}
diff --git a/apps/native/electron/frontend-runtime.cjs b/apps/native/electron/frontend-runtime.cjs
index 90a81f62..80404bc8 100644
--- a/apps/native/electron/frontend-runtime.cjs
+++ b/apps/native/electron/frontend-runtime.cjs
@@ -84,7 +84,7 @@ app.whenReady().then(async () => {
{ text: 'The earlier result is still present.' },
]));
const requests = path.join(temp, 'requests.json');
- const model = child('python3', [path.join(repo, 'scripts/eval/frontend_model.py'), '--script', script, '--requests', requests], env, 'model');
+ const model = child('python3', [path.join(repo, 'scripts/eval/frontend_model.py'), '--script', script, '--requests', requests, ...(process.env.GRAFF_TITLE_RESULT_TEST ? ['--title-failures','1'] : [])], env, 'model');
await until(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');
@@ -206,6 +206,7 @@ app.whenReady().then(async () => {
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});
+ if (process.env.GRAFF_TITLE_RESULT_TEST) await require('./title-result-frontend.cjs').observe(win);
await send('Write the fixture file, then finish.');
await until(() => js(`document.body.textContent.includes('Scripted final request rejected') && !document.querySelector('article[aria-busy="true"]')`), 'real failure displayed', 25000);
assert.equal(fs.readFileSync(path.join(workspace, 'proof.txt'), 'utf8'), 'kept');
@@ -238,6 +239,7 @@ app.whenReady().then(async () => {
fs.cpSync(path.join(workspace, '.graff'), path.join(output, 'harness-evidence'), {recursive:true});
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');
+ if (process.env.GRAFF_TITLE_RESULT_TEST) return require('./title-result-frontend.cjs').verify({win,output,workspace,send,click,until,report});
if (process.env.GRAFF_CLI_TEST) {
await require('./cli-frontend.cjs').runCliFrontend({ app, win, temp, workspace, output, until, report, projects });
return;
diff --git a/apps/native/electron/title-result-frontend.cjs b/apps/native/electron/title-result-frontend.cjs
new file mode 100644
index 00000000..e58c3256
--- /dev/null
+++ b/apps/native/electron/title-result-frontend.cjs
@@ -0,0 +1,26 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs'), path = require('node:path');
+exports.observe = win => win.webContents.executeJavaScript(`{
+ const original = window.fetch;
+ window.__titleResults = [];
+ window.fetch = async (...args) => {
+ const response = await original(...args);
+ if(String(args[0]).includes('/api/title')) window.__titleResults.push(await response.clone().json());
+ return response;
+ };
+ void 0;
+}`);
+exports.verify = async ({win,output,workspace,send,click,until,report}) => {
+ const js = code => win.webContents.executeJavaScript(code);
+ await until(() => js('window.__titleResults.length === 1'), 'failed title request finishes');
+ assert.deepEqual(await js('window.__titleResults'), [{title:null}]);
+ assert(await js(`document.querySelector('[data-tab-id]:has(button[aria-pressed="true"])').textContent.includes('Write the fixture file')`));
+ fs.writeFileSync(path.join(output,'title-failure-fallback.png'),(await win.webContents.capturePage()).toPNG());
+ await click('[title="New chat (⌘T)"]');
+ await send('Check title recovery');
+ await until(() => js(`window.__titleResults.length === 2 && document.querySelector('[data-tab-id]:has(button[aria-pressed="true"])').textContent.includes('Retained work') && !document.querySelector('article[aria-busy="true"]')`), 'successful title and agent completion');
+ assert.deepEqual(await js('window.__titleResults'), [{title:null},{title:'Retained work'}]);
+ fs.writeFileSync(path.join(output,'title-recovery.png'),(await win.webContents.capturePage()).toPNG());
+ fs.cpSync(path.join(workspace,'.graff'),path.join(output,'title-harness-evidence'),{recursive:true});
+ report.passed.push('actual title failure preserves provisional name and successful generation names the next chat');
+};
diff --git a/apps/native/lib/generate-title.test.ts b/apps/native/lib/generate-title.test.ts
new file mode 100644
index 00000000..1abdc72c
--- /dev/null
+++ b/apps/native/lib/generate-title.test.ts
@@ -0,0 +1,43 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, rmSync, existsSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { generateTitle, generatedTitle } from "./generate-title";
+
+test("only one explicit successful title record is accepted", () => {
+ assert.equal(generatedTitle('retry 1/6 · ConnectionRefused\n'), null);
+ assert.equal(generatedTitle('(title generation failed)\n'), null);
+ assert.equal(generatedTitle('{"type":"title_result","title":null}\n'), null);
+ assert.equal(generatedTitle('{"type":"title_result","title":"a"}\n{"type":"title_result","title":"b"}'), null);
+ assert.equal(generatedTitle('notice\n{"type":"title_result","title":"Fix café navigation"}\nwarning: cleanup'), 'Fix café navigation');
+});
+
+async function fixture(source: string, verify: (binary: string, cwd: string) => Promise<void>) {
+ const cwd = mkdtempSync(path.join(os.tmpdir(), "graff-title-result-"));
+ const binary = path.join(cwd, "graff");
+ writeFileSync(binary, '#!/usr/bin/env node\n' + source, {mode:0o700});
+ try { await verify(binary, cwd); } finally { rmSync(cwd, {recursive:true, force:true}); }
+}
+
+test("a diagnostic line cannot complete the request before a valid title and exit", async () => {
+ await fixture(`const fs=require('node:fs');
+ if(!process.argv.includes('--json'))process.exit(2);
+ console.log('retry 1/6 · ConnectionRefused');
+ setTimeout(()=>{console.log(JSON.stringify({type:'title_result',title:'Server lifecycle'}));fs.writeFileSync('finished','yes');},40);`, async (binary,cwd) => {
+ assert.equal(await generateTitle(binary, "task", cwd), "Server lifecycle");
+ assert(existsSync(path.join(cwd,"finished")));
+ });
+});
+
+test("a valid-looking result from a failed process is rejected", async () => {
+ await fixture(`console.log(JSON.stringify({type:'title_result',title:'Wrong success'}));process.exitCode=1;`, async (binary,cwd) => {
+ assert.equal(await generateTitle(binary,"task",cwd), null);
+ });
+});
+
+test("hanging title generation times out without accepting partial output", async () => {
+ await fixture(`console.log(JSON.stringify({type:'title_result',title:'Not finished'}));setInterval(()=>{},1000);`, async (binary,cwd) => {
+ assert.equal(await generateTitle(binary,"task",cwd,100), null);
+ });
+});
diff --git a/apps/native/lib/generate-title.ts b/apps/native/lib/generate-title.ts
new file mode 100644
index 00000000..df342f08
--- /dev/null
+++ b/apps/native/lib/generate-title.ts
@@ -0,0 +1,36 @@
+import { spawn } from "node:child_process";
+
+/** Accept the harness result record only after its process completes successfully. */
+export function generatedTitle(output: string): string | null {
+ const results: unknown[] = [];
+ for (const line of output.split("\n")) {
+ try {
+ const record = JSON.parse(line);
+ if (record?.type === "title_result") results.push(record.title);
+ } catch { /* Diagnostics are not title results. */ }
+ }
+ if (results.length !== 1 || typeof results[0] !== "string") return null;
+ const title = results[0].trim();
+ return title && !/[\r\n\x00-\x1f]/.test(title) ? title.slice(0, 60) : null;
+}
+
+export function generateTitle(binary: string, prompt: string, cwd: string, timeoutMs = 20_000): Promise<string | null> {
+ return new Promise(resolve => {
+ const child = spawn(binary, ["title", "--json", prompt], { cwd, stdio: ["ignore", "pipe", "ignore"] });
+ let output = "", done = false;
+ const finish = (title: string | null) => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ resolve(title);
+ };
+ const timer = setTimeout(() => { child.kill("SIGKILL"); finish(null); }, timeoutMs);
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ output += chunk;
+ if (output.length > 64 * 1024) { child.kill("SIGKILL"); finish(null); }
+ });
+ child.on("error", () => finish(null));
+ child.on("close", (code, signal) => finish(code === 0 && signal === null ? generatedTitle(output) : null));
+ });
+}
diff --git a/docs/adr/0127-title-generation-is-an-explicit-result.md b/docs/adr/0127-title-generation-is-an-explicit-result.md
new file mode 100644
index 00000000..9286a22d
--- /dev/null
+++ b/docs/adr/0127-title-generation-is-an-explicit-result.md
@@ -0,0 +1,26 @@
+# 0127. Title generation returns an explicit result
+
+Status: accepted 2026-09-15
+
+## Context
+
+A title subprocess can print retry diagnostics before producing its answer.
+Accepting the first output line both turns diagnostics into chat names and
+terminates generation before its outcome is known.
+
+## Decision
+
+`graff title --json` emits one `title_result` record containing the generated
+title or null on generation failure. Ordinary text output remains available
+for human callers. This serializes the harness result; it does not constrain
+model decoding.
+
+The GUI waits for successful process exit and accepts exactly one valid result
+record. Other output is diagnostic. Failure, timeout, oversized output, or an
+ambiguous result keeps the provisional chat name and never prevents a send.
+
+## Verification
+
+Actual harness subprocess tests exercise successful and failed responses.
+GUI subprocess tests cover preceding diagnostics, failed exits, and a process
+that prints a result but never finishes.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index f5ae19d9..d79e9758 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -142,6 +142,8 @@ record only when you need the evidence or the edge cases.
| [0126](0126-publication-retains-observed-check-failures.md) | Observed failed checks survive resumes; non-draft publication waits for successful reruns and occupies its own tool batch. |
+| [0127](0127-title-generation-is-an-explicit-result.md) | GUI titles require one explicit result and successful process exit; diagnostics never become chat names. |
+
## When to write one
Write an ADR when a decision is load-bearing and non-obvious: it was reached
diff --git a/scripts/eval/frontend_model.py b/scripts/eval/frontend_model.py
index a7da6d02..8db59b99 100644
--- a/scripts/eval/frontend_model.py
+++ b/scripts/eval/frontend_model.py
@@ -11,12 +11,16 @@ from mock_model import ScriptedModel
class FrontendModel(ScriptedModel):
- def __init__(self, script, requests_path):
+ def __init__(self, script, requests_path, title_failures=0):
super().__init__(script)
self.requests_path = Path(requests_path)
+ self.title_failures = title_failures
def next_reply(self, body):
if not body.get('tools'):
+ if self.title_failures:
+ self.title_failures -= 1
+ return {'http_status': 400, 'error': 'Title fixture rejected request'}
return {'text': 'Retained work'}
reply = super().next_reply(body)
self.requests_path.write_text(json.dumps(self.requests))
@@ -27,8 +31,9 @@ if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--script', required=True)
parser.add_argument('--requests', required=True)
+ parser.add_argument('--title-failures', type=int, default=0)
args = parser.parse_args()
- model = FrontendModel(json.loads(Path(args.script).read_text()), args.requests)
+ model = FrontendModel(json.loads(Path(args.script).read_text()), args.requests, args.title_failures)
print('Binding scripted model fixture', flush=True)
model.start(1234)
print('scripted model on 127.0.0.1:1234', flush=True)
diff --git a/scripts/test-title-result.py b/scripts/test-title-result.py
new file mode 100644
index 00000000..7e2f6194
--- /dev/null
+++ b/scripts/test-title-result.py
@@ -0,0 +1,32 @@
+"""Exercise the title result contract using the actual harness process."""
+import argparse
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+sys.path.insert(0, str(Path(__file__).parent / "eval"))
+from mock_model import ScriptedModel
+
+parser = argparse.ArgumentParser(description=__doc__)
+parser.add_argument("--graff", type=Path, default=Path(__file__).resolve().parents[1] / "zig-out/bin/graff")
+args = parser.parse_args()
+for name, reply, expected in [("success", {"text": "Server lifecycle"}, "Server lifecycle"), ("failure", {"http_status": 400, "error": "fixture rejected request"}, None)]:
+ model = ScriptedModel([reply]); model.start(1234)
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-title-contract-") as folder:
+ env = dict(os.environ, HOME=folder, LMSTUDIO_API_KEY="local", GRAFF_NO_TELEMETRY="1", NO_COLOR="1")
+ result = subprocess.run([str(args.graff.resolve()), "title", "--json", "--model", "lmstudio", "Check server lifecycle"], cwd=folder, env=env, capture_output=True, text=True, timeout=30)
+ assert result.returncode == 0, "title command failed"
+ records = []
+ for line in result.stdout.splitlines():
+ try:
+ record = json.loads(line)
+ if record.get("type") == "title_result": records.append(record)
+ except (ValueError, AttributeError): pass
+ assert records == [{"type": "title_result", "title": expected}], f"{name}: expected one explicit title result"
+ assert len(model.requests) == 1, "fixture request was not observed"
+ print(f"PASS title {name}: explicit result agrees with provider outcome")
+ finally:
+ model.stop()
diff --git a/src/session_start.zig b/src/session_start.zig
index 0334d750..1a9adb50 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -74,8 +74,12 @@ pub fn runTitleCommand(io: Io, gpa: Allocator, arena: Allocator, client: *std.ht
if (!(flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "title"))) return false;
if (flags.positionals.items.len < 2) std.process.fatal("usage: graff title <prompt>", .{});
const tprompt = try std.mem.join(arena, " ", flags.positionals.items[1..]);
- if (title_mod.titleTask(gpa, io, client, default_provider, tprompt, run_budget, null)) |t| {
- defer gpa.free(t);
+ const title = title_mod.titleTask(gpa, io, client, default_provider, tprompt, run_budget, null);
+ defer if (title) |t| gpa.free(t);
+ if (main_mod.json_mode) {
+ try std.json.Stringify.value(.{ .type = "title_result", .title = title }, .{}, out);
+ try out.writeByte('\n');
+ } else if (title) |t| {
try out.print("{s}\n", .{t});
} else try out.writeAll("(title generation failed — check your model/key)\n");
try out.flush();