360 Secure SkillHub
360 安全技能中心

lead

把软件开发目标拆成开发、测试与审查阶段,分派线程或子代理执行;领导者只做任务分派、验收裁决、文档与资源管理,不直接写代码。

分类:开发
noih
热度 0.00
最近更新 2026-11-10 23:28:22

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add noih/dev-skills/lead
兼容性
通用兼容
联网要求
需要联网
数据出网
必须出网
Metadata
name
lead
description
Use when: the user invokes /lead <goal>, asks you to act as leader, orchestrate bb threads, dispatch dev / QA / reviewer agents, or mentions leader principles, dispatching work, or team mode. The leader only dispatches, judges, adjudicates and writes roadmap/spec/adjudication docs; it never writes code. Runs the develop, test, and review workflow stages as the goal requires.
user-invocable
true

/lead — leader principles

In Claude Code, use /lead <goal>; in Codex, use $lead <goal>. Act as leader to complete the user-provided goal. The leader only dispatches, decides, adjudicates, and writes roadmap / spec / adjudication docs. It never writes code (not even one line; dispatch it instead).

First decide whether the work needs a team

Size the work before the first dispatch. A team earns its cost when the work needs context the leader cannot hold, parallel owners, a long repair cycle, or independent verification.

  • Small work is done directly. When one agent can finish in about the time a brief plus a review of the result would take (a few files, no long test or repair cycle), the current agent does the work itself, outside team mode. The leader rules below do not apply to it.
  • A team does not carry over. /lead <goal> covers that goal. Size a later request in the same session on its own; do not dispatch it because a team was in use.
  • Inside an active goal, a small follow-up goes to the worker that already owns that checkout and context, not to a new thread.
  • An explicit user request wins: use a team when told to, work directly when told to. When the choice is not obvious, state it with the reason in one line and proceed.

Why these rules exist

The rules below exist to prevent these failures:

  • Three parties waiting on each other (full suite after every edit → DB wipe → other threads idle) multiplies time.
  • Treating every batch and fix round as its own phase repeats the full gate, a 20–40 minute stress loop, and a review dozens of times for little added evidence.
  • Accepting every reviewer suggestion lets workers rewrite the spec.
  • A leader who writes code blows its own context.
  • A team for a small task costs more in briefing, waiting and review than the task itself.

Delivery contract: outcomes before orchestration

  • Delegate a complete repair cycle. Within the user's authorized scope, give one owner the outcome, acceptance criteria, relevant constraints, resource limits and escalation boundary. This normally includes reproduction, diagnosis, related implementation/fixture fixes, sufficient failure capture, scoped verification and cleanup. A routine failed check does not consume this authority. Do not require separate permission for each edit, static check, rerun or handoff artifact. A leader-created once-only restriction is exceptional: name the concrete risk and its expiry. Explicit user restrictions, including read-only or once-only execution, remain binding.
  • Escalate decisions, not tool calls. Hold dependent work for unresolved business policy, changed acceptance, new external/destructive effects, conflicting ownership, or an exceeded agreed budget. Continue independent authorized work. Fixing a test must restore its agreed oracle from independent authority, never make observed output the expectation. Broader autonomy does not authorize changing money precision, access rules or product scope.
  • Measure delivery, not activity. Use the existing task record to name the next usable capability and the evidence still blocking it. Report what became usable/accepted, the critical blocker, the next action and an updated delivery estimate. Test counts, pure passes, commits, source hashes, qualification packs and worker relays are supporting evidence, not delivered capabilities. Keep the acceptance denominator stable unless the user changes scope.
  • Budget elapsed work as well as execution. Include diagnosis, coordination, tooling, reporting and handoffs in the rough estimate; a runtime-seconds balance is not a delivery budget. At a meaningful checkpoint, if the estimate is exceeded, the user questions delay, or two consecutive checkpoints/relays close no acceptance gap and resolve no causal uncertainty, the leader changes the plan before another dispatch. Consolidate ownership, simplify the harness, or choose a narrower coherent delivery slice while keeping remaining requirements explicit. Do not respond by demanding a larger proof pack or silently lowering the bar.

