Skip to content

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

Python

Add explicit conversation forks for workers and workflows

Rach Pradhan10c02c285ac4
diff --git a/build.zig b/build.zig
index aee1d528..e8ec1175 100644
--- a/build.zig
+++ b/build.zig
@@ -230,6 +230,9 @@ pub fn build(b: *std.Build) void {
const subagent_resume_test = b.addSystemCommand(&.{ "python3", "scripts/test-subagent-resume.py" });
subagent_resume_test.addArtifactArg(exe);
test_step.dependOn(&subagent_resume_test.step);
+ const subagent_fork_test = b.addSystemCommand(&.{ "python3", "scripts/test-subagent-fork.py" });
+ subagent_fork_test.addArtifactArg(exe);
+ test_step.dependOn(&subagent_fork_test.step);
const learn_formal_test = b.addSystemCommand(&.{ "python3", "tests/learn_formal_e2e.py", "--graff" });
learn_formal_test.addArtifactArg(exe);
test_step.dependOn(&learn_formal_test.step);
diff --git a/docs/adr/0299-conversation-history-forks-are-explicit.md b/docs/adr/0299-conversation-history-forks-are-explicit.md
new file mode 100644
index 00000000..943b5330
--- /dev/null
+++ b/docs/adr/0299-conversation-history-forks-are-explicit.md
@@ -0,0 +1,58 @@
+# 0299. Conversation-history forks are explicit, independent worker snapshots
+
+## Context
+
+ADR 0232 deliberately gives normal children a small request prefix instead of
+copying the parent's entire conversation. That remains a useful default, but
+it cannot continue an investigation whose evidence is in prior assistant turns
+and tool results. ADR 0170 already owns durable worker histories; session forks
+already own independent root conversations. Neither needs to become a shared,
+mutable agent history.
+
+## Decision
+
+`subagent.fork_from` opts into a conversation snapshot:
+
+- `current`: the caller's completed history, before its in-flight spawn batch.
+- `session:<name>`: a saved conversation in the current project; no arbitrary
+ path, home-directory search, credential lookup, or source-agent execution.
+- `worker:<task_id>`: a completed retained worker owned by the same parent
+ family. Existing locking, forgotten-worker, deadline and budget checks apply.
+
+The child gets its own deep copy and then the new task. The source checkpoint
+is not rewritten, and siblings cannot append to one another's histories.
+Queued mail belongs to the original worker and is not consumed by a fork.
+`subagent_resume` still continues the original; a fork creates another child.
+
+The child keeps its own instructions, tool catalog, approvals and selected
+workspace/isolation. Source goals, live handles, credentials, root instructions
+and loaded-tool announcements are not adopted. A retained source's read-only,
+text-only and deadline restrictions cannot be relaxed by forking it. This is a
+conversation fork, not a copy of uncommitted filesystem changes.
+
+Same-wire history keeps native completed tool receipts and images. Across wire
+formats, visible dialogue and tool receipts become inert historical text rather
+than executable calls. Opaque compaction requires the original provider, model
+and wire; images require the original wire. Refuse unsupported transfers rather
+than silently dropping evidence. A native opaque window keeps its provenance.
+
+`retained: true` remains a separate opt-in: it saves the new child's history and
+workspace and returns its own `task_id`. Omitted retention remains ephemeral.
+`workflow` accepts the same top-level `fork_from` and `retained` fields for
+phases and pipelines. It resolves its source once, copies it independently into
+each worker, and preserves retained chain workspaces even when they are clean.
+Judges do not inherit the source or gain persistent workers. All paths use the
+shared engine on the REPL and ACP, not client-only behavior.
+
+## Consequences
+
+Existing lightweight delegation is unchanged. Explicit full-history fan-out
+costs memory and input tokens per child; it does not promise the parent's
+cached system/tool prefix. Ephemeral workers that already finished have no
+history to recover: retain them when future continuation is wanted.
+
+Validation lives in `subagent_history*_tests`/`subagent_history_copy.zig` and
+`scripts/test-subagent-fork.py`: owned snapshots, native/cross-wire evidence,
+opaque and image refusal, ownership/budget restrictions, independent siblings,
+original-only resume, and retained phase/pipeline fan-out through ACP and the
+legacy JSON surface.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index c5baffbb..3e705143 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -317,6 +317,8 @@ record only when you need the evidence or the edge cases.
| [0297](0297-sdk-managed-replay-reuses-the-relay.md) | The fetch-only managed SDK reuses account relay/device tapes; prompt retries are explicit, durability limits are stated, and content-free OTLP export remains opt-in and observational. |
| [0298](0298-peer-send-wakes-are-bounded.md) | A `graff peer send` live wake is concurrent and bounded by one shared deadline; misses are reported and the durable room post still succeeds. |
+| [0299](0299-conversation-history-forks-are-explicit.md) | `fork_from` explicitly snapshots current, project-local saved, or family-owned worker history into independent children; lightweight delegation stays the default and `retained` remains opt-in across subagents and workflows. |
+
## When to write one
Write an ADR when a decision is load-bearing and non-obvious: it was reached
diff --git a/scripts/test-subagent-fork.py b/scripts/test-subagent-fork.py
new file mode 100755
index 00000000..383bf988
--- /dev/null
+++ b/scripts/test-subagent-fork.py
@@ -0,0 +1,357 @@
+#!/usr/bin/env python3
+"""Offline fork-history integration on ACP and legacy JSON; no live model calls."""
+import importlib.util
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import traceback
+
+REPO = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(REPO / 'scripts/eval'))
+from mock_model import ScriptedModel
+
+spec = importlib.util.spec_from_file_location('acp_load', REPO / 'scripts/test-acp-session-load.py')
+acp_load = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(acp_load)
+Acp = acp_load.Acp
+
+# A developer's proxy must never receive this fixture's loopback requests.
+LOCAL_NETWORK_ENV = {key: '' for key in (
+ 'http_proxy', 'https_proxy', 'all_proxy', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY')}
+LOCAL_NETWORK_ENV.update(no_proxy='*', NO_PROXY='*')
+
+
+def text(messages):
+ return json.dumps(messages)
+
+
+def tool(name, **arguments):
+ return {'tool': name, 'arguments': arguments}
+
+
+def task(name, suffix=''):
+ return {'description': 'Fork fixture ' + name,
+ 'prompt': 'FORK_TASK:' + name + ' Reply once. ' + suffix,
+ 'isolation': 'shared_cwd'}
+
+
+def spawn(name, source=None, retained=False, background=False):
+ args = task(name)
+ args.update(retained=retained, run_in_background=background)
+ if source is not None:
+ args['fork_from'] = source
+ return tool('subagent', **args)
+
+
+def outputs(body):
+ return text([m for m in body['messages'] if m.get('role') == 'tool'])
+
+
+def last_output(body):
+ return text(next(m for m in reversed(body['messages']) if m.get('role') == 'tool'))
+
+
+def worker_id(body):
+ match = re.search(r'task_id ([a-f0-9]{32})', last_output(body))
+ assert match, 'missing retained task_id: ' + last_output(body)
+ return match[1]
+
+
+def wait_reply(body):
+ match = re.search(r'agent (\d+) started', last_output(body))
+ assert match, 'missing background handle: ' + last_output(body)
+ return tool('agent_output', id=int(match[1]), wait_ms=10000)
+
+
+def wait_file(path, needle):
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline:
+ try:
+ data = path.read_bytes()
+ except FileNotFoundError:
+ data = b''
+ if needle.encode() in data:
+ return data
+ time.sleep(.05)
+ raise AssertionError('checkpoint never persisted ' + needle)
+
+
+def checkpoint(root, ident, answer):
+ paths = list(root.glob('.graff/sessions/*/workers/' + ident + '.json'))
+ assert len(paths) == 1, (ident, paths)
+ data = wait_file(paths[0], answer)
+ record = json.loads(data)
+ assert record['id'] == ident and not record['pending'], record
+ assert answer in text(record['messages'])
+ return paths[0], data
+
+
+def unchanged(snapshot):
+ path, data = snapshot
+ assert path.read_bytes() == data, 'fork rewrote source checkpoint: ' + path.name
+
+
+def contains(body, *needles):
+ sent = text(body['messages'])
+ for needle in needles:
+ assert needle in sent, 'request lost ' + needle
+
+
+def excludes(body, *needles):
+ sent = text(body['messages'])
+ for needle in needles:
+ assert needle not in sent, 'request leaked ' + needle
+
+
+def native_evidence(body):
+ messages = body['messages']
+ calls = [c for m in messages for c in m.get('tool_calls', [])]
+ evidence = [c for c in calls if c['function']['name'] == 'bash'
+ and 'CURRENT_EVIDENCE' in c['function']['arguments']]
+ assert len(evidence) == 1, 'completed native call was not preserved'
+ assert any(m.get('role') == 'tool' and m.get('tool_call_id') == evidence[0]['id']
+ and 'CURRENT_EVIDENCE' in text(m.get('content')) for m in messages)
+ assert not any(c['function']['name'] == 'subagent' for c in calls), 'unfinished spawn copied'
+
+
+class ForkModel(ScriptedModel):
+ def __init__(self, root, saved, workflows):
+ super().__init__([])
+ self.root, self.saved, self.workflows = root, saved, workflows
+ self.route_lock = threading.Lock()
+ self.seen = {}
+ self.errors = []
+ self.finished = False
+ self.original_id = None
+ self.parent = self.sequence()
+ self.started = False
+
+ def next_reply(self, body):
+ super().next_reply(body)
+ # Do not classify against the first user: forked children inherit it.
+ latest = next((m for m in reversed(body.get('messages', []))
+ if m.get('role') == 'user'), {})
+ markers = re.findall(r'FORK_TASK:([A-Z0-9_]+)', text(latest.get('content', '')))
+ with self.route_lock:
+ try:
+ assert markers, 'request has no task marker'
+ # Lightweight workers prepend the parent's request as context.
+ name = markers[-1]
+ if name != 'ROOT':
+ self.seen.setdefault(name, []).append(body)
+ return {'text': 'ANSWER_' + name}
+ if not self.started:
+ self.started = True
+ return next(self.parent)
+ return self.parent.send(body)
+ except Exception:
+ self.errors.append(traceback.format_exc())
+ return {'text': 'FORK_FIXTURE_FAILED'}
+
+ def request_for(self, name):
+ requests = self.seen.get(name, [])
+ assert len(requests) == 1, (name, len(requests))
+ return requests[0]
+
+ def sequence(self):
+ body = yield tool('bash', command='printf CURRENT_EVIDENCE')
+ assert 'CURRENT_EVIDENCE' in last_output(body)
+ body = yield spawn('CURRENT', 'current')
+ contains(self.request_for('CURRENT'), 'FORK_TASK:ROOT', 'CURRENT_EVIDENCE')
+ native_evidence(self.request_for('CURRENT'))
+ assert 'ANSWER_CURRENT' in last_output(body)
+ # Background execution must still return an owned handle and durable id.
+ body = yield spawn('BACKGROUND', 'current', retained=True, background=True)
+ background_id = worker_id(body)
+ body = yield wait_reply(body)
+ assert 'ANSWER_BACKGROUND' in last_output(body)
+ background = checkpoint(self.root, background_id, 'ANSWER_BACKGROUND')
+ contains(self.request_for('BACKGROUND'), 'CURRENT_EVIDENCE')
+
+ body = yield spawn('SAVED', 'session:' + self.saved[0])
+ contains(self.request_for('SAVED'), 'FORK_TASK:SOURCE', 'ANSWER_SOURCE')
+ excludes(self.request_for('SAVED'), 'CURRENT_EVIDENCE', 'ANSWER_CURRENT')
+ unchanged(self.saved[1])
+ assert 'ANSWER_SAVED' in last_output(body)
+
+ body = yield spawn('ORIGINAL', retained=True)
+ self.original_id = worker_id(body)
+ contains(self.request_for('ORIGINAL'), 'FORK_TASK:ROOT')
+ excludes(self.request_for('ORIGINAL'), 'CURRENT_EVIDENCE', 'ANSWER_CURRENT',
+ 'ANSWER_BACKGROUND', 'ANSWER_SOURCE', 'ANSWER_SAVED')
+ original = checkpoint(self.root, self.original_id, 'ANSWER_ORIGINAL')
+ source = 'worker:' + self.original_id
+ branches = []
+ ids = {background_id, self.original_id}
+ for name, other in [('BRANCH_A', 'BRANCH_B'), ('BRANCH_B', 'BRANCH_A')]:
+ body = yield spawn(name, source, retained=True)
+ ident = worker_id(body)
+ assert ident not in ids, 'fork reused worker id'
+ ids.add(ident)
+ branches.append(checkpoint(self.root, ident, 'ANSWER_' + name))
+ contains(self.request_for(name), 'FORK_TASK:ORIGINAL', 'ANSWER_ORIGINAL')
+ excludes(self.request_for(name), 'ANSWER_' + other)
+ unchanged(original)
+
+ body = yield tool('subagent_resume', task_id=self.original_id,
+ message='FORK_TASK:RESUME Follow up on the original only.')
+ body = yield wait_reply(body)
+ assert 'ANSWER_RESUME' in last_output(body)
+ contains(self.request_for('RESUME'), 'ANSWER_ORIGINAL', 'FORK_TASK:RESUME')
+ excludes(self.request_for('RESUME'), 'ANSWER_BRANCH_A', 'ANSWER_BRANCH_B')
+ resumed = checkpoint(self.root, self.original_id, 'ANSWER_RESUME')
+ assert resumed[1] != original[1], 'resume did not update original'
+ for branch in branches:
+ unchanged(branch)
+
+ if self.workflows:
+ before = set(self.root.glob('.graff/sessions/*/workers/*.json'))
+ body = yield tool('workflow', fork_from=source, retained=True, phases=[
+ {'title': 'parallel', 'tasks': [
+ task('PHASE_A', 'Report the inventory of alpha.txt and beta.txt.'),
+ task('PHASE_B', 'Summarize the deployment configuration in gamma.txt.')]},
+ {'title': 'synthesis', 'tasks': [task('SYNTHESIS', '{{prev}}')]}])
+ assert 'ANSWER_SYNTHESIS' in last_output(body), last_output(body)
+ for name in ('PHASE_A', 'PHASE_B', 'SYNTHESIS'):
+ contains(self.request_for(name), 'ANSWER_ORIGINAL', 'ANSWER_RESUME')
+ excludes(self.request_for('PHASE_A'), 'ANSWER_PHASE_B')
+ excludes(self.request_for('PHASE_B'), 'ANSWER_PHASE_A')
+ contains(self.request_for('SYNTHESIS'), 'ANSWER_PHASE_A', 'ANSWER_PHASE_B')
+ self.workflow_records(before, ('PHASE_A', 'PHASE_B', 'SYNTHESIS'), ids)
+ unchanged(resumed)
+
+ before = set(self.root.glob('.graff/sessions/*/workers/*.json'))
+ body = yield tool('workflow', fork_from=source, retained=True, pipeline={
+ 'isolation': 'shared_cwd', 'items': ['ALPHA', 'BETA'], 'stages': [
+ task('PIPE_{{item}}_ONE'), task('PIPE_{{item}}_TWO', '{{prev}}')]})
+ for item, other in [('ALPHA', 'BETA'), ('BETA', 'ALPHA')]:
+ for stage in ('ONE', 'TWO'):
+ request = self.request_for('PIPE_' + item + '_' + stage)
+ contains(request, 'ANSWER_ORIGINAL', 'ANSWER_RESUME')
+ excludes(request, 'ANSWER_PIPE_' + other + '_ONE',
+ 'ANSWER_PIPE_' + other + '_TWO', 'ANSWER_SYNTHESIS')
+ contains(self.request_for('PIPE_' + item + '_TWO'), 'ANSWER_PIPE_' + item + '_ONE')
+ names = tuple('PIPE_' + item + '_' + stage
+ for item in ('ALPHA', 'BETA') for stage in ('ONE', 'TWO'))
+ self.workflow_records(before, names, ids)
+ unchanged(resumed)
+ for branch in branches:
+ unchanged(branch)
+ unchanged(background)
+ unchanged(self.saved[1])
+ self.finished = True
+ yield {'text': 'FORK_FIXTURE_DONE'}
+
+ def workflow_records(self, before, names, ids):
+ paths = set(self.root.glob('.graff/sessions/*/workers/*.json')) - before
+ assert len(paths) == len(names), ('workflow checkpoint count', len(paths), names)
+ found = set()
+ for path in paths:
+ record = json.loads(path.read_bytes())
+ assert record['id'] not in ids and not record['pending']
+ ids.add(record['id'])
+ # Match the final assistant answer, not inherited task text or {{prev}}.
+ final = next(m for m in reversed(record['messages']) if m.get('role') == 'assistant')
+ matches = [name for name in names if 'ANSWER_' + name in text(final)]
+ assert len(matches) == 1, final
+ found.add(matches[0])
+ assert 'ANSWER_ORIGINAL' in text(record['messages'])
+ assert found == set(names), (found, names)
+
+
+def acp_turn(binary, root, home, port, prompt):
+ client = Acp(binary, root, home, port, extra_env=LOCAL_NETWORK_ENV)
+ try:
+ response = client.request('initialize', {'protocolVersion': 1})
+ assert 'result' in response, response
+ sid = client.request('session/new', {'cwd': str(root), 'mcpServers': []})['result']['sessionId']
+ response = client.request('session/prompt', {'sessionId': sid,
+ 'prompt': [{'type': 'text', 'text': prompt}]}, timeout=120)
+ assert response.get('result', {}).get('stopReason') == 'end_turn', response
+ return sid
+ finally:
+ client.close()
+
+
+def legacy_turn(binary, root, home, port, prompt):
+ env = {k: v for k, v in os.environ.items()
+ if not k.endswith('_API_KEY') and not k.startswith(('GRAFF_', 'HARNESS_'))}
+ env.update(HOME=str(home), AI_GATEWAY_API_KEY='local', GRAFF_FLEET='off',
+ GRAFF_VERCEL_URL=f'http://127.0.0.1:{port}/v1/chat/completions',
+ GRAFF_NO_TELEMETRY='1', GRAFF_BEHAVIOR_UPLOAD='off',
+ GRAFF_NO_SMOLIFY='1', NO_COLOR='1')
+ env.update(LOCAL_NETWORK_ENV)
+ done = subprocess.run([str(binary), '--json', '--yolo', '--old', '--no-lean', '--model', 'vercel'],
+ cwd=root, env=env, input=json.dumps({'type': 'user', 'text': prompt}) + '\n',
+ text=True, capture_output=True, timeout=120)
+ assert done.returncode == 0, (done.stdout[-4000:], done.stderr[-2000:])
+
+
+class ForeignModel(ScriptedModel):
+ """A different parent must not fork a known id from another worker family."""
+ def __init__(self, ident):
+ super().__init__([spawn('FORBIDDEN', 'worker:' + ident), {'text': 'OWNERSHIP_DONE'}])
+
+ def check(self):
+ assert len(self.requests) == 2, 'foreign worker reached inference'
+ result = last_output(self.requests[1])
+ assert 'ANSWER_ORIGINAL' not in result
+ # Another family resolves a different checkpoint path. Generic errors
+ # (unknown tool, malformed arguments, exhausted budget) are not evidence
+ # that ownership was enforced.
+ assert any(code in result for code in ('FileNotFound', 'WorkerOwnershipMismatch')), result
+
+
+def check(binary, surface):
+ with tempfile.TemporaryDirectory(prefix='graff-subagent-fork-') as temporary:
+ root = Path(temporary).resolve()
+ home = root / 'home'
+ home.mkdir()
+ # Real independent fixture inputs admit a fleet through the normal R2 gate.
+ for name in ('alpha.txt', 'beta.txt', 'gamma.txt'):
+ (root / name).write_text('Synthetic fork fixture evidence.\n')
+ source_model = ScriptedModel([{'text': 'ANSWER_SOURCE'}])
+ port = source_model.start(0)
+ try:
+ sid = acp_turn(binary, root, home, port, 'FORK_TASK:SOURCE Preserve this evidence.')
+ path = root / '.graff/sessions' / (sid + '.session.json')
+ saved = (sid, (path, wait_file(path, 'ANSWER_SOURCE')))
+ finally:
+ source_model.stop()
+ runner = acp_turn if surface == 'acp' else legacy_turn
+ model = ForkModel(root, saved, workflows=surface == 'acp')
+ port = model.start(0)
+ try:
+ runner(binary, root, home, port, 'FORK_TASK:ROOT Execute the supplied fork fixture tools.')
+ assert not model.errors, model.errors
+ assert model.finished, 'parent did not complete the assertions'
+ # Ephemeral current/saved forks must not accidentally retain checkpoints.
+ records = list(root.glob('.graff/sessions/*/workers/*.json'))
+ assert len(records) == (11 if surface == 'acp' else 4), len(records)
+ snapshots = [(p, p.read_bytes()) for p in records]
+ finally:
+ model.stop()
+ foreign = ForeignModel(model.original_id)
+ port = foreign.start(0)
+ try:
+ runner(binary, root, home, port, 'FORK_TASK:FOREIGN Try the supplied foreign worker fork.')
+ foreign.check()
+ for snapshot in snapshots:
+ unchanged(snapshot)
+ unchanged(saved[1])
+ finally:
+ foreign.stop()
+ print('PASS ' + surface + ': fork requests, owned background worker, immutable sources, original resume'
+ + (', retained phase/pipeline fan-out' if surface == 'acp' else ''))
+
+
+if __name__ == '__main__':
+ binary = Path(sys.argv[1] if len(sys.argv) > 1 else REPO / 'zig-out/bin/graff').resolve()
+ for surface in ('acp', 'json'):
+ check(binary, surface)
diff --git a/src/main.zig b/src/main.zig
index a1c7d159..82dfc016 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -592,7 +592,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("goal_pacing.zig");
_ = .{ @import("presence_accord.zig"), @import("peer_idle.zig"), @import("acp_idle.zig"), @import("presence_chan.zig"), @import("presence_record.zig"), @import("daddy.zig"), @import("peer_inbox_content_test.zig"), @import("peer_inbox_failure_test.zig"), @import("peer_inbox_storage_test.zig"), @import("peer_inbox_sequence_test.zig"), @import("peer_inbox_snapshot_test.zig") };
_ = .{ @import("acp_agents.zig"), @import("repo_context_tests.zig") };
- _ = .{ @import("subagent_activity.zig"), @import("subagent_interactive.zig"), @import("subagent_recovery.zig"), @import("subagent_retained.zig"), @import("subagent_run_tests.zig") };
+ _ = .{ @import("subagent_activity.zig"), @import("subagent_interactive.zig"), @import("subagent_recovery.zig"), @import("subagent_retained.zig"), @import("subagent_history.zig"), @import("subagent_history_copy.zig"), @import("subagent_history_tests.zig"), @import("subagent_run_tests.zig") };
_ = .{ @import("acp_agent_activity.zig"), @import("acp_subagent_live.zig"), @import("acp_line_writer.zig") };
_ = .{ @import("acp_replay.zig"), @import("python_version.zig"), @import("jev_auto.zig"), @import("background_wait.zig"), @import("gateway_compact_tests.zig") };
_ = @import("read_image.zig");
diff --git a/src/schema_agents.zig b/src/schema_agents.zig
index 7d48bebf..240531ec 100644
--- a/src/schema_agents.zig
+++ b/src/schema_agents.zig
@@ -3,9 +3,9 @@ const ToolSpec = @import("schema.zig").ToolSpec;
pub const subagent_spec = ToolSpec{
.name = "subagent",
- .desc = "Delegate a sidecar task; children have file, shell, codedb and skill tools, no parent context, and cannot spawn children. Brief once with context, prompt, established_facts, scope and deliverable. Keep critical-path work local; use disjoint write sets for parallel tasks. Do not set model without a user request or task-specific reason. agent selects a persona; system_prompt overrides it. retained=true preserves history and workspace for follow-up; otherwise the worker is ephemeral. Interactive calls run in background by default; run_in_background=false waits for the child's report on every surface. Headless calls wait by default. agent_message queues feedback without starting a turn; subagent_resume continues a completed worker. agent_output fetches background results; wait_ms>0 waits in headless mode. Do not poll.",
+ .desc = "Delegate a sidecar task; children have file, shell, codedb and skill tools and cannot spawn children. By default they get the user's request, not full history; fork_from explicitly copies a conversation. Brief once with context, prompt, established_facts, scope and deliverable. Keep critical-path work local; use disjoint write sets for parallel tasks. Do not set model without a user request or task-specific reason. agent selects a persona; system_prompt overrides it. retained=true preserves history and workspace for follow-up; otherwise the worker is ephemeral. Interactive calls run in background by default; run_in_background=false waits for the child's report on every surface. Headless calls wait by default. agent_message queues feedback without starting a turn; subagent_resume continues a completed worker. agent_output fetches background results; wait_ms>0 waits in headless mode. Do not poll.",
.schema =
- \\{"type": "object", "properties": {"description": {"type": "string", "description": "Short label for logs, 3-5 words"}, "prompt": {"type": "string", "description": "Numbered steps and search hints; the complete task. Optional context/established_facts/scope/deliverable render as headed sections around this"}, "context": {"type": "string", "description": "Optional: repo and hard constraints the child must not re-derive"}, "established_facts": {"type": "string", "description": "Optional: observed facts, paths, and line numbers the child must treat as given"}, "scope": {"type": "string", "description": "Optional: what not to touch or broaden into"}, "deliverable": {"type": "string", "description": "Optional: required report shape; default is files changed, verified, skipped, open questions"}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name) whose persona the child runs with"}, "system_prompt": {"type": "string", "description": "Optional: replace the child's system prompt with a custom one (overrides agent)"}, "model": {"type": "string", "description": "Optional: run THIS child on an exact model name available on the current provider (e.g. \"gpt-6-luna\"). Highest precedence — beats the persona's own pin and the session default. Ignored (spawn still runs on the session default, with a trace note) if the name is unknown, ambiguous, or not served by this provider — except that a logged-in flat-rate subscription serving the exact name honors it (sub-first routing; the login is the standing consent). For a portable 'cheapest seat' ask, tier is still the better lever."}, "tier": {"type": "string", "enum": ["frontier", "mid", "small"], "description": "Optional: run THIS child on a rung of the current provider's model ladder instead of an exact name — frontier (planner/judge class), mid (reviewers, implementers, researchers), small (mechanical transform/extract/label). Prefer this over model: it stays correct when the root model changes. If the provider has no ladder or no model at that rung, sub-first routing seats the child on a logged-in flat-rate subscription's rung when one exists (no login → the pin is ignored); model wins if both are given."}, "effort": {"type": "string", "enum": ["low", "medium", "high", "xhigh", "max", "none"], "description": "Optional: reasoning effort for THIS child — beats the persona's effort: frontmatter; unpinned children run at medium. An axis independent of model/tier: an effort-only override keeps the persona's model pin. none disables thinking only on supported binary-thinking routes and is rejected before child inference elsewhere. An off-vocabulary value is ignored with a trace note."}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: independent / fan-out children default to \"worktree\" (own branch + checkout; clean unchanged trees are removed unless retained=true; dirty or uniquely committed trees are kept + reported). Use \"shared_cwd\" only for same-branch collaboration (review + fix, a pipeline). isolation_fallback:true is the only way a failed git worktree add may share the caller tree."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up (not a git repo, git error), run in the shared working tree instead of failing the spawn. Default false (fails the spawn on setup failure)."}, "retained": {"type": "boolean", "description": "Optional: persist conversation and workspace for subagent_resume (default false)."}, "run_in_background": {"type": "boolean", "description": "Optional: true starts asynchronously and immediately returns an agent id; false explicitly waits for the child report on every surface. Defaults to true in interactive sessions and false in headless sessions. Do not poll; agent_output(wait_ms>0) blocks until it finishes. A spawn at the live concurrency cap is refused; do not spawn a child to clean up a finished worktree."}}, "required": ["description", "prompt"]}
+ \\{"type": "object", "properties": {"description": {"type": "string", "description": "Short label for logs, 3-5 words"}, "prompt": {"type": "string", "description": "Numbered steps and search hints; the complete task. Optional context/established_facts/scope/deliverable render as headed sections around this"}, "context": {"type": "string", "description": "Optional: repo and hard constraints the child must not re-derive"}, "established_facts": {"type": "string", "description": "Optional: observed facts, paths, and line numbers the child must treat as given"}, "scope": {"type": "string", "description": "Optional: what not to touch or broaden into"}, "deliverable": {"type": "string", "description": "Optional: required report shape; default is files changed, verified, skipped, open questions"}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name) whose persona the child runs with"}, "system_prompt": {"type": "string", "description": "Optional: replace the child's system prompt with a custom one (overrides agent)"}, "model": {"type": "string", "description": "Optional: run THIS child on an exact model name available on the current provider (e.g. \"gpt-6-luna\"). Highest precedence — beats the persona's own pin and the session default. Ignored (spawn still runs on the session default, with a trace note) if the name is unknown, ambiguous, or not served by this provider — except that a logged-in flat-rate subscription serving the exact name honors it (sub-first routing; the login is the standing consent). For a portable 'cheapest seat' ask, tier is still the better lever."}, "tier": {"type": "string", "enum": ["frontier", "mid", "small"], "description": "Optional: run THIS child on a rung of the current provider's model ladder instead of an exact name — frontier (planner/judge class), mid (reviewers, implementers, researchers), small (mechanical transform/extract/label). Prefer this over model: it stays correct when the root model changes. If the provider has no ladder or no model at that rung, sub-first routing seats the child on a logged-in flat-rate subscription's rung when one exists (no login → the pin is ignored); model wins if both are given."}, "effort": {"type": "string", "enum": ["low", "medium", "high", "xhigh", "max", "none"], "description": "Optional: reasoning effort for THIS child — beats the persona's effort: frontmatter; unpinned children run at medium. An axis independent of model/tier: an effort-only override keeps the persona's model pin. none disables thinking only on supported binary-thinking routes and is rejected before child inference elsewhere. An off-vocabulary value is ignored with a trace note."}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: independent / fan-out children default to \"worktree\" (own branch + checkout; clean unchanged trees are removed unless retained=true; dirty or uniquely committed trees are kept + reported). Use \"shared_cwd\" only for same-branch collaboration (review + fix, a pipeline). isolation_fallback:true is the only way a failed git worktree add may share the caller tree."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up (not a git repo, git error), run in the shared working tree instead of failing the spawn. Default false (fails the spawn on setup failure)."}, "fork_from": {"type": "string", "description": "Optional: fork conversation history from current, session:<project-local saved name>, or worker:<owned retained task_id>. Source stays unchanged. Child keeps its own tools, instructions and selected workspace. Cross-wire text/tool evidence transfers; opaque compaction requires the original model and images require the original wire. Use retained:true to continue the new child later."}, "retained": {"type": "boolean", "description": "Optional: persist conversation and workspace for subagent_resume (default false)."}, "run_in_background": {"type": "boolean", "description": "Optional: true starts asynchronously and immediately returns an agent id; false explicitly waits for the child report on every surface. Defaults to true in interactive sessions and false in headless sessions. Do not poll; agent_output(wait_ms>0) blocks until it finishes. A spawn at the live concurrency cap is refused; do not spawn a child to clean up a finished worktree."}}, "required": ["description", "prompt"]}
,
};
@@ -19,9 +19,9 @@ pub const agent_output_spec = ToolSpec{
pub const workflow_spec = ToolSpec{
.name = "workflow",
- .desc = "Run a workflow of parallel subagents (dynamic workflows as data). Two shapes. PHASES (fan-out + synthesis): phases run sequentially; tasks inside a phase run in parallel as isolated subagents with no shared context, so every prompt must be self-contained; from phase 2 on, {{prev}} in a task prompt is replaced with the labeled results of the previous phase (appended if omitted); a phase may carry `when` to run only if a substring appears in {{prev}} (conditional / early-exit). Returns the final phase results. Use for audits, multi-perspective review, parallel research. Tasks may carry their own system_prompt to run prompt variants side by side; when the fleet is on, a phase with 2+ variants is auto-scored by an LLM judge and each variant's fitness feeds back to the fleet (a tournament doubles as a DGM scoring round). PIPELINE (no barrier): pass {pipeline:{items,stages}} instead to map each item through the stages independently — item A can reach stage 3 while item B is still on stage 1; {{item}} is the item and {{prev}} is this item's previous-stage result. Use for per-item work like transform/verify each file. Optional top-level \"context\" (also settable on the pipeline object): one shared string prepended once, plus a blank line, to every task/stage prompt before {{prev}} substitution, so repo/task boilerplate is stated once instead of repeated in every task.",
+ .desc = "Run a workflow of parallel subagents (dynamic workflows as data). Two shapes. PHASES (fan-out + synthesis): phases run sequentially; tasks inside a phase run in parallel as isolated subagents. Optional fork_from gives each a private copy of current, session:<name>, or worker:<task_id> history; retained:true saves each worker for later continuation. Otherwise every prompt must be self-contained; from phase 2 on, {{prev}} in a task prompt is replaced with the labeled results of the previous phase (appended if omitted); a phase may carry `when` to run only if a substring appears in {{prev}} (conditional / early-exit). Returns the final phase results. Use for audits, multi-perspective review, parallel research. Tasks may carry their own system_prompt to run prompt variants side by side; when the fleet is on, a phase with 2+ variants is auto-scored by an LLM judge and each variant's fitness feeds back to the fleet (a tournament doubles as a DGM scoring round). PIPELINE (no barrier): pass {pipeline:{items,stages}} instead to map each item through the stages independently — item A can reach stage 3 while item B is still on stage 1; {{item}} is the item and {{prev}} is this item's previous-stage result. Use for per-item work like transform/verify each file. Optional top-level \"context\" (also settable on the pipeline object): one shared string prepended once, plus a blank line, to every task/stage prompt before {{prev}} substitution, so repo/task boilerplate is stated once instead of repeated in every task.",
.schema =
- \\{"type":"object","properties":{"phases":{"type":"array","description":"Fan-out + synthesis mode (barrier between phases).","items":{"type":"object","properties":{"title":{"type":"string","description":"Short phase label for logs"},"when":{"type":"string","description":"Optional (phase 2+): run this phase only if this substring appears (case-insensitive) in the previous phase's results \u2014 gate a synthesis/exit phase on a sentinel"},"tasks":{"type":"array","items":{"type":"object","properties":{"description":{"type":"string","description":"Short label, 3-5 words"},"prompt":{"type":"string","description":"Complete, self-contained task; may contain {{prev}}"},"agent":{"type":"string","description":"Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name)"},"system_prompt":{"type":"string","description":"Optional: replace this task's system prompt (overrides agent)"},"isolation":{"type":"string","enum":["shared_cwd","worktree"],"description":"Optional: fan-out tasks default to \"worktree\" (own branch + checkout). Use \"shared_cwd\" only when this task must share the same branch and files. isolation_fallback:true is the only way a failed git worktree add may share the caller tree."},"isolation_fallback":{"type":"boolean","description":"Optional: if isolation:\"worktree\" fails to set up, run in the shared working tree instead of failing this task. Default false."}},"required":["description","prompt"]}}},"required":["tasks"]}},"context":{"type":"string","description":"Optional: prepended once, plus a blank line, to every task prompt before {{prev}} substitution."},"pipeline":{"type":"object","description":"No-barrier mode: map each item through the stages independently.","properties":{"items":{"type":"array","items":{"type":"string"},"description":"Things to process, one independent chain each (e.g. file paths)"},"stages":{"type":"array","items":{"type":"object","properties":{"description":{"type":"string","description":"Short stage label"},"prompt":{"type":"string","description":"Self-contained; {{item}} = the item, {{prev}} = this item's previous-stage result"},"agent":{"type":"string","description":"Optional named agent type"},"system_prompt":{"type":"string","description":"Optional: replace this stage's system prompt"},"isolation":{"type":"string","enum":["shared_cwd","worktree"],"description":"Optional: pipeline stages default to \"shared_cwd\" so later stages see earlier edits. Stage 0 may set \"worktree\". isolation_fallback:true is the only way a failed git worktree add may share the caller tree."},"isolation_fallback":{"type":"boolean","description":"Optional: if isolation:\"worktree\" fails to set up, run in the shared working tree instead of failing this stage. Default false."}},"required":["description","prompt"]}},"context":{"type":"string","description":"Optional: prepended once, plus a blank line, to every stage prompt before {{item}}/{{prev}} substitution."},"isolation":{"type":"string","enum":["shared_cwd","worktree"],"description":"Create one worktree per item and reuse it across all stages; preserve changes and return the path/branch."}},"required":["items","stages"]},"isolation":{"type":"string","enum":["shared_cwd","worktree"],"description":"For phases, share one retained worktree across all dependent stages; results include its path and branch for explicit delivery. For pipeline isolation set this on pipeline instead."}}}
+ \\{"type":"object","properties":{"fork_from":{"type":"string","description":"Optional: snapshot current, session:<project-local saved name>, or worker:<owned retained task_id> once for all phase or pipeline workers. Source stays unchanged; each child owns its history, tools and workspace selection. Same rules as subagent.fork_from."},"retained":{"type":"boolean","description":"Optional: retain each phase/pipeline worker and workspace; reports include task_id for subagent_resume or further forks. Default false."},"phases":{"type":"array","description":"Fan-out + synthesis mode (barrier between phases).","items":{"type":"object","properties":{"title":{"type":"string","description":"Short phase label for logs"},"when":{"type":"string","description":"Optional (phase 2+): run this phase only if this substring appears (case-insensitive) in the previous phase's results \u2014 gate a synthesis/exit phase on a sentinel"},"tasks":{"type":"array","items":{"type":"object","properties":{"description":{"type":"string","description":"Short label, 3-5 words"},"prompt":{"type":"string","description":"Complete, self-contained task; may contain {{prev}}"},"agent":{"type":"string","description":"Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name)"},"system_prompt":{"type":"string","description":"Optional: replace this task's system prompt (overrides agent)"},"isolation":{"type":"string","enum":["shared_cwd","worktree"],"description":"Optional: fan-out tasks default to \"worktree\" (own branch + checkout). Use \"shared_cwd\" only when this task must share the same branch and files. isolation_fallback:true is the only way a failed git worktree add may share the caller tree."},"isolation_fallback":{"type":"boolean","description":"Optional: if isolation:\"worktree\" fails to set up, run in the shared working tree instead of failing this task. Default false."}},"required":["description","prompt"]}}},"required":["tasks"]}},"context":{"type":"string","description":"Optional: prepended once, plus a blank line, to every task prompt before {{prev}} substitution."},"pipeline":{"type":"object","description":"No-barrier mode: map each item through the stages independently.","properties":{"items":{"type":"array","items":{"type":"string"},"description":"Things to process, one independent chain each (e.g. file paths)"},"stages":{"type":"array","items":{"type":"object","properties":{"description":{"type":"string","description":"Short stage label"},"prompt":{"type":"string","description":"Self-contained; {{item}} = the item, {{prev}} = this item's previous-stage result"},"agent":{"type":"string","description":"Optional named agent type"},"system_prompt":{"type":"string","description":"Optional: replace this stage's system prompt"},"isolation":{"type":"string","enum":["shared_cwd","worktree"],"description":"Optional: pipeline stages default to \"shared_cwd\" so later stages see earlier edits. Stage 0 may set \"worktree\". isolation_fallback:true is the only way a failed git worktree add may share the caller tree."},"isolation_fallback":{"type":"boolean","description":"Optional: if isolation:\"worktree\" fails to set up, run in the shared working tree instead of failing this stage. Default false."}},"required":["description","prompt"]}},"context":{"type":"string","description":"Optional: prepended once, plus a blank line, to every stage prompt before {{item}}/{{prev}} substitution."},"isolation":{"type":"string","enum":["shared_cwd","worktree"],"description":"Create one worktree per item and reuse it across all stages; preserve changes and return the path/branch."}},"required":["items","stages"]},"isolation":{"type":"string","enum":["shared_cwd","worktree"],"description":"For phases, share one retained worktree across all dependent stages; results include its path and branch for explicit delivery. For pipeline isolation set this on pipeline instead."}}}
,
};
diff --git a/src/subagent.zig b/src/subagent.zig
index 5ca02b1c..eb3f7941 100644
--- a/src/subagent.zig
+++ b/src/subagent.zig
@@ -75,7 +75,10 @@ pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {
if (ask.blocked) return .{ .text = try vision_ask.blockMessage(ctx.gpa, ask), .is_error = true };
// ADR 0232: the child sees the user's request and runs at its parent's effort unless pinned.
const effort = @import("subagent_fork.zig").effort(ctx.parent_effort, ask.pin.effort, ask.pin.provider orelse base);
+ var source_arena = std.heap.ArenaAllocator.init(ctx.gpa);
+ defer source_arena.deinit();
var forked = ctx;
+ forked.fork_source = @import("subagent_history.zig").fromInput(ctx, input, source_arena.allocator()) catch |err| return failure(ctx.gpa, err);
forked.parent_task = try @import("subagent_fork.zig").task(ctx.gpa, ctx.parent_messages);
defer ctx.gpa.free(forked.parent_task);
const keep = tools.json_args.flag(input, "retained");
@@ -253,9 +256,11 @@ pub fn agentJobPump(job: *AgentJob, gpa: Allocator, io: Io) void {
job.done = true;
const retained_state = job.ctx.retained_worker;
job.ctx.retained_worker = null; // completed jobs retain reports, not full conversation arenas
+ job.ctx.fork_source = null;
g_agent_jobs.active -= 1;
g_agent_jobs.mutex.unlock(io);
if (retained_state) |state| state.deinit(gpa, io);
+ if (job.owned) |owned| owned.releaseHistory();
ledger.finish(gpa, io, job.id, job.is_error, job.result, job.usage);
admitNext(gpa, io);
}
@@ -347,7 +352,7 @@ pub fn agentJobsReap(gpa: Allocator, io: Io) void {
job.feedback.deinit(gpa);
if (job.ctx.retained_worker) |state| state.deinit(gpa, io);
if (job.owned) |owned| {
- owned.arena.deinit();
+ owned.deinit();
gpa.destroy(owned);
}
gpa.free(job.label);
@@ -367,7 +372,7 @@ pub fn workflowTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_ove
// `seat` is the PHASE's one model (route_phase.forPhase, resolved once and
// handed to every task alike), never a per-task pin: the variants still
// share one configuration (#290). The effort axis stays unpinned.
- const run = runSub(ctx, "workflow_task", label, prompt, sys_override, niche, isolation, isolation_fallback, seat, null) catch |err| return failure(ctx.gpa, err);
+ const run = runWorkflow(ctx, "workflow_task", label, prompt, sys_override, niche, isolation, isolation_fallback, seat) catch |err| return failure(ctx.gpa, err);
return run.output;
}
@@ -375,10 +380,15 @@ pub fn workflowTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_ove
/// the same invocation-wide atomic ceiling and concurrency limiter.
pub fn workflowRetryTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool, seat: ?Provider) ToolOutput {
// The SAME phase seat: a retry that changed model would break uniformity.
- const run = runSub(ctx, "workflow_retry", label, prompt, sys_override, niche, isolation, isolation_fallback, seat, null) catch |err| return failure(ctx.gpa, err);
+ const run = runWorkflow(ctx, "workflow_retry", label, prompt, sys_override, niche, isolation, isolation_fallback, seat) catch |err| return failure(ctx.gpa, err);
return run.output;
}
+pub fn runWorkflow(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const u8, system: ?[]const u8, niche: []const u8, isolation: Isolation, fallback: bool, seat: ?Provider) !SubRun {
+ if (ctx.retain_children) return @import("subagent_resume.zig").foregroundKind(ctx, kind, label, prompt, system, niche, isolation, fallback, seat, null);
+ return runSub(ctx, kind, label, prompt, system, niche, isolation, fallback, seat, null);
+}
+
/// The --judge LLM-as-judge run (see runEval in main): an isolated subagent
/// scores the work against the rubric and ends with a `score:` line. Mirrors
/// workflowTask — a thin runSub wrapper — so the eval handler can io.async it
diff --git a/src/subagent_history.zig b/src/subagent_history.zig
new file mode 100644
index 00000000..e6697c4c
--- /dev/null
+++ b/src/subagent_history.zig
@@ -0,0 +1,102 @@
+//! Explicit conversation snapshots for fresh workers. Never restore root runtime state.
+const std = @import("std");
+const tools = @import("tools.zig");
+const Provider = @import("provider.zig").Provider;
+const retained = @import("subagent_retained.zig");
+const session = @import("session.zig");
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+pub const Snapshot = struct {
+ messages: []const Value,
+ provider: []const u8,
+ model: []const u8,
+ protocol: Provider.Kind,
+ read_only: bool = false,
+ text_only: bool = false,
+ deadline_ms: ?i64 = null,
+
+ pub fn clone(self: Snapshot, a: Allocator) !Snapshot {
+ var result = self;
+ const bytes = try std.json.Stringify.valueAlloc(a, self.messages, .{});
+ defer a.free(bytes);
+ result.messages = (try std.json.parseFromSliceLeaky(Value, a, bytes, .{ .allocate = .alloc_always })).array.items;
+ result.provider = try a.dupe(u8, self.provider);
+ result.model = try a.dupe(u8, self.model);
+ return result;
+ }
+
+ pub fn seed(self: Snapshot, agent: *@import("agent.zig").Agent) !void {
+ const source: Provider = .{ .id = self.provider, .model = self.model, .kind = self.protocol, .auth = .bearer, .url = "", .api_key = "", .context = 0 };
+ agent.messages = try @import("subagent_history_copy.zig").copy(agent.arena, self.messages, source, agent.provider);
+ if (agent.messages.items.len == 0) return error.NothingToFork;
+ agent.compaction_window = try @import("compaction_window.zig").State.restore(agent.arena, .empty, agent.messages.items);
+ agent.read_only = agent.read_only or self.read_only;
+ agent.text_only = agent.text_only or self.text_only;
+ if (self.deadline_ms) |deadline| agent.loop_deadline_ms = if (agent.loop_deadline_ms) |current| @min(current, deadline) else deadline;
+ }
+};
+
+/// Resolve only explicit project-local names and family-owned worker ids.
+/// No source credentials, approvals, cwd, goals, or live handles are adopted.
+pub fn fromInput(ctx: tools.ToolCtx, input: Value, a: Allocator) !?Snapshot {
+ if (input != .object) return error.InvalidForkSource;
+ const value = input.object.get("fork_from") orelse return null;
+ if (value != .string or value.string.len == 0) return error.InvalidForkSource;
+ if (ctx.from_sub) return error.OnlyParentCanFork;
+ const source = value.string;
+ if (std.mem.eql(u8, source, "current")) {
+ if (ctx.parent_messages.len == 0) return error.NothingToFork;
+ return try (Snapshot{
+ .messages = ctx.parent_messages,
+ .provider = ctx.provider.id,
+ .model = ctx.provider.model,
+ .protocol = ctx.provider.kind,
+ .read_only = ctx.read_only_shell,
+ .deadline_ms = ctx.loop_deadline_ms,
+ }).clone(a);
+ }
+ if (std.mem.startsWith(u8, source, "worker:")) {
+ const state = try retained.load(ctx, source["worker:".len..]);
+ defer state.deinit(ctx.gpa, ctx.io);
+ const record = state.record;
+ if (!retained.budgetAllowed(record, ctx)) return error.RetainedWorkerBudgetUnavailable;
+ if (record.messages.len == 0) return error.NothingToFork;
+ return try (Snapshot{
+ .messages = record.messages,
+ .provider = record.provider,
+ .model = record.model,
+ .protocol = record.protocol orelse protocol(record.provider, record.model),
+ .read_only = record.read_only,
+ .text_only = record.text_only,
+ .deadline_ms = record.deadline_ms,
+ }).clone(a);
+ }
+ if (!std.mem.startsWith(u8, source, "session:")) return error.InvalidForkSource;
+ const name = source["session:".len..];
+ if (!session.validSessionName(name)) return error.InvalidSessionName;
+ session.flushSaves();
+ const relative = try session.sessionPath(a, name);
+ const path = if (ctx.agent_cwd) |cwd| try std.fs.path.join(a, &.{ cwd, relative }) else relative;
+ const data = try std.Io.Dir.cwd().readFileAlloc(ctx.io, path, a, .limited(@import("session_index.zig").max_session_bytes));
+ const saved = try std.json.parseFromSliceLeaky(Value, a, data, .{ .allocate = .alloc_always });
+ if (saved != .object) return error.BadSession;
+ const history = saved.object.get("messages") orelse return error.BadSession;
+ if (history != .array) return error.BadSession;
+ if (history.array.items.len == 0) return error.NothingToFork;
+ const provider = tools.strField(saved, "provider") orelse return error.BadSession;
+ const model = tools.strField(saved, "model") orelse return error.BadSession;
+ // Imported saves contain Anthropic-shaped historical receipts regardless of route metadata.
+ const imported = tools.strField(saved, "imported_from") orelse "";
+ return .{
+ .messages = history.array.items,
+ .provider = provider,
+ .model = model,
+ .protocol = if (std.mem.eql(u8, imported, "claude")) .anthropic else protocol(provider, model),
+ };
+}
+
+fn protocol(id: []const u8, model: []const u8) Provider.Kind {
+ const base: Provider = .{ .id = id, .model = model, .kind = .openai, .auth = .bearer, .url = "", .api_key = "", .context = 0 };
+ return base.withModel(model).kind;
+}
diff --git a/src/subagent_history_copy.zig b/src/subagent_history_copy.zig
new file mode 100644
index 00000000..d4f7e827
--- /dev/null
+++ b/src/subagent_history_copy.zig
@@ -0,0 +1,216 @@
+//! Copy conversation evidence, not the source agent's instructions or capabilities.
+const std = @import("std");
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+const Provider = @import("provider.zig").Provider;
+const messages = @import("messages.zig");
+
+fn str(v: Value, key: []const u8) []const u8 {
+ if (v != .object) return "";
+ const field = v.object.get(key) orelse return "";
+ return if (field == .string) field.string else "";
+}
+fn is(v: Value, key: []const u8, text: []const u8) bool {
+ return std.mem.eql(u8, str(v, key), text);
+}
+fn parentOnly(v: Value) bool {
+ return is(v, "role", "system") or is(v, "role", "developer") or
+ @import("additional_tools.zig").isItem(v) or @import("hot_context.zig").isHotContext(v);
+}
+fn track(a: Allocator, pending: *std.StringHashMapUnmanaged(usize), v: Value, index: usize) !void {
+ if (v != .object) return;
+ if (is(v, "type", "function_call")) {
+ const id = if (str(v, "call_id").len > 0) str(v, "call_id") else str(v, "id");
+ if (id.len > 0) try pending.put(a, id, index);
+ } else if (is(v, "type", "tool_use")) {
+ const id = str(v, "id");
+ if (id.len > 0) try pending.put(a, id, index);
+ } else if (is(v, "type", "function_call_output") or is(v, "type", "function_result")) {
+ _ = pending.remove(str(v, "call_id"));
+ } else if (is(v, "type", "tool_result")) {
+ _ = pending.remove(str(v, "tool_use_id"));
+ } else if (is(v, "role", "tool")) {
+ _ = pending.remove(str(v, "tool_call_id"));
+ }
+ if (v.object.get("tool_calls")) |calls| if (calls == .array) {
+ for (calls.array.items) |call| {
+ const id = str(call, "id");
+ if (id.len > 0) try pending.put(a, id, index);
+ }
+ };
+ if (v.object.get("content")) |content| if (content == .array) {
+ for (content.array.items) |block| try track(a, pending, block, index);
+ };
+}
+
+/// The parent's spawn call is still in flight. Stop before that model/tool
+/// batch rather than inventing a successful result or giving a child a dangling call.
+fn completedPrefix(a: Allocator, history: []const Value) ![]const Value {
+ var pending: std.StringHashMapUnmanaged(usize) = .empty;
+ defer pending.deinit(a);
+ for (history, 0..) |item, i| try track(a, &pending, item, i);
+ var end = history.len;
+ var it = pending.valueIterator();
+ while (it.next()) |index| end = @min(end, index.*);
+ if (end < history.len) {
+ while (end > 0) {
+ const prev = history[end - 1];
+ if (!is(prev, "role", "assistant") and !is(prev, "type", "reasoning") and
+ !is(prev, "type", "thought") and !is(prev, "type", "function_call") and !is(prev, "type", "model_output")) break;
+ end -= 1;
+ }
+ }
+ return history[0..end];
+}
+
+fn privateReasoning(v: Value) bool {
+ return is(v, "type", "reasoning") or is(v, "type", "thinking") or
+ is(v, "type", "redacted_thinking") or is(v, "type", "thought");
+}
+fn stripReasoning(a: Allocator, v: *Value) !void {
+ if (v.* != .object) return;
+ _ = v.object.fetchOrderedRemove("reasoning_content");
+ _ = v.object.fetchOrderedRemove("reasoning");
+ if (v.object.getPtr("content")) |content| if (content.* == .array) {
+ var blocks = std.json.Array.init(a);
+ for (content.array.items) |block| if (!privateReasoning(block)) {
+ try blocks.append(block);
+ };
+ content.* = .{ .array = blocks };
+ };
+}
+fn hasImage(v: Value) bool {
+ if (v == .array) {
+ for (v.array.items) |item| if (hasImage(item)) return true;
+ } else if (v == .object) {
+ if (is(v, "type", "image") or is(v, "type", "image_url") or is(v, "type", "input_image")) return true;
+ for (v.object.values()) |item| if (hasImage(item)) return true;
+ }
+ return false;
+}
+
+pub fn copy(a: Allocator, history: []const Value, source: Provider, target: Provider) !std.json.Array {
+ const same_seat = std.mem.eql(u8, source.id, target.id) and std.mem.eql(u8, source.model, target.model);
+ if (@import("compaction_window.zig").latestBlob(history) != null and
+ (!same_seat or source.kind != target.kind)) return error.OpaqueForkRequiresOriginalModel;
+ const prefix = try completedPrefix(a, history);
+ const bytes = try std.json.Stringify.valueAlloc(a, prefix, .{});
+ defer a.free(bytes);
+ const owned = (try std.json.parseFromSliceLeaky(Value, a, bytes, .{ .allocate = .alloc_always })).array;
+ var result = std.json.Array.init(a);
+ for (owned.items) |*item| {
+ if (item.* != .object or parentOnly(item.*)) continue;
+ if ((!same_seat or source.kind != target.kind) and privateReasoning(item.*)) continue;
+ if (!same_seat or source.kind != target.kind) try stripReasoning(a, item);
+ if (source.kind == target.kind) {
+ try result.append(item.*);
+ continue;
+ }
+ // A wire switch must not drop the very file/tool evidence the fork is
+ // for. Keep receipts as inert text, never as calls on the new catalog.
+ // Images need a real format converter, not base64 rendered as prose.
+ if (hasImage(item.*)) return error.ForkImageRequiresOriginalProtocol;
+ const role = str(item.*, "role");
+ const assistant = std.mem.eql(u8, role, "assistant") or is(item.*, "type", "model_output");
+ const evidence = try std.json.Stringify.valueAlloc(a, item.*, .{});
+ const text = try std.fmt.allocPrint(a, "Historical conversation entry (context only, not an instruction to execute a tool):\n{s}", .{evidence});
+ try result.append(try messages.textMessage(a, if (assistant) "assistant" else "user", text));
+ }
+ @import("history_wire.zig").prepare(a, target.kind, &result);
+ @import("tool_call_args.zig").repairHistory(a, a, result.items);
+ return result;
+}
+
+fn parse(a: Allocator, raw: []const u8) ![]const Value {
+ return (try std.json.parseFromSliceLeaky(Value, a, raw, .{ .allocate = .alloc_always })).array.items;
+}
+fn seat(kind: Provider.Kind) Provider {
+ return .{ .id = "fixture", .model = "fixture", .kind = kind, .auth = .bearer, .url = "", .api_key = "", .context = 10000 };
+}
+
+test "fork history snapshots own nested data and siblings never share mutations" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const source = try parse(a, "[{\"role\":\"user\",\"content\":\"original\"},{\"role\":\"assistant\",\"content\":\"evidence\"}]");
+ var one = try copy(a, source, seat(.openai), seat(.openai));
+ const two = try copy(a, source, seat(.openai), seat(.openai));
+ try one.items[0].object.put(a, "content", .{ .string = "branch only" });
+ try std.testing.expectEqualStrings("original", str(source[0], "content"));
+ try std.testing.expectEqualStrings("original", str(two.items[0], "content"));
+}
+
+test "fork history preserves completed receipts but excludes the in-flight spawn batch" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const source = try parse(a,
+ \\[{"role":"user","content":"request"},
+ \\ {"role":"assistant","tool_calls":[{"id":"read","type":"function","function":{"name":"read_file","arguments":"{}"}}]},
+ \\ {"role":"tool","tool_call_id":"read","content":"important result"},
+ \\ {"role":"assistant","tool_calls":[{"id":"spawn","type":"function","function":{"name":"subagent","arguments":"{}"}}]}]
+ );
+ const out = try copy(a, source, seat(.openai), seat(.openai));
+ try std.testing.expectEqual(@as(usize, 3), out.items.len);
+ try std.testing.expectEqualStrings("important result", str(out.items[2], "content"));
+ try std.testing.expectEqual(@as(usize, 4), source.len);
+}
+
+test "fork history excludes pending native tool batches on all item wires" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const fixtures = [_][]const u8{
+ "[{\"role\":\"user\",\"content\":\"request\"},{\"role\":\"assistant\",\"content\":[{\"type\":\"tool_use\",\"id\":\"x\",\"name\":\"subagent\",\"input\":{}}]}]",
+ "[{\"role\":\"user\",\"content\":\"request\"},{\"type\":\"reasoning\",\"id\":\"r\"},{\"type\":\"function_call\",\"call_id\":\"x\",\"name\":\"subagent\",\"arguments\":\"{}\"}]",
+ "[{\"type\":\"user_input\",\"content\":\"request\"},{\"type\":\"function_call\",\"id\":\"x\",\"name\":\"subagent\",\"arguments\":{}}]",
+ };
+ for (fixtures, [_]Provider.Kind{ .anthropic, .responses, .interactions }) |fixture, kind| {
+ const out = try copy(a, try parse(a, fixture), seat(kind), seat(kind));
+ try std.testing.expectEqual(@as(usize, 1), out.items.len);
+ }
+}
+
+test "fork history cross-wire keeps tool evidence as inert context" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const source = try parse(a, "[{\"role\":\"assistant\",\"content\":[{\"type\":\"tool_use\",\"id\":\"read\",\"name\":\"read_file\",\"input\":{\"path\":\"evidence.txt\"}}]},{\"role\":\"user\",\"content\":[{\"type\":\"tool_result\",\"tool_use_id\":\"read\",\"content\":\"evidence survives\"}]}]");
+ const out = try copy(a, source, seat(.anthropic), seat(.openai));
+ try std.testing.expectEqual(@as(usize, 2), out.items.len);
+ try std.testing.expect(std.mem.indexOf(u8, str(out.items[1], "content"), "evidence survives") != null);
+ try std.testing.expect(out.items[0].object.get("tool_calls") == null);
+}
+
+test "fork history preserves opaque windows only on the original model" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const source = try parse(a, "[{\"type\":\"compaction\",\"encrypted_content\":\"opaque\"},{\"role\":\"user\",\"content\":\"continue\"}]");
+ const out = try copy(a, source, seat(.responses), seat(.responses));
+ try std.testing.expect(@import("compaction_window.zig").latestBlob(out.items) != null);
+ var other = seat(.responses);
+ other.model = "different";
+ try std.testing.expectError(error.OpaqueForkRequiresOriginalModel, copy(a, source, seat(.responses), other));
+ try std.testing.expectError(error.OpaqueForkRequiresOriginalModel, copy(a, source, seat(.responses), seat(.openai)));
+}
+
+test "fork history keeps native images and rejects a lossy wire switch" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const source = try parse(a, "[{\"role\":\"user\",\"content\":[{\"type\":\"image\",\"source\":{\"type\":\"base64\",\"data\":\"AA==\"}}]}]");
+ const out = try copy(a, source, seat(.anthropic), seat(.anthropic));
+ try std.testing.expect(hasImage(out.items[0]));
+ try std.testing.expectError(error.ForkImageRequiresOriginalProtocol, copy(a, source, seat(.anthropic), seat(.openai)));
+}
+
+test "fork history does not grant the source agent tools or instructions" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const source = try parse(a, "[{\"role\":\"system\",\"content\":\"root policy\"},{\"type\":\"additional_tools\",\"role\":\"developer\"},{\"role\":\"user\",\"content\":\"actual request\"}]");
+ const out = try copy(a, source, seat(.openai), seat(.openai));
+ try std.testing.expectEqual(@as(usize, 1), out.items.len);
+ try std.testing.expectEqualStrings("actual request", str(out.items[0], "content"));
+}
diff --git a/src/subagent_history_tests.zig b/src/subagent_history_tests.zig
new file mode 100644
index 00000000..5f7aea92
--- /dev/null
+++ b/src/subagent_history_tests.zig
@@ -0,0 +1,125 @@
+const std = @import("std");
+const Io = std.Io;
+const tools = @import("tools.zig");
+const history = @import("subagent_history.zig");
+const retained = @import("subagent_retained.zig");
+const Value = std.json.Value;
+
+fn context() tools.ToolCtx {
+ return .{ .gpa = std.testing.allocator, .io = std.testing.io, .client = undefined, .provider = .{ .id = "fixture", .model = "fixture", .kind = .openai, .auth = .bearer, .url = "", .api_key = "NOT_HISTORY", .context = 10000 }, .registry = null, .from_sub = false, .approvals = null, .tracer = null, .worker_family = "fork-family" };
+}
+fn input(a: std.mem.Allocator, source: []const u8) !Value {
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(a, "fork_from", .{ .string = source });
+ return .{ .object = obj };
+}
+fn messages(a: std.mem.Allocator) ![]Value {
+ return (try std.json.parseFromSliceLeaky(Value, a, "[{\"role\":\"user\",\"content\":\"saved evidence\"}]", .{})).array.items;
+}
+
+test "fork history source is opt-in and rejects arbitrary paths and nested children" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var ctx = context();
+ try std.testing.expect(try history.fromInput(ctx, .{ .object = .empty }, a) == null);
+ try std.testing.expectError(error.InvalidForkSource, history.fromInput(ctx, try input(a, "other.json"), a));
+ try std.testing.expectError(error.InvalidSessionName, history.fromInput(ctx, try input(a, "session:../other"), a));
+ try std.testing.expectError(error.NothingToFork, history.fromInput(ctx, try input(a, "current"), a));
+ ctx.from_sub = true;
+ try std.testing.expectError(error.OnlyParentCanFork, history.fromInput(ctx, try input(a, "current"), a));
+}
+
+test "fork history detached context owns its snapshot after the parent turn ends" {
+ var source = std.heap.ArenaAllocator.init(std.testing.allocator);
+ var owned = @import("subagent_owned.zig").Owned.init(std.testing.allocator);
+ defer owned.deinit();
+ var ctx = context();
+ ctx.parent_messages = try messages(source.allocator());
+ ctx.fork_source = try history.fromInput(ctx, try input(source.allocator(), "current"), source.allocator());
+ const detached = try owned.context(ctx);
+ source.deinit();
+ try std.testing.expectEqual(@as(usize, 0), detached.parent_messages.len);
+ const snapshot = detached.fork_source.?;
+ try std.testing.expectEqualStrings("saved evidence", snapshot.messages[0].object.get("content").?.string);
+ const serialized = try std.json.Stringify.valueAlloc(owned.arena.allocator(), snapshot, .{});
+ try std.testing.expect(std.mem.indexOf(u8, serialized, "NOT_HISTORY") == null);
+ owned.releaseHistory();
+ try std.testing.expect(owned.history == null);
+}
+
+test "fork history reads a project-local session without adopting credentials or rewriting it" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.createDirPath(std.testing.io, ".graff/sessions");
+ const raw = "{\"provider\":\"fixture\",\"model\":\"fixture\",\"api_key\":\"NOT_HISTORY\",\"messages\":[{\"role\":\"user\",\"content\":\"saved evidence\"}]}";
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = ".graff/sessions/source.session.json", .data = raw });
+ var ctx = context();
+ ctx.agent_cwd = try tmp.dir.realPathFileAlloc(ctx.io, ".", a);
+ const snapshot = (try history.fromInput(ctx, try input(a, "session:source"), a)).?;
+ const serialized = try std.json.Stringify.valueAlloc(a, snapshot, .{});
+ try std.testing.expect(std.mem.indexOf(u8, serialized, "saved evidence") != null);
+ try std.testing.expect(std.mem.indexOf(u8, serialized, "NOT_HISTORY") == null);
+ try std.testing.expectEqualStrings(raw, try tmp.dir.readFileAlloc(ctx.io, ".graff/sessions/source.session.json", a, .unlimited));
+ try std.testing.expectError(error.FileNotFound, history.fromInput(ctx, try input(a, "session:missing"), a));
+}
+
+test "fork history worker snapshot preserves restrictions ownership and original bytes" {
+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest;
+ const io = std.testing.io;
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var original = try Io.Dir.cwd().openDir(io, ".", .{});
+ defer original.close(io);
+ defer _ = std.posix.system.fchdir(original.handle);
+ if (std.posix.system.fchdir(tmp.dir.handle) != 0) return error.ChdirFailed;
+ var ctx = context();
+ const state = try retained.create(ctx, "source");
+ defer state.deinit(ctx.gpa, io);
+ state.record.provider = "fixture";
+ state.record.model = "fixture";
+ state.record.protocol = .openai;
+ state.record.messages = try messages(a);
+ state.record.read_only = true;
+ state.record.text_only = true;
+ state.record.deadline_ms = @import("util.zig").unixMs(io) + 60000;
+ try retained.enqueue(state, "queued only for source");
+ try retained.write(io, state);
+ state.release(io);
+ const source = try std.fmt.allocPrint(a, "worker:{s}", .{state.record.id});
+ const before = try Io.Dir.cwd().readFileAlloc(io, state.path, a, .unlimited);
+ const snapshot = (try history.fromInput(ctx, try input(a, source), a)).?;
+ try std.testing.expect(snapshot.read_only and snapshot.text_only);
+ try std.testing.expectEqual(state.record.deadline_ms, snapshot.deadline_ms);
+ try std.testing.expectEqual(@as(usize, 1), snapshot.messages.len);
+ try std.testing.expectEqualStrings(before, try Io.Dir.cwd().readFileAlloc(io, state.path, a, .unlimited));
+ ctx.worker_family = "foreign-family";
+ try std.testing.expectError(error.FileNotFound, history.fromInput(ctx, try input(a, source), a));
+ ctx.worker_family = "fork-family";
+ state.record.finite_budget = true;
+ try retained.write(io, state);
+ try std.testing.expectError(error.RetainedWorkerBudgetUnavailable, history.fromInput(ctx, try input(a, source), a));
+ state.record.finite_budget = false;
+ state.record.deadline_ms = 1;
+ try retained.write(io, state);
+ try std.testing.expectError(error.RetainedWorkerBudgetUnavailable, history.fromInput(ctx, try input(a, source), a));
+}
+
+test "fork history seeding cannot relax worker restrictions or deadlines" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const ctx = context();
+ var agent: @import("agent.zig").Agent = .{ .gpa = ctx.gpa, .arena = a, .io = ctx.io, .client = undefined, .provider = ctx.provider, .messages = std.json.Array.init(a), .sub = true, .label = "fork", .out = null, .loop_deadline_ms = 5 };
+ const snapshot: history.Snapshot = .{ .messages = try messages(a), .provider = "fixture", .model = "fixture", .protocol = .openai, .read_only = true, .text_only = true, .deadline_ms = 10 };
+ try snapshot.seed(&agent);
+ try std.testing.expect(agent.read_only and agent.text_only);
+ try std.testing.expectEqual(@as(?i64, 5), agent.loop_deadline_ms);
+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
+}
diff --git a/src/subagent_owned.zig b/src/subagent_owned.zig
index cba314a6..26543b13 100644
--- a/src/subagent_owned.zig
+++ b/src/subagent_owned.zig
@@ -7,12 +7,23 @@ const Approvals = @import("approvals.zig").Approvals;
pub const Owned = struct {
arena: std.heap.ArenaAllocator,
+ history: ?std.heap.ArenaAllocator = null,
approvals: Approvals = .{},
pub fn init(gpa: std.mem.Allocator) Owned {
return .{ .arena = .init(gpa) };
}
+ pub fn releaseHistory(self: *Owned) void {
+ if (self.history) |*arena| arena.deinit();
+ self.history = null;
+ }
+
+ pub fn deinit(self: *Owned) void {
+ self.releaseHistory();
+ self.arena.deinit();
+ }
+
pub fn provider(self: *Owned, source: Provider) !Provider {
var copy = source;
inline for (.{ "id", "url", "api_key", "model", "account" }) |field|
@@ -33,6 +44,10 @@ pub const Owned = struct {
copy.parent_tool_call_id = try a.dupe(u8, source.parent_tool_call_id);
copy.parent_task = try a.dupe(u8, source.parent_task);
copy.parent_messages = &.{}; // the caller's history moves on once this call returns
+ if (source.fork_source) |snapshot| {
+ self.history = .init(source.gpa);
+ copy.fork_source = try snapshot.clone(self.history.?.allocator());
+ }
if (source.worker_id) |id| copy.worker_id = try a.dupe(u8, id);
if (source.approvals) |ap| {
ap.mutex.lockUncancelable(source.io);
diff --git a/src/subagent_resume.zig b/src/subagent_resume.zig
index a68caf92..37daa397 100644
--- a/src/subagent_resume.zig
+++ b/src/subagent_resume.zig
@@ -8,11 +8,15 @@ const Isolation = @import("fleet.zig").Isolation;
const Effort = @import("main.zig").ReasoningEffort;
pub fn foreground(ctx: tools.ToolCtx, label: []const u8, prompt: []const u8, system: ?[]const u8, niche: []const u8, isolation: Isolation, fallback: bool, pin: ?Provider, effort: ?Effort) !subagent.SubRun {
+ return foregroundKind(ctx, "subagent", label, prompt, system, niche, isolation, fallback, pin, effort);
+}
+
+pub fn foregroundKind(ctx: tools.ToolCtx, kind: []const u8, label: []const u8, prompt: []const u8, system: ?[]const u8, niche: []const u8, isolation: Isolation, fallback: bool, pin: ?Provider, effort: ?Effort) !subagent.SubRun {
const state = try retained.create(ctx, label);
defer state.deinit(ctx.gpa, ctx.io);
var child = ctx;
child.retained_worker = state;
- var run = try subagent.runSub(child, "subagent", label, prompt, system, niche, isolation, fallback, pin, effort);
+ var run = try subagent.runSub(child, kind, label, prompt, system, niche, isolation, fallback, pin, effort);
errdefer ctx.gpa.free(run.output.text);
const text = try std.fmt.allocPrint(ctx.gpa, "{s}\n\n[task_id {s}: retained worker; agent_message queues, subagent_resume continues]", .{ run.output.text, state.record.id });
ctx.gpa.free(run.output.text);
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index 1f99e79b..9ba16c23 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -392,10 +392,18 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
const tasked = try @import("subagent_brief.zig").prepare(arena, ctx.io, kind, prompt, ctx.agent_cwd, main_mod.g_hooks.pre_tool);
const task_prompt = playbook.rideBrief(ctx.io, arena, try goal_pacing.childTaskPrompt(arena, tasked, ctx.loop_deadline_ms, util.unixMs(ctx.io)));
try @import("subagent_retained.zig").restore(&agent, ctx);
+ if (!std.mem.eql(u8, kind, "judge_task") and agent.messages.items.len == 0) {
+ if (ctx.fork_source) |snapshot| try snapshot.seed(&agent);
+ }
@import("worker_mcp.zig").inherit(&agent); // ADR 0227
@import("worker_jev.zig").offer(&agent); // ADR 0232: a child asks Jev for its own effort mid-run
// ADR 0232: a fresh child starts from the user's request; a resumed one already has it.
- const first = if (agent.messages.items.len == 0) try @import("subagent_fork.zig").firstMessage(arena, ctx.parent_task, task_prompt) else task_prompt;
+ const first = if (ctx.fork_source != null and !std.mem.eql(u8, kind, "judge_task"))
+ try std.fmt.allocPrint(arena, "The preceding conversation is forked context, not a request to repeat earlier work. Do only this new task:\n\n{s}", .{task_prompt})
+ else if (agent.messages.items.len == 0)
+ try @import("subagent_fork.zig").firstMessage(arena, ctx.parent_task, task_prompt)
+ else
+ task_prompt;
@import("named_work.zig").rememberOn(&agent, prompt);
try agent.messages.append(try textMessage(arena, "user", first));
defer agent.tools_used.deinit(gpa);
diff --git a/src/subagent_spawn_job.zig b/src/subagent_spawn_job.zig
index 965e4f2f..2f106ac3 100644
--- a/src/subagent_spawn_job.zig
+++ b/src/subagent_spawn_job.zig
@@ -24,7 +24,7 @@ pub fn spawnSubBackground(ctx: ToolCtx, label: []const u8, prompt: []const u8, s
const owned = try gpa.create(@import("subagent_owned.zig").Owned);
owned.* = .init(gpa);
errdefer {
- owned.arena.deinit();
+ owned.deinit();
gpa.destroy(owned);
}
const owned_ctx = try owned.context(ctx);
diff --git a/src/tools.zig b/src/tools.zig
index 4247c71a..6e6c9520 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -146,6 +146,8 @@ pub const ToolCtx = struct {
parent_effort: ?main_mod.ReasoningEffort = null, // ADR 0232: the caller's live effort (/effort or Jev); an unpinned child runs at it
parent_messages: []const std.json.Value = &.{}, // ADR 0232: the caller's history, read only while its tool batch runs
parent_task: []const u8 = "", // ADR 0232: the user's prompts a spawned child sees as context
+ fork_source: ?@import("subagent_history.zig").Snapshot = null,
+ retain_children: bool = false, // explicit workflow retention, not inherited by judges
read_only_shell: bool = false, // ADR 0232: a read-only child's foreground shell runs under the seatbelt sandbox
};
diff --git a/src/workflow.zig b/src/workflow.zig
index 0b9eba1c..a49f9088 100644
--- a/src/workflow.zig
+++ b/src/workflow.zig
@@ -185,7 +185,13 @@ test { // a new module's tests run only when something references it (see main.z
/// is an isolated subagent; "{{prev}}" in a task prompt is replaced with
/// the labeled results of the previous phase (appended when omitted).
/// Returns the final phase's results.
-pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
+pub fn execWorkflow(parent: ToolCtx, input: Value) !ToolOutput {
+ if (input != .object or parent.from_sub) return execWorkflowShared(parent, input);
+ var arena = std.heap.ArenaAllocator.init(parent.gpa);
+ defer arena.deinit();
+ var ctx = parent;
+ ctx.fork_source = @import("subagent_history.zig").fromInput(ctx, input, arena.allocator()) catch |err| return tools.failure(ctx.gpa, err);
+ ctx.retain_children = tools.json_args.flag(input, "retained");
if (ctx.from_sub or tools.strField(input, "isolation") == null or !std.mem.eql(u8, tools.strField(input, "isolation").?, "worktree")) return execWorkflowShared(ctx, input);
// Pipeline owns one scope per item, never one tree shared by parallel items.
if (tools.json_args.object(input)) |obj| if (obj.contains("pipeline")) return .{ .text = try ctx.gpa.dupe(u8, "Set isolation:worktree on pipeline, not on its outer workflow object."), .is_error = true };
diff --git a/src/workflow_pipeline.zig b/src/workflow_pipeline.zig
index 9bc91861..5fe751e2 100644
--- a/src/workflow_pipeline.zig
+++ b/src/workflow_pipeline.zig
@@ -28,7 +28,7 @@ const ToolOutput = tools.ToolOutput;
const failure = tools.failure;
const subagent = @import("subagent.zig");
-const runSub = subagent.runSub;
+const runWorkflow = subagent.runWorkflow;
const subagent_run = @import("subagent_run.zig");
const failureAllowsRetry = subagent_run.failureAllowsRetry;
@@ -131,7 +131,7 @@ fn pipelineChainShared(ctx: ToolCtx, item: []const u8, stages: []const StageSpec
// Counters only — the fitness fold happens per STAGE after run()'s
// join (#296), never here where it would be a per-item row (#290).
stat.noteAttempt();
- var out = if (runSub(ctx, "workflow_task", st.label, prompt, st.override, st.niche, .shared_cwd, st.isolation_fallback, st.seat.pin, null)) |r| r.output else |e| failure(gpa, e);
+ var out = if (runWorkflow(ctx, "workflow_task", st.label, prompt, st.override, st.niche, .shared_cwd, st.isolation_fallback, st.seat.pin)) |r| r.output else |e| failure(gpa, e);
if (out.is_error) {
// Only spend the one retry (#2) when the harness's own
// classification hasn't already ruled it out (auth, invalid
@@ -141,7 +141,7 @@ fn pipelineChainShared(ctx: ToolCtx, item: []const u8, stages: []const StageSpec
gpa.free(out.text);
// The SAME seat: a retry that changed model would break the
// stage uniformity the fitness row attributes to.
- out = if (runSub(ctx, "workflow_retry", st.label, prompt, st.override, st.niche, .shared_cwd, st.isolation_fallback, st.seat.pin, null)) |r| r.output else |e| failure(gpa, e);
+ out = if (runWorkflow(ctx, "workflow_retry", st.label, prompt, st.override, st.niche, .shared_cwd, st.isolation_fallback, st.seat.pin)) |r| r.output else |e| failure(gpa, e);
}
if (out.is_error) {
// #248 — excerpt the stage's own error BEFORE freeing it, so
diff --git a/src/workflow_workspace.zig b/src/workflow_workspace.zig
index ee942a4b..19b38541 100644
--- a/src/workflow_workspace.zig
+++ b/src/workflow_workspace.zig
@@ -9,12 +9,13 @@ pub const Scope = struct {
io: std.Io,
tree: worktree.AgentWorktree,
finished: bool = false,
+ retained: bool = false,
pub fn init(ctx: tools.ToolCtx) !Scope {
var arena = std.heap.ArenaAllocator.init(ctx.gpa);
errdefer arena.deinit();
const tree = try worktree.agentWorktreeCreateAt(ctx.gpa, ctx.io, arena.allocator(), "workflow", ctx.agent_cwd orelse ".");
- return .{ .arena = arena, .gpa = ctx.gpa, .io = ctx.io, .tree = tree };
+ return .{ .arena = arena, .gpa = ctx.gpa, .io = ctx.io, .tree = tree, .retained = ctx.retain_children };
}
pub fn context(self: *const Scope, parent: tools.ToolCtx) tools.ToolCtx {
@@ -24,6 +25,14 @@ pub const Scope = struct {
}
pub fn finish(self: *Scope, out: tools.ToolOutput) !tools.ToolOutput {
+ if (self.retained) {
+ self.finished = true;
+ defer self.gpa.free(out.text);
+ return .{
+ .text = try std.fmt.allocPrint(self.gpa, "{s}\n\n[workflow workspace retained for worker continuation — path: {s}, branch: {s}]", .{ out.text, self.tree.path, self.tree.branch }),
+ .is_error = out.is_error,
+ };
+ }
const outcome = worktree.agentWorktreeFinish(self.gpa, self.io, self.tree);
self.finished = true;
if (!outcome.kept) return out;
@@ -35,7 +44,7 @@ pub const Scope = struct {
}
pub fn deinit(self: *Scope) void {
- if (!self.finished) _ = worktree.agentWorktreeFinish(self.gpa, self.io, self.tree);
+ if (!self.finished and !self.retained) _ = worktree.agentWorktreeFinish(self.gpa, self.io, self.tree);
self.arena.deinit();
}
};