graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: tighten runtime and PR verification for v0.0.297
Rach Pradhan109e73517256
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 97834222..f16a7bcb 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -69,6 +69,11 @@ jobs:- name: zig build testrun: zig build test --summary all+ - name: Publication, handoff, deferred MCP and legacy listener regressions+ run: |+ command -v lsof || (sudo apt-get update && sudo apt-get install -y lsof)+ python3 scripts/regression-release-297.py+- name: Local learning lifecycle and security regressionrun: python3 tests/learn_e2e.py --graff zig-out/bin/graffdiff --git a/docs/adr/0035-first-turn-skips-deferred-mcp-join.md b/docs/adr/0035-first-turn-skips-deferred-mcp-join.mdindex b9f05e4b..3752d304 100644--- a/docs/adr/0035-first-turn-skips-deferred-mcp-join.md+++ b/docs/adr/0035-first-turn-skips-deferred-mcp-join.md@@ -2,6 +2,8 @@Status: accepted 2026-08-26+Later-request joining is updated by [ADR 0104](0104-live-publication-and-deferred-tool-evidence.md): only finished handshakes join before a model request.+## ContextInteractive `--yolo` (including `graff acp`) starts MCP handshakes in thediff --git a/docs/adr/0104-live-publication-and-deferred-tool-evidence.md b/docs/adr/0104-live-publication-and-deferred-tool-evidence.mdnew file mode 100644index 00000000..35a36247--- /dev/null+++ b/docs/adr/0104-live-publication-and-deferred-tool-evidence.md@@ -0,0 +1,47 @@+# 0104. Refresh evidence at the action boundary++Status: accepted 2026-09-11++## Context++The first version of ADR 0035 still joined every pending MCP handshake on the+second request. ADR 0100's publication evidence could be cached across commits,+and an unavailable lookup was indistinguishable from a valid empty run list.+Artifact claims were read once and rewritten without an interprocess lock.++## Decision++Only completed MCP tasks join at request boundaries. A task publishes a stable+atomic completion flag after handshake cleanup; only then does the request+thread consume its future. Explicit inspection and teardown retain blocking+joins. This updates ADR 0035 without changing first-request catalog policy.++PR publication inspects fresh evidence, with unknown distinct from no runs.+The literal command parser separates flags from quoted body content and reads+body files. Explicit remote heads do not inherit local HEAD evidence. A+publication arms a durable obligation keyed to the existing saved conversation+UUID, so renaming, compaction, and resume cannot satisfy it. Completion reads+current remote head/check data and compares the local head where applicable.+Draft handoff is labelled unverified. It cannot record verified task success.+This extends ADR 0100; a prose review remains heuristic, not proof of coverage.++Claims use a stable lock inode, bounded contention retry, fresh reads, and+atomic data replacement. Failed storage does not report a successful handoff.+The common bash executor repeats the check after earlier permission checks.+The coordination scope is the workspace ledger; this is not a universal shell+sandbox or a cross-workspace ownership database.++Clipboard extraction reads actual AppKit pasteboard types using the system+JavaScript runtime. Synthetic named boards exercise the production extraction+path without reading or modifying the user's general clipboard. The helper+creates no windows and does not activate another application.++## Consequences and verification++The offline release regression runs two independent harness processes to prove+handoff revocation and receiver access. An unfinished MCP handshake is released+only by the second native tool, proving the model request did not wait for it.+The same run streams citation arguments byte by byte. GitHub CLI fixtures check+failed/pending/unavailable evidence, fresh heads, draft handoff, repeated+completion, and resume. Native pasteboard regressions cover raster, PDF, file+URL, invalid, text, and empty inputs. No provider calls are required.diff --git a/docs/adr/0105-explicit-legacy-listener-stop.md b/docs/adr/0105-explicit-legacy-listener-stop.mdnew file mode 100644index 00000000..bc857f00--- /dev/null+++ b/docs/adr/0105-explicit-legacy-listener-stop.md@@ -0,0 +1,31 @@+# 0105. Explicitly stop a selected legacy listener snapshot++Status: accepted 2026-09-11++## Context++ADR 0098 correctly refused to treat inherited environment variables as stop+authority. That left users unable to clean up pre-registry listeners through+the server command even after inspecting them.++## Decision++Keep discovery and automatic cleanup conservative. Add a separate explicit+`servers stop-suspect <pid> <identity-token>` action. Listing offers a token only+when start identity, executable metadata, and dedicated group leadership can+be observed. Stopping rediscovers a same-user orphan listener and requires the+current snapshot to match the token. The signal path rechecks start identity,+executable metadata, and group eligibility before TERM and KILL. Missing or+changed evidence refuses the signal. No ownership record is created.++This adds user-selected stop authority to ADR 0098. It does not infer ownership+from environment hints. A token is a stale-target check, not a credential.++## Consequences++Users can explicitly clean up a discovered legacy listener without weakening+automatic cleanup. Unsupported platforms or opaque processes remain read-only.+The native regression creates its own orphaned listener, verifies an invalid+token leaves it serving, then uses the displayed token and verifies its socket+closes. Port preflight remains a best-effort cross-family observation rather+than a socket reservation.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 8e6721b5..db8f8579 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -114,6 +114,8 @@ record only when you need the evidence or the edge cases.| [0101](0101-gui-tests-preserve-desktop-focus.md) | GUI tests stay hidden by default; visible opt-in can overlap other apps, and native foreground checks require separate opt-in. || [0102](0102-workspace-agents-and-cancel-recovery.md) | Agents uses the workspace area, Tasks visibility is explicit and persisted, and timed-out cancellation retires the worker before session recovery. || [0103](0103-mcp-apps-are-isolated-result-views.md) | MCP Apps are private saved result views in isolated GUI/browser sandboxes; app tool calls require a future approval path. |+| [0104](0104-live-publication-and-deferred-tool-evidence.md) | Requests merge only ready MCP tasks; publication and completion use fresh head evidence; claim transactions serialize handoffs. |+| [0105](0105-explicit-legacy-listener-stop.md) | Only an explicit identity-bound stop-suspect action may terminate an unrecorded legacy listener; automatic cleanup stays conservative. |## When to write onediff --git a/docs/releases/v0.0.297.md b/docs/releases/v0.0.297.mdnew file mode 100644index 00000000..847108a1--- /dev/null+++ b/docs/releases/v0.0.297.md@@ -0,0 +1,35 @@+# Codegraff v0.0.297++This update improves tool responsiveness, clipboard image pasting, PR verification, and coordination between sessions.++## Tools keep moving while MCP connects++A slow MCP handshake no longer holds up the second model request. Finished connections become available on later requests while native tools continue running. Explicit MCP inspection and shutdown can still wait for pending connections. (#860)++## Cleaner completion text++Search citation control markers are removed from streamed completion text, including markers split across response chunks. Surrounding text and ordinary Unicode remain intact. (#819)++## More reliable image pasting on macOS++Clipboard images are read directly through AppKit instead of relying on PNG coercion. PNG, TIFF, JPEG, PDF, and copied image files are exported to a temporary PNG. Conversion and access failures are distinguished from a clipboard with no image. Reads are bounded, and a clipboard change during extraction gets one retry. (#843)++## PR publication and completion checks++Non-draft publication gathers fresh head evidence for each attempt. Failed lookups, malformed responses, and incomplete check data remain unresolved. Body files are read for verification text; quoted text cannot masquerade as a draft flag. An explicitly selected remote head is checked separately from the current local checkout. (#847)++Publishing a PR creates a verification obligation that survives session saves and resumes. Completing todos or repeating `attempt_completion` cannot replace passing checks on the current PR head. Unpushed local changes cannot borrow the previous head's passing CI. A draft can be handed off with an explicit unverified label. (#853)++These checks apply to recognized GitHub CLI commands issued through the harness. Dynamic or compound publication commands must be separated into literal commands. CI results verify check outcomes; the wording review remains a heuristic and does not prove every behavioral claim in a PR description. Fork-qualified heads that cannot be resolved remain draft-only.++## Durable peer handoffs++Claim changes are serialized and written atomically. Each check reloads the current ledger, so a handoff enables the receiver and revokes the previous owner's publication access. Bash rechecks claims at its execution boundary, including RLM calls. Independent branch claims remain separate when the command target can be resolved. Unknown process identity does not expire ownership. (#840)++Claims coordinate sessions sharing a workspace ledger. They are not a general lock against commands run outside the harness, and ambiguous command targets are checked conservatively.++## Legacy server cleanup and port checks++`servers list` identifies suspected orphan listeners and, where their identity can be verified, shows an explicit `stop-suspect` command. Its token binds the selected process start and executable. The stop path rechecks identity and group membership before signalling, including escalation. Suspects are never silently adopted or automatically stopped. (#817)++Port preflight checks cover IPv4 and IPv6 listeners on the same numeric port. The check cannot reserve the socket or eliminate a later bind race, and unsupported shell launch forms remain outside its coverage. Automatic cleanup preserves listening servers when browser visibility is unknown.diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex 09121b07..45cf941e 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -75,3 +75,5 @@{"id": "list-dir-near-miss-hint", "why": "ADR 0093: a misspelled list_dir path should name the closest sibling while retaining error status.", "prompt": "what is in the demo-server folder", "workspace_seed": {"demos-servers/README.md": "# runbook\n"}, "script": [{"tool": "codedb", "arguments": {"command": "list_dir demo-server"}}, {"text": "the folder is demos-servers"}], "assert": [{"event": {"type": "tool_result", "name": "codedb", "is_error": true}}, {"request_contains": {"index": 1, "text": "was not found. Closest match: demos-servers/."}}, {"final_text_contains": "demos-servers"}]}{"id": "subagent-activity-isolated-sink", "why": "Frontendless workers must publish their streamed progress, tool identity and final report to a separate bounded activity feed without emitting child prose as parent text.", "workspace_seed": {"example.txt": "fixture content\n", "check_activity.py": "import json, pathlib\nsnapshots = [json.loads(p.read_text()) for p in pathlib.Path('.graff/live').glob('activity-*/*.json')]\nassert len(snapshots) == 1, len(snapshots)\ns = snapshots[0]\nassert s['agent']['status'] == 'completed', s['agent']\nassert s['response'] == 'Child review complete.', s['response']\nassert any(e['type'] == 'text' and 'Child is inspecting.' in e['text'] for e in s['events']), s['events']\nassert any(e['type'] == 'tool_call' and e['name'] == 'read_file' and e['text'] == 'example.txt' and e['input_key'] == 'path' for e in s['events']), s['events']\nassert any(e['type'] == 'tool_result' and 'fixture content' in e['text'] for e in s['events']), s['events']\nassert not any('Parent has finished.' in e['text'] for e in s['events'])\nprint('child-activity-verified')\n"}, "prompt": "Use one subagent to inspect example.txt, then verify its activity feed with check_activity.py.", "script": [{"tool": "subagent", "arguments": {"description": "Inspect example", "prompt": "Read example.txt and report your findings."}}, {"text": "Child is inspecting.", "tool": "read_file", "arguments": {"path": "example.txt"}}, {"text": "Child review complete."}, {"tool": "bash", "arguments": {"command": "python3 check_activity.py"}}, {"text": "Parent has finished."}], "assert": [{"event": {"type": "tool_result", "name": "bash", "text": "child-activity-verified\n"}}, {"events_at_most": {"match": {"type": "text", "text": "Child is inspecting."}, "count": 0}}, {"final_text_contains": "Parent has finished."}]}{"id":"opaque-compaction-is-not-success-804","why":"An unsupported local fallback must report that opaque history needs server compaction, not emit successful zero-work compaction or discard the preserved context.","args":["--resume","compact-fixture"],"workspace_seed":{".graff/sessions/compact-fixture.session.json":"{\"provider\":\"lmstudio\",\"model\":\"mock\",\"messages\":[{\"type\":\"compaction\",\"encrypted_content\":\"opaque-fixture-804\"},{\"role\":\"user\",\"content\":\"retained-context-804\"}]}"},"controls_before_prompt":[{"type":"compact"}],"prompt":"Continue using the retained context.","script":[{"text":"Retained context is available."}],"assert":[{"event":{"type":"error","message":"compaction failed: ServerCompactionRequired"}},{"events_at_most":{"match":{"type":"compact","ok":true},"count":0}},{"request_contains":{"index":0,"text":"retained-context-804"}},{"request_contains":{"index":0,"text":"opaque-fixture-804"}},{"final_text_contains":"Retained context is available."}]}+{"id": "completion-search-citations-clean", "why": "#819: the authoritative completion must remove search citation control spans while preserving human prose; the release regression also covers byte-fragmented line output.", "args": ["--old"], "prompt": "Return the scripted final result.", "script": [{"tool": "attempt_completion", "arguments": {"result": "Read the docsciteturn0search0turn1search2 today."}, "argument_chunk_size": 1}], "assert": [{"final_text_contains": "Read the docs today."}]}+{"id": "publication-unresolved-command-refused", "why": "#847: a non-literal publication command cannot bypass head/body inspection by chaining checks before creation. No GitHub write or lookup should execute.", "args": ["--old"], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Exercise the scripted prepublication refusal.", "script": [{"tool": "bash", "arguments": {"command": "gh pr checks --watch && gh pr create --title fixture --body '## Verification: local passed'"}}, {"text": "The publication was blocked."}], "assert": [{"event": {"type": "tool_result", "name": "bash", "is_error": true}}, {"request_contains": {"text": "separate literal gh pr command"}}, {"final_text_contains": "The publication was blocked."}]}diff --git a/scripts/eval/mock_model.py b/scripts/eval/mock_model.pyindex 6381b891..6fe1895c 100644--- a/scripts/eval/mock_model.py+++ b/scripts/eval/mock_model.py@@ -113,12 +113,16 @@ class ScriptedModel:if message["content"]:deltas.append({"role": "assistant", "content": message["content"]})for position, call in enumerate(message.get("tool_calls", [])):- deltas.append({"tool_calls": [{- "index": position,- "id": call["id"],- "type": "function",- "function": call["function"],- }]})+ function = call["function"]+ size = reply.get("argument_chunk_size", 0)+ arguments = function["arguments"]+ fragments = [arguments[i:i + size] for i in range(0, len(arguments), size)] if size else [arguments]+ for number, fragment in enumerate(fragments):+ fn = {"arguments": fragment}+ if number == 0: fn["name"] = function["name"]+ deltas.append({"tool_calls": [{+ "index": position, "id": call["id"], "type": "function", "function": fn,+ }]})finish = "tool_calls" if "tool_calls" in message else "stop"for delta in deltas or [{"role": "assistant", "content": ""}]:self._chunk({"choices": [{"index": 0, "delta": delta, "finish_reason": None}]})diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 0ad0de9b..85af2bb6 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": 2190,+ "test_count_baseline": 2209,"test_count_slack": 25,"required_invariants": [{diff --git a/scripts/regression-release-297.py b/scripts/regression-release-297.pynew file mode 100644index 00000000..1a5d2565--- /dev/null+++ b/scripts/regression-release-297.py@@ -0,0 +1,281 @@+#!/usr/bin/env python3+"""Offline production-dispatch regressions for v0.0.297. Never contacts GitHub.++Uses an isolated home/repository, a scripted local model and an argv-recording+stub gh. Listener checks start and stop only this script's own process group.+"""+import argparse+import json+import concurrent.futures+import threading+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tempfile+import time++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "scripts" / "eval"))+from mock_model import ScriptedModel++GH = r'''+import json, pathlib, subprocess, sys+root=pathlib.Path(__file__).resolve().parent.parent+state=json.loads((root/'gh-state.json').read_text())+args=sys.argv[1:]+with (root/'gh-argv.jsonl').open('a') as f:f.write(json.dumps(args)+'\n')+head=subprocess.check_output(['GIT_EXE','rev-parse','HEAD'],cwd=root,text=True).strip()+if args[:2]==['run','list']:+ if state.get('unavailable'):sys.exit(1)+ sha=args[args.index('--commit')+1]+ status=state.get('runs','success') if sha==state['initial_head'] else state.get('new_runs','failure')+ if status=='malformed': print('invalid');sys.exit()+ if status=='none': print('[]');sys.exit()+ print(json.dumps([{'status':'queued' if status=='pending' else 'completed','conclusion':None if status=='pending' else status}]))+elif args[:1]==['api']:+ print(state.get('remote_head', head))+elif args[:2]==['pr','view']:+ remote=state.get('remote_head',head)+ status=state.get('checks','PENDING')+ checks=[] if status=='NONE' else [{'state':status}]+ print(json.dumps({'headRefOid':remote,'isDraft':state.get('draft',False),'body':'## Verification\nLocal tests passed.','statusCheckRollup':checks}))+elif args[:2] in (['pr','create'],['pr','ready']):+ with (root/'mutations.jsonl').open('a') as f:f.write(json.dumps(args)+'\n')+ if '--draft' in args:state['draft']=True+ if args[:2]==['pr','ready']:state['draft']=False+ (root/'gh-state.json').write_text(json.dumps(state))+ print('https://example.invalid/pull/1')+else: sys.exit(88)+'''+++def tool(command):+ return {"tool": "bash", "arguments": {"command": command}}+++def completion(text="Verification complete."):+ return {"tool": "attempt_completion", "arguments": {"result": text}}+++def run_case(graff, name, script, state=None, expected_mutations=0, refused=0, expected_final=None, resume_check=False):+ with tempfile.TemporaryDirectory(prefix="graff-297-") as temp:+ work = Path(temp)+ (work / "bin").mkdir()+ gh = work / "bin" / "gh"+ gh.write_text(f"#!{sys.executable}\n" + GH.replace("GIT_EXE", shutil.which("git")))+ gh.chmod(0o755)+ subprocess.run(["git", "init", "-q", "-b", "fixture"], cwd=work, check=True)+ subprocess.run(["git", "-c", "user.name=Fixture", "-c", "[email protected]", "commit", "-q", "--allow-empty", "-m", "fixture"], cwd=work, check=True)+ head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=work, text=True).strip()+ fixture = dict(initial_head=head, **(state or {}))+ if fixture.get("remote_head") == "initial": fixture["remote_head"] = head+ (work / "gh-state.json").write_text(json.dumps(fixture))+ (work / "notes.md").write_text("Fix the behavior.\n\n## Verification\nLocal regression passed.\n")+ env = {k: v for k, v in os.environ.items() if not k.endswith("_API_KEY")}+ env.update(HOME=temp, PATH=str(work / "bin") + os.pathsep + os.environ["PATH"],+ LMSTUDIO_API_KEY="local", GRAFF_NO_TELEMETRY="1", GRAFF_FLEET="off",+ GRAFF_NO_SMOLIFY="1", GRAFF_NO_CODEDB_GUARD="1", NO_COLOR="1")+ model = ScriptedModel(script)+ model.start(1234)+ try:+ done = subprocess.run([str(graff), "--json", "--yolo", "--old", "--model", "lmstudio"],+ cwd=work, env=env, text=True, capture_output=True, timeout=100,+ input=json.dumps({"type": "user", "text": "Run the scripted publication regression in this fixture repository."}) + "\n")+ assert done.returncode == 0, (name, done.stderr[-2000:])+ events = [json.loads(line) for line in done.stdout.splitlines() if line.startswith('{')]+ mutations = (work / "mutations.jsonl").read_text().splitlines() if (work / "mutations.jsonl").exists() else []+ assert len(mutations) == expected_mutations, (name, mutations, events)+ messages = json.dumps(model.requests)+ assert messages.count("completion deferred: current-head PR verification") >= refused, (name, messages[-8000:])+ if expected_final:+ assert any(expected_final in e.get("text", "") for e in events if e.get("type") == "turn"), (name, done.stdout[-4000:])+ assert any(e.get("type") == "tool_call_finished" and e.get("name") == "attempt_completion" and not e.get("is_error") for e in events), name+ if resume_check:+ sessions = list((work / ".graff/sessions").glob("*.session.json"))+ assert sessions, "fixture session was not persisted"+ saved = next((p for p in sessions if p.name != "last.session.json"), sessions[0])+ model.script.extend([completion("Resumed verification complete."), {"text": "CI is still pending after resume."}])+ resumed = subprocess.run([str(graff), "--json", "--yolo", "--old", "--model", "lmstudio", "--resume", saved.name.removesuffix(".session.json")],+ cwd=work, env=env, text=True, capture_output=True, timeout=100,+ input=json.dumps({"type": "user", "text": "Resume the PR task and check completion."}) + "\n")+ assert resumed.returncode == 0, resumed.stderr[-2000:]+ latest_tool = next(m for m in reversed(model.requests[-1]["messages"]) if m.get("role") == "tool")+ assert "completion deferred: current-head PR verification" in latest_tool["content"], latest_tool+ print(f"PASS {name}: {len(mutations)} publication(s), expected completion gate checked", flush=True)+ finally:+ model.stop()+++def stream_and_mcp(graff):+ with tempfile.TemporaryDirectory(prefix="graff-297-stream-") as temp:+ work = Path(temp)+ server = work / "slow_mcp.py"+ server.write_text("""import json, pathlib, sys, time+for line in sys.stdin:+ try: request=json.loads(line)+ except ValueError: continue+ if 'id' not in request: continue+ deadline=time.monotonic()+25+ while not pathlib.Path('second-native').exists() and time.monotonic()<deadline:time.sleep(.02)+ method=request.get('method')+ result={'protocolVersion':'2024-11-05','capabilities':{'tools':{}},'serverInfo':{'name':'fixture','version':'1'}} if method=='initialize' else {'tools':[]} if method=='tools/list' else {}+ print(json.dumps({'jsonrpc':'2.0','id':request['id'],'result':result}),flush=True)+""")+ (work / ".mcp.json").write_text(json.dumps({"mcpServers": {"withheld": {"command": sys.executable, "args": [str(server)]}}}))+ env = {k: v for k, v in os.environ.items() if not k.endswith("_API_KEY")}+ env.update(HOME=temp, LMSTUDIO_API_KEY="local", GRAFF_NO_TELEMETRY="1", GRAFF_FLEET="off",+ GRAFF_NO_SMOLIFY="1", GRAFF_NO_CODEDB_GUARD="1", GRAFF_MCP_PROBE="0", NO_COLOR="1")+ raw = "Read the docs\ue200cite\ue202turn0search0\ue202turn1search2\ue201 today."+ class TimedModel(ScriptedModel):+ def next_reply(self, body):+ self.times.append(time.monotonic())+ return super().next_reply(body)+ model = TimedModel([tool("printf first > first-native"), tool("printf second > second-native"),+ dict(completion(raw), argument_chunk_size=1)])+ model.times = []+ model.start(1234)+ try:+ done = subprocess.run([str(graff), "--yolo", "--old", "--model", "lmstudio", "-p", "Run the scripted native tool fixture."],+ cwd=work, env=env, text=True, capture_output=True, timeout=45)+ assert done.returncode == 0, done.stderr[-3000:]+ assert (work / "first-native").exists() and (work / "second-native").exists(), done.stderr[-3000:]+ assert model.times[1] - model.times[0] < 5, model.times+ output = done.stdout + done.stderr+ assert "Read the docs today." in output, output[-4000:]+ assert all(mark not in output for mark in ("\ue200", "\ue201", "\ue202", "turn0search0", "turn1search2")), output[-4000:]+ print("PASS deferred MCP: second native tool ran before handshake release; fragmented citations stripped", flush=True)+ finally:+ model.stop()+++def handoff(graff):+ with tempfile.TemporaryDirectory(prefix="graff-297-handoff-") as temp:+ work = Path(temp)+ (work / "bin").mkdir()+ gh = work / "bin/gh"+ gh.write_text(f"#!{sys.executable}\n" + GH.replace("GIT_EXE", shutil.which("git")))+ gh.chmod(0o755)+ subprocess.run(["git", "init", "-q", "-b", "fixture"], cwd=work, check=True)+ subprocess.run(["git", "-c", "user.name=Fixture", "-c", "[email protected]", "commit", "-q", "--allow-empty", "-m", "fixture"], cwd=work, check=True)+ head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=work, text=True).strip()+ (work / "gh-state.json").write_text(json.dumps({"initial_head": head, "checks": "SUCCESS"}))+ (work / "notes.md").write_text("## Verification\nFixture checks passed.\n")+ env = {k: v for k, v in os.environ.items() if not k.endswith("_API_KEY")}+ env.update(HOME=temp, PATH=str(work / "bin") + os.pathsep + os.environ["PATH"], LMSTUDIO_API_KEY="local",+ GRAFF_NO_TELEMETRY="1", GRAFF_FLEET="off", GRAFF_NO_SMOLIFY="1", GRAFF_NO_CODEDB_GUARD="1", NO_COLOR="1")+ acquired, primed, transferred = (threading.Event() for _ in range(3))+ def peer(action, kind="publication", key="fixture", **extra):+ return {"tool": "peer_message", "arguments": dict(action=action, kind=kind, key=key, **extra)}+ class Peers(ScriptedModel):+ def next_reply(self, body):+ actor = "A" if "fixture-actor-A" in json.dumps(body) else "B"+ with self._lock:+ self.requests.append(body)+ step = self.counts[actor]+ self.counts[actor] += 1+ if actor == "A":+ if step == 0: return peer("claim")+ if step == 1:+ acquired.set()+ assert primed.wait(35), "peer did not reach foreign claim gate"+ ledger = json.loads((work / ".graff/artifact-claims.json").read_text())+ receiver = next(c["session"] for c in ledger if c["key"] == "independent")+ return peer("handoff", session=receiver)+ if step == 2:+ transferred.set()+ return tool("gh pr create --title fixture --body-file notes.md")+ else:+ if step == 0:+ assert acquired.wait(35)+ return peer("claim", kind="branch", key="independent")+ if step == 1: return tool("gh pr create --head unrelated --title fixture --body-file notes.md")+ if step == 2: return tool("gh pr create --title fixture --body-file notes.md")+ if step == 3:+ primed.set()+ assert transferred.wait(35)+ return tool("gh pr create --title fixture --body-file notes.md")+ return {"text": "Handoff fixture complete."}+ model = Peers([])+ model.counts = {"A": 0, "B": 0}+ model.start(1234)+ def actor(name):+ return subprocess.run([str(graff), "--json", "--yolo", "--old", "--model", "lmstudio"], cwd=work,+ env=env, text=True, capture_output=True, timeout=100,+ input=json.dumps({"type": "user", "text": "Run fixture-actor-" + name}) + "\n")+ try:+ with concurrent.futures.ThreadPoolExecutor(2) as pool:+ one, two = pool.submit(actor, "A"), pool.submit(actor, "B")+ a, b = one.result(), two.result()+ assert a.returncode == b.returncode == 0, (a.stderr[-1000:], b.stderr[-1000:])+ mutations = (work / "mutations.jsonl").read_text().splitlines() if (work / "mutations.jsonl").exists() else []+ assert len(mutations) == 2, (mutations, a.stdout[-4000:], b.stdout[-4000:])+ assert 'artifact claim held' in a.stdout and 'artifact claim held' in b.stdout, (a.stdout[-3000:], b.stdout[-3000:])+ print("PASS two live sessions: independent branch allowed; handoff enables receiver and revokes old owner", flush=True)+ finally:+ model.stop()+++def orphan_listener(graff):+ if sys.platform not in ("darwin", "linux"):+ return+ import re+ import signal+ import socket+ with tempfile.TemporaryDirectory(prefix="graff-297-orphan-") as temp:+ work = Path(temp)+ child = work / "listener.py"+ child.write_text("""import json,os,pathlib,socket,time+s=socket.socket();s.bind(('127.0.0.1',0));s.listen()+pathlib.Path('listener.json').write_text(json.dumps({'pid':os.getpid(),'port':s.getsockname()[1]}))+while True: time.sleep(1)+""")+ env = dict(os.environ, HOME=temp, GRAFF_FIXTURE="legacy-listener", GRAFF_NO_TELEMETRY="1")+ subprocess.run([sys.executable, "-c", "import subprocess,sys;subprocess.Popen([sys.executable,'listener.py'],start_new_session=True,stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)"], cwd=work, env=env, check=True)+ info = work / "listener.json"+ deadline = time.monotonic() + 10+ while not info.exists() and time.monotonic() < deadline: time.sleep(.05)+ state = json.loads(info.read_text())+ pid, port = state['pid'], state['port']+ try:+ listing = subprocess.run([str(graff), "servers", "list"], cwd=work, env=env, text=True, capture_output=True, timeout=30)+ token = re.search(rf"stop-suspect {pid} ([0-9a-f]+-[0-9a-f]+)", listing.stdout)+ assert token, listing.stdout[-3000:]+ bad = subprocess.run([str(graff), "servers", "stop-suspect", str(pid), "stale-token"], cwd=work, env=env, text=True, capture_output=True, timeout=30)+ assert "unverifiable" in bad.stdout, bad.stdout+ with socket.create_connection(('127.0.0.1', port), timeout=2): pass+ stopped = subprocess.run([str(graff), "servers", "stop-suspect", str(pid), token.group(1)], cwd=work, env=env, text=True, capture_output=True, timeout=30)+ assert "legacy listener stop: stopped" in stopped.stdout, stopped.stdout+ try:+ socket.create_connection(('127.0.0.1', port), timeout=.5).close()+ raise AssertionError("listener survived reported stop")+ except OSError: pass+ assert not (work / '.codegraff/jobs').exists(), "suspect was silently adopted"+ print("PASS legacy orphan: discovery, stale-token refusal, identity-bound explicit stop, no adoption", flush=True)+ finally:+ try: os.killpg(pid, signal.SIGKILL)+ except ProcessLookupError: pass+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--graff", type=Path, default=ROOT / "zig-out/bin/graff")+ args = parser.parse_args()+ orphan_listener(args.graff)+ handoff(args.graff)+ stream_and_mcp(args.graff)+ create = "gh pr create --title fixture --body-file notes.md"+ for bad in ({"runs": "failure"}, {"runs": "pending"}, {"unavailable": True}, {"runs": "malformed"}):+ run_case(args.graff, f"non-draft refuses {bad}", [tool(create), {"text": "Publication blocked."}], bad)+ run_case(args.graff, "body flag cannot turn non-draft into draft", [tool("gh pr create --title fixture --body '--draft'"), {"text": "Blocked."}], {"runs": "failure"})+ run_case(args.graff, "local-only and repeated completion cannot pass PR CI", [tool(create), completion(), completion(), {"text": "CI remains unverified."}], {"runs": "none"}, expected_mutations=1, refused=2, resume_check=True)+ run_case(args.graff, "fresh passing remote head completes", [tool(create), completion()], {"checks": "SUCCESS"}, expected_mutations=1, expected_final="Verification complete.")+ run_case(args.graff, "draft handoff is explicitly unverified", [tool(create + " --draft"), completion("Handing off the draft.")], {"runs": "failure"}, expected_mutations=1, expected_final="Draft handoff")+ commit = "git -c user.name=Fixture -c [email protected] commit --allow-empty -m next"+ run_case(args.graff, "ready refreshes changed head", [tool(create), tool(commit), tool("gh pr ready"), {"text": "New head needs CI."}], {"checks": "FAILURE"}, expected_mutations=1)+ run_case(args.graff, "passing old remote head is not local new head", [tool(create), tool(commit), completion(), {"text": "Push and verify the new head."}], {"checks": "SUCCESS", "remote_head": "initial"}, expected_mutations=1, refused=1)+++if __name__ == "__main__":+ main()diff --git a/src/agent.zig b/src/agent.zigindex d57aeee6..9b2db122 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -123,6 +123,7 @@ pub const Agent = struct {sys_normal: []const u8 = prompts.main_system_prompt, // root system prompt (+ project instructions)sys_override: ?[]const u8 = null, // per-child custom prompt or transient isolated-review basetask_prompt: ?[]const u8 = null, // a subagent's mandate, pinned once before the first history rewrite so compaction can restate it verbatim (recentContextStart can keep no verbatim suffix for a child - its only clean user turn is index 0)+ pr_verification: @import("pr_verify.zig").State = .unused,agent_cwd: ?[]const u8 = null, // subagent-only (#276 P0-1): absolute path of this agent's isolated git worktree, threaded through ToolCtx per tool call instead of a process-wide chdir — parallel siblings each keep their owntools_used: trace.ToolSink = .{}, // external tool calls this agent made (per turn for the root)tool_calls_this_turn: u64 = 0,@@ -531,9 +532,7 @@ pub const Agent = struct {return if (self.scratch_arena) |sa| sa.allocator() else self.arena;}- pub fn messageMutationAlloc(self: *Agent) Allocator {- return self.message_mutation_arena orelse self.arena;- }+ pub const messageMutationAlloc = @import("agent_alloc.zig").messageMutationAlloc;pub const escWatchTask = @import("agent_interrupt.zig").escWatchTask;pub const escPressed = @import("agent_interrupt.zig").escPressed;diff --git a/src/agent_alloc.zig b/src/agent_alloc.zignew file mode 100644index 00000000..2107459b--- /dev/null+++ b/src/agent_alloc.zig@@ -0,0 +1,6 @@+const std = @import("std");+const Agent = @import("agent.zig").Agent;++pub fn messageMutationAlloc(self: *Agent) std.mem.Allocator {+ return self.message_mutation_arena orelse self.arena;+}diff --git a/src/agent_argstream.zig b/src/agent_argstream.zigindex ebda9ae8..4fdb6694 100644--- a/src/agent_argstream.zig+++ b/src/agent_argstream.zig@@ -81,6 +81,7 @@ pub const ArgLive = struct {hi_sur: u16 = 0, // pending UTF-16 high surrogate (0 = none)key: [24]u8 = undefined,key_len: usize = 0,+ citations: @import("cite_markup.zig").Stream = .{},key_over: bool = false, // key overflowed/escaped — cannot be the targetconst State = enum { seek_key, key, post_key, pre_val, skip_val, val, done };@@ -101,7 +102,7 @@ pub const ArgLive = struct {var out_len: usize = 0;for (frag) |c| {if (out_len > out_buf.len - 8) { // keep room for one decoded escape- agent.emitArgText(self.tool, out_buf[0..out_len]);+ self.emit(agent, out_buf[0..out_len]);out_len = 0;}switch (self.state) {@@ -211,7 +212,20 @@ pub const ArgLive = struct {},}}- if (out_len > 0) agent.emitArgText(self.tool, out_buf[0..out_len]);+ if (out_len > 0) self.emit(agent, out_buf[0..out_len]);+ }++ fn emit(self: *ArgLive, agent: *Agent, text: []const u8) void {+ if (self.tool == .rlm) return agent.emitArgText(self.tool, text);+ var clean: [514]u8 = undefined;+ var n: usize = 0;+ for (text) |c| {+ var buf: [3]u8 = undefined;+ const bytes = self.citations.byte(c, &buf);+ @memcpy(clean[n..][0..bytes.len], bytes);+ n += bytes.len;+ }+ agent.emitArgText(self.tool, clean[0..n]);}/// Emit one literal byte, flushing any orphaned high surrogate first.@@ -352,6 +366,10 @@ pub fn argLiveDelta(self: *Agent, obj: std.json.ObjectMap) void {/// never carried these moments (argLiveDelta gates --json off), so JsonSink/// stays silent.fn openLive(self: *Agent, name: []const u8, ix: i64) void {+ if (!@import("builtin").is_test and argToolFor(name) == .attempt_completion and @import("pr_verify.zig").hasObligation(self)) {+ self.arg_live = .{};+ return;+ }if (argToolFor(name) == .rlm) rlm_spec.resetLive(self.gpa, self.io);self.arg_live.open(name, ix);}@@ -384,7 +402,7 @@ pub fn argStreamedFully(self: *Agent, call: ToolCall) bool {// fix B2 added, so it was the last unguarded deref on that path.if (call.input != .object) return false;const v = call.input.object.get(argField(at)) orelse return false;- return v == .string and v.string.len == self.streamed_args_len;+ return v == .string and @import("cite_markup.zig").strippedLen(v.string) == self.streamed_args_len;}test "argStreamedFully: a non-object tool input is refused, not dereferenced" {diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex d6b7701d..04ab4b70 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -351,7 +351,8 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {return .{ .text = refusal, .is_error = true };}const raw = if (tools_mod.json_args.object(call.input)) |o| (tools_mod.json_args.str(o, "result") orelse "") else "";- const result = try cite_markup.dupe(self.arena, raw);+ const cleaned = try cite_markup.dupe(self.arena, raw);+ const result = if (!@import("builtin").is_test and self.pr_verification == .draft) try std.fmt.allocPrint(self.arena, "Draft handoff — CI is not verified.\n\n{s}", .{cleaned}) else cleaned;self.completed = result;if (!self.sub) task_outcome.noteGoalCompleted(self);// .complete retires the epoch (goal_state.currentEpoch) and the checklist parks - readable, no longer current, never deleted (#318).diff --git a/src/argstream_citation_tests.zig b/src/argstream_citation_tests.zignew file mode 100644index 00000000..651e04df--- /dev/null+++ b/src/argstream_citation_tests.zig@@ -0,0 +1,36 @@+//! Regression at the live argument-to-terminal boundary, not only dupe().+const std = @import("std");+const Agent = @import("agent.zig").Agent;+const main = @import("main.zig");++test "#819 completion citations survive no stream boundary into displayed or captured text" {+ const saved_json = main.json_mode;+ const saved_color = main.use_color;+ main.json_mode = false;+ main.use_color = false;+ defer {+ main.json_mode = saved_json;+ main.use_color = saved_color;+ }+ const fixtures = [_][]const u8{+ "{\"result\":\"See \\ue200cite\\ue202turn0search0\\ue202turn1search2\\ue201docs café.\"}",+ "{\"result\":\"See \u{E200}cite\u{E202}turn0search0\u{E202}turn1search2\u{E201}docs café.\"}",+ };+ for (fixtures) |json| {+ // Exercise every split, including the two bytes inside a UTF-8 marker.+ for (0..json.len + 1) |split| {+ var aw: std.Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ var a: Agent = .{ .gpa = std.testing.allocator, .arena = std.testing.allocator, .io = std.testing.io, .client = undefined, .provider = undefined, .messages = undefined, .sub = false, .label = "test", .out = &aw.writer };+ defer a.partial_text.deinit(std.testing.allocator);+ a.arg_live.open("attempt_completion", 0);+ a.arg_live.feed(&a, 0, json[0..split]);+ a.arg_live.feed(&a, 0, json[split..]);+ try std.testing.expectEqualStrings("See docs café.", aw.writer.buffered());+ try std.testing.expectEqualStrings("See docs café.", a.partial_text.items);+ const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json, .{});+ defer parsed.deinit();+ try std.testing.expect(a.argStreamedFully(.{ .id = "1", .name = "attempt_completion", .input = parsed.value }));+ }+ }+}diff --git a/src/artifact_claim.zig b/src/artifact_claim.zigindex f05cfe0c..0df79cbb 100644--- a/src/artifact_claim.zig+++ b/src/artifact_claim.zig@@ -165,12 +165,12 @@ pub fn isClaimedMutation(cmd: []const u8) bool {var saw_gh = false;var saw_pr = false;while (it.next()) |tok| {- if (std.mem.eql(u8, tok, "git")) {+ if (std.mem.eql(u8, std.fs.path.basename(tok), "git")) {saw_git = true;continue;}if (saw_git and (std.mem.eql(u8, tok, "push") or std.mem.eql(u8, tok, "commit") or std.mem.eql(u8, tok, "add"))) return true;- if (std.mem.eql(u8, tok, "gh")) {+ if (std.mem.eql(u8, std.fs.path.basename(tok), "gh")) {saw_gh = true;continue;}@@ -254,7 +254,7 @@ fn ownerLive(io: Io, owner: Owner) bool {return g_test_live;}if (owner.pid == 0) return true;- return proc_identity.probe(io, owner.pid) != .gone;+ return proc_identity.ownerState(owner.start_id, proc_identity.probe(io, owner.pid)) == .held;}fn claimRelevant(held: Kind, mutation: Kind) bool {@@ -269,68 +269,88 @@ fn claimRelevant(held: Kind, mutation: Kind) bool {pub fn gateCommand(arena: Allocator, io: Io, cmd: []const u8, key: []const u8) ?[]const u8 {if (!isClaimedMutation(cmd)) return null;- ensureLoaded(io);+ var scratch = std.heap.ArenaAllocator.init(std.heap.page_allocator);+ defer scratch.deinit();+ const tx = begin(io, scratch.allocator()) catch return "artifact claim ledger unavailable or busy: action NOT performed";+ defer if (tx) |transaction| transaction.end();+ var local: Ledger = .{};+ const ledger = if (tx != null) &local else &g_ledger;+ if (tx) |transaction| loadTransaction(transaction, ledger) catch return "artifact claim ledger unreadable: action NOT performed";const kind = mutationKind(cmd);- const me = selfOwner();+ var me = selfOwner();+ if (!builtin.is_test) me.start_id = proc_identity.selfStartId(io);if (key.len == 0) {- for (g_ledger.slice()) |c| {+ for (ledger.slice()) |c| {if (!claimRelevant(c.kind, kind)) continue;const live = ownerLive(io, c.owner);- if (verdict(g_ledger.slice(), c.kind, c.key, me, live) == .foreign_live)+ if (verdict(ledger.slice(), c.kind, c.key, me, live) == .foreign_live)return refuseText(arena, c.kind, c.key, c.owner);}return null;}- const existing = find(g_ledger.slice(), kind, key) orelse find(g_ledger.slice(), .publication, key);- const check_kind = if (existing) |c| c.kind else kind;- const check_key = if (existing) |c| c.key else key;- const held = find(g_ledger.slice(), check_kind, check_key) orelse return null;- const live = ownerLive(io, held.owner);- return switch (verdict(g_ledger.slice(), check_kind, check_key, me, live)) {- .foreign_live => refuseText(arena, check_kind, check_key, held.owner),- else => null,- };+ for (ledger.slice()) |held| {+ if (!claimRelevant(held.kind, kind)) continue;+ if (held.key.len != 0 and !std.mem.eql(u8, held.key, key)) continue;+ if (!sameOwner(held.owner, me) and ownerLive(io, held.owner)) return refuseText(arena, held.kind, held.key, held.owner);+ }+ return null;}pub fn handleTool(arena: Allocator, io: Io, action: []const u8, kind_s: []const u8, key: []const u8, to_session: []const u8) !ExecResult {- ensureLoaded(io);+ var scratch = std.heap.ArenaAllocator.init(std.heap.page_allocator);+ defer scratch.deinit();+ const tx = begin(io, scratch.allocator()) catch return .{ .text = "claim ledger unavailable or busy", .is_error = true };+ defer if (tx) |transaction| transaction.end();+ var local: Ledger = .{};+ const ledger = if (tx != null) &local else &g_ledger;+ const storage = if (tx != null) scratch.allocator() else storeAlloc();+ if (tx) |transaction| loadTransaction(transaction, ledger) catch return .{ .text = "claim ledger unreadable; no claim changed", .is_error = true };const kind = kindFrom(kind_s) orelse return .{.text = "kind must be branch, issue, commit, pull_request, or publication",.is_error = true,};- const me = selfOwner();+ var me = selfOwner();+ if (!builtin.is_test) me.start_id = proc_identity.selfStartId(io);const now: i64 = 0;- const existing = find(g_ledger.slice(), kind, key);+ const existing = find(ledger.slice(), kind, key);const live = if (existing) |c| ownerLive(io, c.owner) else false;if (std.mem.eql(u8, action, "claim") or std.mem.eql(u8, action, "acquire")) {- const msg = acquire(&g_ledger, storeAlloc(), kind, key, me, now, live) catch |err| switch (err) {+ const msg = acquire(ledger, storage, kind, key, me, now, live) catch |err| switch (err) {error.ClaimHeld => return .{ .text = refuseText(arena, kind, key, existing.?.owner), .is_error = true },else => return .{ .text = "claim acquire failed", .is_error = true },};- flush(io);+ if (tx) |transaction| transaction.write(try persistJson(scratch.allocator(), ledger)) catch return .{ .text = "claim was NOT persisted; retry before publishing", .is_error = true };return .{ .text = msg, .is_error = false };}if (std.mem.eql(u8, action, "release")) {- const msg = release(&g_ledger, kind, key, me, live) catch return .{+ const msg = release(ledger, kind, key, me, live) catch return .{.text = "cannot release a live foreign claim",.is_error = true,};- flush(io);+ if (tx) |transaction| transaction.write(try persistJson(scratch.allocator(), ledger)) catch return .{ .text = "claim was NOT persisted; retry before publishing", .is_error = true };return .{ .text = msg, .is_error = false };}if (std.mem.eql(u8, action, "handoff")) {if (to_session.len == 0) return .{ .text = "handoff needs session (the receiver)", .is_error = true };- const msg = handoff(&g_ledger, storeAlloc(), kind, key, me, .{ .session = to_session }, now, live) catch |err| switch (err) {+ var receiver = Owner{ .session = to_session };+ if (!builtin.is_test) {+ const target = @import("peer_target.zig").resolvePeer(presence.liveAllPeers(io, scratch.allocator()), to_session);+ if (target != .one) return .{ .text = "handoff needs one identifiable live peer", .is_error = true };+ const peer = target.one;+ if (!std.mem.eql(u8, peer.identity, presence.ownIdentity()) or peer.start_id == 0) return .{ .text = "handoff receiver must have verified identity in this workspace", .is_error = true };+ receiver = .{ .session = peer.session_id, .pid = peer.pid, .start_id = peer.start_id };+ }+ const msg = handoff(ledger, storage, kind, key, me, receiver, now, live) catch |err| switch (err) {error.ClaimHeld => return .{ .text = "cannot hand off a claim you do not own", .is_error = true },error.NoClaim => return .{ .text = "no claim to hand off", .is_error = true },else => return .{ .text = "handoff failed", .is_error = true },};- flush(io);+ if (tx) |transaction| transaction.write(try persistJson(scratch.allocator(), ledger)) catch return .{ .text = "claim was NOT persisted; retry before publishing", .is_error = true };return .{ .text = msg, .is_error = false };}if (std.mem.eql(u8, action, "status")) {if (existing) |c| {- const v = verdict(g_ledger.slice(), kind, key, me, live);+ const v = verdict(ledger.slice(), kind, key, me, live);return .{ .text = try std.fmt.allocPrint(arena, "claim {s} {s}: {s} owner=\"{s}\"", .{ @tagName(kind), key, @tagName(v), c.owner.session }), .is_error = false };}return .{ .text = "no claim", .is_error = false };@@ -344,21 +364,28 @@ fn persistPath() ?[]const u8 {return persist_rel;}-fn ensureLoaded(io: Io) void {- if (g_loaded) return;- g_loaded = true;- const path = persistPath() orelse return;- const text = Io.Dir.cwd().readFileAlloc(io, path, storeAlloc(), .limited(64 * 1024)) catch return;- loadJson(storeAlloc(), &g_ledger, text) catch {- g_ledger.len = 0;- };+fn begin(io: Io, arena: Allocator) !?@import("repo_transaction.zig").Transaction {+ const path = persistPath() orelse return null;+ return try @import("repo_transaction.zig").Transaction.begin(io, arena, path);+}++fn loadTransaction(tx: @import("repo_transaction.zig").Transaction, ledger: *Ledger) !void {+ const text = try tx.read() orelse return;+ try loadJson(tx.arena, ledger, text);}-fn flush(io: Io) void {+fn reload(io: Io) !void {const path = persistPath() orelse return;- const json = persistJson(storeAlloc(), &g_ledger) catch return;- if (std.fs.path.dirname(path)) |dir| Io.Dir.cwd().createDirPath(io, dir) catch {};- Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = json }) catch {};+ // Every transaction reads again under the lock. A previously cached owner+ // must never survive a peer's acknowledged handoff.+ g_ledger.len = 0;+ if (g_store) |*st| st.deinit();+ g_store = null;+ const text = Io.Dir.cwd().readFileAlloc(io, path, storeAlloc(), .limited(64 * 1024)) catch |err| switch (err) {+ error.FileNotFound => return,+ else => return err,+ };+ try loadJson(storeAlloc(), &g_ledger, text);}pub fn persistJson(arena: Allocator, ledger: *const Ledger) ![]const u8 {@@ -385,17 +412,17 @@ pub fn persistJson(arena: Allocator, ledger: *const Ledger) ![]const u8 {pub fn loadJson(arena: Allocator, ledger: *Ledger, text: []const u8) !void {ledger.len = 0;- const parsed = std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{}) catch return;- if (parsed != .array) return;+ const parsed = try std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{});+ if (parsed != .array) return error.InvalidLedger;for (parsed.array.items) |item| {- if (item != .object) continue;- const kind_s = if (item.object.get("kind")) |v| (if (v == .string) v.string else continue) else continue;- const kind = kindFrom(kind_s) orelse continue;+ if (item != .object) return error.InvalidLedger;+ const kind_s = if (item.object.get("kind")) |v| (if (v == .string) v.string else return error.InvalidLedger) else return error.InvalidLedger;+ const kind = kindFrom(kind_s) orelse return error.InvalidLedger;const key = if (item.object.get("key")) |v| (if (v == .string) v.string else "") else "";const session = if (item.object.get("session")) |v| (if (v == .string) v.string else "") else "";- const pid: i32 = if (item.object.get("pid")) |v| (if (v == .integer) @intCast(v.integer) else 0) else 0;+ const pid: i32 = if (item.object.get("pid")) |v| (if (v == .integer) (std.math.cast(i32, v.integer) orelse return error.InvalidLedger) else return error.InvalidLedger) else 0;const start_id: u64 = if (item.object.get("start_id")) |v| (if (v == .integer and v.integer >= 0) @intCast(v.integer) else 0) else 0;- if (ledger.len >= max_claims) break;+ if (ledger.len >= max_claims) return error.InvalidLedger;ledger.items[ledger.len] = .{.kind = kind,.key = try arena.dupe(u8, key),@@ -521,7 +548,9 @@ test "file persist reloads after a resume-shaped reset" {defer arena_state.deinit();const ar = arena_state.allocator();const io = std.testing.io;- const file = "zig-cache/artifact-claims-persist-test.json";+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const file = try std.fmt.allocPrint(ar, ".zig-cache/tmp/{s}/claims.json", .{tmp.sub_path});Io.Dir.cwd().deleteFile(io, file) catch {};defer Io.Dir.cwd().deleteFile(io, file) catch {};resetForTest();@@ -532,7 +561,7 @@ test "file persist reloads after a resume-shaped reset" {_ = try handleTool(ar, io, "claim", "publication", "feat/x", "");g_ledger.len = 0;g_loaded = false;- ensureLoaded(io);+ try reload(io);try std.testing.expectEqual(@as(usize, 1), g_ledger.len);try std.testing.expectEqualStrings("feat/x", g_ledger.items[0].key);try std.testing.expectEqualStrings("s-persist", g_ledger.items[0].owner.session);diff --git a/src/cite_markup.zig b/src/cite_markup.zigindex 50d45f44..326f8bd7 100644--- a/src/cite_markup.zig+++ b/src/cite_markup.zig@@ -75,6 +75,46 @@ pub fn dupe(alloc: Allocator, text: []const u8) ![]u8 {return aw.toOwnedSlice();}+/// Incremental counterpart to dupe. Hold at most two bytes while recognizing+/// a UTF-8 control marker; suppress its payload through the matching end.+pub const Stream = struct {+ prefix: u2 = 0,+ hidden: bool = false,++ /// buf needs three bytes. Returned bytes are ordinary user-facing text.+ pub fn byte(self: *Stream, c: u8, buf: *[3]u8) []const u8 {+ var n: usize = 0;+ if (self.prefix == 2 and c >= mark_start and c <= mark_sep) {+ if (c == mark_start) self.hidden = true;+ if (c == mark_end) self.hidden = false;+ self.prefix = 0;+ return buf[0..0];+ }+ if (self.prefix == 1 and c == pua_lead[1]) {+ self.prefix = 2;+ return buf[0..0];+ }+ if (!self.hidden) {+ if (self.prefix > 0) {+ buf[n] = pua_lead[0];+ n += 1;+ }+ if (self.prefix > 1) {+ buf[n] = pua_lead[1];+ n += 1;+ }+ }+ self.prefix = 0;+ if (c == pua_lead[0]) {+ self.prefix = 1;+ } else if (!self.hidden) {+ buf[n] = c;+ n += 1;+ }+ return buf[0..n];+ }+};+test "citation annotations strip to surrounding prose (#805, #811)" {const a = std.testing.allocator;const raw = "See the docs\u{E200}cite\u{E202}turn0view0\u{E201} for details.";diff --git a/src/clipboard_export.js b/src/clipboard_export.jsnew file mode 100644index 00000000..e20275d8--- /dev/null+++ b/src/clipboard_export.js@@ -0,0 +1,41 @@+// Runs under the system JavaScript for Automation runtime; no application+// activation, Apple Events to another app, or shell interpolation is needed.+ObjC.import('AppKit');+function run(argv) {+ const pb = argv[1] ? $.NSPasteboard.pasteboardWithName(argv[1]) : $.NSPasteboard.generalPasteboard;+ const revision = pb.changeCount;+ const types = ObjC.deepUnwrap(pb.types) || [];+ const raster = ['public.png', 'public.tiff', 'public.jpeg', 'public.heic', 'com.compuserve.gif', 'public.webp'];+ let sawImage = false;+ for (const type of raster.concat(['com.adobe.pdf', 'public.file-url'])) {+ if (types.indexOf(type) < 0) continue;+ let data;+ let flavor = type === 'com.adobe.pdf' ? 'pdf' : 'png';+ if (type === 'public.file-url') {+ const value = pb.stringForType(type);+ if (!value || !value.js) continue;+ const url = $.NSURL.URLWithString(value);+ if (!url.isFileURL) continue;+ const ext = (ObjC.unwrap(url.pathExtension) || '').toLowerCase();+ if (!/^(png|jpe?g|gif|webp|tiff?|heic|bmp|pdf)$/.test(ext)) continue;+ sawImage = true;+ flavor = 'furl';+ data = $.NSData.dataWithContentsOfURL(url);+ } else {+ sawImage = true;+ data = pb.dataForType(type);+ }+ if (!data || !data.length) continue;+ const img = $.NSImage.alloc.initWithData(data);+ if (!img || !img.isValid) continue;+ const bitmap = $.NSBitmapImageRep.imageRepWithData(img.TIFFRepresentation);+ if (!bitmap || !bitmap.pixelsWide || !bitmap.pixelsHigh) continue;+ const png = bitmap.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $({}));+ if (!png || !png.length) continue;+ if (pb.changeCount !== revision) return 'changed';+ if (!png.writeToFileAtomically(argv[0], true)) return 'extract';+ return 'ok:' + flavor;+ }+ if (pb.changeCount !== revision) return 'changed';+ return sawImage ? 'convert' : 'empty';+}diff --git a/src/clipboard_native.zig b/src/clipboard_native.zignew file mode 100644index 00000000..b6b2cc77--- /dev/null+++ b/src/clipboard_native.zig@@ -0,0 +1,74 @@+//! Direct pasteboard flavors avoid AppleScript's lossy PNGf coercion (#843).+const std = @import("std");+const clip = @import("vision_clipboard.zig");+const runner = @import("process_runner.zig");+pub const script = @embedFile("clipboard_export.js");++pub fn grab(io: std.Io, gpa: std.mem.Allocator, board: []const u8) clip.GrabAttempt {+ if (@import("builtin").os.tag != .macos) return .empty;+ const path = clip.tempPath(io, gpa, "png") orelse return .{ .failed = .access };+ var keep = false;+ defer if (!keep) clip.discard(io, gpa, path);+ // Retry only when the clipboard changed during the read. Promised flavors+ // can take time to materialize, but cannot block a paste indefinitely.+ for (0..2) |_| {+ const r = runner.runCapped(gpa, io, &.{ "/usr/bin/osascript", "-l", "JavaScript", "-e", script, path, board }, 64, 1024, 5000) catch return .{ .failed = .access };+ defer gpa.free(r.stdout);+ defer gpa.free(r.stderr);+ if (!runner.ranOk(r) or r.stdout_truncated) return .{ .failed = .access };+ const status = std.mem.trim(u8, r.stdout, " \r\n");+ if (std.mem.eql(u8, status, "changed")) continue;+ if (std.mem.eql(u8, status, "empty")) return .empty;+ if (std.mem.eql(u8, status, "convert")) return .{ .failed = .convert };+ if (!std.mem.startsWith(u8, status, "ok:")) return .{ .failed = .extract };+ if (!clip.looksLikePng(io, path)) return .{ .failed = .extract };+ const flavor = std.meta.stringToEnum(clip.Flavor, status[3..]) orelse return .{ .failed = .extract };+ keep = true;+ return .{ .ok = .{ .path = path, .flavor = flavor, .owned = true } };+ }+ return .{ .failed = .access };+}++test "#843 real named pasteboards export PNG TIFF JPEG file URLs and distinguish invalid data" {+ if (@import("builtin").os.tag != .macos) return error.SkipZigTest;+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ const board = clip.tempPath(io, gpa, "pasteboard") orelse return error.OutOfMemory;+ defer gpa.free(board);+ const source = clip.tempPath(io, gpa, "png") orelse return error.OutOfMemory;+ defer clip.discard(io, gpa, source);+ const setup =+ \\ObjC.import('AppKit');+ \\function run(argv) {+ \\ const pb=$.NSPasteboard.pasteboardWithName(argv[0]); pb.clearContents;+ \\ if(argv[1]==='empty') return 'ready';+ \\ if(argv[1]==='text') {pb.setStringForType('fixture','public.utf8-plain-text');return 'ready';}+ \\ if(argv[1]==='invalid') {pb.setDataForType($('broken').dataUsingEncoding($.NSUTF8StringEncoding),'public.png');return 'ready';}+ \\ const png=$.NSData.alloc.initWithBase64EncodedStringOptions('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAEElEQVR4nGP4z8AARAwQCgAf7gP9i18U1AAAAABJRU5ErkJggg==',0);+ \\ if(argv[1]==='pdf') {pb.setDataForType($.NSData.alloc.initWithBase64EncodedStringOptions('JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUl0gL0NvdW50IDEgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA0IDRdIC9Db250ZW50cyA0IDAgUiA+PgplbmRvYmoKNCAwIG9iago8PCAvTGVuZ3RoIDI0ID4+CnN0cmVhbQoxIDAgMCByZyAwIDAgNCA0IHJlIGYKZW5kc3RyZWFtCmVuZG9iagp4cmVmCjAgNQowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDAwMDkgMDAwMDAgbiAKMDAwMDAwMDA1OCAwMDAwMCBuIAowMDAwMDAwMTE1IDAwMDAwIG4gCjAwMDAwMDAxOTggMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA1IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgoyNjkKJSVFT0YK',0),'com.adobe.pdf');return 'ready';}+ \\ if(argv[1]==='furl') {png.writeToFileAtomically(argv[2],true);pb.setStringForType($.NSURL.fileURLWithPath(argv[2]).absoluteString,'public.file-url');return 'ready';}+ \\ const image=$.NSImage.alloc.initWithData(png);+ \\ const bitmap=$.NSBitmapImageRep.imageRepWithData(image.TIFFRepresentation);+ \\ const data=argv[1]==='tiff'?image.TIFFRepresentation:argv[1]==='jpeg'?bitmap.representationUsingTypeProperties($.NSBitmapImageFileTypeJPEG,$({})):png;+ \\ pb.setDataForType(data,argv[1]==='tiff'?'public.tiff':argv[1]==='jpeg'?'public.jpeg':'public.png'); return 'ready';+ \\}+ ;+ for ([_][]const u8{ "png", "tiff", "jpeg", "pdf", "furl", "invalid", "text", "empty" }) |kind| {+ const r = try runner.runCapped(gpa, io, &.{ "/usr/bin/osascript", "-l", "JavaScript", "-e", setup, board, kind, source }, 64, 2048, 5000);+ defer gpa.free(r.stdout);+ defer gpa.free(r.stderr);+ try std.testing.expect(runner.ranOk(r));+ const got = grab(io, gpa, board);+ if (std.mem.eql(u8, kind, "invalid")) {+ try std.testing.expect(got == .failed and got.failed == .convert);+ } else if (std.mem.eql(u8, kind, "text") or std.mem.eql(u8, kind, "empty")) {+ try std.testing.expect(got == .empty);+ } else {+ try std.testing.expect(got == .ok);+ defer got.ok.release(io, gpa);+ try std.testing.expect(clip.looksLikePng(io, got.ok.path));+ try std.testing.expect(got.ok.owned);+ if (std.mem.eql(u8, kind, "furl")) try std.testing.expect(clip.looksLikePng(io, source));+ }+ }+}diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex dd2b065c..e9c9727c 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -490,3 +490,10 @@ pub fn handleRest(line: []const u8, out: *Io.Writer) !void {try @import("help.zig").render(out);try out.flush();}++pub fn handleCommand(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !void {+ if (try @import("commands_session.zig").tryHandle(root, keys, arena, line, out)) return;+ if (try @import("commands_model.zig").tryHandle(root, keys, arena, line, out)) return;+ if (try tryHandle(root, keys, arena, line, out)) return;+ try handleRest(line, out);+}diff --git a/src/exec_bash.zig b/src/exec_bash.zigindex db2a9be1..cdbf8df3 100644--- a/src/exec_bash.zig+++ b/src/exec_bash.zig@@ -252,6 +252,7 @@ test {pub fn exec(ctx: ToolCtx, call: tools.ToolCall) !ToolOutput {const cmd = strField(call.input, "command") orelse return missingArg(ctx.gpa, "command");+ if (try @import("publish_gate.zig").beforeExec(ctx, cmd)) |denied| return denied;// Respect the subagent gate before running even a read-only probe.const approved = if (ctx.from_sub) (if (ctx.approvals) |ap| ap.allowed(ctx.io, cmd) else true) else true;var warning = false;diff --git a/src/goal_verify.zig b/src/goal_verify.zigindex 90b8b264..e6c6d620 100644--- a/src/goal_verify.zig+++ b/src/goal_verify.zig@@ -30,6 +30,7 @@ pub fn hasUnresolved(agent: *const Agent) bool {}pub fn completionGate(arena: Allocator, agent: *Agent) !?[]const u8 {+ if (!@import("builtin").is_test) if (@import("pr_verify.zig").completionGate(agent)) |blocked| return blocked;if (agent.review_mode or agent.sub) return goal_state.completionGate(arena, agent);if (hasUnresolved(agent)) {const rendered = goal_state.renderTodos(agent, goal_state.currentEpoch(agent.goal));@@ -42,6 +43,7 @@ pub fn completionGate(arena: Allocator, agent: *Agent) !?[]const u8 {/// goal/eval/verification obligation is vacuously verified so recipe/// telemetry for chat turns stays usable.pub fn taskVerified(agent: *const Agent) bool {+ if (!@import("builtin").is_test and !@import("pr_verify.zig").taskVerified(agent)) return false;if (hasUnresolved(agent)) return false;if (agent.eval_cmd != null) return agent.eval_verified and !agent.eval_repair_pending;if (goal_state.goalActive(@constCast(agent))) {diff --git a/src/main.zig b/src/main.zigindex 3fe54731..23797275 100644--- a/src/main.zig+++ b/src/main.zig@@ -48,7 +48,12 @@ const util = @import("util.zig"); // shared JSON ObjectMap getters (strFieldObj/const learn_store = @import("learn_store.zig");const learn_eval = @import("learn_eval.zig");const learn_cli = @import("learn_cli.zig");-test { // unit_tests' root is main.zig only, so reference every split-out module or its tests silently never run+test {+ _ = @import("clipboard_native.zig");+ _ = @import("server_orphan.zig");+ _ = @import("repo_transaction.zig");+ _ = .{ @import("pr_command.zig"), @import("pr_evidence.zig"), @import("pr_verify.zig") };+ _ = @import("argstream_citation_tests.zig"); // unit_tests' root is main.zig only, so reference every split-out module or its tests silently never run_ = @import("codex_node_repl.zig");_ = pricing;_ = models_cache;@@ -521,12 +526,7 @@ const pickers = @import("pickers.zig");const commands_session = @import("commands_session.zig");const commands_model = @import("commands_model.zig");const commands_misc = @import("commands_misc.zig");-pub fn handleCommand(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !void {- if (try commands_session.tryHandle(root, keys, arena, line, out)) return;- if (try commands_model.tryHandle(root, keys, arena, line, out)) return;- if (try commands_misc.tryHandle(root, keys, arena, line, out)) return;- try commands_misc.handleRest(line, out);-}+pub const handleCommand = commands_misc.handleCommand;// Session persistence lives in session.zig (kept here for its test{} block).const session = @import("session.zig");// Provider login/credential flows live in oauth.zig.diff --git a/src/mcp.zig b/src/mcp.zigindex 199fb359..eeb11603 100644--- a/src/mcp.zig+++ b/src/mcp.zig@@ -96,7 +96,7 @@ pub const Registry = struct {/// Freed in deinit AFTER the transports referencing them are torn down.task_arenas: []std.heap.ArenaAllocator = &.{},/// Unjoined startServer futures from a deferred --yolo boot.- pending_starts: []Io.Future(mcp_boot.StartOutcome) = &.{},+ pending_starts: []mcp_boot.PendingStart = &.{},/// Names paired with `pending_starts` so companion auto-connect can skip/// a second spawn of a server the deferred fan-out already queued.pending_names: []const []const u8 = &.{},diff --git a/src/mcp_boot.zig b/src/mcp_boot.zigindex dfa91505..136e8205 100644--- a/src/mcp_boot.zig+++ b/src/mcp_boot.zig@@ -9,7 +9,7 @@//!//! `--yolo` (including `-p`) sets `defer_join`: tasks start immediately but//! the first model call is not blocked. `joinBeforeRequest` merges them on-//! the *second* model call (ADR 0035). Lean `-p` with no project `.mcp.json`+//! later model calls as each handshake finishes (ADR 0035). Lean `-p` with no project `.mcp.json`//! skips imported global/plugin handshakes (ADR 0029 is the project file).//! `joinPending` still blocks for `/mcp` and teardown.@@ -35,15 +35,36 @@ pub const StartOutcome = struct {arena_state: ?std.heap.ArenaAllocator = null,};+/// The flag has a stable address even when the pending queue grows. Only the+/// task writes it; the request thread consumes the future after acquire.+pub const PendingStart = struct {+ future: Io.Future(StartOutcome) = .{ .any_future = null, .result = .{} },+ ready: ?*std.atomic.Value(bool) = null,++ fn finished(self: *const PendingStart) bool {+ return if (self.ready) |flag| flag.load(.acquire) else true;+ }++ fn awaitResult(self: *PendingStart, reg: *Registry) StartOutcome {+ const result = self.future.await(reg.io);+ self.future = .{ .any_future = null, .result = .{} };+ if (self.ready) |flag| reg.gpa.destroy(flag);+ self.ready = null;+ return result;+ }+};+const StartCtx = struct {gpa: Allocator,io: Io,home: []const u8,show_diagnostics: bool,stdio_probe: bool,+ ready: ?*std.atomic.Value(bool) = null,};fn startServerTask(ctx: StartCtx, name: []const u8, cfg: std.json.ObjectMap) StartOutcome {+ defer if (ctx.ready) |flag| flag.store(true, .release);var outcome: StartOutcome = .{};var arena_state = std.heap.ArenaAllocator.init(ctx.gpa);const a = arena_state.allocator();@@ -108,50 +129,32 @@ pub fn init(gpa: Allocator, io: Io, config_path: []const u8, global_path: ?[]contry entries.append(a, .{ .name = try a.dupe(u8, entry.key_ptr.*), .cfg = entry.value_ptr.*.object });}- const futures = try gpa.alloc(Io.Future(StartOutcome), entries.items.len);+ const futures = try gpa.alloc(PendingStart, entries.items.len);+ @memset(futures, .{});+ reg.pending_starts = futures; // errdefer must join every launched taskconst started_names = try a.alloc([]const u8, entries.items.len);- // concurrent, not async: io.async may run the handshake inline, so two- // remote servers paid SUM(latency) instead of max(latency) at REPL start.- // defer_join must not take that fallback — inline handshake is the TUI hang.- const ctx = StartCtx{- .gpa = gpa,- .io = io,- .home = home,- .show_diagnostics = show_diagnostics,- .stdio_probe = reg.stdio_probe,- };+ @memset(started_names, "");+ reg.pending_names = started_names;var started: usize = 0;for (entries.items) |e| {+ const flag = try gpa.create(std.atomic.Value(bool));+ flag.* = .init(false);+ var ctx = startCtx(®);+ ctx.ready = flag;const args = .{ ctx, e.name, e.cfg };- if (io.concurrent(startServerTask, args)) |fut| {- futures[started] = fut;- started_names[started] = e.name;- started += 1;- } else |_| {- if (defer_join) continue;- futures[started] = io.async(startServerTask, args);- started_names[started] = e.name;- started += 1;- }- }- if (defer_join) {- if (started == 0) {- gpa.free(futures);- return reg;- }- if (started < futures.len) {- const slim = try gpa.alloc(Io.Future(StartOutcome), started);- @memcpy(slim, futures[0..started]);- gpa.free(futures);- reg.pending_starts = slim;- } else {- reg.pending_starts = futures;- }- reg.pending_names = started_names[0..started];- return reg;+ const fut = io.concurrent(startServerTask, args) catch blk: {+ if (defer_join) {+ gpa.destroy(flag);+ continue;+ }+ break :blk io.async(startServerTask, args);+ };+ futures[started] = .{ .future = fut, .ready = flag };+ started_names[started] = e.name;+ started += 1;}- defer gpa.free(futures);- mergeOutcomes(®, futures[0..started]);+ if (defer_join) return reg;+ _ = joinPending(®);return reg;}@@ -184,25 +187,36 @@ pub fn queueStdio(reg: *Registry, name: []const u8, command: []const u8, args: [var argv = std.json.Array.init(a);for (args) |arg| argv.append(.{ .string = a.dupe(u8, arg) catch return }) catch return;cfg.put(a, "args", .{ .array = argv }) catch return;- const fut = reg.io.concurrent(startServerTask, .{ startCtx(reg), n, cfg }) catch return;- appendPending(reg, fut, n);-}--fn appendPending(reg: *Registry, fut: Io.Future(StartOutcome), name: []const u8) void {+ // Reserve both paired arrays before spawning: allocation failure must not+ // abandon a task that still borrows registry configuration.const old = reg.pending_starts;- const next = reg.gpa.alloc(Io.Future(StartOutcome), old.len + 1) catch return;+ const next = reg.gpa.alloc(PendingStart, old.len + 1) catch return;+ const names = a.alloc([]const u8, old.len + 1) catch {+ reg.gpa.free(next);+ return;+ };+ const flag = reg.gpa.create(std.atomic.Value(bool)) catch {+ reg.gpa.free(next);+ return;+ };+ flag.* = .init(false);+ var ctx = startCtx(reg);+ ctx.ready = flag;+ const fut = reg.io.concurrent(startServerTask, .{ ctx, n, cfg }) catch {+ reg.gpa.destroy(flag);+ reg.gpa.free(next);+ return;+ };@memcpy(next[0..old.len], old);- next[old.len] = fut;+ next[old.len] = .{ .future = fut, .ready = flag };+ @memcpy(names[0..old.len], reg.pending_names);+ names[old.len] = n;if (old.len > 0) reg.gpa.free(old);reg.pending_starts = next;- const a = reg.arena();- const names = a.alloc([]const u8, reg.pending_names.len + 1) catch return;- @memcpy(names[0..reg.pending_names.len], reg.pending_names);- names[reg.pending_names.len] = name;reg.pending_names = names;}-fn mergeOutcomes(reg: *Registry, futures: []Io.Future(StartOutcome)) void {+fn mergeOutcomes(reg: *Registry, futures: []PendingStart) void {const a = reg.arena();var servers: std.ArrayList(*mcp_rpc.Server) = .empty;var tools: std.ArrayList(mcp.Tool) = .empty;@@ -211,7 +225,7 @@ fn mergeOutcomes(reg: *Registry, futures: []Io.Future(StartOutcome)) void {tools.appendSlice(a, reg.tools) catch {};task_arenas.appendSlice(a, reg.task_arenas) catch {};for (futures) |*fut| {- const outcome = fut.await(reg.io);+ const outcome = fut.awaitResult(reg);const server = outcome.server orelse continue;// A companion (eager codedb-pro) or /mcp trust can connect this server// while its deferred start is still in flight. Appending the outcome@@ -277,7 +291,7 @@ fn noteMcpDeferred(io: Io) void {}/// First model call: do not wait for deferred MCP handshakes (ADR 0035).-/// Later requests, `/mcp`, and teardown still `joinPending`.+/// Later requests only consume ready outcomes; `/mcp` and teardown may wait.pub fn joinBeforeRequest(reg: *Registry) bool {switch (firstRequestJoin(reg.pending_starts.len, ®.first_request_join_skipped)) {.none => return false,@@ -285,8 +299,36 @@ pub fn joinBeforeRequest(reg: *Registry) bool {noteMcpDeferred(reg.io);return false;},- .join => return joinPending(reg),+ .join => return joinReady(reg),+ }+}++/// Compact unfinished tasks in place without changing their flag addresses.+/// No unfinished handshake is ever awaited on the request path.+pub fn joinReady(reg: *Registry) bool {+ const pending = reg.pending_starts;+ var merged = false;+ for (pending, 0..) |*task, i| {+ if (task.ready == null or !task.finished()) continue;+ mergeOutcomes(reg, pending[i..][0..1]);+ merged = true;+ }+ // Keep the allocation until every task is consumed; names for consumed+ // slots are blanked so failed connections can be retried while others wait.+ var waiting = false;+ for (pending, 0..) |task, i| {+ if (task.ready != null) {+ waiting = true;+ } else if (i < reg.pending_names.len) {+ @constCast(reg.pending_names)[i] = "";+ }}+ if (!waiting and pending.len > 0) {+ reg.gpa.free(pending);+ reg.pending_starts = &.{};+ reg.pending_names = &.{};+ }+ return merged;}/// Await deferred startServer tasks and append them to the live registry@@ -320,7 +362,7 @@ test "MCP boot fans server handshakes out with io.concurrent" {test "defer_join does not fall back to inline io.async" {const src = @embedFile("mcp_boot.zig");- try std.testing.expect(std.mem.indexOf(u8, src, "if (defer_join) continue") != null);+ try std.testing.expect(std.mem.indexOf(u8, src, "gpa.destroy(flag);") != null);}test "alreadyStarting sees pending names before the handshake finishes" {@@ -365,3 +407,37 @@ test "oneshotSkipsImportedMcp is lean -p with no project .mcp.json" {try std.testing.expect(!oneshotSkipsImportedMcp(true, false, 0)); // --no-leantry std.testing.expect(!oneshotSkipsImportedMcp(false, true, 0)); // REPL}++test "#860 later requests leave unfinished handshakes queued and consume ready tasks" {+ const a = std.testing.allocator;+ const io = std.testing.io;+ var reg = Registry.empty(a, io);+ defer reg.deinit();+ var release_task: Io.Event = .unset;+ defer release_task.set(io);+ const flag = try a.create(std.atomic.Value(bool));+ flag.* = .init(false);+ reg.pending_starts = try a.alloc(PendingStart, 2);+ @memset(reg.pending_starts, .{});+ reg.pending_names = try reg.arena().dupe([]const u8, &.{ "slow", "ready" });+ const Task = struct {+ fn run(task_io: Io, release: *Io.Event, done: *std.atomic.Value(bool)) StartOutcome {+ defer done.store(true, .release);+ release.waitTimeout(task_io, .{ .duration = .{ .raw = .fromSeconds(5), .clock = .awake } }) catch {};+ return .{};+ }+ };+ reg.pending_starts[0] = .{ .future = try io.concurrent(Task.run, .{ io, &release_task, flag }), .ready = flag };+ const ready = try a.create(std.atomic.Value(bool));+ ready.* = .init(true);+ reg.pending_starts[1].ready = ready;+ try std.testing.expect(!joinBeforeRequest(®));+ try std.testing.expect(joinBeforeRequest(®));+ try std.testing.expect(!flag.load(.acquire));+ try std.testing.expect(alreadyStarting(®, "slow"));+ try std.testing.expect(!alreadyStarting(®, "ready"));+ try std.testing.expect(!joinBeforeRequest(®));+ release_task.set(io);+ try std.testing.expect(joinPending(®));+ try std.testing.expectEqual(@as(usize, 0), reg.pending_starts.len);+}diff --git a/src/pr_command.zig b/src/pr_command.zignew file mode 100644index 00000000..d054cf59--- /dev/null+++ b/src/pr_command.zig@@ -0,0 +1,121 @@+//! Literal GitHub CLI arguments. Dynamic shell expressions cannot be vouched+//! for before execution; publish those separately with explicit arguments.+const std = @import("std");+const A = std.mem.Allocator;+pub const Command = struct {+ argv: []const []const u8,+ verb: []const u8,+ cwd: ?[]const u8 = null,++ pub fn flag(self: Command, long: []const u8, short: []const u8) ?[]const u8 {+ for (self.argv, 0..) |arg, i| {+ if (std.mem.eql(u8, arg, long) or (short.len > 0 and std.mem.eql(u8, arg, short)))+ return if (i + 1 < self.argv.len) self.argv[i + 1] else null;+ if (std.mem.startsWith(u8, arg, long) and arg.len > long.len and arg[long.len] == '=') return arg[long.len + 1 ..];+ }+ return null;+ }+ pub fn draft(self: Command) bool {+ var i: usize = 0;+ while (i < self.argv.len) : (i += 1) {+ const arg = self.argv[i];+ if (takesValue(arg)) {+ i += 1;+ continue;+ }+ if (std.mem.eql(u8, arg, "--draft") or std.mem.eql(u8, arg, "--draft=true")) return true;+ }+ return false;+ }+ pub fn has(self: Command, flag_name: []const u8) bool {+ var i: usize = 0;+ while (i < self.argv.len) : (i += 1) {+ if (takesValue(self.argv[i])) {+ i += 1;+ continue;+ }+ if (std.mem.eql(u8, self.argv[i], flag_name)) return true;+ }+ return false;+ }+ pub fn selector(self: Command) ?[]const u8 {+ for (self.argv, 0..) |arg, i| {+ if (std.mem.eql(u8, arg, self.verb) and i + 1 < self.argv.len and !std.mem.startsWith(u8, self.argv[i + 1], "-")) return self.argv[i + 1];+ }+ return null;+ }+};++fn takesValue(arg: []const u8) bool {+ for ([_][]const u8{ "--body", "-b", "--body-file", "-F", "--title", "-t", "--head", "-H", "--base", "-B", "--repo", "-R", "--reviewer", "-r", "--assignee", "-a", "--label", "-l", "--milestone", "-m", "--project", "-p", "--template", "-T" }) |flag| if (std.mem.eql(u8, arg, flag)) return true;+ return false;+}++pub fn parse(a: A, input: []const u8) !Command {+ var args: std.ArrayList([]const u8) = .empty;+ var i: usize = 0;+ while (i < input.len) {+ while (i < input.len and std.ascii.isWhitespace(input[i])) : (i += 1) {+ if (input[i] == '\n' or input[i] == '\r') return error.CompoundCommand;+ }+ if (i == input.len) break;+ const start = i;+ var word: std.ArrayList(u8) = .empty;+ var quote: u8 = 0;+ while (i < input.len) : (i += 1) {+ const c = input[i];+ if (quote == 0 and std.ascii.isWhitespace(c)) break;+ if (quote == 0 and c == '&') {+ if (i != start or i + 1 >= input.len or input[i + 1] != '&' or (i + 2 < input.len and !std.ascii.isWhitespace(input[i + 2]))) return error.CompoundCommand;+ try word.appendSlice(a, "&&");+ i += 2;+ break;+ }+ if (quote != '\'' and (c == '$' or c == '`')) return error.DynamicCommand;+ if (quote == 0 and std.mem.indexOfScalar(u8, "|;<>\n\r()#", c) != null) return error.CompoundCommand;+ if (c == '\\' and quote != '\'') {+ i += 1;+ if (i == input.len) return error.IncompleteEscape;+ try word.append(a, input[i]);+ } else if (c == quote) {+ quote = 0;+ } else if (quote == 0 and (c == '\'' or c == '"')) {+ quote = c;+ } else try word.append(a, c);+ }+ if (quote != 0) return error.UnclosedQuote;+ try args.append(a, try word.toOwnedSlice(a));+ }+ var t = args.items;+ var cwd: ?[]const u8 = null;+ if (t.len >= 3 and std.mem.eql(u8, t[0], "cd") and std.mem.eql(u8, t[2], "&&")) {+ cwd = t[1];+ t = t[3..];+ }+ if (t.len == 0 or !std.mem.eql(u8, std.fs.path.basename(t[0]), "gh")) return error.UnsupportedCommand;+ for (t) |arg| if (std.mem.eql(u8, arg, "&&") or std.mem.eql(u8, arg, "&")) return error.CompoundCommand;+ var j: usize = 1;+ while (j < t.len) : (j += 1) {+ if (std.mem.eql(u8, t[j], "-R") or std.mem.eql(u8, t[j], "--repo")) {+ j += 1;+ continue;+ }+ if (std.mem.eql(u8, t[j], "pr") and j + 1 < t.len) return .{ .argv = t, .verb = t[j + 1], .cwd = cwd };+ return error.UnsupportedCommand;+ }+ return error.UnsupportedCommand;+}++test "PR arguments keep body flags opaque and resolve repository and target" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const c = try parse(arena.allocator(), "cd 'project space' && gh -R owner/repo pr create --head feature --body 'text --draft' --body-file notes.md");+ try std.testing.expect(!c.draft());+ try std.testing.expectEqualStrings("feature", c.flag("--head", "-H").?);+ try std.testing.expectEqualStrings("text --draft", c.flag("--body", "-b").?);+ try std.testing.expectEqualStrings("notes.md", c.flag("--body-file", "-F").?);+ try std.testing.expectError(error.DynamicCommand, parse(arena.allocator(), "gh pr create --body \"$BODY\""));+ try std.testing.expectError(error.CompoundCommand, parse(arena.allocator(), "git commit -m x; gh pr create"));+ try std.testing.expectError(error.CompoundCommand, parse(arena.allocator(), "gh pr create --body x\necho other"));+ try std.testing.expectError(error.CompoundCommand, parse(arena.allocator(), "gh pr create --body x&echo other"));+}diff --git a/src/pr_evidence.zig b/src/pr_evidence.zignew file mode 100644index 00000000..1cf84ac8--- /dev/null+++ b/src/pr_evidence.zig@@ -0,0 +1,113 @@+//! Fresh, bounded GitHub observations. CLI prose and local tests are never a+//! receipt for a remote PR head. Missing data is unknown, not an empty run list.+const std = @import("std");+const runner = @import("process_runner.zig");+const publish = @import("pr_publish.zig");+const A = std.mem.Allocator;+pub const Target = struct { cwd: []const u8 = ".", repo: ?[]const u8 = null, selector: []const u8 };+pub const Receipt = struct { head: []const u8 = "", status: publish.HeadStatus = .unknown, draft: bool = false, body: []const u8 = "" };++pub fn capture(gpa: A, io: std.Io, a: A, target: Target, argv: []const []const u8) ![]const u8 {+ var args: std.ArrayList([]const u8) = .empty;+ try args.appendSlice(a, argv);+ if (std.mem.eql(u8, argv[0], "gh")) if (target.repo) |repo| try args.appendSlice(a, &.{ "--repo", repo });+ const r = try runner.runCappedWithOptions(gpa, io, args.items, 256 * 1024, 2048, 15_000, .{ .cwd = .{ .path = target.cwd } });+ defer gpa.free(r.stdout);+ defer gpa.free(r.stderr);+ if (!runner.ranOk(r) or r.stdout_truncated or r.stderr_truncated) return error.EvidenceUnavailable;+ return a.dupe(u8, std.mem.trim(u8, r.stdout, " \r\n\t"));+}++pub fn localHead(gpa: A, io: std.Io, a: A, target: Target) ![]const u8 {+ const sha = try capture(gpa, io, a, target, &.{ "git", "rev-parse", "--verify", "HEAD" });+ if (!validSha(sha)) return error.InvalidHead;+ return sha;+}++/// --head selects an already-pushed remote branch, not the local checkout.+pub fn remoteHead(gpa: A, io: std.Io, a: A, target: Target, head: []const u8) ![]const u8 {+ if (std.mem.indexOfAny(u8, head, ":?%#") != null) return error.UnsupportedHead;+ const endpoint = try std.fmt.allocPrint(a, "repos/{s}/git/ref/heads/{s}", .{ target.repo orelse "{owner}/{repo}", head });+ var api_target = target;+ api_target.repo = null; // gh api selects the repository in its endpoint+ const sha = try capture(gpa, io, a, api_target, &.{ "gh", "api", endpoint, "--jq", ".object.sha" });+ if (!validSha(sha)) return error.InvalidHead;+ return sha;+}++pub fn validSha(sha: []const u8) bool {+ if (sha.len != 40 and sha.len != 64) return false;+ for (sha) |c| if (!std.ascii.isHex(c)) return false;+ return true;+}++pub fn pr(gpa: A, io: std.Io, a: A, target: Target) !Receipt {+ const json = try capture(gpa, io, a, target, &.{ "gh", "pr", "view", target.selector, "--json", "headRefOid,isDraft,body,statusCheckRollup" });+ return parsePr(a, json);+}++pub fn parsePr(a: A, json: []const u8) !Receipt {+ const v = try std.json.parseFromSliceLeaky(std.json.Value, a, json, .{});+ if (v != .object) return error.InvalidReceipt;+ const head = v.object.get("headRefOid") orelse return error.InvalidReceipt;+ const draft = v.object.get("isDraft") orelse return error.InvalidReceipt;+ const body = v.object.get("body") orelse return error.InvalidReceipt;+ const checks = v.object.get("statusCheckRollup") orelse return error.InvalidReceipt;+ if (head != .string or !validSha(head.string) or draft != .bool or body != .string) return error.InvalidReceipt;+ return .{ .head = head.string, .draft = draft.bool, .body = body.string, .status = checkStatus(checks) };+}++pub fn checkStatus(checks: std.json.Value) publish.HeadStatus {+ if (checks != .array) return .unknown;+ if (checks.array.items.len == 0) return .none;+ var pending = false;+ var passed = false;+ var unknown = false;+ for (checks.array.items) |item| {+ if (item != .object) {+ unknown = true;+ continue;+ }+ const state = text(item, "state");+ const status = text(item, "status");+ const conclusion = text(item, "conclusion");+ if (eq(state, "FAILURE") or eq(state, "ERROR") or eq(conclusion, "FAILURE") or eq(conclusion, "CANCELLED") or eq(conclusion, "TIMED_OUT") or eq(conclusion, "ACTION_REQUIRED") or eq(conclusion, "STALE") or eq(conclusion, "STARTUP_FAILURE")) return .failed;+ if (eq(state, "PENDING") or eq(status, "IN_PROGRESS") or eq(status, "QUEUED") or eq(status, "WAITING") or eq(status, "PENDING") or eq(status, "REQUESTED")) {+ pending = true;+ continue;+ }+ if (eq(state, "SUCCESS") or (eq(status, "COMPLETED") and eq(conclusion, "SUCCESS"))) {+ passed = true;+ continue;+ }+ if (eq(status, "COMPLETED") and (eq(conclusion, "SKIPPED") or eq(conclusion, "NEUTRAL"))) continue;+ unknown = true;+ }+ if (unknown) return .unknown;+ if (pending) return .pending;+ return if (passed) .passed else .unknown;+}+fn text(v: std.json.Value, key: []const u8) []const u8 {+ const field = v.object.get(key) orelse return "";+ return if (field == .string) field.string else "";+}+fn eq(a: []const u8, b: []const u8) bool {+ return std.mem.eql(u8, a, b);+}++test "#853 remote receipt cannot turn missing, pending, failed or partial checks into verified" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const cases = .{+ .{ "null", publish.HeadStatus.unknown },+ .{ "[]", publish.HeadStatus.none },+ .{ "[{\"status\":\"COMPLETED\",\"conclusion\":\"SUCCESS\"}]", publish.HeadStatus.passed },+ .{ "[{\"status\":\"COMPLETED\",\"conclusion\":\"SUCCESS\"},{}]", publish.HeadStatus.unknown },+ .{ "[{\"state\":\"SUCCESS\"},{\"state\":\"PENDING\"}]", publish.HeadStatus.pending },+ .{ "[{\"state\":\"SUCCESS\"},{\"state\":\"FAILURE\"}]", publish.HeadStatus.failed },+ };+ inline for (cases) |c| {+ const v = try std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), c[0], .{});+ try std.testing.expectEqual(c[1], checkStatus(v));+ }+}diff --git a/src/pr_publish.zig b/src/pr_publish.zigindex 8f284906..45da8990 100644--- a/src/pr_publish.zig+++ b/src/pr_publish.zig@@ -16,7 +16,7 @@ pub const Coverage = struct {pub const Evidence = struct {head_sha: []const u8 = "",- head_status: HeadStatus = .none,+ head_status: HeadStatus = .unknown,base_reproduced: bool = false,known_failures_disclosed: bool = false,body: []const u8 = "",@@ -37,12 +37,15 @@ fn seqAfter(cmd: []const u8, first: []const u8, second: []const u8, third: []convar it = std.mem.tokenizeAny(u8, cmd, " \t\r\n;&|\"'`()");var state: u8 = 0;while (it.next()) |tok| {- if (state == 0 and std.mem.eql(u8, tok, first)) {+ if (state == 0 and std.mem.eql(u8, std.fs.path.basename(tok), first)) {state = 1;continue;}if (state == 1) {- if (tok[0] == '-') continue;+ if (tok[0] == '-') {+ if (std.mem.eql(u8, tok, "-R") or std.mem.eql(u8, tok, "--repo")) _ = it.next();+ continue;+ }if (std.mem.eql(u8, tok, second)) {state = 2;continue;@@ -51,8 +54,12 @@ fn seqAfter(cmd: []const u8, first: []const u8, second: []const u8, third: []concontinue;}if (state == 2) {- if (tok[0] == '-') continue;- return std.mem.eql(u8, tok, third);+ if (tok[0] == '-') {+ if (std.mem.eql(u8, tok, "-R") or std.mem.eql(u8, tok, "--repo")) _ = it.next();+ continue;+ }+ if (std.mem.eql(u8, tok, third)) return true;+ state = 0;}}return false;@@ -63,7 +70,12 @@ pub fn isPrCreate(cmd: []const u8) bool {}pub fn isPrReady(cmd: []const u8) bool {- if (seqAfter(cmd, "gh", "pr", "ready")) return true;+ if (seqAfter(cmd, "gh", "pr", "ready")) {+ var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);+ defer arena.deinit();+ const parsed = @import("pr_command.zig").parse(arena.allocator(), cmd) catch return true;+ return !parsed.has("--undo");+ }if (!seqAfter(cmd, "gh", "pr", "edit")) return false;return std.mem.indexOf(u8, cmd, "--draft=false") != null or std.mem.indexOf(u8, cmd, "--draft false") != null;}@@ -73,37 +85,31 @@ pub fn isPrChecksWatch(cmd: []const u8) bool {}pub fn isDraftFlag(cmd: []const u8) bool {- if (std.mem.indexOf(u8, cmd, "--draft=false") != null) return false;- var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n;&|\"'`()");- while (it.next()) |tok| {- if (std.mem.eql(u8, tok, "--draft") or std.mem.eql(u8, tok, "--draft=true")) return true;- }- return false;+ var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);+ defer arena.deinit();+ const parsed = @import("pr_command.zig").parse(arena.allocator(), cmd) catch return false;+ return parsed.draft();}pub fn isNonDraftPublish(cmd: []const u8) bool {- if (isPrChecksWatch(cmd)) return false;if (isPrCreate(cmd)) return !isDraftFlag(cmd);return isPrReady(cmd);}-fn flagValue(cmd: []const u8, flag: []const u8) []const u8 {- const idx = std.mem.indexOf(u8, cmd, flag) orelse return "";- var rest = std.mem.trimStart(u8, cmd[idx + flag.len ..], " \t=");- if (rest.len == 0) return "";- if (rest[0] == '"' or rest[0] == '\'') {- const q = rest[0];- const end = std.mem.indexOfScalar(u8, rest[1..], q) orelse return rest[1..];- return rest[1 .. 1 + end];- }- const end = std.mem.indexOfAny(u8, rest, " \t") orelse rest.len;- return rest[0..end];-}-pub fn extractBody(cmd: []const u8) []const u8 {- const from_body = flagValue(cmd, "--body");- if (from_body.len > 0) return from_body;- return flagValue(cmd, "-b");+ // Keep this legacy pure helper for tests; production uses pr_command and+ // reads --body-file through the bounded evidence gatherer.+ for ([_][]const u8{ "--body ", "-b " }) |flag| {+ const index = std.mem.indexOf(u8, cmd, flag) orelse continue;+ const rest = std.mem.trimStart(u8, cmd[index + flag.len ..], " ");+ if (rest.len == 0) return "";+ if (rest[0] == '"' or rest[0] == '\'') {+ const end = std.mem.indexOfScalar(u8, rest[1..], rest[0]) orelse return "";+ return rest[1..][0..end];+ }+ return rest[0 .. std.mem.indexOfAny(u8, rest, " \t") orelse rest.len];+ }+ return "";}pub fn hasVerificationSection(body: []const u8) bool {@@ -189,30 +195,45 @@ pub fn reason(decision: Decision, ev: Evidence) []const u8 {};}-/// Classify `gh run list --json conclusion,status` output. Empty / unreadable-/// JSON is `none` so PR-only workflows stay allowed.+/// Only a successfully parsed empty array means no pre-PR runs.pub fn headStatusFromRunList(json: []const u8) HeadStatus {- const trimmed = std.mem.trim(u8, json, " \t\r\n");- if (trimmed.len == 0 or trimmed[0] != '[') return .none;- const parsed = std.json.parseFromSlice(std.json.Value, std.heap.page_allocator, trimmed, .{}) catch return .none;+ const parsed = std.json.parseFromSlice(std.json.Value, std.heap.page_allocator, json, .{}) catch return .unknown;defer parsed.deinit();- if (parsed.value != .array) return .none;+ if (parsed.value != .array) return .unknown;if (parsed.value.array.items.len == 0) return .none;var pending = false;var passed = false;+ var unknown = false;for (parsed.value.array.items) |item| {- if (item != .object) continue;- const status = if (item.object.get("status")) |v| (if (v == .string) v.string else "") else "";- const conclusion = if (item.object.get("conclusion")) |v| (if (v == .string) v.string else "") else "";- if (std.mem.eql(u8, status, "in_progress") or std.mem.eql(u8, status, "queued") or std.mem.eql(u8, status, "waiting") or std.mem.eql(u8, status, "pending"))- pending = true;- if (std.mem.eql(u8, conclusion, "failure") or std.mem.eql(u8, conclusion, "cancelled") or std.mem.eql(u8, conclusion, "timed_out") or std.mem.eql(u8, conclusion, "startup_failure"))- return .failed;- if (std.mem.eql(u8, conclusion, "success")) passed = true;+ if (item != .object) {+ unknown = true;+ continue;+ }+ const sv = item.object.get("status") orelse {+ unknown = true;+ continue;+ };+ const cv = item.object.get("conclusion") orelse {+ unknown = true;+ continue;+ };+ if (sv != .string or (cv != .string and cv != .null)) {+ unknown = true;+ continue;+ }+ const status = sv.string;+ const conclusion = if (cv == .string) cv.string else "";+ for ([_][]const u8{ "failure", "cancelled", "timed_out", "startup_failure", "action_required", "stale" }) |failure|+ if (std.mem.eql(u8, conclusion, failure)) return .failed;+ if (!std.mem.eql(u8, status, "completed")) {+ if (std.mem.eql(u8, status, "in_progress") or std.mem.eql(u8, status, "queued") or std.mem.eql(u8, status, "waiting") or std.mem.eql(u8, status, "pending") or std.mem.eql(u8, status, "requested")) pending = true else unknown = true;+ } else if (std.mem.eql(u8, conclusion, "success")) {+ passed = true;+ } else if (!std.mem.eql(u8, conclusion, "skipped") and !std.mem.eql(u8, conclusion, "neutral")) unknown = true;}+ if (unknown) return .unknown;if (pending) return .pending;- if (passed) return .passed;- return .unknown;+ return if (passed) .passed else .unknown;}pub fn refuseText(arena: Allocator, cmd: []const u8, ev: Evidence) []const u8 {@@ -247,7 +268,6 @@ pub fn evidenceFor(cmd: []const u8) Evidence {}pub fn gateCommand(arena: Allocator, cmd: []const u8) ?[]const u8 {- if (isPrChecksWatch(cmd)) return null;if (!isPrCreate(cmd) and !isPrReady(cmd)) return null;const ev = evidenceFor(cmd);const draft = isDraftFlag(cmd) and !isPrReady(cmd);@@ -344,7 +364,7 @@ test "#847 run-list JSON maps failed, pending, passed, and empty" {\\[{"conclusion":"success","status":"completed"}]));try std.testing.expectEqual(HeadStatus.none, headStatusFromRunList("[]"));- try std.testing.expectEqual(HeadStatus.none, headStatusFromRunList(""));+ try std.testing.expectEqual(HeadStatus.unknown, headStatusFromRunList(""));}test "extractBody reads --body quoted text" {@@ -352,3 +372,11 @@ test "extractBody reads --body quoted text" {try std.testing.expect(hasVerificationSection("## Verification\nran zig build test"));try std.testing.expect(hasAbsoluteClaim("atomic delete is preserved"));}++test "#847 compound checks cannot hide a later publication and ready undo stays available" {+ try std.testing.expect(isPrCreate("gh pr checks --watch && gh pr create --title t --body b"));+ try std.testing.expect(isNonDraftPublish("gh pr checks --watch && gh pr create --title t --body b"));+ try std.testing.expect(isPrCreate("/usr/local/bin/gh -R owner/repo pr create --body x"));+ try std.testing.expect(!isPrReady("gh pr ready --undo"));+ try std.testing.expect(!isDraftFlag("gh pr create --body '--draft'"));+}diff --git a/src/pr_verify.zig b/src/pr_verify.zignew file mode 100644index 00000000..f30591fc--- /dev/null+++ b/src/pr_verify.zig@@ -0,0 +1,92 @@+//! Publication creates a durable verification obligation separate from todos.+//! A fresh remote observation is required at every completion attempt.+const std = @import("std");+const evidence = @import("pr_evidence.zig");+const Agent = @import("agent.zig").Agent;+const A = std.mem.Allocator;+pub const State = enum { unused, pending, draft, passed };+const Record = struct { session: []const u8 = "", target: evidence.Target, match_local: bool = true };+const rel = ".graff/pr-verification.json";++fn path(a: A, cwd: []const u8) ![]const u8 {+ return std.fs.path.join(a, &.{ cwd, rel });+}++/// Written before the command is allowed. A failed publication remains+/// unresolved until a real PR is found or the user explicitly changes scope.+pub fn arm(agent: *Agent, target: evidence.Target, match_local: bool) !void {+ const file = try path(agent.arena, agent.agent_cwd orelse ".");+ const tx = try @import("repo_transaction.zig").Transaction.begin(agent.io, agent.arena, file);+ defer tx.end();+ var records: std.ArrayList(Record) = .empty;+ const existing = try tx.read();+ if (existing) |json| {+ const parsed = try std.json.parseFromSliceLeaky([]Record, agent.arena, json, .{});+ try records.appendSlice(agent.arena, parsed);+ }+ const session = @import("http_headers.zig").sessionId(agent.io);+ var found = false;+ for (records.items) |r| if (std.mem.eql(u8, r.session, session) and std.mem.eql(u8, r.target.selector, target.selector) and std.mem.eql(u8, r.target.repo orelse "", target.repo orelse "")) {+ found = true;+ break;+ };+ if (!found) try records.append(agent.arena, .{ .session = session, .target = target, .match_local = match_local });+ if (records.items.len > 32) return error.TooManyPendingPRs;+ const json = try std.json.Stringify.valueAlloc(agent.arena, records.items, .{});+ try tx.write(json);+ agent.pr_verification = .pending;+}++pub fn decision(receipt: evidence.Receipt, local: ?[]const u8) State {+ if (local) |sha| if (!std.mem.eql(u8, sha, receipt.head)) return .pending;+ if (receipt.draft) return .draft;+ return if (receipt.status == .passed) .passed else .pending;+}++pub fn completionGate(agent: *Agent) ?[]const u8 {+ if (agent.review_mode) return null;+ const cwd = agent.agent_cwd orelse ".";+ const file = path(agent.arena, cwd) catch return "completion deferred: unable to read PR verification obligation";+ const json = std.Io.Dir.cwd().readFileAlloc(agent.io, file, agent.arena, .limited(64 * 1024)) catch |err| switch (err) {+ error.FileNotFound => return null,+ else => return "completion deferred: PR verification obligation is unreadable",+ };+ agent.pr_verification = .pending;+ const records = std.json.parseFromSliceLeaky([]Record, agent.arena, json, .{}) catch return "completion deferred: PR verification obligation is malformed";+ if (records.len == 0 or records.len > 32) return "completion deferred: PR verification obligation is incomplete";+ var result: State = .passed;+ for (records) |record| {+ if (!std.mem.eql(u8, record.session, @import("http_headers.zig").sessionId(agent.io))) continue;+ const receipt = evidence.pr(agent.gpa, agent.io, agent.arena, record.target) catch return "completion deferred: current-head PR checks could not be observed. Local tests and completed todos are not remote CI evidence; retry the lookup or leave an explicit draft handoff.";+ const local = if (record.match_local) evidence.localHead(agent.gpa, agent.io, agent.arena, record.target) catch return "completion deferred: local publication head could not be resolved" else null;+ switch (decision(receipt, local)) {+ .pending, .unused => return "completion deferred: current-head PR verification is pending, failed, missing, or stale. Inspect the PR checks and finish CI verification; repeating attempt_completion cannot waive it. An explicit draft PR can be handed off as unverified.",+ .draft => result = .draft,+ .passed => {},+ }+ }+ agent.pr_verification = result;+ return null;+}++test "#853 a changed head or a second completion attempt cannot reuse a passing receipt" {+ const receipt = evidence.Receipt{ .head = "new", .status = .passed };+ try std.testing.expectEqual(State.pending, decision(receipt, "old"));+ try std.testing.expectEqual(State.passed, decision(receipt, "new"));+ for (0..2) |_| try std.testing.expectEqual(State.pending, decision(.{ .head = "new", .status = .pending }, "new"));+ try std.testing.expectEqual(State.draft, decision(.{ .head = "new", .status = .failed, .draft = true }, "new"));+}++pub fn hasObligation(agent: *const Agent) bool {+ const file = path(agent.arena, agent.agent_cwd orelse ".") catch return true;+ const json = std.Io.Dir.cwd().readFileAlloc(agent.io, file, agent.arena, .limited(64 * 1024)) catch |err| return err != error.FileNotFound;+ const records = std.json.parseFromSliceLeaky([]Record, agent.arena, json, .{}) catch return true;+ for (records) |record| if (std.mem.eql(u8, record.session, @import("http_headers.zig").sessionId(agent.io))) return true;+ return false;+}++pub fn taskVerified(agent: *const Agent) bool {+ if (!hasObligation(agent)) return true;+ if (agent.pr_verification != .passed) return false;+ return completionGate(@constCast(agent)) == null and agent.pr_verification == .passed;+}diff --git a/src/publish_gate.zig b/src/publish_gate.zigindex 8297a354..2221587a 100644--- a/src/publish_gate.zig+++ b/src/publish_gate.zig@@ -10,41 +10,81 @@ const tools_mod = @import("tools.zig");const ExecResult = tools_mod.ExecResult;const artifact_claim = @import("artifact_claim.zig");const pr_publish = @import("pr_publish.zig");-const process_runner = @import("process_runner.zig");-fn primeHead(self: *Agent) void {- if (builtin.is_test or pr_publish.testEvidence() != null) return;- const sha_run = process_runner.runCapped(self.gpa, self.io, &.{ "git", "rev-parse", "HEAD" }, 128, 256, 5_000) catch return;- defer self.gpa.free(sha_run.stdout);- defer self.gpa.free(sha_run.stderr);- if (!process_runner.ranOk(sha_run)) return;- const sha = std.mem.trim(u8, sha_run.stdout, " \t\r\n");- if (sha.len < 7) return;- const sha_owned = self.arena.dupe(u8, sha) catch return;- const list_run = process_runner.runCapped(self.gpa, self.io, &.{- "gh", "run", "list",- "--commit", sha_owned, "--json",- "conclusion,status", "--limit", "20",- }, 16 * 1024, 1024, 15_000) catch {- pr_publish.setTestEvidence(.{ .head_sha = sha_owned, .head_status = .none });- return;- };- defer self.gpa.free(list_run.stdout);- defer self.gpa.free(list_run.stderr);- const status = if (process_runner.ranOk(list_run)) pr_publish.headStatusFromRunList(list_run.stdout) else .none;- pr_publish.setTestEvidence(.{ .head_sha = sha_owned, .head_status = status });+fn observe(self: *Agent, cmd: []const u8) !?ExecResult {+ const command = @import("pr_command.zig").parse(self.arena, cmd) catch return .{ .text = "PR publication preflight: the write was NOT performed. Use a separate literal gh pr command so its repository, head, draft flag and body can be verified.", .is_error = true };+ const evmod = @import("pr_evidence.zig");+ var target = evmod.Target{ .cwd = command.cwd orelse self.agent_cwd orelse ".", .repo = command.flag("--repo", "-R"), .selector = command.flag("--head", "-H") orelse "" };+ if (command.cwd != null and self.agent_cwd != null and !std.fs.path.isAbsolute(target.cwd)) target.cwd = try std.fs.path.join(self.arena, &.{ self.agent_cwd.?, target.cwd });+ var dir = try std.Io.Dir.cwd().openDir(self.io, target.cwd, .{});+ defer dir.close(self.io);+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;+ target.cwd = try self.arena.dupe(u8, path_buf[0..try dir.realPath(self.io, &path_buf)]);+ const creating = std.mem.eql(u8, command.verb, "create");+ if (!creating) target.selector = command.selector() orelse "";+ if (target.selector.len == 0) target.selector = evmod.capture(self.gpa, self.io, self.arena, target, &.{ "git", "branch", "--show-current" }) catch "";+ if (target.selector.len == 0) return .{ .text = "PR publication preflight: cannot resolve the target branch or PR; write NOT performed", .is_error = true };+ var ev: pr_publish.Evidence = .{};+ const draft = creating and command.draft();+ if (!draft) {+ if (creating) {+ ev.head_sha = evmod.localHead(self.gpa, self.io, self.arena, target) catch "";+ // An explicit alternate head must be resolved independently of HEAD.+ if (command.flag("--head", "-H")) |head| {+ ev.head_sha = evmod.remoteHead(self.gpa, self.io, self.arena, target, head) catch "";+ }+ if (evmod.validSha(ev.head_sha)) {+ const json = evmod.capture(self.gpa, self.io, self.arena, target, &.{ "gh", "run", "list", "--commit", ev.head_sha, "--json", "conclusion,status", "--limit", "1000" }) catch "";+ ev.head_status = pr_publish.headStatusFromRunList(json);+ // This cap must not silently hide a failing/pending older run.+ const parsed = std.json.parseFromSliceLeaky(std.json.Value, self.arena, json, .{}) catch .null;+ if (parsed == .array and parsed.array.items.len >= 1000) ev.head_status = .unknown;+ }+ ev.body = command.flag("--body", "-b") orelse "";+ if (command.flag("--body-file", "-F")) |body_file| {+ const file = if (std.fs.path.isAbsolute(body_file)) body_file else try std.fs.path.join(self.arena, &.{ target.cwd, body_file });+ ev.body = std.Io.Dir.cwd().readFileAlloc(self.io, file, self.arena, .limited(64 * 1024)) catch "";+ }+ } else {+ const receipt = evmod.pr(self.gpa, self.io, self.arena, target) catch evmod.Receipt{};+ ev = .{ .head_sha = receipt.head, .head_status = receipt.status, .body = receipt.body };+ }+ }+ if (pr_publish.decide(draft, ev) != .allow) return .{ .text = pr_publish.refuseText(self.arena, cmd, ev), .is_error = true };+ @import("pr_verify.zig").arm(self, target, creating and command.flag("--head", "-H") == null) catch return .{ .text = "PR publication preflight: could not persist the CI verification obligation; write NOT performed", .is_error = true };+ return null;}pub fn bash(self: *Agent, cmd: []const u8) !?ExecResult {- if (artifact_claim.gateCommand(self.arena, self.io, cmd, "")) |blocked| return .{- .text = blocked,- .is_error = true,- };- if (!builtin.is_test and (pr_publish.isPrCreate(cmd) or pr_publish.isPrReady(cmd))) primeHead(self);- if (pr_publish.gateCommand(self.arena, cmd)) |blocked| return .{- .text = blocked,- .is_error = true,- };+ const key = if (builtin.is_test) "" else mutationKey(self, cmd);+ if (artifact_claim.gateCommand(self.arena, self.io, cmd, key)) |blocked| return .{ .text = blocked, .is_error = true };+ if (!pr_publish.isPrCreate(cmd) and !pr_publish.isPrReady(cmd)) return null;+ if (!builtin.is_test) return observe(self, cmd);+ if (pr_publish.gateCommand(self.arena, cmd)) |blocked| return .{ .text = blocked, .is_error = true };+ return null;+}++fn mutationKey(self: *Agent, cmd: []const u8) []const u8 {+ if (!artifact_claim.isClaimedMutation(cmd)) return "";+ const ev = @import("pr_evidence.zig");+ const c = @import("pr_command.zig").parse(self.arena, cmd) catch null;+ if (c) |command| {+ if (command.flag("--head", "-H")) |head| return head;+ if (!std.mem.eql(u8, command.verb, "create") and command.selector() != null) return "";+ }+ const cwd = if (c) |command| command.cwd orelse self.agent_cwd orelse "." else self.agent_cwd orelse ".";+ return ev.capture(self.gpa, self.io, self.arena, .{ .cwd = cwd, .selector = "" }, &.{ "git", "branch", "--show-current" }) catch "";+}++/// Recheck at the common bash execution boundary, including RLM host calls.+/// A permission checkpoint earlier in the turn is not a fresh handoff check.+pub fn beforeExec(ctx: tools_mod.ToolCtx, cmd: []const u8) !?tools_mod.ToolOutput {+ if (builtin.is_test) return null;+ if (!artifact_claim.isClaimedMutation(cmd)) return null;+ var scratch = std.heap.ArenaAllocator.init(ctx.gpa);+ defer scratch.deinit();+ var agent: Agent = .{ .gpa = ctx.gpa, .arena = scratch.allocator(), .io = ctx.io, .client = ctx.client, .provider = ctx.provider, .messages = undefined, .sub = ctx.from_sub, .label = "", .out = null, .agent_cwd = ctx.agent_cwd };+ if (try bash(&agent, cmd)) |denied| return .{ .text = try ctx.gpa.dupe(u8, denied.text), .is_error = true };return null;}diff --git a/src/repo_transaction.zig b/src/repo_transaction.zignew file mode 100644index 00000000..5dd9596f--- /dev/null+++ b/src/repo_transaction.zig@@ -0,0 +1,65 @@+//! A stable lock inode and atomic replacement for small workspace ledgers.+//! Unsupported locks, contention, malformed data and I/O failures fail closed.+const std = @import("std");+const Io = std.Io;+const A = std.mem.Allocator;+pub const Transaction = struct {+ file: Io.File,+ path: []const u8,+ io: Io,+ arena: A,++ pub fn begin(io: Io, arena: A, path: []const u8) !Transaction {+ if (std.fs.path.dirname(path)) |parent| try Io.Dir.cwd().createDirPath(io, parent);+ const lock_path = try std.fmt.allocPrint(arena, "{s}.lock", .{path});+ var attempts: usize = 0;+ const lock = while (true) : (attempts += 1) {+ const file = Io.Dir.cwd().createFile(io, lock_path, .{ .truncate = false, .lock = .exclusive, .lock_nonblocking = true }) catch |err| {+ if (err != error.WouldBlock or attempts >= 20) return err;+ try io.sleep(.fromMilliseconds(10), .awake);+ continue;+ };+ break file;+ };+ return .{ .file = lock, .path = path, .io = io, .arena = arena };+ }+ pub fn end(self: Transaction) void {+ self.file.close(self.io);+ }+ pub fn read(self: Transaction) !?[]const u8 {+ return Io.Dir.cwd().readFileAlloc(self.io, self.path, self.arena, .limited(64 * 1024)) catch |err| switch (err) {+ error.FileNotFound => null,+ else => return err,+ };+ }+ pub fn write(self: Transaction, data: []const u8) !void {+ var nonce: [8]u8 = undefined;+ self.io.random(&nonce);+ const tmp = try std.fmt.allocPrint(self.arena, "{s}.{s}.tmp", .{ self.path, std.fmt.bytesToHex(nonce, .lower) });+ defer Io.Dir.cwd().deleteFile(self.io, tmp) catch {};+ {+ const file = try Io.Dir.cwd().createFile(self.io, tmp, .{ .exclusive = true });+ defer file.close(self.io);+ try file.writePositionalAll(self.io, data, 0);+ try file.sync(self.io);+ }+ try Io.Dir.cwd().rename(tmp, Io.Dir.cwd(), self.path, self.io);+ }+};++test "ledger transaction excludes another writer and atomically replaces its content" {+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const a = std.testing.allocator;+ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ const path = try std.fmt.allocPrint(arena.allocator(), ".zig-cache/tmp/{s}/ledger.json", .{tmp.sub_path});+ const first = try Transaction.begin(std.testing.io, arena.allocator(), path);+ defer first.end();+ try std.testing.expectError(error.WouldBlock, Transaction.begin(std.testing.io, arena.allocator(), path));+ try std.testing.expect(try first.read() == null);+ try first.write("one");+ try std.testing.expectEqualStrings("one", (try first.read()).?);+ try first.write("two");+ try std.testing.expectEqualStrings("two", (try first.read()).?);+}diff --git a/src/server_orphan.zig b/src/server_orphan.zignew file mode 100644index 00000000..d403d667--- /dev/null+++ b/src/server_orphan.zig@@ -0,0 +1,106 @@+//! Explicit stop authority for a user-selected legacy listener snapshot.+//! Discovery alone never authorizes a signal or creates an ownership record.+const std = @import("std");+const builtin = @import("builtin");+const identity = @import("proc_identity.zig");+const stop_tree = @import("job_registry_stop.zig");+const Io = std.Io;+extern "c" fn proc_pidpath(pid: c_int, buffer: [*]u8, buffersize: u32) c_int;++pub const Snapshot = struct {+ pid: i32,+ start: u64,+ executable: u64,+ pub fn token(self: Snapshot, buf: []u8) ![]const u8 {+ return std.fmt.bufPrint(buf, "{x}-{x}", .{ self.start, self.executable });+ }+};++pub fn capture(io: Io, pid: i32) ?Snapshot {+ if (pid <= 1) return null;+ const before = switch (identity.probe(io, pid)) {+ .id => |v| v,+ else => return null,+ };+ if (before == 0) return null;+ var buf: [4096]u8 = undefined;+ const exe: []const u8 = if (builtin.os.tag == .macos) blk: {+ const n = proc_pidpath(pid, &buf, buf.len);+ if (n <= 0 or n >= buf.len) return null;+ break :blk std.mem.sliceTo(buf[0..@intCast(n)], 0);+ } else if (builtin.os.tag == .linux) blk: {+ var pbuf: [64]u8 = undefined;+ const path = std.fmt.bufPrint(&pbuf, "/proc/{d}/exe", .{pid}) catch return null;+ const n = Io.Dir.cwd().readLink(io, path, &buf) catch return null;+ break :blk buf[0..n];+ } else return null;+ const stat = Io.Dir.cwd().statFile(io, exe, .{}) catch return null;+ var hash = std.hash.Wyhash.init(0);+ hash.update(exe);+ hash.update(std.mem.asBytes(&stat.inode));+ hash.update(std.mem.asBytes(&stat.size));+ const modified: i128 = stat.mtime.nanoseconds;+ hash.update(std.mem.asBytes(&modified));+ const native = stop_tree.Native{ .io = io };+ if (native.group(pid) != pid or native.ownGroup() == pid) return null;+ if (identity.ownerState(before, identity.probe(io, pid)) != .held) return null;+ // Unknown is not a matching identity, even though it conservatively holds+ // ownership records. Stop authorization requires a positive second read.+ switch (identity.probe(io, pid)) {+ .id => |v| if (v != before) return null,+ else => return null,+ }+ return .{ .pid = pid, .start = before, .executable = hash.final() };+}++pub fn matches(expected: Snapshot, current: ?Snapshot) bool {+ const got = current orelse return false;+ return expected.pid == got.pid and expected.start == got.start and expected.executable == got.executable;+}++const Checked = struct {+ native: stop_tree.Native,+ expected: Snapshot,+ pub fn probe(self: Checked, pid: i32) identity.Probe {+ const current = self.native.probe(pid);+ if (current == .gone) return .gone;+ if (!matches(self.expected, capture(self.native.io, pid))) return .unknown;+ return current;+ }+ pub fn ownGroup(self: Checked) ?i32 {+ return self.native.ownGroup();+ }+ pub fn group(self: Checked, pid: i32) ?i32 {+ return self.native.group(pid);+ }+ pub fn signal(self: Checked, pid: i32, sig: stop_tree.Signal) !void {+ if (!matches(self.expected, capture(self.native.io, pid))) return error.IdentityChanged;+ try self.native.signal(pid, sig);+ }+ pub fn groupGone(self: Checked, pid: i32) ?bool {+ return self.native.groupGone(pid);+ }+ pub fn sleep(self: Checked) !void {+ try self.native.sleep();+ }+};++/// Caller must have re-discovered this exact candidate and received the+/// explicit token displayed to the user; never used by automatic cleanup.+pub fn stop(io: Io, expected: Snapshot, token: []const u8) stop_tree.Result {+ var buf: [80]u8 = undefined;+ const want = expected.token(&buf) catch return .unverifiable;+ if (!std.mem.eql(u8, want, token)) return .unverifiable;+ if (comptime builtin.os.tag == .macos or builtin.os.tag == .linux) {+ return stop_tree.stop(expected.pid, expected.start, Checked{ .native = .{ .io = io }, .expected = expected });+ } else return .unsupported;+}++test "#817 legacy stop snapshot rejects PID reuse, executable changes and unavailable identity" {+ const expected = Snapshot{ .pid = 200, .start = 10, .executable = 30 };+ try std.testing.expect(matches(expected, expected));+ try std.testing.expect(!matches(expected, .{ .pid = 200, .start = 11, .executable = 30 }));+ try std.testing.expect(!matches(expected, .{ .pid = 200, .start = 10, .executable = 31 }));+ try std.testing.expect(!matches(expected, null));+ try std.testing.expectEqual(stop_tree.Result.unverifiable, stop(std.testing.io, expected, "stale-token"));+}diff --git a/src/server_port.zig b/src/server_port.zigindex 8da07e42..b42a8617 100644--- a/src/server_port.zig+++ b/src/server_port.zig@@ -177,13 +177,15 @@ test "server port: all listener families and exact numeric ports" {test "server port: loopback listener preflight does not stop listener" {const io = std.testing.io;- var addr = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0");- var server = try std.Io.net.IpAddress.listen(&addr, io, .{});- defer server.deinit(io);- const status = probe(std.testing.allocator, io, server.socket.address.getPort());- if (status == .unknown) return error.SkipZigTest; // lsof is optional- try std.testing.expectEqual(Status.conflict, status);- var target = server.socket.address;- const stream = try std.Io.net.IpAddress.connect(&target, io, .{ .mode = .stream });- defer stream.close(io);+ for ([_][]const u8{ "127.0.0.1:0", "[::1]:0" }) |address| {+ var addr = try std.Io.net.IpAddress.parseLiteral(address);+ var server = try std.Io.net.IpAddress.listen(&addr, io, .{});+ defer server.deinit(io);+ const status = probe(std.testing.allocator, io, server.socket.address.getPort());+ if (status == .unknown) return error.SkipZigTest; // lsof is optional+ try std.testing.expectEqual(Status.conflict, status);+ var target = server.socket.address;+ const stream = try std.Io.net.IpAddress.connect(&target, io, .{ .mode = .stream });+ defer stream.close(io);+ }}diff --git a/src/servers_cmd.zig b/src/servers_cmd.zigindex ef78f797..bf07432e 100644--- a/src/servers_cmd.zig+++ b/src/servers_cmd.zig@@ -50,13 +50,33 @@ pub fn command(gpa: Allocator, io: Io, arena: Allocator, args: []const []const ufor (recs) |rec| {if (rec.pid == candidate.pid and job_registry.state(io, rec) == .running) recorded = true;}- if (!recorded) try out.print("{d:<8} suspected orphan listener (listener pid {d}); report-only, ownership unverified\n", .{ candidate.pid, candidate.listener });+ if (!recorded) {+ try out.print("{d:<8} suspected orphan listener (listener pid {d}); origin unverified\n", .{ candidate.pid, candidate.listener });+ if (@import("server_orphan.zig").capture(io, candidate.pid)) |snapshot| {+ var token: [80]u8 = undefined;+ try out.print(" After inspecting this process, explicitly stop this snapshot with: graff servers stop-suspect {d} {s}\n", .{ candidate.pid, try snapshot.token(&token) });+ }+ }}if (found.incomplete) try out.writeAll("orphan discovery incomplete: inspection limit or process query failed; listener status is unknown\n");- try out.writeAll("Suspects are never adopted or stopped: environment hints cannot prove ownership or revalidate start/executable/group identity.\n");+ try out.writeAll("Suspects are never adopted or automatically stopped. stop-suspect requires the displayed identity token and revalidates start, executable and process group.\n");return out.writeAll("graff servers stop <pid> ends a verified recorded job only; graff servers prune drops dead records\n");}+ if (std.mem.eql(u8, action, "stop-suspect")) {+ if (args.len != 3) return out.writeAll("usage: graff servers stop-suspect <pid> <identity-token-from-list>\n");+ const pid = std.fmt.parseInt(i32, args[1], 10) catch return out.writeAll("invalid pid; no process stopped\n");+ const found = discovery.scan(gpa, io, arena) catch return out.writeAll("discovery unavailable; no process stopped\n");+ for (found.candidates) |candidate| {+ if (candidate.pid != pid) continue;+ const orphan = @import("server_orphan.zig");+ const snapshot = orphan.capture(io, pid) orelse return out.writeAll("identity unavailable; no process stopped\n");+ const result = orphan.stop(io, snapshot, args[2]);+ return out.print("legacy listener stop: {s}; no ownership record created\n", .{@tagName(result)});+ }+ return out.writeAll("pid is no longer a discovered same-user orphan listener; no process stopped\n");+ }+if (std.mem.eql(u8, action, "stop")) {if (args.len < 2) return out.writeAll("usage: graff servers stop <pid>\n");const pid = std.fmt.parseInt(i32, args[1], 10) catch return out.print("graff servers stop: '{s}' is not a pid\n", .{args[1]});@@ -76,7 +96,7 @@ pub fn command(gpa: Allocator, io: Io, arena: Allocator, args: []const []const u}return;}- return out.print("no record of pid {d} — suspected listeners are report-only and cannot be stopped here; exact start/executable/group identity is not available\n", .{pid});+ return out.print("no record of pid {d} — use servers list to inspect suspected listeners and obtain an explicit stop-suspect identity token\n", .{pid});}if (std.mem.eql(u8, action, "prune")) {@@ -89,5 +109,5 @@ pub fn command(gpa: Allocator, io: Io, arena: Allocator, args: []const []const ureturn out.print("✓ dropped {d} record(s) of servers that are gone\n", .{dropped});}- try out.print("unknown servers command '{s}' — use: graff servers [list | stop <pid> | prune]\n", .{action});+ try out.print("unknown servers command '{s}' — use: graff servers [list | stop <pid> | stop-suspect <pid> <identity-token> | prune]\n", .{action});}diff --git a/src/vision_clipboard.zig b/src/vision_clipboard.zigindex 4cc45473..5db58aef 100644--- a/src/vision_clipboard.zig+++ b/src/vision_clipboard.zig@@ -258,155 +258,10 @@ pub fn pasteboardHintFromInfo(info: []const u8) enum { image, none } {return .none;}-const FlavorTry = union(enum) {- ok: Grab,- miss,- failed: FailKind,-};--/// macOS: export the clipboard image to a file, trying one pasteboard flavor-/// per osascript invocation and stopping at the first that yields a real file.-///-/// Distinguishes an empty clipboard from access / export / conversion failures-/// so Ctrl-V can say something other than "copy an image first" when the-/// pasteboard already holds one (#843). `clipboard info` is consulted only for-/// flavor class names — never for payload bytes.+/// Export actual pasteboard types through AppKit. The named-pasteboard entry+/// point is shared with native regressions without touching the user's board.pub fn grabClipboardImage(io: Io, gpa: Allocator) GrabAttempt {- if (builtin.os.tag != .macos) return .empty;- var saw_fail: ?FailKind = null;- inline for (.{ grabPng, grabFurl, grabPdf }) |step| {- switch (step(io, gpa)) {- .ok => |g| return .{ .ok = g },- .miss => {},- .failed => |k| if (saw_fail == null) {- saw_fail = k;- },- }- }- if (saw_fail) |k| return .{ .failed = k };- return switch (pasteboardImageHint(io, gpa)) {- .image => .{ .failed = .extract },- .unknown => .{ .failed = .access },- .none => .empty,- };-}--fn pasteboardImageHint(io: Io, gpa: Allocator) enum { image, none, unknown } {- const info = runCapture(io, gpa, &.{ "osascript", "-e", "clipboard info" }) orelse return .unknown;- defer gpa.free(info);- return if (pasteboardHintFromInfo(info) == .image) .image else .none;-}--/// `open for access` line with our per-invocation path baked in.-fn openLine(gpa: Allocator, path: []const u8) ?[]const u8 {- return std.fmt.allocPrint(gpa, "set fp to open for access POSIX file \"{s}\" with write permission", .{path}) catch null;-}--fn grabPng(io: Io, gpa: Allocator) FlavorTry {- const path = tempPath(io, gpa, "png") orelse return .{ .failed = .access };- var keep = false;- defer if (!keep) discard(io, gpa, path);-- const open = openLine(gpa, path) orelse return .{ .failed = .access };- defer gpa.free(open);- const argv = [_][]const u8{- "osascript",- "-e",- "try",- "-e",- "set theData to (the clipboard as «class PNGf»)",- "-e",- open,- "-e",- "set eof fp to 0",- "-e",- "write theData to fp",- "-e",- "close access fp",- "-e",- "on error",- "-e",- "error number 1",- "-e",- "end try",- };- switch (runStatus(io, &argv)) {- .spawn => return .{ .failed = .access },- .failed => return .miss,- .ok => {},- }- // Stat the export: osascript exiting 0 is not proof the bytes landed.- if ((regularFileSize(io, path) orelse 0) == 0) return .{ .failed = .extract };- keep = true;- return .{ .ok = .{ .path = path, .flavor = .png, .owned = true } };-}--fn grabFurl(io: Io, gpa: Allocator) FlavorTry {- const raw = switch (runCaptureStatus(io, gpa, &.{ "osascript", "-e", "POSIX path of (the clipboard as «class furl»)" })) {- .ok => |s| s,- .failed => return .miss,- .spawn => return .{ .failed = .access },- };- defer gpa.free(raw);- const src = std.mem.trim(u8, raw, " \t\r\n");- if (!furlLooksStageable(io, src, sipsIsImage)) return .miss;- if (stageableExtension(src)) {- // The user's own file, in place. `owned = false`: never delete it.- const dup = gpa.dupe(u8, src) catch return .{ .failed = .access };- return .{ .ok = .{ .path = dup, .flavor = .furl, .owned = false } };- }- // A .heic/.tiff/.bmp/… that sips vouched for: normalize to PNG.- const out = tempPath(io, gpa, "png") orelse return .{ .failed = .access };- if (sipsToPng(io, src, out) and (regularFileSize(io, out) orelse 0) > 0)- return .{ .ok = .{ .path = out, .flavor = .furl, .owned = true } };- discard(io, gpa, out);- return .{ .failed = .convert };-}--fn grabPdf(io: Io, gpa: Allocator) FlavorTry {- const pdf = tempPath(io, gpa, "pdf") orelse return .{ .failed = .access };- defer discard(io, gpa, pdf); // the intermediate never outlives this call-- const open = openLine(gpa, pdf) orelse return .{ .failed = .access };- defer gpa.free(open);- const argv = [_][]const u8{- "osascript",- "-e",- "try",- "-e",- "set theData to (the clipboard as «class PDF »)",- "-e",- open,- "-e",- "set eof fp to 0",- "-e",- "write theData to fp",- "-e",- "close access fp",- "-e",- "on error",- "-e",- "error number 1",- "-e",- "end try",- };- switch (runStatus(io, &argv)) {- .spawn => return .{ .failed = .access },- .failed => return .miss,- .ok => {},- }- if ((regularFileSize(io, pdf) orelse 0) == 0) return .{ .failed = .extract };-- const out = tempPath(io, gpa, "png") orelse return .{ .failed = .access };- if (sipsToPng(io, pdf, out) and (regularFileSize(io, out) orelse 0) > 0)- return .{ .ok = .{ .path = out, .flavor = .pdf, .owned = true } };- discard(io, gpa, out);- return .{ .failed = .convert };-}--fn sipsToPng(io: Io, in: []const u8, out: []const u8) bool {- if (builtin.os.tag != .macos) return false;- return runQuiet(io, &.{ "sips", "-s", "format", "png", in, "--out", out });+ return @import("clipboard_native.zig").grab(io, gpa, "");}// ── subprocess plumbing ───────────────────────────────────────────────────