Skip to content

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

Python

Fix tracker leftovers on the 0.0.299 line

Rach0d97488173c4
diff --git a/apps/native/components/primitives/StreamingCode.tsx b/apps/native/components/primitives/StreamingCode.tsx
index 8ef7022f..da4c5759 100644
--- a/apps/native/components/primitives/StreamingCode.tsx
+++ b/apps/native/components/primitives/StreamingCode.tsx
@@ -35,9 +35,9 @@ export default function StreamingCode({ node: _node, className, children, collap
<div data-streamdown="code-block-actions" className="pointer-events-auto flex shrink-0 items-center gap-2 rounded-md border border-sidebar bg-sidebar/80 px-1.5 py-1 supports-[backdrop-filter]:bg-sidebar/70 supports-[backdrop-filter]:backdrop-blur">{actions}</div>
</div>}
<div data-language={language} data-streamdown="code-block-body"
- className={`overflow-x-auto rounded-md border border-border bg-background p-4 text-sm ${bounded ? "overflow-y-auto" : ""}`}
+ className={`min-w-0 rounded-md border border-border bg-background p-4 text-sm ${bounded ? "overflow-y-auto" : ""}`}
style={bounded ? { maxHeight: codeBlockMaxHeight } : undefined}>
- <pre><code>{code.replace(/\n+$/, "")}</code></pre>
+ <pre className="overflow-x-auto"><code className="whitespace-pre">{code.replace(/\n+$/, "")}</code></pre>
</div>
</CodeBlockContainer>;
}
diff --git a/apps/native/components/site/ThemeToggle.tsx b/apps/native/components/site/ThemeToggle.tsx
index 44840cbf..aa1ad9b1 100644
--- a/apps/native/components/site/ThemeToggle.tsx
+++ b/apps/native/components/site/ThemeToggle.tsx
@@ -4,20 +4,18 @@ import { createPortal } from "react-dom";
import { restoreActionFocus } from "../primitives/ActionMenu";
import CustomThemes from "./CustomThemes";
import { appearanceEvent, appearanceKey, applyAppearance, readAppearance, type Appearance } from "@/lib/appearance";
-import { placeAnchoredPanel } from "@/lib/anchored-panel";
-import DesktopSettings from "./DesktopSettings";
-import { IconSettingsGear1 } from "@/lib/icons";
+import { appearancePanelPosition, type PanelBox } from "./appearance-panel";
const themes = [
{ id: "codegraff", name: "CodeGraff", detail: "Official · Japanese palette", bg: "#f6eedf", surface: "#fffaf0", ink: "#1b1714", accent: "#2654d9" },
{ id: "light", name: "White", detail: "Light and minimal", bg: "#fafafa", surface: "#ffffff", ink: "#25272b", accent: "#3785fa" },
- { id: "dark", name: "Black", detail: "Near-black olive", bg: "#0b0c09", surface: "#141712", ink: "#f3f5ef", accent: "#5dca8e" },
+ { id: "dark", name: "Black", detail: "Quiet charcoal", bg: "#17181b", surface: "#24262a", ink: "#f4f4f5", accent: "#5b9cf7" },
{ id: "website", name: "Website", detail: "CodeGraff emerald", bg: "#fafaf8", surface: "#ffffff", ink: "#18231e", accent: "#059669" },
] as const;
-export function ThemeToggle({ labeled = false, gear = false }: { labeled?: boolean; gear?: boolean }) {
+export function ThemeToggle({ labeled = false }: { labeled?: boolean }) {
const [theme, setTheme] = useState<Appearance>("dark");
- const [position, setPosition] = useState<{ top: number; left: number } | null>(null);
+ const [position, setPosition] = useState<PanelBox | null>(null);
const trigger = useRef<HTMLButtonElement>(null);
const panel = useRef<HTMLDivElement>(null);
useEffect(() => {
@@ -50,21 +48,23 @@ export function ThemeToggle({ labeled = false, gear = false }: { labeled?: boole
requestAnimationFrame(() => requestAnimationFrame(() => document.documentElement.classList.remove("theme-switching")));
};
return <>
- <button ref={trigger} aria-label="Appearance" title={gear ? "Settings" : "Appearance"} aria-haspopup="dialog" aria-expanded={!!position} onClick={() => {
+ <button ref={trigger} aria-label="Appearance" title="Appearance" aria-haspopup="dialog" aria-expanded={!!position} onClick={() => {
+ if (position) { setPosition(null); return; }
const rect = trigger.current!.getBoundingClientRect();
- setPosition(position ? null : placeAnchoredPanel(rect, { width: window.innerWidth, height: window.innerHeight }));
- }} className={labeled ? "flex w-full items-center rounded-md px-3 py-2 text-left text-xs hover:bg-hover" : "flex size-8 shrink-0 items-center justify-center rounded-lg text-ink-3 hover:bg-hover hover:text-ink"}>
- {labeled ? "Appearance" : gear ? <IconSettingsGear1 size={16} /> : <svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><circle cx="12" cy="12" r="8" /><path d="M12 4a8 8 0 0 1 0 16Z" fill="currentColor" stroke="none" /></svg>}
+ setPosition(appearancePanelPosition(rect, { width: window.innerWidth, height: window.innerHeight }));
+ }} className={labeled
+ ? "flex w-full items-center justify-start rounded-md px-3 py-2 text-left text-xs text-ink-3 hover:bg-hover hover:text-ink"
+ : "flex size-8 shrink-0 items-center justify-center rounded-lg text-ink-3 hover:bg-hover hover:text-ink"}>
+ {labeled ? "Appearance" : <svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><circle cx="12" cy="12" r="8" /><path d="M12 4a8 8 0 0 1 0 16Z" fill="currentColor" stroke="none" /></svg>}
</button>
- {position && createPortal(<div ref={panel} role="dialog" aria-label="Appearance" aria-modal="true" className="fixed z-[200] flex w-[310px] max-w-[calc(100vw-16px)] flex-col overflow-hidden rounded-xl border border-line bg-surface p-3 shadow-overlay" style={{ ...position, maxHeight: `calc(100dvh - ${position.top + 12}px)` }}>
- <div className="mb-3 flex shrink-0 items-center justify-between"><strong className="text-xs font-medium">Appearance</strong><button aria-label="Close appearance" onClick={() => { setPosition(null); restoreActionFocus(trigger.current); }} className="rounded px-1.5 text-ink-3 hover:bg-hover">×</button></div>
- <div className="min-h-0 overflow-y-auto">
+ {position && createPortal(<div ref={panel} role="dialog" aria-label="Appearance" aria-modal="true" className="fixed z-[200] flex max-w-[calc(100vw-16px)] flex-col overflow-hidden rounded-xl border border-line bg-surface p-3 shadow-overlay" style={{ top: position.top, left: position.left, width: position.width, maxHeight: `calc(100dvh - ${position.top + 12}px)` }}>
+ <div className="mb-3 flex shrink-0 items-center justify-between bg-surface"><strong className="text-xs font-medium">Appearance</strong><button aria-label="Close appearance" onClick={() => { setPosition(null); restoreActionFocus(trigger.current); }} className="rounded px-1.5 text-ink-3 hover:bg-hover">×</button></div>
+ <div className="min-h-0 flex-1 overflow-y-auto">
<div className="grid grid-cols-2 gap-2">{themes.map(option => <button key={option.id} aria-pressed={theme === option.id} onClick={() => choose(option.id)} className={`rounded-lg border p-1.5 text-left focus-visible:outline-2 focus-visible:outline-accent ${theme === option.id ? "border-accent bg-accent-tint" : "border-line hover:bg-hover"}`}>
<span aria-hidden="true" className="mb-2 flex h-14 gap-1 overflow-hidden rounded p-1.5" style={{ background: option.bg }}><span className="w-3 rounded-sm" style={{ background: option.id === "codegraff" ? "#d45a43" : option.accent, opacity: .35 }} /><span className="flex flex-1 flex-col gap-1 rounded p-1" style={{ background: option.surface }}><span className="h-1 w-5 rounded" style={{ background: option.ink, opacity: .45 }} /><span className="h-1 w-8 rounded" style={{ background: option.ink, opacity: .15 }} /><span className="mt-auto h-1.5 w-4 rounded" style={{ background: option.accent }} /></span></span>
<span className="block text-[11px] font-medium text-ink">{option.name}</span><span className="block text-[9px] leading-4 text-ink-3">{option.detail}</span>
</button>)}</div>
<CustomThemes selected={theme} />
- <DesktopSettings embedded />
</div>
</div>, document.body)}
</>;
diff --git a/apps/native/components/site/appearance-panel.test.ts b/apps/native/components/site/appearance-panel.test.ts
new file mode 100644
index 00000000..b9b820a1
--- /dev/null
+++ b/apps/native/components/site/appearance-panel.test.ts
@@ -0,0 +1,52 @@
+import { describe, it } from "node:test";
+import assert from "node:assert/strict";
+import {
+ APPEARANCE_PANEL_WIDTH,
+ VIEWPORT_MARGIN,
+ appearancePanelPosition,
+} from "./appearance-panel.ts";
+
+const sidebarGear = { left: 220, right: 252, top: 740, bottom: 772 };
+const desktop = { width: 1280, height: 800 };
+
+function fullyOnScreen(box: { top: number; left: number; width: number }, viewport = desktop, height = 420) {
+ assert.ok(box.left >= VIEWPORT_MARGIN, `left ${box.left} clips the left edge`);
+ assert.ok(box.left + box.width <= viewport.width - VIEWPORT_MARGIN, `right ${box.left + box.width} clips the right edge`);
+ assert.ok(box.top >= VIEWPORT_MARGIN, `top ${box.top} clips the top edge`);
+ assert.ok(box.top + Math.min(height, viewport.height) <= viewport.height || box.top <= viewport.height - VIEWPORT_MARGIN);
+}
+
+describe("appearance panel position", () => {
+ it("opens to the right of a left-sidebar gear instead of hanging off the left", () => {
+ const box = appearancePanelPosition(sidebarGear, desktop);
+ fullyOnScreen(box);
+ assert.equal(box.width, APPEARANCE_PANEL_WIDTH);
+ assert.ok(box.left >= sidebarGear.right, "panel should sit to the trigger's right");
+ // The old `right: innerWidth - trigger.right` placement put the left edge at
+ // trigger.right - 310 = -58.
+ assert.ok(box.left > 0);
+ });
+
+ it("opens to the left of a right-edge trigger instead of overflowing", () => {
+ const trigger = { left: 1240, right: 1272, top: 740, bottom: 772 };
+ const box = appearancePanelPosition(trigger, desktop);
+ fullyOnScreen(box);
+ assert.ok(box.left + box.width <= trigger.left, "panel should sit to the trigger's left when the right side has no room");
+ });
+
+ it("shrinks to the viewport on a narrow window", () => {
+ const viewport = { width: 280, height: 500 };
+ const trigger = { left: 12, right: 44, top: 400, bottom: 432 };
+ const box = appearancePanelPosition(trigger, viewport);
+ assert.equal(box.width, viewport.width - VIEWPORT_MARGIN * 2);
+ assert.equal(box.left, VIEWPORT_MARGIN);
+ fullyOnScreen(box, viewport, 420);
+ });
+
+ it("does not place the panel above the titlebar when there is room below", () => {
+ const trigger = { left: 220, right: 252, top: 80, bottom: 112 };
+ const box = appearancePanelPosition(trigger, desktop);
+ assert.ok(box.top >= 48);
+ fullyOnScreen(box);
+ });
+});
diff --git a/apps/native/components/site/appearance-panel.ts b/apps/native/components/site/appearance-panel.ts
new file mode 100644
index 00000000..dabd6871
--- /dev/null
+++ b/apps/native/components/site/appearance-panel.ts
@@ -0,0 +1,39 @@
+/** Placement for the Appearance dialog (#977). */
+
+export const APPEARANCE_PANEL_WIDTH = 310;
+export const APPEARANCE_PANEL_MIN_HEIGHT = 420;
+export const VIEWPORT_MARGIN = 8;
+export const TITLEBAR_OFFSET = 48;
+
+export type TriggerRect = { left: number; right: number; top: number; bottom: number };
+export type Viewport = { width: number; height: number };
+export type PanelBox = { top: number; left: number; width: number };
+
+/**
+ * Keep the 310px Appearance dialog fully on-screen.
+ * A left-sidebar gear used to set `right: window.innerWidth - trigger.right`,
+ * which pinned the panel's right edge to the trigger and hung the rest off
+ * the left of the viewport. Prefer the trigger's right, then clamp.
+ */
+export function appearancePanelPosition(
+ trigger: TriggerRect,
+ viewport: Viewport,
+ panel: { width?: number; height?: number } = {},
+): PanelBox {
+ const margin = VIEWPORT_MARGIN;
+ const width = Math.min(panel.width ?? APPEARANCE_PANEL_WIDTH, Math.max(0, viewport.width - margin * 2));
+ const height = Math.min(panel.height ?? APPEARANCE_PANEL_MIN_HEIGHT, Math.max(0, viewport.height - margin * 2));
+
+ let left = trigger.right + margin;
+ if (left + width > viewport.width - margin) left = trigger.left - margin - width;
+ if (left < margin) left = margin;
+ if (left + width > viewport.width - margin) left = Math.max(margin, viewport.width - margin - width);
+
+ const below = trigger.bottom + margin;
+ const maxTop = Math.max(margin, viewport.height - height - margin);
+ let top = Math.min(below, maxTop);
+ top = Math.max(Math.min(TITLEBAR_OFFSET, maxTop), top);
+ if (top < margin) top = margin;
+
+ return { top, left, width };
+}
diff --git a/apps/native/lib/attachments.test.ts b/apps/native/lib/attachments.test.ts
index 4e252d8a..6e34a3eb 100644
--- a/apps/native/lib/attachments.test.ts
+++ b/apps/native/lib/attachments.test.ts
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { filesFrom, isImageFile, marker, markerName, splitImageMarkers, withAttachmentMarkers, type Attachment } from "./attachments.ts";
+import { filesFrom, isImageFile, liftAttachmentMarkers, marker, markerName, splitImageMarkers, withAttachmentMarkers, type Attachment } from "./attachments.ts";
const shot: Attachment = { id: "/tmp/a/shot.png", name: "shot.png", path: "/tmp/a/shot.png" };
const notes: Attachment = { id: "/tmp/a/notes.md", name: "notes.md", path: "/tmp/a/notes.md" };
@@ -39,6 +39,16 @@ test("only the staged attachment directory previews; any other path stays text",
assert.deepEqual(splitImageMarkers("@[/tmp/x/graff-native-attachments/notes.md]"), ["@[/tmp/x/graff-native-attachments/notes.md]"]);
});
+test("liftAttachmentMarkers turns staged image tokens into chips", () => {
+ const staged = "@[/tmp/x/graff-native-attachments/shot.png]";
+ const lifted = liftAttachmentMarkers(`look at this ${staged} please`);
+ assert.equal(lifted.text, "look at this please");
+ assert.equal(lifted.attachments.length, 1);
+ assert.equal(lifted.attachments[0]?.name, "shot.png");
+ assert.equal(lifted.attachments[0]?.path, "/tmp/x/graff-native-attachments/shot.png");
+ assert.deepEqual(liftAttachmentMarkers("no images here"), { text: "no images here", attachments: [] });
+});
+
test("markerName is the basename /api/attach answers to", () => {
assert.equal(markerName("@[/tmp/x/graff-native-attachments/shot.png]"), "shot.png");
});
diff --git a/apps/native/lib/attachments.ts b/apps/native/lib/attachments.ts
index 616fba3d..f8d4cb31 100644
--- a/apps/native/lib/attachments.ts
+++ b/apps/native/lib/attachments.ts
@@ -77,6 +77,30 @@ export function splitImageMarkers(text: string): string[] {
return text.split(IMAGE_MARKER_RE);
}
+/** Pull staged-image markers out of draft text so the composer never shows
+ * `@[…/graff-native-attachments/….png]` as spellchecked prose. */
+export function liftAttachmentMarkers(text: string): { text: string; attachments: Attachment[] } {
+ const parts = splitImageMarkers(text);
+ if (parts.length < 2) return { text, attachments: [] };
+ const attachments: Attachment[] = [];
+ let visible = "";
+ for (let i = 0; i < parts.length; i++) {
+ const part = parts[i]!;
+ if (i % 2 === 1) {
+ const path = part.slice(2, -1);
+ attachments.push({
+ id: path,
+ name: markerName(part),
+ path,
+ preview: `/api/attach?name=${encodeURIComponent(markerName(part))}`,
+ });
+ } else {
+ visible += part;
+ }
+ }
+ return { text: visible.replace(/[ \t]{2,}/g, " ").trim(), attachments };
+}
+
/** The staged file's basename — the name `/api/attach?name=` answers to. */
export function markerName(marker: string): string {
return marker.slice(marker.lastIndexOf("/") + 1, -1);
diff --git a/apps/native/lib/composer-draft.test.ts b/apps/native/lib/composer-draft.test.ts
index cd7d780d..6bf6813e 100644
--- a/apps/native/lib/composer-draft.test.ts
+++ b/apps/native/lib/composer-draft.test.ts
@@ -12,6 +12,13 @@ test("a hidden chat retains text and receives its pending upload without changin
expect(second.getSnapshot().attachments).toEqual([]);
});
+test("staged image markers leave the draft and become chips", () => {
+ const store = createComposerDraft();
+ store.setDraft("look @[/tmp/x/graff-native-attachments/shot.png] please");
+ expect(store.getSnapshot().draft).toBe("look please");
+ expect(store.getSnapshot().attachments[0]?.name).toBe("shot.png");
+});
+
test("closing a chat releases previews including an upload that completes after disposal", () => {
const released: string[] = [];
const store = createComposerDraft(files => released.push(...files.map(file => file.id)));
diff --git a/apps/native/lib/composer-draft.ts b/apps/native/lib/composer-draft.ts
index 9f51b5b6..af1583fa 100644
--- a/apps/native/lib/composer-draft.ts
+++ b/apps/native/lib/composer-draft.ts
@@ -1,4 +1,4 @@
-import { discardAttachments, type Attachment } from "./attachments";
+import { discardAttachments, liftAttachmentMarkers, type Attachment } from "./attachments";
type Update<T> = T | ((current: T) => T);
export type ComposerDraft = { draft: string; attachments: Attachment[]; uploads: number; attachError: string | null };
@@ -22,7 +22,22 @@ export function createComposerDraft(release = discardAttachments) {
return {
getSnapshot: () => snapshot,
subscribe: (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; },
- setDraft: (value: Update<string>) => update("draft", value),
+ setDraft: (value: Update<string>) => {
+ const raw = typeof value === "function" ? value(snapshot.draft) : value;
+ const lifted = liftAttachmentMarkers(raw);
+ const extra = lifted.attachments.filter((a) => !snapshot.attachments.some((c) => c.path === a.path));
+ if (lifted.text === snapshot.draft && extra.length === 0) return;
+ if (disposed) {
+ if (extra.length) release(extra);
+ return;
+ }
+ snapshot = {
+ ...snapshot,
+ draft: lifted.text,
+ attachments: extra.length ? [...snapshot.attachments, ...extra] : snapshot.attachments,
+ };
+ listeners.forEach((listener) => listener());
+ },
setAttachments: (value: Update<Attachment[]>) => update("attachments", value),
setUploads: (value: Update<number>) => update("uploads", value),
setAttachError: (value: Update<string | null>) => update("attachError", value),
diff --git a/src/acp.zig b/src/acp.zig
index 13ff1109..1cdf546a 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -72,6 +72,7 @@ fn liveCancelled() bool {
/// printing their list, so nothing waits on a keypress that cannot come.
fn liveSlash(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]const u8 {
if (@import("review.zig").promptFromLine(text) != null) return null;
+ if (@import("issue_cmd.zig").promptFromLine(text) != null) return null;
const live: *LiveTurn = @ptrCast(@alignCast(ctx));
var aw: Io.Writer.Allocating = .init(arena);
// /never is the playbook's own, and handleCommand does not know it.
diff --git a/src/agent.zig b/src/agent.zig
index b4ab06e3..25e80f26 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -329,12 +329,11 @@ pub const Agent = struct {
}
pub fn runTurn(self: *Agent) anyerror![]const u8 {
- // Restore catalog invariants before starting the turn.
- try self.ensureRootTools(self.provider.kind);
var pending_work: empty_completion.PendingWork = .{};
self.completed = null;
self.mcp_context.begin(self.io);
@import("named_work.zig").beginTurn(self);
+ try self.ensureRootTools(self.provider.kind);
var task_scope = @import("task_intent.zig").State.begin(self);
if (!self.sub and !root_turn_prepared.swap(false, .acq_rel)) @import("cancel_source.zig").clear();
var review_deadline = try @import("review_deadline.zig").start(self);
diff --git a/src/agent_empty_completion.zig b/src/agent_empty_completion.zig
index 7367eb3e..07553b54 100644
--- a/src/agent_empty_completion.zig
+++ b/src/agent_empty_completion.zig
@@ -45,6 +45,7 @@ pub fn handle(self: *Agent, final_text: []const u8, hist_len: usize) !bool {
return true;
}
if (@import("task_intent.zig").current(self) == .informational) return false;
+ if (no_local_tools.enabled) return false;
if (!shouldBounce(main_mod.unattended, no_local_tools.lean, self.text_only, self.review_mode, self.sub, self.tool_calls_this_turn, self.model_calls_this_turn, final_text))
return false;
try self.messages.append(try messages.userNote(self.arena, self.provider.kind, bounce_note));
@@ -250,3 +251,27 @@ test "completed informational answer is not an edit-oriented fake_done retry" {
try std.testing.expect(!try handle(&self, "The app separates its UI, parser, and storage.", before));
try std.testing.expectEqual(before, self.messages.items.len);
}
+
+test "no-local-tools lean critique is not an edit-oriented fake_done retry" {
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ var self = pendingFixture(state.allocator());
+ self.empty_completion_retries = 0;
+ const old_unattended = main_mod.unattended;
+ const old_lean = no_local_tools.lean;
+ const old_enabled = no_local_tools.enabled;
+ main_mod.unattended = true;
+ no_local_tools.lean = true;
+ no_local_tools.enabled = true;
+ defer {
+ main_mod.unattended = old_unattended;
+ no_local_tools.lean = old_lean;
+ no_local_tools.enabled = old_enabled;
+ }
+ self.tool_calls_this_turn = 0;
+ self.model_calls_this_turn = 1;
+ try self.messages.append(try messages.textMessage(self.arena, "user", "Critique this design; do not inspect or edit files"));
+ const before = self.messages.items.len;
+ try std.testing.expect(!try handle(&self, "The design is coherent and needs no local changes.", before));
+ try std.testing.expectEqual(before, self.messages.items.len);
+}
diff --git a/src/agent_working.zig b/src/agent_working.zig
index decc663b..d32b358a 100644
--- a/src/agent_working.zig
+++ b/src/agent_working.zig
@@ -44,9 +44,9 @@ pub fn write(w: *Io.Writer, title: []const u8, items: []const Item) void {
}
pub fn writeFromStanding(w: *Io.Writer, st: engine_events.StandingWork) void {
- // Keep completed history, but do not redraw it as WORKING at every prompt.
+ // Keep completed history, but do not redraw a finished checklist as WORKING.
// Use the full counts: an open item may be beyond the displayed slice.
- if (st.goal.len == 0 and st.todos_total > 0 and st.todos_done == st.todos_total) return;
+ if (st.todos_total > 0 and st.todos_done == st.todos_total) return;
var buf: [max_items]Item = undefined;
const n = @min(st.todos.len, buf.len);
for (st.todos[0..n], 0..) |t, i| {
@@ -89,10 +89,10 @@ test "completed checklist stays out of idle prompt redraws" {
var st: engine_events.StandingWork = .{ .todos = &todos, .todos_done = 1, .todos_total = 1 };
writeFromStanding(&aw.writer, st);
try std.testing.expectEqualStrings("", aw.written());
- // A live goal or an open item beyond the displayed slice is still work.
+ // A finished checklist stays idle even when a goal title remains.
st.goal = "continue the goal";
writeFromStanding(&aw.writer, st);
- try std.testing.expect(std.mem.indexOf(u8, aw.written(), "WORKING") != null);
+ try std.testing.expectEqualStrings("", aw.written());
aw.clearRetainingCapacity();
st.goal = "";
st.todos_total = 2;
diff --git a/src/artifact_claim.zig b/src/artifact_claim.zig
index 0e599dfe..8a9dfb5f 100644
--- a/src/artifact_claim.zig
+++ b/src/artifact_claim.zig
@@ -105,17 +105,19 @@ fn ownerLive(io: Io, owner: Owner) bool {
if (sameOwner(owner, g_test_owner)) return true;
return g_test_live;
}
- if (owner.pid == 0) return true;
+ // A legacy handoff with no process identity is not held forever.
+ if (owner.pid == 0) return false;
return proc_identity.ownerState(owner.start_id, proc_identity.probe(io, owner.pid)) == .held;
}
fn claimRelevant(held: Kind, mutation: Kind) bool {
- if (held == mutation or held == .publication) return true;
+ if (held == mutation) return true;
return switch (mutation) {
- .pull_request => held == .branch or held == .commit,
+ .pull_request => held == .branch or held == .commit or held == .publication,
.publication => held == .branch or held == .pull_request or held == .commit,
- .commit => held == .branch,
- else => false,
+ .commit => held == .branch or held == .publication,
+ .issue => false,
+ .branch => held == .publication,
};
}
@@ -201,7 +203,9 @@ pub fn handleToolIn(arena: Allocator, io: Io, action: []const u8, kind_s: []cons
return .{ .text = msg, .is_error = false };
}
if (std.mem.eql(u8, action, "release")) {
- const msg = claim_ledger.releaseIn(ledger, kind, key, me, live, repo) catch return .{
+ const existing_owner = if (existing) |c| c.owner else null;
+ const recoverable = if (existing_owner) |o| o.pid == 0 and (std.mem.eql(u8, o.session, me.session) or o.session.len == 0) else false;
+ const msg = claim_ledger.releaseIn(ledger, kind, key, me, live and !recoverable, repo) catch return .{
.text = "cannot release a live foreign claim",
.is_error = true,
};
@@ -462,3 +466,31 @@ test "shared-tree ACK is not a claim release" {
try std.testing.expect(gateCommand(ar, std.testing.io, "git commit -m wip", "feat/x") != null);
try std.testing.expect(gateCommand(ar, std.testing.io, "git push origin HEAD", "feat/x") != null);
}
+
+test "publication claims do not block unrelated issue creation" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ resetForTest();
+ defer resetForTest();
+ setTestOwner(.{ .session = "s-pub", .pid = 21, .start_id = 3 });
+ _ = try handleTool(ar, std.testing.io, "claim", "publication", "feat/x", "");
+ setTestOwner(.{ .session = "s-other", .pid = 22, .start_id = 4 });
+ setTestOwnerLive(true);
+ try std.testing.expect(gateCommand(ar, std.testing.io, "gh issue create --title x --body y", "12") == null);
+ try std.testing.expect(gateCommand(ar, std.testing.io, "gh pr create --title x --body y", "feat/x") != null);
+}
+
+test "legacy pid-zero handoff can be released by the labeled session" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ resetForTest();
+ defer resetForTest();
+ setTestOwner(.{ .session = "s-legacy", .pid = 0, .start_id = 0 });
+ _ = try handleTool(ar, std.testing.io, "claim", "publication", "feat/legacy", "");
+ setTestOwner(.{ .session = "s-legacy", .pid = 44, .start_id = 8 });
+ setTestOwnerLive(true);
+ const released = try handleTool(ar, std.testing.io, "release", "publication", "feat/legacy", "");
+ try std.testing.expect(!released.is_error);
+}
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index c9cc76e4..0fc8eaa1 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -62,6 +62,7 @@ pub const commands = [_]Item{
.{ .name = "/trace", .desc = "toggle this run's JSONL event trace (and show its path)" },
.{ .name = "/privacy", .usage = "/privacy [local|aggregate|templates|examples]", .desc = "control prompt-learning data egress for this session" },
.{ .name = "/trajectory", .desc = "show this session's agent tree — turns + spawned subagents" },
+ .{ .name = "/issue", .usage = "/issue <what went wrong>", .desc = "file one sanitized public tracker issue from this session" },
.{ .name = "/agents", .desc = "list agent types — builtin personas + .harness/agents" },
.{ .name = "/skills", .usage = "/skills [add|remove <name>]", .desc = "list SKILL.md playbooks + companion tools; add/remove enables or disables one" },
.{ .name = "/plugins", .usage = "/plugins [list|load <name>]", .desc = "list Claude/Cursor/Grok/Codex plugin trees graff is reading in place; load names one" },
diff --git a/src/commands_session.zig b/src/commands_session.zig
index fa022ad6..9e63648b 100644
--- a/src/commands_session.zig
+++ b/src/commands_session.zig
@@ -251,6 +251,11 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try out.flush();
return true;
}
+ if (std.mem.eql(u8, line, "/issue")) {
+ try out.writeAll(@import("issue_cmd.zig").usage);
+ try out.flush();
+ return true;
+ }
if (std.mem.eql(u8, line, "/bash") or std.mem.startsWith(u8, line, "/bash ")) {
const cmd = std.mem.trim(u8, line["/bash".len..], " \t\r\n");
if (cmd.len == 0) {
diff --git a/src/edit_contract.zig b/src/edit_contract.zig
index a05875c9..d5a42891 100644
--- a/src/edit_contract.zig
+++ b/src/edit_contract.zig
@@ -49,6 +49,12 @@ pub fn isContracted(role: []const u8) bool {
return pb.isLandingRole(role);
}
+/// Task-level mutation permission: a contracted slot still does not force
+/// edits on an informational brief, including across the one workflow retry.
+pub fn mutatingTask(role: []const u8, prompt: []const u8) bool {
+ return isContracted(role) and @import("task_intent.zig").classify(prompt) != .informational;
+}
+
/// PURE contract verdict over two `git status --porcelain` snapshots.
///
/// Two distinct failures, both of which mean nothing landed:
@@ -106,3 +112,13 @@ pub fn contractCheck(gpa: Allocator, io: Io, cwd: ?[]const u8, contracted: bool,
gpa.free(out.text);
return .{ .text = gpa.dupe(u8, contract_unmet) catch "", .is_error = true };
}
+
+test "read-only analysis keeps a non-mutating scope in a contracted slot" {
+ const intent = @import("task_intent.zig");
+ try std.testing.expect(isContracted("implement"));
+ try std.testing.expectEqual(intent.Intent.informational, intent.classify("Explain src/parser.zig"));
+ try std.testing.expect(!mutatingTask("implement", "Explain src/parser.zig"));
+ try std.testing.expect(!mutatingTask("implement", "Summarize the architecture"));
+ try std.testing.expect(mutatingTask("implement", "Fix src/parser.zig"));
+ try std.testing.expect(mutatingTask("implement", "Explain then implement the parser"));
+}
diff --git a/src/engine_sink.zig b/src/engine_sink.zig
index 643cef0e..1aed02f0 100644
--- a/src/engine_sink.zig
+++ b/src/engine_sink.zig
@@ -216,7 +216,7 @@ fn tuiEmit(ctx: *anyopaque, ev: Stamped) void {
// Compaction uses the live transport too, but its reply is bookkeeping,
// not a new answer. Gate presentation, including the hosted fallback.
if (a.stream_quiet) switch (ev.event) {
- .reasoning_delta, .text_delta, .tool_arg_delta, .stream_complete => return,
+ .reasoning_delta, .text_delta, .tool_arg_delta, .completion_text, .stream_complete => return,
else => {},
};
if (hosted_frontend) return hostedEmit(a, ev.event);
diff --git a/src/escalation.zig b/src/escalation.zig
index 98623b25..e18055a7 100644
--- a/src/escalation.zig
+++ b/src/escalation.zig
@@ -588,6 +588,7 @@ pub const failure_evidence = fe;
pub const contract_unmet = edit_contract.contract_unmet;
pub const contract_brief_note = edit_contract.contract_brief_note;
pub const isContracted = edit_contract.isContracted;
+pub const mutatingTask = edit_contract.mutatingTask;
pub const contractUnmet = edit_contract.contractUnmet;
pub const treeSnapshot = edit_contract.treeSnapshot;
pub const contractCheck = edit_contract.contractCheck;
diff --git a/src/exec_bash.zig b/src/exec_bash.zig
index a180d3e8..c50050ab 100644
--- a/src/exec_bash.zig
+++ b/src/exec_bash.zig
@@ -76,7 +76,7 @@ fn startedText(gpa: Allocator, id: u32, cmd: []const u8, ssh: bool, auto_bg: boo
const w = &aw.writer;
try w.print("[job {d} started: {s}]\n", .{ id, cmd });
if (auto_bg) {
- try w.print("Command exceeded the {d}s foreground wait and was automatically moved to the background. Process is still running. Waiting via bash_output shows elapsed-time pulses so a long rebuild is distinguishable from a hang. You are notified on exit — do not poll. bash_output(id {d}, wait_ms>0) waits until it exits; omit wait_ms for a snapshot. bash_kill stops it.", .{ wait_s, id });
+ try w.print("Command exceeded the {d}s foreground wait and was automatically moved to the background. Process is still running. You are notified on exit — do not poll. bash_output(id {d}) is a snapshot, not wait-until-exit; omit wait_ms for an immediate snapshot. Leave it on /jobs or bash_kill it. Explicit run_in_background keeps wait-until-exit for intentional long work.", .{ wait_s, id });
} else {
try w.print("This is a persistent job. bash_output wait_ms is a snapshot timeout, not wait-until-exit — omit wait_ms for an immediate snapshot. You are notified on exit — do not poll. bash_output(id {d}) reads unread output. bash_kill stops it.", .{id});
}
@@ -217,6 +217,15 @@ test "cancel hint tells the model to restart with run_in_background" {
try std.testing.expect(std.mem.indexOf(u8, cancel_hint, "run_in_background") != null);
}
+test "auto-promoted jobs snapshot instead of inheriting wait-until-exit" {
+ const gpa = std.testing.allocator;
+ const text = try startedText(gpa, 7, "find /", false, true, 15, "partial");
+ defer gpa.free(text);
+ try std.testing.expect(std.mem.indexOf(u8, text, "wait-until-exit") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "waits until it exits") == null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "run_in_background") != null);
+}
+
fn formatCapped(gpa: Allocator, cmd: []const u8, run: jobs.CappedRun) !ToolOutput {
const exit_code: ?u8 = switch (run.term) {
.exited => |code| code,
@@ -313,6 +322,7 @@ fn execUnchecked(ctx: ToolCtx, call: tools.ToolCall) !ToolOutput {
},
.running => |r| blk: {
defer gpa.free(r.output);
+ jobs.markPersistent(io, r.id);
break :blk .{ .text = try startedText(gpa, r.id, cmd, ssh, true, wait_ms / 1000, r.output) };
},
.cancelled => |c| blk: {
diff --git a/src/help.zig b/src/help.zig
index d8150d2f..ea5de80b 100644
--- a/src/help.zig
+++ b/src/help.zig
@@ -30,7 +30,7 @@ const peers_blurb =
pub const sections = [_]Section{
.{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/save", "/sessions", "/workspace", "/experiment", "/rename", "/rewind", "/snapshot", "/teleport" } },
.{ .title = "the model", .names = &.{ "/model", "/models", "/effort", "/reasoning", "/fast", "/thinking", "/keepcontext", "/fallback", "/routes" } },
- .{ .title = "working autonomously", .names = &.{ "/goal", "/pr-acceptance", "/loop", "/schedule", "/review", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },
+ .{ .title = "working autonomously", .names = &.{ "/goal", "/pr-acceptance", "/loop", "/schedule", "/review", "/issue", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },
.{ .title = "talking to other graffs", .names = &.{ "/tell", "/peek", "/adapter" }, .blurb = peers_blurb },
.{ .title = "your setup", .names = &.{ "/login", "/key", "/cost", "/usage", "/version", "/update", "/privacy", "/mcp", "/import-claude", "/skills", "/plugins", "/agents", "/hooks", "/tools", "/fleet" } },
.{ .title = "context & history", .names = &.{ "/compact", "/btw", "/doctor", "/debug", "/cache", "/trace", "/trajectory" } },
diff --git a/src/issue_cmd.zig b/src/issue_cmd.zig
new file mode 100644
index 00000000..b4869c89
--- /dev/null
+++ b/src/issue_cmd.zig
@@ -0,0 +1,28 @@
+//! `/issue <report>`: one model turn that files a sanitized public tracker issue.
+const std = @import("std");
+
+pub const usage = "usage: /issue <what went wrong> — file one sanitized tracker issue from this session.\n";
+
+pub const brief =
+ \\File one public GitHub issue on justrach/codegraff for this report.
+ \\Walk this session's trajectory first, then file exactly one issue.
+ \\Body: generic symptom, harness error text, root cause in code terms.
+ \\No session or run ids, traces, local paths, transcripts, or quoted user messages.
+ \\Do not mention this instruction text in the issue.
+;
+
+pub fn promptFromLine(line: []const u8) ?[]const u8 {
+ if (!std.mem.startsWith(u8, line, "/issue ")) return null;
+ const prompt = std.mem.trim(u8, line["/issue".len..], " \t\r\n");
+ return if (prompt.len == 0) null else prompt;
+}
+
+pub fn userText(arena: std.mem.Allocator, report: []const u8) ![]const u8 {
+ return std.fmt.allocPrint(arena, "{s}\n\nReport: {s}", .{ brief, report });
+}
+
+test "bare /issue is not a turn; a report is" {
+ try std.testing.expect(promptFromLine("/issue") == null);
+ try std.testing.expect(promptFromLine("/issue ") == null);
+ try std.testing.expectEqualStrings("the stream stalled", promptFromLine("/issue the stream stalled").?);
+}
diff --git a/src/jobs.zig b/src/jobs.zig
index 1068174d..f5f80e36 100644
--- a/src/jobs.zig
+++ b/src/jobs.zig
@@ -19,11 +19,7 @@ pub const ranOk = process_runner.ranOk;
const Agent = agent_mod.Agent;
-/// Same as `runCapped`, but spawns the child with an explicit working
-/// directory instead of inheriting the process's (#276 P0-1: a worktree-
-/// isolated subagent's `bash` calls need their own cwd — per-spawn, via
-/// `std.process.Child.Cwd`, never a process-wide chdir, so parallel sibling
-/// agents on the same pool each keep their own).
+/// `runCapped` with an explicit cwd (#276: per-spawn, never process-wide chdir).
pub fn runCappedCwd(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap: usize, stderr_cap: usize, deadline_ms: u64, cwd: std.process.Child.Cwd) !CappedRun {
return runCappedWithOptions(gpa, io, argv, stdout_cap, stderr_cap, deadline_ms, .{ .cwd = cwd });
}
@@ -116,12 +112,16 @@ const Jobs = struct {
pub var g_jobs: Jobs = .{};
+pub fn markPersistent(io: Io, id: u32) void {
+ g_jobs.mutex.lockUncancelable(io);
+ defer g_jobs.mutex.unlock(io);
+ if (g_jobs.find(id)) |job| job.persistent = true;
+}
+
/// Deterministic test pause after done becomes observable, before UI publish.
pub var completion_test_hook: ?*const fn (Io, u32) void = null;
-/// Drain whatever the MultiReader has buffered into the job's output buffer,
-/// dropping the oldest *unread* bytes past the cap (a chatty server must not
-/// grow memory unboundedly between bash_output polls). Caller holds the mutex.
+/// Drain MultiReader bytes into the job buffer; drop oldest unread past the cap.
fn jobDrain(job: *Job, gpa: Allocator, readers: []const *Io.Reader, now_ms: i64) void {
for (readers, 0..) |r, i| {
const b = r.buffered();
diff --git a/src/main.zig b/src/main.zig
index 9024c346..1715a6df 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("pr_local_checks.zig"), @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig"), @import("review_deadline.zig") };
+ _ = .{ @import("pr_local_checks.zig"), @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig"), @import("review_deadline.zig"), @import("issue_cmd.zig") };
}
diff --git a/src/mainloop.zig b/src/mainloop.zig
index f75c2cfa..4f199368 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -128,17 +128,17 @@ pub fn run(ctx: *Ctx) !void {
const goal_objective: ?[]const u8 = if (main_mod.json_mode) null else repl_glue.goalPromptFromLine(line);
const auto: ?goal_pacing.Autonomous = if (main_mod.json_mode) null else try goal_pacing.autonomousFromLine(ctx.arena, line, goal_objective);
const loop_prompt: ?[]const u8 = if (auto) |a| a.prompt else null;
- // A fresh line starts (or ends) a run: the wall clock begins here, stale todos_dirty is
- // dropped (a checklist finished BEFORE this prompt ended the next run at iteration 1, #318),
- // and an armed budget is echoed - a silently-eaten "5m" reads exactly like a truncated prompt.
+ // A fresh line starts (or ends) a run: wall clock begins here; stale todos_dirty is
+ // dropped, and an armed budget is echoed — a silently-eaten "5m" reads like a truncated prompt.
if (!is_loop_continuation) try goal_pacing.armAndAnnounce(&loop_clock, ctx.root, ctx.out, ctx.arena, util.unixMs(ctx.io), if (auto) |a| a.budget() else null);
var review_prompt: ?[]const u8 = if (!main_mod.json_mode) review.promptFromLine(line) else null;
+ const issue_report: ?[]const u8 = if (!main_mod.json_mode) @import("issue_cmd.zig").promptFromLine(line) else null;
if (!main_mod.json_mode) {
const l = if (line.len > 0 and line[0] == '/') line[1..] else line;
if (std.mem.eql(u8, l, "exit") or std.mem.eql(u8, l, "quit") or std.mem.eql(u8, l, "q")) break;
}
- if (!main_mod.json_mode and repl_glue.isSlashCommandLine(line) and auto == null and review_prompt == null) {
+ if (!main_mod.json_mode and repl_glue.isSlashCommandLine(line) and auto == null and review_prompt == null and issue_report == null) {
// Bare "/" on a TTY: open the filterable command menu.
if (ctx.interactive and line.len == 1) {
if (pickers.listPicker(ctx.root, ctx.arena, ctx.out, "Command ›", &pickers.command_menu)) |idx| {
@@ -157,7 +157,7 @@ pub fn run(ctx: *Ctx) !void {
// JSON lines may run a user turn, mutate the system prompt, or append a score.
var json_request: ?std.json.Parsed(Value) = null;
defer if (json_request) |*request| request.deinit();
- const base_msg: []const u8 = if (review_prompt) |rp| rp else if (loop_prompt) |lp| lp else if (main_mod.json_mode) blk: {
+ const base_msg: []const u8 = if (review_prompt) |rp| rp else if (issue_report) |ir| try @import("issue_cmd.zig").userText(ctx.arena, ir) else if (loop_prompt) |lp| lp else if (main_mod.json_mode) blk: {
json_request = std.json.parseFromSlice(Value, ctx.gpa, line, .{ .allocate = .alloc_if_needed }) catch {
ctx.root.emit(.{ .type = "error", .message = "invalid JSON (expect {\"type\":\"user\",\"text\":\"...\"})" });
continue;
diff --git a/src/mcp.zig b/src/mcp.zig
index 1b8269ad..1e8e5f53 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -482,8 +482,8 @@ pub const Registry = struct {
} else return .{ .text = try out_alloc.dupe(u8, "unknown MCP tool"), .is_error = true };
const server = reg.servers[tool.server_index];
-
- const params = try @import("mcp_turn_context.zig").params(reg.gpa, server.name, tool.original_name, input, context);
+ const turn_ctx = @import("mcp_turn_context.zig").effective(context, reg.io, server.name);
+ const params = try @import("mcp_turn_context.zig").params(reg.gpa, server.name, tool.original_name, input, turn_ctx);
defer reg.gpa.free(params);
reg.mutex.lockUncancelable(reg.io);
diff --git a/src/mcp_turn_context.zig b/src/mcp_turn_context.zig
index faa2d0cb..534b4e7f 100644
--- a/src/mcp_turn_context.zig
+++ b/src/mcp_turn_context.zig
@@ -9,6 +9,18 @@ pub const State = struct {
self.value = .{ .session = session, .turn = uuid(io) };
}
};
+
+var fallback: State = .{};
+
+/// cua_repl / node_repl require host metadata. If a caller forgot to pass
+/// turn context, mint a process-local pair rather than sending a request
+/// the adapter will reject.
+pub fn effective(context: ?Snapshot, io: std.Io, server: []const u8) ?Snapshot {
+ if (context) |ctx| return ctx;
+ if (!(std.mem.eql(u8, server, "cua_repl") or std.mem.eql(u8, server, "node_repl"))) return null;
+ fallback.begin(io);
+ return fallback.value;
+}
fn uuid(io: std.Io) [36]u8 {
var bytes: [16]u8 = undefined;
io.random(&bytes);
@@ -86,3 +98,19 @@ test "computer bridge metadata stays outside arguments and unrelated MCP calls"
}
}
}
+
+test "computer adapters still get turn metadata when the caller omitted it" {
+ const a = std.testing.allocator;
+ const input = try std.json.parseFromSlice(std.json.Value, a, "{}", .{});
+ defer input.deinit();
+ const ctx = effective(null, std.testing.io, "cua_repl");
+ try std.testing.expect(ctx != null);
+ const text = try params(a, "cua_repl", "js", input.value, ctx);
+ defer a.free(text);
+ const decoded = try std.json.parseFromSlice(std.json.Value, a, text, .{});
+ defer decoded.deinit();
+ const meta = decoded.value.object.get("_meta").?.object.get("x-codex-turn-metadata").?.object;
+ try std.testing.expect(meta.get("session_id").?.string.len == 36);
+ try std.testing.expect(meta.get("turn_id").?.string.len == 36);
+ try std.testing.expect(effective(null, std.testing.io, "ordinary") == null);
+}
diff --git a/src/named_work.zig b/src/named_work.zig
index a954b578..b7c29404 100644
--- a/src/named_work.zig
+++ b/src/named_work.zig
@@ -63,6 +63,12 @@ pub fn rememberFrom(self: *Agent) void {
pub fn beginTurn(self: *Agent) void {
rememberFrom(self);
if (!std.mem.eql(u8, taskOf(self), self.named_work_settled)) self.named_work_nudges = 0;
+ if (!self.sub) {
+ const fold = @import("native_fold.zig");
+ if (fold.noticeExplicit(taskOf(self))) {
+ self.invalidateRootTools();
+ }
+ }
}
/// True when `text` names a source path (not a greeting.txt-style data file).
diff --git a/src/native_fold.zig b/src/native_fold.zig
index 52da3980..e2039fa7 100644
--- a/src/native_fold.zig
+++ b/src/native_fold.zig
@@ -146,6 +146,25 @@ pub fn noticeContext(tokens: u64, compact_at: u64) bool {
return true;
}
+/// Lean/small turns hide rlm until a showcase. An explicit request for the
+/// REPL or persistent bindings is a predictable discovery path without
+/// advertising it on every short task.
+pub fn noticeExplicit(text: []const u8) bool {
+ if (listed() or !@import("rlm_spec.zig").available) return false;
+ var words = std.mem.tokenizeAny(u8, text, " \t\r\n,.;:!?()[]{}\"'`");
+ var saw = false;
+ while (words.next()) |word| {
+ if (std.ascii.eqlIgnoreCase(word, "rlm")) {
+ saw = true;
+ break;
+ }
+ }
+ if (!saw) return false;
+ showcaseRlm();
+ markLoaded("rlm");
+ return true;
+}
+
/// Folded-native listing and catalog discovery: hidden on small turns.
pub fn listed() bool {
return g_showcased or isLoaded("rlm");
diff --git a/src/native_fold_rlm.zig b/src/native_fold_rlm.zig
index 4ef85929..1787a194 100644
--- a/src/native_fold_rlm.zig
+++ b/src/native_fold_rlm.zig
@@ -236,3 +236,15 @@ test "showcasing rlm keeps the tools head bytes; schema rides the tail" {
fold.resetSession();
try std.testing.expect(!fold.listed());
}
+
+test "explicit rlm wording showcases without a context threshold" {
+ fold.resetRlmDiscovery();
+ defer fold.resetRlmDiscovery();
+ rlm.available = true;
+ rlm.sync();
+ 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/router_catalog.zig b/src/router_catalog.zig
index f356246d..b89f3e3a 100644
--- a/src/router_catalog.zig
+++ b/src/router_catalog.zig
@@ -58,7 +58,7 @@ fn startBackgroundRefresh(io: Io, gpa: Allocator, home: []const u8, spec: provid
bg_refresh_live = true;
}
-fn joinBackground(io: Io) void {
+pub fn shutdown(io: Io) void {
if (!bg_refresh_live) return;
bg_refresh.await(io);
bg_refresh_live = false;
@@ -530,7 +530,7 @@ pub fn ensureForStartup(io: Io, gpa: Allocator, arena: Allocator, home: []const
/// remains the offline fallback, and each live list is re-cached for the
/// next boot. Returns how many providers were pinged.
pub fn refreshForListing(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys: provider.Keys) usize {
- joinBackground(io);
+ shutdown(io);
pricing_db.ensure(io, gpa, arena, home, true); // the same freshness moment covers the price sheet, network and all
var futures: [provider.provider_specs.len + 1]?Io.Future(FetchOutcome) = @splat(null);
var pinged: usize = 0;
diff --git a/src/session_run.zig b/src/session_run.zig
index 35a5296a..66031cb7 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -247,6 +247,7 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m
// the registry until a peer's liveness probe reaps it.
presence.retire(io);
presence.deinit(gpa);
+ @import("router_catalog.zig").shutdown(io);
// #396: the run is over. The frontend hands the terminal back and latches
// its reader shut before main()'s teardown — a terminal-ownership move the
// sink owns now, in EVERY mode, exactly as the old unconditional call did.
@@ -469,6 +470,7 @@ pub fn finalizeSession(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer
// skips this and gets reaped by the next reader's liveness probe instead.
presence.retire(io);
presence.deinit(gpa); // its gpa-owned globals must not reach the exit-time leak check
+ @import("router_catalog.zig").shutdown(io);
@import("workspace_switch.zig").deinitDisplay(gpa);
if (!json_mode and root.messages.items.len > 0) {
const sink = engine_sink.writerSink(out);
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index f64559a7..d61b92e0 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -292,7 +292,7 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
// §2c: the judge is text-only. It ranks handed excerpts, so a toolset
// only buys it the chance to go re-read the repo — which is where its
// ~3 calls per score went. One judge, one call.
- .text_only = std.mem.eql(u8, kind, "judge_task"),
+ .text_only = std.mem.eql(u8, kind, "judge_task") or @import("task_intent.zig").classify(prompt) == .informational,
.reasoning = effort orelse .medium, // #292 follow-up: effort pin; unpinned workers keep the default depth, not the root's /effort
};
const sub_start = Io.Timestamp.now(ctx.io, .awake);
diff --git a/src/workflow.zig b/src/workflow.zig
index b1f60151..92ed021f 100644
--- a/src/workflow.zig
+++ b/src/workflow.zig
@@ -338,10 +338,9 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
const raw = if (task.get("prompt")) |p| (if (p == .string) p.string else "") else "";
if (raw.len == 0) return .{ .text = try gpa.dupe(u8, "each task needs a non-empty \"prompt\""), .is_error = true };
rawp.* = raw;
- // §3b, stolen from codex's patch-biased delegation: a contracted
- // worker is told to MAKE the edits and to end by listing every
- // changed path, so verify and the root review a diff, not a claim.
- const noted = if (contracted)
+ // Read-only analysis keeps its non-mutating brief across retries.
+ const mutating = escalation.mutatingTask(shapes.canonicalSlot(title), raw);
+ const noted = if (mutating)
try withContext(arena, escalation.contract_brief_note, raw)
else if (report_phase)
try withContext(arena, report_anchors.anchor_brief_note, raw)
@@ -387,12 +386,13 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
route_trace.emitSpawnProvider(ctx.io, ctx.tracer, label, seat.provider, seat.cellOf(niche), seat.sourceFor(override != null), override, niche);
fut.* = ctx.io.async(workflowTask, .{ ctx, label, prompt, override, niche, isolation, isolation_fallback, seat.pin });
}
- for (futures, outputs, labels, prompts, 0..) |*fut, *out, label, prompt, i| {
+ for (futures, outputs, labels, prompts, raws, 0..) |*fut, *out, label, prompt, raw, i| {
if (dup.rep[i] != i) continue;
// §3b — the edit contract, post-await: a contracted phase whose
// porcelain never moved becomes is_error, which the retry below
- // then picks up. #380's honesty flag composes inside it.
- out.* = escalation.contractCheck(gpa, ctx.io, ctx.agent_cwd, contracted, tree_before, report_anchors.anchorCheck(gpa, ctx.io, ctx.agent_cwd, report_phase, vision_ask.flagReport(gpa, fut.await(ctx.io), vision_ask.forPrompt(prompt))));
+ // then picks up. Informational tasks keep a non-mutating scope.
+ const mutating = escalation.mutatingTask(shapes.canonicalSlot(title), raw);
+ out.* = escalation.contractCheck(gpa, ctx.io, ctx.agent_cwd, mutating, tree_before, report_anchors.anchorCheck(gpa, ctx.io, ctx.agent_cwd, report_phase, vision_ask.flagReport(gpa, fut.await(ctx.io), vision_ask.forPrompt(prompt))));
// #63 — terminal per task, so a UI can settle that row without
// waiting for the phase (and before the retry pass below reruns it).
wfp.task(ctx.io, arena, run_id, phase_no, i + 1, tasks.len, label, if (out.is_error) "failed" else "completed");