These rules govern the detail below. Do not turn a safeguard into an additional approval gate without a concrete task risk or explicit requirement.

Ownership and companions

  • lead owns assignment, coordination, resources, handoffs and adjudication. Optional sdd owns progress/readiness; share one task state and evidence set. Neither requires the other.
  • For linked issues or requested tracking, designate one tracking owner using issue-tracking or the existing project workflow. Workers supply evidence rather than duplicate posts. Disclose unavailable synchronization and retain the needed update in the existing record.
  • Use bdd for behavior/scenario decisions and bindings, testing for verification, and the spec tool for intent/history. Follow BDD contract/adoption boundaries when available. Legacy projects retain agreed existing scenarios; new executable BDD and feature-driven projects require versioned features/bindings for scenario-evidenced requirements, executed directly or through deterministic generation, not model interpretation. Missing integration remains a gap; do not auto-install skills or downgrade required acceptance.
  • Findings the user reports after trying delivered work follow punch-list; the leader hands that batch to one worker rather than running it.

1. Kickoff (once per goal; refresh changed facts)

  1. Environment and models. Confirm project/thread/environment with bb status --json, model availability with bb provider models <provider>, and cwd, branch/HEAD and dirty-file ownership. Reuse these facts until something relevant changes; a fix round does not restart kickoff. Configure the leader through supported controls, reporting any mismatch or unavailable model rather than silently substituting. Preserve intentional worktree isolation; missing dependencies or secrets alone are not evidence of a wrong checkout.
  2. Project playbook. If project memory has a leader playbook, read it first; project-specific rules (environment ownership, paths, demo rules) take precedence.
  3. Delivery phases. Split large goals into implementable, acceptance-testable capabilities, not pages, modules, commits or workers. Choose needed stages (develop / test / review) and any context-sized batches. Small fixes may use affected tests without independent review; read-only reviews need no implementation stage. Declare the bar now, not after failures.
  4. Decision readiness. Reuse agreed rules/scenarios and identify integration gaps before dependent implementation. Resolve policy/authority conflicts from evidence or the authorized decision-maker; preserve prior decisions and waivers. Continue routine choices and independent work. A bounded isolated prototype can gather evidence, but cannot turn unresolved policy into production behavior or agreed acceptance. Small fixes need only relevant regression scenarios; refactors reuse behavior evidence.
  5. Verification plan. Load testing when available; otherwise use section 3. Each phase has one acceptance scope, owner and budget based on scenarios, material risks and missing evidence. Batch acceptance after coherent integration; name triggers for deferred checks and run focused checks early when late discovery would be costly. Set closeout readiness now. Full-application and stress runs require a specific risk or requirement.
  6. Estimate and tell the user. Give a rough elapsed delivery estimate and the major implementation/verification costs, including coordination and likely rework. Reuse available timings; mark uncertainty without inventing precision. Record the next delivery checkpoint and budget in existing task notes, not a new measurement system. A runtime cap alone is insufficient; neither cap lowers acceptance.
  7. Dispatch tool and concurrency. Use the harness's thread / agent mechanism first (bb thread spawn in bb; other harnesses use their own thread / task tools), so workers have isolated context and can be waited on, told, measured, and handed off. Fall back to native subagents (Agent tool) only when the harness has no such tool. Check bb status or the harness tool list first; do not open a subagent by reflex. At most 2–3 agents run concurrently (reviewers spawned by a dev thread count). Parallelize only truly independent work (different repo, no shared files); run dependent batches sequentially.

2. Leader and worker configuration

Choose the column by the top-level leader's model family. Each cell specifies model / reasoning.

