graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(playbook): durable user constraints + distilled insights on one itemized ledger (#381, #383)
justrach9910ea47a706
diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.pyindex 47d09715..b2c91d4c 100644--- a/sdk/py/harness_sdk.py+++ b/sdk/py/harness_sdk.py@@ -14,7 +14,7 @@ import urllib.requestfrom typing import Iterator, OptionalMODELS = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"]-TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"]+TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"]PROVIDERS = ["anthropic", "codegraff", "deepseek", "openai", "minimax", "xiaomi", "kimi", "moonshot", "xai", "zai", "fugu", "fireworks", "mlx", "lmstudio", "codex"]diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.tsindex 23d327ec..386da965 100644--- a/sdk/ts/harness.ts+++ b/sdk/ts/harness.ts@@ -11,7 +11,7 @@ import { createInterface } from "node:readline";export const HARNESS_VERSION = "0.10";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "imagegen";+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "imagegen";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by `harness --json` (one JSON object per stdout line), each@@ -432,4 +432,4 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"];-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"];diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.tsindex 030fa2ef..e2a20552 100644--- a/sdk/ts/remote.ts+++ b/sdk/ts/remote.ts@@ -10,7 +10,7 @@export const HARNESS_VERSION = "0.10";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "imagegen";+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "imagegen";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by the bridge (same `--json` contract as the stdio SDK).@@ -323,4 +323,4 @@ export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerat}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"];-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"];diff --git a/src/agent.zig b/src/agent.zigindex 127a6ad2..b152a455 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -137,6 +137,7 @@ pub const Agent = struct {history_rewrites: u32 = 0, // bumped by compact()/emergencyTrim; state pasted into the dead history (e.g. the /loop checklist copy) must be re-carried (#318)session_name: []const u8 = "last", // autosave/resume target (<name>.session.json)session_title: ?[]const u8 = null, // human-readable title/rename metadata+ sys_base: []const u8 = "", // #381: the last BASE handed to prompts.setSystemPrompts, WITHOUT the playbook block — what a mid-session constraint re-composes from (playbook_glue.refreshRoot)sys_strict: []const u8 = prompts.main_system_prompt_strict,sys_ultra: []const u8 = prompts.main_system_prompt ++ prompts.ultracode_system_note, // #326: comptime defaults only — prompts.setSystemPrompts() is the sole production writersys_ultra_strict: []const u8 = prompts.main_system_prompt_strict ++ prompts.ultracode_system_note, // composes onto sys_strict, never replaces itdiff --git a/src/agent_eval.zig b/src/agent_eval.zigindex ab2ea51a..b5570c52 100644--- a/src/agent_eval.zig+++ b/src/agent_eval.zig@@ -24,6 +24,7 @@ const trace = @import("trace.zig");const fleet = @import("fleet.zig");const main_mod = @import("main.zig");const route_policy = @import("route_policy.zig"); // #372 (shape, role, tier) coordinates on the local capture rows+const playbook_reflect = @import("playbook_reflect.zig"); // #383 Reflector: one bounded distillation per process, on a target-met evaltest {_ = @import("agent_eval_tests.zig");@@ -113,6 +114,14 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {bt.recordMisprediction(eval_turn, commitment_id, .{ .pass = true }, .{ .pass = false, .exit = exit_code }, "target not met");self.appendEvalLog(note, det, judge, combined, exit_code, met) catch {};eval_memory.record(self, note, combined, exit_code, met);+ // #383 Reflector: a target-met eval is the moment a run is verifiably+ // finished, so distil it into candidate playbook bullets — ONCE per+ // process, one tool-less model call on the worker seat. Gated inside on+ // trace.g_traj, the same null-sink guard the local DGM capture below+ // uses, which is what keeps agent_eval_tests' stub Agent (undefined+ // provider/client, and a second eval that DOES meet its target) out of a+ // live model call.+ if (met) playbook_reflect.afterEval(self, note, combined orelse 0, run.stdout);// Feed the eval-driven score into the fleet (docs/hyperagents.md §9.B):// on a NEW BEST, submit the genome (this agent's persona) with its achieveddiff --git a/src/agent_tools.zig b/src/agent_tools.zigindex 4e057c74..5c0f45b3 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -44,6 +44,7 @@ const exec = @import("exec.zig");const execTool = exec.execTool;const brief_diversity = @import("brief_diversity.zig"); // #382: N sibling spawns in one batch are a fleet+const playbook_glue = @import("playbook_glue.zig"); // #381: the note_constraint meta armconst util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupted-elapsed measurementconst protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event@@ -353,6 +354,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {};return .{ .text = try clockSleepSuccessText(self.arena, parsed.ms, parsed.clamped), .is_error = false };}+ if (std.mem.eql(u8, call.name, "note_constraint")) return playbook_glue.noteConstraint(self, call.input); // #381: append-only, and it re-composes the root's own promptif (std.mem.eql(u8, call.name, "ask_user")) return self.askUser(call);// todo_readreturn .{ .text = self.renderTodos(goal_state.currentEpoch(self.goal)), .is_error = false };diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 796f9ec2..8cd3dfd7 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -29,6 +29,7 @@ pub const commands = [_]Item{.{ .name = "/goal", .usage = "/goal [30m] [text|pause|resume|status|clear]", .desc = "set a standing objective and work it autonomously; an optional 30s/30m/2h budget paces the run; pause/resume steering, status shows state, clear removes it" },.{ .name = "/loop", .usage = "/loop [30m] <prompt>", .desc = "the same autonomous run as /goal, without adopting a standing objective" },.{ .name = "/review", .usage = "/review <target or instructions>", .desc = "run one isolated read-only review pass; no edits, delegation, or workflows" },+ .{ .name = "/never", .usage = "/never [<text>|rm <id>]", .desc = "standing constraints that ride every subagent brief and survive compaction; bare lists them, rm <id> retires one (alias /constraint)" },.{ .name = "/plan", .desc = "toggle plan mode: read-only explore + propose; writes/edits denied" },.{ .name = "/ultracode", .desc = "toggle persistent workflow mode; bare opens an on/off picker, or /ultracode on|off" },.{ .name = "/fallback", .usage = "/fallback [allow|remove|off]", .desc = "opt-in cross-provider fallback for this workspace (same-provider rollout stays on)" },diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex 84f29255..eadf80da 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -58,6 +58,7 @@ const listPicker = pickers.listPicker;const trace = @import("trace.zig");const commands_privacy = @import("commands_privacy.zig");+const playbook_glue = @import("playbook_glue.zig"); // #381 /never: the durable user-constraint ledgerconst learning_privacy = @import("learning_privacy.zig");fn providerModelCount(provider_id: []const u8) usize {@@ -135,6 +136,7 @@ fn showModelsHealth(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer/// to handleRest() for the unknown-command/help terminal stage.pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {if (try commands_privacy.tryHandle(root, line, out)) return true;+ if (try playbook_glue.command(root, arena, line, out)) return true; // #381 /never | /constraint// #321: doctor.zig shipped with a catalog entry but no dispatch, so /doctor// was advertised in /help and the `/` menu while answering "unknown command".if (std.mem.eql(u8, line, "/doctor")) {diff --git a/src/playbook.zig b/src/playbook.zignew file mode 100644index 00000000..20c5aec1--- /dev/null+++ b/src/playbook.zig@@ -0,0 +1,386 @@+//! #381 + #383 — the itemized playbook: one durable, project-local ledger of+//! short imperative bullets that ride every brief.+//!+//! Two issues, one substrate, because they are the same bug seen from two+//! sides. #381: a user said "no navigation dots", the root compacted, and+//! fresh subagents — who were never told — put the dots back. #383: 120+//! subagent reports full of durable repo knowledge ("no mobile menu exists,+//! don't invent one") evaporated with the context that held them. In both+//! cases the harness HAD the fact and dropped it on the floor between the+//! place it was learned and the brief that needed it.+//!+//! ACE (Zhang et al., ICLR 2026) supplies the shape and the hard rule:+//!+//! * ITEMIZED, not a blob. Iteratively asking a model to rewrite a+//! prompt-sized artifact causes context collapse and brevity bias — the+//! failure #383 quotes. Bullets with stable ids merge instead.+//! * CURATION IS DETERMINISTIC CODE. Nothing in this file asks a model+//! what the playbook should contain. add/retire are explicit ops, dedupe+//! is an exact match on normalized text, and the caps are constants. A+//! model may PROPOSE an item (the #383 reflector) and the user may state+//! one (#381), but only this code decides what lands.+//!+//! ON-DISK FORMAT — `.graff/playbook.jsonl`, append-only JSONL, matching the+//! `.graff/trajectories` conventions (one self-describing JSON object per+//! line, written whole or not at all, never rewritten in place):+//!+//! {"v":1,"op":"add","id":"pb-3f8c1d02","text":"…","source":"user",+//! "provenance":"user:1754…","created_at":1754…}+//! {"v":1,"op":"retire","id":"pb-3f8c1d02","t":1754…}+//!+//! A retire is a NEW RECORD (a tombstone), never an edit, so a concurrent+//! reader mid-append sees either the old state or the new one — never a torn+//! file. `parse` replays the log in order and lets the last op for an id win,+//! which also makes re-adding a retired item work for free.+//!+//! IDS ARE CONTENT-DERIVED: `pb-` + 32 bits of Wyhash over the NORMALIZED+//! text. That makes dedupe and identity the same operation — two phrasings+//! that normalize identically cannot both exist, and an id is stable across+//! sessions and machines, which is what lets a later change attribute+//! per-item fitness to it.+//!+//! ASSEMBLY READS THE FILE, NEVER CONVERSATION MEMORY. `blockNow`'s input is+//! the ledger on disk at the moment a brief is built. That single choice is+//! what makes compaction survival automatic rather than a feature: there is+//! no in-context copy for compaction to summarize away, and a brand-new+//! session in the same project starts with the same constraints.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const util = @import("util.zig");+const trace = @import("trace.zig");++pub const dir = ".graff";+pub const path = ".graff/playbook.jsonl";++/// Whole-ledger read cap. A playbook is bullets, not a corpus; past this the+/// file is something else and injecting it would be the bug, not the fix.+pub const max_file_bytes = 512 * 1024;+/// Longest single item, in bytes, kept on disk and injected.+pub const max_text = 240;+/// #383 curator ceiling on stored LEARNED items. v1 refuses past it with a+/// note rather than evicting: eviction needs per-item fitness to be safe, and+/// that attribution is deliberately follow-up scope.+pub const max_learned = 100;++/// Injection caps. User items outrank learned ones on every axis — more of+/// them, more bytes, and always printed first — because a user constraint is+/// a rule and a learned bullet is a hint.+pub const user_block_items = 30;+pub const user_block_bytes = 2048;+pub const learned_block_items = 12;+pub const learned_block_bytes = 1024;++pub const user_header = "HARD CONSTRAINTS (user, do not violate):";+pub const learned_header = "PLAYBOOK (learned, advisory):";++pub const Source = enum {+ /// #381: a rejection the user stated. Never model-editable, hard-injected.+ user,+ /// #383: an insight distilled from a scored run. Advisory, capped, and+ /// printed after every user item.+ learned,++ pub fn parse(s: []const u8) Source {+ return if (std.mem.eql(u8, s, "learned")) .learned else .user;+ }+};++pub const Item = struct {+ id: []const u8,+ text: []const u8,+ source: Source,+ /// What minted it: `user:<unix ms>` for a typed/observed rejection,+ /// `run:<trajectory run id>` for a distilled one.+ provenance: []const u8 = "",+ created_at: i64 = 0,+};++/// Why an `add` did or did not land. A refusal is reported, never silent:+/// the model and the user both need to know a constraint was NOT recorded.+pub const Add = struct {+ ok: bool = false,+ id: []const u8 = "",+ /// Human/model-facing explanation; "" on success.+ reason: []const u8 = "",+};++/// Word bytes for normalization: ASCII alphanumerics plus every non-ASCII+/// byte, so a UTF-8 word stays one token instead of shattering (the same rule+/// brief_diversity.isWordByte uses, and for the same reason).+fn isWordByte(c: u8) bool {+ return std.ascii.isAlphanumeric(c) or c >= 0x80;+}++/// U+2000–U+206F (General Punctuation) encodes as E2 80 xx / E2 81 xx, and+/// that block is where a model or a paste actually gets its punctuation: em+/// and en dashes, curly quotes, the ellipsis, the bullet. They are dropped+/// like their ASCII cousins — otherwise `no dots — really` and `no dots+/// really` would be two separate constraints forever. Every OTHER non-ASCII+/// byte stays a word byte, so a non-Latin constraint is not shredded.+fn isPunctSeq(text: []const u8, i: usize) bool {+ return i + 2 < text.len and text[i] == 0xE2 and (text[i + 1] == 0x80 or text[i + 1] == 0x81);+}++/// Lowercase, drop punctuation, collapse runs of everything else to one+/// space. This is the whole dedupe key: "No emojis in code comments!" and+/// "no emojis in code comments" are the same constraint stated twice, and a+/// ledger that held both would inject the same rule twice forever.+pub fn normalize(out: []u8, text: []const u8) []const u8 {+ var n: usize = 0;+ var pending_space = false;+ var i: usize = 0;+ while (i < text.len) {+ if (isPunctSeq(text, i)) {+ pending_space = true;+ i += 3;+ continue;+ }+ const c = text[i];+ i += 1;+ if (!isWordByte(c)) {+ pending_space = true;+ continue;+ }+ if (n > 0 and pending_space and n < out.len) {+ out[n] = ' ';+ n += 1;+ }+ pending_space = false;+ if (n == out.len) break;+ out[n] = std.ascii.toLower(c);+ n += 1;+ }+ return out[0..n];+}++/// `pb-` + 32 bits of Wyhash over the normalized text (11 bytes).+pub fn idFor(out: *[11]u8, text: []const u8) []const u8 {+ var nbuf: [max_text]u8 = undefined;+ const h = std.hash.Wyhash.hash(0x381383, normalize(&nbuf, text));+ return std.fmt.bufPrint(out, "pb-{x:0>8}", .{@as(u32, @truncate(h))}) catch out[0..0];+}++fn strOf(o: std.json.ObjectMap, key: []const u8) ?[]const u8 {+ const v = o.get(key) orelse return null;+ return if (v == .string) v.string else null;+}++/// Replay the append-only log into the live item set, oldest first. Malformed+/// lines are skipped rather than fatal — a half-written tail from a killed+/// process must cost at most its own record.+pub fn parse(arena: Allocator, data: []const u8) []const Item {+ var list: std.ArrayList(Item) = .empty;+ var lines = std.mem.splitScalar(u8, data, '\n');+ while (lines.next()) |raw| {+ const line = std.mem.trim(u8, raw, " \t\r");+ if (line.len == 0) continue;+ const v = std.json.parseFromSliceLeaky(std.json.Value, arena, line, .{}) catch continue;+ if (v != .object) continue;+ const id = strOf(v.object, "id") orelse continue;+ var at: ?usize = null;+ for (list.items, 0..) |item, i| if (std.mem.eql(u8, item.id, id)) {+ at = i;+ break;+ };+ if (std.mem.eql(u8, strOf(v.object, "op") orelse "add", "retire")) {+ if (at) |i| _ = list.orderedRemove(i);+ continue;+ }+ const text = strOf(v.object, "text") orelse continue;+ const created = v.object.get("created_at");+ const item: Item = .{+ .id = id,+ .text = text,+ .source = Source.parse(strOf(v.object, "source") orelse "user"),+ .provenance = strOf(v.object, "provenance") orelse "",+ .created_at = if (created) |c| (if (c == .integer) c.integer else 0) else 0,+ };+ if (at) |i| list.items[i] = item else list.append(arena, item) catch break;+ }+ return list.items;+}++/// The live ledger for the current working directory. An absent or unreadable+/// file is an empty playbook, never an error: every caller is on a path that+/// must keep working without one.+pub fn load(io: Io, arena: Allocator) []const Item {+ const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(max_file_bytes)) catch return &.{};+ return parse(arena, data);+}++pub fn countOf(items: []const Item, source: Source) usize {+ var n: usize = 0;+ for (items) |item| n += @intFromBool(item.source == source);+ return n;+}++pub fn find(items: []const Item, id: []const u8) ?Item {+ for (items) |item| if (std.mem.eql(u8, item.id, id)) return item;+ return null;+}++/// Append one already-serialized record. Positional write at the current end+/// of file so a whole line lands at once (serve_events.EventLog's shape).+fn appendLine(io: Io, line: []const u8) bool {+ Io.Dir.cwd().createDirPath(io, dir) catch {};+ const f = Io.Dir.cwd().createFile(io, path, .{ .truncate = false }) catch return false;+ defer f.close(io);+ const st = f.stat(io) catch return false;+ f.writePositionalAll(io, line, st.size) catch return false;+ return true;+}++/// The one way an item is created. DETERMINISTIC: trim, cap, normalize,+/// derive the id, refuse an exact-normalized duplicate, enforce the learned+/// ceiling, append. No model is consulted and nothing existing is rewritten.+pub fn add(io: Io, arena: Allocator, text_in: []const u8, source: Source, provenance: []const u8) Add {+ const trimmed = std.mem.trim(u8, text_in, " \t\r\n-*");+ const text = util.utf8Prefix(trimmed, max_text);+ var nbuf: [max_text]u8 = undefined;+ if (normalize(&nbuf, text).len == 0) return .{ .reason = "empty constraint text" };+ var idbuf: [11]u8 = undefined;+ const id = arena.dupe(u8, idFor(&idbuf, text)) catch return .{ .reason = "out of memory" };+ const items = load(io, arena);+ if (find(items, id) != null) return .{ .id = id, .reason = "already recorded (same normalized text)" };+ if (source == .learned and countOf(items, .learned) >= max_learned)+ return .{ .id = id, .reason = "learned playbook is at its 100-item cap; retire some with /never rm <id> first" };+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ s.write(.{+ .v = @as(u8, 1),+ .op = "add",+ .id = id,+ .text = text,+ .source = @tagName(source),+ .provenance = provenance,+ .created_at = util.unixMs(io),+ }) catch return .{ .id = id, .reason = "could not serialize the record" };+ aw.writer.writeByte('\n') catch return .{ .id = id, .reason = "could not serialize the record" };+ if (!appendLine(io, aw.writer.buffered())) return .{ .id = id, .reason = "could not write " ++ path };+ return .{ .ok = true, .id = id };+}++/// Tombstone `id`. Returns false when no live item carries it, so a caller+/// can say "unknown id" instead of writing a tombstone for nothing.+pub fn retire(io: Io, arena: Allocator, id: []const u8) bool {+ if (find(load(io, arena), id) == null) return false;+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ s.write(.{ .v = @as(u8, 1), .op = "retire", .id = id, .t = util.unixMs(io) }) catch return false;+ aw.writer.writeByte('\n') catch return false;+ return appendLine(io, aw.writer.buffered());+}++fn writeSection(w: *Io.Writer, items: []const Item, source: Source, header: []const u8, cap_items: usize, cap_bytes: usize) !void {+ var shown: usize = 0;+ var used: usize = 0;+ var omitted: usize = 0;+ // Newest first: the most recent "no" is the one most likely to be about+ // the work in flight, and it must survive the cap.+ var i = items.len;+ while (i > 0) {+ i -= 1;+ const item = items[i];+ if (item.source != source) continue;+ if (shown >= cap_items or used + item.text.len + 3 > cap_bytes) {+ omitted += 1;+ continue;+ }+ if (shown == 0) try w.print("{s}\n", .{header});+ try w.print("- {s}\n", .{item.text});+ shown += 1;+ used += item.text.len + 3;+ }+ // An unstated truncation is a lie by omission: a worker told "these are+ // the constraints" must know when it was told only some of them.+ if (omitted > 0) try w.print("[{d} older item(s) omitted by the injection cap — the full ledger is {s}]\n", .{ omitted, path });+}++/// The injection block for `items`, or "" when there is nothing to say.+/// User items always precede learned ones and are capped more generously;+/// each section names itself so a worker can tell a rule from a hint.+pub fn blockFrom(arena: Allocator, items: []const Item) []const u8 {+ if (items.len == 0) return "";+ var aw: Io.Writer.Allocating = .init(arena);+ writeSection(&aw.writer, items, .user, user_header, user_block_items, user_block_bytes) catch return "";+ if (aw.writer.buffered().len > 0) aw.writer.writeByte('\n') catch return "";+ writeSection(&aw.writer, items, .learned, learned_header, learned_block_items, learned_block_bytes) catch return "";+ const out = std.mem.trim(u8, aw.writer.buffered(), "\n");+ return if (out.len == 0) "" else out;+}++/// The block for the ledger as it exists on disk RIGHT NOW. This is the+/// function every injection site calls, and reading the file here rather+/// than caching a copy in the conversation is the whole compaction-survival+/// mechanism.+pub fn blockNow(io: Io, arena: Allocator) []const u8 {+ return blockFrom(arena, load(io, arena));+}++/// Prepend the block to a brief. Identity when the ledger is empty, so a+/// project that never recorded anything pays nothing.+pub fn rideBrief(io: Io, arena: Allocator, prompt: []const u8) []const u8 {+ const b = blockNow(io, arena);+ if (b.len == 0) return prompt;+ return std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ b, prompt }) catch prompt;+}++/// Armed once by prompts.setRootSystemPrompts (production root agents only).+/// Unit tests never arm it, so prompts.setSystemPrompts stays the pure string+/// funnel its own tests assert — and no test path can reach the filesystem+/// through an `undefined` Io.+pub var g_root_inject: bool = false;++/// The ROOT's system prompt for the ledger as it exists on disk right now:+/// base, then the same block every worker brief carries. It lives in the+/// SYSTEM prompt rather than in a per-turn user message on purpose — a+/// re-pasted note lands in compaction input every single turn (#326's+/// lesson), while the system prompt is re-sent verbatim on every request and+/// is exactly what a compacted conversation cannot lose.+pub fn composeRoot(io: Io, arena: Allocator, base: []const u8) []const u8 {+ const items = load(io, arena);+ traceActive(arena, items);+ const b = blockFrom(arena, items);+ if (b.len == 0) return base;+ return std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ base, b }) catch base;+}++/// Comma-joined active ids, capped, for the trajectory row below.+pub fn idList(arena: Allocator, items: []const Item) []const u8 {+ var aw: Io.Writer.Allocating = .init(arena);+ for (items, 0..) |item, i| {+ if (i > 0) aw.writer.writeByte(',') catch break;+ aw.writer.writeAll(item.id) catch break;+ }+ return util.utf8Prefix(aw.writer.buffered(), 1024);+}++/// Fingerprint of the last emitted `kind:"playbook"` row, so re-composing an+/// unchanged ledger does not write the same row again.+var g_last_row: u64 = 0;++/// A NEW `kind:"playbook"` trajectory row naming which item ids were active,+/// rather than new columns on an existing row — the same additive discipline+/// #382's `kind:"diversity"` row established, and what a later change joins+/// against to attribute per-item fitness. Best-effort; never fails a caller.+pub fn traceActive(arena: Allocator, items: []const Item) void {+ const tj = trace.g_traj orelse return;+ const ids = idList(arena, items);+ const fp = std.hash.Wyhash.hash(0x381383, ids);+ if (fp == g_last_row) return;+ g_last_row = fp;+ tj.node(.{+ .kind = "playbook",+ .items = items.len,+ .user_items = countOf(items, .user),+ .learned_items = countOf(items, .learned),+ .ids = ids,+ .t = tj.elapsedMs(),+ });+}++test {+ _ = @import("playbook_tests.zig");+}diff --git a/src/playbook_glue.zig b/src/playbook_glue.zignew file mode 100644index 00000000..1a98b523--- /dev/null+++ b/src/playbook_glue.zig@@ -0,0 +1,120 @@+//! #381 capture surfaces for the playbook substrate: the `/never` REPL+//! command, the root-only `note_constraint` meta tool, and the root+//! system-prompt refresh both of them trigger.+//!+//! Split from playbook.zig so the substrate stays a leaf over std/util/trace.+//! Everything that needs an `*Agent` lives here.+//!+//! WHY TWO CAPTURE SURFACES. `/never` is for the user who knows they are+//! stating a standing rule. `note_constraint` is for the far commoner case+//! #381 actually reports: the user rejects something mid-conversation ("no,+//! stop adding scroll hints") and never thinks of it as configuration. The+//! root already understands that rejection at the moment it happens — the+//! only missing piece was somewhere durable to put it.+//!+//! THE TOOL CANNOT WIDEN ITSELF. `note_constraint` appends `source=user`+//! items and nothing else: no retire, no edit, no learned items, no reading+//! back a ledger it could then rewrite. A model that finds a constraint+//! inconvenient has no mechanism to remove it — only the user does, through+//! `/never rm <id>`. Same shape as the #366 gate: the capability the model+//! gets is strictly the one that makes it safer to run unattended.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const Agent = @import("agent.zig").Agent;+const ExecResult = @import("tools.zig").ExecResult;+const json_args = @import("json_args.zig");+const prompts = @import("prompts.zig");+const playbook = @import("playbook.zig");+const ansi = @import("ansi.zig");+const style = &ansi.style;++/// Re-derive the root's four system-prompt variants from its stored BASE, so+/// a constraint recorded mid-session reaches the very next request instead of+/// waiting for a restart. Cheap: one small file read plus four allocPrints,+/// only on an actual mutation. Best-effort — a failed refresh leaves the+/// previous (still valid) prompt in place, and the ledger on disk is already+/// correct for every brief assembled after it.+pub fn refreshRoot(agent: *Agent, arena: Allocator) void {+ if (agent.sub or agent.sys_base.len == 0) return;+ prompts.setSystemPrompts(agent, agent.sys_base, arena) catch {};+}++/// The `note_constraint` meta-tool handler (root-only; the spec lives in+/// root_specs, so a subagent is never even told it exists). Append-only by+/// construction — see this file's header.+pub fn noteConstraint(agent: *Agent, input: std.json.Value) ExecResult {+ const text = if (json_args.object(input)) |o| (json_args.str(o, "text") orelse "") else "";+ if (std.mem.trim(u8, text, " \t\r\n").len == 0) return .{+ .text = "note_constraint needs a `text` field: one short imperative line, e.g. \"never add scroll hints or progress dots\"",+ .is_error = true,+ };+ var prov_buf: [32]u8 = undefined;+ const provenance = std.fmt.bufPrint(&prov_buf, "user:{d}", .{@import("util.zig").unixMs(agent.io)}) catch "user";+ const r = playbook.add(agent.io, agent.arena, text, .user, provenance);+ if (!r.ok) return .{+ .text = std.fmt.allocPrint(agent.arena, "constraint NOT recorded ({s}){s}{s}", .{+ r.reason,+ if (r.id.len > 0) " — existing id " else "",+ r.id,+ }) catch "constraint not recorded",+ // An already-recorded constraint is the desired end state, not a+ // failure: flagging it as an error would push the model into+ // retrying or apologising for a ledger that is already correct.+ .is_error = !std.mem.eql(u8, r.reason, "already recorded (same normalized text)"),+ };+ refreshRoot(agent, agent.arena);+ agent.say(" {s}⛔ constraint recorded ({s}){s} {s}\n", .{ style.yellow, r.id, style.reset, text }) catch {};+ return .{ .text = std.fmt.allocPrint(agent.arena, "constraint recorded as {s}. It is now in {s} and rides every subagent, workflow and pipeline brief from here on, in this session and in later ones — you do not need to restate it.", .{ r.id, playbook.path }) catch "constraint recorded", .is_error = false };+}++fn list(io: Io, arena: Allocator, out: *Io.Writer) !void {+ const items = playbook.load(io, arena);+ if (items.len == 0) {+ try out.print("playbook empty — /never <text> records a standing constraint ({s})\n", .{playbook.path});+ try out.flush();+ return;+ }+ try out.print("{s}playbook{s} — {s}\n", .{ style.bold, style.reset, playbook.path });+ for (items) |item| try out.print(" {s} {s:<9} {s}\n", .{ item.id, @tagName(item.source), item.text });+ try out.print("{d} item(s) · /never <text> adds one · /never rm <id> retires one\n", .{items.len});+ try out.flush();+}++/// `/never` (alias `/constraint`). Returns false when `line` is neither, so+/// the caller falls through to the rest of the command chain.+///+/// /never list the live ledger+/// /never <text> record a user constraint+/// /never rm <id> retire one (the ONLY removal path there is)+pub fn command(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {+ const rest = for ([_][]const u8{ "/never", "/constraint" }) |name| {+ if (std.mem.eql(u8, line, name)) break "";+ if (std.mem.startsWith(u8, line, name) and line.len > name.len and line[name.len] == ' ') break line[name.len + 1 ..];+ } else return false;+ const arg = std.mem.trim(u8, rest, " \t");+ if (arg.len == 0) {+ try list(root.io, arena, out);+ return true;+ }+ if (std.mem.startsWith(u8, arg, "rm ") or std.mem.startsWith(u8, arg, "remove ")) {+ const id = std.mem.trim(u8, arg[if (arg[0] == 'r' and arg[1] == 'm') 3 else 7..], " \t");+ if (playbook.retire(root.io, arena, id)) {+ refreshRoot(root, arena);+ try out.print("retired {s} — it no longer rides new briefs (the record stays in the log as a tombstone)\n", .{id});+ } else try out.print("no live playbook item with id '{s}' — /never lists them\n", .{id});+ try out.flush();+ return true;+ }+ var prov_buf: [32]u8 = undefined;+ const provenance = std.fmt.bufPrint(&prov_buf, "user:{d}", .{@import("util.zig").unixMs(root.io)}) catch "user";+ const r = playbook.add(root.io, arena, arg, .user, provenance);+ if (r.ok) {+ refreshRoot(root, arena);+ try out.print("{s}⛔ recorded {s}{s} — this now rides every brief, in this session and later ones\n", .{ style.yellow, r.id, style.reset });+ } else try out.print("not recorded: {s}\n", .{r.reason});+ try out.flush();+ return true;+}diff --git a/src/playbook_reflect.zig b/src/playbook_reflect.zignew file mode 100644index 00000000..669e034f--- /dev/null+++ b/src/playbook_reflect.zig@@ -0,0 +1,175 @@+//! #383 Reflector — the one place a MODEL is allowed near the playbook, and+//! only ever as a proposer.+//!+//! ACE's Generator → Reflector → Curator, mapped onto machinery graff already+//! has: the Generator is a normal eval-scored run (the trajectory archive+//! already captures it), the Reflector is the single bounded call below, and+//! the Curator is playbook.add — deterministic code that dedupes, caps, and+//! decides. The model returns candidate bullets; it never sees the ledger,+//! never edits it, and cannot retire anything. That asymmetry is the whole+//! point of the ACE result: iterative model REWRITES of a prompt-sized+//! artifact collapse, iterative deterministic MERGES of identified items do+//! not.+//!+//! COST DISCIPLINE (v1). Exactly ONE extra model call per process, fired on+//! the FIRST eval that meets its target — the moment a run is verifiably+//! finished and there is a real outcome to distil. Not every turn, not every+//! eval, not every subagent report. The call carries no tools (`request(null)`+//! — the title-generation shape), so it cannot fan out, and it runs on the+//! WORKER seat (childProvider), inheriting the same routing every subagent+//! gets rather than reserving a model of its own.+//!+//! SCOPE CUT, stated: distilling from FAILED runs, and per-item fitness+//! attribution (retiring bullets whose attributed score goes negative), are+//! follow-up. v1 records which item ids were active per run — playbook's+//! `kind:"playbook"` trajectory row — which is precisely the join a later+//! change needs and cannot reconstruct after the fact.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const Agent = @import("agent.zig").Agent;+const playbook = @import("playbook.zig");+const playbook_glue = @import("playbook_glue.zig");+const subagent_run = @import("subagent_run.zig");+const title = @import("title.zig");+const trace = @import("trace.zig");+const util = @import("util.zig");+const textMessage = @import("messages.zig").textMessage;++/// At most this many bullets are taken from one reflection, however many the+/// model returns. Three is the issue's own number and it is also the point+/// past which a "lesson" is really a summary of the run.+pub const max_candidates = 3;+/// Shortest useful bullet. Below this a line is a fragment ("yes", "done"),+/// not a durable insight, and normalizing it would collide with anything.+const min_candidate_len = 12;++/// One model call per process, latched here. A session that evals ten times+/// distils once.+var g_reflected: bool = false;++/// Reset seam for the tests — production never calls it.+pub fn resetForTest() void {+ g_reflected = false;+}++fn stripBullet(line_in: []const u8) []const u8 {+ var s = std.mem.trim(u8, line_in, " \t\r");+ // "- x", "* x", "• x", "1. x", "2) x" — every shape a model reaches for.+ if (s.len > 1 and (s[0] == '-' or s[0] == '*')) s = s[1..];+ if (std.mem.startsWith(u8, s, "\xe2\x80\xa2")) s = s[3..];+ if (s.len > 2 and std.ascii.isDigit(s[0]) and (s[1] == '.' or s[1] == ')')) s = s[2..];+ return std.mem.trim(u8, s, " \t\r");+}++/// Pull up to `max_candidates` bullet lines out of a model reply. Pure and+/// total: any text at all yields a (possibly empty) list, so the reflector+/// degrades to "learned nothing" instead of failing a finished eval run.+///+/// Deliberately strict about what counts as a bullet. A model asked for+/// bullets also emits a preamble ("Here are three insights:"), and a+/// preamble curated into the playbook would be injected into every future+/// brief forever — the cost of a false positive is permanent, so only lines+/// that actually look like list items are taken.+pub fn parseCandidates(out: *[max_candidates][]const u8, reply: []const u8) [][]const u8 {+ var n: usize = 0;+ var lines = std.mem.splitScalar(u8, reply, '\n');+ while (lines.next()) |raw| {+ if (n == max_candidates) break;+ const trimmed = std.mem.trim(u8, raw, " \t\r");+ const bulleted = trimmed.len > 1 and (trimmed[0] == '-' or trimmed[0] == '*' or+ std.mem.startsWith(u8, trimmed, "\xe2\x80\xa2") or+ (std.ascii.isDigit(trimmed[0]) and (trimmed[1] == '.' or trimmed[1] == ')')));+ if (!bulleted) continue;+ const text = stripBullet(trimmed);+ if (text.len < min_candidate_len) continue;+ // A model that has nothing to say tends to say so in list form.+ if (std.ascii.eqlIgnoreCase(util.utf8Prefix(text, 4), "none")) continue;+ out[n] = util.utf8Prefix(text, playbook.max_text);+ n += 1;+ }+ return out[0..n];+}++fn reflectPrompt(arena: Allocator, note: []const u8, score: f64, target: u8, output: []const u8) ?[]const u8 {+ const evidence = util.utf8Prefix(if (output.len > 1200) output[output.len - 1200 ..] else output, 1200);+ return std.fmt.allocPrint(arena,+ \\A coding run in this repository just finished and its automated check scored {d:.0}/100 against a target of {d}.+ \\+ \\What the author said they changed: {s}+ \\+ \\Tail of the check's output:+ \\---+ \\{s}+ \\---+ \\+ \\Write at most {d} bullets of DURABLE, REPO-SPECIFIC knowledge worth keeping for future work here — the kind of thing a fresh agent with no memory of this run would waste time rediscovering ("this repo's tests need X before Y", "module Z is generated, edit the template instead", "the build fails unless W is regenerated").+ \\+ \\Rules: one short imperative line per bullet, starting with "- ". No preamble, no summary of what happened, nothing that is only true of this one change, nothing already obvious from the repository's own README. If there is no durable lesson here, reply with exactly: none+ , .{ score, target, if (note.len > 0) note else "(no note given)", evidence, max_candidates }) catch null;+}++/// The distillation call itself: a throwaway one-message agent with NO tools,+/// on the worker seat. Mirrors title.titleTask, which is the established+/// shape in this codebase for "one cheap auxiliary completion".+fn askModel(self: *Agent, prompt: []const u8) ?[]const u8 {+ var arena_state = std.heap.ArenaAllocator.init(self.gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const seat = subagent_run.childProvider(self.provider, self.subagent_provider, self.subagent_cross_provider);+ var agent: Agent = .{+ .gpa = self.gpa,+ .arena = arena,+ .io = self.io,+ .client = self.client,+ .provider = seat,+ .messages = std.json.Array.init(arena),+ .sub = true, // never touches stdout or the root's state+ .label = "reflect",+ .out = null,+ .tracer = self.tracer,+ .run_budget = self.run_budget,+ .call_kind = .judge, // an auxiliary, bounded, non-recursive call — the judge's class+ .responses_output_limit = 512,+ .sys_override = "You distil durable engineering lessons from a finished run. Reply with terse imperative bullets and nothing else.",+ };+ defer agent.tools_used.deinit(self.gpa);+ agent.messages.append(textMessage(arena, "user", prompt) catch return null) catch return null;+ const root = agent.request(null) catch return null;+ return self.arena.dupe(u8, title.assistantText(seat.kind, root)) catch null;+}++/// Called from agent_eval.runEval once a scored run has met its target.+///+/// The `trace.g_traj` gate is load-bearing twice over: it is where the run id+/// used as provenance comes from, AND it is the same null-sink guard the+/// local DGM capture above it uses, which is what keeps agent_eval_tests'+/// stub Agent (`.provider = undefined`, `.client = undefined`, and a target+/// that IS met) from being dragged into a live model call.+pub fn afterEval(self: *Agent, note: []const u8, score: f64, output: []const u8) void {+ const tj = trace.g_traj orelse return;+ if (g_reflected or self.sub) return;+ g_reflected = true;+ const prompt = reflectPrompt(self.arena, note, score, self.eval_target, output) orelse return;+ const reply = askModel(self, prompt) orelse return;+ var buf: [max_candidates][]const u8 = undefined;+ const candidates = parseCandidates(&buf, reply);+ if (self.tracer) |tr| {+ var detail: [64]u8 = undefined;+ tr.note("playbook", std.fmt.bufPrint(&detail, "reflector proposed {d} candidate(s)", .{candidates.len}) catch "");+ }+ if (candidates.len == 0) return;+ const provenance = std.fmt.allocPrint(self.arena, "run:{s}", .{tj.identity.run_id}) catch "run";+ var kept: usize = 0;+ for (candidates) |text| {+ // The Curator. Every rejection here — duplicate, over the learned+ // cap, unwritable ledger — is a deterministic decision, and the+ // model that proposed the bullet has no say in it.+ if (playbook.add(self.io, self.arena, text, .learned, provenance).ok) kept += 1;+ }+ if (kept == 0) return;+ playbook_glue.refreshRoot(self, self.arena);+ self.say(" 📗 playbook: kept {d} learned insight(s) from this run\n", .{kept}) catch {};+}diff --git a/src/playbook_tests.zig b/src/playbook_tests.zignew file mode 100644index 00000000..d71d86bf--- /dev/null+++ b/src/playbook_tests.zig@@ -0,0 +1,436 @@+//! Tests for the #381/#383 playbook substrate, its injection block, its+//! capture surfaces, and the #383 reflector's reply parsing. Reached through+//! the `test { _ = @import(...) }` hook at the bottom of playbook.zig.+//!+//! Everything that touches the ledger FILE goes through a real+//! createFile/read round trip in a scratch cwd rather than a hand-built+//! string: the whole claim of #381 is that a constraint survives a process+//! boundary, and a test that never serializes cannot show that.++const std = @import("std");+const Io = std.Io;++const playbook = @import("playbook.zig");+const reflect = @import("playbook_reflect.zig");+const glue = @import("playbook_glue.zig");+const prompts = @import("prompts.zig");+const Agent = @import("agent.zig").Agent;++/// Run `body` with the process cwd moved into a fresh scratch directory, so+/// the real `.graff/playbook.jsonl` path is exercised without touching the+/// repo checkout. Same fchdir approach agent_eval_tests.zig uses, and for the+/// same reason: the store takes no Dir parameter.+fn inScratch(comptime body: fn (Io, std.mem.Allocator) anyerror!void) !void {+ if (@import("builtin").os.tag == .windows) return;+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var orig = try Io.Dir.cwd().openDir(io, ".", .{});+ defer orig.close(io);+ defer _ = std.posix.system.fchdir(orig.handle);+ if (std.posix.system.fchdir(tmp.dir.handle) != 0) return error.ChdirFailed;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ try body(io, arena_state.allocator());+}++test "normalize: the dedupe key ignores case, punctuation and whitespace runs" {+ var a: [playbook.max_text]u8 = undefined;+ var b: [playbook.max_text]u8 = undefined;+ try std.testing.expectEqualStrings("no emojis in code comments", playbook.normalize(&a, " No EMOJIS, in code-comments!! "));+ try std.testing.expectEqualStrings(playbook.normalize(&a, "No dots."), playbook.normalize(&b, "no dots"));+ try std.testing.expectEqualStrings("", playbook.normalize(&a, " --- "));+ // Non-ASCII stays intact rather than shattering into per-byte tokens.+ try std.testing.expectEqualStrings("café ohne zucker", playbook.normalize(&a, "Café — ohne Zucker"));+}++test "idFor: content-derived, so identity and dedupe are the same operation" {+ var x: [11]u8 = undefined;+ var y: [11]u8 = undefined;+ try std.testing.expectEqualStrings(playbook.idFor(&x, "no scroll hints"), playbook.idFor(&y, " No, Scroll Hints! "));+ try std.testing.expect(!std.mem.eql(u8, playbook.idFor(&x, "no scroll hints"), playbook.idFor(&y, "no progress dots")));+ try std.testing.expect(std.mem.startsWith(u8, playbook.idFor(&x, "anything at all"), "pb-"));+ try std.testing.expectEqual(@as(usize, 11), playbook.idFor(&x, "anything at all").len);+}++test "store round trip: add/dedupe/retire through the real .graff/playbook.jsonl file format" {+ try inScratch(struct {+ fn body(io: Io, arena: std.mem.Allocator) !void {+ try std.testing.expectEqual(@as(usize, 0), playbook.load(io, arena).len);++ const first = playbook.add(io, arena, "never use emojis in code comments", .user, "user:1");+ try std.testing.expect(first.ok);+ const learned = playbook.add(io, arena, "- prefer codedb outline before read on files over 300 lines", .learned, "run:abc123");+ try std.testing.expect(learned.ok); // the leading bullet marker is stripped, not stored++ // Read back through the real serializer + parser, not a fixture.+ const items = playbook.load(io, arena);+ try std.testing.expectEqual(@as(usize, 2), items.len);+ try std.testing.expectEqualStrings("never use emojis in code comments", items[0].text);+ try std.testing.expectEqual(playbook.Source.user, items[0].source);+ try std.testing.expectEqualStrings("user:1", items[0].provenance);+ try std.testing.expect(items[0].created_at > 0);+ try std.testing.expectEqualStrings("prefer codedb outline before read on files over 300 lines", items[1].text);+ try std.testing.expectEqual(playbook.Source.learned, items[1].source);+ try std.testing.expectEqualStrings("run:abc123", items[1].provenance);++ // Dedupe is normalized-exact: a re-statement is refused, reported,+ // and does NOT append a second record.+ const dupe = playbook.add(io, arena, "Never use emojis in CODE comments.", .user, "user:2");+ try std.testing.expect(!dupe.ok);+ try std.testing.expectEqualStrings(first.id, dupe.id);+ try std.testing.expect(std.mem.indexOf(u8, dupe.reason, "already recorded") != null);+ try std.testing.expectEqual(@as(usize, 2), playbook.load(io, arena).len);++ // An empty/punctuation-only constraint is refused rather than+ // stored as an item that injects a bare "- ".+ try std.testing.expect(!playbook.add(io, arena, " *** ", .user, "user:3").ok);++ // Retire is a TOMBSTONE: the add record stays on disk, and the+ // file only ever grows.+ const before = (try Io.Dir.cwd().readFileAlloc(io, playbook.path, arena, .limited(1 << 20))).len;+ try std.testing.expect(playbook.retire(io, arena, first.id));+ const after = try Io.Dir.cwd().readFileAlloc(io, playbook.path, arena, .limited(1 << 20));+ try std.testing.expect(after.len > before);+ try std.testing.expect(std.mem.indexOf(u8, after, "never use emojis in code comments") != null); // history intact+ const live = playbook.load(io, arena);+ try std.testing.expectEqual(@as(usize, 1), live.len);+ try std.testing.expectEqual(playbook.Source.learned, live[0].source);++ // Retiring an unknown id writes nothing and says so.+ try std.testing.expect(!playbook.retire(io, arena, "pb-deadbeef"));++ // Re-adding a retired item works: the later op wins.+ try std.testing.expect(playbook.add(io, arena, "never use emojis in code comments", .user, "user:4").ok);+ try std.testing.expectEqual(@as(usize, 2), playbook.load(io, arena).len);+ }+ }.body);+}++test "parse: a torn tail or a junk line costs at most its own record" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const items = playbook.parse(arena,+ \\{"v":1,"op":"add","id":"pb-00000001","text":"first","source":"user"}+ \\not json at all+ \\{"v":1,"op":"add","id":"pb-00000002","text":"second","source":"learned"}+ \\+ \\{"v":1,"op":"add","id":"pb-000000+ );+ try std.testing.expectEqual(@as(usize, 2), items.len);+ try std.testing.expectEqualStrings("first", items[0].text);+ try std.testing.expectEqualStrings("second", items[1].text);+}++test "blockFrom: user before learned, both headed, and nothing at all when empty" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ try std.testing.expectEqualStrings("", playbook.blockFrom(arena, &.{}));++ const items = [_]playbook.Item{+ .{ .id = "pb-1", .text = "learned first in file order", .source = .learned },+ .{ .id = "pb-2", .text = "no navigation dots", .source = .user },+ .{ .id = "pb-3", .text = "no scroll hints", .source = .user },+ };+ const block = playbook.blockFrom(arena, &items);+ const user_at = std.mem.indexOf(u8, block, playbook.user_header).?;+ const learned_at = std.mem.indexOf(u8, block, playbook.learned_header).?;+ try std.testing.expect(user_at < learned_at); // user ALWAYS outranks learned+ // Newest-first within a section: the most recent "no" leads.+ try std.testing.expect(std.mem.indexOf(u8, block, "- no scroll hints").? < std.mem.indexOf(u8, block, "- no navigation dots").?);+ try std.testing.expect(std.mem.indexOf(u8, block, "- learned first in file order") != null);+ try std.testing.expect(std.mem.indexOf(u8, block, "omitted") == null); // nothing was cut++ // A learned-only ledger must not print an empty HARD CONSTRAINTS header.+ const learned_only = playbook.blockFrom(arena, items[0..1]);+ try std.testing.expect(std.mem.indexOf(u8, learned_only, playbook.user_header) == null);+ try std.testing.expect(std.mem.startsWith(u8, learned_only, playbook.learned_header));+}++test "blockFrom: the item cap truncates newest-first and SAYS it truncated" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const n = playbook.user_block_items + 5;+ const items = try arena.alloc(playbook.Item, n);+ for (items, 0..) |*item, i| item.* = .{+ .id = "pb-x",+ .text = std.fmt.allocPrint(arena, "constraint number {d}", .{i}) catch unreachable,+ .source = .user,+ };+ const block = playbook.blockFrom(arena, items);+ // Every bullet is preceded by a newline (the header's, or the previous+ // bullet's), so this counts them exactly.+ try std.testing.expectEqual(playbook.user_block_items, std.mem.count(u8, block, "\n- "));+ // Silent truncation would be a lie: a worker told "these are the+ // constraints" has to know when it was told only some of them.+ try std.testing.expect(std.mem.indexOf(u8, block, "5 older item(s) omitted") != null);+ try std.testing.expect(std.mem.indexOf(u8, block, playbook.path) != null);+ // The newest survived and the oldest was the one cut.+ try std.testing.expect(std.mem.indexOf(u8, block, "constraint number 34") != null);+ try std.testing.expect(std.mem.indexOf(u8, block, "constraint number 0\n") == null);+}++test "blockFrom: the byte cap bounds the block even with one absurd item each" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const long = try arena.alloc(u8, playbook.max_text);+ @memset(long, 'x');+ const items = try arena.alloc(playbook.Item, 40);+ for (items, 0..) |*item, i| item.* = .{ .id = "pb-x", .text = long, .source = if (i % 2 == 0) .user else .learned };+ const block = playbook.blockFrom(arena, items);+ try std.testing.expect(block.len < playbook.user_block_bytes + playbook.learned_block_bytes + 512);+}++test "rideBrief: identity on an empty ledger, block-prefixed once there is one" {+ try inScratch(struct {+ fn body(io: Io, arena: std.mem.Allocator) !void {+ try std.testing.expectEqualStrings("do the thing", playbook.rideBrief(io, arena, "do the thing"));+ try std.testing.expect(playbook.add(io, arena, "no navigation dots", .user, "user:1").ok);+ const brief = playbook.rideBrief(io, arena, "do the thing");+ try std.testing.expect(std.mem.startsWith(u8, brief, playbook.user_header));+ try std.testing.expect(std.mem.indexOf(u8, brief, "- no navigation dots") != null);+ try std.testing.expect(std.mem.endsWith(u8, brief, "do the thing"));+ }+ }.body);+}++test "composeRoot: gated off until armed, then appends the same block to the root's base" {+ try inScratch(struct {+ fn body(io: Io, arena: std.mem.Allocator) !void {+ try std.testing.expect(playbook.add(io, arena, "no scroll hints", .user, "user:1").ok);+ const composed = playbook.composeRoot(io, arena, "BASE");+ try std.testing.expect(std.mem.startsWith(u8, composed, "BASE"));+ try std.testing.expect(std.mem.indexOf(u8, composed, "- no scroll hints") != null);+ }+ }.body);+}++test "the learned cap refuses rather than evicting, and never touches user items" {+ try inScratch(struct {+ fn body(io: Io, arena: std.mem.Allocator) !void {+ for (0..playbook.max_learned) |i| {+ const text = try std.fmt.allocPrint(arena, "learned insight number {d}", .{i});+ try std.testing.expect(playbook.add(io, arena, text, .learned, "run:x").ok);+ }+ const over = playbook.add(io, arena, "one insight too many", .learned, "run:x");+ try std.testing.expect(!over.ok);+ try std.testing.expect(std.mem.indexOf(u8, over.reason, "cap") != null);+ // v1 refuses; it does NOT evict, because choosing a victim needs+ // per-item fitness and that attribution is follow-up scope.+ try std.testing.expectEqual(playbook.max_learned, playbook.countOf(playbook.load(io, arena), .learned));+ // A user constraint still lands: the learned ceiling is not a+ // ceiling on the user's own rules.+ try std.testing.expect(playbook.add(io, arena, "never ship on a Friday", .user, "user:1").ok);+ }+ }.body);+}++test "reflector (#383): parses at most 3 bullets out of a canned reply, no live call" {+ var out: [reflect.max_candidates][]const u8 = undefined;++ const typical =+ \\Here are the durable lessons from this run:+ \\- the zig sources are capped at 600 lines; split before adding a module+ \\* regenerate the SDKs after any tool-schema change or CI fails+ \\1. run zig fmt on touched files before committing+ \\- a fourth bullet that must not be taken+ \\+ \\Hope that helps!+ ;+ const got = reflect.parseCandidates(&out, typical);+ try std.testing.expectEqual(@as(usize, 3), got.len);+ try std.testing.expectEqualStrings("the zig sources are capped at 600 lines; split before adding a module", got[0]);+ try std.testing.expectEqualStrings("regenerate the SDKs after any tool-schema change or CI fails", got[1]);+ try std.testing.expectEqualStrings("run zig fmt on touched files before committing", got[2]);++ // Prose-only replies yield nothing: a preamble curated into the playbook+ // would be injected into every future brief forever, so a false positive+ // costs far more than a missed insight.+ try std.testing.expectEqual(@as(usize, 0), reflect.parseCandidates(&out, "I could not find anything durable worth recording.").len);+ try std.testing.expectEqual(@as(usize, 0), reflect.parseCandidates(&out, "none").len);+ try std.testing.expectEqual(@as(usize, 0), reflect.parseCandidates(&out, "- none").len);+ try std.testing.expectEqual(@as(usize, 0), reflect.parseCandidates(&out, "- ok").len); // too short to be an insight+ try std.testing.expectEqual(@as(usize, 0), reflect.parseCandidates(&out, "").len);++ // An oversized bullet is capped, not dropped.+ var big: [playbook.max_text * 2]u8 = undefined;+ @memset(&big, 'y');+ big[0] = '-';+ big[1] = ' ';+ const capped = reflect.parseCandidates(&out, &big);+ try std.testing.expectEqual(@as(usize, 1), capped.len);+ try std.testing.expectEqual(playbook.max_text, capped[0].len);+}++test "reflector curation is deterministic: the same candidates twice add nothing the second time" {+ try inScratch(struct {+ fn body(io: Io, arena: std.mem.Allocator) !void {+ var out: [reflect.max_candidates][]const u8 = undefined;+ const reply = "- regenerate the SDKs after any tool-schema change\n- zig sources are capped at 600 lines";+ for (0..2) |_| {+ for (reflect.parseCandidates(&out, reply)) |text| _ = playbook.add(io, arena, text, .learned, "run:abc");+ }+ const items = playbook.load(io, arena);+ try std.testing.expectEqual(@as(usize, 2), items.len);+ for (items) |item| {+ try std.testing.expectEqual(playbook.Source.learned, item.source);+ try std.testing.expectEqualStrings("run:abc", item.provenance); // provenance is the minting run+ }+ }+ }.body);+}++/// A root Agent with just enough wired up for the capture surfaces: real io+/// (they touch the ledger file), a captured writer, and undefined provider/+/// client, which neither surface goes near.+fn stubRoot(gpa: std.mem.Allocator, arena: std.mem.Allocator, out: *Io.Writer) Agent {+ return .{+ .gpa = gpa,+ .arena = arena,+ .io = std.testing.io,+ .client = undefined,+ .provider = undefined,+ .messages = undefined,+ .sub = false,+ .label = "test",+ .out = out,+ };+}++test "/never (#381): bare lists, text adds, rm retires — and a non-/never line falls through" {+ try inScratch(struct {+ fn body(io: Io, arena: std.mem.Allocator) !void {+ var aw: Io.Writer.Allocating = .init(arena);+ var root = stubRoot(std.testing.allocator, arena, &aw.writer);++ // Unrelated lines are NOT claimed, including the prefix trap.+ try std.testing.expect(!try glue.command(&root, arena, "/models", &aw.writer));+ try std.testing.expect(!try glue.command(&root, arena, "/neverending story", &aw.writer));++ try std.testing.expect(try glue.command(&root, arena, "/never", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "playbook empty") != null);++ aw.clearRetainingCapacity();+ try std.testing.expect(try glue.command(&root, arena, "/never no navigation dots or scroll hints", &aw.writer));+ const added = aw.writer.buffered();+ // Duped: the writer below is cleared and rewritten, and a slice+ // into its retained buffer would silently become another message.+ const id = try arena.dupe(u8, added[std.mem.indexOf(u8, added, "pb-").?..][0..11]);+ const items = playbook.load(io, arena);+ try std.testing.expectEqual(@as(usize, 1), items.len);+ try std.testing.expectEqualStrings("no navigation dots or scroll hints", items[0].text);+ try std.testing.expectEqual(playbook.Source.user, items[0].source);+ try std.testing.expect(std.mem.startsWith(u8, items[0].provenance, "user:"));++ // The alias is the same command, and it dedupes against the same ledger.+ aw.clearRetainingCapacity();+ try std.testing.expect(try glue.command(&root, arena, "/constraint No navigation dots, or scroll hints!", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "not recorded") != null);+ try std.testing.expectEqual(@as(usize, 1), playbook.load(io, arena).len);++ aw.clearRetainingCapacity();+ try std.testing.expect(try glue.command(&root, arena, "/never", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "no navigation dots") != null);+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "user") != null);++ aw.clearRetainingCapacity();+ try std.testing.expect(try glue.command(&root, arena, "/never rm pb-deadbeef", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "no live playbook item") != null);++ aw.clearRetainingCapacity();+ const rm = try std.fmt.allocPrint(arena, "/never rm {s}", .{id});+ try std.testing.expect(try glue.command(&root, arena, rm, &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "retired") != null);+ try std.testing.expectEqual(@as(usize, 0), playbook.load(io, arena).len);+ }+ }.body);+}++test "note_constraint (#381): appends user items only, is idempotent, and can never retire one" {+ try inScratch(struct {+ fn body(io: Io, arena: std.mem.Allocator) !void {+ var aw: Io.Writer.Allocating = .init(arena);+ var root = stubRoot(std.testing.allocator, arena, &aw.writer);+ const call = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"text\":\"never use emojis in code comments\"}", .{});++ const first = glue.noteConstraint(&root, call);+ try std.testing.expect(!first.is_error);+ try std.testing.expect(std.mem.indexOf(u8, first.text, "constraint recorded as pb-") != null);+ const items = playbook.load(io, arena);+ try std.testing.expectEqual(@as(usize, 1), items.len);+ try std.testing.expectEqual(playbook.Source.user, items[0].source); // NEVER .learned++ // A repeat is the desired end state, not a failure: reporting it as+ // an error would push the model into retrying a correct ledger.+ const again = glue.noteConstraint(&root, call);+ try std.testing.expect(!again.is_error);+ try std.testing.expectEqual(@as(usize, 1), playbook.load(io, arena).len);++ // Empty/blank text is refused rather than stored.+ const blank = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"text\":\" \"}", .{});+ try std.testing.expect(glue.noteConstraint(&root, blank).is_error);+ const missing = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{}", .{});+ try std.testing.expect(glue.noteConstraint(&root, missing).is_error);++ // The append-only contract, structurally: whatever the model puts+ // in `text`, the ledger only ever grows and the item stays live.+ // There is no argument shape that reaches retire from here.+ for ([_][]const u8{ "{\"text\":\"retire pb-00000001\"}", "{\"text\":\"rm all\"}", "{\"op\":\"retire\",\"id\":\"pb-00000001\",\"text\":\"x\"}" }) |raw| {+ const before = playbook.load(io, arena).len;+ _ = glue.noteConstraint(&root, try std.json.parseFromSliceLeaky(std.json.Value, arena, raw, .{}));+ try std.testing.expect(playbook.load(io, arena).len >= before);+ }+ try std.testing.expect(playbook.find(playbook.load(io, arena), items[0].id) != null); // the original survived every one+ }+ }.body);+}++test "refreshRoot (#381): a constraint recorded mid-session reaches the ROOT's own prompt, all four variants" {+ try inScratch(struct {+ fn body(io: Io, arena: std.mem.Allocator) !void {+ _ = io; // the ledger is reached through the agent's own io here+ const saved = playbook.g_root_inject;+ defer playbook.g_root_inject = saved;+ var aw: Io.Writer.Allocating = .init(arena);+ var root = stubRoot(std.testing.allocator, arena, &aw.writer);++ try prompts.setRootSystemPrompts(&root, "ROOT-BASE", arena);+ try std.testing.expectEqualStrings("ROOT-BASE", root.sys_base);+ try std.testing.expectEqualStrings("ROOT-BASE", root.sys_normal); // empty ledger costs nothing++ _ = glue.noteConstraint(&root, try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"text\":\"no scroll hints\"}", .{}));+ // noteConstraint refreshed it: no restart, no re-login, next request.+ for ([_][]const u8{ root.sys_normal, root.sys_strict, root.sys_ultra, root.sys_ultra_strict }) |v| {+ try std.testing.expect(std.mem.indexOf(u8, v, "ROOT-BASE") != null);+ try std.testing.expect(std.mem.indexOf(u8, v, "- no scroll hints") != null);+ }+ // The BASE is remembered unpolluted, so the next refresh composes+ // from it rather than stacking a second block onto the first.+ try std.testing.expectEqualStrings("ROOT-BASE", root.sys_base);+ _ = glue.noteConstraint(&root, try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"text\":\"no progress dots\"}", .{}));+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, root.sys_normal, playbook.user_header));+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, root.sys_normal, "ROOT-BASE"));+ try std.testing.expect(std.mem.indexOf(u8, root.sys_normal, "- no progress dots") != null);++ // And a persona swap through the ordinary funnel keeps the block.+ try prompts.setSystemPrompts(&root, "PERSONA-BASE", arena);+ try std.testing.expect(std.mem.indexOf(u8, root.sys_normal, "PERSONA-BASE") != null);+ try std.testing.expect(std.mem.indexOf(u8, root.sys_normal, "- no progress dots") != null);+ }+ }.body);+}++test "idList: the kind:\"playbook\" row's id column is the join key for later attribution" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ try std.testing.expectEqualStrings("", playbook.idList(arena, &.{}));+ try std.testing.expectEqualStrings("pb-1,pb-2", playbook.idList(arena, &.{+ .{ .id = "pb-1", .text = "a", .source = .user },+ .{ .id = "pb-2", .text = "b", .source = .learned },+ }));+}diff --git a/src/prompts.zig b/src/prompts.zigindex 2d451859..b8813256 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -14,6 +14,7 @@ const std = @import("std");const Allocator = std.mem.Allocator;const shapes = @import("shapes.zig");const Agent = @import("agent.zig").Agent;+const playbook = @import("playbook.zig"); // #381: the user-constraint block composed onto the ROOT's base promptpub const main_system_prompt =\\You are a coding agent running in a minimal terminal harness on the@@ -97,6 +98,8 @@ pub const main_system_prompt =\\fix. Match the surrounding file's style and keep diffs minimal: no drive-by\\refactors, renames, or reformatting the task did not require.\\+ \\The moment the user rejects, forbids, or vetoes something ("no dots", "not vanilla JS", "stop adding scroll hints"), call note_constraint with one short imperative line recording it, then carry on — recorded constraints are injected into every later subagent, workflow and pipeline brief and survive compaction, so a rejection you leave unrecorded is one your fresh workers will repeat.+ \\\\Write the final message as an update to a teammate who has not seen your\\screen. Cite evidence as `path:line` instead of pasting file bodies — never\\dump large file contents into an answer — and backtick-wrap commands, paths,@@ -175,13 +178,32 @@ pub fn ultracodeActive(agent: *const Agent) bool {/// sys_normal directly and never recomputed them). `ultra` COMPOSES onto/// whichever base is active rather than replacing it, so /strict and/// /ultracode stay independent toggles.+///+/// #381: the base is also remembered verbatim on `sys_base`, and the live+/// user-constraint block is composed onto it here — inside the one funnel —+/// so a persona swap or a `set_system_prompt` can never drop the user's+/// standing "no"s on the floor. Gated on `playbook.g_root_inject` (armed only+/// by setRootSystemPrompts below) so this stays a pure string funnel for the+/// tests and for every non-root agent.pub fn setSystemPrompts(agent: *Agent, base: []const u8, arena: Allocator) !void {- agent.sys_normal = base;- agent.sys_strict = try std.fmt.allocPrint(arena, "{s}{s}", .{ base, strict_note });- agent.sys_ultra = try std.fmt.allocPrint(arena, "{s}{s}", .{ base, ultracode_system_note });+ agent.sys_base = base;+ const composed = if (playbook.g_root_inject) playbook.composeRoot(agent.io, arena, base) else base;+ agent.sys_normal = composed;+ agent.sys_strict = try std.fmt.allocPrint(arena, "{s}{s}", .{ composed, strict_note });+ agent.sys_ultra = try std.fmt.allocPrint(arena, "{s}{s}", .{ composed, ultracode_system_note });agent.sys_ultra_strict = try std.fmt.allocPrint(arena, "{s}{s}", .{ agent.sys_strict, ultracode_system_note });}+/// The ROOT's entry to the same funnel, called once by session_run when the+/// root agent is built. Arming here rather than at a global switch keeps the+/// filesystem read strictly on the one code path that has a real session+/// behind it — subagents get their briefs' block from playbook.rideBrief, and+/// a bare `Agent` in a unit test gets neither.+pub fn setRootSystemPrompts(agent: *Agent, base: []const u8, arena: Allocator) !void {+ playbook.g_root_inject = true;+ return setSystemPrompts(agent, base, arena);+}+pub const sub_system_prompt =\\You are a subagent spawned by an orchestrator agent inside a terminal\\harness. Complete the assigned task using your tools, without askingdiff --git a/src/schema.zig b/src/schema.zigindex b9e0716f..ef96e9fd 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -132,6 +132,11 @@ const meta_specs = [_]ToolSpec{\\{"type": "object", "properties": {"note": {"type": "string", "description": "What you changed since the last eval"}}},},+ // #381: the durable-rejection capture surface. Root-only, and APPEND-ONLY+ // by construction — there is no retire/edit/list operation here at all,+ // so a model that finds a constraint inconvenient has no mechanism to+ // widen it; only the user can, with /never rm <id>.+ .{ .name = "note_constraint", .desc = "Record a standing user constraint in this project's playbook (.graff/playbook.jsonl). Call it the moment the user rejects, forbids or vetoes something, passing ONE short imperative line stating what must not happen (e.g. never add scroll hints or progress dots). The recorded line is injected verbatim into every later subagent, workflow and pipeline brief and into your own system context, in this session and in future ones, so it survives compaction and reaches fresh agents that never saw the rejection. Append-only: this tool cannot edit, retire or list items - only the user can, with /never. Recording the same constraint twice is harmless and does nothing.", .schema = "{\"type\": \"object\", \"properties\": {\"text\": {\"type\": \"string\", \"description\": \"One short imperative line in the user's own terms, stating what must not happen\"}}, \"required\": [\"text\"]}" },.{.name = "ask_user",.desc = "Ask the human a question and wait for their typed reply, which is returned as this tool's result. Use when you need a decision, clarification, or missing information. This routes the human turn through the tool channel — the user is just another tool you can call.",@@ -192,49 +197,31 @@ pub const root_specs = base_specs ++ meta_specs ++ [_]ToolSpec{ subagent_spec, w// The common catalog (clock_sleep off) is static too. Previously every root// startup allocated and filled a filtered ToolSpec array before rendering even// one provider catalog.-const root_specs_without_clock = blk: {- var out: [root_specs.len - 1]ToolSpec = undefined;+/// The root catalog minus the named optional entries, built once at compile+/// time. The length check is the guard: each name must match EXACTLY one+/// spec, so a rename or a duplicated entry is a compile error rather than a+/// silently-wrong catalog.+fn rootSpecsWithout(comptime drop: []const []const u8) [root_specs.len - drop.len]ToolSpec {+ var out: [root_specs.len - drop.len]ToolSpec = undefined;var len: usize = 0;- for (root_specs) |tool| {- if (std.mem.eql(u8, tool.name, "clock_sleep")) continue;+ entry: for (root_specs) |tool| {+ for (drop) |name| if (std.mem.eql(u8, tool.name, name)) continue :entry;out[len] = tool;len += 1;}- if (len != out.len) @compileError("root tool catalog must contain exactly one clock_sleep entry");- break :blk out;-};+ if (len != out.len) @compileError("root tool catalog optional entries changed");+ return out;+}-const root_specs_without_learning = blk: {- var out: [root_specs.len - 1]ToolSpec = undefined;- var len: usize = 0;- for (root_specs) |tool| {- if (std.mem.eql(u8, tool.name, "learn_candidate")) continue;- out[len] = tool;- len += 1;- }- if (len != out.len) @compileError("root tool catalog must contain exactly one learn_candidate entry");- break :blk out;-};+const root_specs_without_clock = rootSpecsWithout(&.{"clock_sleep"});+const root_specs_without_learning = rootSpecsWithout(&.{"learn_candidate"});+const root_specs_without_optional = rootSpecsWithout(&.{ "clock_sleep", "learn_candidate" });-const root_specs_without_optional = blk: {- var out: [root_specs.len - 2]ToolSpec = undefined;- var len: usize = 0;- for (root_specs) |tool| {- if (std.mem.eql(u8, tool.name, "clock_sleep") or std.mem.eql(u8, tool.name, "learn_candidate")) continue;- out[len] = tool;- len += 1;- }- if (len != out.len) @compileError("root tool catalog optional entries changed");- break :blk out;-};+pub const meta_names = [_][]const u8{ "todo_write", "todo_read", "ask_user", "eval", "attempt_completion", "clock_sleep", "note_constraint" };pub fn isMetaName(name: []const u8) bool {- return std.mem.eql(u8, name, "todo_write") or- std.mem.eql(u8, name, "todo_read") or- std.mem.eql(u8, name, "ask_user") or- std.mem.eql(u8, name, "eval") or- std.mem.eql(u8, name, "attempt_completion") or- std.mem.eql(u8, name, "clock_sleep");+ for (meta_names) |m| if (std.mem.eql(u8, name, m)) return true;+ return false;}// #352: optional built-ins — advertised only while tool_gates says they are@@ -513,16 +500,8 @@ test "providerDisplayName & providerLoginKind: id mapping with sane fallbacks" {try std.testing.expectEqualStrings("kimi_device", providerLoginKind("kimi"));try std.testing.expectEqualStrings("api_key", providerLoginKind("openai"));}-test "isMetaName: the five orchestrator-handled meta tools" {- try std.testing.expect(isMetaName("todo_write"));- try std.testing.expect(isMetaName("todo_read"));- try std.testing.expect(isMetaName("ask_user"));- try std.testing.expect(isMetaName("attempt_completion"));- try std.testing.expect(isMetaName("clock_sleep"));- try std.testing.expect(!isMetaName("bash"));- try std.testing.expect(!isMetaName("subagent"));- try std.testing.expect(!isMetaName("codedb"));-}+// isMetaName's own coverage, and #381's note_constraint catalog contract,+// live in tool_schema_tests.zig — this file is at the 600-line ceiling.test "effectiveRootSpecs: drops clock_sleep from the root tool catalog unless the flag is on (#225)" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);diff --git a/src/session_run.zig b/src/session_run.zigindex 983a025e..161ea4ff 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -260,7 +260,7 @@ pub fn buildRootAgent(.tools_openai = "",.tools_responses = "",};- try prompts.setSystemPrompts(&root, sys_normal, arena);+ try prompts.setRootSystemPrompts(&root, sys_normal, arena); // #381: same funnel + the live .graff/playbook.jsonl constraint block// Startup pays for one provider format, not all three. Other formats are// rendered on first switch with the same built-in + live MCP inputs.try root.ensureRootTools(default_provider.kind);diff --git a/src/subagent_run.zig b/src/subagent_run.zigindex 3d3644e7..44427788 100644--- a/src/subagent_run.zig+++ b/src/subagent_run.zig@@ -11,6 +11,7 @@ pub const Provider = @import("provider.zig").Provider;const route_policy = @import("route_policy.zig"); // #376 rung stratificationconst util = @import("util.zig");const goal_pacing = @import("goal_pacing.zig");+const playbook = @import("playbook.zig"); // #381/#383: the constraint + learned block every brief carriesconst tools = @import("tools.zig");const ToolCtx = tools.ToolCtx;const ToolOutput = tools.ToolOutput;@@ -290,7 +291,15 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const// A /loop deadline on the parent reaches the child as guidance on its own// task prompt (goal_pacing.childTaskPrompt): same absolute deadline, minus// the margin the parent needs to integrate the result. No-op without one.- const task_prompt = try goal_pacing.childTaskPrompt(arena, prompt, ctx.loop_deadline_ms, util.unixMs(ctx.io));+ //+ // #381/#383: playbook.rideBrief then prepends the live constraint ++ // learned block. THIS is the one injection point for every spawn path+ // there is — the `subagent` tool (sync and background), workflow phase+ // tasks, workflow retries, pipeline stages and the judge all funnel+ // through runSub — and it reads .graff/playbook.jsonl at assembly time,+ // never a copy held in the parent's conversation, which is exactly why a+ // compacted (or brand-new) session still carries the user's "no"s.+ const task_prompt = playbook.rideBrief(ctx.io, arena, try goal_pacing.childTaskPrompt(arena, prompt, ctx.loop_deadline_ms, util.unixMs(ctx.io)));try agent.messages.append(try textMessage(arena, "user", task_prompt));defer agent.tools_used.deinit(gpa);const report = agent.runTurn();@@ -346,7 +355,11 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const};const empty = text.len == 0;const report_body = if (empty) "subagent finished without a report" else text;- const detail = cards.writeSubagentDetail(ctx.io, arena, sub_id, label, kind, prompt, report_body, !empty, run_ms, used_tools);+ // task_prompt, not the raw `prompt`: the detail file is the record of what+ // this worker was ACTUALLY sent, so it has to show the deadline note and+ // the #381 constraint block too. Reading a report against the raw prompt+ // is how "the subagent ignored my instruction" becomes unfalsifiable.+ const detail = cards.writeSubagentDetail(ctx.io, arena, sub_id, label, kind, task_prompt, report_body, !empty, run_ms, used_tools);cards.subagentDoneCard(arena, sub_id, sprite, label, !empty, run_ms, used_tools, detail);var extra: []const u8 = isolation_note;diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 75e491f0..4ed49370 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -79,6 +79,13 @@ const acp = @import("acp.zig");// unchanged and still reachable — this is the file that exists for that.const agent_eval_control_tests = @import("agent_eval_control_tests.zig");+// #381/#383: the itemized playbook. playbook.zig is reached in production+// (prompts.zig, subagent_run.zig) and pulls its own tests in, but the glue and+// reflector modules are only ever reached through a call, so their tests need+// the hook.+const playbook_glue = @import("playbook_glue.zig");+const playbook_reflect = @import("playbook_reflect.zig");+// #345: the global-vs-project MCP config merge. mcp.zig does reference its// decls, but the hook makes the coverage explicit rather than contingent on// that staying true.@@ -117,4 +124,6 @@ test {_ = mcp_config;_ = acp;_ = agent_eval_control_tests;+ _ = playbook_glue;+ _ = playbook_reflect;}diff --git a/src/tool_schema_tests.zig b/src/tool_schema_tests.zigindex c1e02883..8decadc1 100644--- a/src/tool_schema_tests.zig+++ b/src/tool_schema_tests.zig@@ -192,3 +192,43 @@ test "the discovery path itself flattens, so nothing reaches a provider unlowere}.check);}}++// The two below live here rather than in schema.zig, which is at the+// 600-line ceiling.++test "isMetaName: every orchestrator-handled meta tool, and nothing else" {+ for (schema.meta_names) |name| try std.testing.expect(schema.isMetaName(name));+ try std.testing.expect(schema.isMetaName("note_constraint")); // #381: inline — it mutates the root's own system prompt+ try std.testing.expect(!schema.isMetaName("bash"));+ try std.testing.expect(!schema.isMetaName("subagent"));+ try std.testing.expect(!schema.isMetaName("codedb"));+ // Every meta name must be a real root spec: a meta tool nothing advertises+ // is dead dispatch, and a meta name with no spec is unreachable.+ for (schema.meta_names) |name| {+ var found = false;+ for (schema.root_specs) |t| if (std.mem.eql(u8, t.name, name)) {+ found = true;+ };+ try std.testing.expect(found);+ }+}++test "note_constraint (#381): root-only, append-only, and a valid one-property schema" {+ var found = false;+ for (schema.root_specs) |t| if (std.mem.eql(u8, t.name, "note_constraint")) {+ found = true;+ var parsed = try std.json.parseFromSlice(Value, std.testing.allocator, t.schema, .{});+ defer parsed.deinit();+ try std.testing.expectEqualStrings("text", parsed.value.object.get("required").?.array.items[0].string);+ try std.testing.expectEqual(@as(usize, 1), parsed.value.object.get("properties").?.object.count());+ // The append-only contract is ADVERTISED, not merely implemented: a+ // model that believed it could retire an item would keep trying.+ try std.testing.expect(std.mem.indexOf(u8, t.desc, "Append-only") != null);+ try std.testing.expect(std.mem.indexOf(u8, t.desc, "survives compaction") != null);+ };+ try std.testing.expect(found);+ // A subagent must never be handed it: a child never saw the rejection, so+ // anything it recorded would be second-hand at best.+ try std.testing.expect(std.mem.indexOf(u8, schema.tools_openai_sub, "note_constraint") == null);+ try std.testing.expect(std.mem.indexOf(u8, schema.tools_anthropic_sub, "note_constraint") == null);+}