Skip to content
This repository was archived by the owner on Sep 28, 2026. It is now read-only.

fix: collect handoffs when workers finish before wait sees them - #13

Merged
jnyross merged 5 commits into
mainfrom
fix/collect-completed-handoff-on-first-wait
Aug 9, 2026
Merged

jnyross merged 5 commits into
mainfrom
fix/collect-completed-handoff-on-first-wait

Conversation

@jnyross

@jnyross jnyross commented Aug 9, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • P0 from Lisbon dogfood v3: workers can finish with a contract-valid handoff while wait snapshots stay empty/idle; root then blocks with no handoffs after the full research window.
  • Collection pattern: read first, then wait, read after every wait; deep nested handoff extract; accept complete|passed|blocked|failed.
  • Harness regressions: already-complete on first read; handoff via post-wait read when wait is empty.
  • Docs + validator phrases so generation cannot drop the rule.

Evidence

jnyross/mac-vm-testing-harness codexgraph-vm-test @ 0981258 — candidates/frozen-lisbon-v3/ (forensics: N2A idle-complete in 160.6s with 8 candidates; root rounds=1, idle=15 over 30 min).

Test plan

  • validate_skill / graph_coherence / node tests 13/13 / auto_release
  • CI green

Note

Medium Risk
Changes core task-collection behavior for all codex-graph workers; incorrect read/wait ordering or handoff parsing could still miss or mis-classify terminals, but scope is bounded to the harness/skill docs with regression tests.

Overview
Fixes a P0 collection bug where graph roots could block for the full research window even though workers had already returned valid JSON handoffs—because wait-only polling saw empty/idle snapshots while read_thread already held the terminal turn (Lisbon dogfood v3).

Collection contract is now read first, then wait, read after every wait: task-lifecycle.md documents the pattern (with updated example loop), and validate_skill.py enforces the phrases so generated graphs cannot drop the rule.

Harness (task_collection_harness.js): optional readThread; findHandoffInValue for nested turns/items and string JSON; complete as a terminal status (mapped to passed); unwrapToolSnapshot for { value, raw } envelopes; cursor merge so read cannot rewind wait progress; early exit when the first read finds a handoff. Tests cover already-complete threads, empty-wait + post-read handoff, and envelope unwrapping.

Reviewed by Cursor Bugbot for commit 1fb91c5. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • New Features

    • Task collection now detects completed handoffs immediately, including nested or JSON-encoded results.
    • Collection reads task state before waiting and after every wait.
    • Additional terminal statuses are recognized during handoff processing.
  • Bug Fixes

    • Empty wait results no longer prematurely end collection when a follow-up read may reveal progress.
    • Improved handling of completed tasks and terminal states discovered during collection.
  • Tests

    • Added coverage for immediate completion, nested handoffs, and results found after empty waits.

Lisbon dogfood v3: research workers completed in ~161s with valid JSON,
but the root collection loop reported idle for 30 minutes. Require an
initial read_thread before wait, pair every wait with a read, and deeply
search nested turns/items (including string JSON) for node handoffs.
Regression coverage for already-complete threads and empty wait snapshots.
@coderabbitai

coderabbitai Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Task collection now reads before waiting and after each wait. It recursively finds terminal handoffs in structured and JSON-encoded values. It recognizes complete, preserves read requests, and validates the updated lifecycle rules.

Changes

Task collection lifecycle

Layer / File(s) Summary
Recursive handoff extraction
skills/codex-graph/scripts/task_collection_harness.js, skills/codex-graph/scripts/task_collection_harness.test.js
Handoff detection accepts complete, unwraps tool snapshots, and searches nested objects, arrays, and JSON strings.
Read and wait collection flow
skills/codex-graph/scripts/task_collection_harness.js, skills/codex-graph/references/task-lifecycle.md, skills/codex-graph/scripts/task_collection_harness.test.js, skills/codex-graph/scripts/validate_skill.py
collectTask performs an initial read and a read after each wait. Read-discovered terminal handoffs stop collection and do not consume unchanged idle polling budget. The lifecycle reference and validation rules require both reads. Tests cover initial completion and post-wait discovery.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant collectTask
  participant readThread
  participant waitThreads
  participant findHandoffInValue
  collectTask->>readThread: initial read
  readThread-->>collectTask: thread snapshot
  collectTask->>findHandoffInValue: inspect snapshot
  alt no terminal handoff
    loop after each wait
      collectTask->>waitThreads: wait for thread updates
      waitThreads-->>collectTask: wait snapshot
      collectTask->>readThread: read current thread
      readThread-->>collectTask: thread snapshot
      collectTask->>findHandoffInValue: inspect snapshot
    end
  end
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the primary fix: collecting handoffs when workers finish before wait observes them.
Description check ✅ Passed The description explains the behavior, validation evidence, regression coverage, and test status, but uses alternate headings for Validation and Test notes.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/collect-completed-handoff-on-first-wait

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