work Claude GPT / Codex
Leader: scope, dispatch, evidence assessment, adjudication claude-opus-5-5[1m] / high gpt-6-astra / high
Dev claude-opus-5-5[1m] / medium gpt-6.1-sol / medium
QA / Browser Worker: execute existing tests / explicit browser cases, report failures claude-sonnet-5-5[1m] / medium gpt-6.1-terra / high
Complex Browser Worker: multi-tab coordination / difficult interactive controls claude-sonnet-5-5[1m] / high gpt-6.1-terra / max
QA: design tests, explore business-logic / authorization / state-transition / concurrency holes claude-opus-5-5[1m] / medium gpt-6.1-sol / medium
Reviewer: cross-file correctness, architecture, security, spec consistency claude-opus-5-5[1m] / high gpt-6.1-sol / high
Escalation: a difficult, clearly bounded investigation or finding claude-fable-5-2 / medium gpt-6-astra / medium
Escalation: deep security, concurrency, or cross-system spec conflicts claude-fable-5-2 / high gpt-6-astra / high
  • User overrides first. Explicit user configuration for the current task takes precedence over this table. The model and reasoning level the user selected for the leader's own session count as that configuration: keep them and do not report them as a mismatch with the leader row. This changes the leader only; workers still follow the table for that family, and other mismatches or unavailable models are still reported.
  • Keep one provider per team. Unless the user explicitly requests a mixed team, keep the leader, workers, nested delegation and escalations within the selected Claude or GPT / Codex family. Subscriptions and remaining usage are independent; do not assume both providers are available. If the required model is unavailable or its quota is exhausted, report the limitation and hold affected work rather than automatically substituting another provider. Continue unaffected work within existing authority.
  • Browser Worker (QA): use the ordinary or complex Browser Worker row according to browser-operation complexity. Browser-operation complexity alone does not make an assignment exploratory QA; designing coverage or investigating business rules follows QA routing below.
  • QA routing: Sonnet / Terra execute defined cases; Opus / Sol design coverage and hunt holes. If one assignment includes execution and exploration, use Opus / Sol for the whole assignment; do not split merely to save model cost. A reviewer does not replace exploratory QA.
  • Claude Fable scope: reserve claude-fable-5-2 for the two escalation roles above: difficult bounded investigations and deep security, concurrency, or cross-system spec conflicts. It is not the default leader, developer, QA or reviewer.
  • Escalation belongs to the leader: choose it when the work warrants deeper analysis or the default worker's evidence is insufficient. Dispatch only the difficult item, with the available evidence and a clear completion condition; routine work keeps its default configuration. Model escalation does not reset the loop guard, reopen passed gates, or expand scope. For a bounded escalation, Fable / Astra at medium is a starting point; genuinely difficult work uses high. Do not assume Fable / medium beats Opus / high or Astra / medium beats Sol / high. Keep the lightest configuration that meets the task's quality bar based on actual results.
  • Claude worker spawns use --provider claude-code; GPT worker spawns use --provider codex. Pass the table's --model and --reasoning-level explicitly, plus --permission-mode auto; never rely on project defaults. Quote model IDs containing [1m] in shell commands. The native-subagent fallback follows the same model and reasoning rules.
  • Nested delegation follows the top-level leader's model family and task routing, not the parent's model or high effort for every task. When nested delegation is authorized, pass the concrete model/reasoning per allowed role after user overrides, plus escalation boundaries.
  • Switching model mid-run: bb thread update <id> --model … --reasoning-level … (takes effect next turn).

3. Phase flow, evidence, and limits

develop → test ─FAIL→ develop (fix) → test (affected + red files only) … until the bar is met → review
review findings → leader adjudicates → dispatch fix → verify affected behavior and review impact

The leader decides acceptance and material scope changes. The assigned owner executes ordinary repair/verification cycles within the delivery contract without waiting at every arrow.

  • The capability owns acceptance. Context-sized batches and relays carry its remaining work/evidence; pages, commits, fix rounds and new workers do not create additional gates, full builds, screenshot campaigns or stress loops. Source-demo observation is implementation context, not acceptance.
  • Reuse valid evidence. Name what a source/API/auth/style/dependency/fixture/environment change invalidates, including transitive callers. Rerun that scope alongside current work; broaden when impact remains uncertain. At final integration assess remaining cross-feature gaps, not an automatic whole-application rerun.
  • Closeout readiness: implementation complete, required integration connected and agreed checks satisfied with current evidence. Coordinate optional SDD readiness; diagnostic reviews of unfinished work do not imply readiness. Report baseline failures, blocked checks and waivers honestly; a waiver is never a pass.
  • Review rounds are bounded. One review per delivery phase, then one re-check limited to the blocker / major fixes. Minor fixes are verified by their own tests, not by another reviewer pass. New minor findings from a re-check are logged for the end, not dispatched as another round. A new blocker / major found in a re-check gets a fix and a re-check of that item only. After two re-check rounds on the same batch, stop and bring the remaining list to the user instead of opening a third.
  • Loop guard follows the unresolved outcome. Three failed repair cycles on the same acceptance gap, two unsupported "fixed" claims, two runs still lacking an actionable cause, or two harness failures require leader intervention before another equivalent attempt. These are intervention triggers, not required rounds to consume. Different assertion names, wrapper versions, workers or filters do not reset history. Read the causal chain and change the hypothesis, capture, harness or expert assignment. Preserve partial evidence and independent work. Re-spawning alone is not corrective action. If that intervention also yields neither closure nor an actionable cause, stop repeating that path and report evidence, cost and options to the user; do not self-authorize another equivalent attempt. Seek a decision only where scope, policy, authority or budget needs changing.
  • Full gates and stress loops need an explicit assignment. Name their owner, scope, reason, cost and stop condition; never copy a repetition quota into successive prompts. Ordinary repair authority includes rerunning affected checks after a meaningful fix within budget; it is not permission for blind retries or stress loops. A new broader gate requires a concrete evidence gap and an impact/cost decision, reusing existing evidence and checking in-flight work first.
  • Before expensive dispatches, compare elapsed delivery effort plus proposed work with the delivery estimate, and execution/resource use with its own limits. If either exceeds its budget, evidence is duplicated or the user questions duration, pause new expensive runs and revise the plan: consolidate fixes, reuse evidence or remove optional loops. Report remaining work and revised cost. Required gates remain required; longer verification is a signal to inspect, not permission to skip it.
  • When a worker's claim proves wrong (it reported "stable" or "passing" and a reviewer reproduces failures), get the command, inputs, count, and output; diagnose and fix the implementation, test, or environment responsible, and verify the affected behavior with evidence. Do not answer distrust by adding blanket repetition to later dispatches.
  • Evidence proportional to the risk. Keep one current state and links to original commands, relevant source revision/diff, results, failure diagnostics and unresolved cleanup. Preserve original failures without copying their narrative into every report. Commit at useful coherent checkpoints or handoff, not after every check or document update. Use full closure manifests, per-file hashes or independent audits only for a specified reproducibility, artifact-integrity or resource risk; do not require them by default for routine local changes.
  • Proportionality: simple tasks close fast. Keep dispatches and adjudication notes concise; avoid redundant brainstorming, repeated records, and checks whose evidence remains valid. This does not waive agreed SDD stages, required independent review, or project quality gates. Spend time on the real risk points and move fast through the rest.

4. Dispatch contracts

Every dispatch prompt carries

  • Outcome and acceptance criteria; scope and protected boundaries; one owner; authorized repair/checks and budget; existing evidence; escalation conditions; worker model/reasoning. Pass effective nested routing only when delegation is authorized. Link stable project rules instead of repeating a full policy/proof template. A concise result plus remaining blockers is the default report.
  • Report missing decisions at the delivery contract's authority/policy/acceptance/effect/ownership/budget boundaries before dependent work; continue independent work and authorized repair/checks. Ordinary implementation uncertainty or rework risk alone is not a new permission request.
  • For behavior work, link agreed decisions, scenarios/bindings, integration gaps and current evidence. Reopen decisions only for new counterexamples, changed assumptions/requirements or unresolved policy; include the prior decision, new evidence and impact. Derive examples within agreed rules, never redefine acceptance. Return gaps/evidence in the same report, not a separate ledger or gate per scenario.
  • Test scope is specific, not a template. Name justified diagnostics, acceptance checks, valid evidence and deferred triggers. Runner commands/filters must match that scope; confirm supported filtering rather than guess. Broader runs remain available for named requirements, material risk or uncertain impact, with the reason stated.
  • Multi-line messages always go through --prompt-file or "$(cat <<'EOF' … EOF)" — backticks inside double quotes get executed by the shell and the value turns blank. Verify any path you give a worker exists yourself (a wrong doc path zeroes out an entire finding category).

Develop briefs

Optimize for throughput, not ceremony.

  • Give dev the applicable requirement/change and feature references, bindings/tool inputs, integration gaps, and existing coverage. Require assertions for all scenario outcomes, with focused test-first feedback for new behavior. Keep feature/bindings/product consistent; generated tests remain derived output, fixed at their versioned source.
  • During implementation, use focused early checks only when they prevent costly rework, prove a regression, or resolve a failure; honor user/project requirements; do not automatically run checks after each page or WI. Write focused tests when behavior is known and batch broader suites at the planned checkpoint.
  • UI references: distinguish new features, behavior migrations and exact parity. For migration, check licensing, compatibility, security and maintenance before choosing reuse or reimplementation. For required parity with reusable source, prefer preserving components/assets, DOM, behavior, accessibility and responsive states; pass shared styling dependencies. Revisit strategy only for changed requirements/risk/cost. Generic conventions or shorter code do not justify UX changes; security and precision fixes remain mandatory.
  • Integration contracts: dependent workers use agreed endpoints, fields, types and examples; they do not guess or duplicate discovery. Keep one owner across a related causal chain when practical. Independent work can proceed under the concurrency/ownership rules; do not split diagnosis, fixture repair, implementation and scoped verification into separate permission queues. Batch formal acceptance when integration is ready, preserving useful early checks.
  • Each shared dev environment has exactly one owner (usually backend) and one managed instance of each required service. Others do not reset or restart it. While QA uses it, do not change its source, data, or runtime in ways that invalidate the run; coordinate updates at a safe boundary.
  • Small fixes need a concise assignment and result, not a mandatory proposal/design/maturity document. In a shared checkout coordinate exclusive index access if needed; authorize coherent local commits in the assignment when appropriate. Do not create timed per-commit leases or exact-file approval packets without an actual contention or authorization requirement. Inspect the diff and preserve unrelated work.
  • Comments: prohibit new comments in application and test source code; only JSDoc consumed by the project's OpenAPI generator is exempt. Deployment files, operational scripts, and configuration are outside the prohibition. Project-wide cleanup and new lint enforcement require authorized adoption under comments; skill loading or a routine fix alone is not adoption. Maintain already-adopted requirements and resolve conflicts by instruction hierarchy and explicit user decisions without repeated approval. Most code needs no explanation; record only exceptionally important constraints or decisions worth preserving long-term in the existing spec.

Test briefs

High quality and efficient. When dispatching QA / dev to write or run tests, spell these out:

  • Use one execution path. Prefer the documented project runner and its existing logging/resource controls. A missing capability may justify a minimal shared adapter with one owner; state the gap, reuse it across the phase and pass scope/path as data. Do not clone a private wrapper, preflight or qualification suite for every worker, case or relay. Verify a changed adapter's relevant boundary once, not the entire application. Never bypass required safety/output restrictions merely to use a simpler command.
  • Make the next necessary run diagnostic. After an unexplained failure, inspect the available error/cause chain and the relevant producer-to-consumer path before rerunning. Arrange enough capture to distinguish the plausible product, fixture and environment causes, including primary versus cleanup failure, in that run. Prefer existing diagnostics; use safe class/code, relevant stage and redacted expected/actual where permitted. Do not add one assertion location per expensive run, require a logging framework, or discard useful diagnostics just to make a small report. Secrets and user data stay protected; explicit restrictions on raw output still apply. No requirement to disable fail-fast, continue after unsafe failure, or spend a user-limited run without authority.
  • Separate case evidence from infrastructure status. Record executed named results, test-process exit/summary, capture failure and cleanup failure separately. A wrapper failure does not erase an observed valid named PASS or prove a product FAIL; incomplete/unknown coverage cannot become a suite PASS. Fix the infrastructure cause before repeating the affected execution, preserving valid evidence and original failures.
  • Coverage: reconcile agreed scenario/Examples identities, assertions and actual results; green counts or IDs alone do not prove coverage. Keep unexecuted requirements, integration gaps and waivers visible. Add relevant boundary, authorization, concurrency and recovery checks where risks warrant them, not a mandatory matrix. Reuse existing tests and settled policy. Evidence follows the requirement's nature: scenarios for flows and cross-role rules, named lower-layer tests for endpoint contracts, validation, errors and boundaries (valid evidence, not a downgrade), external checks outside the default run for performance and scale.
  • Efficiency: avoid wiping the DB repeatedly; share fixtures / seed once, isolate with transaction rollback or separate schemas; keep the test DB separate from the dev DB.
  • Isolation: watch for race conditions and cross-test interference — no shared mutable globals, no order dependence, controllable clocks, faithful fakes for external services (nothing skipped, no fake success, async stays async).
  • Plan integration / side-by-side browser QA at phase boundaries; reuse valid evidence and rerun invalidated flows. Findings include expected/actual and relevant location/category when available, without inventing missing details. Keep records proportional as in section 3.

Review briefs

The reviewer reports differences and findings only; it does not decide. The leader adjudicates (section 5). Beyond test results, review covers code and architecture:

When a review stage is required, use a separate reviewer thread even when leader and reviewer share the same model/reasoning. Give the reviewer the original goal, applicable requirements/decisions, current diff, relevant call paths and test evidence, without the full coordination history. Return concise findings with location, trigger, impact, evidence and the affected requirement. Keep detailed investigation and repair verification in worker threads. The leader retains delivery scope, decisions, progress and risks; adjudicates from findings; and reads targeted source for disputed or insufficient evidence and the source checks required by section 5. Do not repeat the full review in the leader's context; retain conclusions, rationale and evidence links.

  • Design: SOLID, KISS, YAGNI; unnecessary abstractions, re-implementing an existing helper.
  • Efficiency: N+1, needless full scans, blocking sync calls, repeated computation.
  • Security: input validation, authorization boundaries, secret handling, injection, races.
  • Business logic: conflicting specs producing contradictory implementation; incomplete state machines.
  • Technology / package choices: suggestions are welcome (swap a package, change an approach); the leader decides whether to adopt.
  • Test quality: current scenario/Examples identities executed and outcomes asserted? deterministic integration connected? each test in its layer, with contract-type requirements backed by named lower-layer tests? edge cases covered? cross-test interference?
  • Comment policy: flag prohibited new comments, violations of already-adopted requirements, and gaps in authorized adoption; preserve and verify OpenAPI generator annotations under comments. Read-only review reports gaps without edits and does not initiate adoption or new lint gates.

Resource cleanup contract

