# Copilot loop operations

Canonical owner for operating the deterministic Copilot PR follow-up state machine — the operational reference for the routed `copilot_pr_followup`, `wait_watch`, `reviewer_fixer`, and `final_approval` paths behind `dev-loop`. The machine's states and transitions are defined by [Copilot Loop State Graph](./copilot-loop-state-graph.md).

Use it with the [Copilot PR Follow-up Skill](../copilot-pr-followup/SKILL.md), the [Public Dev Loop Contract](./public-dev-loop-contract.md), and, when the current step depends on async start/resume/status or retrospective enforcement, the [Retrospective Checkpoint Contract](./retrospective-checkpoint-contract.md).

## Deterministic orchestration authority

At each PR-follow-up/watch decision, use `detect-copilot-loop-state.mjs` or reviewer-side
`detect-reviewer-loop-state.mjs` for the current state, allowed transitions, next action
and stop condition. Their mappings are owned by [Copilot Loop State Graph](./copilot-loop-state-graph.md)
and [Reviewer Loop State Graph](./reviewer-loop-state-graph.md).

Resolve helpers using the main skill's asset layout: `../../scripts/` relative to
`skills/copilot-pr-followup/SKILL.md` in this source tree, or bundled `scripts/` inside
normalized installed skills. For MVP `story -> PR -> tracker sync`, follow
[Tracker-First Story-to-PR Contract](./tracker-first-loop-state.md), including its
inherited `#21` authority/link/reverse-sync rules and post-merge sync verification.

## Key guarantees from the state machine

These routing guarantees are owned by [Copilot Loop State Graph](./copilot-loop-state-graph.md); see `COPILOT-STATE-UNRESOLVED-PRIORITY`, `COPILOT-STATE-TERMINAL-STOP`, `COPILOT-STATE-REPLY-BEFORE-REREQUEST`, and `COPILOT-STATE-ACTIVE-REQUEST-WAIT` there for the routing rules driving `unresolvedThreadCount`, `copilotReviewRequestStatus`, and `agentFixStatus`.

## How to use the state machine in practice

1. Run `node <resolved-skill-scripts>/loop/detect-copilot-loop-state.mjs --repo <owner/name> --pr <number>`
   to get the current Copilot-loop state, decisive snapshot fields, and recommended next action.

2. After a separate `<resolved-skill-scripts>/github/request-copilot-review.mjs` call, apply `COPILOT-FOLLOWUP-REQUEST-BRANCHING` in the [follow-up skill](../copilot-pr-followup/SKILL.md), then refresh the detector normally. `--review-request-status` is unsupported. For combined detection/request/watch routing, use `copilot-pr-handoff.mjs` and consume its returned request/watch contract; it preserves its own request result, not an externally supplied override.

3. When the agent has applied a fix and wants to signal reply/resolve is next, build a snapshot
   with `agentFixStatus: "applied"` and use `--input <snapshot.json>` for interpretation.

