Skip to content

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

Python

Preserve tool state and reject incomplete verification

Rach Pradhan0b9634e90cb6
diff --git a/docs/adr/0173-loaded-tool-order-survives-resume.md b/docs/adr/0173-loaded-tool-order-survives-resume.md
new file mode 100644
index 00000000..cce79d92
--- /dev/null
+++ b/docs/adr/0173-loaded-tool-order-survives-resume.md
@@ -0,0 +1,22 @@
+# 0173. Loaded tool order survives resume
+
+Status: accepted 2026-09-23
+
+## Context
+
+A native tool loaded after an external tool was inserted before the existing
+external schema. This changed the reusable catalog prefix. Saving the two kinds
+separately also lost their interleaved order when restoring a session.
+
+## Decision
+
+Both kinds use one admission sequence. Render the loaded tail in that order and
+persist an ordered list of names alongside the legacy selection fields. Restore
+names against the current catalog; do not persist schemas or permissions. Older
+snapshots retain their original native-first restoration behavior.
+
+## Consequences
+
+Appending a loaded tool preserves the bytes of prior catalog entries. Real
+save/load and emitted-request tests guard this property. Actual cache hits remain
+provider-dependent; stable catalog bytes alone do not establish a billing gain.
diff --git a/docs/adr/0174-completion-requires-terminal-tool-results.md b/docs/adr/0174-completion-requires-terminal-tool-results.md
new file mode 100644
index 00000000..25802c93
--- /dev/null
+++ b/docs/adr/0174-completion-requires-terminal-tool-results.md
@@ -0,0 +1,24 @@
+# 0174. Completion requires terminal tool results
+
+Status: accepted 2026-09-23
+
+## Context
+
+A shell call can return successfully while its process is still running. Such a
+receipt is not evidence that verification passed. Reading a background job also
+needs to preserve its terminal exit status instead of returning unconditional
+success.
+
+## Decision
+
+Tool results carry an explicit pending bit separately from errors and cancellation.
+Deferred completion rejects pending, failed, or cancelled companion results.
+Background output reports a failure for a nonzero or abnormal terminal exit.
+Normal background launch remains a successful launch with pending work.
+
+## Consequences
+
+Verification and completion may share a response only after the executed check
+produces a successful terminal result. Tests cover pending launches and resumed
+successes and failures. The prompt does not ask for redundant verification merely
+to combine it with completion.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 3ab1b5c5..863a9c3b 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -195,6 +195,10 @@ record only when you need the evidence or the edge cases.
| [0171](0171-cost-rates-belong-to-the-provider-route.md) | Cost estimates use the actual provider route, preserve cache and long-context rates, and leave unknown tariffs unpriced. |
| [0172](0172-model-guidance-is-request-scoped.md) | Model guidance is composed once per request from the current model, with root-only delegation and stable repeated prefixes. |
+| [0173](0173-loaded-tool-order-survives-resume.md) | Native and external schemas share admission order, which survives session save and restore. |
+
+| [0174](0174-completion-requires-terminal-tool-results.md) | Deferred completion rejects pending work and preserves background verification exit status. |
+
## When to write one
Write an ADR when a decision is load-bearing and non-obvious: it was reached
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 7a51ecc1..09158e08 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -119,3 +119,8 @@
{"args": ["--old"], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Run the isolated publication fixture and report its result.", "id": "publication-pending-ci-failure", "why": "#1179: pending exact-head branch CI is reread before deciding whether publication is ready.", "github_fixture": {"checks": "SUCCESS", "runs": "pending", "run_sequence": ["pending", "failure"], "review_files": ["notes.md"]}, "script": [{"tool": "shell", "arguments": {"command": "gh pr create --title fixture --body-file notes.md"}}, {"text": "Publication remains blocked by failed CI."}], "assert": [{"request_contains": {"text": "exact head SHA has an unexplained failed branch run"}}], "verify_command": ["python3", "-c", "from pathlib import Path; assert not Path('mutations.jsonl').exists()"]}
{"id": "btw-advertised-tools-never-execute", "why": "ADR0011: cached tools remain advertised to /btw, but an unsolicited tool call must never dispatch or pollute the parent history.", "workspace_seed": {"sentinel.txt": "unchanged"}, "prompt": "Describe the current task briefly.", "controls_after_turn": [{"type": "btw", "text": "SIDE-QUESTION-SENTINEL"}], "second_prompt": "Continue the original discussion.", "script": [{"text": "Initial discussion."}, {"tool": "write_file", "arguments": {"path": "sentinel.txt", "content": "SIDE-EFFECT-SENTINEL"}}, {"text": "Original discussion continues."}], "assert": [{"event": {"type": "error", "message": "side question failed; the conversation is unchanged"}}, {"no_event": {"type": "tool_call"}}, {"file_equals": {"path": "sentinel.txt", "content": "unchanged"}}, {"request_contains": {"index": 1, "text": "\"tools\""}}, {"request_lacks": {"index": -1, "text": "SIDE-QUESTION-SENTINEL"}}, {"request_lacks": {"index": -1, "text": "SIDE-EFFECT-SENTINEL"}}, {"final_text_contains": "Original discussion continues."}]}
{"id": "completion-result-keeps-evidence-and-limits", "why": "A result-only completion must deliver the full verified answer and remaining limitations without requiring duplicate assistant prose; this checks delivery, not model compliance with the wording.", "prompt": "Run the fixture verification command, then report the exact evidence and the remaining integration-test limitation.", "script": [{"tool": "shell", "arguments": {"command": "printf 'fixture verification: OK\\n'"}}, {"tool": "attempt_completion", "arguments": {"result": "Verified: fixture verification: OK.\nRemaining: integration tests were not run."}}], "assert": [{"event": {"type": "tool_result", "name": "shell", "is_error": false}}, {"final_text_contains": "Verified: fixture verification: OK."}, {"final_text_contains": "Remaining: integration tests were not run."}, {"events_at_most": {"match": {"type": "model_call_started"}, "count": 2}}]}
+{"args": ["--old"], "prompt": "Run the scripted verification fixture and report only observed results.", "id": "completion-pending-automatic", "why": "An unfinished shell receipt cannot satisfy same-batch completion; pending is not command failure.", "script": [{"tools": [{"tool": "shell", "arguments": {"command": "sleep 1; exit 0", "timeout": 1}}, {"tool": "attempt_completion", "arguments": {"result": "PREMATURE_COMPLETION"}}]}, {"text": "Verification is still pending."}], "assert": [{"event": {"type": "tool_call_finished", "name": "shell", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": true}}, {"no_event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"final_text_contains": "Verification is still pending."}]}
+{"args": ["--old"], "prompt": "Run the scripted verification fixture and report only observed results.", "id": "completion-pending-explicit", "why": "An unfinished shell receipt cannot satisfy same-batch completion; pending is not command failure.", "script": [{"tools": [{"tool": "shell", "arguments": {"command": "sleep 0.2; exit 0", "run_in_background": true}}, {"tool": "attempt_completion", "arguments": {"result": "PREMATURE_COMPLETION"}}]}, {"text": "Verification is still pending."}], "assert": [{"event": {"type": "tool_call_finished", "name": "shell", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": true}}, {"no_event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"final_text_contains": "Verification is still pending."}]}
+{"args": ["--old"], "prompt": "Run the scripted verification fixture and report only observed results.", "id": "completion-resumed-failure", "why": "A resumed verification result admits completion only after a successful terminal exit.", "script": [{"tool": "shell", "arguments": {"command": "printf 'RESUMED_EXIT_SEVEN\\n'; exit 7", "run_in_background": true}}, {"tool": "shell", "arguments": {"command": "sleep 0.3"}}, {"tools": [{"tool": "shell", "arguments": {"action": "output", "id": 1, "wait_ms": 1000}}, {"tool": "attempt_completion", "arguments": {"result": "FAILED_COMPLETION"}}]}, {"text": "Verification failed; completion withheld."}], "assert": [{"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": true}}, {"no_event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"event": {"type": "tool_result", "name": "shell", "is_error": true, "text": "[job 1: exited with code 7]\nRESUMED_EXIT_SEVEN\n", "id": "call_3_0"}}, {"request_contains": {"text": "exited with code 7"}}]}
+{"args": ["--old"], "prompt": "Run the scripted verification fixture and report only observed results.", "id": "completion-resumed-success", "why": "A resumed verification result admits completion only after a successful terminal exit.", "script": [{"tool": "shell", "arguments": {"command": "printf 'RESUMED_EXIT_ZERO\\n'; exit 0", "run_in_background": true}}, {"tool": "shell", "arguments": {"command": "sleep 0.3"}}, {"tools": [{"tool": "shell", "arguments": {"action": "output", "id": 1, "wait_ms": 1000}}, {"tool": "attempt_completion", "arguments": {"result": "VERIFIED_COMPLETION"}}]}, {"text": "Verification failed; completion withheld."}], "assert": [{"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"final_text_contains": "VERIFIED_COMPLETION"}, {"event": {"type": "tool_result", "name": "shell", "is_error": false, "text": "[job 1: exited with code 0]\nRESUMED_EXIT_ZERO\n", "id": "call_3_0"}}]}
+{"id": "malformed-edit-batch-recovers", "why": "A string-valued edits field used to panic on unchecked union access; return a tool error without writing so the next model turn can retry a valid array and finish.", "args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Create version.txt with alpha and beta, then update both lines using a batched edit. Correct any malformed arguments and verify the final file.", "script": [{"tool": "write_file", "arguments": {"path": "version.txt", "content": "alpha\nbeta\n"}}, {"tool": "edit_file", "arguments": {"path": "version.txt", "edits": "[{\"old_string\":\"alpha\",\"new_string\":\"ALPHA\"}]"}}, {"tool": "edit_file", "arguments": {"path": "version.txt", "edits": [{"old_string": "alpha", "new_string": "ALPHA"}, {"old_string": "beta", "new_string": "BETA"}]}}, {"tool": "bash", "arguments": {"command": "test \"$(cat version.txt)\" = \"$(printf 'ALPHA\\nBETA')\" && echo EDIT_BATCH_RECOVERED"}}, {"text": "The corrected batch landed and was verified."}], "assert": [{"event": {"type": "tool_call_finished", "name": "edit_file", "is_error": true}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 1}}, {"event": {"type": "tool_call_finished", "name": "edit_file", "is_error": false}}, {"request_contains": {"index": 2, "text": "edits must be an array"}}, {"event": {"type": "tool_result", "name": "bash", "text": "EDIT_BATCH_RECOVERED\n"}}, {"file_equals": {"path": "version.txt", "content": "ALPHA\nBETA\n"}}, {"final_text_contains": "The corrected batch landed and was verified."}]}
diff --git a/graff-evals/README.md b/graff-evals/README.md
index 52a184df..8710d195 100644
--- a/graff-evals/README.md
+++ b/graff-evals/README.md
@@ -184,3 +184,15 @@ and saved-selection path applies. Subscription calls are labelled separately;
the metered subtotal is retained, while total USD stays unknown rather than
presenting a flat subscription as free inference. API list-price estimates
require a separately validated model/rate snapshot.
+
+### Validated fixture versions
+
+`validated` (v1) remains frozen for existing result comparisons. Its visible and
+held-out checks do not cover every SPEC requirement, including the `Validated`
+export and empty-error `Invalid` combinations; a v1 pass is limited to that grader.
+
+`validated-contract-v2` is a separate task and fixture with explicit alias
+classmethod semantics, collection wrapping examples, and empty-Invalid
+short-circuit checks. Its held-out checker independently verifies these and
+remaining named contract behaviors. Compare both harness arms on the same task
+version; do not pool v1 and v2 passes or rewrite earlier raw results.
diff --git a/graff-evals/fixtures/validated-contract-v2/SPEC.md b/graff-evals/fixtures/validated-contract-v2/SPEC.md
new file mode 100644
index 00000000..1c88154a
--- /dev/null
+++ b/graff-evals/fixtures/validated-contract-v2/SPEC.md
@@ -0,0 +1,27 @@
+# Validated error accumulation (DeepSWE `returns-validated-error-accumulation`, distilled)
+
+`validated.py` must expose `Valid`, `Invalid`, `Validated` (alias of the
+union behavior via classmethods on either). `Validated.from_validated(v)`
+returns the same Valid or Invalid instance; `Validated.from_failure(err)`
+returns `Invalid((err,))`. The concrete representation of the alias is unrestricted.
+
+- `Valid(x)` and `Invalid(errors)` where `Invalid` stores errors as an
+ immutable tuple. `Invalid.from_failure(err)` wraps a single error in a
+ 1-tuple.
+- `bind(fn)` short-circuits: `Invalid` stays `Invalid` (fn not called);
+ `Valid` calls `fn` and returns its Validated.
+- `apply(other)` is applicative. Two `Invalid`s concatenate **self then
+ other**, left to right. `Valid` + `Invalid` → that `Invalid`.
+ `Valid(f).apply(Valid(x))` → `Valid(f(x))`.
+- `swap()`: `Valid(x)` → `Invalid((x,))`; `Invalid(errs)` → `Valid(errs)`.
+- `from_validated(v)` returns the same instance.
+- `alt(fn)` on `Invalid` maps `fn` over each error; on `Valid` is identity.
+- `__match_args__` is `("value",)` for Valid and `("errors",)` for Invalid.
+- `combine(a, b, fn)` applicative-combines two containers with `fn(a,b)`.
+- `combine_n(items, fn)` applies `fn` to N inner values, accumulating
+ every error if any item is Invalid.
+
+An `Invalid(())` still represents failure: `combine` and `combine_n` must
+return Invalid without calling `fn`, even when the accumulated tuple is empty.
+`from_failure` and `Valid.swap` wrap collection-valued errors/values as a single
+item rather than flattening them.
diff --git a/graff-evals/fixtures/validated-contract-v2/test_validated.py b/graff-evals/fixtures/validated-contract-v2/test_validated.py
new file mode 100644
index 00000000..dff59834
--- /dev/null
+++ b/graff-evals/fixtures/validated-contract-v2/test_validated.py
@@ -0,0 +1,66 @@
+from validated import Invalid, Valid, combine, combine_n
+
+
+def test_from_failure_tuple():
+ i = Invalid.from_failure("e")
+ assert i.errors == ("e",), i.errors
+
+
+def test_apply_concat():
+ a = Invalid.from_failure("a")
+ b = Invalid.from_failure("b")
+ got = a.apply(b)
+ assert got.errors == ("a", "b"), got.errors
+
+
+def test_swap_wraps():
+ assert Valid(3).swap() == Invalid((3,))
+ assert Invalid(("e",)).swap() == Valid(("e",))
+
+
+def test_bind_short_circuit():
+ called = []
+ Invalid.from_failure("e").bind(lambda x: called.append(x) or Valid(x))
+ assert called == []
+ assert Valid(2).bind(lambda x: Valid(x + 1)) == Valid(3)
+
+
+def test_combine_n():
+ got = combine_n((Valid(1), Invalid.from_failure("x"), Invalid.from_failure("y")), lambda a, b, c: a)
+ assert got.errors == ("x", "y"), got.errors
+ assert combine(Valid(2), Valid(3), lambda x, y: x + y) == Valid(5)
+
+
+def test_alias_contract():
+ from validated import Validated
+ for value in (Valid(8), Invalid(("alias",))):
+ assert Validated.from_validated(value) is value
+ assert Validated.from_failure("failure").errors == ("failure",)
+
+
+def test_collection_is_one_failure():
+ error = ["single", "compound", "error"]
+ assert Invalid.from_failure(error).errors == (error,)
+ assert Valid(error).swap().errors == (error,)
+
+
+def test_empty_invalid_never_calls_combiner():
+ def forbidden(*args):
+ raise AssertionError("combiner called despite Invalid input")
+ for items in ((Invalid(()),), (Valid(7), Invalid(()))):
+ result = combine_n(items, forbidden)
+ assert isinstance(result, Invalid)
+ assert result.errors == ()
+ assert isinstance(combine(Invalid(()), Valid(7), forbidden), Invalid)
+
+
+if __name__ == "__main__":
+ test_from_failure_tuple()
+ test_apply_concat()
+ test_swap_wraps()
+ test_bind_short_circuit()
+ test_combine_n()
+ test_alias_contract()
+ test_collection_is_one_failure()
+ test_empty_invalid_never_calls_combiner()
+ print("OK")
diff --git a/graff-evals/fixtures/validated-contract-v2/validated.py b/graff-evals/fixtures/validated-contract-v2/validated.py
new file mode 100644
index 00000000..d4d43a0a
--- /dev/null
+++ b/graff-evals/fixtures/validated-contract-v2/validated.py
@@ -0,0 +1,99 @@
+"""Validated / Invalid — incomplete. Fix the SPEC.md contract."""
+
+
+class Valid:
+ __match_args__ = ("value",)
+
+ def __init__(self, value):
+ self.value = value
+
+ def bind(self, fn):
+ return fn(self.value)
+
+ def apply(self, other):
+ if isinstance(other, Invalid):
+ return other
+ return Valid(self.value(other.value))
+
+ def swap(self):
+ # BUG: does not wrap in a 1-tuple
+ return Invalid(self.value)
+
+ def alt(self, fn):
+ return self
+
+ @classmethod
+ def from_validated(cls, v):
+ return v
+
+ def __eq__(self, other):
+ return type(other) is Valid and other.value == self.value
+
+ def __repr__(self):
+ return f"Valid({self.value!r})"
+
+
+class Invalid:
+ __match_args__ = ("errors",)
+
+ def __init__(self, errors):
+ if isinstance(errors, tuple):
+ self.errors = errors
+ elif isinstance(errors, (list, set)):
+ self.errors = tuple(errors)
+ else:
+ # BUG: single error stored bare instead of 1-tuple
+ self.errors = errors
+
+ @classmethod
+ def from_failure(cls, err):
+ return cls(err)
+
+ def bind(self, fn):
+ return self
+
+ def apply(self, other):
+ # BUG: does not concatenate when other is Invalid
+ if isinstance(other, Invalid):
+ return self
+ return self
+
+ def swap(self):
+ return Valid(self.errors)
+
+ def alt(self, fn):
+ if isinstance(self.errors, tuple):
+ return Invalid(tuple(fn(e) for e in self.errors))
+ return Invalid(fn(self.errors))
+
+ @classmethod
+ def from_validated(cls, v):
+ return v
+
+ def __eq__(self, other):
+ return type(other) is Invalid and other.errors == self.errors
+
+ def __repr__(self):
+ return f"Invalid({self.errors!r})"
+
+
+def combine(a, b, fn):
+ if isinstance(a, Valid) and isinstance(b, Valid):
+ return Valid(fn(a.value, b.value))
+ if isinstance(a, Invalid) and isinstance(b, Invalid):
+ return a.apply(b)
+ return a if isinstance(a, Invalid) else b
+
+
+def combine_n(items, fn):
+ errs = []
+ vals = []
+ for it in items:
+ if isinstance(it, Invalid):
+ e = it.errors if isinstance(it.errors, tuple) else (it.errors,)
+ errs.extend(e)
+ else:
+ vals.append(it.value)
+ if errs:
+ return Invalid(tuple(errs))
+ return Valid(fn(*vals))
diff --git a/graff-evals/hidden/validated-contract-v2.py b/graff-evals/hidden/validated-contract-v2.py
new file mode 100644
index 00000000..d8902342
--- /dev/null
+++ b/graff-evals/hidden/validated-contract-v2.py
@@ -0,0 +1,127 @@
+#!/usr/bin/env python3
+"""Independent held-out checks for the explicit validated-contract-v2 SPEC.
+Run with --source PATH; no dependence on visible test implementations.
+"""
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import types
+
+
+def audit(source):
+ data = source.read_bytes()
+ module = types.ModuleType("validated_contract_subject")
+ exec(compile(data, str(source), "exec"), module.__dict__)
+ results = []
+
+ def check(name, fn):
+ try:
+ fn()
+ results.append({"name": name, "passed": True})
+ except Exception as exc:
+ results.append({"name": name, "passed": False,
+ "error": f"{type(exc).__name__}: {exc}"})
+
+ def require(condition, reason):
+ if not condition:
+ raise AssertionError(reason)
+
+ V, I = module.Valid, module.Invalid
+ check("required_Validated_export", lambda: require(hasattr(module, "Validated"), "Validated export missing"))
+
+ def alias_classmethods():
+ alias = module.Validated
+ for item in (V(3), I(("e",))):
+ require(alias.from_validated(item) is item, "Validated.from_validated must preserve identity")
+ error = ["one error"]
+ out = alias.from_failure(error)
+ require(isinstance(out, I), "Validated.from_failure must produce Invalid")
+ require(out.errors == (error,), "Validated.from_failure must wrap one error")
+ check("Validated_classmethods", alias_classmethods)
+
+ def immutable_storage():
+ errors = ["a", "b"]
+ out = I(errors)
+ errors.append("c")
+ require(isinstance(out.errors, tuple) and out.errors == ("a", "b"), "errors must be a tuple snapshot")
+ check("immutable_error_storage", immutable_storage)
+
+ def atomic_failure():
+ for error in (["a", "b"], ("a", "b"), None, "ab"):
+ out = I.from_failure(error)
+ require(out.errors == (error,), "from_failure must wrap rather than flatten")
+ check("from_failure_wraps_collection_as_one_error", atomic_failure)
+
+ def swap():
+ for value in ([1, 2], (1, 2), None):
+ require(V(value).swap().errors == (value,), "swap must wrap the entire value")
+ require(I(()).swap() == V(()), "empty errors swap to Valid empty tuple")
+ check("swap_collection_and_empty_tuple", swap)
+
+ def identities():
+ def forbidden(*_):
+ raise AssertionError("callback must not run")
+ valid, invalid = V(1), I(())
+ require(valid.alt(forbidden) is valid, "Valid.alt is identity")
+ require(isinstance(invalid.bind(forbidden), I), "Invalid.bind stays Invalid")
+ for cls in (V, I):
+ for item in (valid, invalid):
+ require(cls.from_validated(item) is item, "from_validated must return identical instance")
+ require(invalid.alt(forbidden).errors == (), "alt on empty errors stays empty")
+ require(I(("a", "b")).alt(str.upper).errors == ("A", "B"), "alt maps each error")
+ check("bind_alt_and_conversion_identities", identities)
+
+ def applicative():
+ require(V.__match_args__ == ("value",), "Valid match declaration")
+ require(I.__match_args__ == ("errors",), "Invalid match declaration")
+ require(V(6).bind(lambda x: V(x - 2)) == V(4), "Valid.bind calls function")
+ require(V(lambda x: x + 11).apply(V(5)) == V(16), "valid applicative")
+ match V(27):
+ case V(value):
+ require(value == 27, "Valid match argument")
+ match I(("pattern",)):
+ case I(errors):
+ require(errors == ("pattern",), "Invalid match argument")
+ require(I(("a", "b")).apply(I(("c", "d"))).errors == ("a", "b", "c", "d"), "error ordering")
+ require(I(()).apply(I(("x",))).errors == ("x",), "empty left errors concatenate")
+ require(I(("x",)).apply(I(())).errors == ("x",), "empty right errors concatenate")
+ require(isinstance(I(()).apply(V(9)), I), "Invalid apply Valid remains Invalid")
+ require(isinstance(V(lambda x: x).apply(I(())), I), "Valid apply empty Invalid remains Invalid")
+ check("applicative_empty_errors_and_order", applicative)
+
+ def combine_short_circuit():
+ def forbidden(*_):
+ raise AssertionError("combination callback ran with Invalid input")
+ for a, b in ((I(()), V(1)), (V(1), I(())), (I(()), I(()))):
+ require(isinstance(module.combine(a, b, forbidden), I), "combine must preserve Invalid")
+ for items in ((I(()),), (V(1), I(())), (I(()), I(()))):
+ out = module.combine_n(items, forbidden)
+ require(isinstance(out, I) and out.errors == (), "any Invalid yields Invalid, including zero errors")
+ check("combine_and_combine_n_empty_Invalid_short_circuit", combine_short_circuit)
+
+ def combine_n():
+ require(module.combine_n((V(2), V(3), V(4)), lambda a, b, c: a * b + c) == V(10), "N values/order")
+ out = module.combine_n((I(("a", "b")), V(2), I(("c",))), lambda *_: None)
+ require(isinstance(out, I) and out.errors == ("a", "b", "c"), "all errors left to right")
+ check("combine_n_success_and_order", combine_n)
+ return {"source": str(source), "sha256": hashlib.sha256(data).hexdigest(),
+ "contract_version": "validated-contract-v2", "checks": results,
+ "contract_pass": all(r["passed"] for r in results)}
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source", type=Path, required=True)
+ args = parser.parse_args()
+ try:
+ result = audit(args.source.resolve())
+ except Exception as exc:
+ print(json.dumps({"audit_error": f"{type(exc).__name__}: {exc}", "contract_pass": False}))
+ return 2
+ print(json.dumps(result, indent=2))
+ return 0 if result["contract_pass"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/graff-evals/tasks/validated-contract-v2.json b/graff-evals/tasks/validated-contract-v2.json
new file mode 100644
index 00000000..d90ac740
--- /dev/null
+++ b/graff-evals/tasks/validated-contract-v2.json
@@ -0,0 +1,13 @@
+{
+ "id": "validated-contract-v2",
+ "suite": "swe",
+ "category": "swe",
+ "source": "https://deepswe.datacurve.ai/run \u2014 returns-validated-error-accumulation (distilled, no Harbor)",
+ "files_dir": "fixtures/validated-contract-v2",
+ "prompt": "Valid/Invalid do not implement the complete contract. Read SPEC.md and validated.py, then make `python3 test_validated.py` print OK. Do not edit tests. Export Validated with the specified classmethods; wrap collection-valued errors as one item; preserve Invalid even when its error tuple is empty.",
+ "check": "python3 test_validated.py && python3 \"$TASK_ROOT/hidden/validated-contract-v2.py\" --source validated.py",
+ "timeout_s": 300,
+ "fixture_version": 2,
+ "contract_version": "validated-contract-v2",
+ "supersedes": "validated"
+}
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index 9630e0e2..e8e37759 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -15,7 +15,7 @@
"src/repl.zig",
"TUI/root.zig"
],
- "test_count_baseline": 2667,
+ "test_count_baseline": 2670,
"test_count_slack": 25,
"required_invariants": [
{
diff --git a/src/agent_eval_control.zig b/src/agent_eval_control.zig
index 999a0a6f..242b7e0c 100644
--- a/src/agent_eval_control.zig
+++ b/src/agent_eval_control.zig
@@ -52,7 +52,7 @@ pub fn batchBlocksCompletion(calls: []const ToolCall) bool {
std.mem.eql(u8, call.name, "write_file") or
std.mem.eql(u8, call.name, "rlm") or
std.mem.eql(u8, call.name, "subagent")) return true;
- if (std.mem.startsWith(u8, call.name, "mcp__")) return !companionReadOnly(call.name, call.input);
+ if (std.mem.startsWith(u8, call.name, "mcp__") and !companionReadOnly(call.name, call.input)) return true;
}
return false;
}
@@ -80,4 +80,4 @@ pub const completion_with_mutation =
"attempt_completion must be a separate post-verification action; this batch also contains a workspace-changing tool";
pub const completion_verify_failed =
- "attempt_completion was not accepted: a verify tool in this batch failed. Fix that result, then complete.";
+ "attempt_completion was not accepted: a verify tool in this batch failed or is still pending. Resolve that result, then complete.";
diff --git a/src/agent_eval_control_tests.zig b/src/agent_eval_control_tests.zig
index 3937536d..81ba6466 100644
--- a/src/agent_eval_control_tests.zig
+++ b/src/agent_eval_control_tests.zig
@@ -150,3 +150,27 @@ test "eval steering carries controller state and local belief memory" {
try std.testing.expect(std.mem.indexOf(u8, note, "prior plan is dropped") != null);
try std.testing.expect(std.mem.indexOf(u8, note, "compiler failed") != null);
}
+
+test "read-only MCP never hides a later mutation from completion policy" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const read = try call(arena, "mcp__codedbpro__read", "{}");
+ const done = try call(arena, "attempt_completion", "{\"result\":\"done\"}");
+ for ([_][]const u8{ "edit_file", "write_file", "rlm", "subagent", "mcp__codedbpro__edit" }) |name| {
+ const mutation = try call(arena, name, "{}");
+ const orders = [_][3]ToolCall{
+ .{ read, mutation, done }, .{ read, done, mutation },
+ .{ mutation, read, done }, .{ mutation, done, read },
+ .{ done, read, mutation }, .{ done, mutation, read },
+ };
+ for (orders) |batch| {
+ try std.testing.expect(eval_control.batchBlocksCompletion(&batch));
+ try std.testing.expect(!eval_control.shouldDeferCompletion(&batch));
+ }
+ }
+ for ([_][2]ToolCall{ .{ read, done }, .{ done, read } }) |batch| {
+ try std.testing.expect(!eval_control.batchBlocksCompletion(&batch));
+ try std.testing.expect(eval_control.shouldDeferCompletion(&batch));
+ }
+}
diff --git a/src/agent_tool_batch.zig b/src/agent_tool_batch.zig
index c3813dcb..33f917b7 100644
--- a/src/agent_tool_batch.zig
+++ b/src/agent_tool_batch.zig
@@ -140,14 +140,14 @@ fn aborted() bool {
fn takeOutput(self: *Agent, call: ToolCall, output: ToolOutput, handle_threshold: usize, handle_target: tool_handle.Target) !ExecResult {
self.read_miss.noteOutput(call.name, call.input, output.text, output.is_error);
- try @import("pr_local_checks.zig").record(self, call, .{ .text = output.text, .is_error = output.is_error, .cancelled = output.cancelled });
+ try @import("pr_local_checks.zig").record(self, call, .{ .text = output.text, .is_error = output.is_error, .cancelled = output.cancelled, .pending = output.pending });
const handled = try tool_handle.forResult(self.gpa, self.arena, handle_target, output.text, handle_threshold);
const text = try tool_handle.withFirstNote(self.arena, handled, &self.handle_note_shown);
if (self.eval_cmd != null and eval_control.toolInvalidatesEval(call)) {
self.eval_verified = false;
self.eval_repair_pending = false;
}
- return .{ .text = text, .is_error = output.is_error, .cancelled = output.cancelled, .ms = output.ms };
+ return .{ .text = text, .is_error = output.is_error, .cancelled = output.cancelled, .pending = output.pending, .ms = output.ms };
}
fn handleTarget(self: *Agent) tool_handle.Target {
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 2c079cc2..50941a5c 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -145,7 +145,7 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
if (defer_completion) if (eval_control.completionIndex(calls)) |i| {
var verify_failed = ext_idx.items.len == 0;
for (ext_idx.items) |j| {
- if (results[j].is_error or results[j].cancelled) verify_failed = true;
+ if (results[j].is_error or results[j].cancelled or results[j].pending) verify_failed = true;
}
if (verify_failed) {
self.emitToolRejected(calls[i], "eval_stale", eval_control.completion_verify_failed);
diff --git a/src/edit_batch.zig b/src/edit_batch.zig
index 5f0ea651..cf186eb5 100644
--- a/src/edit_batch.zig
+++ b/src/edit_batch.zig
@@ -20,14 +20,16 @@ const ToolOutput = tools.ToolOutput;
const Value = std.json.Value;
/// The `edits`-array arm of edit_file; exec.zig routes here when the input
-/// carries a non-null `edits` field. Same confinement and worktree
+/// carries an `edits` field. Same confinement and worktree
/// resolution as edit_verify.execEdit.
pub fn execBatch(ctx: ToolCtx, input: Value) !ToolOutput {
const gpa = ctx.gpa;
const path = tools.strField(input, "path") orelse return tools.missingArg(gpa, "path");
if (!approvals.confinedPath(path) or !approvals.noSymlinkEscape(ctx.io, path, ctx.agent_cwd))
return .{ .text = try std.fmt.allocPrint(gpa, "{s} is outside the working directory — edit_file stays inside it", .{path}), .is_error = true };
- const list = input.object.get("edits").?.array;
+ const edits = input.object.get("edits") orelse return tools.missingArg(gpa, "edits");
+ if (edits != .array) return .{ .text = try gpa.dupe(u8, "edits must be an array of edit span objects"), .is_error = true };
+ const list = edits.array;
if (list.items.len == 0) return .{ .text = try gpa.dupe(u8, "edits must contain at least one span"), .is_error = true };
// #747: same absolute selected-tree path as execEdit (write + verify).
@@ -90,3 +92,35 @@ test "execBatch: two spans apply in one call; a bad span reports its index and p
const after = try tmp.dir.readFileAlloc(io, "f.txt", a, .limited(4096));
try std.testing.expect(std.mem.indexOf(u8, after, "3 three") != null); // span 1 landed
}
+
+test "execBatch dispatch rejects malformed edits then accepts a corrected array" {
+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "f.txt", .data = "alpha\nbeta\n" });
+ const rel = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/f.txt", .{&tmp.sub_path});
+ var client: std.http.Client = undefined;
+ const ctx: ToolCtx = .{ .gpa = a, .io = io, .client = &client, .provider = undefined, .registry = null, .from_sub = false, .approvals = null, .tracer = null };
+ for ([_][]const u8{ "\"serialized edits\"", "null", "{}", "true", "7" }) |bad| {
+ const encoded = try std.fmt.allocPrint(a, "{{\"path\":\"P\",\"edits\":{s}}}", .{bad});
+ var input = try std.json.parseFromSliceLeaky(Value, a, encoded, .{ .allocate = .alloc_always });
+ try input.object.put(a, "path", .{ .string = rel });
+ const out = @import("exec.zig").execTool(ctx, .{ .id = "bad-edit", .name = "edit_file", .input = input });
+ try std.testing.expect(out.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, out.text, "edits must be an array") != null);
+ const unchanged = try tmp.dir.readFileAlloc(io, "f.txt", a, .limited(4096));
+ try std.testing.expectEqualStrings("alpha\nbeta\n", unchanged);
+ }
+ var input = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"path":"P","edits":[{"old_string":"alpha","new_string":"ALPHA"},{"old_string":"beta","new_string":"BETA"}]}
+ , .{ .allocate = .alloc_always });
+ try input.object.put(a, "path", .{ .string = rel });
+ const out = @import("exec.zig").execTool(ctx, .{ .id = "corrected-edit", .name = "edit_file", .input = input });
+ try std.testing.expect(!out.is_error);
+ const changed = try tmp.dir.readFileAlloc(io, "f.txt", a, .limited(4096));
+ try std.testing.expectEqualStrings("ALPHA\nBETA\n", changed);
+}
diff --git a/src/exec_bash.zig b/src/exec_bash.zig
index 0b2bd64d..b922a133 100644
--- a/src/exec_bash.zig
+++ b/src/exec_bash.zig
@@ -340,7 +340,7 @@ fn execUnchecked(ctx: ToolCtx, call: tools.ToolCall) !ToolOutput {
}) catch |err| return .{ .text = try spawnFailText(gpa, err), .is_error = true };
if (bg) {
@import("subagent_interactive.zig").request(ctx);
- return .{ .text = try startedText(gpa, job.id, job.cmd, ssh, false, 0, "") };
+ return .{ .text = try startedText(gpa, job.id, job.cmd, ssh, false, 0, ""), .pending = true };
}
const wait_ms = rootWaitMsFor(input, ctx.interactive_children);
const waited = jobs.waitForeground(gpa, io, job.id, wait_ms) catch |err| return .{
@@ -356,7 +356,7 @@ fn execUnchecked(ctx: ToolCtx, call: tools.ToolCall) !ToolOutput {
defer gpa.free(r.output);
jobs.markPersistent(io, r.id);
@import("subagent_interactive.zig").request(ctx);
- break :blk .{ .text = try startedText(gpa, r.id, cmd, ssh, true, wait_ms / 1000, r.output) };
+ break :blk .{ .text = try startedText(gpa, r.id, cmd, ssh, true, wait_ms / 1000, r.output), .pending = true };
},
.cancelled => |c| blk: {
defer jobs.reapFinished(gpa, io, c.id);
diff --git a/src/jobs.zig b/src/jobs.zig
index 624bc3da..ab78c3d6 100644
--- a/src/jobs.zig
+++ b/src/jobs.zig
@@ -417,8 +417,9 @@ pub fn jobOutput(gpa: Allocator, io: Io, id: u32, wait_ms: u64) !ToolOutput {
const text = try aw.toOwnedSlice();
job.cursor = job.buf.items.len;
if (job.done) job_notify.dismiss(io, id); // the exit was just read here; no wake for it (ADR 0061)
+ const result: ToolOutput = .{ .text = text, .pending = !job.done, .is_error = job.done and (job.stopped_idle or job.killed or (job.exit_code orelse 1) != 0), .cancelled = job.killed };
g_jobs.mutex.unlock(io);
- return .{ .text = text };
+ return result;
}
g_jobs.mutex.unlock(io);
if (Agent.esc_cancel.load(.acquire)) {
diff --git a/src/jobs_tests.zig b/src/jobs_tests.zig
index eb2940e5..c88bb75b 100644
--- a/src/jobs_tests.zig
+++ b/src/jobs_tests.zig
@@ -182,6 +182,7 @@ test "#850: a bounded promote leaves the child on bash_output and bash_kill" {
const snap = try jobs.jobOutput(gpa, io, id, 0);
defer gpa.free(snap.text);
try std.testing.expect(std.mem.indexOf(u8, snap.text, "running") != null);
+ try std.testing.expect(snap.pending and !snap.is_error);
const killed = try jobs.jobKill(gpa, io, id);
defer gpa.free(killed.text);
try std.testing.expect(!killed.is_error);
@@ -189,6 +190,7 @@ test "#850: a bounded promote leaves the child on bash_output and bash_kill" {
const after = try jobs.jobOutput(gpa, io, id, 2_000);
defer gpa.free(after.text);
try std.testing.expect(std.mem.indexOf(u8, after.text, "running") == null);
+ try std.testing.expect(after.cancelled and after.is_error and !after.pending);
}
test "ADR 0152: auto-parked job output ignores wait_ms" {
diff --git a/src/mcp_schema_gate.zig b/src/mcp_schema_gate.zig
index d47ce67d..7be3e0a0 100644
--- a/src/mcp_schema_gate.zig
+++ b/src/mcp_schema_gate.zig
@@ -174,7 +174,7 @@ fn publish(arena: Allocator, name: []const u8, rendered: []const u8) !*Node {
}
var g_seq: usize = 0;
-fn nextSeq() usize {
+pub fn nextSeq() usize {
g_seq += 1;
return g_seq;
}
diff --git a/src/mcp_schema_gate_tests.zig b/src/mcp_schema_gate_tests.zig
index f085272b..48603f01 100644
--- a/src/mcp_schema_gate_tests.zig
+++ b/src/mcp_schema_gate_tests.zig
@@ -393,3 +393,65 @@ test "tool_desc stays JSON-escape-free (it is spliced into a raw schema string)"
defer ph.deinit();
try testing.expectEqualStrings("object", ph.value.object.get("type").?.string);
}
+
+test "mixed native MCP loads preserve earlier emitted tool entries" {
+ withDefaults();
+ defer withDefaults();
+ const fold = @import("native_fold.zig");
+ const saved_enabled = fold.enabled;
+ const saved_stable = gate.g_stable_catalog;
+ fold.enabled = true;
+ gate.g_stable_catalog = true;
+ gate.g_policy.budget = 1;
+ fold.clearLoadedSession();
+ defer {
+ fold.clearLoadedSession();
+ fold.enabled = saved_enabled;
+ gate.g_stable_catalog = saved_stable;
+ }
+ var state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer state.deinit();
+ const a = state.allocator();
+ const fat = try fixture(a, "fat", 3, 2000);
+ const schema = @import("schema.zig");
+ const specs = [_]schema.ToolSpec{.{ .name = gate.tool_name, .desc = gate.tool_desc, .schema = gate.tool_schema }};
+ const load = try std.json.parseFromSliceLeaky(Value, a, "{\"tools\":[\"mcp__fat__t0\"]}", .{});
+ const loaded = try gate.loadInto(a, fat, load);
+ try testing.expectEqual(@as(usize, 1), loaded.loaded);
+ const routes = [_]struct { id: []const u8, kind: @import("provider.zig").Provider.Kind, model: []const u8 }{
+ .{ .id = "codegraff", .kind = .openai, .model = "mimo-v2.5" },
+ .{ .id = "xai", .kind = .responses, .model = "grok-4.6" },
+ .{ .id = "codex", .kind = .responses, .model = "gpt-6-sol" },
+ };
+ var before: [routes.len][]const u8 = undefined;
+ var catalogs: [routes.len][]const u8 = undefined;
+ for (routes, 0..) |route, i| {
+ var agent = try @import("agent_request_body_responses.zig").testAgentFor(a, route.id, route.kind, route.model);
+ catalogs[i] = try schema.renderRootTools(a, route.kind, &specs, fat);
+ const body = try agent.buildBody(catalogs[i], false, true, true);
+ defer testing.allocator.free(body);
+ const parsed = try std.json.parseFromSliceLeaky(Value, a, body, .{ .allocate = .alloc_always });
+ before[i] = try std.json.Stringify.valueAlloc(a, parsed.object.get("tools").?, .{});
+ }
+ fold.markLoaded("todo_read");
+ for (routes, 0..) |route, i| {
+ var agent = try @import("agent_request_body_responses.zig").testAgentFor(a, route.id, route.kind, route.model);
+ const catalog = try schema.renderRootTools(a, route.kind, &specs, fat);
+ try testing.expect(std.mem.startsWith(u8, catalog, catalogs[i][0 .. catalogs[i].len - 1]));
+ const body = try agent.buildBody(catalog, false, true, true);
+ defer testing.allocator.free(body);
+ const parsed = try std.json.parseFromSliceLeaky(Value, a, body, .{ .allocate = .alloc_always });
+ const entries = parsed.object.get("tools").?.array.items;
+ const earlier = try std.json.parseFromSliceLeaky(Value, a, before[i], .{});
+ // Hosted provider tools may follow the catalog; require every existing
+ // catalog entry to retain its relative position ahead of the new native.
+ const old_tools = earlier.array.items;
+ try testing.expectEqual(old_tools.len + 1, entries.len);
+ const added = if (route.kind == .openai) entries[2].object.get("function").? else entries[2];
+ try testing.expectEqualStrings("todo_read", added.object.get("name").?.string);
+ for (old_tools[0..2], entries[0..2]) |old, new| {
+ try testing.expectEqualStrings(try std.json.Stringify.valueAlloc(a, old, .{}), try std.json.Stringify.valueAlloc(a, new, .{}));
+ }
+ try testing.expect(std.mem.indexOf(u8, body, "todo_read") != null);
+ }
+}
diff --git a/src/native_fold.zig b/src/native_fold.zig
index b86ce916..c6b8b528 100644
--- a/src/native_fold.zig
+++ b/src/native_fold.zig
@@ -196,7 +196,10 @@ fn unmark(name: []const u8) void {
var i: usize = 0;
while (i < g_loaded_len) : (i += 1) {
if (std.mem.eql(u8, g_loaded[i], name)) {
- if (i + 1 < g_loaded_len) g_loaded[i] = g_loaded[g_loaded_len - 1];
+ if (i + 1 < g_loaded_len) {
+ g_loaded[i] = g_loaded[g_loaded_len - 1];
+ g_loaded_seq[i] = g_loaded_seq[g_loaded_len - 1];
+ }
g_loaded_len -= 1;
return;
}
@@ -217,6 +220,7 @@ pub fn anyFolded() bool {
var g_loaded: [folded.len][]const u8 = undefined;
var g_loaded_len: usize = 0;
+var g_loaded_seq: [folded.len]usize = undefined;
pub fn isLoaded(name: []const u8) bool {
for (g_loaded[0..g_loaded_len]) |n| {
@@ -234,6 +238,7 @@ pub fn markLoaded(name: []const u8) void {
for (folded) |tool| {
if (std.mem.eql(u8, name, tool)) {
g_loaded[g_loaded_len] = tool;
+ g_loaded_seq[g_loaded_len] = mcp_schema_gate.nextSeq();
g_loaded_len += 1;
return;
}
@@ -255,34 +260,46 @@ pub fn clearLoadedSession() void {
/// The session's loaded folded natives, in load order (schema.zig's stable
/// tail appends them after the stable head — load order keeps it append-only).
+pub fn loadSeq(name: []const u8) ?usize {
+ for (loadedNames(), g_loaded_seq[0..g_loaded_len]) |loaded, seq| {
+ if (std.mem.eql(u8, name, loaded)) return seq;
+ }
+ return null;
+}
+
pub fn loadedNames() []const []const u8 {
return g_loaded[0..g_loaded_len];
}
/// GRAFF_STABLE_CATALOG tail (schema.zig renderRootTools, #476): every tool
/// whose schema has loaded this session, appended in LOAD ORDER after the
-/// stable catalog head — folded natives first, then MCP tools by gate seq.
+/// stable catalog head — natives and MCP tools share one admission sequence.
/// Append-only is the point: a load changes only the tools array's tail
/// bytes, and the provider's prefix cache (tools serialize before messages)
/// survives what a mid-array re-insertion would bust.
pub fn renderLoadedTail(s: *std.json.Stringify, kind: @import("provider.zig").Provider.Kind, out: Allocator, mcp_tools: []const @import("mcp.zig").Tool) !void {
const schema_mod = @import("schema.zig");
const mcp = @import("mcp.zig");
- for (loadedNames()) |name| {
- // #868: available rlm is already in the catalog head.
+ const Entry = struct { seq: usize, native: ?[]const u8 = null, external: ?mcp.Tool = null };
+ var loaded: std.ArrayList(Entry) = .empty;
+ for (loadedNames(), g_loaded_seq[0..g_loaded_len]) |name, seq| {
if (std.mem.eql(u8, name, "rlm") and @import("rlm_spec.zig").available) continue;
- const spec = (try findRootSpec(out, name)) orelse continue;
- try schema_mod.writeToolEntry(s, kind, spec.name, spec.desc, .{ .raw = spec.schema });
+ try loaded.append(out, .{ .seq = seq, .native = name });
}
- var loaded: std.ArrayList(mcp.Tool) = .empty;
- for (mcp_tools) |m| if (mcp_schema_gate.policyDeferred(mcp_tools, m) and mcp_schema_gate.loadSeq(m.qualified_name) != null)
- try loaded.append(out, m);
- std.mem.sort(mcp.Tool, loaded.items, {}, struct {
- fn lt(_: void, a: mcp.Tool, b: mcp.Tool) bool {
- return mcp_schema_gate.loadSeq(a.qualified_name).? < mcp_schema_gate.loadSeq(b.qualified_name).?;
+ for (mcp_tools) |m| if (mcp_schema_gate.policyDeferred(mcp_tools, m)) {
+ if (mcp_schema_gate.loadSeq(m.qualified_name)) |seq| try loaded.append(out, .{ .seq = seq, .external = m });
+ };
+ std.mem.sort(Entry, loaded.items, {}, struct {
+ fn lt(_: void, a: Entry, b: Entry) bool {
+ return a.seq < b.seq;
}
}.lt);
- for (loaded.items) |m| try schema_mod.writeToolEntry(s, kind, m.qualified_name, m.description, .{ .value = m.input_schema });
+ for (loaded.items) |entry| {
+ if (entry.native) |name| {
+ const spec = (try findRootSpec(out, name)) orelse continue;
+ try schema_mod.writeToolEntry(s, kind, spec.name, spec.desc, .{ .raw = spec.schema });
+ } else if (entry.external) |m| try schema_mod.writeToolEntry(s, kind, m.qualified_name, m.description, .{ .value = m.input_schema });
+ }
}
/// Whether the root catalog skips this native spec at render: folded and not
@@ -499,10 +516,12 @@ test "explicit native loads rebuild the active provider catalog (#492)" {
const saved_enabled = enabled;
const saved_loaded = g_loaded;
+ const saved_seq = g_loaded_seq;
const saved_loaded_len = g_loaded_len;
defer {
enabled = saved_enabled;
g_loaded = saved_loaded;
+ g_loaded_seq = saved_seq;
g_loaded_len = saved_loaded_len;
}
enabled = true;
diff --git a/src/pr_local_checks.zig b/src/pr_local_checks.zig
index d7b47366..3cc2ff4c 100644
--- a/src/pr_local_checks.zig
+++ b/src/pr_local_checks.zig
@@ -80,7 +80,7 @@ pub fn record(root: anytype, call: ToolCall, result: ExecResult) !void {
const target = ev.Target{ .cwd = cwd, .selector = "" };
const head = ev.localHead(root.gpa, root.io, root.arena, target) catch "";
const dirty = ev.capture(root.gpa, root.io, root.arena, target, &.{ "git", "status", "--porcelain", "--untracked-files=no" }) catch "unknown";
- try root.publication_checks.recordReceipt(root.arena, .{ .repository = repository, .command = command, .head_after = head, .tracked_tree_clean_after = dirty.len == 0, .output = result.text, .failed = result.is_error or result.cancelled, .completed = std.mem.indexOf(u8, result.text, "[job ") == null });
+ try root.publication_checks.recordReceipt(root.arena, .{ .repository = repository, .command = command, .head_after = head, .tracked_tree_clean_after = dirty.len == 0, .output = result.text, .failed = result.is_error or result.cancelled, .completed = !result.pending and std.mem.indexOf(u8, result.text, "[job ") == null });
}
pub fn batchGate(root: anytype, calls: []const ToolCall, call: ToolCall) !?ExecResult {
@@ -135,11 +135,11 @@ pub const State = struct {
const command = std.mem.trim(u8, raw, " \t\r\n");
for (self.failed.items, 0..) |entry, i| {
if (!std.mem.eql(u8, entry.cwd, cwd) or !std.mem.eql(u8, entry.command, command)) continue;
- if (!result.is_error and !result.cancelled and std.mem.indexOf(u8, result.text, "[job ") == null)
+ if (!result.is_error and !result.cancelled and !result.pending and std.mem.indexOf(u8, result.text, "[job ") == null)
_ = self.failed.orderedRemove(i);
return;
}
- if (!result.is_error and !result.cancelled and std.mem.indexOf(u8, result.text, "[job ") == null) return;
+ if (!result.is_error and !result.cancelled and !result.pending and std.mem.indexOf(u8, result.text, "[job ") == null) return;
try self.failed.append(arena, .{ .cwd = try arena.dupe(u8, cwd), .command = try arena.dupe(u8, command), .repository = try arena.dupe(u8, repository) });
}
@@ -199,6 +199,8 @@ test "observed failed check survives unrelated success and clears only on its su
try std.testing.expect(state.unresolved("/fixture") != null);
try state.observe(a, "/fixture", call, .{ .text = "[job 1 started]", .is_error = false });
try std.testing.expect(state.unresolved("/fixture") != null);
+ try state.observe(a, "/fixture", call, .{ .text = "exit 0", .is_error = false, .pending = true });
+ try std.testing.expect(state.unresolved("/fixture") != null);
try state.observe(a, "/fixture", call, .{ .text = "OK", .is_error = false });
try std.testing.expect(state.unresolved("/fixture") == null);
}
diff --git a/src/prompt_text.zig b/src/prompt_text.zig
index 27c2e8c4..4b6b958d 100644
--- a/src/prompt_text.zig
+++ b/src/prompt_text.zig
@@ -358,10 +358,10 @@ pub const parallel_tools_note = parallel_core_note ++ parallel_examples_note ++
pub const lean_local_tools_note =
\\
\\read_file before editing; prefer edit_file for existing files and
- \\write_file only for new files. Navigate with codedb (context, around,
+ \\write_file only for new files. Use the smallest unique edit spans and
+ \\preserve terminal-newline state. Navigate with codedb (context, around,
\\callpath, list_dir, status).
\\Independent reads belong in ONE response, not a chain of turns.
- \\A passing verify command and attempt_completion belong in ONE response.
;
/// --lean swap-in for `parallel_core_note`. The long Parallelize / fan-out
@@ -371,20 +371,23 @@ pub const lean_parallel_note =
\\
\\Independent reads and checks belong in ONE response; they run concurrently.
\\A call that needs an earlier result, or two writes to the same file, stays
- \\in its own turn. A passing verify and attempt_completion share a response.
+ \\in its own turn.
;
pub const lean_intro_note =
\\You are a coding agent. Use the cataloged tools; never invent one.
\\A file change described in prose is not done — call edit_file or write_file.
\\Independent reads belong in ONE response, not one per turn.
- \\For requested changes, a passing test and attempt_completion belong in ONE response.
++ @import("task_intent.zig").guidance;
pub const lean_work_note =
\\
\\For requested changes, apply the change and verify with the project's own
\\tests in its OWN environment. Use named files and tests directly.
+ \\Batch a final verification shell call with attempt_completion only when
+ \\the answer needs no result-dependent detail. The harness blocks completion
+ \\if verification fails. If interpretation is needed, inspect results first.
+ \\Never rerun verification just to batch.
\\Do not add unrequested tests. Never repeat a tool call with identical
\\parameters. When a change request names a file, read it and edit that path
\\before answering — do not describe a fix you have not applied.
diff --git a/src/rlm.zig b/src/rlm.zig
index 4cb0eabe..455e706c 100644
--- a/src/rlm.zig
+++ b/src/rlm.zig
@@ -114,7 +114,7 @@ pub fn runScript(ctx: ToolCtx, code: []const u8) !ToolOutput {
if (try observed.fetchPut(key, {})) |_| continue;
const output = claimed.get(key) orelse continue;
const input_value = pathValue(arena, call.args_json);
- try observer.record(observer.context, .{ .id = "rlm", .name = call.name, .input = input_value }, .{ .text = output.text, .is_error = output.is_error, .cancelled = output.cancelled });
+ try observer.record(observer.context, .{ .id = "rlm", .name = call.name, .input = input_value }, .{ .text = output.text, .is_error = output.is_error, .cancelled = output.cancelled, .pending = output.pending });
}
}
diff --git a/src/session_catalog.zig b/src/session_catalog.zig
index 1f0390e6..cb1b7c38 100644
--- a/src/session_catalog.zig
+++ b/src/session_catalog.zig
@@ -154,7 +154,10 @@ fn connected(root: *const Agent) []const Tool {
pub fn mixFingerprint(root: *const Agent, f: anytype) void {
f.flag(native.listed());
- for (native.loadedNames()) |name| f.text(name);
+ for (native.loadedNames()) |name| {
+ f.text(name);
+ f.num(native.loadSeq(name).?);
+ }
for (connected(root)) |tool| {
if (gate.loadSeq(tool.qualified_name)) |seq| {
f.text(tool.qualified_name);
@@ -172,7 +175,7 @@ pub fn write(root: *const Agent, s: *std.json.Stringify) !void {
try s.write(native.listed());
try s.objectField("mcp");
try s.beginArray();
- // Match the existing native-first, MCP-by-sequence catalog tail.
+ // Preserve legacy fields for older readers; order below unifies both kinds.
var previous: usize = 0;
while (true) {
var next: ?Tool = null;
@@ -189,6 +192,30 @@ pub fn write(root: *const Agent, s: *std.json.Stringify) !void {
previous = best;
}
try s.endArray();
+ try s.objectField("order");
+ try s.beginArray();
+ previous = 0;
+ while (true) {
+ var next: ?[]const u8 = null;
+ var best: usize = std.math.maxInt(usize);
+ for (native.loadedNames()) |name| {
+ const seq = native.loadSeq(name).?;
+ if (seq > previous and seq < best) {
+ next = name;
+ best = seq;
+ }
+ }
+ for (connected(root)) |tool| {
+ const seq = gate.loadSeq(tool.qualified_name) orelse continue;
+ if (seq > previous and seq < best) {
+ next = tool.qualified_name;
+ best = seq;
+ }
+ }
+ try s.write(next orelse break);
+ previous = best;
+ }
+ try s.endArray();
try s.endObject();
}
@@ -201,25 +228,33 @@ pub fn restore(root: *Agent, obj: std.json.ObjectMap) !void {
if (saved.object.get("rlm_showcased")) |v| {
if (v == .bool and v.bool) native.showcaseRlm();
}
- if (saved.object.get("native")) |names| {
- if (names == .array) for (names.array.items) |name| {
- if (name != .string or !native.isFolded(name.string)) continue;
- if (try native.findRootSpec(root.arena, name.string) != null)
- native.markLoaded(name.string);
- };
+ if (saved.object.get("order")) |names| {
+ if (names == .array) {
+ for (names.array.items) |name| try restoreName(root, name);
+ return;
+ }
}
- if (saved.object.get("mcp")) |names| {
- if (names == .array) for (names.array.items) |name| {
- if (name != .string) continue;
- for (connected(root)) |tool| {
- if (!std.mem.eql(u8, tool.qualified_name, name.string)) continue;
- var input: std.json.ObjectMap = .empty;
- var list: std.json.Array = .init(root.arena);
- try list.append(name);
- try input.put(root.arena, "tools", .{ .array = list });
- _ = try gate.loadInto(root.arena, connected(root), .{ .object = input });
- break;
- }
- };
+ // Legacy snapshots predate interleaving and rendered natives first.
+ for ([_][]const u8{ "native", "mcp" }) |field| {
+ if (saved.object.get(field)) |names| {
+ if (names == .array) for (names.array.items) |name| try restoreName(root, name);
+ }
+ }
+}
+
+fn restoreName(root: *Agent, name: std.json.Value) !void {
+ if (name != .string) return;
+ if (native.isFolded(name.string)) {
+ if (try native.findRootSpec(root.arena, name.string) != null) native.markLoaded(name.string);
+ return;
+ }
+ for (connected(root)) |tool| {
+ if (!std.mem.eql(u8, tool.qualified_name, name.string)) continue;
+ var input: std.json.ObjectMap = .empty;
+ var list: std.json.Array = .init(root.arena);
+ try list.append(name);
+ try input.put(root.arena, "tools", .{ .array = list });
+ _ = try gate.loadInto(root.arena, connected(root), .{ .object = input });
+ break;
}
}
diff --git a/src/tools.zig b/src/tools.zig
index 618fab60..e6d4e203 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -33,6 +33,7 @@ pub const ExecResult = struct {
text: []const u8,
is_error: bool,
cancelled: bool = false, // ended by user Esc, not by failing (#266)
+ pending: bool = false, // asynchronous work has no terminal result yet
ms: i64 = 0, // wall-clock of the tool exec (external tools only; --timing)
};
@@ -80,6 +81,7 @@ pub const ToolOutput = struct {
text: []u8 = &.{}, // gpa-owned
is_error: bool = false,
cancelled: bool = false, // ended by user Esc, not by failing (#266)
+ pending: bool = false, // asynchronous work has no terminal result yet
ms: i64 = 0, // set by execTool
};