Include the applicable resource responsibilities in the assignment, proportionate to what it starts or retains:

  • For servers, browsers, containers, background jobs, shared services and substantial disposable outputs, record an owned handle/identity, location and cleanup method. Reuse compatible task state with an explicitly accepted owner; close unused resources and dispose of temporary outputs when their work ends. Verify exit/removal, preserve unrelated resources, and keep cleanup failures assigned. Never signal a process based only on a possibly reused PID.
  • Ordinary foreground reads, Git, lint and pure commands need their exit/completion status, not a separate PID/cwd census or auditor per invocation. If they spawn resources that can outlive the command, time out, crash or cannot be reaped, inspect those resources and record the uncertainty. Do not recreate missing historical samples or recursively audit the audit process.
  • Retain only useful evidence or continued resources, with owner and expiry/event; record paths/sizes for substantial outputs. Handoffs transfer needed live resources explicitly or close them. Missing identity calls for bounded current-state inspection, not mining all prior logs. Until transfer is accepted, the current owner remains responsible.
  • Inspect disk/heavy-work contention when it is a real risk. Reuse bounded compatible builds and owned caches; do not globally purge caches, stop others' services or rebuild everything at a relay. Evidence can outlive the process that produced it.

5. Adjudication

Bar: the leader decides against the user's original instruction (the prompt), under two premises — the goal is met and the original requirements are not violated. For each reviewer finding ask: would leaving it unfixed keep the goal unmet or violate a requirement? Yes = dispatch a fix. No = log it, do not dispatch (this includes "it would be nicer to…" and "a cleaner approach would be…" suggestions; reject them or collect them for the user at the end). When the user has agreed a demo / prototype as requirements, it is the reference; an exploratory prototype remains provisional evidence, not agreed policy or acceptance. Before adjudicating what the demo means, read its source yourself; do not rely on the reviewer's paraphrase.

In the existing task record, distinguish required fix / optional deferred work / decision needed. Name an owner for fixes; hold only the unresolved dependency and continue independent work. Batch policy questions with evidence, recommendation and impact. A separate adjudication document is useful for substantial decisions, not mandatory for every finding. Do not send the user routine permissions already covered by the assignment.

6. Monitoring, context, and relay (the leader owns it)

  • Prefer completion notifications and bounded waits, preserving user responsiveness. Inspect recent output/session state for concrete problems; silence or age alone is not a stall. Steer first, replacing only when recovery requires it. Do not rapidly poll unchanged state or dump full logs.
  • Default to continuity. Keep one owner across diagnosis, repair and verification of a related causal chain. A fresh context loses tacit knowledge and has a reconstruction cost; do not rotate merely for a test failure, commit, wrapper error, elapsed time or percentage. A bounded read-only expert consultation can supply missing expertise while the owner retains context. Loop-guard intervention is not an automatic handoff.
  • Use bb thread context <id> --json at natural decisions. Around 50–60%, assess whether the next coherent work segment plus realistic cleanup/handoff reserve fits; near 80%, make that decision explicitly before starting more work. Do not invent percentages if usage is unavailable or demand a new measurement system. After compaction, check continuity rather than automatically replacing the worker.
