Task orphan check

From sonichi/sutando · View interactive version

Task orphan check is an AI agent skill from the GitHub repository sonichi/sutando. Resolve orphan tasks left in `<workspace>/tasks/` from a previous session that crashed mid-execution. Classifies each live task as done / fresh / stale by cross-referencing per-side-effect markers, then archives or recovers as appropriate. Runs once on startup; safe to re-invoke.

How to use this skill

Skill file

Task orphan check

Recovery half of the post-#1049 task-bridge redesign. Replaces the brittle attempts-counter (#1049 + #1066's followup) with a startup-time classification pass that uses existing side-effect markers (PR #1048's .sending files for Discord, result files in results/, archive presence) to decide what to do with each live task in <workspace>/tasks/.

Usage: /task-orphan-check

Designed to be invoked from /startup (PR #1072) as step 1, before /schedule-crons starts the task watcher. Also callable standalone for manual recovery.

Why this exists

If the agent crashes mid-task with non-idempotent side effects already executed (Discord message sent, file written, API call made) but the archive of result + task files never ran, on restart the task file is still in tasks/. The watcher re-emits it. The agent re-processes. The side effect fires a second time.

PR #1049 tried to solve this with an attempts: N counter inside the task file — but the bumper-write fired the watcher's own Renamed event, creating an infinite self-trigger loop. PR #1066 tried to patch the loop by switching to in-place writes — but on macOS, open(file, 'w') STILL fires the Created event because O_WRONLY|O_CREAT|O_TRUNC flips the ItemCreated bit. Both PRs are working around the wrong layer.

This skill moves the dedup logic out of the watcher's event surface entirely. The agent does a single classification pass at startup, cross-references markers that already exist (PR #1048 ships them for Discord delivery; result files in results/ mark "this task was completed"), and decides per-task what to do. No counter, no in-band writes, no self-trigger loop.

On Activation

The procedure below is non-LLM where possible — mechanical file checks + side-effect marker reads. The LLM-judgment parts are bounded (per-task classification with explicit decision rules).

Step 1 — List live tasks

WS="$(bash scripts/sutando-config.sh workspace)"
ls "$WS/tasks/"task-*.txt 2>/dev/null | head -200

If no live tasks, emit "orphan-check: no live tasks, nothing to recover" and idle.

Step 2 — Classify each task

Run the classifier; do not re-derive the verdicts by hand:

python3 skills/task-orphan-check/scripts/classify.py        # add --workspace DIR to override

It prints one JSON object — tasks[] with id, source, access_tier, channel_id, label (the readable channel label step 3b uses), age_s, import (with import_intent; import_task_id — the task_id the current status.json carries, null when it has none; and for a bound or unbound run import_phase / import_idle_s), verdict (done / held / worker-held / unknown / fresh / orphan / import-resume / import-stalled / import-unbound; a worker-held row also carries holder, the recipient id) and a reason naming the marker, sentinel or age line it matched — plus counts. Read-only: it moves and writes nothing; step 3 acts on its verdicts. The rules it encodes are the ones below (pinned by tests/task-orphan-check-classify.test.py); if you change a rule, change the script and its test, then this prose.

For each file in tasks/, let <id> be the value of the id: header line (e.g. task-1779570142563). The file is tasks/<id>.txt. Per-task paths below use <id> consistently — note <id> already includes the task- prefix; do NOT add it again.

  1. Parse the header — extract id, timestamp, source, channel_id (Discord channel or ag2.space room id — both producers supply it, and the later contextNotFrom/requeue workflow needs the exact id, so never discard it in favor of the friendly name), chat_id (Telegram), room_name / channel_name (whichever the surface carries — ag2.space sends room_name and no channel_name, so a reader that parses only the latter gets nothing and step 3b falls back to the raw id), user_id, access_tier (owner / team / other; default to owner if the field is absent — pre-tier task files predate the field and were authored by the owner). The classifier reads them with local_task_protocol.parse_task_headers_lenient — the shape-union parser — because this pass sees files from every writer and era: the desktop's legacy Claude-import writer is task-mid (task: before channel_id:), and the strict task-last parser would read its channel_id and priority as absent.
  1. Cross-reference completion markers (any single match = task already completed):

Step 2b — .sending contract clarification (per qingyun-sutando review of #1074):

| site | gate applied before .sending |

|---|---|

| src/discord-bridge.py claim loop | f.name.startswith("proactive-") |

| src/slack-bridge.py claim loop | f.name.startswith("proactive-") |

| src/telegram-bridge.py claim loop | PROACTIVE_PREFIXES = ("proactive-", "briefing-", "insight-", "friction-") |

This line previously described the task form as a live mid-delivery state. It is a dead branch, and not a harmless one: on 2026-08-02 it was cited as a real completion namespace while reviewing #2525, which would have added handling for a case that cannot arise. tests/sending-suffix-is-proactive-only.test.py pins the invariant; if a future change does start claiming task results by rename, that test fails and this row must be restored with the producing site named.

Step 2c — a task a worker holds is not the core's orphan. The pool router delegates a task by writing a sentinel deliveries/<recipient>/<id>{.txt,.accepted,.claimed}; the payload stays in tasks/, where the recipient reads it. Once ANY worker holds a sentinel — even an unaccepted one — the task is that worker's to answer, and the core's age line says nothing about it: on 2026-09-18 the boot pass archived four owner DMs held by two worker seats (6–26 min old, no result yet because the workers were mid-answer) and reported them to the owner as unanswered. The predicate is skills/worker-pool/scripts/worker_delivery.py:holder_of (the worker-pool skill is optional: absent skill ⇒ no router ⇒ nobody holds anything) — the same one the Stop hook (src/check-pending-tasks.sh) and scripts/unanswered-tasks.py apply — never a local re-scan of deliveries/. It answers None only when the directory or sentinel is genuinely absent (ENOENT); any other stat failure propagates, and the classifier turns that into UNKNOWN, because reading an unreadable deliveries/ as "nobody holds it" is exactly what hands a worker's task to the core. A completion marker (step 2) still wins: a held task with a result is done.

  1. Compute age — use the IMMUTABLE arrival time, NOT file mtime (mtime gets reset by rsync, git checkout, touch, or workspace sync, which would make a genuinely old orphan look FRESH and re-fire its side effect — exactly the bug this skill exists to prevent):

Step 3a — consented Claude-Code import tasks are not orphans at 5 minutes. A task is an import task when it is owner-tier and carries a run intent: the header channel_id: onboarding-wizard (the desktop's legacy Import-button writer, claude_import.rs); the slash command /import-claude-context as a standalone token; or one of the documented trigger sentences, case-insensitive — "import my Claude history", "import my Claude Code history" (the onboarding DM message and the Settings sentence both contain it), "read my Claude Code sessions", "bring my Claude context along". A path or a bare skill-name mention is not an intent: an owner review task reading "Review PR 4177 which touches skills/import-claude-context/SKILL.md" classifies like any other task (orphan at 5 min, archived with a re-queue line) — the first cut matched the bare substring and would have parked that task in tasks/ forever, invisible to the recovery DM (#4177 review). The import is consented, idempotent and resumable (skills/import-claude-context/SKILL.md), and its main task is expected to take seconds — but on 2026-09-11 (desktop v0.6.8-rc3, engine 4b02fbaf) the core answered the greeting, ran its boot recap and went idle without starting it, so at 322 s the prose rule above would have archived a task the owner had just consented to and posted it in the recovery DM instead of letting the watcher's startup sweep re-emit it. Its marker is <workspace>/data/claude-import/status.json — written by index.py in the same seconds as the acknowledgement DM (results/proactive-<ts>.txt, which the bridge claims and archives, so it cannot serve as a marker). It is read as this task's only by identity, never by timestamp: status.json is one global file, and every phase the import scripts write carries the task_id the run was started with (index.py --task-id <id> — skills/import-claude-context/SKILL.md step 1 — stores run: {task_id, run_id} in state.json, and _common.write_status stamps both onto every status). A status is bound to a task when status.task_id == <id>. A status bound to a different task is, for this task, the same as no status (#4177 review: an older run A ending after a genuine new request B was queued satisfied "newer than the task" and B was archived as done without ever executing — the absent row classified orphan correctly, the timestamp was never a receipt). A status with no task_id (a pre-#4177 writer, or index.py run without --task-id) that post-dates the task may be this task's run or another's: not enough to archive, enough to report — fail toward recovery, since a spurious DM line costs a line and a wrong archive costs the owner's import.

The "never orphaned" guarantee is bounded, and here is the window. index.py writes status.json (indexed) after the index files and state (index.py line ~482–490), so the durable "started" flag lands after step 1's effect, not before it. An import that dies mid-index — between the acknowledgement and that write — leaves no marker, gets the 30-minute line above, and is then orphaned like any other task: archived, listed in the DM with its re-queue line, restartable by the owner saying "import my Claude history". That outcome is recoverable, so the write is not reordered; but a started import is only never-orphaned from the indexed write onward.

  1. Classify outcome:

Step 3 — Recover orphan tasks (tier-aware)

ORPHAN handling depends on source because text-side recovery only makes sense for surfaces where the owner can still see and act on the DM. Voice/phone conversations don't replay in text. The flat per-task sentinel that v0.1.1 used was the wrong default for high-volume team-tier orphans whose conversation threads had moved on — see feedback_orphan_check_tier_classify_before_sentinel for the 2026-05-26 post-mortem (22-message blast across 5 channels, 13 of them into one active episode thread).

Invocation contract. orphan-check runs once at /startup step 1 (PR #1072), BEFORE the task watcher attaches. Under that contract the deferred branch (row 2 of the table below) has no race window — the watcher isn't running between step 3's defer-decision and step 3b's archive mv. If you invoke /task-orphan-check standalone with a live watcher already attached, the deferred branch is racy: the watcher may pick up the un-archived tasks/<id>.txt between step 3 and step 3b and re-classify it as FRESH or ORPHAN on its own pass (no results/<id>.txt exists yet, so the completion-marker check in step 2.2 won't catch it). Safe workaround for standalone invocation: rename tasks/<id>.txt → tasks/<id>.txt.deferred at defer-time so the watcher's task-*.txt glob skips it, then have step 3b mv tasks/<id>.txt.deferred → tasks/archive/<id>.txt atomically. Verify the watcher's glob actually excludes the suffix on your installation before relying on it.

Decision table — apply per orphan, first match wins:

| source | Action |

|----------|--------|

| voice / phone (any tier) | Silent archive. Text recovery to a voice/phone surface is the wrong shape; the conversation has hung up or moved on. mv tasks/<id>.txt tasks/archive/<id>.txt. No result write. Log: archived-silent: voice/phone source. |

| any other source (incl. discord / telegram / slack / chat / whatsapp / email / missing field / future surfaces) | Defer; aggregate in step 3b. Append <id> to an in-pass deferred_orphans list (along with its access_tier for per-tier counting). Do NOT write a per-task result. Do NOT archive yet — leave the task file in tasks/ so step 3b consumes it (see "Invocation contract" above for the standalone-invocation .deferred suffix workaround). Log: deferred: queued for consolidated DM (source=<source>, tier=<tier>). |

All tiers (owner / team / other) flow through the same aggregated DM so the owner has visibility into stale tasks across all tiers — previously, team/other-tier orphans were [no-send]-archived and the owner had no record. Preview-extraction in step 3b strips the bridge-injected system-instructions block so non-owner previews show the actual user ask, not boilerplate.

Step 3b — Aggregate deferred orphans into ONE proactive DM

Run once at the end of the orphan pass, after every orphan has been classified by the table above. If deferred_orphans, stalled_imports, unbound_imports and unknown_holds are all empty, skip. (A stalled or unbound import alone still earns the DM — it is the only surface that run reaches.)

Otherwise:

  1. ts=$(date +%s).
  1. Extract preview body for each orphan, stripping any in-band system-instructions block. Non-owner-tier task files have a ===SUTANDO SYSTEM INSTRUCTIONS=== block injected at the FRONT by the bridge (src/discord-bridge.py). Previewing the first 100 chars without stripping would leak the boilerplate, not the user's actual ask. For each <id>:

```python

body = read("tasks/<id>.txt")

if "===SUTANDO SYSTEM INSTRUCTIONS===" in body:

after_first = body.split("===SUTANDO SYSTEM INSTRUCTIONS===", 1)[1]

if "===" in after_first:

body = after_first.split("===", 1)[1]

preview = body.strip()[:100]

```

The system-instructions block is only stripped for the preview — the archived task file body remains intact (see step 5), so re-queueing via mv tasks/archive/<id>.txt tasks/ preserves sandboxing for non-owner tiers.

  1. Resolve a readable channel label for each orphan, then group.

channel_id alone is unreadable in a report — !JzcRmAhNYbiWhIWNCL:ag2.space

tells the owner nothing about which conversation stalled. The task file already

carries the name the bridge saw:

```python

name = header.get("room_name") or header.get("channel_name") # bridges write one of these

cid = header.get("channel_id") or header.get("chat_id") or ""

label = f"{name} ({cid})" if name else (cid or "DM")

```

Use label everywhere the report shows a channel. Keep the id: it is what

contextNotFrom and re-queue commands key on, so dropping it trades one

unreadable report for an unactionable one. Group deferred_orphans by

access_tier (owner / team / other) → per-tier counts; and by label →

per-channel counts.

  1. Apply step 3c bomb-guard (see below) to decide whether to truncate the preview list.
  1. Write <workspace>/results/proactive-orphan-recovery-${ts}.txt:

```

Orphan recovery — N stale tasks from a prior session (oldest <Nm>, newest <Nm>, no completion markers).

By tier: owner (<o>), team (<t>), other (<r>).

By channel: <name> (<id>) — <x>; <name2> (<id2>) — <y>; DM — <z>; ...

Previews (most-recent first, first ~100 chars of task body; in-band system instructions stripped):

[If truncated by step 3c: "+<N-20> more — see tasks/archive/ for the full list."]

[If stalled_imports is non-empty, one line per entry, from the classifier's import_phase / import_idle_s:]

Import stalled at phase <p> since <idle, e.g. 3d 2h> (task-<id>, still in tasks/ — it resumes on the next sweep; say "import my Claude history" to resume it now, or /import-claude-context --discard to drop the run).

[If unbound_imports is non-empty, one line per entry, from the classifier's import_phase / import_idle_s:]

An import run started (phase <p>, last moved <idle> ago) but cannot be matched to this request (task-<id>, still in tasks/ — its status carries no task id); say "import my Claude history" to re-run it, or /import-claude-context --discard to drop the run.

[If unknown_holds is non-empty, one line per entry:]

Could not read deliveries/ for task-<id> (<error>), so whether a worker holds it is unknown — left in tasks/, not archived; if it is yours it will be answered by the next sweep, otherwise check the host's file permissions (TCC on ~/Documents is the known cause).

To re-queue an individual task: mv "$(bash scripts/sutando-config.sh workspace)/tasks/archive/task-<id>.txt" "$(bash scripts/sutando-config.sh workspace)/tasks/" (M0 helper resolves to <workspace>/tasks/... — <repo>/workspace/tasks/... by default).

The archived file retains its original body (incl. system-instructions block for non-owner tasks), so re-queueing preserves sandboxing.

If none still matter: no action needed — they're already archived.

```

  1. For each <id> in deferred_orphans: mv tasks/<id>.txt tasks/archive/<id>.txt. Entries of stalled_imports, unbound_imports and unknown_holds are not moved — they stay in tasks/ so the watcher's sweep can resume or re-run them.

The bridge routes proactive-* to the owner's DM (single delivery), not back to each origin channel. Log: aggregated-all-tiers: <N> orphans → 1 proactive DM (owner=<o>, team=<t>, other=<r>).

Step 3c — Bomb-guard (defense in depth)

Two layers:

  1. Total-deferred-count cap. If len(deferred_orphans) > 30, truncate the preview list in step 3b's DM body to the 20 most-recent orphans and add a footer: +<N-20> more — see tasks/archive/ for the full list. The per-tier and per-channel count lines remain accurate (they reflect the full set, not the truncated preview list). This bounds DM size when a long crash (multi-day) leaves dozens of stale tasks.
  1. Per-channel-delivery guard (future-proofing). If any future code path adds per-channel result writes (e.g., a 3rd table row that bypasses both silent-archive and the aggregated DM), tally per-channel deliveries; collapse any single channel_id receiving >5 into one summary post. Today the table emits zero per-channel posts (voice silent, everything else aggregated into one owner DM), so this branch is a no-op — defense so the next person who adds a 3rd row can't accidentally re-create the v0.1.1 noise-bomb.

Step 4 — Sanity check archive directory

Confirm tasks/archive/ exists; create if not (mkdir -p). Should always be present in normal operation; defensive.

Step 5 — Emit summary

orphan-check complete:
  total live tasks scanned: N
  archived as done (completion marker found): M
  left fresh for watcher: K
  left for the core after a limit hold (held): H
  left for its worker (worker-held): W
  left in place, deliveries/ unreadable (unknown): X
  left for the watcher as a started import (import-resume): I
  left for the watcher but reported as stalled (import-stalled): S
  left for the watcher but reported as unmatched (import-unbound): U
  recovered as orphan (sentinel result written): J

The summary lands in the conversation buffer so the agent's first turn (and operator) sees what happened. If M+K+H+W+X+I+S+U+J ≠ N, the script bailed mid-pass — log a warning and let the operator investigate.

What this DOES NOT touch

Known residual risk: the <5min sub-window for non-Discord surfaces

A task that arrived <5 minutes before a crash, executed its side effect, then died before writing its result file has NO completion marker AND looks FRESH (age < 5min) → orphan-check leaves it for the watcher → side effect re-fires. Unavoidable without per-side-effect markers, and the .sending markers only close it for Discord.

Currently covered: Discord DM delivery (PR #1048's .sending), file presence in results/, the Claude-Code import's data/claude-import/status.json (step 3a — read by the task_id it carries, never by timestamp; the import is resumable, so this marker exempts rather than re-fires; it is written after step 1's index, so a run dying before that is orphaned recoverably at 30 min).

Residual hole, in priority order:

Conservative default for the hole: any orphan without a CLEAR completion marker gets the recovery-sentinel treatment, which surfaces to the operator rather than silently re-firing. As other bridges/tools grow their own per-side-effect markers, orphan-check should learn to read them at step 2 — the marker list is intentionally a code-level data table, not buried in prose.

What it MIGHT need in the future

Failure modes

Why not just clear `tasks/` at startup?

That would lose tasks that legitimately arrived in the gap between previous session's death and this session's startup. Those need to be processed, not nuked. The classification pass distinguishes "completed but unarchived" from "arrived and never seen."

Relationship to other PRs

Implementation note: classification is a script, recovery is prose

Step 2 runs scripts/classify.py (read-only, stdlib + src/local_task_protocol.py + src/core_limit_hold.py; tests/task-orphan-check-classify.test.py). It exists because the rules stopped being "marker-or-not + age-vs-5min" the day the import exemption (step 3a) was needed, and a rule that only lives in prose is applied by whichever reading the agent makes that boot — the 2026-09-11 run reasoned its way to "would now classify … as an ORPHAN" about a task it had itself left unstarted. Steps 3–5 (the archive moves, the aggregated DM, the summary) stay agent-executed: they are small per pass (typically 0-3 live tasks) and each is a plain Bash/Write call over the classifier's verdicts.

Iteration log

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.