4. Branch on the detector output instead of inventing a polling loop:
   - `state=waiting_for_copilot_review` with `snapshot.copilotReviewOnCurrentHead=false`: do **not** poll manually; either run `node <resolved-skill-scripts>/loop/run-watch-cycle.mjs --repo <owner/name> --pr <number>` for persistent async waiting or report the wait state and resume later after the single detector call
   - `state=waiting_for_ci` with `snapshot.ciStatus` in `{ "pending", "none" }`: do **not** poll manually by default; use `node <dev-loops-package-root>/cli/index.mjs loop watch-ci --repo <owner/name> --pr <number> --timeout 540` or `node <resolved-skill-scripts>/github/wait-pr-checks.mjs --repo <owner/name> --pr <number> --timeout 540` (one call waits at most about 170 s per `DEV-LOOP-PROBE-TIMEOUT-CEILING`; on `outcome: "pending"` run the returned `reissue` unchanged; settle-blocking with a 0/1/2 exit contract) to block-wait on the combined check/status state (provider-agnostic — CircleCI, GitHub Actions, and any external commit-status / check-run). `gh run watch <run-id>` is an Actions-only fallback when the current-head run id is already known and you know the gating checks are GitHub Actions. Either way, on `timeout`/`changed` report pending CI and resume later after the single detector refresh. Before considering the bounded exception, read [Zero-suite local-validation exception](./copilot-ci-status-contract.md#zero-suite-local-validation-exception), including its unavailable CLI input; these prerequisites cannot override a detector result of `none`.
   - `snapshot.ciStatus="failure"` remains a stop/fix state, never a wait loop

5. For reviewer-side draft-review work, run `node <resolved-skill-scripts>/loop/detect-reviewer-loop-state.mjs --repo <owner/name> --pr <number> [--local-state <path>]`.
   If the state reaches `draft_review_ready`, stage the pending review with
   `node <resolved-skill-scripts>/github/stage-reviewer-draft.mjs --repo <owner/name> --pr <number> --review-file <merged-review.json> --local-state-output <state.json>`,
   then re-run the detector with `--local-state <state.json>`.

6. Interpret the machine output per [Interpreting Copilot completion versus PR lifecycle completion](./copilot-loop-state-graph.md#interpreting-copilot-completion-versus-pr-lifecycle-completion); a fresh gate-coordination `nextAction` takes precedence over a `pre_approval_gate` hint. For stop states (`review_request_unavailable`,
   `blocked_needs_user_decision`), report to the user and do not proceed.

7. Before you request another Copilot round on a later head, apply `COPILOT-STATE-CARRIED-CONVERGENCE`
   in [Copilot Loop State Graph](./copilot-loop-state-graph.md). It owns the carried-convergence
   preconditions, the `suppressed_post_convergence` outcome and the
   `refinement.requireCopilotConvergenceAtLatestHead` strict mode (ADR 0090).

## Judgment calls that remain in the agent layer

See [Copilot Loop State Graph](./copilot-loop-state-graph.md)'s "Agent judgment boundary" for the bounded list of decisions the state machine leaves to the agent.

## Pre-follow-up working rules

> **Phase boundary:** Steps 1-4 apply when no PR exists yet (issue intake).
> If a PR already exists, skip to [Deterministic orchestration authority](#deterministic-orchestration-authority) —
> the state machine owns all post-PR routing.

### Step 1: Choose the work item

Prefer a GitHub issue over an ad hoc TODO, prioritizing `type:task` under the relevant
epic and `status:ready`. Inspect milestone, labels and acceptance criteria; check for
an existing PR before proposing execution.

Useful checks:
- `gh issue list --state open`
- `node scripts/github/view-issue.mjs --repo <owner/name> --issue <number>`
- `gh pr list --state open`

For a status/progress/readiness/merge-state/next-step question (including “what is next”), follow `FACADE-STATUS-AUTHORITATIVE-FAIL-CLOSED` and the status reporting contract in [Public Dev Loop Contract](./public-dev-loop-contract.md), and include the resolved artifact identity in the answer. For issue targets, resolve issue↔PR linkage via the startup resolver (`node <dev-loops-package-root>/cli/index.mjs loop startup --issue <number>`, run inside the `dev-loop` async subagent) rather than running `detect-linked-issue-pr.mjs` manually.

### Step 2: Confirm issue scope before execution

Before Copilot handoff or follow-up fixes, summarize the issue number/title, parent
epic if present, milestone, labels, exact acceptance criteria, intended narrow scope
and non-goals inferred from the issue/plan.

If the work item is phase-like, ambiguous, or likely to shape more than one downstream step, default to a short fan-out / fan-in refinement pass before implementation:
- generate 2-3 plan variants in parallel when practical
- compare the variants explicitly
- merge them into one bounded execution plan
- only then proceed with GitHub execution

If the issue text is too vague, stop and ask a short clarification question rather than guessing.

### Step 3: Decide whether Copilot or Pi should act next

Use this heuristic:

#### Prefer Copilot when
- there is a ready implementation issue with clear acceptance criteria
- no PR exists yet for that issue
- the user wants the repository's normal GitHub/Copilot path
- the next step is “start work” rather than “finish this already-open PR right now”

#### Prefer Pi follow-up when
- a PR already exists
- Copilot has already pushed work and now needs review/fix follow-up
- there are unresolved comments or failing checks
- the user wants async in-session watching and response

#### Prefer plain analysis only when
- the user is asking what should happen next
- authorization for GitHub state changes has not been given yet
- the issue/PR state is unclear and needs inspection first

### Step 4: Copilot handoff rules

Use the GitHub issue as authority; preserve its acceptance criteria and narrow scope,
without adjacent backlog work. Prefer one issue per PR unless the user requests bundling.

Before any GitHub mutation such as assigning the issue, posting instructions, or changing labels, confirm first unless explicitly authorized.

Assign `copilot-swe-agent`, referencing the issue and acceptance criteria in
implementation-focused, test-aware instructions.

## PR description contract

This section governs tracker-backed (Copilot-handoff) PRs; issue-less/plan-file-backed PRs are governed by merge precondition 7 in merge-preconditions.md instead.

Author a detailed structured description ([Agent Instructions](../../AGENTS.md) when present, otherwise the [PR Body Skeleton](../dev-loop/templates/pr-body.md)). At minimum include change summary, scope/context, explicit acceptance criteria, explicit definition of done, explicit non-goals, and `Closes #N` (or `Fixes #N`) for the linked issue.

Checkbox rule: acceptance criteria, definition-of-done items, and any task list must be rendered as real GitHub markdown checkboxes inside list items (`- [ ]` / `- [x]`, also `* [ ]` / `* [x]`). Do not wrap checkbox markers (e.g. `[x]`) in backticks. Do not place checkbox markers inside table cells — task lists are not interactive there even with a leading `- `.

`validateTrackerBackedPrBodySpec` (`@dev-loops/core/loop/issue-refinement-artifact`,
reusing `validatePrBodySpec`) runs at BOTH ends of the lifecycle: `create-pr.mjs` fails
closed at PR-creation time on a non-conformant tracker-backed body, and `ready-for-review.mjs`
re-checks it at draft exit. For a PR closing an issue, its OWN body must contain an Objective/why section, an In scope section,
Acceptance criteria and Definition of done checklists, explicit Non-goals, and
`Closes #N`/`Fixes #N`; otherwise it fails closed. A linked issue's criteria or reviewer
judgment cannot substitute. The
[PR Body Skeleton](../dev-loop/templates/pr-body.md) is conformant.

<!-- rule: OPS-PR-VALIDATION-STABLE-EVIDENCE -->
`OPS-PR-VALIDATION-STABLE-EVIDENCE`: For tracker-backed PRs, the PR description's Validation section MUST record each validation command or named check together with its stable pass/fail outcome. A SHA or result explicitly labelled historical is allowed. It MUST NOT include volatile aggregate test, assertion, or asset counts; skip counts; durations; timestamps; or incidental totals unless an explicit acceptance criterion makes that exact quantity behaviorally significant. A current-head SHA, a "current" or "fresh" head claim, and gate verdict or lifecycle status (for example "draft_gate clean at <sha>") MUST NOT appear in the body. These head-bound details and detailed totals MUST live in head-stamped validation artifacts and gate verdict comments. A gate requirement stated as DoD prose (for example "draft_gate and pre_approval_gate pass on the final head") is a requirement, not a status claim, and is allowed.

<!-- rule: OPS-DRAFT-FIRST-PR -->
`OPS-DRAFT-FIRST-PR`: New PRs MUST open as **draft** through `create-pr.mjs`, which
rejects `--ready`. Agents MUST NOT create ready PRs. The two sanctioned draft exits are
`ready-for-review.mjs` (`gh pr ready`) for a normal ready flip, and `restore-ready.mjs`
only to restore a PR that `convert-to-draft.mjs` made a transient draft while CI is
blocking. Both run through `readyForReview()` and require clean current-head `draft_gate` evidence, with one exception owned by `GATE-EXEC-ROUND-CAP` (ADR 0208): `ready-for-review.mjs` accepts the cap-round-fixed proof in place of that verdict. `restore-ready.mjs` never accepts it, because the proof was never CI-checked at the current head. It refuses a cap-fixed PR whose only evidence is that proof, and the remedy is `ready-for-review.mjs` once CI is green.
[TRACKER-PROJECTION-REQUIRED-METADATA](./tracker-first-loop-state.md#31-required-pr-metadata)
owns the corresponding tracker metadata requirement.

Use `create-pr.mjs` only after authoritative issue↔PR resolution finds no open linked
PR; otherwise reuse/update that PR. The wrapper preserves `gh pr create`'s stdout
(the PR URL line first), appends the early-surface JSON line when a base resolves (plus a `{board}` line on the lightweight issue-less or body-less path), and defaults to self-assignment (`--assignee @me`).

A session that creates the branch and PR itself MUST run the pre-PR review per
`PRE-PR-BEFORE-FIRST-PUSH` in [Pre-push review contract](./pre-pr-review-contract.md)
before the branch's first push and before `create-pr.mjs`; until then, the session
and its sub-delegates commit locally and do not push. `pr create` also refuses without the review record (the guard and its writer are in `PRE-PR-BEFORE-FIRST-PUSH`).

MUST use `node <resolved-skill-scripts>/github/create-pr.mjs --repo <owner/name> --assignee @me --base <base> --head <head> --title "..." --body-file <body-file>` (always draft, self-assigned by default; `--assignee @me` is the default).

<!-- rule: CLOSING-REF-BRANCH-MISMATCH -->
`CLOSING-REF-BRANCH-MISMATCH`: `create-pr.mjs` and `edit-pr.mjs` MUST fail closed
when ANY closing reference in `--body`/`--body-file` disagrees with the expected issue.
Check every case-insensitive `close`/`closes`/`closed`, `fix`/`fixes`/`fixed`, and
`resolve`/`resolves`/`resolved` reference; a correct first reference cannot excuse
a wrong later one. Resolve the expected issue from `issue-<N>` or `dl/issue-<N>-*`:
creation uses `--head`, otherwise the current branch, with explicit `--issue <n>`
taking precedence; editing uses the PR head branch, otherwise `closingIssuesReferences`.
Matching references, no closing references, or no resolvable issue (issue-less
lightweight) pass. `--allow-cross-issue` records an intentional exception. The guard
only compares issue numbers: it never rewrites the body or changes GitHub auto-close
semantics. `validatePrBodySpec` still owns the draft-exit `Closes`/`Fixes` vocabulary.

## Timeout and watch policy

One Copilot review watch boundary must be capped. Defaults:
- poll interval for review/activity watchers: **1 minute** (derived from `packages/core/src/loop/policy-constants.mjs` DEFAULT_POLL_INTERVAL_MS)
- max watch timeout per Copilot review boundary: **30 minutes** (derived from `packages/core/src/loop/policy-constants.mjs` COPILOT_REVIEW_WAIT_TIMEOUT_MS)
- if that 30-minute watch budget expires, refresh authoritative state once; if the refreshed state still resolves `waiting_for_copilot_review`, stop with `watch timeout — PR #<number> needs manual attention`
- do not silently extend that 30-minute cap unless the user or conductor explicitly authorizes a longer watch budget for the active PR
- parent/subagent no-activity threshold for watcher-style runs: at least **15 minutes**
- active-long-running notice threshold for watcher-style runs: about **30 minutes**

`probe-copilot-review.mjs`, `run-watch-cycle.mjs`, and the `watchArgs` emitted by `copilot-pr-handoff.mjs` build in these defaults. Do not pass removed CLI policy flags (`--poll-interval-ms`, `--probe-only`). The scripts reject them, and every routed `dev-loops` subcommand rejects them the same way, with the script's exit code and error text. `probe-copilot-review.mjs` does accept `--timeout` (watch budget in seconds; `0` = single immediate idle check, no watch); timeouts and intervals are otherwise derived from `packages/core/src/loop/policy-constants.mjs`.

### Outer-loop checkpoint: canonical re-attachment artifact

`outer-loop.mjs` writes the outer-loop checkpoint (`tmp/copilot-loop/<owner>/<repo>/pr-<n>/outer-loop-state.json`) at every conductor cycle. It is the canonical re-attachment artifact for async subagent runs and records:

| Field | Meaning |
|---|---|
| `pr` | PR number |
| `repo` | Repository slug (`owner/name`; lowercased by `outer-loop.mjs`) |
| `outerAction` | Next action: `continue_wait`, `reenter_copilot_loop`, `reenter_reviewer_loop`, `stop`, `done` |
| `copilotState` | Current copilot inner-loop state |
| `reviewerState` | Current reviewer inner-loop state |
| `reviewerScope` | Reviewer scope mode (always present; e.g. `all_reviewers` or `single_reviewer`) |
| `reviewerLogin` | Reviewer GitHub login (always present; `null` unless single-reviewer scope) |
| `reason` | Stop reason (`null` when `outerAction` is not `stop`) |
| `timestamp` | ISO 8601 timestamp of checkpoint write |
| `waitCycles` | Number of wait cycles accumulated |
| `headSha` | PR head SHA at checkpoint time (`null` when unavailable) |

### Re-attachment contract

When a fresh `dev-loop` async subagent starts on a PR that already has an outer-loop
checkpoint, it must read the checkpoint before entering any intake or follow-up procedure:

1. If `outerAction` is `continue_wait` or `reenter_copilot_loop`: auto-resume the loop
   rather than treating the start as fresh intake.
2. If `outerAction` is `reenter_reviewer_loop`: enter the reviewer-loop path.
3. If `outerAction` is `stop`: the loop is blocked or needs a human decision; report the `reason` and ask for direction.
4. If no checkpoint or `outerAction` is `done`: `done` means the PR is merged/closed; normal fresh startup.

The checkpoint is the only source of truth for re-attachment. Do not rely on chat context
or local notes to determine "where we left off."

## Hard rule: no agent-authored shell polling

Helper-owned sleep inside `run-watch-cycle.mjs`, `probe-copilot-review.mjs`, or `watch-initial-copilot-pr.mjs` is allowed and is not a blocker. Agent-authored shell polling (`sleep`, `for`, `while`, `timeout` wrappers around tool invocations) is a contract breach. This rule applies to ALL repos using the dev-loop workflow.

## Runner handoff teardown

<!-- rule: RUNNER-HANDOFF-TEARDOWN -->
`RUNNER-HANDOFF-TEARDOWN`: A coordinator that owns a PR runner claim MUST release it at hand-back with `pr-runner-coordination.mjs handoff --repo <owner/name> --pr <number> --run-id <the id used at claim>`. When a verified runtime run id exists, `handoff` uses it and a mismatching `--run-id` is `ownership_lost`. When none exists (for example on Claude Code), the explicit `--run-id` is accepted as the identity and the handoff succeeds only when it equals the active owner; any other owner gives `ownership_lost`. On native Codex the verified thread identity is still required, and an explicit `--run-id` alone is refused with `run_id_required`. With neither id, `handoff` refuses with `run_id_required` and a message that names the remedy. The automatic release at a terminal stop (`loop handoff`, `loop gate-coordination`) reads the run id from the environment only, so a coordinator that claimed the PR MUST prefix those calls with `DEVLOOPS_RUN_ID=<the id used at claim>`. When the result carries `runnerRelease.status: skipped_no_async_run_id` (its `remedy` names the command), a coordinator that claimed the PR MUST run the explicit `handoff --run-id` before its hand-back. Without a claim the handoff writes nothing: `handoff_noop` when no owner exists, `ownership_lost` (exit 1) when another run holds the claim. `takeover` succeeds only once `status` reports `stale: true` (exit signal or max age); otherwise it refuses with `active_run_exists`, and a missing run id is `run_id_required`. `status` reports `stale` and `staleReason`, and `takeover` refuses a live non-stale owner.

## Hard rule: no inline interpreters

<!-- rule: OPS-NO-INLINE-INTERPRETER -->
`OPS-NO-INLINE-INTERPRETER`: Coordinator and agent flows MUST NOT invoke an inline interpreter (`node -e`/`node --eval`, `python3 -c`, `bun -e`/`--eval`/`-p`/`--print`, `bun -` or `bun <<EOF` stdin scripts, `python3 - <<EOF` heredocs, or equivalent) to (a) parse any dev-loops tool output, or (b) mutate repository files. Sanctioned paths: a tool's `--jq`/`--silent` output flags (or `gh ... --jq`) for (a); the editor/patch tools, or `gh ... --body-file` composed from a `--jq` read, for (b). Decision: interpreters outside the pinned toolchain (`perl`, `ruby`, `deno`) stay uncovered by the hook; the pinned toolchain is node, python and bun. This rule applies to ALL repos using the dev-loop workflow, not just the source repo.

Post-watch read pattern: after a probe/watch settles, do not parse its output — re-read state via `detect-copilot-loop-state.mjs --repo <owner/name> --pr <number>`; read the unresolved thread bodies via `capture-review-threads.mjs --repo <owner/name> --pr <number> --unresolved --bodies` (the canonical working-set read: trusted comment bodies pre-joined per thread; an unresolved thread with no trusted comment is reported in `skippedUntrusted` with its logins and the remedy, `GATE-REVIEW-COMMENT-TRUST`) and the thread/comment ids for reply-resolve via `list-review-threads.mjs --repo <owner/name> --pr <number> --unresolved-only` (see [Copilot PR Follow-up Skill](../copilot-pr-followup/SKILL.md) Step 6).

If the polling interval is 1 minute, do not treat silence shorter than one full poll interval as suspicious, and do not configure needs-attention thresholds close to a few seconds for this loop.

## Codex runtime setup

<!-- rule: OPS-WRITABLE-TOOL-CACHE -->
`OPS-WRITABLE-TOOL-CACHE`: Sanctioned validation and log tooling MUST route child-tool caches deterministically without per-command agent overrides. npm smoke tests preserve an explicit cache or a writable default, and otherwise probe a temporary cache before consuming npm commands. Actions log retrieval uses the uncached per-job API. A real permission denial still stops the actor under `OPS-CODEX-RUNTIME-SETUP`; this rule grants no permission changes or denial retries.

<!-- rule: OPS-CODEX-RUNTIME-SETUP -->
`OPS-CODEX-RUNTIME-SETUP`: Codex coordinators and workers MUST apply this setup before scoped artifact writes, Git writes or targeted verification, after any mandatory startup/envelope or pull-first bootstrap. Fixers first verify and read this document from the emitting toolchain's pinned contracts. This is bounded runtime guidance, not comprehensive Codex support; it never broadens the role, branch, paths or phase authority. `operation: complete` remains delivery-only: no source edits, source validation, staging, commit or push.

- Use actual managed tools and permissions. Codex has no native Claude role or Claude hook grant. Preserve legitimately inherited run context and the invoked operation's context requirements; never fabricate Claude/Pi identity variables, alter permission settings, launch another harness or work around a denied tool.
- For temporary artifacts and repository edits, use supported native file/patch tools with absolute paths. Read back artifacts with file-read tools or `cat`. Apply `OPS-NO-INLINE-INTERPRETER` above to temporary artifacts too: no inline Python/Node or interpreter heredoc for artifact writing or output parsing. Use sanctioned CLI output selectors for parsing.
- Before an authorized protected Git write, obtain read-only facts from the explicit authorized worktree: `git rev-parse --show-toplevel`, `git branch --show-current`, `git rev-parse --path-format=absolute --git-dir` and `git rev-parse --path-format=absolute --git-common-dir`. Linked worktrees may place per-worktree and shared Git metadata outside writable roots. Check those actual absolute locations against the managed permission profile; a writable checkout does not imply writable shared metadata. Stop on a branch/root mismatch. Address mutations with `git -C <absolute-authorized-worktree> ...` per [Worktree guidance](./worktree-guidance.md#default-rule-use-a-worktree-for-mutating-local-work).
- Under Codex only, before an authorized Git write to protected shared Git metadata, use `tools.exec_command` with `sandbox_permissions: "require_escalated"` and a factual `justification` up front when the actual managed environment requires it; do not probe with a write expected to be denied. Apply the same resource check to configured targeted suites needing shared Git metadata or local sockets. A managed request remains subject to normal approval review; it does not grant new workflow authority.
- For authorized implementation work, run staging, staged secret scan and commit as three separate tool invocations; inspect each native exit before the next. A failed stage permits no scan or commit; a scanner hit or error stops the actor. Resolve the scanner from the verified selected source/install toolchain (for fixers, the emitting root): verify `scripts/security/scan-staged-diff.mjs` there, then invoke `node <absolute-verified-scanner-path>` with the authorized mutation worktree as explicit cwd. Never select a cwd-relative consumer script or change cwd to the toolchain. Follow [WORKTREE-SCRIPT-LAUNCHER-CWD](./worktree-guidance.md#agent-shell-commands) for launcher use and retain existing commit and validation contracts. This setup grants no stage or commit permission to artifact-only roles or delivery-only operations.
- An ordinary command-input error or executed failing test is not automatically a permission/classifier denial; inspect the actual result and use supported recovery only if there was no real denial. A permission or classifier denial stops this actor immediately: no subsequent read, verification or alternate-command attempt. Hand back the original denial verbatim and already-known cwd, branch, tool, permissions and runtime context. Do not provoke a denial to test this rule or retry a denied form.
- Record actual collaboration parent/child task identities and actual `CODEX_THREAD_ID` (or its absence) from genuine runtime evidence, the setup source, native commands/tools and outcomes. A parent's recorded binding is not proof of child inheritance. Report an actual commit or precise blocker; static contract tests do not prove runtime permission enforcement, and Codex evidence must never claim native Claude hooks ran.
- Native Codex async context requires matching first-record `session_meta` child evidence (`source.subagent.thread_spawn`, consistent parent IDs and positive depth); `CODEX_THREAD_ID` alone is only a lookup key. The bounded current-layout reader fails closed on missing, unsupported or uncertain metadata and derives the shared `codex-thread-<child-id>` run identity without inherited Pi/neutral markers. MAIN follows [Codex active joins](./main-agent-contract.md#codex-active-joins) to mitigate the upstream idle-parent wake limitation; this is not a repair to Codex itself.

Pi and Claude keep their existing role loading, native tools and hook authority. This section adds no native enforcement to either harness.