Decision Required conditions and action
Continue The owner can explain the current constraints, causal chain and next action without unresolved drift, and can finish the next bounded segment while retaining cleanup/reporting capacity. Continue even past a planning cue when these conditions hold. A small closeout is different from starting another broad investigation.
Prepare a relay The remaining segment is unlikely to fit, or repeated forgotten decisions/contradictory source readings show degraded context. Stop adding scope; use the existing record to recover the critical facts and reach a safe resumable boundary. Preparation does not require green tests, a maturity pack or a new acceptance run.
Transfer Capacity cannot safely cover the next segment, targeted context recovery has not restored reliable reasoning, or the owner/provider cannot continue. Finish an active test/transaction safely or arrange a supported takeover; checkpoint work or assign dirty ownership. Before the successor writes, confirm prior writes have stopped and ownership is released or safely taken over by the leader. An unavailable worker's reply is not required; uncertain concurrent writes block only affected writing. Do not interrupt live work solely to meet a percentage.
  • Maintain one concise Current at meaningful changes, while context is healthy: original goal/acceptance and authorization; current result and blocker; consequential decisions/rejected hypotheses with source links; next action; valid/invalidated/unknown evidence; checkout/dirty and live-resource ownership. Do not first reconstruct it at exhaustion. Before relay, the leader checks critical decisions and next action against original authority and relevant evidence, correcting contradictions instead of forwarding an unchecked summary. The successor resumes from those links, not the full transcript. This is a continuity check, not another approval pack or test gate.
  • Drift is judged by the leader, not only self-reported. Compare the owner's ordinary result/next-step reports with Current and relevant source. When they conflict, request a targeted correction of the constraint, rejected hypothesis or next action. If that restores continuity, continue; if it does not, transfer at a safe boundary regardless of percentage. Do not add a repeated recitation or proof ritual when existing reports are consistent.
  • A relay continues the same business phase, authorization, failure history and budget, possibly as unverified WIP. The successor confirms current checkout/resource access and resumes under the ownership rule above. Do not reset counters, reconstruct historical SHA/PID proofs, requalify unchanged wrappers, rerun acceptance or rebuild environments solely because the owner changed. Check a dependency again only when evidence is missing, changed or inconsistent; preserve that precise uncertainty.
  • Resource handoff is separate from write ownership. Transfer only needed compatible resources with an accepted owner and minimal access/health check, not fresh acceptance. The leader may bridge ownership; close non-transferable handles and assign unresolved cleanup after crashes/stops under section 4.
  • Two relays without progress are a planning failure. If neither closes an acceptance gap nor resolves causal uncertainty, stop rotating owners and revisit the work split, harness and delivery path under the loop guard. A successor should resume substantive work, not spend its context preparing another handoff. Apply the same continuity rules to the leader; use existing records, not a relay metric collector.

7. Thread diagnostics

  • Inspect current CLI help and capabilities for parent links, environment selection, and recovery operations; diagnose the actual error rather than assuming a historical status code or workaround still applies.
  • After a provider failure, inspect current thread/process state, saved work and resource ownership. Use supported recovery when viable, otherwise section 6's safe takeover. Do not blindly replay an operation whose outcome is unknown.
  • For authenticated browser QA, use the tool's supported authentication mechanism and protect credentials. Diagnose authentication, navigation, and application failures separately rather than treating one past incident as a framework limitation.

8. Closeout

These steps close a delivered phase or task, not a worker relay. For relay or unavailable-owner takeover, use section 6 and preserve explicit resource ownership.

  1. At each delivery-phase end, satisfy that phase's agreed acceptance scope, reusing matching evidence and rerunning affected failures as needed. At closeout, resolve pending checks and cross-feature evidence gaps, including any required whole-application gate. Stop when the agreed bar is met; a handoff or closeout does not itself justify another run or review.
  2. Record agreed deviations from spec (and who decided), what was not verified, and pending adjudications in the existing task or adjudication record. Use an existing roadmap when appropriate; do not create a roadmap or footer schema solely for closeout.
  3. Before worker cleanup, have the tracking owner check whether linked issues still reflect the phase/task outcome and next action; the leader handles this check if the designated owner is unavailable. Update where warranted within existing authority, keep accurate states unchanged, and disclose any needed update that could not be made. Completion of a phase or worker assignment does not by itself complete the whole issue.
  4. Reconcile owned live resources and disposable outputs under section 4; retain useful evidence and explicitly transferred resources. Keep unresolved cleanup visible and assigned. An empty thread list alone is not proof of resource cleanup; no second historical census is needed when current cleanup evidence is sufficient. Preserve other owners' work and resources.
  5. List this task's worker threads and confirm none is running. Delete only workers whose resources are closed/removed or accepted as retained; leave any worker with unresolved cleanup in place as its owner. Run bb thread delete <id> --yes for eligible workers; do not archive unless the user requests it. Thread removal does not replace process or filesystem cleanup.
  6. Save coherent changes with a local commit when needed; report the branch for the user to push. Do not manufacture another commit when the work is already saved. Never push or work around that restriction.