cursor[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

Carry afterCursor from read_thread responses so idle wait polls still
advance pagination, and only append read items when the read snapshot
fingerprint changes.
cursor[bot]

This comment was marked as resolved.

Only apply read_thread afterCursor when it differs from the request
cursor, so an echoed read cursor cannot overwrite a newer wait cursor.
@cursor

cursor Bot commented Aug 9, 2026

Copy link
Copy Markdown

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Read cursor never persisted
    • afterCursor is now assigned from read_thread responses on the initial and post-wait reads so pagination advances across idle waits.
  • ✅ Fixed: Read path duplicates collected items
    • Post-wait reads still scan for handoffs but append items only when the read snapshot fingerprint changes, matching wait-path deduplication.

You can send follow-ups to the cloud agent here.

jnyross added 2 commits August 9, 2026 15:33
…doff

- Unwrap resolveTool {value,raw} envelopes before reading wait/read snapshots
- Update lifecycle JS example to read-first and read-after-wait
- Dedupe collected items; keep newest matching handoff from later reads
Address CodeRabbit/Devin review on the collection PR: peel {value,raw}
before reading snapshots, and avoid recording the same worker item many
times across polls.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 2 new potential issues.

View 1 additional finding in Devin Review.

Open in Devin Review

Comment on lines +257 to 264
// Prefer wait progress; only take read's cursor when it advances past the
// request cursor. Read often echoes the request afterCursor when there is
// no further page, which must not rewind a newer wait cursor.
const requestCursor = request.afterCursor;
if (nextCursor !== undefined) afterCursor = nextCursor;

if (isValidTerminalHandoff(snapshot.terminal, nodeId)) {
terminal = snapshot.terminal;
if (readCursor !== undefined && readCursor !== requestCursor) {
afterCursor = readCursor;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Progress marker from the follow-up check can be reset to an older position, causing already-seen output to be re-fetched

The position marker is overwritten with the follow-up check's value whenever it merely differs from the value that was sent (readCursor !== requestCursor at skills/codex-graph/scripts/task_collection_harness.js:262) instead of only when it is newer, so a stale value can undo the progress just made and the same output is fetched again.
Impact: Collection can spin over the same page of worker output, burning the limited number of rounds and potentially blocking a task whose result was already available.

Cursor precedence between wait and read snapshots

The comment at skills/codex-graph/scripts/task_collection_harness.js:257-259 states the intent: "only take read's cursor when it advances past the request cursor... must not rewind a newer wait cursor." The implementation compares readCursor against request.afterCursor (the cursor that was sent), not against nextCursor (the newer cursor wait just returned). So if wait advances c1 -> c2 and the read returns any cursor other than c1 (e.g. its own older/paging cursor r0), afterCursor becomes r0, discarding c2.

Related: the pre-loop read at skills/codex-graph/scripts/task_collection_harness.js:173-179 seeds afterCursor from the read tool's cursor and then feeds it into the wait request at line 204, mixing cursor namespaces from two different tools. The documented pattern in skills/codex-graph/references/task-lifecycle.md:200-208 never adopts the read cursor for wait, so harness and docs disagree.

Suggested change
// Prefer wait progress; only take read's cursor when it advances past the
// request cursor. Read often echoes the request afterCursor when there is
// no further page, which must not rewind a newer wait cursor.
const requestCursor = request.afterCursor;
if (nextCursor !== undefined) afterCursor = nextCursor;
if (isValidTerminalHandoff(snapshot.terminal, nodeId)) {
terminal = snapshot.terminal;
if (readCursor !== undefined && readCursor !== requestCursor) {
afterCursor = readCursor;
}
previousFingerprint = fingerprint;
// Prefer wait progress; only take read's cursor when wait produced none.
// Read often echoes the request afterCursor when there is no further
// page, which must not rewind a newer wait cursor.
const requestCursor = request.afterCursor;
if (nextCursor !== undefined) {
afterCursor = nextCursor;
} else if (readCursor !== undefined && readCursor !== requestCursor) {
afterCursor = readCursor;
}
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines 193 to 198
if (hasNewData) {
collectionRounds += 1;
idlePolls = 0;
collectStructuredItems(snapshot.items);
} else {
idlePolls += 1;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Documented collection loop no longer stores any of the worker output it receives

The step that saved the worker's returned output items was deleted from the documented collection loop (skills/codex-graph/references/task-lifecycle.md:193-195), so scripts generated from this pattern keep only the final summary object and throw away every intermediate item they fetch.
Impact: Graphs built from this guidance lose the collected evidence items, so blocked or partial runs report no gathered work even though it was retrieved.

Removed item collection in the reference snippet

The previous snippet called collectStructuredItems(snapshot.items) inside the hasNewData branch. The new snippet increments counters only and never accumulates snapshot.items, nor does it collect items from the paired read_thread result at skills/codex-graph/references/task-lifecycle.md:202-210; only handoff is retained. This contradicts section 5 of the same file (skills/codex-graph/references/task-lifecycle.md:230-233), which requires blocked results to carry every collected upstream handoff/evidence, and it diverges from the harness implementation, which does accumulate items via ingestSnapshot (skills/codex-graph/scripts/task_collection_harness.js:141-153).

Suggested change
if (hasNewData) {
collectionRounds += 1;
idlePolls = 0;
collectStructuredItems(snapshot.items);
} else {
idlePolls += 1;
}
if (hasNewData) {
collectionRounds += 1;
idlePolls = 0;
collectStructuredItems(snapshot.items);
} else {
idlePolls += 1;
}
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

@jnyross
jnyross merged commit dce28be into main Aug 9, 2026
4 checks passed
@jnyross
jnyross deleted the fix/collect-completed-handoff-on-first-wait branch August 9, 2026 14:37
cursor Bot pushed a commit that referenced this pull request Aug 9, 2026
Await-adjacent matching correctly skips wrapper collectors, but treated
scripts with no read/wait bindings the same way and green-lit #13.
Require tool bindings when there are no await-adjacent call sites.
jnyross added a commit that referenced this pull request Aug 9, 2026
…es (#16)

* feat: dynamic-workflow golden test cases from real Grok/Claude orchestration shapes

Turn curated Grok Rhai workflows (destination/hotel discovery funnels,
fixed-lane research DAGs) and Claude multi-agent patterns (disjoint
worktree implementers, review-scorer panels) into a maintainable
codex-graph test-case pack:

- docs/dynamic-workflow-testcase-catalog.md: source survey, shape
  analysis, tier/contract mapping, prioritized shortlist
- skills/codex-graph/testcases/: catalog.json + six case bundles
  (GOAL.md, EXPECTATIONS.md with fenced machine contract,
  topology.hint.mmd passing graph_coherence.py)
- testcases/harness/: offline expectations loader + static workflow.js
  checker (per-node env #14, read-first collection #13, node-local
  prompt scoping #12, result normalization #11) with CLI and 15 tests
- task_collection_harness.test.js: three pattern-derived fixtures
  (atomic screen fan-out terminal-at-first-read, screen-then-POV
  staged cardinality with root-owned fail-open, adversarial dual
  validators failing closed on malformed verdicts)
- both regression runners execute the new suite and lint the hints

Goals are synthetic and anonymized; no live Desktop run required.

* fix: harden expectations checker per PR #16 review

- collection:read-first / read-after-wait judge await-adjacent call
  sites only; parameter lists, bindings, and comments can no longer
  flip the verdict (v3 param-swap now fails; wrapper-based correct
  collectors are no longer false-failed)
- setup:pending-resolution requires bounded-resolution evidence
  (attempts constant or task-list poll) alongside the clientThreadId
  identifier; mentions-only scripts fail
- checkWorkflowText refuses vacuous ok on an empty contract
- atomic-screen-fanout goal genericized (composition/origin/month)
- disjoint-writers-worktree contract declares its drawn repair path
  (single_repair, R1, V2)
- four new negative/positive controls in testcases.test.js; README
  semantics updated to match the strengthened checks

* fix: fail collection checks when read/wait tools are absent

Await-adjacent matching correctly skips wrapper collectors, but treated
scripts with no read/wait bindings the same way and green-lit #13.
Require tool bindings when there are no await-adjacent call sites.

---------

Co-authored-by: Cursor Agent <[email protected]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants