opencode-swarm 7.181.3 → 7.181.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
  2. package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
  3. package/dist/cli/{coder-settlement-txte2m87.js → coder-settlement-vbs5rj3z.js} +3 -3
  4. package/dist/cli/{config-doctor-101n3c1r.js → config-doctor-3cb51z08.js} +2 -2
  5. package/dist/cli/{core-s0yzzpaj.js → core-0h7y8z0s.js} +1 -1
  6. package/dist/cli/{curator-dp49fr0p.js → curator-9sn55eyk.js} +22 -22
  7. package/dist/cli/{curator-drift-r7w3cg3m.js → curator-drift-d4jkgrba.js} +5 -5
  8. package/dist/cli/{curator-llm-factory-tycc9xkw.js → curator-llm-factory-zwc2gpe7.js} +22 -22
  9. package/dist/cli/{evidence-summary-service-r648x5f2.js → evidence-summary-service-sb5seqs3.js} +8 -8
  10. package/dist/cli/{gate-evidence-8rh69tsh.js → gate-evidence-emq2y7kz.js} +2 -2
  11. package/dist/cli/{guardrail-explain-dfyj1g1c.js → guardrail-explain-a3hcrpwv.js} +23 -23
  12. package/dist/cli/{guardrail-log-yr60w7h6.js → guardrail-log-ftv03v4x.js} +3 -3
  13. package/dist/cli/{guardrail-reset-eztc62va.js → guardrail-reset-d6qmnvff.js} +22 -22
  14. package/dist/cli/{hive-promoter-g56ba4a4.js → hive-promoter-pktjn46n.js} +22 -22
  15. package/dist/cli/{index-k5rqe97g.js → index-0ea0c676.js} +5 -5
  16. package/dist/cli/{index-dy9mxh0z.js → index-12fxtcce.js} +24 -24
  17. package/dist/cli/{index-m4e3p8na.js → index-1epynxc4.js} +1 -1
  18. package/dist/cli/{index-8c37kzh6.js → index-1msszzg2.js} +1 -1
  19. package/dist/cli/{index-rchygh27.js → index-3ga3ts3h.js} +1 -1
  20. package/dist/cli/{index-xqr076aq.js → index-4qpz7mpn.js} +1 -1
  21. package/dist/cli/{index-1ks0rnzn.js → index-54sd9bbn.js} +5 -5
  22. package/dist/cli/{index-kexzhwbq.js → index-68ben2q8.js} +2 -2
  23. package/dist/cli/{index-hcaspktr.js → index-6jrn46zy.js} +1 -1
  24. package/dist/cli/{index-h6gxh3an.js → index-9eg8f4zm.js} +117 -66
  25. package/dist/cli/{index-vgjmahnd.js → index-9s2rp2j5.js} +2 -2
  26. package/dist/cli/{index-ekwe81my.js → index-dkprb20b.js} +1 -1
  27. package/dist/cli/{index-7s6ct0t2.js → index-dwc1wztn.js} +4 -4
  28. package/dist/cli/{index-1w1xrk5k.js → index-enmvd9ap.js} +1 -1
  29. package/dist/cli/{index-6ep83w7x.js → index-epq8am78.js} +1 -1
  30. package/dist/cli/{index-ttgex8ky.js → index-fsye9ygy.js} +2 -2
  31. package/dist/cli/{index-mdqp0cq2.js → index-gtpq64q7.js} +1 -1
  32. package/dist/cli/{index-yv0q0hp9.js → index-hqa71xfm.js} +3 -3
  33. package/dist/cli/{index-789tdsfv.js → index-j97nc02q.js} +1 -1
  34. package/dist/cli/{index-qdz43cne.js → index-myacmqmf.js} +22 -22
  35. package/dist/cli/{index-ckrm4784.js → index-r4vve32m.js} +3 -3
  36. package/dist/cli/{index-4ffryqb1.js → index-rgfz80gt.js} +1 -1
  37. package/dist/cli/{index-2pt5g7zz.js → index-v4h99xhr.js} +1 -1
  38. package/dist/cli/{index-yzapt508.js → index-x4am0jxt.js} +3 -3
  39. package/dist/cli/{index-nw8pfcw1.js → index-y03jadcy.js} +1 -1
  40. package/dist/cli/{index-4jvt3r77.js → index-y28np6j9.js} +1 -1
  41. package/dist/cli/{index-sr9k8sh7.js → index-zp6fss8c.js} +3 -3
  42. package/dist/cli/index.js +23 -23
  43. package/dist/cli/{knowledge-escalator-0rcft6q4.js → knowledge-escalator-5q4y97e4.js} +6 -6
  44. package/dist/cli/{knowledge-events-7jyz3qxs.js → knowledge-events-x7q8yepd.js} +4 -4
  45. package/dist/cli/{knowledge-store-asa26g6p.js → knowledge-store-r7ng2nf8.js} +1 -1
  46. package/dist/cli/{knowledge-validator-j3x9ezej.js → knowledge-validator-e78m6cqe.js} +2 -2
  47. package/dist/cli/{mcp-70hefjk6.js → mcp-208jwxps.js} +1 -1
  48. package/dist/cli/{model-preflight-szekh1dc.js → model-preflight-xakn1356.js} +22 -22
  49. package/dist/cli/{pending-delegations-rb6bhv5x.js → pending-delegations-w4a5tg11.js} +2 -2
  50. package/dist/cli/{pr-subscriptions-v4ms5pfb.js → pr-subscriptions-8289esc9.js} +1 -1
  51. package/dist/cli/{pr-workflow-gate-qmfpz6wb.js → pr-workflow-gate-b7yx0x21.js} +22 -22
  52. package/dist/cli/{scan-cursor-7zn4t1hw.js → scan-cursor-edpbzp72.js} +2 -2
  53. package/dist/cli/{schema-tx62mfy8.js → schema-dnsxhyr3.js} +1 -1
  54. package/dist/cli/{scope-persistence-f8w12sns.js → scope-persistence-z1f7d4tw.js} +5 -5
  55. package/dist/cli/{server-f2vrp2wc.js → server-t2edntv4.js} +22 -22
  56. package/dist/cli/{skill-generator-jme09w7n.js → skill-generator-5n7vf0s3.js} +7 -7
  57. package/dist/cli/{snapshot-coordination-init-ad83sq6c.js → snapshot-coordination-init-t14dk9je.js} +22 -22
  58. package/dist/cli/{speckit-checkoff-98gfvn3r.js → speckit-checkoff-4ws84g13.js} +3 -3
  59. package/dist/cli/{worktree-collision-ownership-47kdjtqb.js → worktree-collision-ownership-wj6337ec.js} +2 -2
  60. package/dist/cli/{worktree-isolation-etaawcnt.js → worktree-isolation-9fyj85tc.js} +22 -22
  61. package/dist/hooks/delegation-gate.d.ts +10 -8
  62. package/dist/hooks/task-id-resolver.d.ts +7 -0
  63. package/dist/index.js +14 -5
  64. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.181.3",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; a presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error; cancel_pending cancels pending lanes; otherwise observe-only. Non-blocking poll (wait omitted or false) and blocking join (wait: true) supported. The wait budget bounds the observer call only — expiry never kills a lane nor proves it died; poll again or cancel explicitly, never abort. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending; busy/retry lanes never go stale for running long. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.181.4",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; a presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error; cancel_pending cancels pending lanes; otherwise observe-only. Non-blocking poll (wait omitted or false) and blocking join (wait: true) supported. The wait budget bounds the observer call only — expiry never kills a lane nor proves it died; poll again or cancel explicitly, never abort. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending; busy/retry lanes never go stale for running long. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -930,7 +930,8 @@ ACTION: ${correction.action}`}var GUIDANCE_TEMPLATES,ACTION_TEMPLATES;var init_c
930
930
  `}function parseTaskSplitRegistry(content){if(content===void 0)return{v:1,entries:[]};let value;try{value=JSON.parse(content)}catch(error49){throw new EvaluationConflictError(`task split registry is corrupt: ${String(error49)}`)}if(!value||typeof value!=="object"||Array.isArray(value))throw new EvaluationConflictError("task split registry is corrupt");let record2=value;if(record2.v!==1||!Array.isArray(record2.entries))throw new EvaluationConflictError("task split registry is corrupt");return{v:1,entries:record2.entries.map((candidate)=>{if(!candidate||typeof candidate!=="object"||Array.isArray(candidate))throw new EvaluationConflictError("task split registry is corrupt");let entry=candidate;if(typeof entry.lineageHash!=="string"||!["train","validation","test"].includes(String(entry.split))||!Array.isArray(entry.taskIds)||!entry.taskIds.every((id)=>typeof id==="string")||!Array.isArray(entry.inputHashes)||!entry.inputHashes.every((hash3)=>typeof hash3==="string"))throw new EvaluationConflictError("task split registry is corrupt");return{lineageHash:entry.lineageHash,split:entry.split,taskIds:[...new Set(entry.taskIds)].sort(),inputHashes:[...new Set(entry.inputHashes)].sort()}})}}function evaluationConflictError(conflict){return conflict.kind==="corrupt"?new EvaluationConflictError(`existing evaluation artifact is corrupt: ${conflict.filePath}: ${String(conflict.cause)}`):new EvaluationConflictError(`immutable evaluation artifact conflicts with existing content: ${conflict.filePath}`)}function writeImmutable(options){return writeImmutableArtifact({...options,agent:AGENT,serialize:serialized,conflictError:evaluationConflictError})}function validateTaskInputs(directory,task){resolveContainedExistingPath(directory,task.instructionPath);let environmentRoot=resolveContainedExistingPath(directory,task.environment.path);if(task.scorer.kind==="project"){let executable=task.scorer.argv[0];if(!executable)throw Error("project scorer requires an executable");let scorerPath=resolveContainedExistingPath(directory,executable),relative14=path61.relative(environmentRoot,scorerPath);if(!relative14||relative14===".."||relative14.startsWith(`..${path61.sep}`)||path61.isAbsolute(relative14))throw Error("project scorer executable must be inside the admitted task environment")}}async function admitEvaluationTask(directory,input,inputRoot=directory){let task=EvaluationTaskV1Schema.parse(input);if(await computeTaskInputContentHash(inputRoot,task)!==task.contentHash)throw Error(`task ${task.id} content hash does not match its canonical inputs`);validateTaskInputs(inputRoot,task);let lineageInputHash=await computeTaskLineageInputHash(inputRoot,task),relative14=path61.join("evolution","tasks",task.split,`${task.id}.json`),admissionLock=TASK_SPLIT_REGISTRY_RELATIVE,filePath=swarmPath(directory,relative14);return assertProjectRoot(directory),await mkdir10(path61.dirname(filePath),{recursive:!0}),withEvidenceLock(directory,admissionLock,AGENT,task.id,async()=>{let registryPath=swarmPath(directory,TASK_SPLIT_REGISTRY_RELATIVE),registry2=parseTaskSplitRegistry(await readOptionalFile(registryPath)),existingTaskEntry=registry2.entries.find((entry)=>entry.taskIds.includes(task.id));if(existingTaskEntry&&existingTaskEntry.split!==task.split)throw new EvaluationConflictError(`task ${task.id} is already admitted to a different split`);let parentEntry=task.derivedFromTaskId?registry2.entries.find((entry)=>entry.taskIds.includes(task.derivedFromTaskId)):void 0;if(task.derivedFromTaskId&&!parentEntry)throw new EvaluationConflictError(`derived task ${task.id} references an unadmitted parent ${task.derivedFromTaskId}`);let lineageEntry=parentEntry??registry2.entries.find((entry)=>entry.lineageHash===lineageInputHash||entry.inputHashes.includes(lineageInputHash));if(lineageEntry&&lineageEntry.split!==task.split)throw new EvaluationConflictError(`task ${task.id} lineage is already admitted to ${lineageEntry.split}; derived and aliased tasks must inherit that split`);for(let split of["train","validation","test"]){if(split===task.split)continue;if(await readOptionalFile(swarmPath(directory,"evolution","tasks",split,`${task.id}.json`)))throw new EvaluationConflictError(`task ${task.id} is already admitted to a different split`)}let desired=serialized(task),existing=await readOptionalFile(filePath);if(existing!==void 0){let parsed=EvaluationTaskV1Schema.parse(JSON.parse(existing));if(serialized(parsed)===desired){if(lineageEntry)lineageEntry.taskIds=[...new Set([...lineageEntry.taskIds,task.id])].sort(),lineageEntry.inputHashes=[...new Set([...lineageEntry.inputHashes,lineageInputHash])].sort();else registry2.entries.push({lineageHash:lineageInputHash,split:task.split,taskIds:[task.id],inputHashes:[lineageInputHash]});return registry2.entries.sort((left,right)=>left.lineageHash.localeCompare(right.lineageHash)),await atomicWriteFile(registryPath,serialized(registry2)),parsed}if(task.split!=="train")throw new EvaluationConflictError(`${task.split} task ${task.id} is immutable after admission`)}if(await atomicWriteFile(filePath,desired),lineageEntry)lineageEntry.taskIds=[...new Set([...lineageEntry.taskIds,task.id])].sort(),lineageEntry.inputHashes=[...new Set([...lineageEntry.inputHashes,lineageInputHash])].sort();else registry2.entries.push({lineageHash:lineageInputHash,split:task.split,taskIds:[task.id],inputHashes:[lineageInputHash]});return registry2.entries.sort((left,right)=>left.lineageHash.localeCompare(right.lineageHash)),await atomicWriteFile(registryPath,serialized(registry2)),task})}async function saveTaskSetSnapshot(directory,input,inputRoot=directory){let snapshot=TaskSetSnapshotV1Schema.parse(input),ids=snapshot.tasks.map((task)=>task.id);if(new Set(ids).size!==ids.length)throw Error("task-set contains duplicate task ids");if(snapshot.tasks.some((task)=>task.split!==snapshot.split))throw Error("task-set tasks must all belong to the declared split");for(let task of snapshot.tasks)if(await computeTaskInputContentHash(inputRoot,task)!==task.contentHash)throw Error(`task ${task.id} content hash is invalid`);if(computeTaskSetContentHash(snapshot)!==snapshot.contentHash)throw Error("task-set content hash does not match its canonical inputs");let relative14=path61.join("evolution","task-sets",`${snapshot.contentHash}.json`);return writeImmutable({directory,relativeLockPath:relative14,filePath:swarmPath(directory,relative14),taskId:snapshot.id,value:snapshot,parse:(value)=>TaskSetSnapshotV1Schema.parse(value),isEquivalent:(existing,desired)=>existing.contentHash===desired.contentHash})}async function saveEvaluationRun(directory,input){let run=EvaluationRunV1Schema.parse(input);if(computeRunIntegrityHash(run)!==run.integrityHash)throw Error(`run ${run.runId} integrity hash is invalid`);let relative14=path61.join("evolution","runs",`${run.runId}.json`);return writeImmutable({directory,relativeLockPath:relative14,filePath:swarmPath(directory,relative14),taskId:run.runId,value:run,parse:(value)=>EvaluationRunV1Schema.parse(value)})}async function readEvaluationRun(directory,runId){let content=await readOptionalFile(swarmPath(directory,"evolution","runs",`${runId}.json`));return content===void 0?void 0:EvaluationRunV1Schema.parse(JSON.parse(content))}async function savePromotionDecision(directory,input){let decision=PromotionDecisionV1Schema.parse(input),relative14=path61.join("evolution","decisions",`${decision.decisionId}.json`);return writeImmutable({directory,relativeLockPath:relative14,filePath:swarmPath(directory,relative14),taskId:decision.runId,value:decision,parse:(value)=>PromotionDecisionV1Schema.parse(value),isEquivalent:(existing,desired)=>{let{decidedAt:_existingTimestamp,...existingCore}=existing,{decidedAt:_desiredTimestamp,...desiredCore}=desired;return canonicalJson2(existingCore)===canonicalJson2(desiredCore)}})}async function saveGateAuditResult(directory,input){let result=GateAuditResultV1Schema.parse(input),relative14=path61.join("evidence","gate-audit",result.runId,"results.json");return writeImmutable({directory,relativeLockPath:relative14,filePath:swarmPath(directory,relative14),taskId:result.runId,value:result,parse:(value)=>GateAuditResultV1Schema.parse(value)})}async function saveGateAuditManifest(directory,input){let manifest=GateAuditManifestV1Schema.parse(input),relative14=path61.join("evolution","gate-audit-manifests",`${manifest.id}.json`);return writeImmutable({directory,relativeLockPath:relative14,filePath:swarmPath(directory,relative14),taskId:manifest.id,value:manifest,parse:(value)=>GateAuditManifestV1Schema.parse(value)})}async function readGateAuditManifest(directory,runId){let content=await readOptionalFile(swarmPath(directory,"evolution","gate-audit-manifests",`${runId}.json`));return content===void 0?void 0:GateAuditManifestV1Schema.parse(JSON.parse(content))}async function readGateAuditResult(directory,runId){let content=await readOptionalFile(swarmPath(directory,"evidence","gate-audit",runId,"results.json"));return content===void 0?void 0:GateAuditResultV1Schema.parse(JSON.parse(content))}async function listGateAuditResults(directory){let root=swarmPath(directory,"evidence","gate-audit"),entries=[];try{entries=await readdir2(root,{withFileTypes:!0})}catch(error49){if(error49.code==="ENOENT")return{results:[],corruptRunIds:[]};throw error49}let results=[],corruptRunIds=[];for(let entry of entries.sort((left,right)=>left.name.localeCompare(right.name))){if(!entry.isDirectory()||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/.test(entry.name))continue;try{let parsed=GateAuditResultV1Schema.parse(JSON.parse(await readFile12(path61.join(root,entry.name,"results.json"),"utf8")));if(parsed.runId!==entry.name)throw Error("run id/path mismatch");results.push(parsed)}catch{corruptRunIds.push(entry.name)}}return{results,corruptRunIds}}function parseTestLedger(content){return content.split(/\r?\n/).filter((line)=>line.trim().length>0).map((line,index)=>{try{return TestConsumptionClaimV1Schema.parse(JSON.parse(line))}catch(error49){throw new EvaluationConflictError(`test-consumption ledger is corrupt at line ${index+1}: ${String(error49)}`)}})}async function claimHeldOutTest(directory,input){let claim=TestConsumptionClaimV1Schema.parse(input),filePath=swarmPath(directory,TEST_LEDGER_RELATIVE);return assertProjectRoot(directory),await mkdir10(path61.dirname(filePath),{recursive:!0}),withEvidenceLock(directory,TEST_LEDGER_RELATIVE,AGENT,claim.runId,async()=>{let content=await readOptionalFile(filePath)??"",claims=parseTestLedger(content),identicalRun=claims.find((entry)=>entry.runId===claim.runId);if(identicalRun){if(identicalRun.taskSetHash===claim.taskSetHash&&identicalRun.baselineHash===claim.baselineHash&&identicalRun.candidateHash===claim.candidateHash)return identicalRun;throw new EvaluationConflictError(`run ${claim.runId} conflicts with its prior held-out test claim`)}let prior=claims.find((entry)=>entry.taskSetHash===claim.taskSetHash);if(prior)throw new TestAlreadyConsumedError(prior);return await atomicWriteFile(filePath,`${content.replace(/\s*$/,"")}${content.trim()?`
931
931
  `:""}${serialized(claim)}`),claim})}async function getProtectedEvaluationRunIds(directory){let protectedIds=new Set,ledger=await readOptionalFile(swarmPath(directory,TEST_LEDGER_RELATIVE));for(let claim of parseTestLedger(ledger??""))protectedIds.add(claim.runId);let decisionsDirectory=swarmPath(directory,"evolution","decisions"),files=[];try{files=await readdir2(decisionsDirectory)}catch(error49){if(error49.code!=="ENOENT")throw error49}for(let filename of files.filter((value)=>value.endsWith(".json")).sort()){let decision=PromotionDecisionV1Schema.parse(JSON.parse(await readFile12(path61.join(decisionsDirectory,filename),"utf8")));if(protectedIds.add(decision.runId),protectedIds.add(decision.lineage.baselineRunId),decision.lineage.historicalBestRunId!=="unavailable")protectedIds.add(decision.lineage.historicalBestRunId)}return protectedIds}var AGENT="evaluation-store",TEST_LEDGER_RELATIVE,TASK_SPLIT_REGISTRY_RELATIVE,EvaluationConflictError,TestAlreadyConsumedError;var init_store=__esm(()=>{init_immutable_store();init_lock();init_task_file();init_project_boundary();init_contracts();init_hashing();TEST_LEDGER_RELATIVE=path61.join("evolution","test-consumption.jsonl"),TASK_SPLIT_REGISTRY_RELATIVE=path61.join("evolution","tasks","split-registry.json");EvaluationConflictError=class EvaluationConflictError extends Error{constructor(message){super(message);this.name="EvaluationConflictError"}};TestAlreadyConsumedError=class TestAlreadyConsumedError extends Error{priorClaim;constructor(priorClaim){super(`held-out test task set ${priorClaim.taskSetHash} was already consumed by run ${priorClaim.runId}`);this.name="TestAlreadyConsumedError",this.priorClaim=priorClaim}}});import*as fs36 from"node:fs/promises";import*as path62 from"node:path";function artifactKey(artifact){return`${artifact.namespace}/${artifact.id}`}function validId(value){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/.test(value)}async function evaluationRunCandidates(directory){let root=path62.join(directory,".swarm","evolution","runs"),entries=[];try{entries=await fs36.readdir(root,{withFileTypes:!0})}catch(error49){if(error49.code==="ENOENT")return{candidates:[],corrupt:[]};throw error49}let candidates=[],corrupt=[];for(let entry of entries.sort((a,b)=>a.name.localeCompare(b.name))){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let id=entry.name.slice(0,-5);if(!validId(id))continue;let artifact={namespace:"evaluation-run",id},target=path62.join(root,entry.name);try{let run=EvaluationRunV1Schema.parse(JSON.parse(await fs36.readFile(target,"utf8")));if(run.runId!==id)throw Error("run id/path mismatch");candidates.push({artifact,createdAt:run.createdAt,target,kind:"file"})}catch{corrupt.push(artifact)}}return{candidates,corrupt}}async function gateAuditCandidates(directory){let root=path62.join(directory,".swarm","evidence","gate-audit"),entries=[];try{entries=await fs36.readdir(root,{withFileTypes:!0})}catch(error49){if(error49.code==="ENOENT")return{candidates:[],corrupt:[]};throw error49}let candidates=[],corrupt=[];for(let entry of entries.sort((a,b)=>a.name.localeCompare(b.name))){if(!entry.isDirectory()||!validId(entry.name))continue;let artifact={namespace:"gate-audit",id:entry.name},target=path62.join(root,entry.name);try{let result=GateAuditResultV1Schema.parse(JSON.parse(await fs36.readFile(path62.join(target,"results.json"),"utf8")));if(result.runId!==entry.name)throw Error("run id/path mismatch");candidates.push({artifact,createdAt:result.createdAt,target,kind:"directory"})}catch{corrupt.push(artifact)}}return{candidates,corrupt}}async function retentionCandidates(directory){let[runs,audits]=await Promise.all([evaluationRunCandidates(directory),gateAuditCandidates(directory)]);return{candidates:[...runs.candidates,...audits.candidates].sort((a,b)=>artifactKey(a.artifact).localeCompare(artifactKey(b.artifact))),corrupt:[...runs.corrupt,...audits.corrupt].sort((a,b)=>artifactKey(a).localeCompare(artifactKey(b)))}}async function protectedArtifacts(directory){let ids=await getProtectedEvaluationRunIds(directory);return new Set([...ids].map((id)=>`evaluation-run/${id}`))}async function removeCandidate(candidate){if(candidate.kind==="directory"){await fs36.rm(candidate.target,{recursive:!0,force:!0});return}await fs36.unlink(candidate.target)}async function archiveEvaluationArtifacts(args2){return assertProjectRoot(args2.directory),withEvidenceLock(args2.directory,path62.join("evolution","retention-index"),"evaluation-retention","archive",async()=>{let inventory=await retentionCandidates(args2.directory),protectedKeys=await _retentionInternals.protectedArtifacts(args2.directory),protectedRefs=inventory.candidates.filter((candidate)=>protectedKeys.has(artifactKey(candidate.artifact))).map((candidate)=>candidate.artifact),eligible=inventory.candidates.filter((candidate)=>!protectedKeys.has(artifactKey(candidate.artifact))),now=args2.now??new Date,cutoff=new Date(now.getTime()-args2.maxAgeDays*86400000).toISOString(),selectedKeys=new Set(eligible.filter((candidate)=>candidate.createdAt<cutoff).map((candidate)=>artifactKey(candidate.artifact))),remaining=eligible.filter((candidate)=>!selectedKeys.has(artifactKey(candidate.artifact))).sort((a,b)=>a.createdAt===b.createdAt?artifactKey(a.artifact).localeCompare(artifactKey(b.artifact)):a.createdAt.localeCompare(b.createdAt));if(args2.maxBundles!==void 0&&remaining.length>args2.maxBundles)for(let candidate of remaining.slice(0,remaining.length-args2.maxBundles))selectedKeys.add(artifactKey(candidate.artifact));let selectedCandidates=eligible.filter((candidate)=>selectedKeys.has(artifactKey(candidate.artifact))).sort((a,b)=>artifactKey(a.artifact).localeCompare(artifactKey(b.artifact))),archived=[],failed=[];if(!args2.dryRun)for(let candidate of selectedCandidates){if(protectedKeys=await _retentionInternals.protectedArtifacts(args2.directory),protectedKeys.has(artifactKey(candidate.artifact))){protectedRefs.push(candidate.artifact);continue}try{await _retentionInternals.removeCandidate(candidate),archived.push(candidate.artifact)}catch(error49){failed.push({artifact:candidate.artifact,error:error49 instanceof Error?error49.message:String(error49)})}}return{inventory:inventory.candidates.map((candidate)=>candidate.artifact),selected:selectedCandidates.map((candidate)=>candidate.artifact),archived,corrupt:inventory.corrupt,protected:[...new Map(protectedRefs.map((artifact)=>[artifactKey(artifact),artifact])).values()].sort((a,b)=>artifactKey(a).localeCompare(artifactKey(b))),failed}})}var _retentionInternals;var init_retention=__esm(()=>{init_lock();init_project_boundary();init_contracts();init_store();_retentionInternals={protectedArtifacts,removeCandidate}});import*as fs37 from"node:fs";import*as fsp2 from"node:fs/promises";import*as readline from"node:readline";async function atomicRenameWithRetry(src,dst,renameFn=fsp2.rename){let lastErr;for(let attempt=0;attempt<RENAME_MAX_ATTEMPTS2;attempt++)try{await renameFn(src,dst);return}catch(err){lastErr=err;let code=err?.code;if(!code||!RENAME_RETRY_CODES.has(code))throw err;if(attempt<RENAME_MAX_ATTEMPTS2-1)await new Promise((resolve31)=>setTimeout(resolve31,RENAME_BACKOFF_MS))}throw lastErr}function emptyResult(dryRun){return{inventory:0,selected:0,archived:0,corrupt:0,bytesBefore:0,bytesAfter:0,dryRun,aborted:!1}}async function readCacheRows(filePath){let bytesBefore=(await _internals56.stat(filePath)).size,stream=_internals56.createReadStream(filePath,{encoding:"utf8",highWaterMark:65536}),rl=readline.createInterface({input:stream,crlfDelay:1/0}),rows=[],corrupt=0,bytesRead=0,aborted2=!1;try{for await(let line of rl){let lineBytes=Buffer.byteLength(line,"utf8")+1;if(bytesRead+=lineBytes,bytesRead>MAX_READ_BYTES){aborted2=!0;break}if(line.length===0)continue;let record2=null;try{let parsed=JSON.parse(line);if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed))record2=parsed;else{corrupt++;continue}}catch{corrupt++;continue}rows.push({raw:line,bytes:lineBytes,record:record2})}}finally{rl.close(),stream.destroy()}return{rows,corrupt,aborted:aborted2,bytesBefore}}function oldestFirst(a,b){let at=typeof a.record?.capturedAt==="string"?a.record.capturedAt:"",bt=typeof b.record?.capturedAt==="string"?b.record.capturedAt:"";if(at===bt)return a.raw.localeCompare(b.raw);return at.localeCompare(bt)}function selectSurvivors(rows,maxRecords,maxBytes){let ordered=[...rows].sort(oldestFirst),keepFrom=0;if(typeof maxRecords==="number"&&ordered.length>maxRecords)keepFrom=ordered.length-maxRecords;if(typeof maxBytes==="number"&&maxBytes>0){let total=0;for(let i=keepFrom;i<ordered.length;i++)total+=ordered[i].bytes;while(keepFrom<ordered.length&&total>maxBytes)total-=ordered[keepFrom].bytes,keepFrom++}let survivors=ordered.slice(keepFrom),selected=rows.length-survivors.length;return{survivors,selected}}async function rewriteAtomic(filePath,survivors){let tmpPath=`${filePath}.tmp.${Date.now()}.${process.pid}`,payload=survivors.length>0?`${survivors.map((row)=>row.raw).join(`
932
932
  `)}
933
- `:"",succeeded=!1,fd=_internals56.openSync(tmpPath,"w");try{_internals56.writeSync(fd,payload,0),_internals56.fsyncSync(fd),_internals56.closeSync(fd),await _internals56.renameWithRetry(tmpPath,filePath),succeeded=!0}catch(err){try{_internals56.closeSync(fd)}catch{}let msg=err instanceof Error?err.message:String(err);throw Error(`documents-cache rewrite failed: ${msg}`)}finally{if(!succeeded)try{await _internals56.unlink(tmpPath)}catch{}}return Buffer.byteLength(payload,"utf8")}async function pruneEvidenceDocuments(args2){assertProjectRoot(args2.directory);let dryRun=args2.dryRun===!0,capsUnset=(typeof args2.maxBytes!=="number"||args2.maxBytes<=0)&&(typeof args2.maxRecords!=="number"||args2.maxRecords<=0),filePath=validateSwarmPath(args2.directory,EVIDENCE_CACHE_FILE),stat8;try{stat8=await _internals56.stat(filePath)}catch(err){if(err?.code==="ENOENT")return emptyResult(dryRun);throw err}if(capsUnset)return{inventory:0,selected:0,archived:0,corrupt:0,bytesBefore:stat8.size,bytesAfter:stat8.size,dryRun,aborted:!1};let readResult;try{readResult=await readCacheRows(filePath)}catch(err){let msg=err instanceof Error?err.message:String(err);throw warn(`documents-cache prune: read failed: ${msg}`),err}if(readResult.aborted)return warn(`documents-cache prune: aborted, file exceeds ${MAX_READ_BYTES} bytes; left untouched`),{inventory:readResult.rows.length,selected:0,archived:0,corrupt:readResult.corrupt,bytesBefore:readResult.bytesBefore,bytesAfter:readResult.bytesBefore,dryRun,aborted:!0};let{survivors,selected}=selectSurvivors(readResult.rows,args2.maxRecords,args2.maxBytes);if(dryRun){let bytesAfter2=survivors.reduce((sum,row)=>sum+row.bytes,0);return{inventory:readResult.rows.length,selected,archived:0,corrupt:readResult.corrupt,bytesBefore:readResult.bytesBefore,bytesAfter:bytesAfter2,dryRun:!0,aborted:!1}}if(selected===0&&readResult.corrupt===0)return{inventory:readResult.rows.length,selected:0,archived:0,corrupt:0,bytesBefore:readResult.bytesBefore,bytesAfter:readResult.bytesBefore,dryRun:!1,aborted:!1};let bytesAfter=await rewriteAtomic(filePath,survivors);return{inventory:readResult.rows.length,selected,archived:selected,corrupt:readResult.corrupt,bytesBefore:readResult.bytesBefore,bytesAfter,dryRun:!1,aborted:!1}}var EVIDENCE_CACHE_FILE="evidence-cache/documents.jsonl",MAX_READ_BYTES=104857600,RENAME_MAX_ATTEMPTS2=5,RENAME_BACKOFF_MS=10,RENAME_RETRY_CODES,_internals56;var init_documents_retention=__esm(()=>{init_utils2();init_utils();init_project_boundary();RENAME_RETRY_CODES=new Set(["EPERM","EBUSY","ENOTEMPTY","EACCES"]),_internals56={stat:(p)=>fsp2.stat(p),createReadStream:(p,options)=>fs37.createReadStream(p,options),openSync:(p,flags)=>fs37.openSync(p,flags),writeSync:(fd,data,position)=>fs37.writeSync(fd,data,position),fsyncSync:(fd)=>fs37.fsyncSync(fd),closeSync:(fd)=>fs37.closeSync(fd),renameWithRetry:atomicRenameWithRetry,unlink:(p)=>fsp2.unlink(p)}});import{mkdirSync as mkdirSync23,readdirSync as readdirSync8,realpathSync as realpathSync13,renameSync as renameSync15,rmSync as rmSync7,statSync as statSync20}from"node:fs";import*as fs38 from"node:fs/promises";import*as path63 from"node:path";function isValidEvidenceType(type){return VALID_EVIDENCE_TYPES.includes(type)}function isSecretscanEvidence(evidence){return evidence.type==="secretscan"}function validateProjectRoot(directory){assertProjectRoot(directory,{realpathSync:_internals57.realpathSync,statSync:_internals57.statSync},"evidence")}async function saveEvidence(directory,taskId,evidence,abortSignal){abortSignal?.throwIfAborted(),_internals57.validateProjectRoot(directory);let sanitizedTaskId=sanitizeTaskId2(taskId),relativePath=path63.join("evidence",sanitizedTaskId,"evidence.json");return validateSwarmPath(directory,relativePath),_internals57.validateEvidence(evidence),withEvidenceLock(directory,relativePath,"evidence-manager",sanitizedTaskId,async()=>{abortSignal?.throwIfAborted();let evidencePath=validateSwarmPath(directory,relativePath),evidenceDir=path63.dirname(evidencePath),bundle,existingContent=await readSwarmFileAsync(directory,relativePath);if(abortSignal?.throwIfAborted(),existingContent!==null)try{let parsed=JSON.parse(existingContent);bundle=EvidenceBundleSchema.parse(parsed)}catch(error49){warn(`Existing evidence bundle invalid for task ${sanitizedTaskId}, creating new: ${error49 instanceof Error?error49.message:String(error49)}`);let now=new Date().toISOString();bundle={schema_version:"1.0.0",task_id:sanitizedTaskId,entries:[],created_at:now,updated_at:now}}else{let now=new Date().toISOString();bundle={schema_version:"1.0.0",task_id:sanitizedTaskId,entries:[],created_at:now,updated_at:now}}let MAX_BUNDLE_ENTRIES=100,entries=[...bundle.entries,evidence];if(entries.length>MAX_BUNDLE_ENTRIES)entries=entries.slice(entries.length-MAX_BUNDLE_ENTRIES);let updatedBundle={...bundle,entries,updated_at:new Date().toISOString()},bundleJson=JSON.stringify(updatedBundle);if(bundleJson.length>EVIDENCE_MAX_JSON_BYTES)throw Error(`Evidence bundle size (${bundleJson.length} bytes) exceeds maximum (${EVIDENCE_MAX_JSON_BYTES} bytes)`);mkdirSync23(evidenceDir,{recursive:!0});let tempPath=path63.join(evidenceDir,`evidence.json.tmp.${Date.now()}.${process.pid}`);try{await bunWrite(tempPath,bundleJson),abortSignal?.throwIfAborted(),renameSync15(tempPath,evidencePath)}catch(error49){try{rmSync7(tempPath,{force:!0})}catch{}throw error49}return invalidateCachedArtifact(evidencePath),updatedBundle})}function isFlatRetrospective(parsed){return parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed)&&parsed.type==="retrospective"&&!parsed.schema_version}function remapLegacyTaskComplexity(entry){let taskComplexity=entry.task_complexity;if(typeof taskComplexity==="string"&&taskComplexity in LEGACY_TASK_COMPLEXITY_MAP)return{...entry,task_complexity:LEGACY_TASK_COMPLEXITY_MAP[taskComplexity]};return entry}function wrapFlatRetrospective(flatEntry,taskId){let now=new Date().toISOString(),remappedEntry=remapLegacyTaskComplexity(flatEntry);return{schema_version:"1.0.0",task_id:remappedEntry.task_id??taskId,created_at:remappedEntry.timestamp??now,updated_at:remappedEntry.timestamp??now,entries:[remappedEntry]}}async function loadEvidence(directory,taskId,options){let sanitizedTaskId=sanitizeTaskId2(taskId),relativePath=path63.join("evidence",sanitizedTaskId,"evidence.json");if(relativePath.length>4096)return{status:"not_found"};let evidencePath=validateSwarmPath(directory,relativePath),content=await readSwarmFileAsync(directory,relativePath);if(content===null)return{status:"not_found"};let parsed;try{parsed=JSON.parse(content)}catch{return{status:"invalid_schema",errors:["Invalid JSON"]}}if(isFlatRetrospective(parsed)){let wrappedBundle=_internals57.wrapFlatRetrospective(parsed,sanitizedTaskId);try{let validated=EvidenceBundleSchema.parse(wrappedBundle);if(options?.migrate===!1)return{status:"found",bundle:validated};try{validateProjectRoot(directory),await withEvidenceLock(directory,relativePath,"evidence-loader",sanitizedTaskId,async()=>{let evidenceDir=path63.dirname(evidencePath),bundleJson=JSON.stringify(validated),tempPath=path63.join(evidenceDir,`evidence.json.tmp.${Date.now()}.${process.pid}`);try{await bunWrite(tempPath,bundleJson),await fs38.rename(tempPath,evidencePath),invalidateCachedArtifact(evidencePath)}catch(writeError){try{rmSync7(tempPath,{force:!0})}catch{}warn(`Failed to persist repaired flat retrospective for task ${sanitizedTaskId}: ${writeError instanceof Error?writeError.message:String(writeError)}`)}})}catch(lockErr){warn(`Evidence lock failed during flat-retrospective write-back for task ${sanitizedTaskId}: ${lockErr instanceof Error?lockErr.message:String(lockErr)}`)}return{status:"found",bundle:validated}}catch(error49){return warn(`Wrapped flat retrospective failed validation for task ${sanitizedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`),{status:"invalid_schema",errors:error49 instanceof ZodError?error49.issues.map((e)=>`${e.path.join(".")}: ${e.message}`):[error49 instanceof Error?error49.message:String(error49)]}}}try{return{status:"found",bundle:EvidenceBundleSchema.parse(parsed)}}catch(error49){return warn(`Evidence bundle validation failed for task ${sanitizedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`),{status:"invalid_schema",errors:error49 instanceof ZodError?error49.issues.map((e)=>`${e.path.join(".")}: ${e.message}`):[error49 instanceof Error?error49.message:String(error49)]}}}async function listEvidenceTaskIds(directory){let evidenceBasePath=validateSwarmPath(directory,"evidence");try{statSync20(evidenceBasePath)}catch{return[]}let entries;try{entries=readdirSync8(evidenceBasePath)}catch{return[]}let taskIds=[];for(let entry of entries){let entryPath=path63.join(evidenceBasePath,entry);try{if(!statSync20(entryPath).isDirectory())continue;sanitizeTaskId2(entry),taskIds.push(entry)}catch(error49){if(error49 instanceof Error&&!error49.message.startsWith("Invalid task ID"))warn(`Error reading evidence entry '${entry}': ${error49.message}`)}}return taskIds.sort()}async function deleteEvidence(directory,taskId){let sanitizedTaskId=sanitizeTaskId2(taskId);try{validateProjectRoot(directory)}catch{return!1}let relativePath=path63.join("evidence",sanitizedTaskId),evidenceDir=validateSwarmPath(directory,relativePath);try{statSync20(evidenceDir)}catch{return!1}try{return rmSync7(evidenceDir,{recursive:!0,force:!0}),!0}catch(error49){return warn(`Failed to delete evidence for task ${sanitizedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`),!1}}async function checkRequirementCoverage(phase,directory){let relativePath=path63.join("evidence",`req-coverage-phase-${phase}.json`),absolutePath=path63.resolve(directory,".swarm",relativePath);try{return await fs38.access(absolutePath),{exists:!0,path:absolutePath}}catch{return{exists:!1,path:absolutePath}}}async function archiveEvidence(directory,maxAgeDays,maxBundles,options){let taskIds=await _internals57.listEvidenceTaskIds(directory),cutoffDate=options?.now?new Date(options.now):_internals57.now();cutoffDate.setDate(cutoffDate.getDate()-maxAgeDays);let cutoffIso=cutoffDate.toISOString(),selected=new Set,selectedByAge=new Set,selectedByCount=new Set,archived=[],failed=[],remainingBundles=[];for(let taskId of taskIds){let result;try{result=await _internals57.loadEvidence(directory,taskId)}catch{warn("archive: skipping corrupt or unreadable evidence for task",taskId);continue}if(result.status!=="found")continue;if(result.bundle.updated_at<cutoffIso)selected.add(taskId),selectedByAge.add(taskId);else remainingBundles.push({taskId,updatedAt:result.bundle.updated_at})}if(maxBundles!==void 0&&remainingBundles.length>maxBundles){remainingBundles.sort((a,b)=>a.updatedAt.localeCompare(b.updatedAt));let toDelete=remainingBundles.length-maxBundles;for(let i=0;i<toDelete;i++)selected.add(remainingBundles[i].taskId),selectedByCount.add(remainingBundles[i].taskId)}if(!options?.dryRun)for(let taskId of[...selected].sort())if(await _internals57.deleteEvidence(directory,taskId))archived.push(taskId);else failed.push(taskId);let evaluation=await archiveEvaluationArtifacts({directory,maxAgeDays,maxBundles,dryRun:options?.dryRun,now:options?.now}),documentsCache={inventory:0,selected:0,archived:0,corrupt:0,bytesBefore:0,bytesAfter:0,dryRun:options?.dryRun===!0,aborted:!1};if(typeof options?.cacheMaxBytes==="number"&&options.cacheMaxBytes>0||typeof options?.cacheMaxRecords==="number"&&options.cacheMaxRecords>0)try{documentsCache=await _internals57.pruneEvidenceDocuments({directory,maxBytes:options?.cacheMaxBytes,maxRecords:options?.cacheMaxRecords,dryRun:options?.dryRun})}catch(error49){let msg=error49 instanceof Error?error49.message:String(error49);warn(`archiveEvidence: documents-cache prune failed (fail-open): ${msg}`)}if(options?.report)return{inventoryEvidence:[...taskIds].sort(),selectedEvidence:[...selected].sort(),selectedEvidenceByAge:[...selectedByAge].sort(),selectedEvidenceByCount:[...selectedByCount].sort(),archivedEvidence:archived.sort(),failedEvidence:failed.sort(),evaluation,documentsCache};return archived.sort()}function validateEvidence(evidence){return EvidenceSchema.parse(evidence)}var VALID_EVIDENCE_TYPES,sanitizeTaskId2,LEGACY_TASK_COMPLEXITY_MAP,_internals57;var init_manager2=__esm(()=>{init_zod();init_evidence_schema();init_retention();init_utils2();init_utils();init_bun_compat();init_project_boundary();init_swarm_artifact_cache();init_documents_retention();init_lock();init_task_id();VALID_EVIDENCE_TYPES=["review","test","diff","approval","note","retrospective","syntax","placeholder","sast","sbom","build","quality_budget","secretscan"];sanitizeTaskId2=sanitizeTaskId;LEGACY_TASK_COMPLEXITY_MAP={low:"simple",medium:"moderate",high:"complex"};_internals57={wrapFlatRetrospective,loadEvidence,listEvidenceTaskIds,validateProjectRoot,validateEvidence,saveEvidence,deleteEvidence,pruneEvidenceDocuments,realpathSync:realpathSync13,statSync:statSync20,now:()=>new Date}});function createQueue(now){return{items:[],dropped:0,llmCallsUsed:0,tokensUsed:0,retriesUsed:0,lastDrainAt:now,enqueuedSinceLastDrain:0}}function getOrCreateQueue(sessionID){let queue=queuesBySession.get(sessionID);if(!queue){queue=createQueue(_internals58.now()),queuesBySession.set(sessionID,queue);while(queuesBySession.size>500){let oldest=queuesBySession.keys().next().value;if(oldest===void 0||oldest===sessionID)break;queuesBySession.delete(oldest)}}return queue}function positiveIntOr(value,fallback){return Number.isFinite(value)&&Number(value)>0?Math.floor(Number(value)):fallback}function enqueueCandidate(sessionID,candidate,limits){if(typeof sessionID!=="string"||sessionID.length===0)return{enqueued:!1,dropped:0,evictedOldest:!1};let queue=getOrCreateQueue(sessionID),maxQueueSize=positiveIntOr(limits.maxQueueSize,50);queue.items.push({candidate,enqueuedAt:_internals58.now(),attempts:0}),queue.enqueuedSinceLastDrain++;let evictedOldest=!1;while(queue.items.length>maxQueueSize)queue.items.shift(),queue.dropped++,evictedOldest=!0;return{enqueued:!0,dropped:queue.dropped,evictedOldest}}function computeDrainSize(depth,velocity,limits){if(!Number.isFinite(depth)||depth<=0)return 0;let minDrain=positiveIntOr(limits.minDrain,1),maxDrain=Math.max(minDrain,positiveIntOr(limits.maxDrain,minDrain)),depthFactor=clampUnit(limits.drainDepthFactor),velocityFactor=clampUnit(limits.drainVelocityFactor),safeVelocity=Number.isFinite(velocity)&&velocity>0?velocity:0,adaptive=minDrain+depthFactor*depth+velocityFactor*safeVelocity,bounded=Math.min(Math.max(Math.ceil(adaptive),minDrain),maxDrain);return Math.min(bounded,Math.floor(depth))}function clampUnit(value){let n=Number(value);if(!Number.isFinite(n)||n<=0)return 0;return n>1?1:n}function computeArrivalVelocity(stats2,now){let elapsedMs=now-stats2.lastDrainAt;if(!Number.isFinite(elapsedMs)||elapsedMs<=0)return 0;return stats2.enqueuedSinceLastDrain*1000/elapsedMs}function takeDrainBatch(sessionID,size){let queue=queuesBySession.get(sessionID);if(!queue||queue.items.length===0)return[];let count=Math.max(0,Math.min(Math.floor(size),queue.items.length)),batch=queue.items.splice(0,count);queue.lastDrainAt=_internals58.now(),queue.enqueuedSinceLastDrain=0;for(let item of batch)item.attempts++;return batch}function requeueCandidate(sessionID,item,limits){let queue=queuesBySession.get(sessionID);if(!queue)return;let maxQueueSize=positiveIntOr(limits.maxQueueSize,50);queue.items.unshift(item);while(queue.items.length>maxQueueSize)queue.items.pop(),queue.dropped++}function getQueueDepth(sessionID){if(!sessionID)return 0;return queuesBySession.get(sessionID)?.items.length??0}function reserveLlmBudget(sessionID,estimatedTokens,limits){let queue=queuesBySession.get(sessionID);if(!queue)return!1;let maxCalls=Math.max(0,Math.floor(Number(limits.maxLlmCallsPerSession)||0)),maxTokens=Math.max(0,Math.floor(Number(limits.maxTokensPerSession)||0));if(maxCalls===0||maxTokens===0)return!1;let tokens=Math.max(0,Math.floor(Number(estimatedTokens)||0));if(queue.llmCallsUsed+1>maxCalls)return!1;if(queue.tokensUsed+tokens>maxTokens)return!1;return queue.llmCallsUsed++,queue.tokensUsed+=tokens,!0}function recordRetry(sessionID){let queue=queuesBySession.get(sessionID);if(!queue)return 0;return queue.retriesUsed++,queue.retriesUsed}function getQueueStats(sessionID){let queue=sessionID?queuesBySession.get(sessionID):void 0;if(!queue)return{depth:0,dropped:0,llmCallsUsed:0,tokensUsed:0,retriesUsed:0,lastDrainAt:0,enqueuedSinceLastDrain:0};return{depth:queue.items.length,dropped:queue.dropped,llmCallsUsed:queue.llmCallsUsed,tokensUsed:queue.tokensUsed,retriesUsed:queue.retriesUsed,lastDrainAt:queue.lastDrainAt,enqueuedSinceLastDrain:queue.enqueuedSinceLastDrain}}function resetSessionQueue(sessionID){if(sessionID===void 0){queuesBySession.clear();return}queuesBySession.delete(sessionID)}var MAX_CANDIDATE_DRAIN_ATTEMPTS=5,queuesBySession,_internals58;var init_candidate_queue=__esm(()=>{queuesBySession=new Map,_internals58={now:()=>Date.now()}});import{existsSync as existsSync34}from"node:fs";import{mkdir as mkdir11,readFile as readFile14,rename as rename6,writeFile as writeFile5}from"node:fs/promises";import*as path64 from"node:path";async function acquireLock(dir){let acquire=import_proper_lockfile7.default.lock(dir,LOCK_RETRY_OPTS),timer,timeout=new Promise((_,reject)=>{timer=setTimeout(()=>{reject(Error(`SKILL_IMPROVER_QUOTA_LOCK_TIMEOUT: failed to acquire lock on ${dir} within ${LOCK_ACQUIRE_TIMEOUT_MS}ms`))},LOCK_ACQUIRE_TIMEOUT_MS)});try{return await Promise.race([acquire,timeout])}finally{if(timer)clearTimeout(timer)}}function resolveQuotaPath(directory,scope="skill-improver"){return path64.join(directory,".swarm",scope==="knowledge-enrichment"?"knowledge-enrichment-quota.json":"skill-improver-quota.json")}function todayKey(window2,now=new Date){if(window2==="utc")return now.toISOString().slice(0,10);let yr=now.getFullYear(),m=String(now.getMonth()+1).padStart(2,"0"),d=String(now.getDate()).padStart(2,"0");return`${yr}-${m}-${d}`}async function readState3(filePath){if(!existsSync34(filePath))return null;try{let raw=await readFile14(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed.date!=="string"||typeof parsed.calls_used!=="number"||typeof parsed.max_calls!=="number"||parsed.window!=="utc"&&parsed.window!=="local")return null;return parsed}catch{return null}}async function writeState(filePath,state2){await mkdir11(path64.dirname(filePath),{recursive:!0});let tmp=`${filePath}.tmp-${process.pid}`;await writeFile5(tmp,JSON.stringify(state2,null,2),"utf-8"),await rename6(tmp,filePath)}async function getQuotaState(directory,opts){let filePath=resolveQuotaPath(directory,opts.scope),today=todayKey(opts.window,opts.now),existing=await readState3(filePath);if(!existing||existing.date!==today||existing.window!==opts.window){let fresh={date:today,calls_used:0,max_calls:opts.maxCalls,window:opts.window};return await writeState(filePath,fresh),fresh}return{...existing,max_calls:opts.maxCalls}}async function reserveQuota(directory,opts){let filePath=resolveQuotaPath(directory,opts.scope);await mkdir11(path64.dirname(filePath),{recursive:!0});let release=null;try{release=await acquireLock(path64.dirname(filePath));let state2=await getQuotaState(directory,opts);if(state2.calls_used+opts.nCalls>opts.maxCalls)return{allowed:!1,state:state2,reason:`daily quota exhausted: used=${state2.calls_used} requested=${opts.nCalls} max=${opts.maxCalls}`};let next={...state2,calls_used:state2.calls_used+opts.nCalls,max_calls:opts.maxCalls,last_run_at:(opts.now??new Date).toISOString()};return await writeState(filePath,next),{allowed:!0,state:next}}finally{if(release)try{await release()}catch{}}}async function releaseQuota(directory,opts){let filePath=resolveQuotaPath(directory,opts.scope);await mkdir11(path64.dirname(filePath),{recursive:!0});let release=null;try{release=await acquireLock(path64.dirname(filePath));let state2=await getQuotaState(directory,opts),next={...state2,calls_used:Math.max(0,state2.calls_used-opts.nCalls),max_calls:opts.maxCalls};return await writeState(filePath,next),next}finally{if(release)try{await release()}catch{}}}var import_proper_lockfile7,LOCK_ACQUIRE_TIMEOUT_MS=1e4,LOCK_RETRY_OPTS;var init_skill_improver_quota=__esm(()=>{import_proper_lockfile7=__toESM(require_proper_lockfile(),1),LOCK_RETRY_OPTS={retries:{retries:30,minTimeout:50,maxTimeout:200,factor:1.5},stale:5000}});function getStoredInputArgs(callID){return storedInputArgs.get(callID)}function setStoredInputArgs(callID,args2){storedInputArgs.set(callID,args2);while(storedInputArgs.size>2000){let oldest=storedInputArgs.keys().next().value;if(oldest===void 0||oldest===callID)break;storedInputArgs.delete(oldest)}}function deleteStoredInputArgs(callID){storedInputArgs.delete(callID)}var storedInputArgs;var init_stored_input_args=__esm(()=>{storedInputArgs=new Map});function isSafeAttributionId(value){return value.length<=TASK_ID_RESOLUTION_LIMITS.maxTokenChars&&SAFE_ATTRIBUTION_ID.test(value)&&!/^ses_/i.test(value)&&!value.includes("..")}function isAllowedAttributionId(value,knownPlanTaskIds,planContextOverLimit=!1){if(!isSafeAttributionId(value))return!1;return!STRICT_PLAN_ID.test(value)||!planContextOverLimit&&!knownPlanTaskIds||knownPlanTaskIds?.has(value)===!0}function sorted(values){return[...values].sort()}function addCandidate(candidates,value){if(candidates.add(value),candidates.size>TASK_ID_RESOLUTION_LIMITS.maxCandidates)return{status:"over_limit",input:"candidates"};return null}function select(candidates,source){if(candidates.size===1)return{status:"resolved",taskId:[...candidates][0],source};if(candidates.size>1)return{status:"ambiguous",candidates:sorted(candidates)};return null}function validateKnownIds(knownPlanTaskIds){if(!knownPlanTaskIds)return null;if(knownPlanTaskIds.size>TASK_ID_RESOLUTION_LIMITS.maxKnownIds)return{status:"over_limit",input:"knownPlanTaskIds"};for(let value of knownPlanTaskIds)if(typeof value!=="string"||value.length>TASK_ID_RESOLUTION_LIMITS.maxTokenChars||!STRICT_PLAN_ID.test(value))return{status:"invalid",input:"knownPlanTaskIds"};return null}function isStrictExplicitPlanField(value,knownPlanTaskIds,planContextOverLimit=!1){return STRICT_PLAN_ID.test(value)&&(planContextOverLimit||knownPlanTaskIds!==void 0)}function resolveTaskId(input,options){try{if(options.planContextOverLimit&&options.knownPlanTaskIds)return{status:"invalid",input:"planContext"};let knownValidation=validateKnownIds(options.knownPlanTaskIds);if(knownValidation)return knownValidation;let totalChars=0,textFields=[];for(let field of TEXT_FIELDS){let raw=input[field];if(raw===void 0||raw===null)continue;if(typeof raw!=="string")return{status:"invalid",input:field};if(raw.length>TASK_ID_RESOLUTION_LIMITS.maxFieldChars)return{status:"over_limit",input:field};if(totalChars+=raw.length,totalChars>TASK_ID_RESOLUTION_LIMITS.maxTotalChars)return{status:"over_limit",input:"totalText"};textFields.push(raw)}let explicit=new Set;for(let field of EXPLICIT_FIELDS){let raw=input[field];if(raw===void 0||raw===null)continue;if(typeof raw!=="string")return{status:"invalid",input:field};let value=raw.trim();if(value.length>TASK_ID_RESOLUTION_LIMITS.maxTokenChars)return{status:"over_limit",input:field};if(!(options.policy==="plan"?value.length<=20&&STRICT_PLAN_ID.test(value)&&(!options.knownPlanTaskIds||options.knownPlanTaskIds.has(value)||options.planContextOverLimit):isAllowedAttributionId(value,options.knownPlanTaskIds,options.planContextOverLimit))){if(options.policy==="plan"&&value.length<=20&&STRICT_PLAN_ID.test(value)&&options.knownPlanTaskIds)return{status:"invalid",input:field};if(options.policy==="attribution"&&isStrictExplicitPlanField(value,options.knownPlanTaskIds,options.planContextOverLimit))return{status:"invalid",input:field};continue}let overflow=addCandidate(explicit,value);if(overflow)return overflow}if(options.policy==="plan"){let explicitSelection=select(explicit,"explicit");if(explicitSelection)return explicitSelection;if(options.planContextOverLimit)return{status:"over_limit",input:"knownPlanTaskIds"};let taskLineCandidates=new Set;for(let text of textFields){TASK_LINE.lastIndex=0;for(let lineMatch of text.matchAll(TASK_LINE)){PLAN_CANDIDATE.lastIndex=0;for(let match of lineMatch[1].matchAll(PLAN_CANDIDATE)){let value=match[1];if(options.knownPlanTaskIds&&!options.knownPlanTaskIds.has(value))continue;let overflow=addCandidate(taskLineCandidates,value);if(overflow)return overflow}}}let taskLineSelection=select(taskLineCandidates,"task_line");if(taskLineSelection)return taskLineSelection;let textCandidates=new Set;for(let text of textFields){PLAN_CANDIDATE.lastIndex=0;for(let match of text.matchAll(PLAN_CANDIDATE)){let value=match[1];if(options.knownPlanTaskIds&&!options.knownPlanTaskIds.has(value))continue;let overflow=addCandidate(textCandidates,value);if(overflow)return overflow}}let textSelection=select(textCandidates,"text");if(textSelection)return textSelection}else{let hasInvalidRawMarker=!1;for(let rawMarker of[ATTRIBUTION_ID_MARKER_RAW,ATTRIBUTION_TASK_MARKER_RAW])for(let text of textFields){rawMarker.lastIndex=0;for(let match of text.matchAll(rawMarker)){let value=match[1];if(value.length>TASK_ID_RESOLUTION_LIMITS.maxTokenChars)return{status:"over_limit",input:"markerToken"};if(!isAllowedAttributionId(value,options.knownPlanTaskIds,options.planContextOverLimit))hasInvalidRawMarker=!0}}if(hasInvalidRawMarker)return{status:"invalid",input:"marker"};let marked=new Set;for(let marker of[ATTRIBUTION_ID_MARKER,ATTRIBUTION_TASK_MARKER])for(let text of textFields){marker.lastIndex=0;for(let match of text.matchAll(marker)){let value=match[1];if(value.length>TASK_ID_RESOLUTION_LIMITS.maxTokenChars)return{status:"over_limit",input:"markerToken"};if(!isAllowedAttributionId(value,options.knownPlanTaskIds,options.planContextOverLimit))continue;let overflow=addCandidate(marked,value);if(overflow)return overflow}}let explicitSelection=select(explicit,"explicit");if(explicitSelection)return explicitSelection;let markerSelection=select(marked,"marker");if(markerSelection)return markerSelection}if(options.fallback!==void 0){if(!options.fallbackProvenUnique)return{status:"invalid",input:"fallback"};let fallback=options.fallback.trim(),validFallback=options.policy==="plan"?STRICT_PLAN_ID.test(fallback)&&options.knownPlanTaskIds?.has(fallback)===!0:isAllowedAttributionId(fallback,options.knownPlanTaskIds,options.planContextOverLimit);if(fallback.length>TASK_ID_RESOLUTION_LIMITS.maxTokenChars||!validFallback)return{status:"invalid",input:"fallback"};return{status:"resolved",taskId:fallback,source:"fallback"}}return{status:"missing"}}catch{return{status:"invalid",input:"resolver"}}}function resolveDelegatedPlanTaskId(args2,planContext){let options=planContext instanceof Set?{knownPlanTaskIds:planContext}:planContext,result=resolveTaskId(args2,{policy:"plan",...options});return result.status==="resolved"?result.taskId:null}var TASK_ID_RESOLUTION_LIMITS,TEXT_FIELDS,EXPLICIT_FIELDS,STRICT_PLAN_ID,SAFE_ATTRIBUTION_ID,PLAN_CANDIDATE,TASK_LINE,ATTRIBUTION_ID_MARKER,ATTRIBUTION_TASK_MARKER,ATTRIBUTION_ID_MARKER_RAW,ATTRIBUTION_TASK_MARKER_RAW;var init_task_id_resolver=__esm(()=>{TASK_ID_RESOLUTION_LIMITS={maxFields:4,maxFieldChars:32768,maxTotalChars:131072,maxKnownIds:1024,maxCandidates:32,maxTokenChars:80},TEXT_FIELDS=["prompt","description","task","input"],EXPLICIT_FIELDS=["plan_task_id","planTaskId","task_id","taskId"],STRICT_PLAN_ID=/^\d+\.\d+(?:\.\d+)*$/,SAFE_ATTRIBUTION_ID=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,PLAN_CANDIDATE=/\b(\d+\.\d+(?:\.\d+)*)\b/g,TASK_LINE=/^\s*TASK\s*[:=]\s*(.*)$/gim,ATTRIBUTION_ID_MARKER=/\b(?:task_id|task-id|taskId)\s*[:=]\s*([A-Za-z0-9][A-Za-z0-9._-]*)/gi,ATTRIBUTION_TASK_MARKER=/\bTASK\s*[:=]\s*([A-Za-z0-9][A-Za-z0-9._-]*)[ \t]*(?=\r?$)/gim,ATTRIBUTION_ID_MARKER_RAW=/\b(?:task_id|task-id|taskId)\s*[:=][ \t]*([^\s]*)/gi,ATTRIBUTION_TASK_MARKER_RAW=/\bTASK\s*[:=][ \t]*([^\s]+)[ \t]*(?=\r?$)/gim});function collectPlanTaskIdContextFromPhases(phases){let collected=new Set;for(let phase of phases)for(let task of phase?.tasks??[]){if(!task||typeof task.id!=="string")continue;if(collected.add(task.id),collected.size>TASK_ID_RESOLUTION_LIMITS.maxKnownIds)return{status:"over_limit"}}return{status:"available",taskIds:collected}}async function loadPlanTaskIdContext(directory){try{let plan=await loadPlanJsonOnly(directory);if(!plan)return{status:"unavailable"};return collectPlanTaskIdContextFromPhases(plan.phases)}catch{return{status:"unavailable"}}}function toTaskIdPlanContextOptions(context){if(context.status==="available")return{knownPlanTaskIds:context.taskIds};if(context.status==="over_limit")return{planContextOverLimit:!0};return{}}var init_plan_task_id_context=__esm(()=>{init_manager();init_task_id_resolver()});import*as fs39 from"node:fs";import*as path65 from"node:path";function cacheGet(cache2,key){let hit=cache2.get(key);if(hit===void 0)return;return cache2.delete(key),cache2.set(key,hit),hit}function cacheSet(cache2,key,value){cache2.delete(key),cache2.set(key,value);while(cache2.size>MAX_CACHED_PROJECTS){let oldest=cache2.keys().next();if(oldest.done)break;cache2.delete(oldest.value)}}function statFingerprint(resolved){let stat8=_internals59.statSync(resolved,{bigint:!0}),size=Number(stat8.size);return{size,fingerprint:typeof stat8.mtimeNs==="bigint"?`${stat8.mtimeNs}:${size}`:null}}function resolvePendingPath(directory){return validateSwarmPath(directory,"skill-usage-pending.json")}function resolveSkillUsageLockPath(directory){return validateSwarmPath(directory,SKILL_USAGE_LOCK_BASENAME)}function siblingSwarmPath(resolved,basename11){return path65.join(path65.dirname(resolved),basename11)}function ensureSwarmDir2(resolved){let dir=path65.dirname(resolved);if(!_internals59.existsSync(dir))_internals59.mkdirSync(dir,{recursive:!0})}function sleepSyncMs(ms){try{let view=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(view,0,0,ms);return}catch{let until=Date.now()+ms,spins=0;while(Date.now()<until)spins+=1}}function tryCreateLock(lockPath){try{let fd=_internals59.openSync(lockPath,"wx");return _internals59.closeSync(fd),!0}catch{return!1}}function breakStaleLock(lockPath){try{let age=_internals59.now()-_internals59.statSync(lockPath).mtimeMs;if(Math.abs(age)<=SKILL_USAGE_LOCK_STALE_MS)return!1}catch{return!1}try{_internals59.unlinkSync(lockPath)}catch{return!1}return tryCreateLock(lockPath)}function acquireSkillUsageLock(directory){let lockPath;try{lockPath=resolveSkillUsageLockPath(directory)}catch{return null}return acquireSkillUsageLockAt(lockPath)}function acquireSkillUsageLockAt(lockPath){try{ensureSwarmDir2(lockPath)}catch{return null}if(tryCreateLock(lockPath))return{lockPath};if(breakStaleLock(lockPath))return{lockPath};return null}function acquireSkillUsageLockOrThrowAt(lockPath){for(let attempt=0;attempt<ENQUEUE_LOCK_ATTEMPTS;attempt++){let handle=acquireSkillUsageLockAt(lockPath);if(handle)return handle;if(attempt<ENQUEUE_LOCK_ATTEMPTS-1)sleepSyncMs(ENQUEUE_LOCK_RETRY_MS)}throw Error(SKILL_USAGE_LOCK_UNAVAILABLE)}function releaseSkillUsageLock(handle){try{_internals59.unlinkSync(handle.lockPath)}catch{}}function emptyCounters(){let counters={};for(let key of SKILL_USAGE_COUNTER_KEYS)counters[key]=0;return counters}function emptyCoverage(){return{complete:!0,oldestRetained:null,newestRetained:null,entriesDropped:0,skillsDropped:0,floorPerSkill:SKILL_USAGE_LIMITS.floorPerSkill}}function createPendingDocument(){return{version:SKILL_USAGE_LIMITS.version,migrated:!1,records:[],counters:emptyCounters(),coverage:emptyCoverage()}}function parseRecord(raw){if(typeof raw!=="object"||raw===null)return null;let r=raw;if(typeof r.id!=="string"||r.id.length===0)return null;if(typeof r.skillPath!=="string"||r.skillPath.length===0)return null;if(r.verdict!=="compliant"&&r.verdict!=="violated")return null;if(typeof r.timestamp!=="string")return null;let state2=r.state==="in_flight"||r.state==="uncertain"?r.state:"pending";return{id:r.id,skillPath:r.skillPath,verdict:r.verdict,timestamp:r.timestamp,enqueuedAt:typeof r.enqueuedAt==="string"?r.enqueuedAt:r.timestamp,state:state2,attempts:typeof r.attempts==="number"&&r.attempts>=0?r.attempts:0,...typeof r.inFlightAt==="string"&&{inFlightAt:r.inFlightAt}}}function parsePendingDocument(raw){let parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)throw Error("sidecar root is not an object");if(!Array.isArray(parsed.records))throw Error("sidecar `records` is not an array");let doc2=createPendingDocument();doc2.version=typeof parsed.version==="number"?parsed.version:SKILL_USAGE_LIMITS.version,doc2.migrated=parsed.migrated===!0;let seen=new Set;for(let rawRecord of parsed.records){let record2=parseRecord(rawRecord);if(!record2)continue;if(seen.has(record2.id))continue;seen.add(record2.id),doc2.records.push(record2)}let counters=parsed.counters;if(counters&&typeof counters==="object")for(let key of SKILL_USAGE_COUNTER_KEYS){let value=counters[key];if(typeof value==="number"&&Number.isFinite(value)&&value>=0)doc2.counters[key]=value}let coverage=parsed.coverage;if(coverage&&typeof coverage==="object")doc2.coverage={complete:coverage.complete!==!1,oldestRetained:typeof coverage.oldestRetained==="string"?coverage.oldestRetained:null,newestRetained:typeof coverage.newestRetained==="string"?coverage.newestRetained:null,entriesDropped:typeof coverage.entriesDropped==="number"?coverage.entriesDropped:0,skillsDropped:typeof coverage.skillsDropped==="number"?coverage.skillsDropped:0,floorPerSkill:SKILL_USAGE_LIMITS.floorPerSkill};return doc2}function quarantinePendingDocument(directory,resolved){let stamp=new Date(_internals59.now()).toISOString().replace(/[:.]/g,"-");try{let target=validateSwarmPath(directory,`skill-usage-pending.corrupt-${stamp}.json`);return _internals59.renameSync(resolved,target),target}catch(err){log("[skill-usage-pending] quarantine failed (continuing with a fresh queue):",err instanceof Error?err.message:String(err));return}}function loadPendingDocument(directory){return loadPendingDocumentAt(directory,resolvePendingPath(directory))}function loadPendingDocumentAt(directory,resolved){let size,fingerprint;try{({size,fingerprint}=statFingerprint(resolved))}catch{return{doc:createPendingDocument(),quarantined:!1}}if(size<=SKILL_USAGE_LIMITS.readMaxBytes)try{let cached2=fingerprint===null?void 0:cacheGet(_documentCache,resolved),raw=cached2!==void 0&&cached2.fingerprint===fingerprint?cached2.text:_internals59.readFileSync(resolved,"utf-8"),doc3=parsePendingDocument(raw);if(fingerprint!==null&&raw.length<=MAX_CACHED_DOCUMENT_BYTES)cacheSet(_documentCache,resolved,{fingerprint,text:raw});return{doc:doc3,quarantined:!1}}catch(err){log("[skill-usage-pending] corrupt sidecar — quarantining:",err instanceof Error?err.message:String(err))}_documentCache.delete(resolved);let quarantinePath=quarantinePendingDocument(directory,resolved),doc2=createPendingDocument();return doc2.counters.corrupt+=1,{doc:doc2,quarantined:!0,...quarantinePath!==void 0&&{quarantinePath}}}function savePendingDocument(directory,doc2){savePendingDocumentAt(directory,resolvePendingPath(directory),doc2)}function savePendingDocumentAt(directory,resolved,doc2){ensureSwarmDir2(resolved),doc2.version=SKILL_USAGE_LIMITS.version,doc2.coverage.floorPerSkill=SKILL_USAGE_LIMITS.floorPerSkill;let tmpPath=siblingSwarmPath(resolved,`skill-usage-pending-${process.pid}-${_internals59.now()}.tmp`),serialized2=JSON.stringify(doc2);try{_internals59.writeFileSync(tmpPath,serialized2,"utf-8"),_internals59.renameSync(tmpPath,resolved)}catch(err){try{if(_internals59.existsSync(tmpPath))_internals59.unlinkSync(tmpPath)}catch{}throw _documentCache.delete(resolved),err instanceof Error?err:Error(String(err))}_coverageCache.delete(resolved);try{let{fingerprint}=statFingerprint(resolved);if(fingerprint!==null&&serialized2.length<=MAX_CACHED_DOCUMENT_BYTES)cacheSet(_documentCache,resolved,{fingerprint,text:serialized2});else _documentCache.delete(resolved)}catch{_documentCache.delete(resolved)}_pressureDirectory=directory,refreshPressureFromCounts(doc2.records.length,serialized2.length)}function readPendingManifest(directory){let resolved;try{resolved=resolvePendingPath(directory)}catch{return{coverage:emptyCoverage(),migrated:!1}}let fingerprint;try{if(!_internals59.existsSync(resolved))return{coverage:emptyCoverage(),migrated:!1};({fingerprint}=statFingerprint(resolved))}catch{return{coverage:emptyCoverage(),migrated:!1}}if(fingerprint!==null){let cached2=cacheGet(_coverageCache,resolved);if(cached2&&cached2.fingerprint===fingerprint)return{coverage:cached2.coverage,migrated:cached2.migrated}}try{let cachedText=fingerprint===null?void 0:cacheGet(_documentCache,resolved),raw=cachedText!==void 0&&cachedText.fingerprint===fingerprint?cachedText.text:_internals59.readFileSync(resolved,"utf-8"),doc2=parsePendingDocument(raw);if(fingerprint!==null)cacheSet(_coverageCache,resolved,{fingerprint,coverage:doc2.coverage,migrated:doc2.migrated});return{coverage:doc2.coverage,migrated:doc2.migrated}}catch{return{coverage:emptyCoverage(),migrated:!1}}}function isSkillWindowTrustworthy(coverage,retainedCount){if(coverage.complete)return!0;if(retainedCount<SKILL_USAGE_LIMITS.curatorMinSample)return!1;let floor=coverage.floorPerSkill>0?coverage.floorPerSkill:SKILL_USAGE_LIMITS.floorPerSkill;return retainedCount>=floor}function recordBytes(record2){return JSON.stringify(record2).length+1}function queueByteSize(doc2){let total=0;for(let record2 of doc2.records)total+=recordBytes(record2);return total}function ageMsOf(record2,nowMs){let parsed=Date.parse(record2.enqueuedAt);if(Number.isNaN(parsed))return 0;return nowMs-parsed}function evictionRank(record2){if(record2.state==="uncertain")return 0;if(record2.state==="pending")return 1;return 2}function enforceQueueBounds(doc2,nowMs=_internals59.now()){let survivors=[];for(let record2 of doc2.records){if(ageMsOf(record2,nowMs)>SKILL_USAGE_LIMITS.maxAgeMs){if(record2.state==="uncertain")doc2.counters.uncertain_expired+=1;else doc2.counters.dropped+=1;continue}survivors.push(record2)}doc2.records=survivors;let bytes=queueByteSize(doc2),count=doc2.records.length,overBudget=()=>count>SKILL_USAGE_LIMITS.queueMaxRecords||bytes>SKILL_USAGE_LIMITS.queueMaxBytes;if(overBudget()){let order=doc2.records.map((record2,index)=>({record:record2,index})).sort((a,b)=>{let rank=evictionRank(a.record)-evictionRank(b.record);if(rank!==0)return rank;if(a.record.enqueuedAt!==b.record.enqueuedAt)return a.record.enqueuedAt<b.record.enqueuedAt?-1:1;return a.index-b.index}),evicted=new Set;for(let{record:record2}of order){if(!overBudget())break;if(evicted.add(record2),count-=1,bytes-=recordBytes(record2),record2.state==="uncertain")doc2.counters.uncertain_expired+=1;else doc2.counters.pending_evicted+=1,doc2.counters.pressure+=1}if(evicted.size>0)doc2.records=doc2.records.filter((record2)=>!evicted.has(record2))}refreshPressureFromCounts(doc2.records.length,bytes)}function refreshPressureFromCounts(records,bytes){_pressure=records>=SKILL_USAGE_LIMITS.queueMaxRecords||bytes>=SKILL_USAGE_LIMITS.queueMaxBytes,_pressureCheckedAt=_internals59.now()}function isSkillUsageQueueUnderPressure(directory){let now=_internals59.now();if(_pressureDirectory===directory&&now-_pressureCheckedAt<PRESSURE_CACHE_MS)return _pressure;_pressureDirectory=directory,_pressureCheckedAt=now;try{let resolved=resolvePendingPath(directory);if(!_internals59.existsSync(resolved))return _pressure=!1,!1;_pressure=_internals59.statSync(resolved).size>=SKILL_USAGE_LIMITS.queueMaxBytes}catch{_pressure=!1}return _pressure}function mergePendingRecords(doc2,incoming,nowIso2){let known=new Set(doc2.records.map((r)=>r.id)),added=0;for(let input of incoming){if(known.has(input.id))continue;known.add(input.id),doc2.records.push({id:input.id,skillPath:input.skillPath,verdict:input.verdict,timestamp:input.timestamp,enqueuedAt:nowIso2,state:"pending",attempts:0}),added+=1}return doc2.counters.accepted+=added,added}function enqueueSkillUsageFeedback(directory,input){let resolved;try{resolved=resolvePendingPath(directory)}catch{throw Error(SKILL_USAGE_LOCK_UNAVAILABLE)}let handle=acquireSkillUsageLockOrThrowAt(siblingSwarmPath(resolved,SKILL_USAGE_LOCK_BASENAME));try{let{doc:doc2}=loadPendingDocumentAt(directory,resolved);mergePendingRecords(doc2,[input],new Date(_internals59.now()).toISOString()),enforceQueueBounds(doc2),savePendingDocumentAt(directory,resolved,doc2)}finally{releaseSkillUsageLock(handle)}}function resolveStaleInFlight(doc2,nowMs=_internals59.now()){let resolved=0;for(let record2 of doc2.records){if(record2.state!=="in_flight")continue;let claimedAt=record2.inFlightAt?Date.parse(record2.inFlightAt):NaN,age=Number.isNaN(claimedAt)?Number.POSITIVE_INFINITY:nowMs-claimedAt;if(Math.abs(age)<=SKILL_USAGE_LOCK_STALE_MS)continue;record2.state="uncertain",record2.inFlightAt=void 0,resolved+=1}return resolved}function selectConsumableRecords(doc2,sinceTimestamp){return doc2.records.filter((record2)=>{if(record2.state!=="pending")return!1;if(sinceTimestamp!==void 0&&record2.timestamp<=sinceTimestamp)return!1;return!0})}function markRecordsInFlight(doc2,ids,nowIso2=new Date(_internals59.now()).toISOString()){let wanted=new Set(ids);for(let record2 of doc2.records){if(!wanted.has(record2.id))continue;record2.state="in_flight",record2.inFlightAt=nowIso2}}function dequeueRecords(doc2,ids){let wanted=new Set(ids),before=doc2.records.length;return doc2.records=doc2.records.filter((record2)=>!wanted.has(record2.id)),before-doc2.records.length}function applyTerminalOutcome(doc2,ids,outcome){let removed=dequeueRecords(doc2,ids);return doc2.counters[outcome]+=removed,removed}function retainWithRetry(doc2,ids){let wanted=new Set(ids),retried=[],unrecoverable=[];for(let record2 of doc2.records){if(!wanted.has(record2.id))continue;if(record2.attempts+=1,record2.state="pending",record2.inFlightAt=void 0,record2.attempts>=SKILL_USAGE_LIMITS.maxAttempts)unrecoverable.push(record2.id);else retried.push(record2.id)}if(doc2.counters.bump_retry+=retried.length,unrecoverable.length>0)applyTerminalOutcome(doc2,unrecoverable,"bump_unrecoverable");return{retried,unrecoverable}}function buildSkillUsageHealthPayload(doc2,trigger,gauges){let pendingRetained=0,uncertainRetained=0;for(let record2 of doc2.records)if(record2.state==="uncertain")uncertainRetained+=1;else pendingRetained+=1;return{trigger,accepted:doc2.counters.accepted,compacted:doc2.counters.compacted,dropped:doc2.counters.dropped,skills_dropped:doc2.counters.skills_dropped,corrupt:doc2.counters.corrupt,pending_retained:pendingRetained,uncertain_retained:uncertainRetained,uncertain_expired:doc2.counters.uncertain_expired,pending_evicted:doc2.counters.pending_evicted,no_source_knowledge:doc2.counters.no_source_knowledge,no_matching_knowledge:doc2.counters.no_matching_knowledge,bump_retry:doc2.counters.bump_retry,bump_unrecoverable:doc2.counters.bump_unrecoverable,bump_applied_zero:doc2.counters.bump_applied_zero,pressure:doc2.counters.pressure,curator_skipped:doc2.counters.curator_skipped,bytes:gauges.bytes,limit_bytes:gauges.limitBytes,oldest_timestamp:doc2.coverage.oldestRetained,newest_timestamp:doc2.coverage.newestRetained,coverage:doc2.coverage.complete}}function emitSkillUsageHealth(doc2,trigger,gauges,directory){try{let healthPayload=buildSkillUsageHealthPayload(doc2,trigger,gauges);if(_internals59.emitHealth(healthPayload),directory)observeStoreHealth({directory,kind:"skill_usage_health",payload:healthPayload})}catch(err){log("[skill-usage-pending] health emit failed (best-effort):",err instanceof Error?err.message:String(err))}}var SKILL_USAGE_LIMITS,SKILL_USAGE_LOCK_STALE_MS=300000,ENQUEUE_LOCK_ATTEMPTS=5,ENQUEUE_LOCK_RETRY_MS=10,SKILL_USAGE_LOCK_UNAVAILABLE="skill-usage pending queue lock unavailable; refusing to append an unqueued actionable verdict",PRESSURE_CACHE_MS=5000,SKILL_USAGE_COUNTER_KEYS,_internals59,_pressure=!1,_pressureCheckedAt=0,_pressureDirectory=null,MAX_CACHED_PROJECTS=8,MAX_CACHED_DOCUMENT_BYTES,_coverageCache,_documentCache,SKILL_USAGE_LOCK_BASENAME="skill-usage.lock";var init_skill_usage_pending=__esm(()=>{init_learning_health();init_telemetry();init_logger();init_utils2();SKILL_USAGE_LIMITS={version:1,maxEntries:5000,maxBytes:1572864,maxAgeMs:7776000000,floorPerSkill:20,curatorMinSample:10,readMaxBytes:1677722,migrationChunkBytes:262144,headerMaxBytes:8192,queueMaxRecords:5000,queueMaxBytes:524288,maxAttempts:5,checkInterval:50},SKILL_USAGE_COUNTER_KEYS=["accepted","compacted","dropped","skills_dropped","corrupt","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped"],_internals59={existsSync:fs39.existsSync.bind(fs39),readFileSync:fs39.readFileSync.bind(fs39),writeFileSync:fs39.writeFileSync.bind(fs39),renameSync:fs39.renameSync.bind(fs39),mkdirSync:fs39.mkdirSync.bind(fs39),statSync:fs39.statSync.bind(fs39),openSync:fs39.openSync.bind(fs39),closeSync:fs39.closeSync.bind(fs39),unlinkSync:fs39.unlinkSync.bind(fs39),now:()=>Date.now(),emitHealth:(payload)=>{telemetry.skillUsageHealth(payload)}},MAX_CACHED_DOCUMENT_BYTES=SKILL_USAGE_LIMITS.queueMaxBytes;_coverageCache=new Map,_documentCache=new Map});import*as crypto7 from"node:crypto";import*as fs40 from"node:fs";import*as path66 from"node:path";import{StringDecoder}from"node:string_decoder";function resolveLogPath(directory){return validateSwarmPath(directory,"skill-usage.jsonl")}function normalizeComplianceVerdict(verdict){return verdict==="violation"?"violated":verdict}function isActionableVerdict(verdict){return verdict==="compliant"||verdict==="violated"}function normalizeSkillUsageEntry(raw){let entry=raw;return{...entry,complianceVerdict:normalizeComplianceVerdict(entry.complianceVerdict)}}function legacySkillUsageId(entry){let stable=JSON.stringify({skillPath:entry.skillPath,agentName:entry.agentName,taskID:entry.taskID,timestamp:entry.timestamp,complianceVerdict:entry.complianceVerdict,sessionID:entry.sessionID,skillVersion:entry.skillVersion});return`legacy:${crypto7.createHash("sha256").update(stable).digest("hex")}`}function parseSkillUsageEntry(raw){let entry=raw;if(entry.type==="feedback_applied")return null;if(typeof entry.skillPath!=="string"||typeof entry.agentName!=="string"||typeof entry.taskID!=="string"||typeof entry.timestamp!=="string"||typeof entry.complianceVerdict!=="string"||typeof entry.sessionID!=="string")return null;return normalizeSkillUsageEntry({...entry,id:typeof entry.id==="string"?entry.id:legacySkillUsageId(entry)})}function parseFeedbackMarker(raw){let marker=raw;if(marker.type!=="feedback_applied")return null;if(typeof marker.timestamp!=="string")return null;if(!Array.isArray(marker.processedEntryIds))return null;let processedEntryIds=marker.processedEntryIds.filter((id)=>typeof id==="string"&&id.length>0);return{type:"feedback_applied",timestamp:marker.timestamp,processedEntryIds}}function appendFeedbackAppliedMarker(directory,processedEntryIds){if(processedEntryIds.length===0)return;let resolved=resolveLogPath(directory),dir=path66.dirname(resolved);if(!_internals60.existsSync(dir))_internals60.mkdirSync(dir,{recursive:!0});let marker={type:"feedback_applied",timestamp:new Date().toISOString(),processedEntryIds:[...new Set(processedEntryIds)]};_internals60.appendFileSync(resolved,`${JSON.stringify(marker)}
933
+ `:"",succeeded=!1,fd=_internals56.openSync(tmpPath,"w");try{_internals56.writeSync(fd,payload,0),_internals56.fsyncSync(fd),_internals56.closeSync(fd),await _internals56.renameWithRetry(tmpPath,filePath),succeeded=!0}catch(err){try{_internals56.closeSync(fd)}catch{}let msg=err instanceof Error?err.message:String(err);throw Error(`documents-cache rewrite failed: ${msg}`)}finally{if(!succeeded)try{await _internals56.unlink(tmpPath)}catch{}}return Buffer.byteLength(payload,"utf8")}async function pruneEvidenceDocuments(args2){assertProjectRoot(args2.directory);let dryRun=args2.dryRun===!0,capsUnset=(typeof args2.maxBytes!=="number"||args2.maxBytes<=0)&&(typeof args2.maxRecords!=="number"||args2.maxRecords<=0),filePath=validateSwarmPath(args2.directory,EVIDENCE_CACHE_FILE),stat8;try{stat8=await _internals56.stat(filePath)}catch(err){if(err?.code==="ENOENT")return emptyResult(dryRun);throw err}if(capsUnset)return{inventory:0,selected:0,archived:0,corrupt:0,bytesBefore:stat8.size,bytesAfter:stat8.size,dryRun,aborted:!1};let readResult;try{readResult=await readCacheRows(filePath)}catch(err){let msg=err instanceof Error?err.message:String(err);throw warn(`documents-cache prune: read failed: ${msg}`),err}if(readResult.aborted)return warn(`documents-cache prune: aborted, file exceeds ${MAX_READ_BYTES} bytes; left untouched`),{inventory:readResult.rows.length,selected:0,archived:0,corrupt:readResult.corrupt,bytesBefore:readResult.bytesBefore,bytesAfter:readResult.bytesBefore,dryRun,aborted:!0};let{survivors,selected}=selectSurvivors(readResult.rows,args2.maxRecords,args2.maxBytes);if(dryRun){let bytesAfter2=survivors.reduce((sum,row)=>sum+row.bytes,0);return{inventory:readResult.rows.length,selected,archived:0,corrupt:readResult.corrupt,bytesBefore:readResult.bytesBefore,bytesAfter:bytesAfter2,dryRun:!0,aborted:!1}}if(selected===0&&readResult.corrupt===0)return{inventory:readResult.rows.length,selected:0,archived:0,corrupt:0,bytesBefore:readResult.bytesBefore,bytesAfter:readResult.bytesBefore,dryRun:!1,aborted:!1};let bytesAfter=await rewriteAtomic(filePath,survivors);return{inventory:readResult.rows.length,selected,archived:selected,corrupt:readResult.corrupt,bytesBefore:readResult.bytesBefore,bytesAfter,dryRun:!1,aborted:!1}}var EVIDENCE_CACHE_FILE="evidence-cache/documents.jsonl",MAX_READ_BYTES=104857600,RENAME_MAX_ATTEMPTS2=5,RENAME_BACKOFF_MS=10,RENAME_RETRY_CODES,_internals56;var init_documents_retention=__esm(()=>{init_utils2();init_utils();init_project_boundary();RENAME_RETRY_CODES=new Set(["EPERM","EBUSY","ENOTEMPTY","EACCES"]),_internals56={stat:(p)=>fsp2.stat(p),createReadStream:(p,options)=>fs37.createReadStream(p,options),openSync:(p,flags)=>fs37.openSync(p,flags),writeSync:(fd,data,position)=>fs37.writeSync(fd,data,position),fsyncSync:(fd)=>fs37.fsyncSync(fd),closeSync:(fd)=>fs37.closeSync(fd),renameWithRetry:atomicRenameWithRetry,unlink:(p)=>fsp2.unlink(p)}});import{mkdirSync as mkdirSync23,readdirSync as readdirSync8,realpathSync as realpathSync13,renameSync as renameSync15,rmSync as rmSync7,statSync as statSync20}from"node:fs";import*as fs38 from"node:fs/promises";import*as path63 from"node:path";function isValidEvidenceType(type){return VALID_EVIDENCE_TYPES.includes(type)}function isSecretscanEvidence(evidence){return evidence.type==="secretscan"}function validateProjectRoot(directory){assertProjectRoot(directory,{realpathSync:_internals57.realpathSync,statSync:_internals57.statSync},"evidence")}async function saveEvidence(directory,taskId,evidence,abortSignal){abortSignal?.throwIfAborted(),_internals57.validateProjectRoot(directory);let sanitizedTaskId=sanitizeTaskId2(taskId),relativePath=path63.join("evidence",sanitizedTaskId,"evidence.json");return validateSwarmPath(directory,relativePath),_internals57.validateEvidence(evidence),withEvidenceLock(directory,relativePath,"evidence-manager",sanitizedTaskId,async()=>{abortSignal?.throwIfAborted();let evidencePath=validateSwarmPath(directory,relativePath),evidenceDir=path63.dirname(evidencePath),bundle,existingContent=await readSwarmFileAsync(directory,relativePath);if(abortSignal?.throwIfAborted(),existingContent!==null)try{let parsed=JSON.parse(existingContent);bundle=EvidenceBundleSchema.parse(parsed)}catch(error49){warn(`Existing evidence bundle invalid for task ${sanitizedTaskId}, creating new: ${error49 instanceof Error?error49.message:String(error49)}`);let now=new Date().toISOString();bundle={schema_version:"1.0.0",task_id:sanitizedTaskId,entries:[],created_at:now,updated_at:now}}else{let now=new Date().toISOString();bundle={schema_version:"1.0.0",task_id:sanitizedTaskId,entries:[],created_at:now,updated_at:now}}let MAX_BUNDLE_ENTRIES=100,entries=[...bundle.entries,evidence];if(entries.length>MAX_BUNDLE_ENTRIES)entries=entries.slice(entries.length-MAX_BUNDLE_ENTRIES);let updatedBundle={...bundle,entries,updated_at:new Date().toISOString()},bundleJson=JSON.stringify(updatedBundle);if(bundleJson.length>EVIDENCE_MAX_JSON_BYTES)throw Error(`Evidence bundle size (${bundleJson.length} bytes) exceeds maximum (${EVIDENCE_MAX_JSON_BYTES} bytes)`);mkdirSync23(evidenceDir,{recursive:!0});let tempPath=path63.join(evidenceDir,`evidence.json.tmp.${Date.now()}.${process.pid}`);try{await bunWrite(tempPath,bundleJson),abortSignal?.throwIfAborted(),renameSync15(tempPath,evidencePath)}catch(error49){try{rmSync7(tempPath,{force:!0})}catch{}throw error49}return invalidateCachedArtifact(evidencePath),updatedBundle})}function isFlatRetrospective(parsed){return parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed)&&parsed.type==="retrospective"&&!parsed.schema_version}function remapLegacyTaskComplexity(entry){let taskComplexity=entry.task_complexity;if(typeof taskComplexity==="string"&&taskComplexity in LEGACY_TASK_COMPLEXITY_MAP)return{...entry,task_complexity:LEGACY_TASK_COMPLEXITY_MAP[taskComplexity]};return entry}function wrapFlatRetrospective(flatEntry,taskId){let now=new Date().toISOString(),remappedEntry=remapLegacyTaskComplexity(flatEntry);return{schema_version:"1.0.0",task_id:remappedEntry.task_id??taskId,created_at:remappedEntry.timestamp??now,updated_at:remappedEntry.timestamp??now,entries:[remappedEntry]}}async function loadEvidence(directory,taskId,options){let sanitizedTaskId=sanitizeTaskId2(taskId),relativePath=path63.join("evidence",sanitizedTaskId,"evidence.json");if(relativePath.length>4096)return{status:"not_found"};let evidencePath=validateSwarmPath(directory,relativePath),content=await readSwarmFileAsync(directory,relativePath);if(content===null)return{status:"not_found"};let parsed;try{parsed=JSON.parse(content)}catch{return{status:"invalid_schema",errors:["Invalid JSON"]}}if(isFlatRetrospective(parsed)){let wrappedBundle=_internals57.wrapFlatRetrospective(parsed,sanitizedTaskId);try{let validated=EvidenceBundleSchema.parse(wrappedBundle);if(options?.migrate===!1)return{status:"found",bundle:validated};try{validateProjectRoot(directory),await withEvidenceLock(directory,relativePath,"evidence-loader",sanitizedTaskId,async()=>{let evidenceDir=path63.dirname(evidencePath),bundleJson=JSON.stringify(validated),tempPath=path63.join(evidenceDir,`evidence.json.tmp.${Date.now()}.${process.pid}`);try{await bunWrite(tempPath,bundleJson),await fs38.rename(tempPath,evidencePath),invalidateCachedArtifact(evidencePath)}catch(writeError){try{rmSync7(tempPath,{force:!0})}catch{}warn(`Failed to persist repaired flat retrospective for task ${sanitizedTaskId}: ${writeError instanceof Error?writeError.message:String(writeError)}`)}})}catch(lockErr){warn(`Evidence lock failed during flat-retrospective write-back for task ${sanitizedTaskId}: ${lockErr instanceof Error?lockErr.message:String(lockErr)}`)}return{status:"found",bundle:validated}}catch(error49){return warn(`Wrapped flat retrospective failed validation for task ${sanitizedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`),{status:"invalid_schema",errors:error49 instanceof ZodError?error49.issues.map((e)=>`${e.path.join(".")}: ${e.message}`):[error49 instanceof Error?error49.message:String(error49)]}}}try{return{status:"found",bundle:EvidenceBundleSchema.parse(parsed)}}catch(error49){return warn(`Evidence bundle validation failed for task ${sanitizedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`),{status:"invalid_schema",errors:error49 instanceof ZodError?error49.issues.map((e)=>`${e.path.join(".")}: ${e.message}`):[error49 instanceof Error?error49.message:String(error49)]}}}async function listEvidenceTaskIds(directory){let evidenceBasePath=validateSwarmPath(directory,"evidence");try{statSync20(evidenceBasePath)}catch{return[]}let entries;try{entries=readdirSync8(evidenceBasePath)}catch{return[]}let taskIds=[];for(let entry of entries){let entryPath=path63.join(evidenceBasePath,entry);try{if(!statSync20(entryPath).isDirectory())continue;sanitizeTaskId2(entry),taskIds.push(entry)}catch(error49){if(error49 instanceof Error&&!error49.message.startsWith("Invalid task ID"))warn(`Error reading evidence entry '${entry}': ${error49.message}`)}}return taskIds.sort()}async function deleteEvidence(directory,taskId){let sanitizedTaskId=sanitizeTaskId2(taskId);try{validateProjectRoot(directory)}catch{return!1}let relativePath=path63.join("evidence",sanitizedTaskId),evidenceDir=validateSwarmPath(directory,relativePath);try{statSync20(evidenceDir)}catch{return!1}try{return rmSync7(evidenceDir,{recursive:!0,force:!0}),!0}catch(error49){return warn(`Failed to delete evidence for task ${sanitizedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`),!1}}async function checkRequirementCoverage(phase,directory){let relativePath=path63.join("evidence",`req-coverage-phase-${phase}.json`),absolutePath=path63.resolve(directory,".swarm",relativePath);try{return await fs38.access(absolutePath),{exists:!0,path:absolutePath}}catch{return{exists:!1,path:absolutePath}}}async function archiveEvidence(directory,maxAgeDays,maxBundles,options){let taskIds=await _internals57.listEvidenceTaskIds(directory),cutoffDate=options?.now?new Date(options.now):_internals57.now();cutoffDate.setDate(cutoffDate.getDate()-maxAgeDays);let cutoffIso=cutoffDate.toISOString(),selected=new Set,selectedByAge=new Set,selectedByCount=new Set,archived=[],failed=[],remainingBundles=[];for(let taskId of taskIds){let result;try{result=await _internals57.loadEvidence(directory,taskId)}catch{warn("archive: skipping corrupt or unreadable evidence for task",taskId);continue}if(result.status!=="found")continue;if(result.bundle.updated_at<cutoffIso)selected.add(taskId),selectedByAge.add(taskId);else remainingBundles.push({taskId,updatedAt:result.bundle.updated_at})}if(maxBundles!==void 0&&remainingBundles.length>maxBundles){remainingBundles.sort((a,b)=>a.updatedAt.localeCompare(b.updatedAt));let toDelete=remainingBundles.length-maxBundles;for(let i=0;i<toDelete;i++)selected.add(remainingBundles[i].taskId),selectedByCount.add(remainingBundles[i].taskId)}if(!options?.dryRun)for(let taskId of[...selected].sort())if(await _internals57.deleteEvidence(directory,taskId))archived.push(taskId);else failed.push(taskId);let evaluation=await archiveEvaluationArtifacts({directory,maxAgeDays,maxBundles,dryRun:options?.dryRun,now:options?.now}),documentsCache={inventory:0,selected:0,archived:0,corrupt:0,bytesBefore:0,bytesAfter:0,dryRun:options?.dryRun===!0,aborted:!1};if(typeof options?.cacheMaxBytes==="number"&&options.cacheMaxBytes>0||typeof options?.cacheMaxRecords==="number"&&options.cacheMaxRecords>0)try{documentsCache=await _internals57.pruneEvidenceDocuments({directory,maxBytes:options?.cacheMaxBytes,maxRecords:options?.cacheMaxRecords,dryRun:options?.dryRun})}catch(error49){let msg=error49 instanceof Error?error49.message:String(error49);warn(`archiveEvidence: documents-cache prune failed (fail-open): ${msg}`)}if(options?.report)return{inventoryEvidence:[...taskIds].sort(),selectedEvidence:[...selected].sort(),selectedEvidenceByAge:[...selectedByAge].sort(),selectedEvidenceByCount:[...selectedByCount].sort(),archivedEvidence:archived.sort(),failedEvidence:failed.sort(),evaluation,documentsCache};return archived.sort()}function validateEvidence(evidence){return EvidenceSchema.parse(evidence)}var VALID_EVIDENCE_TYPES,sanitizeTaskId2,LEGACY_TASK_COMPLEXITY_MAP,_internals57;var init_manager2=__esm(()=>{init_zod();init_evidence_schema();init_retention();init_utils2();init_utils();init_bun_compat();init_project_boundary();init_swarm_artifact_cache();init_documents_retention();init_lock();init_task_id();VALID_EVIDENCE_TYPES=["review","test","diff","approval","note","retrospective","syntax","placeholder","sast","sbom","build","quality_budget","secretscan"];sanitizeTaskId2=sanitizeTaskId;LEGACY_TASK_COMPLEXITY_MAP={low:"simple",medium:"moderate",high:"complex"};_internals57={wrapFlatRetrospective,loadEvidence,listEvidenceTaskIds,validateProjectRoot,validateEvidence,saveEvidence,deleteEvidence,pruneEvidenceDocuments,realpathSync:realpathSync13,statSync:statSync20,now:()=>new Date}});function createQueue(now){return{items:[],dropped:0,llmCallsUsed:0,tokensUsed:0,retriesUsed:0,lastDrainAt:now,enqueuedSinceLastDrain:0}}function getOrCreateQueue(sessionID){let queue=queuesBySession.get(sessionID);if(!queue){queue=createQueue(_internals58.now()),queuesBySession.set(sessionID,queue);while(queuesBySession.size>500){let oldest=queuesBySession.keys().next().value;if(oldest===void 0||oldest===sessionID)break;queuesBySession.delete(oldest)}}return queue}function positiveIntOr(value,fallback){return Number.isFinite(value)&&Number(value)>0?Math.floor(Number(value)):fallback}function enqueueCandidate(sessionID,candidate,limits){if(typeof sessionID!=="string"||sessionID.length===0)return{enqueued:!1,dropped:0,evictedOldest:!1};let queue=getOrCreateQueue(sessionID),maxQueueSize=positiveIntOr(limits.maxQueueSize,50);queue.items.push({candidate,enqueuedAt:_internals58.now(),attempts:0}),queue.enqueuedSinceLastDrain++;let evictedOldest=!1;while(queue.items.length>maxQueueSize)queue.items.shift(),queue.dropped++,evictedOldest=!0;return{enqueued:!0,dropped:queue.dropped,evictedOldest}}function computeDrainSize(depth,velocity,limits){if(!Number.isFinite(depth)||depth<=0)return 0;let minDrain=positiveIntOr(limits.minDrain,1),maxDrain=Math.max(minDrain,positiveIntOr(limits.maxDrain,minDrain)),depthFactor=clampUnit(limits.drainDepthFactor),velocityFactor=clampUnit(limits.drainVelocityFactor),safeVelocity=Number.isFinite(velocity)&&velocity>0?velocity:0,adaptive=minDrain+depthFactor*depth+velocityFactor*safeVelocity,bounded=Math.min(Math.max(Math.ceil(adaptive),minDrain),maxDrain);return Math.min(bounded,Math.floor(depth))}function clampUnit(value){let n=Number(value);if(!Number.isFinite(n)||n<=0)return 0;return n>1?1:n}function computeArrivalVelocity(stats2,now){let elapsedMs=now-stats2.lastDrainAt;if(!Number.isFinite(elapsedMs)||elapsedMs<=0)return 0;return stats2.enqueuedSinceLastDrain*1000/elapsedMs}function takeDrainBatch(sessionID,size){let queue=queuesBySession.get(sessionID);if(!queue||queue.items.length===0)return[];let count=Math.max(0,Math.min(Math.floor(size),queue.items.length)),batch=queue.items.splice(0,count);queue.lastDrainAt=_internals58.now(),queue.enqueuedSinceLastDrain=0;for(let item of batch)item.attempts++;return batch}function requeueCandidate(sessionID,item,limits){let queue=queuesBySession.get(sessionID);if(!queue)return;let maxQueueSize=positiveIntOr(limits.maxQueueSize,50);queue.items.unshift(item);while(queue.items.length>maxQueueSize)queue.items.pop(),queue.dropped++}function getQueueDepth(sessionID){if(!sessionID)return 0;return queuesBySession.get(sessionID)?.items.length??0}function reserveLlmBudget(sessionID,estimatedTokens,limits){let queue=queuesBySession.get(sessionID);if(!queue)return!1;let maxCalls=Math.max(0,Math.floor(Number(limits.maxLlmCallsPerSession)||0)),maxTokens=Math.max(0,Math.floor(Number(limits.maxTokensPerSession)||0));if(maxCalls===0||maxTokens===0)return!1;let tokens=Math.max(0,Math.floor(Number(estimatedTokens)||0));if(queue.llmCallsUsed+1>maxCalls)return!1;if(queue.tokensUsed+tokens>maxTokens)return!1;return queue.llmCallsUsed++,queue.tokensUsed+=tokens,!0}function recordRetry(sessionID){let queue=queuesBySession.get(sessionID);if(!queue)return 0;return queue.retriesUsed++,queue.retriesUsed}function getQueueStats(sessionID){let queue=sessionID?queuesBySession.get(sessionID):void 0;if(!queue)return{depth:0,dropped:0,llmCallsUsed:0,tokensUsed:0,retriesUsed:0,lastDrainAt:0,enqueuedSinceLastDrain:0};return{depth:queue.items.length,dropped:queue.dropped,llmCallsUsed:queue.llmCallsUsed,tokensUsed:queue.tokensUsed,retriesUsed:queue.retriesUsed,lastDrainAt:queue.lastDrainAt,enqueuedSinceLastDrain:queue.enqueuedSinceLastDrain}}function resetSessionQueue(sessionID){if(sessionID===void 0){queuesBySession.clear();return}queuesBySession.delete(sessionID)}var MAX_CANDIDATE_DRAIN_ATTEMPTS=5,queuesBySession,_internals58;var init_candidate_queue=__esm(()=>{queuesBySession=new Map,_internals58={now:()=>Date.now()}});import{existsSync as existsSync34}from"node:fs";import{mkdir as mkdir11,readFile as readFile14,rename as rename6,writeFile as writeFile5}from"node:fs/promises";import*as path64 from"node:path";async function acquireLock(dir){let acquire=import_proper_lockfile7.default.lock(dir,LOCK_RETRY_OPTS),timer,timeout=new Promise((_,reject)=>{timer=setTimeout(()=>{reject(Error(`SKILL_IMPROVER_QUOTA_LOCK_TIMEOUT: failed to acquire lock on ${dir} within ${LOCK_ACQUIRE_TIMEOUT_MS}ms`))},LOCK_ACQUIRE_TIMEOUT_MS)});try{return await Promise.race([acquire,timeout])}finally{if(timer)clearTimeout(timer)}}function resolveQuotaPath(directory,scope="skill-improver"){return path64.join(directory,".swarm",scope==="knowledge-enrichment"?"knowledge-enrichment-quota.json":"skill-improver-quota.json")}function todayKey(window2,now=new Date){if(window2==="utc")return now.toISOString().slice(0,10);let yr=now.getFullYear(),m=String(now.getMonth()+1).padStart(2,"0"),d=String(now.getDate()).padStart(2,"0");return`${yr}-${m}-${d}`}async function readState3(filePath){if(!existsSync34(filePath))return null;try{let raw=await readFile14(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed.date!=="string"||typeof parsed.calls_used!=="number"||typeof parsed.max_calls!=="number"||parsed.window!=="utc"&&parsed.window!=="local")return null;return parsed}catch{return null}}async function writeState(filePath,state2){await mkdir11(path64.dirname(filePath),{recursive:!0});let tmp=`${filePath}.tmp-${process.pid}`;await writeFile5(tmp,JSON.stringify(state2,null,2),"utf-8"),await rename6(tmp,filePath)}async function getQuotaState(directory,opts){let filePath=resolveQuotaPath(directory,opts.scope),today=todayKey(opts.window,opts.now),existing=await readState3(filePath);if(!existing||existing.date!==today||existing.window!==opts.window){let fresh={date:today,calls_used:0,max_calls:opts.maxCalls,window:opts.window};return await writeState(filePath,fresh),fresh}return{...existing,max_calls:opts.maxCalls}}async function reserveQuota(directory,opts){let filePath=resolveQuotaPath(directory,opts.scope);await mkdir11(path64.dirname(filePath),{recursive:!0});let release=null;try{release=await acquireLock(path64.dirname(filePath));let state2=await getQuotaState(directory,opts);if(state2.calls_used+opts.nCalls>opts.maxCalls)return{allowed:!1,state:state2,reason:`daily quota exhausted: used=${state2.calls_used} requested=${opts.nCalls} max=${opts.maxCalls}`};let next={...state2,calls_used:state2.calls_used+opts.nCalls,max_calls:opts.maxCalls,last_run_at:(opts.now??new Date).toISOString()};return await writeState(filePath,next),{allowed:!0,state:next}}finally{if(release)try{await release()}catch{}}}async function releaseQuota(directory,opts){let filePath=resolveQuotaPath(directory,opts.scope);await mkdir11(path64.dirname(filePath),{recursive:!0});let release=null;try{release=await acquireLock(path64.dirname(filePath));let state2=await getQuotaState(directory,opts),next={...state2,calls_used:Math.max(0,state2.calls_used-opts.nCalls),max_calls:opts.maxCalls};return await writeState(filePath,next),next}finally{if(release)try{await release()}catch{}}}var import_proper_lockfile7,LOCK_ACQUIRE_TIMEOUT_MS=1e4,LOCK_RETRY_OPTS;var init_skill_improver_quota=__esm(()=>{import_proper_lockfile7=__toESM(require_proper_lockfile(),1),LOCK_RETRY_OPTS={retries:{retries:30,minTimeout:50,maxTimeout:200,factor:1.5},stale:5000}});function getStoredInputArgs(callID){return storedInputArgs.get(callID)}function setStoredInputArgs(callID,args2){storedInputArgs.set(callID,args2);while(storedInputArgs.size>2000){let oldest=storedInputArgs.keys().next().value;if(oldest===void 0||oldest===callID)break;storedInputArgs.delete(oldest)}}function deleteStoredInputArgs(callID){storedInputArgs.delete(callID)}var storedInputArgs;var init_stored_input_args=__esm(()=>{storedInputArgs=new Map});function stripUntrustedAttributionMarkdown(text){let lines=text.split(/\r?\n/),kept=[],fence,inBlockQuote=!1;for(let line of lines){if(fence){let close=line.match(/^[ \t]{0,3}(`+|~+)[ \t]*$/);if(close&&close[1][0]===fence.marker&&close[1].length>=fence.length)fence=void 0;continue}let open4=line.match(/^[ \t]{0,3}(`{3,}|~{3,})(.*)$/);if(open4&&!(open4[1][0]==="`"&&open4[2].includes("`"))){fence={marker:open4[1][0],length:open4[1].length};continue}if(/^[ \t]{0,3}>/.test(line)){inBlockQuote=!0;continue}if(inBlockQuote)if(line.trim()==="")inBlockQuote=!1;else continue;kept.push(line)}return kept.join(`
934
+ `)}function isSafeAttributionId(value){return value.length<=TASK_ID_RESOLUTION_LIMITS.maxTokenChars&&SAFE_ATTRIBUTION_ID.test(value)&&!/^ses_/i.test(value)&&!value.includes("..")}function isAllowedAttributionId(value,knownPlanTaskIds,planContextOverLimit=!1){if(!isSafeAttributionId(value))return!1;return!STRICT_PLAN_ID.test(value)||!planContextOverLimit&&!knownPlanTaskIds||knownPlanTaskIds?.has(value)===!0}function sorted(values){return[...values].sort()}function addCandidate(candidates,value){if(candidates.add(value),candidates.size>TASK_ID_RESOLUTION_LIMITS.maxCandidates)return{status:"over_limit",input:"candidates"};return null}function select(candidates,source){if(candidates.size===1)return{status:"resolved",taskId:[...candidates][0],source};if(candidates.size>1)return{status:"ambiguous",candidates:sorted(candidates)};return null}function validateKnownIds(knownPlanTaskIds){if(!knownPlanTaskIds)return null;if(knownPlanTaskIds.size>TASK_ID_RESOLUTION_LIMITS.maxKnownIds)return{status:"over_limit",input:"knownPlanTaskIds"};for(let value of knownPlanTaskIds)if(typeof value!=="string"||value.length>TASK_ID_RESOLUTION_LIMITS.maxTokenChars||!STRICT_PLAN_ID.test(value))return{status:"invalid",input:"knownPlanTaskIds"};return null}function isStrictExplicitPlanField(value,knownPlanTaskIds,planContextOverLimit=!1){return STRICT_PLAN_ID.test(value)&&(planContextOverLimit||knownPlanTaskIds!==void 0)}function resolveTaskId(input,options){try{if(options.planContextOverLimit&&options.knownPlanTaskIds)return{status:"invalid",input:"planContext"};let knownValidation=validateKnownIds(options.knownPlanTaskIds);if(knownValidation)return knownValidation;let totalChars=0,textFields=[];for(let field of TEXT_FIELDS){let raw=input[field];if(raw===void 0||raw===null)continue;if(typeof raw!=="string")return{status:"invalid",input:field};if(raw.length>TASK_ID_RESOLUTION_LIMITS.maxFieldChars)return{status:"over_limit",input:field};if(totalChars+=raw.length,totalChars>TASK_ID_RESOLUTION_LIMITS.maxTotalChars)return{status:"over_limit",input:"totalText"};textFields.push(raw)}let explicit=new Set;for(let field of EXPLICIT_TASK_ID_FIELDS){let raw=input[field];if(raw===void 0||raw===null)continue;if(typeof raw!=="string")return{status:"invalid",input:field};let value=raw.trim();if(value.length>TASK_ID_RESOLUTION_LIMITS.maxTokenChars)return{status:"over_limit",input:field};if(!(options.policy==="plan"?value.length<=20&&STRICT_PLAN_ID.test(value)&&(!options.knownPlanTaskIds||options.knownPlanTaskIds.has(value)||options.planContextOverLimit):isAllowedAttributionId(value,options.knownPlanTaskIds,options.planContextOverLimit))){if(options.policy==="plan"&&value.length<=20&&STRICT_PLAN_ID.test(value)&&options.knownPlanTaskIds)return{status:"invalid",input:field};if(options.policy==="attribution"&&isStrictExplicitPlanField(value,options.knownPlanTaskIds,options.planContextOverLimit))return{status:"invalid",input:field};continue}let overflow=addCandidate(explicit,value);if(overflow)return overflow}if(options.policy==="plan"){let explicitSelection=select(explicit,"explicit");if(explicitSelection)return explicitSelection;if(options.planContextOverLimit)return{status:"over_limit",input:"knownPlanTaskIds"};let taskLineCandidates=new Set;for(let text of textFields){TASK_LINE.lastIndex=0;for(let lineMatch of text.matchAll(TASK_LINE)){PLAN_CANDIDATE.lastIndex=0;for(let match of lineMatch[1].matchAll(PLAN_CANDIDATE)){let value=match[1];if(options.knownPlanTaskIds&&!options.knownPlanTaskIds.has(value))continue;let overflow=addCandidate(taskLineCandidates,value);if(overflow)return overflow}}}let taskLineSelection=select(taskLineCandidates,"task_line");if(taskLineSelection)return taskLineSelection;let textCandidates=new Set;for(let text of textFields){PLAN_CANDIDATE.lastIndex=0;for(let match of text.matchAll(PLAN_CANDIDATE)){let value=match[1];if(options.knownPlanTaskIds&&!options.knownPlanTaskIds.has(value))continue;let overflow=addCandidate(textCandidates,value);if(overflow)return overflow}}let textSelection=select(textCandidates,"text");if(textSelection)return textSelection}else{let markerTextFields=options.standaloneTaskMarkerOnly?textFields.map(stripUntrustedAttributionMarkdown):textFields,hasInvalidRawMarker=!1,rawMarkers=options.standaloneTaskMarkerOnly?[ATTRIBUTION_TASK_MARKER_RAW_STANDALONE]:[ATTRIBUTION_ID_MARKER_RAW,ATTRIBUTION_TASK_MARKER_RAW];for(let rawMarker of rawMarkers)for(let text of markerTextFields){rawMarker.lastIndex=0;for(let match of text.matchAll(rawMarker)){let value=match[1];if(value.length>TASK_ID_RESOLUTION_LIMITS.maxTokenChars)return{status:"over_limit",input:"markerToken"};if(!isAllowedAttributionId(value,options.knownPlanTaskIds,options.planContextOverLimit))hasInvalidRawMarker=!0}}if(hasInvalidRawMarker)return{status:"invalid",input:"marker"};let marked=new Set,markers=options.standaloneTaskMarkerOnly?[ATTRIBUTION_TASK_MARKER_STANDALONE]:[ATTRIBUTION_ID_MARKER,ATTRIBUTION_TASK_MARKER];for(let marker of markers)for(let text of markerTextFields){marker.lastIndex=0;for(let match of text.matchAll(marker)){let value=match[1];if(value.length>TASK_ID_RESOLUTION_LIMITS.maxTokenChars)return{status:"over_limit",input:"markerToken"};if(!isAllowedAttributionId(value,options.knownPlanTaskIds,options.planContextOverLimit))continue;let overflow=addCandidate(marked,value);if(overflow)return overflow}}let explicitSelection=select(explicit,"explicit");if(explicitSelection)return explicitSelection;let markerSelection=select(marked,"marker");if(markerSelection)return markerSelection}if(options.fallback!==void 0){if(!options.fallbackProvenUnique)return{status:"invalid",input:"fallback"};let fallback=options.fallback.trim(),validFallback=options.policy==="plan"?STRICT_PLAN_ID.test(fallback)&&options.knownPlanTaskIds?.has(fallback)===!0:isAllowedAttributionId(fallback,options.knownPlanTaskIds,options.planContextOverLimit);if(fallback.length>TASK_ID_RESOLUTION_LIMITS.maxTokenChars||!validFallback)return{status:"invalid",input:"fallback"};return{status:"resolved",taskId:fallback,source:"fallback"}}return{status:"missing"}}catch{return{status:"invalid",input:"resolver"}}}function resolveDelegatedPlanTaskId(args2,planContext){let options=planContext instanceof Set?{knownPlanTaskIds:planContext}:planContext,result=resolveTaskId(args2,{policy:"plan",...options});return result.status==="resolved"?result.taskId:null}var TASK_ID_RESOLUTION_LIMITS,TEXT_FIELDS,EXPLICIT_TASK_ID_FIELDS,STRICT_PLAN_ID,SAFE_ATTRIBUTION_ID,PLAN_CANDIDATE,TASK_LINE,ATTRIBUTION_ID_MARKER,ATTRIBUTION_TASK_MARKER,ATTRIBUTION_TASK_MARKER_STANDALONE,ATTRIBUTION_ID_MARKER_RAW,ATTRIBUTION_TASK_MARKER_RAW,ATTRIBUTION_TASK_MARKER_RAW_STANDALONE;var init_task_id_resolver=__esm(()=>{TASK_ID_RESOLUTION_LIMITS={maxFields:4,maxFieldChars:32768,maxTotalChars:131072,maxKnownIds:1024,maxCandidates:32,maxTokenChars:80},TEXT_FIELDS=["prompt","description","task","input"],EXPLICIT_TASK_ID_FIELDS=["plan_task_id","planTaskId","task_id","taskId"],STRICT_PLAN_ID=/^\d+\.\d+(?:\.\d+)*$/,SAFE_ATTRIBUTION_ID=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,PLAN_CANDIDATE=/\b(\d+\.\d+(?:\.\d+)*)\b/g,TASK_LINE=/^\s*TASK\s*[:=]\s*(.*)$/gim,ATTRIBUTION_ID_MARKER=/\b(?:task_id|task-id|taskId)\s*[:=]\s*([A-Za-z0-9][A-Za-z0-9._-]*)/gi,ATTRIBUTION_TASK_MARKER=/\bTASK\s*[:=]\s*([A-Za-z0-9][A-Za-z0-9._-]*)[ \t]*(?=\r?$)/gim,ATTRIBUTION_TASK_MARKER_STANDALONE=/^TASK\s*[:=]\s*([A-Za-z0-9][A-Za-z0-9._-]*)[ \t]*\r?$/gim,ATTRIBUTION_ID_MARKER_RAW=/\b(?:task_id|task-id|taskId)\s*[:=][ \t]*([^\s]*)/gi,ATTRIBUTION_TASK_MARKER_RAW=/\bTASK\s*[:=][ \t]*([^\s]+)[ \t]*(?=\r?$)/gim,ATTRIBUTION_TASK_MARKER_RAW_STANDALONE=/^TASK\s*[:=][ \t]*([^\s]+)[ \t]*\r?$/gim});function collectPlanTaskIdContextFromPhases(phases){let collected=new Set;for(let phase of phases)for(let task of phase?.tasks??[]){if(!task||typeof task.id!=="string")continue;if(collected.add(task.id),collected.size>TASK_ID_RESOLUTION_LIMITS.maxKnownIds)return{status:"over_limit"}}return{status:"available",taskIds:collected}}async function loadPlanTaskIdContext(directory){try{let plan=await loadPlanJsonOnly(directory);if(!plan)return{status:"unavailable"};return collectPlanTaskIdContextFromPhases(plan.phases)}catch{return{status:"unavailable"}}}function toTaskIdPlanContextOptions(context){if(context.status==="available")return{knownPlanTaskIds:context.taskIds};if(context.status==="over_limit")return{planContextOverLimit:!0};return{}}var init_plan_task_id_context=__esm(()=>{init_manager();init_task_id_resolver()});import*as fs39 from"node:fs";import*as path65 from"node:path";function cacheGet(cache2,key){let hit=cache2.get(key);if(hit===void 0)return;return cache2.delete(key),cache2.set(key,hit),hit}function cacheSet(cache2,key,value){cache2.delete(key),cache2.set(key,value);while(cache2.size>MAX_CACHED_PROJECTS){let oldest=cache2.keys().next();if(oldest.done)break;cache2.delete(oldest.value)}}function statFingerprint(resolved){let stat8=_internals59.statSync(resolved,{bigint:!0}),size=Number(stat8.size);return{size,fingerprint:typeof stat8.mtimeNs==="bigint"?`${stat8.mtimeNs}:${size}`:null}}function resolvePendingPath(directory){return validateSwarmPath(directory,"skill-usage-pending.json")}function resolveSkillUsageLockPath(directory){return validateSwarmPath(directory,SKILL_USAGE_LOCK_BASENAME)}function siblingSwarmPath(resolved,basename11){return path65.join(path65.dirname(resolved),basename11)}function ensureSwarmDir2(resolved){let dir=path65.dirname(resolved);if(!_internals59.existsSync(dir))_internals59.mkdirSync(dir,{recursive:!0})}function sleepSyncMs(ms){try{let view=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(view,0,0,ms);return}catch{let until=Date.now()+ms,spins=0;while(Date.now()<until)spins+=1}}function tryCreateLock(lockPath){try{let fd=_internals59.openSync(lockPath,"wx");return _internals59.closeSync(fd),!0}catch{return!1}}function breakStaleLock(lockPath){try{let age=_internals59.now()-_internals59.statSync(lockPath).mtimeMs;if(Math.abs(age)<=SKILL_USAGE_LOCK_STALE_MS)return!1}catch{return!1}try{_internals59.unlinkSync(lockPath)}catch{return!1}return tryCreateLock(lockPath)}function acquireSkillUsageLock(directory){let lockPath;try{lockPath=resolveSkillUsageLockPath(directory)}catch{return null}return acquireSkillUsageLockAt(lockPath)}function acquireSkillUsageLockAt(lockPath){try{ensureSwarmDir2(lockPath)}catch{return null}if(tryCreateLock(lockPath))return{lockPath};if(breakStaleLock(lockPath))return{lockPath};return null}function acquireSkillUsageLockOrThrowAt(lockPath){for(let attempt=0;attempt<ENQUEUE_LOCK_ATTEMPTS;attempt++){let handle=acquireSkillUsageLockAt(lockPath);if(handle)return handle;if(attempt<ENQUEUE_LOCK_ATTEMPTS-1)sleepSyncMs(ENQUEUE_LOCK_RETRY_MS)}throw Error(SKILL_USAGE_LOCK_UNAVAILABLE)}function releaseSkillUsageLock(handle){try{_internals59.unlinkSync(handle.lockPath)}catch{}}function emptyCounters(){let counters={};for(let key of SKILL_USAGE_COUNTER_KEYS)counters[key]=0;return counters}function emptyCoverage(){return{complete:!0,oldestRetained:null,newestRetained:null,entriesDropped:0,skillsDropped:0,floorPerSkill:SKILL_USAGE_LIMITS.floorPerSkill}}function createPendingDocument(){return{version:SKILL_USAGE_LIMITS.version,migrated:!1,records:[],counters:emptyCounters(),coverage:emptyCoverage()}}function parseRecord(raw){if(typeof raw!=="object"||raw===null)return null;let r=raw;if(typeof r.id!=="string"||r.id.length===0)return null;if(typeof r.skillPath!=="string"||r.skillPath.length===0)return null;if(r.verdict!=="compliant"&&r.verdict!=="violated")return null;if(typeof r.timestamp!=="string")return null;let state2=r.state==="in_flight"||r.state==="uncertain"?r.state:"pending";return{id:r.id,skillPath:r.skillPath,verdict:r.verdict,timestamp:r.timestamp,enqueuedAt:typeof r.enqueuedAt==="string"?r.enqueuedAt:r.timestamp,state:state2,attempts:typeof r.attempts==="number"&&r.attempts>=0?r.attempts:0,...typeof r.inFlightAt==="string"&&{inFlightAt:r.inFlightAt}}}function parsePendingDocument(raw){let parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)throw Error("sidecar root is not an object");if(!Array.isArray(parsed.records))throw Error("sidecar `records` is not an array");let doc2=createPendingDocument();doc2.version=typeof parsed.version==="number"?parsed.version:SKILL_USAGE_LIMITS.version,doc2.migrated=parsed.migrated===!0;let seen=new Set;for(let rawRecord of parsed.records){let record2=parseRecord(rawRecord);if(!record2)continue;if(seen.has(record2.id))continue;seen.add(record2.id),doc2.records.push(record2)}let counters=parsed.counters;if(counters&&typeof counters==="object")for(let key of SKILL_USAGE_COUNTER_KEYS){let value=counters[key];if(typeof value==="number"&&Number.isFinite(value)&&value>=0)doc2.counters[key]=value}let coverage=parsed.coverage;if(coverage&&typeof coverage==="object")doc2.coverage={complete:coverage.complete!==!1,oldestRetained:typeof coverage.oldestRetained==="string"?coverage.oldestRetained:null,newestRetained:typeof coverage.newestRetained==="string"?coverage.newestRetained:null,entriesDropped:typeof coverage.entriesDropped==="number"?coverage.entriesDropped:0,skillsDropped:typeof coverage.skillsDropped==="number"?coverage.skillsDropped:0,floorPerSkill:SKILL_USAGE_LIMITS.floorPerSkill};return doc2}function quarantinePendingDocument(directory,resolved){let stamp=new Date(_internals59.now()).toISOString().replace(/[:.]/g,"-");try{let target=validateSwarmPath(directory,`skill-usage-pending.corrupt-${stamp}.json`);return _internals59.renameSync(resolved,target),target}catch(err){log("[skill-usage-pending] quarantine failed (continuing with a fresh queue):",err instanceof Error?err.message:String(err));return}}function loadPendingDocument(directory){return loadPendingDocumentAt(directory,resolvePendingPath(directory))}function loadPendingDocumentAt(directory,resolved){let size,fingerprint;try{({size,fingerprint}=statFingerprint(resolved))}catch{return{doc:createPendingDocument(),quarantined:!1}}if(size<=SKILL_USAGE_LIMITS.readMaxBytes)try{let cached2=fingerprint===null?void 0:cacheGet(_documentCache,resolved),raw=cached2!==void 0&&cached2.fingerprint===fingerprint?cached2.text:_internals59.readFileSync(resolved,"utf-8"),doc3=parsePendingDocument(raw);if(fingerprint!==null&&raw.length<=MAX_CACHED_DOCUMENT_BYTES)cacheSet(_documentCache,resolved,{fingerprint,text:raw});return{doc:doc3,quarantined:!1}}catch(err){log("[skill-usage-pending] corrupt sidecar — quarantining:",err instanceof Error?err.message:String(err))}_documentCache.delete(resolved);let quarantinePath=quarantinePendingDocument(directory,resolved),doc2=createPendingDocument();return doc2.counters.corrupt+=1,{doc:doc2,quarantined:!0,...quarantinePath!==void 0&&{quarantinePath}}}function savePendingDocument(directory,doc2){savePendingDocumentAt(directory,resolvePendingPath(directory),doc2)}function savePendingDocumentAt(directory,resolved,doc2){ensureSwarmDir2(resolved),doc2.version=SKILL_USAGE_LIMITS.version,doc2.coverage.floorPerSkill=SKILL_USAGE_LIMITS.floorPerSkill;let tmpPath=siblingSwarmPath(resolved,`skill-usage-pending-${process.pid}-${_internals59.now()}.tmp`),serialized2=JSON.stringify(doc2);try{_internals59.writeFileSync(tmpPath,serialized2,"utf-8"),_internals59.renameSync(tmpPath,resolved)}catch(err){try{if(_internals59.existsSync(tmpPath))_internals59.unlinkSync(tmpPath)}catch{}throw _documentCache.delete(resolved),err instanceof Error?err:Error(String(err))}_coverageCache.delete(resolved);try{let{fingerprint}=statFingerprint(resolved);if(fingerprint!==null&&serialized2.length<=MAX_CACHED_DOCUMENT_BYTES)cacheSet(_documentCache,resolved,{fingerprint,text:serialized2});else _documentCache.delete(resolved)}catch{_documentCache.delete(resolved)}_pressureDirectory=directory,refreshPressureFromCounts(doc2.records.length,serialized2.length)}function readPendingManifest(directory){let resolved;try{resolved=resolvePendingPath(directory)}catch{return{coverage:emptyCoverage(),migrated:!1}}let fingerprint;try{if(!_internals59.existsSync(resolved))return{coverage:emptyCoverage(),migrated:!1};({fingerprint}=statFingerprint(resolved))}catch{return{coverage:emptyCoverage(),migrated:!1}}if(fingerprint!==null){let cached2=cacheGet(_coverageCache,resolved);if(cached2&&cached2.fingerprint===fingerprint)return{coverage:cached2.coverage,migrated:cached2.migrated}}try{let cachedText=fingerprint===null?void 0:cacheGet(_documentCache,resolved),raw=cachedText!==void 0&&cachedText.fingerprint===fingerprint?cachedText.text:_internals59.readFileSync(resolved,"utf-8"),doc2=parsePendingDocument(raw);if(fingerprint!==null)cacheSet(_coverageCache,resolved,{fingerprint,coverage:doc2.coverage,migrated:doc2.migrated});return{coverage:doc2.coverage,migrated:doc2.migrated}}catch{return{coverage:emptyCoverage(),migrated:!1}}}function isSkillWindowTrustworthy(coverage,retainedCount){if(coverage.complete)return!0;if(retainedCount<SKILL_USAGE_LIMITS.curatorMinSample)return!1;let floor=coverage.floorPerSkill>0?coverage.floorPerSkill:SKILL_USAGE_LIMITS.floorPerSkill;return retainedCount>=floor}function recordBytes(record2){return JSON.stringify(record2).length+1}function queueByteSize(doc2){let total=0;for(let record2 of doc2.records)total+=recordBytes(record2);return total}function ageMsOf(record2,nowMs){let parsed=Date.parse(record2.enqueuedAt);if(Number.isNaN(parsed))return 0;return nowMs-parsed}function evictionRank(record2){if(record2.state==="uncertain")return 0;if(record2.state==="pending")return 1;return 2}function enforceQueueBounds(doc2,nowMs=_internals59.now()){let survivors=[];for(let record2 of doc2.records){if(ageMsOf(record2,nowMs)>SKILL_USAGE_LIMITS.maxAgeMs){if(record2.state==="uncertain")doc2.counters.uncertain_expired+=1;else doc2.counters.dropped+=1;continue}survivors.push(record2)}doc2.records=survivors;let bytes=queueByteSize(doc2),count=doc2.records.length,overBudget=()=>count>SKILL_USAGE_LIMITS.queueMaxRecords||bytes>SKILL_USAGE_LIMITS.queueMaxBytes;if(overBudget()){let order=doc2.records.map((record2,index)=>({record:record2,index})).sort((a,b)=>{let rank=evictionRank(a.record)-evictionRank(b.record);if(rank!==0)return rank;if(a.record.enqueuedAt!==b.record.enqueuedAt)return a.record.enqueuedAt<b.record.enqueuedAt?-1:1;return a.index-b.index}),evicted=new Set;for(let{record:record2}of order){if(!overBudget())break;if(evicted.add(record2),count-=1,bytes-=recordBytes(record2),record2.state==="uncertain")doc2.counters.uncertain_expired+=1;else doc2.counters.pending_evicted+=1,doc2.counters.pressure+=1}if(evicted.size>0)doc2.records=doc2.records.filter((record2)=>!evicted.has(record2))}refreshPressureFromCounts(doc2.records.length,bytes)}function refreshPressureFromCounts(records,bytes){_pressure=records>=SKILL_USAGE_LIMITS.queueMaxRecords||bytes>=SKILL_USAGE_LIMITS.queueMaxBytes,_pressureCheckedAt=_internals59.now()}function isSkillUsageQueueUnderPressure(directory){let now=_internals59.now();if(_pressureDirectory===directory&&now-_pressureCheckedAt<PRESSURE_CACHE_MS)return _pressure;_pressureDirectory=directory,_pressureCheckedAt=now;try{let resolved=resolvePendingPath(directory);if(!_internals59.existsSync(resolved))return _pressure=!1,!1;_pressure=_internals59.statSync(resolved).size>=SKILL_USAGE_LIMITS.queueMaxBytes}catch{_pressure=!1}return _pressure}function mergePendingRecords(doc2,incoming,nowIso2){let known=new Set(doc2.records.map((r)=>r.id)),added=0;for(let input of incoming){if(known.has(input.id))continue;known.add(input.id),doc2.records.push({id:input.id,skillPath:input.skillPath,verdict:input.verdict,timestamp:input.timestamp,enqueuedAt:nowIso2,state:"pending",attempts:0}),added+=1}return doc2.counters.accepted+=added,added}function enqueueSkillUsageFeedback(directory,input){let resolved;try{resolved=resolvePendingPath(directory)}catch{throw Error(SKILL_USAGE_LOCK_UNAVAILABLE)}let handle=acquireSkillUsageLockOrThrowAt(siblingSwarmPath(resolved,SKILL_USAGE_LOCK_BASENAME));try{let{doc:doc2}=loadPendingDocumentAt(directory,resolved);mergePendingRecords(doc2,[input],new Date(_internals59.now()).toISOString()),enforceQueueBounds(doc2),savePendingDocumentAt(directory,resolved,doc2)}finally{releaseSkillUsageLock(handle)}}function resolveStaleInFlight(doc2,nowMs=_internals59.now()){let resolved=0;for(let record2 of doc2.records){if(record2.state!=="in_flight")continue;let claimedAt=record2.inFlightAt?Date.parse(record2.inFlightAt):NaN,age=Number.isNaN(claimedAt)?Number.POSITIVE_INFINITY:nowMs-claimedAt;if(Math.abs(age)<=SKILL_USAGE_LOCK_STALE_MS)continue;record2.state="uncertain",record2.inFlightAt=void 0,resolved+=1}return resolved}function selectConsumableRecords(doc2,sinceTimestamp){return doc2.records.filter((record2)=>{if(record2.state!=="pending")return!1;if(sinceTimestamp!==void 0&&record2.timestamp<=sinceTimestamp)return!1;return!0})}function markRecordsInFlight(doc2,ids,nowIso2=new Date(_internals59.now()).toISOString()){let wanted=new Set(ids);for(let record2 of doc2.records){if(!wanted.has(record2.id))continue;record2.state="in_flight",record2.inFlightAt=nowIso2}}function dequeueRecords(doc2,ids){let wanted=new Set(ids),before=doc2.records.length;return doc2.records=doc2.records.filter((record2)=>!wanted.has(record2.id)),before-doc2.records.length}function applyTerminalOutcome(doc2,ids,outcome){let removed=dequeueRecords(doc2,ids);return doc2.counters[outcome]+=removed,removed}function retainWithRetry(doc2,ids){let wanted=new Set(ids),retried=[],unrecoverable=[];for(let record2 of doc2.records){if(!wanted.has(record2.id))continue;if(record2.attempts+=1,record2.state="pending",record2.inFlightAt=void 0,record2.attempts>=SKILL_USAGE_LIMITS.maxAttempts)unrecoverable.push(record2.id);else retried.push(record2.id)}if(doc2.counters.bump_retry+=retried.length,unrecoverable.length>0)applyTerminalOutcome(doc2,unrecoverable,"bump_unrecoverable");return{retried,unrecoverable}}function buildSkillUsageHealthPayload(doc2,trigger,gauges){let pendingRetained=0,uncertainRetained=0;for(let record2 of doc2.records)if(record2.state==="uncertain")uncertainRetained+=1;else pendingRetained+=1;return{trigger,accepted:doc2.counters.accepted,compacted:doc2.counters.compacted,dropped:doc2.counters.dropped,skills_dropped:doc2.counters.skills_dropped,corrupt:doc2.counters.corrupt,pending_retained:pendingRetained,uncertain_retained:uncertainRetained,uncertain_expired:doc2.counters.uncertain_expired,pending_evicted:doc2.counters.pending_evicted,no_source_knowledge:doc2.counters.no_source_knowledge,no_matching_knowledge:doc2.counters.no_matching_knowledge,bump_retry:doc2.counters.bump_retry,bump_unrecoverable:doc2.counters.bump_unrecoverable,bump_applied_zero:doc2.counters.bump_applied_zero,pressure:doc2.counters.pressure,curator_skipped:doc2.counters.curator_skipped,bytes:gauges.bytes,limit_bytes:gauges.limitBytes,oldest_timestamp:doc2.coverage.oldestRetained,newest_timestamp:doc2.coverage.newestRetained,coverage:doc2.coverage.complete}}function emitSkillUsageHealth(doc2,trigger,gauges,directory){try{let healthPayload=buildSkillUsageHealthPayload(doc2,trigger,gauges);if(_internals59.emitHealth(healthPayload),directory)observeStoreHealth({directory,kind:"skill_usage_health",payload:healthPayload})}catch(err){log("[skill-usage-pending] health emit failed (best-effort):",err instanceof Error?err.message:String(err))}}var SKILL_USAGE_LIMITS,SKILL_USAGE_LOCK_STALE_MS=300000,ENQUEUE_LOCK_ATTEMPTS=5,ENQUEUE_LOCK_RETRY_MS=10,SKILL_USAGE_LOCK_UNAVAILABLE="skill-usage pending queue lock unavailable; refusing to append an unqueued actionable verdict",PRESSURE_CACHE_MS=5000,SKILL_USAGE_COUNTER_KEYS,_internals59,_pressure=!1,_pressureCheckedAt=0,_pressureDirectory=null,MAX_CACHED_PROJECTS=8,MAX_CACHED_DOCUMENT_BYTES,_coverageCache,_documentCache,SKILL_USAGE_LOCK_BASENAME="skill-usage.lock";var init_skill_usage_pending=__esm(()=>{init_learning_health();init_telemetry();init_logger();init_utils2();SKILL_USAGE_LIMITS={version:1,maxEntries:5000,maxBytes:1572864,maxAgeMs:7776000000,floorPerSkill:20,curatorMinSample:10,readMaxBytes:1677722,migrationChunkBytes:262144,headerMaxBytes:8192,queueMaxRecords:5000,queueMaxBytes:524288,maxAttempts:5,checkInterval:50},SKILL_USAGE_COUNTER_KEYS=["accepted","compacted","dropped","skills_dropped","corrupt","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped"],_internals59={existsSync:fs39.existsSync.bind(fs39),readFileSync:fs39.readFileSync.bind(fs39),writeFileSync:fs39.writeFileSync.bind(fs39),renameSync:fs39.renameSync.bind(fs39),mkdirSync:fs39.mkdirSync.bind(fs39),statSync:fs39.statSync.bind(fs39),openSync:fs39.openSync.bind(fs39),closeSync:fs39.closeSync.bind(fs39),unlinkSync:fs39.unlinkSync.bind(fs39),now:()=>Date.now(),emitHealth:(payload)=>{telemetry.skillUsageHealth(payload)}},MAX_CACHED_DOCUMENT_BYTES=SKILL_USAGE_LIMITS.queueMaxBytes;_coverageCache=new Map,_documentCache=new Map});import*as crypto7 from"node:crypto";import*as fs40 from"node:fs";import*as path66 from"node:path";import{StringDecoder}from"node:string_decoder";function resolveLogPath(directory){return validateSwarmPath(directory,"skill-usage.jsonl")}function normalizeComplianceVerdict(verdict){return verdict==="violation"?"violated":verdict}function isActionableVerdict(verdict){return verdict==="compliant"||verdict==="violated"}function normalizeSkillUsageEntry(raw){let entry=raw;return{...entry,complianceVerdict:normalizeComplianceVerdict(entry.complianceVerdict)}}function legacySkillUsageId(entry){let stable=JSON.stringify({skillPath:entry.skillPath,agentName:entry.agentName,taskID:entry.taskID,timestamp:entry.timestamp,complianceVerdict:entry.complianceVerdict,sessionID:entry.sessionID,skillVersion:entry.skillVersion});return`legacy:${crypto7.createHash("sha256").update(stable).digest("hex")}`}function parseSkillUsageEntry(raw){let entry=raw;if(entry.type==="feedback_applied")return null;if(typeof entry.skillPath!=="string"||typeof entry.agentName!=="string"||typeof entry.taskID!=="string"||typeof entry.timestamp!=="string"||typeof entry.complianceVerdict!=="string"||typeof entry.sessionID!=="string")return null;return normalizeSkillUsageEntry({...entry,id:typeof entry.id==="string"?entry.id:legacySkillUsageId(entry)})}function parseFeedbackMarker(raw){let marker=raw;if(marker.type!=="feedback_applied")return null;if(typeof marker.timestamp!=="string")return null;if(!Array.isArray(marker.processedEntryIds))return null;let processedEntryIds=marker.processedEntryIds.filter((id)=>typeof id==="string"&&id.length>0);return{type:"feedback_applied",timestamp:marker.timestamp,processedEntryIds}}function appendFeedbackAppliedMarker(directory,processedEntryIds){if(processedEntryIds.length===0)return;let resolved=resolveLogPath(directory),dir=path66.dirname(resolved);if(!_internals60.existsSync(dir))_internals60.mkdirSync(dir,{recursive:!0});let marker={type:"feedback_applied",timestamp:new Date().toISOString(),processedEntryIds:[...new Set(processedEntryIds)]};_internals60.appendFileSync(resolved,`${JSON.stringify(marker)}
934
935
  `,"utf-8")}function streamLogLines(filePath,chunkBytes,onLine,onOverlongLine){let size=Math.max(1024,Math.floor(chunkBytes)),fd=_internals60.openSync(filePath,"r");try{let buf=Buffer.alloc(size),decoder=new StringDecoder("utf8"),carry="",position=0;for(;;){let bytesRead=_internals60.readSync(fd,buf,0,size,position);if(!bytesRead||bytesRead<=0)break;position+=bytesRead;let parts=(carry+decoder.write(buf.subarray(0,bytesRead))).split(`
935
936
  `);carry=parts.pop()??"";for(let part of parts){let trimmed=part.trim();if(trimmed)onLine(trimmed)}if(carry.length>size*4)carry="",onOverlongLine?.()}let tail=(carry+decoder.end()).trim();if(tail)onLine(tail)}finally{_internals60.closeSync(fd)}}function compactionTrigger(directory){if(_suppressedOptionalAppends>0)return"pressure";if(_appendsSinceCompaction>=SKILL_USAGE_LIMITS.maxEntries)return"append-count";if(!_internals60.readPendingManifest(directory).migrated)return"unmigrated";try{let resolved=resolveLogPath(directory);if(!_internals60.existsSync(resolved))return null;return _internals60.statSync(resolved).size>SKILL_USAGE_LIMITS.maxBytes?"bytes":null}catch{return"bytes"}}function maybeRunMaintenance(directory){let shouldRun=_appendCount2%SKILL_USAGE_LIMITS.checkInterval===0;if(_appendCount2+=1,_appendsSinceCompaction+=1,!shouldRun)return;try{let trigger=compactionTrigger(directory);if(trigger===null)return;if(trigger!=="unmigrated")_appendsSinceCompaction=0;_internals60.pruneSkillUsageLog(directory,SKILL_USAGE_LOG_MAX_ENTRIES_PER_SKILL)}catch(err){log("[skill-usage-log] maintenance pass failed (fail-open):",err instanceof Error?err.message:String(err))}}function appendSkillUsageEntry(directory,entry){let{skillPath,agentName,taskID,timestamp,complianceVerdict,sessionID,reviewerNotes,skillVersion}=entry;if(!skillPath||typeof skillPath!=="string")throw Error("skillPath is required and must be a non-empty string");if(/\.\.[/\\]/.test(skillPath))throw Error("skillPath contains path traversal sequence");if(!agentName||typeof agentName!=="string")throw Error("agentName is required and must be a non-empty string");if(!taskID||typeof taskID!=="string")throw Error("taskID is required and must be a non-empty string");if(!timestamp||typeof timestamp!=="string")throw Error("timestamp is required and must be a non-empty string");if(!complianceVerdict||typeof complianceVerdict!=="string")throw Error("complianceVerdict is required and must be a non-empty string");if(!sessionID||typeof sessionID!=="string")throw Error("sessionID is required and must be a non-empty string");let resolved=validateSwarmPath(directory,"skill-usage.jsonl"),dir=path66.dirname(resolved);if(!_internals60.existsSync(dir))_internals60.mkdirSync(dir,{recursive:!0});let verdict=normalizeComplianceVerdict(complianceVerdict),actionable=isActionableVerdict(verdict),canonicalPath=canonicalSkillPath(skillPath);if(!actionable&&_internals60.isQueueUnderPressure(directory)){_suppressedOptionalAppends+=1;return}let fullEntry={id:_internals60.generateId(),skillPath:canonicalPath,agentName,taskID,timestamp,complianceVerdict:verdict,sessionID,...reviewerNotes!==void 0&&{reviewerNotes},...skillVersion!==void 0&&{skillVersion}};if(actionable)_internals60.enqueueSkillUsageFeedback(directory,{id:fullEntry.id,skillPath:canonicalPath,verdict,timestamp});_internals60.appendFileSync(resolved,`${JSON.stringify(fullEntry)}
936
937
  `,"utf-8"),maybeRunMaintenance(directory)}function readLogSlice(directory){let resolved=resolveLogPath(directory);if(!_internals60.existsSync(resolved))return{text:"",truncated:!1};let size;try{size=_internals60.statSync(resolved).size}catch{return{text:"",truncated:!1}}if(size<=SKILL_USAGE_LIMITS.readMaxBytes)try{return{text:_internals60.readFileSync(resolved,"utf-8"),truncated:!1}}catch{return{text:"",truncated:!1}}try{let start=size-SKILL_USAGE_LIMITS.readMaxBytes,fd=_internals60.openSync(resolved,"r");try{let buf=Buffer.alloc(size-start);_internals60.readSync(fd,buf,0,buf.length,start);let content=buf.toString("utf-8"),firstNewline=content.indexOf(`
@@ -1226,9 +1227,9 @@ ${expectedBodyBlock}
1226
1227
  `).slice(0,3).join(`
1227
1228
  `),headingMatch=/^\s*(APPROVED|NEEDS_REVISION|REJECTED)\s*$/im.exec(nextLines);if(headingMatch)return headingMatch[1].toUpperCase()}let lines=text.split(`
1228
1229
  `),tailStart=Math.max(0,lines.length-6),inFence=!1;for(let i=0;i<lines.length;i++){if(/^\s*(?:`{3,})/.test(lines[i]))inFence=!inFence;if(i<tailStart)continue;if(inFence)continue;let line=lines[i];if(line.includes("|"))continue;let bare=/^\s*(APPROVED|NEEDS_REVISION|REJECTED)\s*$/i.exec(line);if(bare)return bare[1].toUpperCase()}return null}function taskLooksLikePlanCritic(args2){let text=[args2.prompt,args2.task,args2.description,args2.message,args2.input].filter((value)=>typeof value==="string").join(`
1229
- `).toLowerCase();if(!text)return!1;return PLAN_CRITIC_TASK_SIGNALS.some((signal)=>text.includes(signal))}async function isPlanCriticApproved(directory){try{let plan=await loadPlanJsonOnly(directory);if(!plan)return!1;let planId=derivePlanId(plan),approved=await loadLastPlanCriticApprovedSnapshot(directory,planId);if(!approved)return!1;if(approved.approval?.verdict!=="APPROVED"||approved.approval?.source!=="plan_critic_gate")return!1;if(approved.payloadHash!==computePlanStructureHash(plan))return!1;return!0}catch{return!1}}async function assertPlanCriticApprovedForExecution(directory,plan){if(!plan)return;let planId=derivePlanId(plan),approved=await loadLastPlanCriticApprovedSnapshot(directory,planId);if(!approved)throw Error("PLAN_CRITIC_GATE_VIOLATION: Cannot delegate to coder before plan critic approval. Delegate to critic in MODE: CRITIC-GATE and require VERDICT: APPROVED before EXECUTE. If the critic already returned APPROVED but the snapshot was not recorded "+"(format/signal mismatch — issue #2012), call approve_plan_critic with a reason, "+"or run /swarm approve-plan-critic <reason>, to record a manual approval.");if(approved.approval?.verdict!=="APPROVED"||approved.approval?.source!=="plan_critic_gate")throw Error("PLAN_CRITIC_GATE_VIOLATION: Latest approved-plan snapshot does not contain plan critic VERDICT: APPROVED evidence. Re-run MODE: CRITIC-GATE and wait for explicit approval before coder execution. If the critic already returned APPROVED but the snapshot was not recorded (issue #2012), call approve_plan_critic or run /swarm approve-plan-critic.");if(approved.payloadHash!==computePlanStructureHash(plan))throw Error("PLAN_CRITIC_GATE_VIOLATION: Current plan differs from the last critic-approved snapshot. Re-run MODE: CRITIC-GATE after plan changes before delegating to coder. If re-review is not possible, call approve_plan_critic or run /swarm approve-plan-critic to record a fresh manual approval for the current plan.")}function resolvePlanCriticPolicyForExecution(directory,plan,sessionOverrides={}){try{let profile=getProfileForIdentity(directory,{swarm:plan.swarm,title:plan.title});if(!profile)return{required:DEFAULT_QA_GATES.critic_pre_plan,source:"default_missing_profile"};return{required:getEffectiveGates(profile,sessionOverrides).critic_pre_plan,source:sessionOverrides.critic_pre_plan===!0&&profile.gates.critic_pre_plan===!1?"session_ratchet":"persisted_profile"}}catch(error49){return warn(`[delegation-gate] failed to resolve critic_pre_plan profile; enforcing the gate: ${error49 instanceof Error?error49.message:String(error49)}`),{required:!0,source:"corrupt_profile_conservative"}}}async function recordPlanCriticApprovalSnapshotIfApplicable(directory,input,args2,output){if((typeof args2.subagent_type==="string"?stripKnownSwarmPrefix(args2.subagent_type):null)!=="critic")return;if(!taskLooksLikePlanCritic(args2))return;if(extractPlanCriticVerdict(output)!=="APPROVED")return;let plan=await loadPlanJsonOnly(directory);if(!plan)for(let attempt=0;attempt<2&&!plan;attempt++)await new Promise((resolve47)=>setTimeout(resolve47,150)),plan=await loadPlanJsonOnly(directory);if(!plan){warn("[delegation-gate] plan critic APPROVED verdict could not be recorded: plan.json not readable after retry. The critic_pre_plan gate will block coder delegation until a snapshot exists. Call approve_plan_critic (or /swarm approve-plan-critic) with a reason to record a manual approval if the critic genuinely approved.");return}await takeSnapshotEvent(directory,plan,{source:"critic_approved",approvalMetadata:{verdict:"APPROVED",source:"plan_critic_gate",session_id:input.sessionID,call_id:input.callID,approved_at:new Date().toISOString()},payloadHashOverride:computePlanStructureHash(plan)})}async function forceRecordPlanCriticApproval(directory,sessionID,options={}){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("NOT_AUTHORIZED: approve_plan_critic requires an active architect session. The plan-critic gate escape hatch is an architect-only escalation; a coder/reviewer cannot self-unblock. Run /swarm approve-plan-critic from an architect context, or ask the user to run it.");let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path88.join(directory,".swarm","plan.json");if(fs54.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recording a plan-critic approval.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot record a plan-critic "+"approval for a non-existent plan. Save a plan first.")}let planId=derivePlanId(plan),recordedAt=new Date().toISOString(),sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?options.reason.trim().slice(0,500):void 0,userConfirmed=options.userConfirmed===!0;await takeSnapshotEvent(directory,plan,{source:"critic_approved",approvalMetadata:{verdict:"APPROVED",source:"plan_critic_gate",method:"manual_override",reason:sanitizedReason,user_confirmed:userConfirmed,session_id:sessionID,approved_at:recordedAt},payloadHashOverride:computePlanStructureHash(plan)});try{appendCoreEventSync(directory,{type:"plan_critic_gate_manual_approval",timestamp:recordedAt,sessionID,plan_id:planId,user_confirmed:userConfirmed,...sanitizedReason?{reason:sanitizedReason}:{}})}catch(err){warn(`[delegation-gate] plan_critic_gate_manual_approval audit event write failed: ${err instanceof Error?err.message:String(err)}`)}return{planId,recordedAt,...sanitizedReason?{reason:sanitizedReason}:{},userConfirmed}}async function forceRecordRetrySoundingBoardApproval(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("APPROVE_RETRY_SOUNDING_BOARD_ARCHITECT_REQUIRED: approve_retry_sounding_board requires an active architect session. The coder retry circuit-breaker escape hatch is architect-only; a coder/reviewer cannot self-unblock.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('APPROVE_RETRY_UNKNOWN_TASK: approve_retry_sounding_board requires the exact plan task id (e.g. "2.1").');let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path88.join(directory,".swarm","plan.json");if(fs54.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recording a retry sounding-board approval.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot record a retry "+"sounding-board approval without a plan. Save a plan first.")}if(!new Set(plan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))).has(taskId))throw Error(`APPROVE_RETRY_UNKNOWN_TASK: task ${taskId} is not in the current plan. Refusing to record evidence for a foreign task id.`);let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),evidence=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence);if(!evidence||!workflow.authoritative)throw Error(`APPROVE_RETRY_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no retry state to recover.`);let prior;try{prior=readCoderRetryEscalations(directory,taskId,workflow.retryEpoch)}catch(error49){if(error49 instanceof Error&&error49.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("APPROVE_RETRY_AUDIT_INDEX_UNREADABLE: the retry audit authority index is unreadable, so the prior sounding_board_consultation cannot be verified. Repair the events store (see /swarm doctor) and retry.");throw error49}if(!prior.has("sounding_board_consultation"))throw Error(`APPROVE_RETRY_CONSULTATION_REQUIRED: task ${taskId} has no durable sounding_board_consultation escalation for retry epoch ${workflow.retryEpoch}. `+"Dispatch critic_sounding_board first — this tool records an obtained APPROVED verdict, it cannot substitute for the consultation.");let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?options.reason.trim().slice(0,500):void 0,recordedAt=new Date().toISOString(),transitionId=`retry-sb-manual:${sessionID}:epoch${workflow.retryEpoch}`;await recordGateEvidence2(directory,taskId,"critic_sounding_board",sessionID,!1,{transitionId,expectedGeneration:workflow.generation});let auditEventRecorded=!0;try{appendCoreEventSync(directory,{type:"coder_retry_circuit_breaker",timestamp:recordedAt,taskId,generation:workflow.generation,retryEpoch:workflow.retryEpoch,rejectionCount:workflow.retryCount,rejectionHistory:[...workflow.retryHistory],phase:Number(taskId.split(".")[0])||0,action:"sounding_board_manual_approval",...sanitizedReason?{reason:sanitizedReason}:{}},{dedupeOnAuthorityKey:!0})}catch(err){auditEventRecorded=!1,warn(`[delegation-gate] sounding_board_manual_approval audit event write failed: ${err instanceof Error?err.message:String(err)}`)}return{taskId,generation:workflow.generation,retryEpoch:workflow.retryEpoch,recordedAt,auditEventRecorded}}function isTaskCompletedForParallelGuidance(task){let status=task.status??"pending";return status==="completed"||status==="closed"}function getPlanTaskDeclaredFiles(plan,taskId){if(!plan||!taskId)return null;for(let phase of plan.phases){let task=phase.tasks.find((candidate)=>candidate.id===taskId);if(task)return[...task.files_touched]}return null}function describeCoderScopeFailure(args2,planTaskIdContext){if(planTaskIdContext.status==="over_limit")return`loaded plan task context exceeds the shared bounded limit (${TASK_ID_RESOLUTION_LIMITS.maxKnownIds} task ids); task-id resolution fails closed instead of guessing. Provide an explicit structured scope declaration or narrow the plan context before delegating.`;let resolution=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(planTaskIdContext)}),knownPlanTaskIds=planTaskIdContext.status==="available"?planTaskIdContext.taskIds:void 0,knownSummary=knownPlanTaskIds?[...knownPlanTaskIds].sort().join(", ")||"(none)":"(none)",rawTaskId=args2.task_id??args2.taskId,explicitFieldShape=typeof rawTaskId==="string"&&rawTaskId.trim().length>0?`"${rawTaskId.trim().slice(0,40)}" (non-plan-shaped; treated as runtime session id and ignored — falling through to text extraction)`:"absent",candidateTextFields=[args2.prompt,args2.description,args2.task,args2.input],taskLineCandidates=new Set,taskLineDetected=!1;for(let field of candidateTextFields){if(typeof field!=="string")continue;let taskLine=extractTaskLine(field);if(!taskLine)continue;taskLineDetected=!0;for(let m of taskLine.matchAll(/\b(\d+\.\d+(?:\.\d+)*)\b/g))if(knownPlanTaskIds?.has(m[1]))taskLineCandidates.add(m[1])}let textCandidates=new Set;for(let field of candidateTextFields){if(typeof field!=="string")continue;for(let m of field.matchAll(/\b(\d+\.\d+(?:\.\d+)*)\b/g))if(knownPlanTaskIds?.has(m[1]))textCandidates.add(m[1])}if(resolution.status==="invalid"&&typeof rawTaskId==="string"&&isStrictTaskId(rawTaskId.trim()))return`explicit task_id "${rawTaskId.trim().slice(0,40)}" is plan-shaped but does not resolve safely against the loaded plan, so resolution fails closed before prompt fallback. Known plan task ids: ${knownSummary}.`;if(resolution.status==="over_limit")return`task-id resolution exceeded a bounded input limit (${resolution.input}); provide exactly one concise TASK: <N.M> line or a valid explicit plan task_id. Known plan task ids: ${knownSummary}.`;if(taskLineCandidates.size>1)return`multiple candidate task ids found in TASK: line: [${[...taskLineCandidates].sort().join(", ")}]; provide exactly one unambiguous TASK: <id> line. Known plan task ids: ${knownSummary}.`;if(textCandidates.size>1)return`multiple candidate task ids found in prompt text: [${[...textCandidates].sort().join(", ")}]; provide exactly one unambiguous TASK: <id> line. Known plan task ids: ${knownSummary}.`;return`no plan task id could be resolved. Include a TASK: <N.M> line or plan-task-shaped task_id arg. Explicit task_id field: ${explicitFieldShape}. TASK: line detected: ${taskLineDetected?"yes":"no"}. Known plan task ids: ${knownSummary}.`}function stripSingleTrailingAnnotationSuffix(value){let suffixMatch=value.match(/(?:\s+\([^()]*\))+$/);if(!suffixMatch)return value;let suffix=suffixMatch[0];if((suffix.match(/\([^()]*\)/g)??[]).length!==1)return null;return value.slice(0,-suffix.length).trimEnd()||null}function normalizeFileDirectiveValue(rawValue){let value=rawValue.trim();if(!value)return null;let quote=value[0];if(quote==='"'||quote==="'"){let closingQuoteIndex=value.indexOf(quote,1);if(closingQuoteIndex===-1)return null;let filePath=value.slice(1,closingQuoteIndex);if(!filePath)return null;let suffix=value.slice(closingQuoteIndex+1);if(suffix.length>0&&!/^\s+\([^()]*\)\s*$/.test(suffix))return null;return filePath}let normalized=stripSingleTrailingAnnotationSuffix(value);if(!normalized||/[,;|]/.test(normalized))return null;return normalized}function extractTaskFileDirectives(args2,mode){let files=new Set,present=!1;for(let field of[args2.prompt,args2.description,args2.task,args2.input]){if(typeof field!=="string")continue;for(let line of field.split(/\r?\n/)){if(!/^\s*FILE\s*:/i.test(line))continue;present=!0;let value=normalizeFileDirectiveValue(line.replace(/^\s*FILE\s*:\s*/i,""));if(!value){if(mode==="observe")continue;return{present:!0,files:null}}files.add(value)}}return{present,files:present&&files.size>0?[...files]:null}}function parsePerTaskVerdicts(outputText2){let verdicts=new Map,errors3=[],reviewedPattern=/^\[REVIEWED\]\s*\|\s*(?:task-)?(\d+\.\d+(?:\.\d+)*)\s*\|\s*(APPROVED|REJECTED|CONCERNS)\s*\|?/im,testedPattern=/^\[TESTED\]\s*\|\s*(?:task-)?(\d+\.\d+(?:\.\d+)*)\s*\|\s*(PASS|FAIL|SKIPPED)\s*\|?/im;for(let line of outputText2.split(/\r?\n/)){let trimmed=line.trim(),match=reviewedPattern.exec(trimmed);if(match){let taskId=match[1],verdict=match[2];if(isStrictTaskId(taskId)){let existing=verdicts.get(taskId);if(existing){if(existing.verdict!==verdict||existing.kind!=="REVIEWED")errors3.push(`STAGE_B_VERDICT_CONFLICT: task ${taskId} has conflicting verdicts: ${existing.kind}/${existing.verdict} vs REVIEWED/${verdict}`)}else verdicts.set(taskId,{verdict,kind:"REVIEWED"})}continue}if(match=testedPattern.exec(trimmed),match){let taskId=match[1],verdict=match[2];if(isStrictTaskId(taskId)){let existing=verdicts.get(taskId);if(existing){if(existing.verdict!==verdict||existing.kind!=="TESTED")errors3.push(`STAGE_B_VERDICT_CONFLICT: task ${taskId} has conflicting verdicts: ${existing.kind}/${existing.verdict} vs TESTED/${verdict}`)}else verdicts.set(taskId,{verdict,kind:"TESTED"})}}}return{verdicts,errors:errors3}}async function findTaskAwaitingCompletion(directory,requestedTaskId){if(!directory)return null;let plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{return null}if(!plan)return null;let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),tasks=plan.phases.flatMap((phase)=>phase.tasks),orderedTasks=requestedTaskId?[...tasks.filter((task)=>task.id===requestedTaskId),...tasks.filter((task)=>task.id!==requestedTaskId)]:tasks;for(let task of orderedTasks){let taskId=task.id,evidence=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence),councilEvidence=evidence?.gates.council,awaitsQaCompletion=workflow.authoritative&&workflow.state==="tests_run",awaitsCouncilCompletion=workflow.authoritative&&workflow.state==="pre_check_passed"&&councilEvidence?.verdict==="APPROVE";if(!awaitsQaCompletion&&!awaitsCouncilCompletion)continue;let planStatus=task.status??"pending";if(planStatus==="completed"||planStatus==="closed"||planStatus==="blocked")continue;return taskId}return null}function completionGateViolationMessage(taskAwaitingCompletion){return`TASK_COMPLETION_GATE_VIOLATION: Task ${taskAwaitingCompletion} reached tests_run but is not marked completed in plan.json/plan.md. Call update_task_status with task_id="${taskAwaitingCompletion}" and status="completed". Read-only inspection remains available; a proven-disjoint task may continue; if plan.json is ledger-stale, retry save_plan with reconcile_ledger_projection=true and otherwise-unchanged plan content.`}function readCoderRetryEscalations(directory,taskId,retryEpoch){return getCoderRetryEscalationActions(directory,taskId,retryEpoch)}async function emitCoderRetryEscalation(directory,input){try{appendCoreEventSync(directory,{type:"coder_retry_circuit_breaker",timestamp:new Date().toISOString(),taskId:input.taskId,generation:input.generation,retryEpoch:input.retryEpoch,rejectionCount:input.rejectionCount,rejectionHistory:input.rejectionHistory,phase:Number(input.taskId.split(".")[0])||0,action:input.action},{dedupeOnAuthorityKey:!0})}catch(error49){if(error49 instanceof Error&&error49.message===CORE_EVENT_LOCKED)throw Error("TASK_RETRY_AUDIT_LOCKED");throw error49}}async function enforceCoderRetryEscalation(input){if(input.retryCount<3)return;let prior;try{prior=readCoderRetryEscalations(input.directory,input.taskId,input.retryEpoch)}catch(error49){if(error49 instanceof Error&&error49.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("TASK_RETRY_AUDIT_INDEX_UNREADABLE");throw error49}if(!prior.has("sounding_board_consultation"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"sounding_board_consultation"}),Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} reached the bounded retry threshold. Dispatch critic_sounding_board for this exact task before another coder attempt.`);if(prior.has("simplification"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"user_escalation"}),Error(`TASK_RETRY_USER_ESCALATION_REQUIRED: task ${input.taskId} failed its critic-guided simplified retry. Stop and ask the user to change scope, authorize repair, or choose a different approach.`);if(!input.criticSatisfied)throw Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} is waiting for an exact-generation critic_sounding_board APPROVED verdict.`);await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"simplification"})}function canRunWhileTaskAwaitsCompletion(input){let normalizedTool=input.normalizedTool.toLowerCase();if(isReadOnlyTool(normalizedTool))return!0;if(COMPLETION_RECOVERY_TOOLS.has(normalizedTool))return!0;if(normalizedTool==="spec_write"&&input.directory&&fs54.existsSync(path88.join(input.directory,".swarm","spec-staleness.json")))return!0;if(normalizedTool==="save_plan"&&input.args.reconcile_ledger_projection===!0)return!0;if(normalizedTool==="update_task_status"&&input.requestedTaskId===input.awaitingTaskId)return!0;if(input.directory&&input.requestedTaskId&&input.requestedTaskId!==input.awaitingTaskId)try{if(isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0}catch{return!1}return!1}async function buildParallelExecutionGuidance(directory,sessionID,session){if(!directory)return null;let plan=await loadPlanJsonOnly(directory);if(!plan)return null;let profile=plan.execution_profile,enabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=session?.maxConcurrencyOverride??maxConcurrent,allTasks=plan.phases.flatMap((phase)=>phase.tasks),blockedTasks=allTasks.filter((task)=>{if(task.status!=="blocked")return!1;let reason=(task.blocked_reason??"").toLowerCase();return reason.includes("fail")||reason.includes("error")||reason.includes("exception")}),totalTasks=allTasks.length,backoffTriggered=!1;if(totalTasks>0&&blockedTasks.length>0){let failureRate=blockedTasks.length/totalTasks,FAILURE_RATE_THRESHOLD=0.2,BACKOFF_MULTIPLIER=0.5;if(failureRate>0.2&&blockedTasks.length>=2){let newConcurrency=Math.max(1,Math.floor(effectiveMaxConcurrent*0.5));if(newConcurrency<effectiveMaxConcurrent)effectiveMaxConcurrent=newConcurrency,session.maxConcurrencyOverride=newConcurrency,backoffTriggered=!0}}if(!enabled||effectiveMaxConcurrent<=1)return null;if(hasActiveLeanTurbo(sessionID))return"[NEXT] Lean Turbo is active; use lean_turbo_run_phase and Lean Turbo lane guidance instead of standard execution-profile slot filling.";let currentPhaseId=resolveActivePhaseId(plan),currentPhase=plan.phases.find((phase)=>phase.id===currentPhaseId);if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan),fallbackReason=null;if(pendingTaskIds.length<2)fallbackReason="fewer than two pending tasks in the active phase — nothing to parallelize";else try{let verdict=computeParallelVerdict(directory,pendingTaskIds,{plan});if(verdict.verdict==="all_disjoint");else if(verdict.verdict==="unknown_scopes"){let shown=verdict.unknownScopeTasks.slice(0,6).join(", "),more=verdict.unknownScopeTasks.length>6?` (and ${verdict.unknownScopeTasks.length-6} more)`:"";fallbackReason=`no live declared scope for task${verdict.unknownScopeTasks.length===1?"":"s"}: ${shown}${more} — call declare_scope for each pending task, then retry`}else{let conflictPair=verdict.pairs.find((pair)=>pair.verdict==="conflict"),evidence=(conflictPair?.evidence??[]).slice(0,3).join("; ");fallbackReason=`declared scopes overlap: tasks ${conflictPair?.a??"?"} and ${conflictPair?.b??"?"} conflict (${evidence||"shared paths"})`}}catch{fallbackReason="verdict computation failed (fail-safe serial per v8 contract)"}if(fallbackReason!==null)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; SERIAL fallback active (v8 automatic safety) — exact reason: ${fallbackReason}. Run plan_conflict_check on the pending tasks to inspect the conflict matrix and a suggested serialization order, or proceed serially (one coder at a time).`;let completed=new Set;for(let task of allTasks){let taskId=task.id;if(isTaskCompletedForParallelGuidance(task))completed.add(taskId);if(getTaskState(session,taskId)==="complete")completed.add(taskId)}let occupied=new Set;for(let task of allTasks){let taskId=task.id;if(task.status==="in_progress")occupied.add(taskId);let state2=getTaskState(session,taskId);if(ACTIVE_PARALLEL_TASK_STATES.has(state2))occupied.add(taskId)}let availableSlots=Math.max(0,effectiveMaxConcurrent-occupied.size);if(availableSlots<=0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; all standard execution slots are occupied. Continue current active task gates before starting more coder work.`;let eligible=tasks.filter((task)=>{let taskId=task.id;if((task.status??"pending")!=="pending")return!1;if(occupied.has(taskId))return!1;return task.depends.every((dep)=>completed.has(dep))}).map((task)=>task.id).slice(0,availableSlots);if(eligible.length===0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; no dependency-ready pending tasks are available for a new coder slot. Continue the current task/gate.`;let failureWarning=backoffTriggered?` (${blockedTasks.length} blocked task(s) detected — concurrency auto-reduced due to failures)`:"";return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; ${occupied.size} slot(s) occupied. Eligible now: ${eligible.join(", ")}. [NEXT] dispatch up to ${availableSlots} eligible coder task(s) before waiting; preserve ONE task per coder call and call declare_scope for each task.${failureWarning}`}function collectPendingTaskIdsForActivePhase(plan){let currentPhaseId=resolveActivePhaseId(plan),currentPhase=plan.phases.find((phase)=>phase.id===currentPhaseId);if(!currentPhase)return[];return currentPhase.tasks.filter((t)=>t.status==="pending").map((t)=>t.id)}function scopeVerdictAllowsParallel(directory,plan){try{let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan);if(pendingTaskIds.length<2)return!1;return computeParallelVerdict(directory,pendingTaskIds,{plan}).verdict==="all_disjoint"}catch{return!1}}async function getEvidenceTaskId(session,directory){let resolvedPlanPath,primary=session.currentTaskId??session.lastCoderDelegationTaskId;if(primary)return primary;if(session.taskWorkflowStates&&session.taskWorkflowStates.size>0)return session.taskWorkflowStates.keys().next().value??null;try{if(typeof directory!=="string"||directory.length===0)return null;let resolvedDirectory=path88.resolve(directory),planPath=path88.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path88.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path88.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs54.promises.readFile(resolvedPlanPath,"utf-8"),plan=EvidenceTaskIdPlanSchema.parse(JSON.parse(planContent));if(!plan||!Array.isArray(plan.phases))return null;for(let phase of plan.phases)if(Array.isArray(phase.tasks)){for(let task of phase.tasks)if(task.status==="in_progress")return task.id??null}}catch(err){if(err instanceof ZodError){let issueSummary=err.issues.slice(0,3).map((issue2)=>issue2.message).join("; ");return warn(`[delegation-gate] getEvidenceTaskId ignored invalid plan schema at ${resolvedPlanPath??"unknown path"}: ${issueSummary}`),null}if(process.env.DEBUG_SWARM&&err instanceof Error)warn(`[delegation-gate] getEvidenceTaskId error: ${err.message} (code=${err.code??"none"})`);return null}return null}async function resolveEvidenceTaskId(args2,session,directory,options={}){let plan=null,planTaskIdContext;try{if(plan=await loadPlanJsonOnly(directory),plan)planTaskIdContext=collectPlanTaskIdContextFromPhases(plan.phases)}catch{}if(args2)try{let resolution=resolveTaskId(args2,{policy:"plan",...planTaskIdContext?toTaskIdPlanContextOptions(planTaskIdContext):{}});if(resolution.status==="resolved"){if(planTaskIdContext?.status==="over_limit"&&!plan?.phases.some((phase)=>phase?.tasks?.some((task)=>task?.id===resolution.taskId)))return null;return resolution.taskId}if(resolution.status==="invalid"||resolution.status==="ambiguous"||resolution.status==="over_limit")return null}catch{}if(options.allowSessionFallback===!1)return null;return getEvidenceTaskId(session,directory)}function sameReplayPrompt(existing,incoming){if(existing===void 0||incoming===void 0)return existing===incoming;return existing.digest===incoming.digest&&existing.chars===incoming.chars&&existing.truncated===incoming.truncated&&existing.text===incoming.text}function hasStableBackgroundReplayIdentity(existing,incoming){return existing.correlationId===incoming.correlationId&&existing.subagentSessionId===incoming.subagentSessionId&&existing.parentSessionId===incoming.parentSessionId&&existing.callID===incoming.callID&&existing.jobId===incoming.jobId&&existing.normalizedAgent===incoming.normalizedAgent&&existing.swarmPrefixedAgent===incoming.swarmPrefixedAgent&&existing.planTaskId===incoming.planTaskId&&existing.evidenceTaskId===incoming.evidenceTaskId&&sameReplayPrompt(existing.prompt,incoming.prompt)}function hydrateBackgroundReplayInput(existing,incoming){return{...incoming,workspace:existing.workspace,taskChangeContext:existing.taskChangeContext,worktree:existing.worktree,coderReservationId:existing.coderReservationId,prompt:existing.prompt,generation:existing.generation??1}}function sanitizeDenialText(value){return value.replace(/[\x00-\x1f\x7f]+/g," ")}function createDelegationGateHook(config2,directory,registeredAgents){initDurableStatusPath(directory);let enabled=config2.hooks?.delegation_gate!==!1,delegationMaxChars=config2.hooks?.delegation_max_chars??4000,backgroundSubagentsEnabled=config2.hooks?.background_subagents===!0,backgroundPendingTimeoutMs=(config2.hooks?.background_pending_timeout_minutes??30)*60000,MAX_PENDING_CODER_CHANGE_CONTEXTS=128,coderTaskChangeContextByCallID=new Map,begunCoderSettlementsByCallID=new Map,rememberBegunCoderSettlement=(callID,taskId,transitionId)=>{if(!begunCoderSettlementsByCallID.has(callID)&&begunCoderSettlementsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BEGUN_SETTLEMENT_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live begun settlements are already tracked`);begunCoderSettlementsByCallID.set(callID,{taskId,transitionId})},backgroundCoderReservationByCallID=new Map,coderObservedFilesByCallID=new Map,stageBDispatchGenerationsByCallID=new Map,gateDispatchPrimaryTaskByCallID=new Map,stageBDispatchContextByCallID=new Map,reviewRouteByTaskKey=new Map,stageBRouteSlotByCallID=new Map,reviewRouteTaskKey=(sessionId,taskId)=>`${sessionId}\x00${taskId}`,MAX_REVIEW_ROUTE_RECORDS=128,rememberReviewRoute=(key2,route)=>{reviewRouteByTaskKey.delete(key2),reviewRouteByTaskKey.set(key2,route);while(reviewRouteByTaskKey.size>MAX_REVIEW_ROUTE_RECORDS){let oldest=reviewRouteByTaskKey.keys().next().value;if(!oldest)break;reviewRouteByTaskKey.delete(oldest)}},clearReviewRouteStateForSession=(sessionId)=>{let prefix=`${sessionId}\x00`;for(let key2 of reviewRouteByTaskKey.keys())if(key2.startsWith(prefix))reviewRouteByTaskKey.delete(key2)},bindReviewRouteSlots=(callID,sessionId,role,taskIds)=>{let bindings=new Map,session=swarmState.agentSessions.get(sessionId);for(let taskId of taskIds){let route=reviewRouteByTaskKey.get(reviewRouteTaskKey(sessionId,taskId));if(!route||route.kind!=="review_route_receipt")continue;let identities=role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities;if(slots.length===0||identities.length!==slots.length)continue;let prior=stageBRouteSlotByCallID.get(callID)?.get(taskId),settled=session?getStageBRouteEvidence(session,taskId).find((entry)=>entry.role===role&&entry.sessionId===sessionId&&entry.taskId===taskId&&entry.callId===callID&&entry.generation===stageBDispatchGenerationsByCallID.get(callID)?.get(taskId)):void 0,existing=prior??settled,occupiedSlots=new Set;for(let entry of session?getStageBRouteEvidence(session,taskId):[])if(entry.role===role&&entry.slotId)occupiedSlots.add(entry.slotId);for(let[otherCallId,otherBindings]of stageBRouteSlotByCallID){if(otherCallId===callID)continue;let other=otherBindings.get(taskId);if(other?.role===role&&other.sessionId===sessionId&&other.taskId===taskId&&other.slotId)occupiedSlots.add(other.slotId)}let slotIndex=existing?slots.indexOf(existing.slotId??""):slots.findIndex((slotId2)=>!occupiedSlots.has(slotId2));if(slotIndex<0||slotIndex>=slots.length)continue;let slotId=slots[slotIndex];bindings.set(taskId,{role,identity:identities[slotIndex],sessionId,taskId,slotId,callId:callID,...existing?.childSessionId?{childSessionId:existing.childSessionId}:{},generation:stageBDispatchGenerationsByCallID.get(callID)?.get(taskId)})}if(bindings.size>0)stageBRouteSlotByCallID.set(callID,bindings)},publishedScopeBindingsByCallID=new Map,publishScopeBinding=async(callID,bindingDirectory,binding)=>{let published=await persistAndRegisterScopeBinding(bindingDirectory,binding);if(!published.ok)throw Error(`${published.code}: ${published.message}`);let entries=publishedScopeBindingsByCallID.get(callID)??[];entries.push({directory:bindingDirectory,binding}),publishedScopeBindingsByCallID.delete(callID),publishedScopeBindingsByCallID.set(callID,entries);while(publishedScopeBindingsByCallID.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=publishedScopeBindingsByCallID.keys().next().value;if(oldest===void 0)break;let evicted=publishedScopeBindingsByCallID.get(oldest)??[];publishedScopeBindingsByCallID.delete(oldest);for(let entry of evicted)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)}},clearPublishedScopeBindings=(callID)=>{let entries=publishedScopeBindingsByCallID.get(callID)??[];publishedScopeBindingsByCallID.delete(callID);for(let entry of entries)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)},taskMetadata=async(input)=>{let bindRouteChildSession=()=>{let routeBindings=stageBRouteSlotByCallID.get(input.callID);if(!routeBindings)return;for(let binding of routeBindings.values())binding.childSessionId=input.childSessionID},result=await claimScopeBindingForChildDurably({directory,parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});if(!result.ok){if(result.code==="SCOPE_NOT_DECLARED"){bindRouteChildSession();return}throw Error(`${result.code}: ${result.message}`)}let{previous,claimed}=result.value,entries=publishedScopeBindingsByCallID.get(input.callID)??[];for(let entry of entries)if(entry.directory===directory&&entry.binding.bindingId===previous.bindingId&&entry.binding.generationId===previous.generationId)entry.binding=claimed;let childSession=ensureAgentSession(input.childSessionID,"coder",directory);if(childSession.prmDelegationCallId!==input.callID)childSession.prmDelegationCallId=input.callID,resetPrmSessionState(childSession,input.childSessionID);childSession.currentTaskId=claimed.taskId,childSession.declaredCoderScope=[...claimed.files],bindRouteChildSession()},sessionEnded=(sessionID,includeOwnedChildren=!1)=>{if(!sessionID)return;clearReviewRouteStateForSession(sessionID);let removed=clearScopeBindings((binding)=>binding.ownerSessionId===sessionID||includeOwnedChildren&&binding.parentOwnerSessionId===sessionID);for(let binding of removed)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});if(removed.some((binding)=>binding.ownerSessionId===sessionID&&binding.activation==="active")){let endedSession=swarmState.agentSessions.get(sessionID);if(endedSession)endedSession.currentTaskId=null,endedSession.declaredCoderScope=null}for(let[callID,entries]of publishedScopeBindingsByCallID){let remaining=entries.filter((entry)=>entry.binding.ownerSessionId!==sessionID&&(!includeOwnedChildren||entry.binding.parentOwnerSessionId!==sessionID));if(remaining.length===0)publishedScopeBindingsByCallID.delete(callID);else if(remaining.length!==entries.length)publishedScopeBindingsByCallID.set(callID,remaining)}},clearCoderTaskChangeContext=(callID)=>{coderTaskChangeContextByCallID.delete(callID),coderObservedFilesByCallID.delete(callID)},rememberStageBDispatchGenerations=(callID,generations)=>{if(!stageBDispatchGenerationsByCallID.has(callID)&&stageBDispatchGenerationsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`STAGE_B_CONTEXT_CAPACITY: refusing Stage B dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live generation bindings are already tracked`);stageBDispatchGenerationsByCallID.set(callID,generations)},releasePrelaunchBackgroundCoderReservation=async(callID)=>{let reservation=backgroundCoderReservationByCallID.get(callID);if(!reservation)return;if(await _internals80.releaseBackgroundCoderReservationForDispatch(directory,{...reservation,reason:"recovered"})){backgroundCoderReservationByCallID.delete(callID);return}warn(`[delegation-gate] pre-launch background coder reservation ${reservation.reservationId} could not be released; later admission remains fail-closed`)},rememberCoderObservedFiles=(callID,observedFiles)=>{if(!coderObservedFilesByCallID.has(callID)&&coderObservedFilesByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS){let oldest=coderObservedFilesByCallID.keys().next().value;if(oldest!==void 0)coderObservedFilesByCallID.delete(oldest)}coderObservedFilesByCallID.set(callID,observedFiles)},rememberCoderTaskChangeContext=async(callID,declaredFiles,observationDirectory=directory,workflowGeneration)=>{if(!coderTaskChangeContextByCallID.has(callID)&&coderTaskChangeContextByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BACKGROUND_CODER_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live change baselines are already tracked`);coderTaskChangeContextByCallID.set(callID,{declaredFiles,baseline:await captureWorkspaceSnapshotAsync(observationDirectory),workflowGeneration})},beginForegroundCoderSettlementIfNeeded=async(input,taskId,background,worktree)=>{if(backgroundSubagentsEnabled&&isBackgroundTrue(background))return;let context=coderTaskChangeContextByCallID.get(input.callID);if(!context||context.workflowGeneration===void 0)throw Error(`CODER_SETTLEMENT_CONTEXT_MISSING: no durable baseline or generation for task ${taskId}`);let baselineDirtyFiles=Array.isArray(context.baseline.changedFiles)?context.baseline.changedFiles:[];if(baselineDirtyFiles.length>0){let sample=baselineDirtyFiles.slice(0,5).join(", ");throw Error(`CODER_SETTLEMENT_CLEAN_BASELINE_REQUIRED: ${String(baselineDirtyFiles.length)} uncommitted/untracked change(s) present at dispatch (${sample}${baselineDirtyFiles.length>5?", …":""}). `+"Commit or stash them before dispatching a coder — exact-task settlement cannot attribute coder mutations from a dirty launch baseline. "+`(.swarm/ plugin runtime state is excluded from this check automatically.) Task ${taskId} was not dispatched and no settlement state was created.`)}await beginCoderSettlement({directory,taskId,transitionId:`coder:${input.callID}`,actor:input.sessionID,expectedGeneration:context.workflowGeneration,context,...worktree?{worktree}:{}}),rememberBegunCoderSettlement(input.callID,taskId,`coder:${input.callID}`)},shouldRememberCoderTaskChangeContext=(_declaredFiles,_background)=>!0,backgroundCompletionClaimed=(record2)=>{let callID=record2.callID;clearPublishedScopeBindings(callID),clearCoderTaskChangeContext(callID),begunCoderSettlementsByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),stageBRouteSlotByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID),deleteStoredInputArgs(callID)};if(!enabled)return{messagesTransform:async(_input,_output)=>{},toolBefore:async(input,output)=>{let args2=output.args;if(!isTaskToolId(input.tool)||!args2||typeof args2.subagent_type!=="string"||stripKnownSwarmPrefix(args2.subagent_type)!=="coder")return;let prepared=await prepareCoderScope(directory,input,args2);await publishScopeBinding(input.callID,directory,prepared.binding)},toolAfter:async(input,output)=>{if(isTaskToolId(input.tool)&&outputLooksLikeBackgroundRunning(output))return;clearPublishedScopeBindings(input.callID)},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async()=>{}};return{toolBefore:async(input,output)=>{if(!input.sessionID)return;let normalized=normalizeToolName(input.tool),preflightArgs=output.args;if(isTaskToolId(input.tool)&&preflightArgs&&typeof preflightArgs.subagent_type==="string"){let exactPreflightAgent=preflightArgs.subagent_type,preflightAgent=stripKnownSwarmPrefix(exactPreflightAgent),registeredMode=registeredAgents?Object.entries(registeredAgents).find(([name])=>name.toLowerCase()===exactPreflightAgent.trim().toLowerCase())?.[1]:void 0,isCriticDispatch=preflightAgent.startsWith("critic"),isRegistryMatchedDispatch=registeredMode!==void 0,isPrimaryDispatch=registeredMode?.mode==="primary";if((isCriticDispatch||isRegistryMatchedDispatch)&&!isPrimaryDispatch){let denialError;if(isCriticDispatch){let legacyCriticModel=config2.agents?.[preflightAgent]?.model??DEFAULT_MODELS[preflightAgent]??DEFAULT_MODELS.default,criticModel=registeredAgents?resolveRuntimeAgentModel(config2,registeredAgents,exactPreflightAgent)??resolveRegisteredAgentModel(config2,exactPreflightAgent)??legacyCriticModel:legacyCriticModel;try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(criticModel,swarmState.opencodeClient)==="unresolved")telemetry.modelUnresolved(preflightAgent,criticModel,"plan-critic dispatch preflight"),denialError=`PLAN_CRITIC_MODEL_UNRESOLVED: the ${sanitizeDenialText(exactPreflightAgent)} agent's effective model "${sanitizeDenialText(criticModel)}" does not resolve against the provider catalog — the critic can never run, so the plan-critic gate cannot produce VERDICT: APPROVED. `+`Fix the effective model configuration for "${sanitizeDenialText(exactPreflightAgent)}" in opencode-swarm.json (including any matching swarm override or inherited critic model), then re-run MODE: CRITIC-GATE.`}catch(error49){if(error49 instanceof Error&&error49.message.startsWith("PLAN_CRITIC_MODEL_UNRESOLVED")){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),error49}}}else{let overrideEntry=resolveEffectiveAgentOverride(config2,exactPreflightAgent),finalModel=overrideEntry&&typeof overrideEntry.model==="string"&&overrideEntry.model.trim()===""?"":(registeredAgents?resolveRuntimeAgentModel(config2,registeredAgents,exactPreflightAgent):void 0)??resolveRegisteredAgentModel(config2,exactPreflightAgent);if(finalModel===void 0||finalModel.trim()==="")telemetry.modelUnresolved(preflightAgent,"(no final selection)","swarm-agent dispatch preflight"),denialError=`SWARM_AGENT_MODEL_MISSING_SELECTION: the ${sanitizeDenialText(exactPreflightAgent)} agent is registered but has no final model selection (blank model override or a stale swarm registry entry) — dispatching it cannot succeed. `+"Fix agents.<role>.model in opencode-swarm.json (the matching swarm override wins over the top-level entry) or correct the swarm configuration, then retry.";else try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(finalModel,swarmState.opencodeClient)==="unresolved")telemetry.modelUnresolved(preflightAgent,finalModel,"swarm-agent dispatch preflight"),denialError=`SWARM_AGENT_MODEL_UNRESOLVED: the ${sanitizeDenialText(exactPreflightAgent)} agent's effective model "${sanitizeDenialText(finalModel)}" does not resolve against the provider catalog — dispatching this role will fail permanently ("Model not found"/"Forbidden"). `+"Fix the effective model configuration in opencode-swarm.json (the matching swarm override wins over top-level agents.<role>.model). fallback_models entries only serve transient runtime failures; configure a resolvable primary model for this role."}catch{}}if(denialError!==void 0){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),Error(denialError)}}}let completionArgs=output.args;if(completionArgs){let completionPlanContext;try{let plan2=await loadPlanJsonOnly(directory);if(plan2)completionPlanContext=collectPlanTaskIdContextFromPhases(plan2.phases)}catch{}let requestedTaskId=resolveDelegatedPlanTaskId(completionArgs,completionPlanContext?toTaskIdPlanContextOptions(completionPlanContext):void 0);if(requestedTaskId){let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot3,readTaskEvidence:readTaskEvidence3}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),recoveredCoder=await recoverCoderSettlement(directory,requestedTaskId);if(recoveredCoder){let recoveredSession=ensureAgentSession(input.sessionID,void 0,directory),workflow=getTaskWorkflowSnapshot3(recoveredCoder.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredTerminal=await recoverPreparedTaskTerminal(directory,requestedTaskId,input.sessionID);if(recoveredTerminal){let recoveredSession=ensureAgentSession(input.sessionID,void 0,directory),workflow=getTaskWorkflowSnapshot3(recoveredTerminal.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredRepair=null;try{recoveredRepair=await recoverPreparedTaskRepair(directory,requestedTaskId,input.sessionID)}catch(error49){criticalWarn(`[delegation-gate] task-repair recovery deferred for ${requestedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`)}if(recoveredRepair){let recoveredSession=ensureAgentSession(input.sessionID,void 0,directory),workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,requestedTaskId));recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}}let taskAwaitingCompletion=await findTaskAwaitingCompletion(directory,requestedTaskId);if(taskAwaitingCompletion){if(!canRunWhileTaskAwaitsCompletion({directory,normalizedTool:normalized,args:completionArgs,awaitingTaskId:taskAwaitingCompletion,requestedTaskId}))throw Error(completionGateViolationMessage(taskAwaitingCompletion))}}if(!isTaskToolId(input.tool))return;let args2=output.args;if(!args2)return;let subagentType=args2.subagent_type;if(typeof subagentType!=="string")return;let targetAgent=stripKnownSwarmPrefix(subagentType);if(!backgroundSubagentsEnabled&&isBackgroundTrue(args2.background)&&isKnownCanonicalRole(targetAgent))throw Error(SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE);if(targetAgent==="reviewer"||targetAgent==="test_engineer"){let routedTaskId=null,routeDispatchStarted=!1;try{let reviewSession=swarmState.agentSessions.get(input.sessionID);if(reviewSession){let activePrReviewBinding=await readPrReviewReentryBindingContext(directory,input.sessionID),reviewTaskId=await resolveEvidenceTaskId(args2,reviewSession,directory,activePrReviewBinding?{allowSessionFallback:!1}:void 0),changedFiles=reviewTaskId?getModifiedFilesForTask(reviewSession,reviewTaskId):[],routeTaskId=reviewTaskId??`unresolved-${input.callID}`;routedTaskId=routeTaskId,markStageBRouteRequired(reviewSession,routeTaskId);let pendingRoute=buildReviewRoutePending({sessionId:input.sessionID,taskId:routeTaskId});if(await persistReviewRouteReceipt({projectRoot:directory,receipt:pendingRoute}),routeDispatchStarted=!0,rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),pendingRoute),changedFiles.length===0){let routerError=buildReviewRouteRouterError({code:"NO_CHANGED_FILES",sessionId:input.sessionID,taskId:routeTaskId});await persistReviewRouteReceipt({projectRoot:directory,receipt:routerError}),rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),routerError)}else{let routing=await routeReviewForChanges(directory,changedFiles),routeReceipt=buildReviewRouteReceipt({sessionId:input.sessionID,taskId:routeTaskId,complexity:routing.depth,semanticRisk:routing.reason,requiredReviewers:Array.from({length:routing.reviewerCount},(_,index)=>`${routeTaskId}:reviewer:${index+1}`),requiredTestEngineers:Array.from({length:routing.testEngineerCount},(_,index)=>`${routeTaskId}:test_engineer:${index+1}`)});if(await persistReviewRouteReceipt({projectRoot:directory,receipt:routeReceipt}),rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),routeReceipt),shouldParallelizeReview(routing))pushAdvisory(reviewSession,`REVIEW ROUTING: High complexity detected (${routing.reason}). Consider parallel review: ${routing.reviewerCount} reviewers, ${routing.testEngineerCount} test engineers recommended.`)}}}catch(error49){let detail=error49 instanceof Error?error49.message:String(error49);if(!routeDispatchStarted){warn(`[delegation-gate] review route dispatch could not establish its pending receipt: ${detail}`);return}let routerError=buildReviewRouteRouterError({code:/unavailable|timed out|timeout|not found/i.test(detail)?"ROUTER_UNAVAILABLE":"ROUTER_FAILED",sessionId:input.sessionID,taskId:routedTaskId??`unresolved-${input.callID}`,detail});try{if(await persistReviewRouteReceipt({projectRoot:directory,receipt:routerError}),routedTaskId)rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routedTaskId),routerError)}catch(persistError){warn(`[delegation-gate] review route receipt was not recorded: ${detail}; router-error persistence failed: ${persistError instanceof Error?persistError.message:String(persistError)}`)}}}if(targetAgent==="coder"||targetAgent==="reviewer"){let acceptancePromptText=ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
1230
+ `).toLowerCase();if(!text)return!1;return PLAN_CRITIC_TASK_SIGNALS.some((signal)=>text.includes(signal))}async function isPlanCriticApproved(directory){try{let plan=await loadPlanJsonOnly(directory);if(!plan)return!1;let planId=derivePlanId(plan),approved=await loadLastPlanCriticApprovedSnapshot(directory,planId);if(!approved)return!1;if(approved.approval?.verdict!=="APPROVED"||approved.approval?.source!=="plan_critic_gate")return!1;if(approved.payloadHash!==computePlanStructureHash(plan))return!1;return!0}catch{return!1}}async function assertPlanCriticApprovedForExecution(directory,plan){if(!plan)return;let planId=derivePlanId(plan),approved=await loadLastPlanCriticApprovedSnapshot(directory,planId);if(!approved)throw Error("PLAN_CRITIC_GATE_VIOLATION: Cannot delegate to coder before plan critic approval. Delegate to critic in MODE: CRITIC-GATE and require VERDICT: APPROVED before EXECUTE. If the critic already returned APPROVED but the snapshot was not recorded "+"(format/signal mismatch — issue #2012), call approve_plan_critic with a reason, "+"or run /swarm approve-plan-critic <reason>, to record a manual approval.");if(approved.approval?.verdict!=="APPROVED"||approved.approval?.source!=="plan_critic_gate")throw Error("PLAN_CRITIC_GATE_VIOLATION: Latest approved-plan snapshot does not contain plan critic VERDICT: APPROVED evidence. Re-run MODE: CRITIC-GATE and wait for explicit approval before coder execution. If the critic already returned APPROVED but the snapshot was not recorded (issue #2012), call approve_plan_critic or run /swarm approve-plan-critic.");if(approved.payloadHash!==computePlanStructureHash(plan))throw Error("PLAN_CRITIC_GATE_VIOLATION: Current plan differs from the last critic-approved snapshot. Re-run MODE: CRITIC-GATE after plan changes before delegating to coder. If re-review is not possible, call approve_plan_critic or run /swarm approve-plan-critic to record a fresh manual approval for the current plan.")}function resolvePlanCriticPolicyForExecution(directory,plan,sessionOverrides={}){try{let profile=getProfileForIdentity(directory,{swarm:plan.swarm,title:plan.title});if(!profile)return{required:DEFAULT_QA_GATES.critic_pre_plan,source:"default_missing_profile"};return{required:getEffectiveGates(profile,sessionOverrides).critic_pre_plan,source:sessionOverrides.critic_pre_plan===!0&&profile.gates.critic_pre_plan===!1?"session_ratchet":"persisted_profile"}}catch(error49){return warn(`[delegation-gate] failed to resolve critic_pre_plan profile; enforcing the gate: ${error49 instanceof Error?error49.message:String(error49)}`),{required:!0,source:"corrupt_profile_conservative"}}}async function recordPlanCriticApprovalSnapshotIfApplicable(directory,input,args2,output){if((typeof args2.subagent_type==="string"?stripKnownSwarmPrefix(args2.subagent_type):null)!=="critic")return;if(!taskLooksLikePlanCritic(args2))return;if(extractPlanCriticVerdict(output)!=="APPROVED")return;let plan=await loadPlanJsonOnly(directory);if(!plan)for(let attempt=0;attempt<2&&!plan;attempt++)await new Promise((resolve47)=>setTimeout(resolve47,150)),plan=await loadPlanJsonOnly(directory);if(!plan){warn("[delegation-gate] plan critic APPROVED verdict could not be recorded: plan.json not readable after retry. The critic_pre_plan gate will block coder delegation until a snapshot exists. Call approve_plan_critic (or /swarm approve-plan-critic) with a reason to record a manual approval if the critic genuinely approved.");return}await takeSnapshotEvent(directory,plan,{source:"critic_approved",approvalMetadata:{verdict:"APPROVED",source:"plan_critic_gate",session_id:input.sessionID,call_id:input.callID,approved_at:new Date().toISOString()},payloadHashOverride:computePlanStructureHash(plan)})}async function forceRecordPlanCriticApproval(directory,sessionID,options={}){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("NOT_AUTHORIZED: approve_plan_critic requires an active architect session. The plan-critic gate escape hatch is an architect-only escalation; a coder/reviewer cannot self-unblock. Run /swarm approve-plan-critic from an architect context, or ask the user to run it.");let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path88.join(directory,".swarm","plan.json");if(fs54.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recording a plan-critic approval.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot record a plan-critic "+"approval for a non-existent plan. Save a plan first.")}let planId=derivePlanId(plan),recordedAt=new Date().toISOString(),sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?options.reason.trim().slice(0,500):void 0,userConfirmed=options.userConfirmed===!0;await takeSnapshotEvent(directory,plan,{source:"critic_approved",approvalMetadata:{verdict:"APPROVED",source:"plan_critic_gate",method:"manual_override",reason:sanitizedReason,user_confirmed:userConfirmed,session_id:sessionID,approved_at:recordedAt},payloadHashOverride:computePlanStructureHash(plan)});try{appendCoreEventSync(directory,{type:"plan_critic_gate_manual_approval",timestamp:recordedAt,sessionID,plan_id:planId,user_confirmed:userConfirmed,...sanitizedReason?{reason:sanitizedReason}:{}})}catch(err){warn(`[delegation-gate] plan_critic_gate_manual_approval audit event write failed: ${err instanceof Error?err.message:String(err)}`)}return{planId,recordedAt,...sanitizedReason?{reason:sanitizedReason}:{},userConfirmed}}async function forceRecordRetrySoundingBoardApproval(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("APPROVE_RETRY_SOUNDING_BOARD_ARCHITECT_REQUIRED: approve_retry_sounding_board requires an active architect session. The coder retry circuit-breaker escape hatch is architect-only; a coder/reviewer cannot self-unblock.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('APPROVE_RETRY_UNKNOWN_TASK: approve_retry_sounding_board requires the exact plan task id (e.g. "2.1").');let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path88.join(directory,".swarm","plan.json");if(fs54.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recording a retry sounding-board approval.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot record a retry "+"sounding-board approval without a plan. Save a plan first.")}if(!new Set(plan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))).has(taskId))throw Error(`APPROVE_RETRY_UNKNOWN_TASK: task ${taskId} is not in the current plan. Refusing to record evidence for a foreign task id.`);let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),evidence=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence);if(!evidence||!workflow.authoritative)throw Error(`APPROVE_RETRY_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no retry state to recover.`);let prior;try{prior=readCoderRetryEscalations(directory,taskId,workflow.retryEpoch)}catch(error49){if(error49 instanceof Error&&error49.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("APPROVE_RETRY_AUDIT_INDEX_UNREADABLE: the retry audit authority index is unreadable, so the prior sounding_board_consultation cannot be verified. Repair the events store (see /swarm doctor) and retry.");throw error49}if(!prior.has("sounding_board_consultation"))throw Error(`APPROVE_RETRY_CONSULTATION_REQUIRED: task ${taskId} has no durable sounding_board_consultation escalation for retry epoch ${workflow.retryEpoch}. `+"Dispatch critic_sounding_board first — this tool records an obtained APPROVED verdict, it cannot substitute for the consultation.");let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?options.reason.trim().slice(0,500):void 0,recordedAt=new Date().toISOString(),transitionId=`retry-sb-manual:${sessionID}:epoch${workflow.retryEpoch}`;await recordGateEvidence2(directory,taskId,"critic_sounding_board",sessionID,!1,{transitionId,expectedGeneration:workflow.generation});let auditEventRecorded=!0;try{appendCoreEventSync(directory,{type:"coder_retry_circuit_breaker",timestamp:recordedAt,taskId,generation:workflow.generation,retryEpoch:workflow.retryEpoch,rejectionCount:workflow.retryCount,rejectionHistory:[...workflow.retryHistory],phase:Number(taskId.split(".")[0])||0,action:"sounding_board_manual_approval",...sanitizedReason?{reason:sanitizedReason}:{}},{dedupeOnAuthorityKey:!0})}catch(err){auditEventRecorded=!1,warn(`[delegation-gate] sounding_board_manual_approval audit event write failed: ${err instanceof Error?err.message:String(err)}`)}return{taskId,generation:workflow.generation,retryEpoch:workflow.retryEpoch,recordedAt,auditEventRecorded}}function isTaskCompletedForParallelGuidance(task){let status=task.status??"pending";return status==="completed"||status==="closed"}function getPlanTaskDeclaredFiles(plan,taskId){if(!plan||!taskId)return null;for(let phase of plan.phases){let task=phase.tasks.find((candidate)=>candidate.id===taskId);if(task)return[...task.files_touched]}return null}function describeCoderScopeFailure(args2,planTaskIdContext){if(planTaskIdContext.status==="over_limit")return`loaded plan task context exceeds the shared bounded limit (${TASK_ID_RESOLUTION_LIMITS.maxKnownIds} task ids); task-id resolution fails closed instead of guessing. Provide an explicit structured scope declaration or narrow the plan context before delegating.`;let resolution=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(planTaskIdContext)}),knownPlanTaskIds=planTaskIdContext.status==="available"?planTaskIdContext.taskIds:void 0,knownSummary=knownPlanTaskIds?[...knownPlanTaskIds].sort().join(", ")||"(none)":"(none)",rawTaskId=args2.task_id??args2.taskId,explicitFieldShape=typeof rawTaskId==="string"&&rawTaskId.trim().length>0?`"${rawTaskId.trim().slice(0,40)}" (non-plan-shaped; treated as runtime session id and ignored — falling through to text extraction)`:"absent",candidateTextFields=[args2.prompt,args2.description,args2.task,args2.input],taskLineCandidates=new Set,taskLineDetected=!1;for(let field of candidateTextFields){if(typeof field!=="string")continue;let taskLine=extractTaskLine(field);if(!taskLine)continue;taskLineDetected=!0;for(let m of taskLine.matchAll(/\b(\d+\.\d+(?:\.\d+)*)\b/g))if(knownPlanTaskIds?.has(m[1]))taskLineCandidates.add(m[1])}let textCandidates=new Set;for(let field of candidateTextFields){if(typeof field!=="string")continue;for(let m of field.matchAll(/\b(\d+\.\d+(?:\.\d+)*)\b/g))if(knownPlanTaskIds?.has(m[1]))textCandidates.add(m[1])}if(resolution.status==="invalid"&&typeof rawTaskId==="string"&&isStrictTaskId(rawTaskId.trim()))return`explicit task_id "${rawTaskId.trim().slice(0,40)}" is plan-shaped but does not resolve safely against the loaded plan, so resolution fails closed before prompt fallback. Known plan task ids: ${knownSummary}.`;if(resolution.status==="over_limit")return`task-id resolution exceeded a bounded input limit (${resolution.input}); provide exactly one concise TASK: <N.M> line or a valid explicit plan task_id. Known plan task ids: ${knownSummary}.`;if(taskLineCandidates.size>1)return`multiple candidate task ids found in TASK: line: [${[...taskLineCandidates].sort().join(", ")}]; provide exactly one unambiguous TASK: <id> line. Known plan task ids: ${knownSummary}.`;if(textCandidates.size>1)return`multiple candidate task ids found in prompt text: [${[...textCandidates].sort().join(", ")}]; provide exactly one unambiguous TASK: <id> line. Known plan task ids: ${knownSummary}.`;return`no plan task id could be resolved. Include a TASK: <N.M> line or plan-task-shaped task_id arg. Explicit task_id field: ${explicitFieldShape}. TASK: line detected: ${taskLineDetected?"yes":"no"}. Known plan task ids: ${knownSummary}.`}function stripSingleTrailingAnnotationSuffix(value){let suffixMatch=value.match(/(?:\s+\([^()]*\))+$/);if(!suffixMatch)return value;let suffix=suffixMatch[0];if((suffix.match(/\([^()]*\)/g)??[]).length!==1)return null;return value.slice(0,-suffix.length).trimEnd()||null}function normalizeFileDirectiveValue(rawValue){let value=rawValue.trim();if(!value)return null;let quote=value[0];if(quote==='"'||quote==="'"){let closingQuoteIndex=value.indexOf(quote,1);if(closingQuoteIndex===-1)return null;let filePath=value.slice(1,closingQuoteIndex);if(!filePath)return null;let suffix=value.slice(closingQuoteIndex+1);if(suffix.length>0&&!/^\s+\([^()]*\)\s*$/.test(suffix))return null;return filePath}let normalized=stripSingleTrailingAnnotationSuffix(value);if(!normalized||/[,;|]/.test(normalized))return null;return normalized}function extractTaskFileDirectives(args2,mode){let files=new Set,present=!1;for(let field of[args2.prompt,args2.description,args2.task,args2.input]){if(typeof field!=="string")continue;for(let line of field.split(/\r?\n/)){if(!/^\s*FILE\s*:/i.test(line))continue;present=!0;let value=normalizeFileDirectiveValue(line.replace(/^\s*FILE\s*:\s*/i,""));if(!value){if(mode==="observe")continue;return{present:!0,files:null}}files.add(value)}}return{present,files:present&&files.size>0?[...files]:null}}function parsePerTaskVerdicts(outputText2){let verdicts=new Map,errors3=[],reviewedPattern=/^\[REVIEWED\]\s*\|\s*(?:task-)?(\d+\.\d+(?:\.\d+)*)\s*\|\s*(APPROVED|REJECTED|CONCERNS)\s*\|?/im,testedPattern=/^\[TESTED\]\s*\|\s*(?:task-)?(\d+\.\d+(?:\.\d+)*)\s*\|\s*(PASS|FAIL|SKIPPED)\s*\|?/im;for(let line of outputText2.split(/\r?\n/)){let trimmed=line.trim(),match=reviewedPattern.exec(trimmed);if(match){let taskId=match[1],verdict=match[2];if(isStrictTaskId(taskId)){let existing=verdicts.get(taskId);if(existing){if(existing.verdict!==verdict||existing.kind!=="REVIEWED")errors3.push(`STAGE_B_VERDICT_CONFLICT: task ${taskId} has conflicting verdicts: ${existing.kind}/${existing.verdict} vs REVIEWED/${verdict}`)}else verdicts.set(taskId,{verdict,kind:"REVIEWED"})}continue}if(match=testedPattern.exec(trimmed),match){let taskId=match[1],verdict=match[2];if(isStrictTaskId(taskId)){let existing=verdicts.get(taskId);if(existing){if(existing.verdict!==verdict||existing.kind!=="TESTED")errors3.push(`STAGE_B_VERDICT_CONFLICT: task ${taskId} has conflicting verdicts: ${existing.kind}/${existing.verdict} vs TESTED/${verdict}`)}else verdicts.set(taskId,{verdict,kind:"TESTED"})}}}return{verdicts,errors:errors3}}async function findTaskAwaitingCompletion(directory,requestedTaskId){if(!directory)return null;let plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{return null}if(!plan)return null;let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),tasks=plan.phases.flatMap((phase)=>phase.tasks),orderedTasks=requestedTaskId?[...tasks.filter((task)=>task.id===requestedTaskId),...tasks.filter((task)=>task.id!==requestedTaskId)]:tasks;for(let task of orderedTasks){let taskId=task.id,evidence=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence),councilEvidence=evidence?.gates.council,awaitsQaCompletion=workflow.authoritative&&workflow.state==="tests_run",awaitsCouncilCompletion=workflow.authoritative&&workflow.state==="pre_check_passed"&&councilEvidence?.verdict==="APPROVE";if(!awaitsQaCompletion&&!awaitsCouncilCompletion)continue;let planStatus=task.status??"pending";if(planStatus==="completed"||planStatus==="closed"||planStatus==="blocked")continue;return taskId}return null}function completionGateViolationMessage(taskAwaitingCompletion){return`TASK_COMPLETION_GATE_VIOLATION: Task ${taskAwaitingCompletion} reached tests_run but is not marked completed in plan.json/plan.md. Call update_task_status with task_id="${taskAwaitingCompletion}" and status="completed". Read-only inspection remains available; a proven-disjoint task may continue; if plan.json is ledger-stale, retry save_plan with reconcile_ledger_projection=true and otherwise-unchanged plan content.`}function readCoderRetryEscalations(directory,taskId,retryEpoch){return getCoderRetryEscalationActions(directory,taskId,retryEpoch)}async function emitCoderRetryEscalation(directory,input){try{appendCoreEventSync(directory,{type:"coder_retry_circuit_breaker",timestamp:new Date().toISOString(),taskId:input.taskId,generation:input.generation,retryEpoch:input.retryEpoch,rejectionCount:input.rejectionCount,rejectionHistory:input.rejectionHistory,phase:Number(input.taskId.split(".")[0])||0,action:input.action},{dedupeOnAuthorityKey:!0})}catch(error49){if(error49 instanceof Error&&error49.message===CORE_EVENT_LOCKED)throw Error("TASK_RETRY_AUDIT_LOCKED");throw error49}}async function enforceCoderRetryEscalation(input){if(input.retryCount<3)return;let prior;try{prior=readCoderRetryEscalations(input.directory,input.taskId,input.retryEpoch)}catch(error49){if(error49 instanceof Error&&error49.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("TASK_RETRY_AUDIT_INDEX_UNREADABLE");throw error49}if(!prior.has("sounding_board_consultation"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"sounding_board_consultation"}),Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} reached the bounded retry threshold. Dispatch critic_sounding_board for this exact task before another coder attempt.`);if(prior.has("simplification"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"user_escalation"}),Error(`TASK_RETRY_USER_ESCALATION_REQUIRED: task ${input.taskId} failed its critic-guided simplified retry. Stop and ask the user to change scope, authorize repair, or choose a different approach.`);if(!input.criticSatisfied)throw Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} is waiting for an exact-generation critic_sounding_board APPROVED verdict.`);await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"simplification"})}function isExplicitTaskEvidenceAgent(targetAgent){return EXPLICIT_TASK_EVIDENCE_AGENTS.has(stripKnownSwarmPrefix(targetAgent))}function evidenceTaskResolutionOptions(targetAgent,allowSessionFallback){if(isExplicitTaskEvidenceAgent(targetAgent))return{policy:"attribution",allowSessionFallback:!1};if(allowSessionFallback===!1)return{allowSessionFallback:!1};return}function canRunWhileTaskAwaitsCompletion(input){let normalizedTool=input.normalizedTool.toLowerCase();if(isReadOnlyTool(normalizedTool))return!0;if(COMPLETION_RECOVERY_TOOLS.has(normalizedTool))return!0;if(normalizedTool==="spec_write"&&input.directory&&fs54.existsSync(path88.join(input.directory,".swarm","spec-staleness.json")))return!0;if(normalizedTool==="save_plan"&&input.args.reconcile_ledger_projection===!0)return!0;if(normalizedTool==="update_task_status"&&input.requestedTaskId===input.awaitingTaskId)return!0;if(input.directory&&input.requestedTaskId&&input.requestedTaskId!==input.awaitingTaskId)try{if(isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0}catch{return!1}return!1}async function buildParallelExecutionGuidance(directory,sessionID,session){if(!directory)return null;let plan=await loadPlanJsonOnly(directory);if(!plan)return null;let profile=plan.execution_profile,enabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=session?.maxConcurrencyOverride??maxConcurrent,allTasks=plan.phases.flatMap((phase)=>phase.tasks),blockedTasks=allTasks.filter((task)=>{if(task.status!=="blocked")return!1;let reason=(task.blocked_reason??"").toLowerCase();return reason.includes("fail")||reason.includes("error")||reason.includes("exception")}),totalTasks=allTasks.length,backoffTriggered=!1;if(totalTasks>0&&blockedTasks.length>0){let failureRate=blockedTasks.length/totalTasks,FAILURE_RATE_THRESHOLD=0.2,BACKOFF_MULTIPLIER=0.5;if(failureRate>0.2&&blockedTasks.length>=2){let newConcurrency=Math.max(1,Math.floor(effectiveMaxConcurrent*0.5));if(newConcurrency<effectiveMaxConcurrent)effectiveMaxConcurrent=newConcurrency,session.maxConcurrencyOverride=newConcurrency,backoffTriggered=!0}}if(!enabled||effectiveMaxConcurrent<=1)return null;if(hasActiveLeanTurbo(sessionID))return"[NEXT] Lean Turbo is active; use lean_turbo_run_phase and Lean Turbo lane guidance instead of standard execution-profile slot filling.";let currentPhaseId=resolveActivePhaseId(plan),currentPhase=plan.phases.find((phase)=>phase.id===currentPhaseId);if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan),fallbackReason=null;if(pendingTaskIds.length<2)fallbackReason="fewer than two pending tasks in the active phase — nothing to parallelize";else try{let verdict=computeParallelVerdict(directory,pendingTaskIds,{plan});if(verdict.verdict==="all_disjoint");else if(verdict.verdict==="unknown_scopes"){let shown=verdict.unknownScopeTasks.slice(0,6).join(", "),more=verdict.unknownScopeTasks.length>6?` (and ${verdict.unknownScopeTasks.length-6} more)`:"";fallbackReason=`no live declared scope for task${verdict.unknownScopeTasks.length===1?"":"s"}: ${shown}${more} — call declare_scope for each pending task, then retry`}else{let conflictPair=verdict.pairs.find((pair)=>pair.verdict==="conflict"),evidence=(conflictPair?.evidence??[]).slice(0,3).join("; ");fallbackReason=`declared scopes overlap: tasks ${conflictPair?.a??"?"} and ${conflictPair?.b??"?"} conflict (${evidence||"shared paths"})`}}catch{fallbackReason="verdict computation failed (fail-safe serial per v8 contract)"}if(fallbackReason!==null)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; SERIAL fallback active (v8 automatic safety) — exact reason: ${fallbackReason}. Run plan_conflict_check on the pending tasks to inspect the conflict matrix and a suggested serialization order, or proceed serially (one coder at a time).`;let completed=new Set;for(let task of allTasks){let taskId=task.id;if(isTaskCompletedForParallelGuidance(task))completed.add(taskId);if(getTaskState(session,taskId)==="complete")completed.add(taskId)}let occupied=new Set;for(let task of allTasks){let taskId=task.id;if(task.status==="in_progress")occupied.add(taskId);let state2=getTaskState(session,taskId);if(ACTIVE_PARALLEL_TASK_STATES.has(state2))occupied.add(taskId)}let availableSlots=Math.max(0,effectiveMaxConcurrent-occupied.size);if(availableSlots<=0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; all standard execution slots are occupied. Continue current active task gates before starting more coder work.`;let eligible=tasks.filter((task)=>{let taskId=task.id;if((task.status??"pending")!=="pending")return!1;if(occupied.has(taskId))return!1;return task.depends.every((dep)=>completed.has(dep))}).map((task)=>task.id).slice(0,availableSlots);if(eligible.length===0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; no dependency-ready pending tasks are available for a new coder slot. Continue the current task/gate.`;let failureWarning=backoffTriggered?` (${blockedTasks.length} blocked task(s) detected — concurrency auto-reduced due to failures)`:"";return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; ${occupied.size} slot(s) occupied. Eligible now: ${eligible.join(", ")}. [NEXT] dispatch up to ${availableSlots} eligible coder task(s) before waiting; preserve ONE task per coder call and call declare_scope for each task.${failureWarning}`}function collectPendingTaskIdsForActivePhase(plan){let currentPhaseId=resolveActivePhaseId(plan),currentPhase=plan.phases.find((phase)=>phase.id===currentPhaseId);if(!currentPhase)return[];return currentPhase.tasks.filter((t)=>t.status==="pending").map((t)=>t.id)}function scopeVerdictAllowsParallel(directory,plan){try{let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan);if(pendingTaskIds.length<2)return!1;return computeParallelVerdict(directory,pendingTaskIds,{plan}).verdict==="all_disjoint"}catch{return!1}}async function getEvidenceTaskId(session,directory){let resolvedPlanPath,primary=session.currentTaskId??session.lastCoderDelegationTaskId;if(primary)return primary;if(session.taskWorkflowStates&&session.taskWorkflowStates.size>0)return session.taskWorkflowStates.keys().next().value??null;try{if(typeof directory!=="string"||directory.length===0)return null;let resolvedDirectory=path88.resolve(directory),planPath=path88.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path88.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path88.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs54.promises.readFile(resolvedPlanPath,"utf-8"),plan=EvidenceTaskIdPlanSchema.parse(JSON.parse(planContent));if(!plan||!Array.isArray(plan.phases))return null;for(let phase of plan.phases)if(Array.isArray(phase.tasks)){for(let task of phase.tasks)if(task.status==="in_progress")return task.id??null}}catch(err){if(err instanceof ZodError){let issueSummary=err.issues.slice(0,3).map((issue2)=>issue2.message).join("; ");return warn(`[delegation-gate] getEvidenceTaskId ignored invalid plan schema at ${resolvedPlanPath??"unknown path"}: ${issueSummary}`),null}if(process.env.DEBUG_SWARM&&err instanceof Error)warn(`[delegation-gate] getEvidenceTaskId error: ${err.message} (code=${err.code??"none"})`);return null}return null}async function resolveEvidenceTaskId(args2,session,directory,options={}){let plan=null,planTaskIdContext;try{if(plan=await loadPlanJsonOnly(directory),plan)planTaskIdContext=collectPlanTaskIdContextFromPhases(plan.phases)}catch{}if(args2)try{let policy=options.policy??"plan",planContextOptions=policy==="attribution"&&planTaskIdContext?.status==="over_limit"?{}:planTaskIdContext?toTaskIdPlanContextOptions(planTaskIdContext):{},resolutionOptions={policy,...planContextOptions,standaloneTaskMarkerOnly:policy==="attribution"},resolution=resolveTaskId(args2,resolutionOptions);if(resolution.status==="resolved"){let resolvedTaskId=resolution.taskId;if(policy==="attribution"&&!isStrictTaskId(resolvedTaskId)){let markerOnlyArgs={...args2};for(let field of EXPLICIT_TASK_ID_FIELDS)delete markerOnlyArgs[field];let markerResolution=resolveTaskId(markerOnlyArgs,resolutionOptions);if(markerResolution.status!=="resolved"||!isStrictTaskId(markerResolution.taskId))return null;resolvedTaskId=markerResolution.taskId}if(planTaskIdContext?.status==="over_limit"&&!plan?.phases.some((phase)=>phase?.tasks?.some((task)=>task?.id===resolvedTaskId)))return null;return resolvedTaskId}if(resolution.status==="invalid"||resolution.status==="ambiguous"||resolution.status==="over_limit")return null}catch{}if(options.allowSessionFallback===!1)return null;return getEvidenceTaskId(session,directory)}function sameReplayPrompt(existing,incoming){if(existing===void 0||incoming===void 0)return existing===incoming;return existing.digest===incoming.digest&&existing.chars===incoming.chars&&existing.truncated===incoming.truncated&&existing.text===incoming.text}function hasStableBackgroundReplayIdentity(existing,incoming){return existing.correlationId===incoming.correlationId&&existing.subagentSessionId===incoming.subagentSessionId&&existing.parentSessionId===incoming.parentSessionId&&existing.callID===incoming.callID&&existing.jobId===incoming.jobId&&existing.normalizedAgent===incoming.normalizedAgent&&existing.swarmPrefixedAgent===incoming.swarmPrefixedAgent&&existing.planTaskId===incoming.planTaskId&&existing.evidenceTaskId===incoming.evidenceTaskId&&sameReplayPrompt(existing.prompt,incoming.prompt)}function hydrateBackgroundReplayInput(existing,incoming){return{...incoming,workspace:existing.workspace,taskChangeContext:existing.taskChangeContext,worktree:existing.worktree,coderReservationId:existing.coderReservationId,prompt:existing.prompt,generation:existing.generation??1}}function sanitizeDenialText(value){return value.replace(/[\x00-\x1f\x7f]+/g," ")}function createDelegationGateHook(config2,directory,registeredAgents){initDurableStatusPath(directory);let enabled=config2.hooks?.delegation_gate!==!1,delegationMaxChars=config2.hooks?.delegation_max_chars??4000,backgroundSubagentsEnabled=config2.hooks?.background_subagents===!0,backgroundPendingTimeoutMs=(config2.hooks?.background_pending_timeout_minutes??30)*60000,MAX_PENDING_CODER_CHANGE_CONTEXTS=128,coderTaskChangeContextByCallID=new Map,begunCoderSettlementsByCallID=new Map,rememberBegunCoderSettlement=(callID,taskId,transitionId)=>{if(!begunCoderSettlementsByCallID.has(callID)&&begunCoderSettlementsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BEGUN_SETTLEMENT_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live begun settlements are already tracked`);begunCoderSettlementsByCallID.set(callID,{taskId,transitionId})},backgroundCoderReservationByCallID=new Map,coderObservedFilesByCallID=new Map,stageBDispatchGenerationsByCallID=new Map,gateDispatchPrimaryTaskByCallID=new Map,stageBDispatchContextByCallID=new Map,reviewRouteByTaskKey=new Map,stageBRouteSlotByCallID=new Map,reviewRouteTaskKey=(sessionId,taskId)=>`${sessionId}\x00${taskId}`,MAX_REVIEW_ROUTE_RECORDS=128,rememberReviewRoute=(key2,route)=>{reviewRouteByTaskKey.delete(key2),reviewRouteByTaskKey.set(key2,route);while(reviewRouteByTaskKey.size>MAX_REVIEW_ROUTE_RECORDS){let oldest=reviewRouteByTaskKey.keys().next().value;if(!oldest)break;reviewRouteByTaskKey.delete(oldest)}},clearReviewRouteStateForSession=(sessionId)=>{let prefix=`${sessionId}\x00`;for(let key2 of reviewRouteByTaskKey.keys())if(key2.startsWith(prefix))reviewRouteByTaskKey.delete(key2)},bindReviewRouteSlots=(callID,sessionId,role,taskIds)=>{let bindings=new Map,session=swarmState.agentSessions.get(sessionId);for(let taskId of taskIds){let route=reviewRouteByTaskKey.get(reviewRouteTaskKey(sessionId,taskId));if(!route||route.kind!=="review_route_receipt")continue;let identities=role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities;if(slots.length===0||identities.length!==slots.length)continue;let prior=stageBRouteSlotByCallID.get(callID)?.get(taskId),settled=session?getStageBRouteEvidence(session,taskId).find((entry)=>entry.role===role&&entry.sessionId===sessionId&&entry.taskId===taskId&&entry.callId===callID&&entry.generation===stageBDispatchGenerationsByCallID.get(callID)?.get(taskId)):void 0,existing=prior??settled,occupiedSlots=new Set;for(let entry of session?getStageBRouteEvidence(session,taskId):[])if(entry.role===role&&entry.slotId)occupiedSlots.add(entry.slotId);for(let[otherCallId,otherBindings]of stageBRouteSlotByCallID){if(otherCallId===callID)continue;let other=otherBindings.get(taskId);if(other?.role===role&&other.sessionId===sessionId&&other.taskId===taskId&&other.slotId)occupiedSlots.add(other.slotId)}let slotIndex=existing?slots.indexOf(existing.slotId??""):slots.findIndex((slotId2)=>!occupiedSlots.has(slotId2));if(slotIndex<0||slotIndex>=slots.length)continue;let slotId=slots[slotIndex];bindings.set(taskId,{role,identity:identities[slotIndex],sessionId,taskId,slotId,callId:callID,...existing?.childSessionId?{childSessionId:existing.childSessionId}:{},generation:stageBDispatchGenerationsByCallID.get(callID)?.get(taskId)})}if(bindings.size>0)stageBRouteSlotByCallID.set(callID,bindings)},publishedScopeBindingsByCallID=new Map,publishScopeBinding=async(callID,bindingDirectory,binding)=>{let published=await persistAndRegisterScopeBinding(bindingDirectory,binding);if(!published.ok)throw Error(`${published.code}: ${published.message}`);let entries=publishedScopeBindingsByCallID.get(callID)??[];entries.push({directory:bindingDirectory,binding}),publishedScopeBindingsByCallID.delete(callID),publishedScopeBindingsByCallID.set(callID,entries);while(publishedScopeBindingsByCallID.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=publishedScopeBindingsByCallID.keys().next().value;if(oldest===void 0)break;let evicted=publishedScopeBindingsByCallID.get(oldest)??[];publishedScopeBindingsByCallID.delete(oldest);for(let entry of evicted)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)}},clearPublishedScopeBindings=(callID)=>{let entries=publishedScopeBindingsByCallID.get(callID)??[];publishedScopeBindingsByCallID.delete(callID);for(let entry of entries)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)},taskMetadata=async(input)=>{let bindRouteChildSession=()=>{let routeBindings=stageBRouteSlotByCallID.get(input.callID);if(!routeBindings)return;for(let binding of routeBindings.values())binding.childSessionId=input.childSessionID},result=await claimScopeBindingForChildDurably({directory,parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});if(!result.ok){if(result.code==="SCOPE_NOT_DECLARED"){bindRouteChildSession();return}throw Error(`${result.code}: ${result.message}`)}let{previous,claimed}=result.value,entries=publishedScopeBindingsByCallID.get(input.callID)??[];for(let entry of entries)if(entry.directory===directory&&entry.binding.bindingId===previous.bindingId&&entry.binding.generationId===previous.generationId)entry.binding=claimed;let childSession=ensureAgentSession(input.childSessionID,"coder",directory);if(childSession.prmDelegationCallId!==input.callID)childSession.prmDelegationCallId=input.callID,resetPrmSessionState(childSession,input.childSessionID);childSession.currentTaskId=claimed.taskId,childSession.declaredCoderScope=[...claimed.files],bindRouteChildSession()},sessionEnded=(sessionID,includeOwnedChildren=!1)=>{if(!sessionID)return;clearReviewRouteStateForSession(sessionID);let removed=clearScopeBindings((binding)=>binding.ownerSessionId===sessionID||includeOwnedChildren&&binding.parentOwnerSessionId===sessionID);for(let binding of removed)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});if(removed.some((binding)=>binding.ownerSessionId===sessionID&&binding.activation==="active")){let endedSession=swarmState.agentSessions.get(sessionID);if(endedSession)endedSession.currentTaskId=null,endedSession.declaredCoderScope=null}for(let[callID,entries]of publishedScopeBindingsByCallID){let remaining=entries.filter((entry)=>entry.binding.ownerSessionId!==sessionID&&(!includeOwnedChildren||entry.binding.parentOwnerSessionId!==sessionID));if(remaining.length===0)publishedScopeBindingsByCallID.delete(callID);else if(remaining.length!==entries.length)publishedScopeBindingsByCallID.set(callID,remaining)}},clearCoderTaskChangeContext=(callID)=>{coderTaskChangeContextByCallID.delete(callID),coderObservedFilesByCallID.delete(callID)},rememberStageBDispatchGenerations=(callID,generations)=>{if(!stageBDispatchGenerationsByCallID.has(callID)&&stageBDispatchGenerationsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`STAGE_B_CONTEXT_CAPACITY: refusing Stage B dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live generation bindings are already tracked`);stageBDispatchGenerationsByCallID.set(callID,generations)},releasePrelaunchBackgroundCoderReservation=async(callID)=>{let reservation=backgroundCoderReservationByCallID.get(callID);if(!reservation)return;if(await _internals80.releaseBackgroundCoderReservationForDispatch(directory,{...reservation,reason:"recovered"})){backgroundCoderReservationByCallID.delete(callID);return}warn(`[delegation-gate] pre-launch background coder reservation ${reservation.reservationId} could not be released; later admission remains fail-closed`)},rememberCoderObservedFiles=(callID,observedFiles)=>{if(!coderObservedFilesByCallID.has(callID)&&coderObservedFilesByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS){let oldest=coderObservedFilesByCallID.keys().next().value;if(oldest!==void 0)coderObservedFilesByCallID.delete(oldest)}coderObservedFilesByCallID.set(callID,observedFiles)},rememberCoderTaskChangeContext=async(callID,declaredFiles,observationDirectory=directory,workflowGeneration)=>{if(!coderTaskChangeContextByCallID.has(callID)&&coderTaskChangeContextByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BACKGROUND_CODER_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live change baselines are already tracked`);coderTaskChangeContextByCallID.set(callID,{declaredFiles,baseline:await captureWorkspaceSnapshotAsync(observationDirectory),workflowGeneration})},beginForegroundCoderSettlementIfNeeded=async(input,taskId,background,worktree)=>{if(backgroundSubagentsEnabled&&isBackgroundTrue(background))return;let context=coderTaskChangeContextByCallID.get(input.callID);if(!context||context.workflowGeneration===void 0)throw Error(`CODER_SETTLEMENT_CONTEXT_MISSING: no durable baseline or generation for task ${taskId}`);let baselineDirtyFiles=Array.isArray(context.baseline.changedFiles)?context.baseline.changedFiles:[];if(baselineDirtyFiles.length>0){let sample=baselineDirtyFiles.slice(0,5).join(", ");throw Error(`CODER_SETTLEMENT_CLEAN_BASELINE_REQUIRED: ${String(baselineDirtyFiles.length)} uncommitted/untracked change(s) present at dispatch (${sample}${baselineDirtyFiles.length>5?", …":""}). `+"Commit or stash them before dispatching a coder — exact-task settlement cannot attribute coder mutations from a dirty launch baseline. "+`(.swarm/ plugin runtime state is excluded from this check automatically.) Task ${taskId} was not dispatched and no settlement state was created.`)}await beginCoderSettlement({directory,taskId,transitionId:`coder:${input.callID}`,actor:input.sessionID,expectedGeneration:context.workflowGeneration,context,...worktree?{worktree}:{}}),rememberBegunCoderSettlement(input.callID,taskId,`coder:${input.callID}`)},shouldRememberCoderTaskChangeContext=(_declaredFiles,_background)=>!0,backgroundCompletionClaimed=(record2)=>{let callID=record2.callID;clearPublishedScopeBindings(callID),clearCoderTaskChangeContext(callID),begunCoderSettlementsByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),stageBRouteSlotByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID),deleteStoredInputArgs(callID)};if(!enabled)return{messagesTransform:async(_input,_output)=>{},toolBefore:async(input,output)=>{let args2=output.args;if(!isTaskToolId(input.tool)||!args2||typeof args2.subagent_type!=="string"||stripKnownSwarmPrefix(args2.subagent_type)!=="coder")return;let prepared=await prepareCoderScope(directory,input,args2);await publishScopeBinding(input.callID,directory,prepared.binding)},toolAfter:async(input,output)=>{if(isTaskToolId(input.tool)&&outputLooksLikeBackgroundRunning(output))return;clearPublishedScopeBindings(input.callID)},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async()=>{}};return{toolBefore:async(input,output)=>{if(!input.sessionID)return;let normalized=normalizeToolName(input.tool),preflightArgs=output.args;if(isTaskToolId(input.tool)&&preflightArgs&&typeof preflightArgs.subagent_type==="string"){let exactPreflightAgent=preflightArgs.subagent_type,preflightAgent=stripKnownSwarmPrefix(exactPreflightAgent),registeredMode=registeredAgents?Object.entries(registeredAgents).find(([name])=>name.toLowerCase()===exactPreflightAgent.trim().toLowerCase())?.[1]:void 0,isCriticDispatch=preflightAgent.startsWith("critic"),isRegistryMatchedDispatch=registeredMode!==void 0,isPrimaryDispatch=registeredMode?.mode==="primary";if((isCriticDispatch||isRegistryMatchedDispatch)&&!isPrimaryDispatch){let denialError;if(isCriticDispatch){let legacyCriticModel=config2.agents?.[preflightAgent]?.model??DEFAULT_MODELS[preflightAgent]??DEFAULT_MODELS.default,criticModel=registeredAgents?resolveRuntimeAgentModel(config2,registeredAgents,exactPreflightAgent)??resolveRegisteredAgentModel(config2,exactPreflightAgent)??legacyCriticModel:legacyCriticModel;try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(criticModel,swarmState.opencodeClient)==="unresolved")telemetry.modelUnresolved(preflightAgent,criticModel,"plan-critic dispatch preflight"),denialError=`PLAN_CRITIC_MODEL_UNRESOLVED: the ${sanitizeDenialText(exactPreflightAgent)} agent's effective model "${sanitizeDenialText(criticModel)}" does not resolve against the provider catalog — the critic can never run, so the plan-critic gate cannot produce VERDICT: APPROVED. `+`Fix the effective model configuration for "${sanitizeDenialText(exactPreflightAgent)}" in opencode-swarm.json (including any matching swarm override or inherited critic model), then re-run MODE: CRITIC-GATE.`}catch(error49){if(error49 instanceof Error&&error49.message.startsWith("PLAN_CRITIC_MODEL_UNRESOLVED")){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),error49}}}else{let overrideEntry=resolveEffectiveAgentOverride(config2,exactPreflightAgent),finalModel=overrideEntry&&typeof overrideEntry.model==="string"&&overrideEntry.model.trim()===""?"":(registeredAgents?resolveRuntimeAgentModel(config2,registeredAgents,exactPreflightAgent):void 0)??resolveRegisteredAgentModel(config2,exactPreflightAgent);if(finalModel===void 0||finalModel.trim()==="")telemetry.modelUnresolved(preflightAgent,"(no final selection)","swarm-agent dispatch preflight"),denialError=`SWARM_AGENT_MODEL_MISSING_SELECTION: the ${sanitizeDenialText(exactPreflightAgent)} agent is registered but has no final model selection (blank model override or a stale swarm registry entry) — dispatching it cannot succeed. `+"Fix agents.<role>.model in opencode-swarm.json (the matching swarm override wins over the top-level entry) or correct the swarm configuration, then retry.";else try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(finalModel,swarmState.opencodeClient)==="unresolved")telemetry.modelUnresolved(preflightAgent,finalModel,"swarm-agent dispatch preflight"),denialError=`SWARM_AGENT_MODEL_UNRESOLVED: the ${sanitizeDenialText(exactPreflightAgent)} agent's effective model "${sanitizeDenialText(finalModel)}" does not resolve against the provider catalog — dispatching this role will fail permanently ("Model not found"/"Forbidden"). `+"Fix the effective model configuration in opencode-swarm.json (the matching swarm override wins over top-level agents.<role>.model). fallback_models entries only serve transient runtime failures; configure a resolvable primary model for this role."}catch{}}if(denialError!==void 0){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),Error(denialError)}}}let completionArgs=output.args;if(completionArgs){let completionPlanContext;try{let plan2=await loadPlanJsonOnly(directory);if(plan2)completionPlanContext=collectPlanTaskIdContextFromPhases(plan2.phases)}catch{}let requestedTaskId=resolveDelegatedPlanTaskId(completionArgs,completionPlanContext?toTaskIdPlanContextOptions(completionPlanContext):void 0);if(requestedTaskId){let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot3,readTaskEvidence:readTaskEvidence3}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),recoveredCoder=await recoverCoderSettlement(directory,requestedTaskId);if(recoveredCoder){let recoveredSession=ensureAgentSession(input.sessionID,void 0,directory),workflow=getTaskWorkflowSnapshot3(recoveredCoder.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredTerminal=await recoverPreparedTaskTerminal(directory,requestedTaskId,input.sessionID);if(recoveredTerminal){let recoveredSession=ensureAgentSession(input.sessionID,void 0,directory),workflow=getTaskWorkflowSnapshot3(recoveredTerminal.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredRepair=null;try{recoveredRepair=await recoverPreparedTaskRepair(directory,requestedTaskId,input.sessionID)}catch(error49){criticalWarn(`[delegation-gate] task-repair recovery deferred for ${requestedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`)}if(recoveredRepair){let recoveredSession=ensureAgentSession(input.sessionID,void 0,directory),workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,requestedTaskId));recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}}let taskAwaitingCompletion=await findTaskAwaitingCompletion(directory,requestedTaskId);if(taskAwaitingCompletion){if(!canRunWhileTaskAwaitsCompletion({directory,normalizedTool:normalized,args:completionArgs,awaitingTaskId:taskAwaitingCompletion,requestedTaskId}))throw Error(completionGateViolationMessage(taskAwaitingCompletion))}}if(!isTaskToolId(input.tool))return;let args2=output.args;if(!args2)return;let subagentType=args2.subagent_type;if(typeof subagentType!=="string")return;let targetAgent=stripKnownSwarmPrefix(subagentType);if(!backgroundSubagentsEnabled&&isBackgroundTrue(args2.background)&&isKnownCanonicalRole(targetAgent))throw Error(SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE);if(targetAgent==="reviewer"||targetAgent==="test_engineer"){let routedTaskId=null,routeDispatchStarted=!1;try{let reviewSession=swarmState.agentSessions.get(input.sessionID);if(reviewSession){let activePrReviewBinding=await readPrReviewReentryBindingContext(directory,input.sessionID),reviewTaskId=await resolveEvidenceTaskId(args2,reviewSession,directory,activePrReviewBinding?{allowSessionFallback:!1}:void 0),changedFiles=reviewTaskId?getModifiedFilesForTask(reviewSession,reviewTaskId):[],routeTaskId=reviewTaskId??`unresolved-${input.callID}`;routedTaskId=routeTaskId,markStageBRouteRequired(reviewSession,routeTaskId);let pendingRoute=buildReviewRoutePending({sessionId:input.sessionID,taskId:routeTaskId});if(await persistReviewRouteReceipt({projectRoot:directory,receipt:pendingRoute}),routeDispatchStarted=!0,rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),pendingRoute),changedFiles.length===0){let routerError=buildReviewRouteRouterError({code:"NO_CHANGED_FILES",sessionId:input.sessionID,taskId:routeTaskId});await persistReviewRouteReceipt({projectRoot:directory,receipt:routerError}),rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),routerError)}else{let routing=await routeReviewForChanges(directory,changedFiles),routeReceipt=buildReviewRouteReceipt({sessionId:input.sessionID,taskId:routeTaskId,complexity:routing.depth,semanticRisk:routing.reason,requiredReviewers:Array.from({length:routing.reviewerCount},(_,index)=>`${routeTaskId}:reviewer:${index+1}`),requiredTestEngineers:Array.from({length:routing.testEngineerCount},(_,index)=>`${routeTaskId}:test_engineer:${index+1}`)});if(await persistReviewRouteReceipt({projectRoot:directory,receipt:routeReceipt}),rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),routeReceipt),shouldParallelizeReview(routing))pushAdvisory(reviewSession,`REVIEW ROUTING: High complexity detected (${routing.reason}). Consider parallel review: ${routing.reviewerCount} reviewers, ${routing.testEngineerCount} test engineers recommended.`)}}}catch(error49){let detail=error49 instanceof Error?error49.message:String(error49);if(!routeDispatchStarted){warn(`[delegation-gate] review route dispatch could not establish its pending receipt: ${detail}`);return}let routerError=buildReviewRouteRouterError({code:/unavailable|timed out|timeout|not found/i.test(detail)?"ROUTER_UNAVAILABLE":"ROUTER_FAILED",sessionId:input.sessionID,taskId:routedTaskId??`unresolved-${input.callID}`,detail});try{if(await persistReviewRouteReceipt({projectRoot:directory,receipt:routerError}),routedTaskId)rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routedTaskId),routerError)}catch(persistError){warn(`[delegation-gate] review route receipt was not recorded: ${detail}; router-error persistence failed: ${persistError instanceof Error?persistError.message:String(persistError)}`)}}}if(targetAgent==="coder"||targetAgent==="reviewer"){let acceptancePromptText=ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
1230
1231
  `),acceptanceCheck=validateCoderReviewerAcceptanceField(acceptancePromptText);if(!acceptanceCheck.valid){let detail=acceptanceCheck.reason==="acceptance_field_empty"?"its ACCEPTANCE field is present but empty/whitespace-only":"it has no ACCEPTANCE field";throw Error(`ACCEPTANCE_FIELD_REQUIRED: the ${targetAgent} delegation was blocked because ${detail}. `+"Every coder/reviewer dispatch MUST carry a non-empty ACCEPTANCE: line in its prompt — the mapped FR-###/SC-### ids "+"(for a single-task dispatch the delegation gate injects their verbatim requirement text from .swarm/spec.md automatically; phase/final-council multi-task reviewer dispatches are NOT auto-injected and must paste the verbatim text yourself) when the task maps to one or more spec requirements, or a one-line task-derived statement of what DONE looks like otherwise (see the ACCEPTANCE FIELD RESOLUTION section of your system prompt and .swarm/spec.md). Add an ACCEPTANCE: line to the delegation prompt and re-dispatch. Do NOT investigate the installed swarm plugin package (node_modules/opencode-swarm, "+"~/.cache/opencode) — the fix is in your dispatch content, not in plugin internals. If this same error "+"repeats after 2 fix attempts, STOP and present the blocker to the user.")}let coverageResult,coverageTaskId=null;try{let coveragePlan=await _internals80.loadPlanJsonOnly(directory);if(coveragePlan){let coveragePlanTaskContext=collectPlanTaskIdContextFromPhases(coveragePlan.phases);if(coverageTaskId=resolveDelegatedPlanTaskId(args2,toTaskIdPlanContextOptions(coveragePlanTaskContext)),coverageTaskId){let coverageTask=coveragePlan.phases.flatMap((phase)=>phase.tasks).find((t)=>t.id===coverageTaskId),frRefs=coverageTask?.fr_refs;if(coverageTask&&Array.isArray(frRefs)&&frRefs.length>0){let specText=await fs54.promises.readFile(path88.join(directory,".swarm","spec.md"),"utf8");injectSpecRequirementsIntoAcceptance({args:args2,frRefs,specText});let effectiveAcceptanceText=ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
1231
- `);coverageResult=checkAcceptanceCoversFrRefs({acceptanceText:effectiveAcceptanceText,frRefs,specText})}}}}catch{coverageResult=void 0}if(coverageResult&&coverageResult.covered===!1)throw buildAcceptanceCoverageMismatchError({targetAgent,coverageTaskId,coverageResult})}if(TASK_GATE_AGENTS.has(targetAgent)){let isPrReviewReentryAgent=targetAgent==="reviewer"||targetAgent==="test_engineer";if(isPrReviewReentryAgent&&swarmState.pendingRehydrations.size>0)await Promise.allSettled([...swarmState.pendingRehydrations]);let stageBSession=ensureAgentSession(input.sessionID,void 0,directory),activePrReviewBinding=isPrReviewReentryAgent?await readPrReviewReentryBindingContext(directory,input.sessionID):null,resolvedTaskId=await resolveEvidenceTaskId(args2,stageBSession,directory,activePrReviewBinding?{allowSessionFallback:!1}:void 0),candidateTaskIds=new Set;if(resolvedTaskId)candidateTaskIds.add(resolvedTaskId);let dispatchPlan=await loadPlanJsonOnly(directory);if(dispatchPlan){let knownIds=new Set(dispatchPlan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))),dispatchText=[args2.prompt,args2.description,args2.task,args2.input].filter((value)=>typeof value==="string").join(`
1232
+ `);coverageResult=checkAcceptanceCoversFrRefs({acceptanceText:effectiveAcceptanceText,frRefs,specText})}}}}catch{coverageResult=void 0}if(coverageResult&&coverageResult.covered===!1)throw buildAcceptanceCoverageMismatchError({targetAgent,coverageTaskId,coverageResult})}if(TASK_GATE_AGENTS.has(targetAgent)){let isPrReviewReentryAgent=targetAgent==="reviewer"||targetAgent==="test_engineer";if(isPrReviewReentryAgent&&swarmState.pendingRehydrations.size>0)await Promise.allSettled([...swarmState.pendingRehydrations]);let stageBSession=ensureAgentSession(input.sessionID,void 0,directory),activePrReviewBinding=isPrReviewReentryAgent?await readPrReviewReentryBindingContext(directory,input.sessionID):null,resolvedTaskId=await resolveEvidenceTaskId(args2,stageBSession,directory,evidenceTaskResolutionOptions(targetAgent,activePrReviewBinding?!1:void 0)),candidateTaskIds=new Set;if(resolvedTaskId)candidateTaskIds.add(resolvedTaskId);let dispatchPlan=await loadPlanJsonOnly(directory);if(dispatchPlan&&!isExplicitTaskEvidenceAgent(targetAgent)){let knownIds=new Set(dispatchPlan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))),dispatchText=[args2.prompt,args2.description,args2.task,args2.input].filter((value)=>typeof value==="string").join(`
1232
1233
  `);for(let match of dispatchText.matchAll(/(?:task-)?(\d+\.\d+(?:\.\d+)*)/gi))if(match[1]&&knownIds.has(match[1]))candidateTaskIds.add(match[1])}let generations=new Map,{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot3,readTaskEvidence:readTaskEvidence3}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));if(activePrReviewBinding&&!resolvedTaskId&&isPrReviewReentryAgent){if(stageBSession.taskWorkflowStates.size>0||dispatchPlan)throw Error(`TASK_WORKFLOW_TASK_ID_REQUIRED: cannot dispatch ${targetAgent} for PR-review re-entry without an explicit task_id or task identifier in the prompt while a plan or task workflow state exists. Bind the re-entry to the exact task before dispatching; refusing to guess from session or plan state protects parallel tasks from cross-attribution.`);let{reserveActivePrReviewReentryAuthorization}=await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate));if(await reserveActivePrReviewReentryAuthorization(directory,input.sessionID,{role:targetAgent==="test_engineer"?"test_engineer":"reviewer",callID:input.callID})){rememberStageBDispatchGenerations(input.callID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,null),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED",standalonePrReviewReentry:!0}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}if(await readPrReviewReentryBindingContext(directory,input.sessionID))throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot dispatch ${targetAgent} without a task workflow because its one-use PR-review re-entry authorization was already consumed or is unavailable. Issue a fresh authorization immediately before the direct Task dispatch.`)}for(let taskId of candidateTaskIds){let workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,taskId));if(taskId===resolvedTaskId&&await isCouncilGateActive(directory,config2.council)){if(!stageBSession.taskCouncilWorkflowGeneration)stageBSession.taskCouncilWorkflowGeneration=new Map;if(!stageBSession.taskCouncilWorkflowGeneration.has(taskId))stageBSession.taskCouncilWorkflowGeneration.set(taskId,workflow.generation)}if(targetAgent!=="reviewer"&&targetAgent!=="test_engineer"){generations.set(taskId,workflow.generation);continue}if(workflow.authoritative&&(workflow.state==="pre_check_passed"||workflow.state==="reviewer_run")){generations.set(taskId,workflow.generation);continue}if(taskId===resolvedTaskId){let{reserveActivePrReviewReentryAuthorization}=await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate));if(await reserveActivePrReviewReentryAuthorization(directory,input.sessionID,{role:targetAgent==="test_engineer"?"test_engineer":"reviewer",callID:input.callID})){rememberStageBDispatchGenerations(input.callID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}let stageARemediation=workflow.state==="rework_required"?"Remediation: if the Stage B verdict did not require a code change, call recover_rework_task for task "+taskId+" (architect-only, audited; requires green secretscan AND sast_scan evidence newer than the verdict — normally from a fresh pre_check_batch run; unavailable when SAST is disabled), then re-dispatch. "+"Otherwise delegate the coder to repair the code, re-run pre_check_batch, and re-dispatch once stage_a_passed has fired.":`Remediation: run pre_check_batch on the task's changed files first. If pre_check_batch passes but the task remains coder_delegated (typical after /swarm reset-session), run /swarm recover ${taskId} to repair Stage A attribution, then re-dispatch.`;throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot dispatch ${targetAgent} for task ${taskId} from ${workflow.state}. Stage B (${targetAgent}) requires the task to be at pre_check_passed (or later) — a state written only by the stage_a_passed transition, which is emitted when pre_check_batch completes with the task correctly attributed. `+stageARemediation+(targetAgent==="reviewer"||targetAgent==="test_engineer"?" For PR-review re-entry outside the task workflow, issue a one-use authorization with authorize_pr_review_reentry immediately before the Task dispatch.":""))}}rememberStageBDispatchGenerations(input.callID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}if(targetAgent!=="coder")return;let session=ensureAgentSession(input.sessionID,void 0,directory);if(!session||!session.taskWorkflowStates)return;let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,readTaskEvidenceState:readTaskEvidenceState2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),requestedScopeTaskId=typeof args2.task_id==="string"?args2.task_id.trim():typeof args2.taskId==="string"?args2.taskId.trim():"",classifiedFeedbackScope=isStrictTaskId(requestedScopeTaskId)?await resolvePrFeedbackScopeDeclaration(directory,input.sessionID,requestedScopeTaskId):null,resolvedPreflightTaskId=classifiedFeedbackScope?null:await resolveEvidenceTaskId(args2,session,directory),preflightPlan=classifiedFeedbackScope?null:await loadPlanJsonOnly(directory),preflightTaskId=resolvedPreflightTaskId&&preflightPlan?.phases.some((phase)=>phase.tasks.some((task)=>task.id===resolvedPreflightTaskId))?resolvedPreflightTaskId:null,preflightEvidenceState=preflightTaskId?await readTaskEvidenceState2(directory,preflightTaskId):null;if(preflightEvidenceState?.kind==="unparseable"){let errorName=preflightEvidenceState.error instanceof Error?preflightEvidenceState.error.name:"UnknownError";throw Error(`TASK_EVIDENCE_UNREADABLE: Task ${preflightTaskId} evidence at ${preflightEvidenceState.evidencePath} is corrupt or from an incompatible build (${errorName}); refusing to treat it as idle. Repair or remove the evidence file (repair_gate_evidence) before dispatching.`)}let preflightEvidence=preflightEvidenceState?.kind==="ok"?preflightEvidenceState.evidence:null,preflightWorkflow=getTaskWorkflowSnapshot2(preflightEvidence);if(preflightTaskId){if(await enforceCoderRetryEscalation({directory,taskId:preflightTaskId,generation:preflightWorkflow.generation,retryEpoch:preflightWorkflow.retryEpoch,retryCount:preflightWorkflow.retryCount,retryHistory:preflightWorkflow.retryHistory,criticSatisfied:preflightEvidence?.gates.critic_sounding_board!=null}),preflightWorkflow.state==="coder_delegated"){if(!(hasActiveTurboMode(input.sessionID)&&!preflightTaskId.startsWith("3.")))throw Error(`STAGE_A_REQUIRED: Task ${preflightTaskId} has an accepted coder mutation that has not passed pre_check_batch. Run Stage A first. If Stage A fails, the task becomes rework_required and the same-task coder may repair it. Do not send known-broken output to reviewer.`)}}let preparedScope;try{preparedScope=await prepareCoderScope(directory,input,args2)}catch(error49){if(preflightTaskId){let failed=await transitionTaskWorkflowEvidence2(directory,preflightTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration:preflightWorkflow.generation,transitionId:`coder-preflight:${input.callID}`}),failedWorkflow=getTaskWorkflowSnapshot2(failed);if(failedWorkflow.retryCount>=3)await emitCoderRetryEscalation(directory,{taskId:preflightTaskId,generation:failedWorkflow.generation,retryEpoch:failedWorkflow.retryEpoch,rejectionCount:failedWorkflow.retryCount,rejectionHistory:failedWorkflow.retryHistory,action:"sounding_board_consultation"})}throw error49}let{taskId:incomingCoderTaskId}=preparedScope;if(incomingCoderTaskId)session.lastCoderDelegationTaskId=incomingCoderTaskId;let coderEvidence=incomingCoderTaskId?await readTaskEvidence2(directory,incomingCoderTaskId):null,coderWorkflow=getTaskWorkflowSnapshot2(coderEvidence),coderDispatchGeneration=coderWorkflow.generation;if(incomingCoderTaskId){if(incomingCoderTaskId!==preflightTaskId)await enforceCoderRetryEscalation({directory,taskId:incomingCoderTaskId,generation:coderWorkflow.generation,retryEpoch:coderWorkflow.retryEpoch,retryCount:coderWorkflow.retryCount,retryHistory:coderWorkflow.retryHistory,criticSatisfied:coderEvidence?.gates.critic_sounding_board!=null})}let reserveBackgroundCoderIfNeeded=async(maxConcurrent2)=>{if(!backgroundSubagentsEnabled||!isBackgroundTrue(args2.background))return;try{await _internals80.maintainBackgroundDelegationsForDispatch(directory,{lockTimeoutMs:1000,reason:"admission"})}catch(error49){warn(`[delegation-gate] pre-admission background maintenance skipped: ${error49 instanceof Error?error49.message:String(error49)}`)}let occupiedTaskIds=[...session.taskWorkflowStates.entries()].filter(([,state2])=>state2==="coder_delegated").map(([taskId])=>taskId),claim=await _internals80.reserveBackgroundCoderSlotForDispatch(directory,{parentSessionId:input.sessionID,planTaskId:incomingCoderTaskId||null,callID:input.callID,maxConcurrent:maxConcurrent2,occupiedTaskIds});if(!claim.ok){let detail=claim.detail?` ${claim.detail}`:"",code=claim.reason==="capacity"?"PARALLEL_SLOTS_EXHAUSTED":claim.reason==="duplicate_task"||claim.reason==="duplicate_call"?"BACKGROUND_CODER_TASK_RESERVED":"BACKGROUND_CODER_RESERVATION_UNCERTAIN";throw Error(`${code}: background coder admission was blocked (${claim.reason}).${detail}`)}backgroundCoderReservationByCallID.set(input.callID,claim.reservation)};if(preparedScope.kind==="pr_feedback"){await reserveBackgroundCoderIfNeeded(1);try{if(shouldRememberCoderTaskChangeContext(preparedScope.declaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,preparedScope.declaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,preparedScope.binding),await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background)}catch(error49){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error49}return}let plan=preparedScope.plan,profile=plan.execution_profile,parallelEnabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=session.maxConcurrencyOverride??maxConcurrent,scopeAllowsParallel=scopeVerdictAllowsParallel(directory,plan),standardWorktreeIsolationActive=parallelEnabled&&effectiveMaxConcurrent>1&&!hasActiveLeanTurbo(input.sessionID),parallelModeActive=standardWorktreeIsolationActive&&scopeAllowsParallel,criticPolicy=resolvePlanCriticPolicyForExecution(directory,plan,session.qaGateSessionOverrides??{});if(log(`[delegation-gate] critic_pre_plan policy task=${incomingCoderTaskId??"unknown"} required=${criticPolicy.required} source=${criticPolicy.source}`),criticPolicy.required)await assertPlanCriticApprovedForExecution(directory,plan);let{declaredFiles:incomingCoderDeclaredFiles,binding:correlatedBinding}=preparedScope;for(let task of plan.phases.flatMap((phase)=>phase.tasks)){let taskId=task.id,evidenceState=await readTaskEvidenceState2(directory,taskId);if(evidenceState.kind==="unparseable"){if(incomingCoderTaskId&&taskId===incomingCoderTaskId){let errorName=evidenceState.error instanceof Error?evidenceState.error.name:"UnknownError";throw Error(`TASK_EVIDENCE_UNREADABLE: Task ${taskId} evidence at ${evidenceState.evidencePath} is corrupt or from an incompatible build (${errorName}); refusing to treat it as idle. Repair or remove the evidence file (repair_gate_evidence) before dispatching.`)}warn(`[delegation-gate] Task ${taskId} evidence at ${evidenceState.evidencePath} is corrupt or from an incompatible build — treating as idle for this dispatch. Repair it before the task's next delegation.`)}let durableWorkflow=getTaskWorkflowSnapshot2(evidenceState.kind==="ok"?evidenceState.evidence:null),state2=durableWorkflow.authoritative?durableWorkflow.state:"idle";if(session.taskWorkflowStates.set(taskId,state2),updateTaskWorkflowCache(session,taskId,durableWorkflow),state2!=="coder_delegated")continue;let freshnessThreshold=session.sessionRehydratedAt>0?session.sessionRehydratedAt:session.lastPhaseCompleteTimestamp??0,hasCurrentSessionCoderDelegation=(swarmState.delegationChains.get(input.sessionID)??[]).some((d)=>stripKnownSwarmPrefix(d.to)==="coder"&&d.timestamp>freshnessThreshold);if(!durableWorkflow.authoritative&&!hasCurrentSessionCoderDelegation){session.taskWorkflowStates.set(taskId,"idle"),warn(`[delegation-gate] Reset stale coder_delegated state for task ${taskId} — `+"no coder delegation found in current session.");continue}if(hasActiveTurboMode(input.sessionID)){if(!taskId.startsWith("3."))continue}if(parallelModeActive&&incomingCoderTaskId&&taskId!==incomingCoderTaskId)continue;throw Error(`STAGE_A_REQUIRED: Task ${taskId} has an accepted coder mutation that has not passed pre_check_batch. Run Stage A first. If Stage A fails, the task becomes rework_required and the same-task coder may repair it. Do not send known-broken output to reviewer.`)}if(parallelModeActive){let coderDelegatedCount=0;for(let s of session.taskWorkflowStates.values())if(s==="coder_delegated")coderDelegatedCount++;if(coderDelegatedCount>=effectiveMaxConcurrent)throw Error(`PARALLEL_SLOTS_EXHAUSTED: ${coderDelegatedCount} coder task(s) are awaiting review (max_concurrent_tasks=${effectiveMaxConcurrent}). Dispatch reviewer/test_engineer for an in-flight coder task before starting another coder.`)}if(standardWorktreeSerializationSessions.has(input.sessionID)){if(checkStandardWorktreeSerializationRelease(input.sessionID,resolveWorktreeIsolationConfig(config2)),standardWorktreeSerializationSessions.has(input.sessionID))throw Error("STANDARD_WORKTREE_ISOLATION_SERIALIZED: prior standard worktree isolation setup failed in this session; wait for the active coder task to finish before dispatching another coder.")}await reserveBackgroundCoderIfNeeded(parallelModeActive?effectiveMaxConcurrent:1);try{if(!parallelModeActive){if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration)}if(!standardWorktreeIsolationActive){if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,correlatedBinding),await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background);return}let resolvedTaskId=incomingCoderTaskId,laneScope=correlatedBinding.files;await precreateStandardWorktreeSession({config:config2,directory,parentSessionID:input.sessionID,callID:input.callID,taskId:resolvedTaskId??sanitizeWorktreeTaskId(input.callID),planTaskId:resolvedTaskId??void 0,reservationId:backgroundCoderReservationByCallID.get(input.callID)?.reservationId??buildBackgroundCoderReservationId({parentSessionId:input.sessionID,planTaskId:resolvedTaskId,callID:input.callID}),generation:coderDispatchGeneration,description:typeof args2.description==="string"?args2.description:void 0,outputArgs:args2,scope:laneScope&&laneScope.length>0&&resolvedTaskId?{taskId:resolvedTaskId,files:laneScope}:void 0});let standardDispatch=standardWorktreeByCallID.get(input.callID);if(standardDispatch){if(resolvedTaskId)try{let childSessionId=typeof args2.task_id==="string"?args2.task_id.trim():"";if(!childSessionId||childSessionId===input.sessionID)throw Error("SCOPE_CHILD_IDENTITY_MISSING: worktree dispatch did not return a distinct child session id");await savePlan(standardDispatch.handle.worktreePath,plan,{preserveCompletedStatuses:!1});let childBinding=deriveChildScopeBinding(correlatedBinding,{childDirectory:standardDispatch.handle.worktreePath,childSessionId,parentCallId:input.callID});await publishScopeBinding(input.callID,standardDispatch.handle.worktreePath,childBinding);let childSession=ensureAgentSession(childSessionId,"coder",standardDispatch.handle.worktreePath);childSession.currentTaskId=childBinding.taskId,childSession.declaredCoderScope=[...childBinding.files]}catch(error49){throw clearPublishedScopeBindings(input.callID),await cleanupStandardWorktreeForCallId(input.callID,"denied",directory,resolveWorktreeIsolationConfig(config2).worktree_dir),error49}if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,standardDispatch.handle.worktreePath,coderDispatchGeneration)}else{if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration);let degradation=getStandardWorktreeDegradationReason(input.sessionID);if(degradation)try{appendCoreEventSync(directory,{type:"worktree_isolation_degraded",timestamp:new Date().toISOString(),sessionId:input.sessionID,callId:input.callID,taskId:incomingCoderTaskId,reason:degradation.reason.length>500?`${degradation.reason.slice(0,500)}… (truncated)`:degradation.reason,degradedAt:new Date(degradation.at).toISOString()})}catch(eventError){log(`[delegation-gate] worktree_isolation_degraded event write failed: ${eventError instanceof Error?eventError.message:String(eventError)}`)}await publishScopeBinding(input.callID,directory,correlatedBinding)}await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background,standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:incomingCoderTaskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner)}:void 0)}catch(error49){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error49}},messagesTransform:async(_input,output)=>{let messages=output.messages;if(!messages||messages.length===0)return;let lastUserMessageIndex=-1;for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="user"){lastUserMessageIndex=i;break}if(lastUserMessageIndex===-1)return;let lastUserMessage=messages[lastUserMessageIndex];if(!lastUserMessage?.parts)return;let agent=lastUserMessage.info?.agent;if(agent==="")return;let strippedAgent=agent?stripKnownSwarmPrefix(agent):void 0;if(strippedAgent&&strippedAgent!=="architect")return;let textPartIndex=lastUserMessage.parts.findIndex((p)=>p?.type==="text"&&p.text!==void 0);if(textPartIndex===-1)return;let textPart=lastUserMessage.parts[textPartIndex],text=textPart.text??"",taskDisclosureSessionID=lastUserMessage.info?.sessionID;if(taskDisclosureSessionID){let currentTaskIdForWindow=ensureAgentSession(taskDisclosureSessionID,void 0,directory).currentTaskId;if(currentTaskIdForWindow){let taskLineRegex=/^[ \t]*-[ \t]*(?:\[[ x]\][ \t]+)?(\d+\.\d+(?:\.\d+)*)[:. ].*/gm,taskLines=[];taskLineRegex.lastIndex=0;let regexMatch=taskLineRegex.exec(text);while(regexMatch!==null)taskLines.push({line:regexMatch[0],taskId:regexMatch[1],index:regexMatch.index}),regexMatch=taskLineRegex.exec(text);if(taskLines.length>5){let currentIdx=taskLines.findIndex((t)=>t.taskId===currentTaskIdForWindow),windowStart=Math.max(0,currentIdx-2),windowEnd=Math.min(taskLines.length-1,currentIdx+3),visibleTasks=taskLines.slice(windowStart,windowEnd+1),hiddenBefore=windowStart,hiddenAfter=taskLines.length-1-windowEnd,totalTasks=taskLines.length,visibleCount=visibleTasks.length,firstTaskIndex=taskLines[0].index,lastTask=taskLines[taskLines.length-1],lastTaskEnd=lastTask.index+lastTask.line.length,before=text.slice(0,firstTaskIndex),after=text.slice(lastTaskEnd),visibleLines=visibleTasks.map((t)=>t.line).join(`
1233
1234
  `),trimComment=`[Task window: showing ${visibleCount} of ${totalTasks} tasks]`,trimmedMiddle=(hiddenBefore>0?`[...${hiddenBefore} tasks hidden...]
1234
1235
  `:"")+visibleLines+(hiddenAfter>0?`
@@ -1238,7 +1239,7 @@ ${trimComment}${after}`}}}let sessionID=lastUserMessage.info?.sessionID,planTask
1238
1239
  ${parallelGuidance??"[NEXT] Execute the next gate for the current task."}`}else guidance=parallelGuidance??"[NEXT] Begin the first plan task and run gates sequentially.";let carrierIdx=messages.findIndex((m)=>m&&isGuidanceCarrier(m)),insertIdx=carrierIdx>=0?carrierIdx+1:0;insertGuidanceCarrier(messages,"delegation",guidance,insertIdx)}}let warnings=[];if(text.length>delegationMaxChars)warnings.push(`Delegation exceeds recommended size (${text.length} chars, limit ${delegationMaxChars}). Consider splitting into smaller tasks.`);if(isCoderDelegation){let fileMatches=text.match(/^FILE:/gm);if(fileMatches&&fileMatches.length>1)warnings.push(`Multiple FILE: directives detected (${fileMatches.length}). Each coder task should target ONE file.`)}if(isCoderDelegation){let taskMatches=text.match(/^TASK:/gm);if(taskMatches&&taskMatches.length>1)warnings.push(`Multiple TASK: sections detected (${taskMatches.length}). Send ONE task per coder call.`)}if(isCoderDelegation){let batchingPattern=/\b(?:and also|then also|additionally|as well as|along with|while you'?re at it)[.,]?\b/gi,batchingMatches=text.match(batchingPattern);if(batchingMatches&&batchingMatches.length>0)warnings.push(`Batching language detected (${batchingMatches.join(", ")}). Break compound objectives into separate coder calls.`)}if(isCoderDelegation){let taskLine=extractTaskLine(text);if(taskLine){if(/\s+and\s+(update|add|remove|modify|refactor|implement|create|delete|fix|change|build|deploy|write|test|move|rename|extend|extract|convert|migrate|upgrade|replace)\b/i.test(taskLine))warnings.push('TASK line contains "and" connecting separate actions')}}if(isCoderDelegation&&sessionID){let delegationChain=swarmState.delegationChains.get(sessionID);if(delegationChain&&delegationChain.length>=2){let coderIndices=[];for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){if(coderIndices.unshift(i),coderIndices.length===2)break}if(coderIndices.length===2){let prevCoderIndex=coderIndices[0],betweenCoders=delegationChain.slice(prevCoderIndex+1),hasReviewer=betweenCoders.some((d)=>stripKnownSwarmPrefix(d.to)==="reviewer"),hasTestEngineer=betweenCoders.some((d)=>stripKnownSwarmPrefix(d.to)==="test_engineer"),session=ensureAgentSession(sessionID,void 0,directory),priorTaskStuckAtCoder=priorCoderTaskId!==null&&getTaskState(session,priorCoderTaskId)==="coder_delegated";if(!hasReviewer||!hasTestEngineer||priorTaskStuckAtCoder){if(session.qaSkipCount>=1){telemetry.qaSkipViolation(_input.sessionID,session.agentName,session.qaSkipCount+1);let skippedTasks=session.qaSkipTaskIds.join(", ");throw Error(`\uD83D\uDED1 QA GATE ENFORCEMENT: ${session.qaSkipCount+1} consecutive coder delegations without reviewer/test_engineer. Skipped tasks: [${skippedTasks}]. DELEGATE to reviewer and test_engineer NOW before any further coder work.`)}session.qaSkipCount++,session.qaSkipTaskIds.push(currentTaskId??"unknown"),warnings.push("⚠️ PROTOCOL VIOLATION: Previous coder task completed, but QA gate was skipped. "+"You MUST delegate to reviewer (code review) and test_engineer (test execution) before starting a new coder task. Review RULES 7-8 in your system prompt.")}}}}if(warnings.length===0)return;let warningText=`⚠️ BATCH DETECTED: Your coder delegation appears to contain multiple tasks.
1239
1240
  Rule 3: ONE task per coder call. Split this into separate delegations.
1240
1241
  ${warnings.map((w)=>`Detected signal: ${w}`).join(`
1241
- `)}`,batchWarnCarrierIdx=messages.findIndex((m)=>m&&isGuidanceCarrier(m)),batchWarnInsertIdx=batchWarnCarrierIdx>=0?batchWarnCarrierIdx+1:0;insertGuidanceCarrier(messages,"delegation",warningText,batchWarnInsertIdx)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=isTaskToolId(input.tool);if(!input.sessionID){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let session=swarmState.agentSessions.get(input.sessionID);if(!session){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let{qaGateSessionOverrides}=ensureAgentSession(input.sessionID,void 0,directory),councilActive=await isCouncilGateActive(directory,config2.council,qaGateSessionOverrides??{});if(normalized==="submit_council_verdicts"){try{let result=typeof _output==="string"?JSON.parse(_output):_output;if(result&&typeof result==="object"&&result.success===!0&&typeof result.overallVerdict==="string"){let directArgs=input.args,storedArgs=getStoredInputArgs(input.callID),taskIdRaw=directArgs?.taskId??storedArgs?.taskId,taskId=typeof taskIdRaw==="string"?taskIdRaw:null;if(taskId){if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let priorRewarded=session.taskCouncilApproved.get(taskId)?.rewarded===!0;if(session.taskCouncilApproved.set(taskId,{verdict:result.overallVerdict,roundNumber:typeof result.roundNumber==="number"?result.roundNumber:1,quorumSize:typeof result.quorumSize==="number"?result.quorumSize:1,rewarded:priorRewarded}),councilActive&&result.overallVerdict==="APPROVE"&&result.allCriteriaMet===!0&&(result.requiredFixesCount??0)===0)pushAdvisory(session,`Council approved task ${taskId}. Call update_task_status with status="completed" so the central plan/evidence transaction can commit it.`)}}}catch(err){log(`[delegation-gate] toolAfter submit_council_verdicts: failed to parse output: ${err instanceof Error?err.message:String(err)}`)}return}if(isTaskTool2){let standardDispatch=standardWorktreeByCallID.get(input.callID),directArgsRaw=input.args,directArgs=directArgsRaw?{...directArgsRaw}:void 0;if(standardDispatch&&directArgs)if(standardDispatch.planTaskId)directArgs.task_id=standardDispatch.planTaskId;else delete directArgs.task_id;let storedArgs=getStoredInputArgs(input.callID),subagentType=directArgs?.subagent_type??storedArgs?.subagent_type,backgroundResultIsRunning=outputLooksLikeBackgroundRunning(_output),outputTerminalState=_output?.state,isTerminalFailure=outputTerminalState==="failed"||outputTerminalState==="error"||outputTerminalState==="cancelled"||outputTerminalState==="canceled";if(!isTerminalFailure&&typeof subagentType==="string"&&isKnownCanonicalRole(stripKnownSwarmPrefix(subagentType))&&(isBackgroundTrue(directArgs?.background)||isBackgroundTrue(storedArgs?.background)||backgroundResultIsRunning)){let coderReservation=backgroundCoderReservationByCallID.get(input.callID),backgroundRecordDurable=!backgroundSubagentsEnabled,backgroundOwnershipDurable=backgroundRecordDurable,backgroundCorrelationConflict=!1;if(backgroundSubagentsEnabled){let protectUntrackedBackgroundWorktree=async(taskId,reason)=>{if(!standardDispatch)return{detail:"no isolated worktree ownership tag was available",durable:!1};let detail,durable=!1;try{let preserved=await _internals79.preserveBackgroundWorktreeOwnershipForCallId(input.callID);durable=preserved.outcome==="preserved",detail=durable?`ownership tag ${preserved.tag} at ${preserved.ref}`:`ownership preservation failed: ${preserved.error??preserved.outcome}`}catch(err){detail=`ownership preservation threw: ${err instanceof Error?err.message:String(err)}`}return recordWorktreeMergeFailure(taskId??void 0,{outcome:"failed",stage:"background-correlation-persist",message:`${reason}; ${detail}. Automatic orphan reclamation is blocked until the dispatch is recovered.`,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,queuedAt:Date.now()}),{detail,durable}};try{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope)),{buildPromptSnapshot,findByCorrelationIdDetailed}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshotAsync:captureWorkspaceSnapshotAsync2}=await Promise.resolve().then(() => (init_workspace_snapshot(),exports_workspace_snapshot)),{subagentSessionId,jobId}=extractDispatchIds2(_output);if(!subagentSessionId&&!backgroundResultIsRunning){if(await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID);return}if(subagentSessionId){let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory),scope=session.declaredCoderScope&&session.declaredCoderScope.length>0?session.declaredCoderScope.join(","):evidenceTaskId,prHeadShaRaw=mergedArgs.prHeadSha??mergedArgs.pr_head_sha,prHeadSha=typeof prHeadShaRaw==="string"?prHeadShaRaw:null,taskChangeContext=stripKnownSwarmPrefix(subagentType)==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,fallbackWorkspace=taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:await captureWorkspaceSnapshotAsync2(directory,{prHeadSha,scope}),pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:fallbackWorkspace,taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(stripKnownSwarmPrefix(subagentType))?stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId??""):void 0,worktree:standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner),reservationId:standardDispatch.reservationId,generation:standardDispatch.generation}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwnerRead=findByCorrelationIdDetailed(directory,subagentSessionId);if(existingOwnerRead.status==="uncertain")throw Error(`delegation store unreadable after ${existingOwnerRead.attempts} attempts (${existingOwnerRead.reason}); cannot verify the existing owner for background correlation ${subagentSessionId}`);let existingOwner=existingOwnerRead.value,pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals80.recordPendingDelegationForBackground(directory,pendingInput,{staleTimeoutMs:backgroundPendingTimeoutMs});if(backgroundRecordDurable=primaryOutcome.status==="recorded"||primaryOutcome.status==="duplicate",backgroundCorrelationConflict=primaryOutcome.status==="conflict",primaryOutcome.status==="conflict"){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"background correlation id conflicts with an existing immutable launch owner"),worktreeStatus=!standardDispatch?"No isolated worktree was attached to this conflicting call.":preservation.durable?`The current worktree was durably preserved with ${preservation.detail}.`:`The current worktree was not durably preserved (${preservation.detail}); automatic reclamation remains blocked pending recovery.`,reservationStatus=coderReservation?`The current reservation ${coderReservation.reservationId} was retained and was not bound to the conflicting correlation.`:primaryOutcome.record.coderReservationId?`No new reservation was present for this replay; the durable owner's reservation ${primaryOutcome.record.coderReservationId} remains unchanged.`:"No current or durable-owner coder reservation was present.";backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION CORRELATION CONFLICT: ${subagentType} (${subagentSessionId}) collided with a different durable launch owner (parent=${primaryOutcome.record.parentSessionId}, call=${primaryOutcome.record.callID}, agent=${primaryOutcome.record.swarmPrefixedAgent}, task=${primaryOutcome.record.planTaskId??"none"}). Inspect that existing owner and reconcile it before continuing. ${worktreeStatus} ${reservationStatus} No fallback owner was written and no reservation was bound. Do not abort, delete, or re-dispatch this correlation until reconciliation is complete. Do not advance task ${evidenceTaskId??"unknown"} until the collision is resolved.`)}else if(primaryOutcome.status==="failed"){if(backgroundRecordDurable=await _internals80.writeDelegationFallbackForBackground(directory,pendingInput)!==null,backgroundRecordDurable)warn(`[delegation-gate] background delegation ${subagentSessionId} persisted to the independent fallback artifact after the primary ledger write failed`)}if(!backgroundCorrelationConflict&&!backgroundRecordDurable){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"both background correlation stores failed");backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION UNTRACKED: ${subagentType} (${subagentSessionId}) launched, but both durable correlation stores failed. Recovery protection: ${preservation.detail}. Do not advance task ${evidenceTaskId??"unknown"} until the dispatch is recovered.`)}else if(!backgroundCorrelationConflict){if(backgroundOwnershipDurable=!0,coderReservation){if(!await _internals80.bindBackgroundCoderReservationForDispatch(directory,{...coderReservation,correlationId:subagentSessionId,generation:pendingInput.generation??1}))pushAdvisory(session,`BACKGROUND CODER RESERVATION UNBOUND: task ${evidenceTaskId??"unknown"} is durably tracked, but its pre-launch reservation could not be bound to ${subagentSessionId}. Further coder admission remains fail-closed until completion or recovery reconciles it.`)}}}else{let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch returned no trusted correlation id");backgroundOwnershipDurable=preservation.durable,warn("[delegation-gate] background dispatch had no correlation id (no jobId / no envelope) — not tracked"),pushAdvisory(session,`BACKGROUND DELEGATION UNCORRELATED: ${subagentType} launched without a trusted session correlation. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered or safely re-dispatched.`)}}catch(err){let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch correlation recording threw");backgroundOwnershipDurable=preservation.durable,warn(`[delegation-gate] background pending recording failed: ${err instanceof Error?err.message:String(err)}`),pushAdvisory(session,`BACKGROUND DELEGATION DURABILITY FAILURE: ${subagentType} launched, but its completion owner could not be persisted. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered.`)}}if(backgroundOwnershipDurable){let provisioningOwner=standardDispatch?.provisioningOwner??(standardDispatch?.reservationId!==void 0&&standardDispatch?.generation!==void 0?{reservationId:standardDispatch.reservationId,generation:standardDispatch.generation,branchName:standardDispatch.handle.branchName}:void 0);_internals79.removeWorktreeProvisioningOwner(directory,input.callID,provisioningOwner)}if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID)}if(!backgroundCorrelationConflict)backgroundCoderReservationByCallID.delete(input.callID);if(!backgroundResultIsRunning)clearPublishedScopeBindings(input.callID);return}let foregroundCoderTaskId=typeof subagentType==="string"&&stripKnownSwarmPrefix(subagentType)==="coder"?standardDispatch?.planTaskId??standardDispatch?.taskId??(typeof directArgs?.task_id==="string"?directArgs.task_id:typeof storedArgs?.task_id==="string"?storedArgs.task_id:null):null;clearPublishedScopeBindings(input.callID);try{if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs??{}};await recordPlanCriticApprovalSnapshotIfApplicable(directory,input,mergedArgs,_output)}catch(err){warn(`[delegation-gate] plan critic approval snapshot failed: ${err instanceof Error?err.message:String(err)}`)}if(typeof subagentType==="string"){let advisoryPrompt={...storedArgs??{},...directArgs??{}}.prompt;if(typeof advisoryPrompt==="string"&&advisoryPrompt.length>0)appendDelegationEnvelopeAdvisory(session,advisoryPrompt,{planTasks:[],validAgents:[...ALL_AGENT_NAMES]})}let standardWorktreeSettled=!standardDispatch,coderSettlementCommitted=!1,coderSettlementEvidence=null,isStandardWorktreeFailure=outputTerminalState==="cancelled"||outputTerminalState==="failed"||outputTerminalState==="error";if(standardDispatch&&!isStandardWorktreeFailure){let taskChangeContext=coderTaskChangeContextByCallID.get(input.callID);if(taskChangeContext)rememberCoderObservedFiles(input.callID,await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline));standardWorktreeByCallID.delete(input.callID),awaitingMergeByCallID.set(input.callID,{callID:input.callID,parentSessionID:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId,branch:standardDispatch.handle.branchName,worktreePath:standardDispatch.handle.worktreePath,mergeStrategy:standardDispatch.mergeStrategy,queuedAt:Date.now()});let observedForMerge=coderObservedFilesByCallID.get(input.callID);if(!Array.isArray(observedForMerge))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: isolated task ${standardDispatch.planTaskId??standardDispatch.taskId} changed files could not be proven from its clean launch baseline`);standardWorktreeSettled=(await finishStandardWorktreeDispatch(directory,standardDispatch,config2,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async(merged)=>{coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge),landedUnstaged:merged.strategy==="squash-unstaged"})).evidence,coderSettlementCommitted=!0}}).catch((err)=>{let reason=err instanceof Error?err.message:String(err);warn(`[delegation-gate] standard worktree merge-back failed for ${standardDispatch.taskId}: ${reason}`),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"merge-back",message:reason,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,completedAt:Date.now()});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID,void 0,directory);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_MERGE_FAILED: task ${standardDispatch.taskId} preserved at ${standardDispatch.handle.worktreePath}; reason: ${reason}.`),awaitingMergeByCallID.delete(input.callID)}))?.outcome==="merged"}if(standardDispatch&&isStandardWorktreeFailure){standardWorktreeByCallID.delete(input.callID);let reason=outputTerminalState==="cancelled"?"cancelled":"denied";await _internals79.preserveDirtyWorktreeForCallId(input.callID,reason,directory),closeProjectDb(standardDispatch.handle.worktreePath);let removal=await _internals79.removeWorktree(standardDispatch.handle.worktreePath,directory).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)recordDeadLaneReclaim(directory,{lanePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,reason:removalError}),pushAdvisory(ensureAgentSession(standardDispatch.parentSessionID,void 0,directory),`WORKTREE_LANE_STRANDED: lane ${standardDispatch.handle.worktreePath} could not be removed (${removalError}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`);await _internals79.postMergeCleanup(directory,standardDispatch.handle.branchName),awaitingMergeByCallID.delete(input.callID),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"task-result",message:`task terminated with ${outputTerminalState??"terminal-failure"}`});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID,void 0,directory);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_TASK_FAILED: task ${standardDispatch.taskId} terminated with ${outputTerminalState??"terminal-failure"}; worktree preserved and cleaned without merge-back.`)}let hasReviewer=!1,hasTestEngineer=!1;if(typeof subagentType==="string"){let targetAgent=stripKnownSwarmPrefix(subagentType);if(targetAgent==="reviewer")hasReviewer=!0;if(targetAgent==="test_engineer")hasTestEngineer=!0;let standalonePrReviewReentry=stageBDispatchContextByCallID.get(input.callID)?.standalonePrReviewReentry===!0;if(!councilActive&&!standalonePrReviewReentry){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],attributionResult=parsePerTaskVerdicts(outputText(_output));for(let err of attributionResult.errors)warn(`[delegation-gate] ${err}`);do{if(attributionResult.verdicts.size===0){let dispatchCtx=stageBDispatchContextByCallID.get(input.callID),expectedTasks=dispatchCtx?[...dispatchCtx.taskIds].join(", "):gateDispatchPrimaryTaskByCallID.get(input.callID)??"unknown";warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING: ${targetAgent} dispatch for call ${input.callID} returned no structured verdict lines. Expected tasks: ${expectedTasks}. Agent output must include [REVIEWED] or [TESTED] verdict lines.`);let failClosedTaskIds=dispatchCtx?[...dispatchCtx.taskIds]:gateDispatchPrimaryTaskByCallID.has(input.callID)?[gateDispatchPrimaryTaskByCallID.get(input.callID)]:[];for(let failTaskId of failClosedTaskIds){let failState=session.taskWorkflowStates.get(failTaskId);if(failState&&stageBEligibleStates.includes(failState))session.taskWorkflowStates.set(failTaskId,"rework_required"),session.stageBCompletion?.delete(failTaskId),warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING fail-closed: task ${failTaskId} → rework_required`)}break}let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state2]of session.taskWorkflowStates){if(!stageBEligibleStates.includes(state2))continue;if(!attributionResult.verdicts.has(taskId))continue;let eligibleState=state2,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`);continue}let verdictEntry=attributionResult.verdicts.get(taskId),dispatchCtxForVerdict=stageBDispatchContextByCallID.get(input.callID);if(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"&&verdictEntry?.verdict==="SKIPPED"){warn(`[delegation-gate] Stage B test gate SKIPPED (tests not run) for task ${taskId} from call ${input.callID} — leaving state ${state2} for test-gate re-dispatch; reviewer proof preserved`);continue}if(!(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"?verdictEntry?.verdict==="PASS":verdictEntry?.verdict==="APPROVED")){try{let rejected=await transitionTaskWorkflowEvidence2(directory,taskId,{type:"stage_b_failed",gate:targetAgent,expectedGeneration:launchGeneration,transitionId:`gate-failed:${input.callID}:${taskId}`});session.taskWorkflowStates.set(taskId,"rework_required"),session.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(session,taskId,getTaskWorkflowSnapshot2(rejected))}catch(err){warn(`[delegation-gate] Stage B rejection could not be persisted for ${taskId}: ${err instanceof Error?err.message:String(err)}`)}continue}let routeBinding=stageBRouteSlotByCallID.get(input.callID)?.get(taskId),legacyUnrouted=!isStageBRouteRequired(session,taskId)&&!routeBinding&&(()=>{try{return isLegacyTaskGateRequirementsChain(readTaskGateRequirementsReceiptsSync(directory,taskId))}catch{return!1}})(),existingRouteEvidence=getStageBRouteEvidence(session,taskId),prospectiveRouteEvidence=routeBinding?[...existingRouteEvidence.filter((entry)=>entry.role!==routeBinding.role||entry.sessionId!==routeBinding.sessionId||entry.taskId!==routeBinding.taskId||entry.callId!==routeBinding.callId||entry.childSessionId!==routeBinding.childSessionId||entry.generation!==routeBinding.generation),routeBinding]:getStageBRouteEvidence(session,taskId),routeEnforcementEnabled=config2.review_routing?.enforce_receipts??!0,routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:routeEnforcementEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:routeBinding?{role:routeBinding.role,identity:routeBinding.identity,callId:routeBinding.callId,childSessionId:routeBinding.childSessionId,generation:routeBinding.generation}:void 0});if(!routeDecision.canAdvance){warn(`[delegation-gate] Stage B route receipt blocked ${taskId}: ${routeDecision.reason??"unknown reason"}`);continue}let routeCompleteDecision=routeEnforcementEnabled&&routeBinding?enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:!0,requireEvidenceBindings:!0,requireCompleteEvidence:!0}):void 0,routeComplete=routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:routeDecision.canAdvance,routeEvidenceRollback=routeBinding?reserveStageBRouteEvidence(session,taskId,routeBinding):null;if(routeBinding&&!routeEvidenceRollback){warn(`[delegation-gate] Stage B route evidence capacity exceeded for ${taskId}`);continue}try{let turbo=hasActiveTurboMode(input.sessionID),{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));await recordGateEvidence2(directory,taskId,targetAgent,input.sessionID,turbo,{expectedGeneration:launchGeneration,transitionId:`gate:${input.callID}:${taskId}`,routeBinding,routeComplete:routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:void 0})}catch(err){routeEvidenceRollback?.(),warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`);continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||reviewerCompletesStageB))try{if(eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel: could not advance ${taskId} (${eligibleState}) → tests_run: ${err instanceof Error?err.message:String(err)}`)}else try{if(targetAgent==="reviewer"&&eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});else if(routeComplete&&targetAgent==="test_engineer"&&eligibleState==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel intermediate: could not advance ${taskId} (${eligibleState}) after ${targetAgent}: ${err instanceof Error?err.message:String(err)}`)}}}while(!1)}}}if(typeof subagentType==="string"){let coderSettleTaskId=null;try{let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory);if(!evidenceTaskId&&stripKnownSwarmPrefix(subagentType)==="coder"){let begun=begunCoderSettlementsByCallID.get(input.callID);if(begun?.taskId)evidenceTaskId=begun.taskId}if(coderSettleTaskId=evidenceTaskId,evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID),gateAgents=["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"],targetAgentForEvidence=stripKnownSwarmPrefix(subagentType);if(gateAgents.includes(targetAgentForEvidence))if(targetAgentForEvidence==="reviewer"||targetAgentForEvidence==="test_engineer");else{if(!(!isTerminalFailure&&(targetAgentForEvidence!=="critic"&&targetAgentForEvidence!=="critic_sounding_board"||extractPlanCriticVerdict(_output)==="APPROVED")))throw Error(`TASK_GATE_NOT_SATISFIED: ${targetAgentForEvidence} did not return a trusted positive verdict`);let{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),gateLaunchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId);if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0)throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: no launch binding for ${targetAgentForEvidence} task ${evidenceTaskId}`);await recordGateEvidence2(directory,evidenceTaskId,targetAgentForEvidence,input.sessionID,turbo,{expectedGeneration:gateLaunchGeneration,transitionId:`gate:${input.callID}:${evidenceTaskId}`})}else{let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,recordAgentDispatch:recordAgentDispatch2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),taskChangeContext=targetAgentForEvidence==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,rawObservedFiles=taskChangeContext?coderObservedFilesByCallID.get(input.callID)??await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(targetAgentForEvidence==="coder"&&!Array.isArray(rawObservedFiles))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: shared-root task ${evidenceTaskId} changed files could not be proven from its clean launch baseline`);let observedFiles=taskChangeContext?.declaredFiles&&Array.isArray(rawObservedFiles)?rawObservedFiles.filter((filePath)=>isPathWithinDeclaredScope(filePath,taskChangeContext.declaredFiles,taskChangeContext.baseline.directory)):[],context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&observedFiles.length>0,updated;if(standardDispatch&&!isStandardWorktreeFailure){if(!coderSettlementCommitted||!coderSettlementEvidence)throw Error(`CODER_SETTLEMENT_NOT_COMMITTED: isolated merge for ${evidenceTaskId} did not durably publish accepted-mutation evidence`);updated=coderSettlementEvidence}else updated=(await settleCoderDispatch({directory,taskId:evidenceTaskId,transitionId:`coder:${input.callID}`,accepted,testEngineerExempt:context.testEngineerExempt===!0,settlementFailed:!standardDispatch&&isTerminalFailure})).evidence,coderSettlementCommitted=!0;if(accepted){let workflow=getTaskWorkflowSnapshot2(updated);session.taskWorkflowStates.set(evidenceTaskId,workflow.state),session.stageBCompletion?.delete(evidenceTaskId),session.taskCouncilApproved?.delete(evidenceTaskId),session.taskCouncilWorkflowGeneration?.delete(evidenceTaskId),updateTaskWorkflowCache(session,evidenceTaskId,workflow)}}else await recordAgentDispatch2(directory,evidenceTaskId,targetAgentForEvidence,turbo,context)}}}catch(err){let normalizedAgent=stripKnownSwarmPrefix(subagentType);if(warn(`[delegation-gate] evidence recording failed: ${err instanceof Error?err.message:String(err)}`),normalizedAgent==="coder"){let terminalAbort=!1;if(coderSettleTaskId&&!coderSettlementCommitted){releaseCoderDispatchOwnership(directory,coderSettleTaskId,`coder:${input.callID}`);try{let abortOutcome=await abortCoderSettlementIfDoomed({directory,taskId:coderSettleTaskId,transitionId:`coder:${input.callID}`});terminalAbort=abortOutcome==="aborted"||abortOutcome==="already-aborted"}catch(abortErr){warn(`[delegation-gate] doomed settlement abort failed for ${coderSettleTaskId}: ${abortErr instanceof Error?abortErr.message:String(abortErr)}`)}if(terminalAbort)clearCoderTaskChangeContext(input.callID)}if(terminalAbort)pushAdvisory(session,`CODER_SETTLEMENT_ABORTED: task ${coderSettleTaskId} dispatch ${input.callID} was settled as ABORTED — its launch baseline was dirty or had no git history, so the coder's changes cannot be attributed. Reconcile the workspace (commit, stash, or discard the coder's output), then repair the task with update_task_status and re-dispatch from a clean tree.`);else pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`);throw err}}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"){if(coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID);if(begunCoderSettlementsByCallID.delete(input.callID),!coderSettlementCommitted)stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),deleteStoredInputArgs(input.callID)}}}if(storedArgs!==void 0)deleteStoredInputArgs(input.callID);if(!subagentType||!hasReviewer||councilActive){let delegationChain=swarmState.delegationChains.get(input.sessionID);if(delegationChain&&delegationChain.length>0){let lastCoderIndex=-1;for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){lastCoderIndex=i;break}let searchStart=lastCoderIndex===-1?0:lastCoderIndex,afterCoder=delegationChain.slice(searchStart);for(let delegation of afterCoder){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}if(lastCoderIndex!==-1&&hasReviewer&&hasTestEngineer)session.qaSkipCount=0,session.qaSkipTaskIds=[]}}if(stageBDispatchGenerationsByCallID.delete(input.callID),stageBRouteSlotByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state2]of session.taskWorkflowStates)if(state2==="tests_run"){let taskAwaiting=await findTaskAwaitingCompletion(directory);if(taskAwaiting&&!session.completionGateWarnedForTask.has(taskAwaiting))pushAdvisory(session,completionGateViolationMessage(taskAwaiting)),session.completionGateWarnedForTask.add(taskAwaiting);break}}if(standardWorktreeSettled&&coderSettlementCommitted){if(foregroundCoderTaskId)await completeCoderSettlementCleanup(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}finally{if(foregroundCoderTaskId)releaseCoderDispatchOwnership(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async(callID)=>{stageBRouteSlotByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID);let begun=begunCoderSettlementsByCallID.get(callID);if(!begun?.taskId)return;try{await abortCoderSettlement({directory,taskId:begun.taskId,transitionId:begun.transitionId,reason:"dispatch denied by a fail-closed gate after settlement began"})}catch(error49){criticalWarn(`[delegation-gate] denied-dispatch settlement rollback failed for call ${callID} (task ${begun.taskId}): ${error49 instanceof Error?error49.message:String(error49)}`)}finally{releaseCoderDispatchOwnership(directory,begun.taskId,begun.transitionId),begunCoderSettlementsByCallID.delete(callID),clearCoderTaskChangeContext(callID),clearPublishedScopeBindings(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)}}}}var EvidenceTaskIdPlanSchema,BoundedPendingScopeMap,pendingCoderScopeByTaskId,SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE="SWARM_BACKGROUND_TASK_BLOCKED: OpenCode background subagents (Task with background=true, requires OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true or OPENCODE_EXPERIMENTAL=true) remain experimental upstream and are disabled by default in swarm. Omit `background` (or set background=false), or explicitly enable hooks.background_subagents only after reviewing the background-subagent recovery and readiness guidance.",COVERAGE_DIAG_SNIPPET_CAP=80,COVERAGE_DIAG_MAX_SCAN=400,COVERAGE_DIAG_MIN_PREFIX=10,ACCEPTANCE_EXPECTED_BODY_CAP=2000,ACCEPTANCE_ARGS_FIELDS,PLAN_CRITIC_TASK_SIGNALS,ACTIVE_PARALLEL_TASK_STATES,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,recordPendingDelegationForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).recordPendingDelegationDetailed(...args2),writeDelegationFallbackForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).writeDelegationFallback(...args2),reserveBackgroundCoderSlotForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).reserveBackgroundCoderSlot(...args2),bindBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).bindBackgroundCoderReservation(...args2),releaseBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).releaseBackgroundCoderReservation(...args2),maintainBackgroundDelegationsForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).maintainBackgroundDelegations(...args2),_internals80;var init_delegation_gate=__esm(()=>{init_zod();init_pending_delegations();init_workspace_snapshot();init_agent_model();init_agent_names();init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_core_events();init_task_gate_requirements();init_policy();init_gate_evidence_classification();init_review_router();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_routing_enforcement();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_telemetry();init_logger();init_task_id();init_plan_task_id_context();init_task_id_resolver();init_task_id_resolver();init_project_db();init_coder_settlement();init_task_repair();init_task_terminal();init_dead_lane_reclaim();init_worktree_isolation();init_pr_workflow_gate();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_normalize_tool_name();init_utils2();EvidenceTaskIdPlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();BoundedPendingScopeMap=class BoundedPendingScopeMap extends Map{expiresAtByKey=new Map;sweepExpired(now=Date.now()){for(let[key2,expiresAt]of this.expiresAtByKey)if(expiresAt<=now)this.delete(key2)}set(key2,value){this.sweepExpired(),this.delete(key2),super.set(key2,value),this.expiresAtByKey.set(key2,Date.now()+300000);while(this.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=this.keys().next().value;if(!oldest)break;this.delete(oldest)}return this}get(key2){return this.sweepExpired(),super.get(key2)}has(key2){return this.sweepExpired(),super.has(key2)}delete(key2){return this.expiresAtByKey.delete(key2),super.delete(key2)}clear(){this.expiresAtByKey.clear(),super.clear()}};pendingCoderScopeByTaskId=new BoundedPendingScopeMap;ACCEPTANCE_ARGS_FIELDS=["prompt","description","task","input","message"];PLAN_CRITIC_TASK_SIGNALS=["critic-gate","plan critic","review plan","review the plan","plan.md","approve the plan","plan approval","pre-implementation review","evaluate this plan","evaluate the plan","assess this plan","assess the plan","plan soundness","before implementation","review the plan below"];ACTIVE_PARALLEL_TASK_STATES=new Set(["coder_delegated","pre_check_passed","reviewer_run","tests_run"]);COMPLETION_RECOVERY_TOOLS=new Set(["get_approved_plan","get_qa_gate_profile","check_gate_status"]),TASK_GATE_AGENTS=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);_internals80={resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,maintainBackgroundDelegationsForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,extractPlanTaskId,forceRecordPlanCriticApproval,beforePrFeedbackScopeConsume:void 0,get provisionWorktree(){return _internals79.provisionWorktree},set provisionWorktree(v){_internals79.provisionWorktree=v},get removeWorktree(){return _internals79.removeWorktree},set removeWorktree(v){_internals79.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals79.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals79.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals79.postMergeCleanup},set postMergeCleanup(v){_internals79.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals79.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals79.preserveBackgroundWorktreeOwnershipForCallId=v}}});function positiveIntegerOrDefault(value,fallback){return Number.isInteger(value)&&Number(value)>0?Number(value):fallback}function rememberSession(sessionID,state2){if(realtimeLearningNudgeBySession.has(sessionID))realtimeLearningNudgeBySession.delete(sessionID);realtimeLearningNudgeBySession.set(sessionID,state2);while(realtimeLearningNudgeBySession.size>500){let oldestSessionID=realtimeLearningNudgeBySession.keys().next().value;if(oldestSessionID===void 0)break;realtimeLearningNudgeBySession.delete(oldestSessionID)}}function recordRealtimeLearningToolCall(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID),nextState={observedToolCallCount:(prior?.observedToolCallCount??0)+1,lastNudgedAtToolCallCount:prior?.lastNudgedAtToolCallCount??0};return rememberSession(sessionID,nextState),nextState.observedToolCallCount}function getRealtimeLearningToolCallCount(sessionID){if(!sessionID)return 0;return realtimeLearningNudgeBySession.get(sessionID)?.observedToolCallCount??0}function shouldInjectRealtimeLearningNudge(args2){if(!args2.sessionID)return!1;if(args2.config?.enabled===!1)return!1;if(args2.realtimeAdmission?.enabled===!0&&args2.realtimeAdmission?.supersede_nudge!==!1)return!1;let state2=realtimeLearningNudgeBySession.get(args2.sessionID),toolCallCount=state2?.observedToolCallCount??0,firstAfterToolCalls=positiveIntegerOrDefault(args2.config?.first_after_tool_calls,10),repeatAfterToolCalls=positiveIntegerOrDefault(args2.config?.repeat_after_tool_calls,25);if(toolCallCount<firstAfterToolCalls)return!1;if(!state2||state2.lastNudgedAtToolCallCount===0)return!0;return toolCallCount-state2.lastNudgedAtToolCallCount>=repeatAfterToolCalls}function recordRealtimeLearningNudge(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID);if(!prior)return;rememberSession(sessionID,{...prior,lastNudgedAtToolCallCount:prior.observedToolCallCount})}function resetRealtimeLearningNudgeState(){realtimeLearningNudgeBySession.clear()}function clearRealtimeLearningNudgeSession(sessionID){realtimeLearningNudgeBySession.delete(sessionID)}function buildRealtimeLearningNudge(args2){return["[SWARM LEARNING NUDGE]",`Session has ${args2.toolCallCount} tool calls in phase ${args2.currentPhase}. Before continuing, decide whether the current work revealed a durable procedural lesson.`,"- If yes, call knowledge_add now with actionable when/then/scope fields so later turns can retrieve it.","- If the signal needs review across evidence, repeated outcomes, or generated-skill health, let the curator phase/postmortem path handle it; curator can emit knowledge_application_findings and skill_candidates without activating skills.","- Prefer reinforcing existing knowledge over noisy one-offs. Do not save transient setup failures, stale negative tool claims, or repo-specific accidents without a reusable trigger.","- If repeated KNOWLEDGE_IGNORED/VIOLATED outcomes or stale generated skills are accumulating, use skill_improve only when enabled/approved; generated skills stay proposal/draft gated and must not auto-activate.","- If there is nothing durable, continue without adding knowledge."].join(`
1242
+ `)}`,batchWarnCarrierIdx=messages.findIndex((m)=>m&&isGuidanceCarrier(m)),batchWarnInsertIdx=batchWarnCarrierIdx>=0?batchWarnCarrierIdx+1:0;insertGuidanceCarrier(messages,"delegation",warningText,batchWarnInsertIdx)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=isTaskToolId(input.tool);if(!input.sessionID){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let session=swarmState.agentSessions.get(input.sessionID);if(!session){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let{qaGateSessionOverrides}=ensureAgentSession(input.sessionID,void 0,directory),councilActive=await isCouncilGateActive(directory,config2.council,qaGateSessionOverrides??{});if(normalized==="submit_council_verdicts"){try{let result=typeof _output==="string"?JSON.parse(_output):_output;if(result&&typeof result==="object"&&result.success===!0&&typeof result.overallVerdict==="string"){let directArgs=input.args,storedArgs=getStoredInputArgs(input.callID),taskIdRaw=directArgs?.taskId??storedArgs?.taskId,taskId=typeof taskIdRaw==="string"?taskIdRaw:null;if(taskId){if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let priorRewarded=session.taskCouncilApproved.get(taskId)?.rewarded===!0;if(session.taskCouncilApproved.set(taskId,{verdict:result.overallVerdict,roundNumber:typeof result.roundNumber==="number"?result.roundNumber:1,quorumSize:typeof result.quorumSize==="number"?result.quorumSize:1,rewarded:priorRewarded}),councilActive&&result.overallVerdict==="APPROVE"&&result.allCriteriaMet===!0&&(result.requiredFixesCount??0)===0)pushAdvisory(session,`Council approved task ${taskId}. Call update_task_status with status="completed" so the central plan/evidence transaction can commit it.`)}}}catch(err){log(`[delegation-gate] toolAfter submit_council_verdicts: failed to parse output: ${err instanceof Error?err.message:String(err)}`)}return}if(isTaskTool2){let standardDispatch=standardWorktreeByCallID.get(input.callID),directArgsRaw=input.args,directArgs=directArgsRaw?{...directArgsRaw}:void 0;if(standardDispatch&&directArgs)if(standardDispatch.planTaskId)directArgs.task_id=standardDispatch.planTaskId;else delete directArgs.task_id;let storedArgs=getStoredInputArgs(input.callID),subagentType=directArgs?.subagent_type??storedArgs?.subagent_type,backgroundResultIsRunning=outputLooksLikeBackgroundRunning(_output),outputTerminalState=_output?.state,isTerminalFailure=outputTerminalState==="failed"||outputTerminalState==="error"||outputTerminalState==="cancelled"||outputTerminalState==="canceled";if(!isTerminalFailure&&typeof subagentType==="string"&&isKnownCanonicalRole(stripKnownSwarmPrefix(subagentType))&&(isBackgroundTrue(directArgs?.background)||isBackgroundTrue(storedArgs?.background)||backgroundResultIsRunning)){let coderReservation=backgroundCoderReservationByCallID.get(input.callID),backgroundRecordDurable=!backgroundSubagentsEnabled,backgroundOwnershipDurable=backgroundRecordDurable,backgroundCorrelationConflict=!1;if(backgroundSubagentsEnabled){let protectUntrackedBackgroundWorktree=async(taskId,reason)=>{if(!standardDispatch)return{detail:"no isolated worktree ownership tag was available",durable:!1};let detail,durable=!1;try{let preserved=await _internals79.preserveBackgroundWorktreeOwnershipForCallId(input.callID);durable=preserved.outcome==="preserved",detail=durable?`ownership tag ${preserved.tag} at ${preserved.ref}`:`ownership preservation failed: ${preserved.error??preserved.outcome}`}catch(err){detail=`ownership preservation threw: ${err instanceof Error?err.message:String(err)}`}return recordWorktreeMergeFailure(taskId??void 0,{outcome:"failed",stage:"background-correlation-persist",message:`${reason}; ${detail}. Automatic orphan reclamation is blocked until the dispatch is recovered.`,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,queuedAt:Date.now()}),{detail,durable}};try{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope)),{buildPromptSnapshot,findByCorrelationIdDetailed}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshotAsync:captureWorkspaceSnapshotAsync2}=await Promise.resolve().then(() => (init_workspace_snapshot(),exports_workspace_snapshot)),{subagentSessionId,jobId}=extractDispatchIds2(_output);if(!subagentSessionId&&!backgroundResultIsRunning){if(await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID);return}if(subagentSessionId){let mergedArgs={...storedArgs??{},...directArgs},normalizedSubagentType=stripKnownSwarmPrefix(subagentType),evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory,evidenceTaskResolutionOptions(normalizedSubagentType)),scope=session.declaredCoderScope&&session.declaredCoderScope.length>0?session.declaredCoderScope.join(","):evidenceTaskId,prHeadShaRaw=mergedArgs.prHeadSha??mergedArgs.pr_head_sha,prHeadSha=typeof prHeadShaRaw==="string"?prHeadShaRaw:null,taskChangeContext=stripKnownSwarmPrefix(subagentType)==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,fallbackWorkspace=taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:await captureWorkspaceSnapshotAsync2(directory,{prHeadSha,scope}),pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:fallbackWorkspace,taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(normalizedSubagentType)?stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId??""):void 0,worktree:standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner),reservationId:standardDispatch.reservationId,generation:standardDispatch.generation}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwnerRead=findByCorrelationIdDetailed(directory,subagentSessionId);if(existingOwnerRead.status==="uncertain")throw Error(`delegation store unreadable after ${existingOwnerRead.attempts} attempts (${existingOwnerRead.reason}); cannot verify the existing owner for background correlation ${subagentSessionId}`);let existingOwner=existingOwnerRead.value,pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals80.recordPendingDelegationForBackground(directory,pendingInput,{staleTimeoutMs:backgroundPendingTimeoutMs});if(backgroundRecordDurable=primaryOutcome.status==="recorded"||primaryOutcome.status==="duplicate",backgroundCorrelationConflict=primaryOutcome.status==="conflict",primaryOutcome.status==="conflict"){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"background correlation id conflicts with an existing immutable launch owner"),worktreeStatus=!standardDispatch?"No isolated worktree was attached to this conflicting call.":preservation.durable?`The current worktree was durably preserved with ${preservation.detail}.`:`The current worktree was not durably preserved (${preservation.detail}); automatic reclamation remains blocked pending recovery.`,reservationStatus=coderReservation?`The current reservation ${coderReservation.reservationId} was retained and was not bound to the conflicting correlation.`:primaryOutcome.record.coderReservationId?`No new reservation was present for this replay; the durable owner's reservation ${primaryOutcome.record.coderReservationId} remains unchanged.`:"No current or durable-owner coder reservation was present.";backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION CORRELATION CONFLICT: ${subagentType} (${subagentSessionId}) collided with a different durable launch owner (parent=${primaryOutcome.record.parentSessionId}, call=${primaryOutcome.record.callID}, agent=${primaryOutcome.record.swarmPrefixedAgent}, task=${primaryOutcome.record.planTaskId??"none"}). Inspect that existing owner and reconcile it before continuing. ${worktreeStatus} ${reservationStatus} No fallback owner was written and no reservation was bound. Do not abort, delete, or re-dispatch this correlation until reconciliation is complete. Do not advance task ${evidenceTaskId??"unknown"} until the collision is resolved.`)}else if(primaryOutcome.status==="failed"){if(backgroundRecordDurable=await _internals80.writeDelegationFallbackForBackground(directory,pendingInput)!==null,backgroundRecordDurable)warn(`[delegation-gate] background delegation ${subagentSessionId} persisted to the independent fallback artifact after the primary ledger write failed`)}if(!backgroundCorrelationConflict&&!backgroundRecordDurable){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"both background correlation stores failed");backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION UNTRACKED: ${subagentType} (${subagentSessionId}) launched, but both durable correlation stores failed. Recovery protection: ${preservation.detail}. Do not advance task ${evidenceTaskId??"unknown"} until the dispatch is recovered.`)}else if(!backgroundCorrelationConflict){if(backgroundOwnershipDurable=!0,coderReservation){if(!await _internals80.bindBackgroundCoderReservationForDispatch(directory,{...coderReservation,correlationId:subagentSessionId,generation:pendingInput.generation??1}))pushAdvisory(session,`BACKGROUND CODER RESERVATION UNBOUND: task ${evidenceTaskId??"unknown"} is durably tracked, but its pre-launch reservation could not be bound to ${subagentSessionId}. Further coder admission remains fail-closed until completion or recovery reconciles it.`)}}}else{let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch returned no trusted correlation id");backgroundOwnershipDurable=preservation.durable,warn("[delegation-gate] background dispatch had no correlation id (no jobId / no envelope) — not tracked"),pushAdvisory(session,`BACKGROUND DELEGATION UNCORRELATED: ${subagentType} launched without a trusted session correlation. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered or safely re-dispatched.`)}}catch(err){let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch correlation recording threw");backgroundOwnershipDurable=preservation.durable,warn(`[delegation-gate] background pending recording failed: ${err instanceof Error?err.message:String(err)}`),pushAdvisory(session,`BACKGROUND DELEGATION DURABILITY FAILURE: ${subagentType} launched, but its completion owner could not be persisted. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered.`)}}if(backgroundOwnershipDurable){let provisioningOwner=standardDispatch?.provisioningOwner??(standardDispatch?.reservationId!==void 0&&standardDispatch?.generation!==void 0?{reservationId:standardDispatch.reservationId,generation:standardDispatch.generation,branchName:standardDispatch.handle.branchName}:void 0);_internals79.removeWorktreeProvisioningOwner(directory,input.callID,provisioningOwner)}if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID)}if(!backgroundCorrelationConflict)backgroundCoderReservationByCallID.delete(input.callID);if(!backgroundResultIsRunning)clearPublishedScopeBindings(input.callID);return}let foregroundCoderTaskId=typeof subagentType==="string"&&stripKnownSwarmPrefix(subagentType)==="coder"?standardDispatch?.planTaskId??standardDispatch?.taskId??(typeof directArgs?.task_id==="string"?directArgs.task_id:typeof storedArgs?.task_id==="string"?storedArgs.task_id:null):null;clearPublishedScopeBindings(input.callID);try{if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs??{}};await recordPlanCriticApprovalSnapshotIfApplicable(directory,input,mergedArgs,_output)}catch(err){warn(`[delegation-gate] plan critic approval snapshot failed: ${err instanceof Error?err.message:String(err)}`)}if(typeof subagentType==="string"){let advisoryPrompt={...storedArgs??{},...directArgs??{}}.prompt;if(typeof advisoryPrompt==="string"&&advisoryPrompt.length>0)appendDelegationEnvelopeAdvisory(session,advisoryPrompt,{planTasks:[],validAgents:[...ALL_AGENT_NAMES]})}let standardWorktreeSettled=!standardDispatch,coderSettlementCommitted=!1,coderSettlementEvidence=null,isStandardWorktreeFailure=outputTerminalState==="cancelled"||outputTerminalState==="failed"||outputTerminalState==="error";if(standardDispatch&&!isStandardWorktreeFailure){let taskChangeContext=coderTaskChangeContextByCallID.get(input.callID);if(taskChangeContext)rememberCoderObservedFiles(input.callID,await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline));standardWorktreeByCallID.delete(input.callID),awaitingMergeByCallID.set(input.callID,{callID:input.callID,parentSessionID:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId,branch:standardDispatch.handle.branchName,worktreePath:standardDispatch.handle.worktreePath,mergeStrategy:standardDispatch.mergeStrategy,queuedAt:Date.now()});let observedForMerge=coderObservedFilesByCallID.get(input.callID);if(!Array.isArray(observedForMerge))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: isolated task ${standardDispatch.planTaskId??standardDispatch.taskId} changed files could not be proven from its clean launch baseline`);standardWorktreeSettled=(await finishStandardWorktreeDispatch(directory,standardDispatch,config2,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async(merged)=>{coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge),landedUnstaged:merged.strategy==="squash-unstaged"})).evidence,coderSettlementCommitted=!0}}).catch((err)=>{let reason=err instanceof Error?err.message:String(err);warn(`[delegation-gate] standard worktree merge-back failed for ${standardDispatch.taskId}: ${reason}`),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"merge-back",message:reason,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,completedAt:Date.now()});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID,void 0,directory);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_MERGE_FAILED: task ${standardDispatch.taskId} preserved at ${standardDispatch.handle.worktreePath}; reason: ${reason}.`),awaitingMergeByCallID.delete(input.callID)}))?.outcome==="merged"}if(standardDispatch&&isStandardWorktreeFailure){standardWorktreeByCallID.delete(input.callID);let reason=outputTerminalState==="cancelled"?"cancelled":"denied";await _internals79.preserveDirtyWorktreeForCallId(input.callID,reason,directory),closeProjectDb(standardDispatch.handle.worktreePath);let removal=await _internals79.removeWorktree(standardDispatch.handle.worktreePath,directory).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)recordDeadLaneReclaim(directory,{lanePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,reason:removalError}),pushAdvisory(ensureAgentSession(standardDispatch.parentSessionID,void 0,directory),`WORKTREE_LANE_STRANDED: lane ${standardDispatch.handle.worktreePath} could not be removed (${removalError}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`);await _internals79.postMergeCleanup(directory,standardDispatch.handle.branchName),awaitingMergeByCallID.delete(input.callID),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"task-result",message:`task terminated with ${outputTerminalState??"terminal-failure"}`});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID,void 0,directory);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_TASK_FAILED: task ${standardDispatch.taskId} terminated with ${outputTerminalState??"terminal-failure"}; worktree preserved and cleaned without merge-back.`)}let hasReviewer=!1,hasTestEngineer=!1;if(typeof subagentType==="string"){let targetAgent=stripKnownSwarmPrefix(subagentType);if(targetAgent==="reviewer")hasReviewer=!0;if(targetAgent==="test_engineer")hasTestEngineer=!0;let standalonePrReviewReentry=stageBDispatchContextByCallID.get(input.callID)?.standalonePrReviewReentry===!0;if(!councilActive&&!standalonePrReviewReentry){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],attributionResult=parsePerTaskVerdicts(outputText(_output));for(let err of attributionResult.errors)warn(`[delegation-gate] ${err}`);do{if(attributionResult.verdicts.size===0){let dispatchCtx=stageBDispatchContextByCallID.get(input.callID),expectedTasks=dispatchCtx?[...dispatchCtx.taskIds].join(", "):gateDispatchPrimaryTaskByCallID.get(input.callID)??"unknown";warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING: ${targetAgent} dispatch for call ${input.callID} returned no structured verdict lines. Expected tasks: ${expectedTasks}. Agent output must include [REVIEWED] or [TESTED] verdict lines.`);let failClosedTaskIds=dispatchCtx?[...dispatchCtx.taskIds]:gateDispatchPrimaryTaskByCallID.has(input.callID)?[gateDispatchPrimaryTaskByCallID.get(input.callID)]:[];for(let failTaskId of failClosedTaskIds){let failState=session.taskWorkflowStates.get(failTaskId);if(failState&&stageBEligibleStates.includes(failState))session.taskWorkflowStates.set(failTaskId,"rework_required"),session.stageBCompletion?.delete(failTaskId),warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING fail-closed: task ${failTaskId} → rework_required`)}break}let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state2]of session.taskWorkflowStates){if(!stageBEligibleStates.includes(state2))continue;if(!attributionResult.verdicts.has(taskId))continue;let eligibleState=state2,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`);continue}let verdictEntry=attributionResult.verdicts.get(taskId),dispatchCtxForVerdict=stageBDispatchContextByCallID.get(input.callID);if(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"&&verdictEntry?.verdict==="SKIPPED"){warn(`[delegation-gate] Stage B test gate SKIPPED (tests not run) for task ${taskId} from call ${input.callID} — leaving state ${state2} for test-gate re-dispatch; reviewer proof preserved`);continue}if(!(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"?verdictEntry?.verdict==="PASS":verdictEntry?.verdict==="APPROVED")){try{let rejected=await transitionTaskWorkflowEvidence2(directory,taskId,{type:"stage_b_failed",gate:targetAgent,expectedGeneration:launchGeneration,transitionId:`gate-failed:${input.callID}:${taskId}`});session.taskWorkflowStates.set(taskId,"rework_required"),session.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(session,taskId,getTaskWorkflowSnapshot2(rejected))}catch(err){warn(`[delegation-gate] Stage B rejection could not be persisted for ${taskId}: ${err instanceof Error?err.message:String(err)}`)}continue}let routeBinding=stageBRouteSlotByCallID.get(input.callID)?.get(taskId),legacyUnrouted=!isStageBRouteRequired(session,taskId)&&!routeBinding&&(()=>{try{return isLegacyTaskGateRequirementsChain(readTaskGateRequirementsReceiptsSync(directory,taskId))}catch{return!1}})(),existingRouteEvidence=getStageBRouteEvidence(session,taskId),prospectiveRouteEvidence=routeBinding?[...existingRouteEvidence.filter((entry)=>entry.role!==routeBinding.role||entry.sessionId!==routeBinding.sessionId||entry.taskId!==routeBinding.taskId||entry.callId!==routeBinding.callId||entry.childSessionId!==routeBinding.childSessionId||entry.generation!==routeBinding.generation),routeBinding]:getStageBRouteEvidence(session,taskId),routeEnforcementEnabled=config2.review_routing?.enforce_receipts??!0,routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:routeEnforcementEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:routeBinding?{role:routeBinding.role,identity:routeBinding.identity,callId:routeBinding.callId,childSessionId:routeBinding.childSessionId,generation:routeBinding.generation}:void 0});if(!routeDecision.canAdvance){warn(`[delegation-gate] Stage B route receipt blocked ${taskId}: ${routeDecision.reason??"unknown reason"}`);continue}let routeCompleteDecision=routeEnforcementEnabled&&routeBinding?enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:!0,requireEvidenceBindings:!0,requireCompleteEvidence:!0}):void 0,routeComplete=routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:routeDecision.canAdvance,routeEvidenceRollback=routeBinding?reserveStageBRouteEvidence(session,taskId,routeBinding):null;if(routeBinding&&!routeEvidenceRollback){warn(`[delegation-gate] Stage B route evidence capacity exceeded for ${taskId}`);continue}try{let turbo=hasActiveTurboMode(input.sessionID),{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));await recordGateEvidence2(directory,taskId,targetAgent,input.sessionID,turbo,{expectedGeneration:launchGeneration,transitionId:`gate:${input.callID}:${taskId}`,routeBinding,routeComplete:routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:void 0})}catch(err){routeEvidenceRollback?.(),warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`);continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||reviewerCompletesStageB))try{if(eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel: could not advance ${taskId} (${eligibleState}) → tests_run: ${err instanceof Error?err.message:String(err)}`)}else try{if(targetAgent==="reviewer"&&eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});else if(routeComplete&&targetAgent==="test_engineer"&&eligibleState==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel intermediate: could not advance ${taskId} (${eligibleState}) after ${targetAgent}: ${err instanceof Error?err.message:String(err)}`)}}}while(!1)}}}if(typeof subagentType==="string"){let coderSettleTaskId=null;try{let mergedArgs={...storedArgs??{},...directArgs},targetAgentForEvidence=stripKnownSwarmPrefix(subagentType),evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory,evidenceTaskResolutionOptions(targetAgentForEvidence));if(!evidenceTaskId&&stripKnownSwarmPrefix(subagentType)==="coder"){let begun=begunCoderSettlementsByCallID.get(input.callID);if(begun?.taskId)evidenceTaskId=begun.taskId}if(coderSettleTaskId=evidenceTaskId,evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID);if(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"].includes(targetAgentForEvidence))if(targetAgentForEvidence==="reviewer"||targetAgentForEvidence==="test_engineer");else{if(!(!isTerminalFailure&&(targetAgentForEvidence!=="critic"&&targetAgentForEvidence!=="critic_sounding_board"||extractPlanCriticVerdict(_output)==="APPROVED")))throw Error(`TASK_GATE_NOT_SATISFIED: ${targetAgentForEvidence} did not return a trusted positive verdict`);let{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),gateLaunchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId);if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0)throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: no launch binding for ${targetAgentForEvidence} task ${evidenceTaskId}`);await recordGateEvidence2(directory,evidenceTaskId,targetAgentForEvidence,input.sessionID,turbo,{expectedGeneration:gateLaunchGeneration,transitionId:`gate:${input.callID}:${evidenceTaskId}`})}else{let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,recordAgentDispatch:recordAgentDispatch2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),taskChangeContext=targetAgentForEvidence==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,rawObservedFiles=taskChangeContext?coderObservedFilesByCallID.get(input.callID)??await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(targetAgentForEvidence==="coder"&&!Array.isArray(rawObservedFiles))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: shared-root task ${evidenceTaskId} changed files could not be proven from its clean launch baseline`);let observedFiles=taskChangeContext?.declaredFiles&&Array.isArray(rawObservedFiles)?rawObservedFiles.filter((filePath)=>isPathWithinDeclaredScope(filePath,taskChangeContext.declaredFiles,taskChangeContext.baseline.directory)):[],context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&observedFiles.length>0,updated;if(standardDispatch&&!isStandardWorktreeFailure){if(!coderSettlementCommitted||!coderSettlementEvidence)throw Error(`CODER_SETTLEMENT_NOT_COMMITTED: isolated merge for ${evidenceTaskId} did not durably publish accepted-mutation evidence`);updated=coderSettlementEvidence}else updated=(await settleCoderDispatch({directory,taskId:evidenceTaskId,transitionId:`coder:${input.callID}`,accepted,testEngineerExempt:context.testEngineerExempt===!0,settlementFailed:!standardDispatch&&isTerminalFailure})).evidence,coderSettlementCommitted=!0;if(accepted){let workflow=getTaskWorkflowSnapshot2(updated);session.taskWorkflowStates.set(evidenceTaskId,workflow.state),session.stageBCompletion?.delete(evidenceTaskId),session.taskCouncilApproved?.delete(evidenceTaskId),session.taskCouncilWorkflowGeneration?.delete(evidenceTaskId),updateTaskWorkflowCache(session,evidenceTaskId,workflow)}}else await recordAgentDispatch2(directory,evidenceTaskId,targetAgentForEvidence,turbo,context)}}}catch(err){let normalizedAgent=stripKnownSwarmPrefix(subagentType);if(warn(`[delegation-gate] evidence recording failed: ${err instanceof Error?err.message:String(err)}`),normalizedAgent==="coder"){let terminalAbort=!1;if(coderSettleTaskId&&!coderSettlementCommitted){releaseCoderDispatchOwnership(directory,coderSettleTaskId,`coder:${input.callID}`);try{let abortOutcome=await abortCoderSettlementIfDoomed({directory,taskId:coderSettleTaskId,transitionId:`coder:${input.callID}`});terminalAbort=abortOutcome==="aborted"||abortOutcome==="already-aborted"}catch(abortErr){warn(`[delegation-gate] doomed settlement abort failed for ${coderSettleTaskId}: ${abortErr instanceof Error?abortErr.message:String(abortErr)}`)}if(terminalAbort)clearCoderTaskChangeContext(input.callID)}if(terminalAbort)pushAdvisory(session,`CODER_SETTLEMENT_ABORTED: task ${coderSettleTaskId} dispatch ${input.callID} was settled as ABORTED — its launch baseline was dirty or had no git history, so the coder's changes cannot be attributed. Reconcile the workspace (commit, stash, or discard the coder's output), then repair the task with update_task_status and re-dispatch from a clean tree.`);else pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`);throw err}}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"){if(coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID);if(begunCoderSettlementsByCallID.delete(input.callID),!coderSettlementCommitted)stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),deleteStoredInputArgs(input.callID)}}}if(storedArgs!==void 0)deleteStoredInputArgs(input.callID);if(!subagentType||!hasReviewer||councilActive){let delegationChain=swarmState.delegationChains.get(input.sessionID);if(delegationChain&&delegationChain.length>0){let lastCoderIndex=-1;for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){lastCoderIndex=i;break}let searchStart=lastCoderIndex===-1?0:lastCoderIndex,afterCoder=delegationChain.slice(searchStart);for(let delegation of afterCoder){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}if(lastCoderIndex!==-1&&hasReviewer&&hasTestEngineer)session.qaSkipCount=0,session.qaSkipTaskIds=[]}}if(stageBDispatchGenerationsByCallID.delete(input.callID),stageBRouteSlotByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state2]of session.taskWorkflowStates)if(state2==="tests_run"){let taskAwaiting=await findTaskAwaitingCompletion(directory);if(taskAwaiting&&!session.completionGateWarnedForTask.has(taskAwaiting))pushAdvisory(session,completionGateViolationMessage(taskAwaiting)),session.completionGateWarnedForTask.add(taskAwaiting);break}}if(standardWorktreeSettled&&coderSettlementCommitted){if(foregroundCoderTaskId)await completeCoderSettlementCleanup(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}finally{if(foregroundCoderTaskId)releaseCoderDispatchOwnership(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async(callID)=>{stageBRouteSlotByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID);let begun=begunCoderSettlementsByCallID.get(callID);if(!begun?.taskId)return;try{await abortCoderSettlement({directory,taskId:begun.taskId,transitionId:begun.transitionId,reason:"dispatch denied by a fail-closed gate after settlement began"})}catch(error49){criticalWarn(`[delegation-gate] denied-dispatch settlement rollback failed for call ${callID} (task ${begun.taskId}): ${error49 instanceof Error?error49.message:String(error49)}`)}finally{releaseCoderDispatchOwnership(directory,begun.taskId,begun.transitionId),begunCoderSettlementsByCallID.delete(callID),clearCoderTaskChangeContext(callID),clearPublishedScopeBindings(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)}}}}var EvidenceTaskIdPlanSchema,BoundedPendingScopeMap,pendingCoderScopeByTaskId,SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE="SWARM_BACKGROUND_TASK_BLOCKED: OpenCode background subagents (Task with background=true, requires OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true or OPENCODE_EXPERIMENTAL=true) remain experimental upstream and are disabled by default in swarm. Omit `background` (or set background=false), or explicitly enable hooks.background_subagents only after reviewing the background-subagent recovery and readiness guidance.",COVERAGE_DIAG_SNIPPET_CAP=80,COVERAGE_DIAG_MAX_SCAN=400,COVERAGE_DIAG_MIN_PREFIX=10,ACCEPTANCE_EXPECTED_BODY_CAP=2000,ACCEPTANCE_ARGS_FIELDS,PLAN_CRITIC_TASK_SIGNALS,ACTIVE_PARALLEL_TASK_STATES,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,EXPLICIT_TASK_EVIDENCE_AGENTS,recordPendingDelegationForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).recordPendingDelegationDetailed(...args2),writeDelegationFallbackForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).writeDelegationFallback(...args2),reserveBackgroundCoderSlotForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).reserveBackgroundCoderSlot(...args2),bindBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).bindBackgroundCoderReservation(...args2),releaseBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).releaseBackgroundCoderReservation(...args2),maintainBackgroundDelegationsForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).maintainBackgroundDelegations(...args2),_internals80;var init_delegation_gate=__esm(()=>{init_zod();init_pending_delegations();init_workspace_snapshot();init_agent_model();init_agent_names();init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_core_events();init_task_gate_requirements();init_policy();init_gate_evidence_classification();init_review_router();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_routing_enforcement();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_telemetry();init_logger();init_task_id();init_plan_task_id_context();init_task_id_resolver();init_task_id_resolver();init_project_db();init_coder_settlement();init_task_repair();init_task_terminal();init_dead_lane_reclaim();init_worktree_isolation();init_pr_workflow_gate();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_normalize_tool_name();init_utils2();EvidenceTaskIdPlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();BoundedPendingScopeMap=class BoundedPendingScopeMap extends Map{expiresAtByKey=new Map;sweepExpired(now=Date.now()){for(let[key2,expiresAt]of this.expiresAtByKey)if(expiresAt<=now)this.delete(key2)}set(key2,value){this.sweepExpired(),this.delete(key2),super.set(key2,value),this.expiresAtByKey.set(key2,Date.now()+300000);while(this.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=this.keys().next().value;if(!oldest)break;this.delete(oldest)}return this}get(key2){return this.sweepExpired(),super.get(key2)}has(key2){return this.sweepExpired(),super.has(key2)}delete(key2){return this.expiresAtByKey.delete(key2),super.delete(key2)}clear(){this.expiresAtByKey.clear(),super.clear()}};pendingCoderScopeByTaskId=new BoundedPendingScopeMap;ACCEPTANCE_ARGS_FIELDS=["prompt","description","task","input","message"];PLAN_CRITIC_TASK_SIGNALS=["critic-gate","plan critic","review plan","review the plan","plan.md","approve the plan","plan approval","pre-implementation review","evaluate this plan","evaluate the plan","assess this plan","assess the plan","plan soundness","before implementation","review the plan below"];ACTIVE_PARALLEL_TASK_STATES=new Set(["coder_delegated","pre_check_passed","reviewer_run","tests_run"]);COMPLETION_RECOVERY_TOOLS=new Set(["get_approved_plan","get_qa_gate_profile","check_gate_status"]),TASK_GATE_AGENTS=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]),EXPLICIT_TASK_EVIDENCE_AGENTS=new Set(["critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor"]);_internals80={resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,maintainBackgroundDelegationsForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,extractPlanTaskId,forceRecordPlanCriticApproval,beforePrFeedbackScopeConsume:void 0,get provisionWorktree(){return _internals79.provisionWorktree},set provisionWorktree(v){_internals79.provisionWorktree=v},get removeWorktree(){return _internals79.removeWorktree},set removeWorktree(v){_internals79.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals79.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals79.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals79.postMergeCleanup},set postMergeCleanup(v){_internals79.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals79.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals79.preserveBackgroundWorktreeOwnershipForCallId=v}}});function positiveIntegerOrDefault(value,fallback){return Number.isInteger(value)&&Number(value)>0?Number(value):fallback}function rememberSession(sessionID,state2){if(realtimeLearningNudgeBySession.has(sessionID))realtimeLearningNudgeBySession.delete(sessionID);realtimeLearningNudgeBySession.set(sessionID,state2);while(realtimeLearningNudgeBySession.size>500){let oldestSessionID=realtimeLearningNudgeBySession.keys().next().value;if(oldestSessionID===void 0)break;realtimeLearningNudgeBySession.delete(oldestSessionID)}}function recordRealtimeLearningToolCall(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID),nextState={observedToolCallCount:(prior?.observedToolCallCount??0)+1,lastNudgedAtToolCallCount:prior?.lastNudgedAtToolCallCount??0};return rememberSession(sessionID,nextState),nextState.observedToolCallCount}function getRealtimeLearningToolCallCount(sessionID){if(!sessionID)return 0;return realtimeLearningNudgeBySession.get(sessionID)?.observedToolCallCount??0}function shouldInjectRealtimeLearningNudge(args2){if(!args2.sessionID)return!1;if(args2.config?.enabled===!1)return!1;if(args2.realtimeAdmission?.enabled===!0&&args2.realtimeAdmission?.supersede_nudge!==!1)return!1;let state2=realtimeLearningNudgeBySession.get(args2.sessionID),toolCallCount=state2?.observedToolCallCount??0,firstAfterToolCalls=positiveIntegerOrDefault(args2.config?.first_after_tool_calls,10),repeatAfterToolCalls=positiveIntegerOrDefault(args2.config?.repeat_after_tool_calls,25);if(toolCallCount<firstAfterToolCalls)return!1;if(!state2||state2.lastNudgedAtToolCallCount===0)return!0;return toolCallCount-state2.lastNudgedAtToolCallCount>=repeatAfterToolCalls}function recordRealtimeLearningNudge(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID);if(!prior)return;rememberSession(sessionID,{...prior,lastNudgedAtToolCallCount:prior.observedToolCallCount})}function resetRealtimeLearningNudgeState(){realtimeLearningNudgeBySession.clear()}function clearRealtimeLearningNudgeSession(sessionID){realtimeLearningNudgeBySession.delete(sessionID)}function buildRealtimeLearningNudge(args2){return["[SWARM LEARNING NUDGE]",`Session has ${args2.toolCallCount} tool calls in phase ${args2.currentPhase}. Before continuing, decide whether the current work revealed a durable procedural lesson.`,"- If yes, call knowledge_add now with actionable when/then/scope fields so later turns can retrieve it.","- If the signal needs review across evidence, repeated outcomes, or generated-skill health, let the curator phase/postmortem path handle it; curator can emit knowledge_application_findings and skill_candidates without activating skills.","- Prefer reinforcing existing knowledge over noisy one-offs. Do not save transient setup failures, stale negative tool claims, or repo-specific accidents without a reusable trigger.","- If repeated KNOWLEDGE_IGNORED/VIOLATED outcomes or stale generated skills are accumulating, use skill_improve only when enabled/approved; generated skills stay proposal/draft gated and must not auto-activate.","- If there is nothing durable, continue without adding knowledge."].join(`
1242
1243
  `)}var REALTIME_LEARNING_NUDGE_ID_PREFIX="realtime-learning-nudge",realtimeLearningNudgeBySession;var init_realtime_learning_nudge=__esm(()=>{realtimeLearningNudgeBySession=new Map});function trajectoryStepGeneration(){return stepCounterGeneration}function bumpStepCounterGeneration(){stepCounterGeneration+=1}function evictOldestStepSessionIfNeeded(key2){if(sessionStepCounters.has(key2))return;while(sessionStepCounters.size>=MAX_TRACKED_STEP_SESSIONS){let oldestSessionId=sessionStepCounters.keys().next().value;if(oldestSessionId===void 0)break;sessionStepCounters.delete(oldestSessionId)}}function nextTrajectoryStep(sessionId,directory){let key2=compositeSessionKey(directory,sessionId);evictOldestStepSessionIfNeeded(key2);let step=(sessionStepCounters.get(key2)??0)+1;return sessionStepCounters.set(key2,step),step}function seedTrajectoryStepCounter(sessionId,directory,step){if(!Number.isFinite(step)||step<=0)return;let key2=compositeSessionKey(directory,sessionId);evictOldestStepSessionIfNeeded(key2);let current=sessionStepCounters.get(key2)??0;if(step>current)sessionStepCounters.set(key2,Math.floor(step))}function clearTrajectoryStepCounters(sessionId){if(sessionId!==void 0){let suffix=sessionKeySuffix(sessionId),removed=!1;for(let key2 of sessionStepCounters.keys())if(key2.endsWith(suffix))sessionStepCounters.delete(key2),removed=!0;if(removed)bumpStepCounterGeneration()}else if(sessionStepCounters.size>0)sessionStepCounters.clear(),bumpStepCounterGeneration()}var MAX_TRACKED_STEP_SESSIONS=500,sessionStepCounters,stepCounterGeneration=0;var init_trajectory_step_state=__esm(()=>{init_canonical_root();sessionStepCounters=new Map});function normalizeText2(value){return value?.trim()??""}function entryKey(scope){return[normalizeText2(scope.sessionID),normalizeText2(scope.invocationID),normalizeText2(scope.swarmID),normalizeText2(scope.role)].join("␟")}function parseModelString(model){let value=model.trim();if(!value)return;let separator=value.indexOf("/");if(separator<=0||separator===value.length-1)return;return{providerID:value.slice(0,separator),modelID:value.slice(separator+1)}}function pruneScopedModelOverrides(now){for(let[key2,entry]of scopedModelOverrides)if(now-entry.updatedAt>1800000)scopedModelOverrides.delete(key2);while(scopedModelOverrides.size>256){let first=scopedModelOverrides.keys().next().value;if(!first)break;scopedModelOverrides.delete(first)}}function selectionFromEntry(entry,chain){if(entry.fallbackIndex>=chain.totalModels)return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,exhausted:!0,totalModels:chain.totalModels};if(entry.fallbackIndex===0)return{generation:entry.generation,fallbackIndex:0,modelString:chain.primary?.modelString,model:chain.primary?.override,exhausted:!1,totalModels:chain.totalModels};let fallback=chain.fallbacks[entry.fallbackIndex-1];return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,modelString:fallback?.modelString,model:fallback?.override,exhausted:!1,totalModels:chain.totalModels}}function normalizeModelChain(primaryModel,fallbackModels){let seen=new Set,normalizedFallbacks=[],normalizedPrimary,primaryText=normalizeText2(primaryModel);if(primaryText){let parsed=parseModelString(primaryText);if(parsed)normalizedPrimary={modelString:primaryText,override:parsed},seen.add(primaryText)}for(let candidate of fallbackModels){let text=normalizeText2(candidate??void 0);if(!text||seen.has(text))continue;let parsed=parseModelString(text);if(!parsed)continue;seen.add(text),normalizedFallbacks.push({modelString:text,override:parsed})}return Object.freeze({primary:normalizedPrimary,fallbacks:Object.freeze(normalizedFallbacks),signature:[primaryText,...normalizedFallbacks.map((entry)=>entry.modelString)].join("␞"),totalModels:1+normalizedFallbacks.length})}function resolveScopedModelSelection(scope,chain,now=Date.now()){pruneScopedModelOverrides(now);let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature){let next={key:key2,updatedAt:now,generation:(current?.generation??0)+1,fallbackIndex:0,signature:chain.signature};return scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,next),selectionFromEntry(next,chain)}return current.updatedAt=now,scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),selectionFromEntry(current,chain)}function advanceScopedModelSelection(scope,chain,expectedGeneration,now=Date.now()){let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature)return{accepted:!1,selection:resolveScopedModelSelection(scope,chain,now)};if(current.generation!==expectedGeneration)return current.updatedAt=now,{accepted:!1,selection:selectionFromEntry(current,chain)};return current.updatedAt=now,current.fallbackIndex=Math.min(current.fallbackIndex+1,chain.totalModels),scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),{accepted:!0,selection:selectionFromEntry(current,chain)}}function resetScopedModelSelection(scope,expectedGeneration){let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current)return!1;if(expectedGeneration!==void 0&&current.generation!==expectedGeneration)return!1;return scopedModelOverrides.delete(key2)}function clearScopedModelSelectionsForSession(sessionID){let normalizedSessionID=normalizeText2(sessionID);for(let[key2,entry]of scopedModelOverrides)if(key2.startsWith(`${normalizedSessionID}␟`))scopedModelOverrides.delete(entry.key)}function getScopedModelSelectionSnapshot(){return[...scopedModelOverrides.values()].map((entry)=>{let[sessionID,invocationID,swarmID,role]=entry.key.split("␟");return{key:{sessionID,invocationID,swarmID:swarmID||void 0,role},generation:entry.generation,fallbackIndex:entry.fallbackIndex,updatedAt:entry.updatedAt}})}function resetScopedModelSelectionStateForTests(){scopedModelOverrides.clear()}var scopedModelOverrides;var init_model_override_state=__esm(()=>{scopedModelOverrides=new Map});function normalizeText3(value){return value?.trim()??""}function parentCallKey(parentSessionID,callID){return`${normalizeText3(parentSessionID)}␟${normalizeText3(callID)}`}function normalizeRoute(input,now){return{parentSessionID:normalizeText3(input.parentSessionID),invocationID:normalizeText3(input.invocationID),callID:normalizeText3(input.callID),role:normalizeText3(input.role),actionDigest:normalizeText3(input.actionDigest),swarmID:normalizeText3(input.swarmID)||void 0,updatedAt:now}}function routeScope(route){return{sessionID:route.parentSessionID,invocationID:route.invocationID,swarmID:route.swarmID,role:route.role}}function upsertRoute(route){let key2=parentCallKey(route.parentSessionID,route.callID),prior=routesByParentCall.get(key2);if(prior?.childSessionID)routeKeyByChildSession.delete(prior.childSessionID);if(routesByParentCall.delete(key2),routesByParentCall.set(key2,route),route.childSessionID)routeKeyByChildSession.set(route.childSessionID,key2)}function pruneRoutes(now){for(let[key2,route]of routesByParentCall)if(now-route.updatedAt>PENDING_TASK_MODEL_ROUTE_TTL_MS){if(routesByParentCall.delete(key2),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}while(routesByParentCall.size>MAX_PENDING_TASK_MODEL_ROUTES){let oldestKey=routesByParentCall.keys().next().value;if(typeof oldestKey!=="string")break;let route=routesByParentCall.get(oldestKey);if(routesByParentCall.delete(oldestKey),route?.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}}function matchingRouteForParent(parentSessionID,role,actionDigest){let match,normalizedParent=normalizeText3(parentSessionID),normalizedRole=normalizeText3(role),normalizedDigest=normalizeText3(actionDigest);for(let route of routesByParentCall.values()){if(route.parentSessionID!==normalizedParent||route.role!==normalizedRole)continue;if(normalizedDigest&&route.actionDigest!==normalizedDigest)continue;if(match)return"ambiguous";match=route}return match}function touchRoute(route,now){route.updatedAt=now,upsertRoute(route)}function registerPendingTaskModelRoute(input,now=Date.now()){pruneRoutes(now);let route=normalizeRoute(input,now);return upsertRoute(route),{...route}}function bindPendingTaskModelRouteChild(input,now=Date.now()){pruneRoutes(now);let key2=parentCallKey(input.parentSessionID,input.callID),route=routesByParentCall.get(key2);if(!route)return;if(route.childSessionID)routeKeyByChildSession.delete(route.childSessionID);return route.childSessionID=normalizeText3(input.childSessionID),touchRoute(route,now),{...route}}function advancePendingTaskModelRoute(input){let now=input.now??Date.now();pruneRoutes(now);let routeKey=routeKeyByChildSession.get(normalizeText3(input.childSessionID));if(!routeKey)return;let route=routesByParentCall.get(routeKey);if(!route||route.role!==normalizeText3(input.role)||route.actionDigest!==normalizeText3(input.actionDigest))return;let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now),advanced=advanceScopedModelSelection(routeScope(route),chain,input.expectedGeneration??selection.generation,now);return touchRoute(route,now),{accepted:advanced.accepted,exhausted:advanced.selection.exhausted,fallbackIndex:advanced.selection.fallbackIndex,generation:advanced.selection.generation,scope:routeScope(route),route:{...route}}}async function resolveTaskChatModelOverride(input){let now=input.now??Date.now();pruneRoutes(now);let normalizedChild=normalizeText3(input.childSessionID),normalizedRole=normalizeText3(input.role),route,boundKey=routeKeyByChildSession.get(normalizedChild);if(boundKey)route=routesByParentCall.get(boundKey);let resolvedParentSessionID;if(!route&&input.lookupParentSessionID){if(resolvedParentSessionID=normalizeText3(await input.lookupParentSessionID(normalizedChild)),resolvedParentSessionID){let match=matchingRouteForParent(resolvedParentSessionID,normalizedRole,input.actionDigest);if(match==="ambiguous")return{status:"ambiguous"};route=match}}if(!route)return{status:"missing"};if(route.role!==normalizedRole||input.actionDigest&&route.actionDigest!==normalizeText3(input.actionDigest))return{status:"mismatch",route:{...route}};if(resolvedParentSessionID&&route.parentSessionID!==resolvedParentSessionID)return{status:"mismatch",route:{...route}};let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now);if(touchRoute(route,now),selection.exhausted)return{status:"exhausted",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};if(selection.fallbackIndex===0||!selection.model)return{status:"primary",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};return{status:"override",model:selection.model,modelString:selection.modelString,fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}}}function clearPendingTaskModelRoutesForSession(sessionID){let normalizedSessionID=normalizeText3(sessionID);for(let[key2,route]of routesByParentCall)if(route.parentSessionID===normalizedSessionID||route.childSessionID===normalizedSessionID){if(routesByParentCall.delete(key2),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}clearScopedModelSelectionsForSession(normalizedSessionID)}function getPendingTaskModelRouteSnapshot(){return[...routesByParentCall.values()].map((route)=>({...route}))}function getTaskModelRoutingStateSnapshot(){return{routes:getPendingTaskModelRouteSnapshot(),scopedSelections:getScopedModelSelectionSnapshot()}}function clearAllTaskModelRoutingState(){routesByParentCall.clear(),routeKeyByChildSession.clear(),resetScopedModelSelectionStateForTests()}var MAX_PENDING_TASK_MODEL_ROUTES=256,PENDING_TASK_MODEL_ROUTE_TTL_MS=1800000,routesByParentCall,routeKeyByChildSession;var init_task_model_routing=__esm(()=>{init_model_override_state();routesByParentCall=new Map,routeKeyByChildSession=new Map});function evictOldest(map2,cap){while(map2.size>=cap){let oldest=map2.keys().next().value;if(oldest===void 0)break;map2.delete(oldest)}}function hydrationProjectKey(directory){let memoKey=canonicalRootKeyLexical(directory),memoized=directoryKeyMemo.get(memoKey);if(memoized!==void 0)return memoized;let key2=canonicalProjectKey(directory);if(!directoryKeyMemo.has(memoKey))evictOldest(directoryKeyMemo,MAX_DIRECTORY_KEY_MEMO);return directoryKeyMemo.set(memoKey,key2),key2}function beginHydrationScope(directory){let projectKey=hydrationProjectKey(directory),generation=(projectHydrationGenerations.get(projectKey)??0)+1;if(!projectHydrationGenerations.has(projectKey))evictOldest(projectHydrationGenerations,MAX_TRACKED_PROJECTS);return projectHydrationGenerations.set(projectKey,generation),{projectKey,generation}}function currentHydrationGeneration(projectKey){return projectHydrationGenerations.get(projectKey)??0}function nextSessionHydrationStamp(projectKey){return currentHydrationGeneration(projectKey)+1}function getRehydrationCache(projectKey){return rehydrationCaches.get(projectKey)}function setRehydrationCache(projectKey,cache2){if(!rehydrationCaches.has(projectKey))evictOldest(rehydrationCaches,MAX_TRACKED_PROJECTS);rehydrationCaches.set(projectKey,cache2)}function recordHydratedAggregateKeys(projectKey,keys){if(!hydratedAggregateKeys.has(projectKey))evictOldest(hydratedAggregateKeys,MAX_TRACKED_PROJECTS);hydratedAggregateKeys.set(projectKey,new Set(keys))}function hydratedAggregateKeysFor(projectKey){return hydratedAggregateKeys.get(projectKey)??new Set}function clearHydrationOwnershipState(){projectHydrationGenerations.clear(),rehydrationCaches.clear(),hydratedAggregateKeys.clear(),directoryKeyMemo.clear()}var MAX_TRACKED_PROJECTS=32,MAX_DIRECTORY_KEY_MEMO=64,projectHydrationGenerations,rehydrationCaches,hydratedAggregateKeys,directoryKeyMemo;var init_hydration_ownership=__esm(()=>{init_canonical_project();init_canonical_root();projectHydrationGenerations=new Map,rehydrationCaches=new Map,hydratedAggregateKeys=new Map,directoryKeyMemo=new Map});import{existsSync as existsSync46,mkdirSync as mkdirSync29,readFileSync as readFileSync35,writeFileSync as writeFileSync19}from"node:fs";import*as path89 from"node:path";function recordSessionStart(directory,startMs){try{let swarmDir=path89.join(directory,".swarm"),sessionDir=path89.join(swarmDir,"session"),filePath=path89.join(sessionDir,SESSION_START_FILE),line=JSON.stringify({startMs,ts:Date.now()});mkdirSync29(sessionDir,{recursive:!0}),writeFileSync19(filePath,`${line}
1243
1244
  `,{flag:"a"})}catch{}}function readEarliestSessionStart(directory){try{let filePath=path89.join(directory,".swarm","session",SESSION_START_FILE);if(!existsSync46(filePath))return null;let lines=readFileSync35(filePath,"utf-8").split(`
1244
1245
  `),validStartMs=[];for(let line of lines){if(!line.trim())continue;try{let parsed=JSON.parse(line);if(typeof parsed.startMs==="number"&&Number.isFinite(parsed.startMs))validStartMs.push(parsed.startMs)}catch{}}if(validStartMs.length===0)return null;return new Date(Math.min(...validStartMs)).toISOString()}catch{return null}}var SESSION_START_FILE="session-start.jsonl";var init_session_start_store=()=>{};import{randomUUID as randomUUID12}from"node:crypto";function parseRecordPayload(payload,label){let parsed=JSON.parse(payload);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw Error(`Invalid SQLite snapshot ${label} payload`);return parsed}function claimSnapshotSessionOwnership(sessionId,canTakeOver=!1){let existing=localSessionOwners.get(sessionId);if(existing){if(canTakeOver)existing.canTakeOver=!0;return existing.token}let token=randomUUID12();return localSessionOwners.set(sessionId,{token,canTakeOver}),token}function isSnapshotSessionOwnedLocally(sessionId){return localSessionOwners.has(sessionId)}function releaseSnapshotSessionOwnership(sessionId){localSessionOwners.delete(sessionId)}function clearSnapshotSessionOwnerships(){localSessionOwners.clear()}function nextGeneration(directory,namespace,entityKey){return(getCoordinationState(directory,namespace,entityKey)?.generation??0)+1}function writeSnapshotRows(directory,snapshot,options={}){withCoordinationTransaction(directory,()=>{transitionCoordinationState(directory,{namespace:META_NAMESPACE,entityKey:"project",generation:nextGeneration(directory,META_NAMESPACE,"project"),status:"active",payload:JSON.stringify({version:snapshot.version,writtenAt:snapshot.writtenAt,workflowSchema:snapshot.workflowSchema})});for(let[key2,aggregate]of Object.entries(snapshot.toolAggregates))transitionCoordinationState(directory,{namespace:TOOL_NAMESPACE,entityKey:key2,generation:nextGeneration(directory,TOOL_NAMESPACE,key2),status:"active",payload:JSON.stringify(aggregate)});for(let[sessionId,agentName]of Object.entries(snapshot.activeAgent)){if(options.onlyLocallyOwnedSessions&&!isSnapshotSessionOwnedLocally(sessionId))continue;if(getCoordinationState(directory,ACTIVE_AGENT_NAMESPACE,sessionId)?.status==="deleted")continue;transitionCoordinationState(directory,{namespace:ACTIVE_AGENT_NAMESPACE,entityKey:sessionId,generation:nextGeneration(directory,ACTIVE_AGENT_NAMESPACE,sessionId),status:"active",payload:JSON.stringify(agentName)})}for(let[sessionId,chain]of Object.entries(snapshot.delegationChains)){if(options.onlyLocallyOwnedSessions&&!isSnapshotSessionOwnedLocally(sessionId))continue;if(getCoordinationState(directory,DELEGATION_CHAIN_NAMESPACE,sessionId)?.status==="deleted")continue;transitionCoordinationState(directory,{namespace:DELEGATION_CHAIN_NAMESPACE,entityKey:sessionId,generation:nextGeneration(directory,DELEGATION_CHAIN_NAMESPACE,sessionId),status:"active",payload:JSON.stringify(chain)})}for(let[sessionId,session]of Object.entries(snapshot.agentSessions)){let localOwner=localSessionOwners.get(sessionId),ownerToken=localOwner?.token;if(options.onlyLocallyOwnedSessions&&!localOwner)continue;let current=getCoordinationState(directory,SESSION_NAMESPACE,sessionId),currentOwner2,deleted=null;try{if(current?.status==="deleted")deleted=JSON.parse(current.payload);else if(current)currentOwner2=JSON.parse(current.payload).ownerToken}catch{continue}if(options.onlyLocallyOwnedSessions&&currentOwner2&&currentOwner2!==ownerToken&&!localOwner?.canTakeOver)continue;if(deleted&&(!ownerToken||deleted.reason!=="stale"||deleted.ownerToken!==ownerToken))continue;let payload={session,...ownerToken?{ownerToken}:{}};transitionCoordinationState(directory,{namespace:SESSION_NAMESPACE,entityKey:sessionId,generation:nextGeneration(directory,SESSION_NAMESPACE,sessionId),status:"active",payload:JSON.stringify(payload)})}})}function importSnapshotRowsOnce(directory,snapshot,sourceDigest,source="session/state.json"){return importCoordinationOnce(directory,{source,sourceDigest,rowCount:Object.keys(snapshot.agentSessions).length,emptyNamespace:META_NAMESPACE},()=>writeSnapshotRows(directory,snapshot))}function readSnapshotRows(directory){if(!projectDbExists(directory))return null;return withCoordinationTransaction(directory,()=>{let meta3=listCoordinationStates(directory,META_NAMESPACE,1)[0];if(!meta3)return null;_snapshotStoreInternals.afterSnapshotMetaRead();let parsedMeta=parseRecordPayload(meta3.payload,"metadata");if(parsedMeta.version!==1&&parsedMeta.version!==2&&parsedMeta.version!==3)throw Error("Unsupported SQLite snapshot version");if(!Number.isFinite(parsedMeta.writtenAt))throw Error("Invalid SQLite snapshot metadata writtenAt");if(parsedMeta.workflowSchema!==void 0&&typeof parsedMeta.workflowSchema!=="string")throw Error("Invalid SQLite snapshot metadata workflowSchema");let snapshot={version:parsedMeta.version,writtenAt:parsedMeta.writtenAt,...parsedMeta.workflowSchema!==void 0&&{workflowSchema:parsedMeta.workflowSchema},toolAggregates:{},activeAgent:{},delegationChains:{},agentSessions:{}};for(let row of listCoordinationStates(directory,TOOL_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS))snapshot.toolAggregates[row.entityKey]=parseRecordPayload(row.payload,"tool aggregate");for(let row of listCoordinationStates(directory,ACTIVE_AGENT_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS)){if(row.status==="deleted")continue;let agentName=JSON.parse(row.payload);if(typeof agentName!=="string")throw Error("Invalid SQLite snapshot active-agent payload");snapshot.activeAgent[row.entityKey]=agentName}for(let row of listCoordinationStates(directory,DELEGATION_CHAIN_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS)){if(row.status==="deleted")continue;let chain=JSON.parse(row.payload);if(!Array.isArray(chain))throw Error("Invalid SQLite snapshot delegation-chain payload");snapshot.delegationChains[row.entityKey]=chain}for(let row of listCoordinationStates(directory,SESSION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS)){if(row.status==="deleted")continue;let payload=parseRecordPayload(row.payload,"agent-session");if(!payload.session||typeof payload.session!=="object"||Array.isArray(payload.session)||payload.ownerToken!==void 0&&typeof payload.ownerToken!=="string")throw Error("Invalid SQLite snapshot agent-session payload");snapshot.agentSessions[row.entityKey]=payload.session}return snapshot})}function isSnapshotSessionAuthoritativelyStale(directory,sessionId,staleDurationMs,now=Date.now()){try{if(!projectDbExists(directory)||!sessionId)return!1;let row=getCoordinationState(directory,SESSION_NAMESPACE,sessionId);if(!row||row.status==="deleted")return!0;let lastToolCallTime=parseRecordPayload(row.payload,"agent-session").session?.lastToolCallTime;if(typeof lastToolCallTime!=="number"||!Number.isFinite(lastToolCallTime))return!1;return now-lastToolCallTime>staleDurationMs}catch{return!1}}function clearSnapshotRows(directory){if(!projectDbExists(directory))return 0;let removed=0;return withCoordinationTransaction(directory,()=>{for(let namespace of SNAPSHOT_NAMESPACES)for(let row of listCoordinationStates(directory,namespace,MAX_COORDINATION_STATE_LIST_ROWS))if(deleteCoordinationState(directory,namespace,row.entityKey,row.revision))removed+=1;deleteCoordinationImports(directory,["session/state.json",SNAPSHOT_PROJECTION_SOURCE])}),removed}function deleteSnapshotSessionRows(directory,sessionId,reason="ended"){if(!projectDbExists(directory)||!sessionId)return 0;let removed=0;return withCoordinationTransaction(directory,()=>{let ownerToken=localSessionOwners.get(sessionId)?.token,sessionRow=getCoordinationState(directory,SESSION_NAMESPACE,sessionId);if(reason==="stale"&&!ownerToken)return;if(sessionRow&&sessionRow.status!=="deleted")try{let persistedOwner=JSON.parse(sessionRow.payload).ownerToken;if(persistedOwner&&persistedOwner!==ownerToken)return}catch{return}for(let namespace of[SESSION_NAMESPACE,ACTIVE_AGENT_NAMESPACE,DELEGATION_CHAIN_NAMESPACE]){let row=getCoordinationState(directory,namespace,sessionId);if(!row||row.status==="deleted")continue;if(transitionCoordinationState(directory,{namespace,entityKey:sessionId,expectedRevision:row.revision,generation:row.generation+1,status:"deleted",payload:JSON.stringify({reason,...ownerToken?{ownerToken}:{}})}).outcome==="applied")removed+=1}}),removed}var META_NAMESPACE="session.snapshot.meta",SESSION_NAMESPACE="session.snapshot.agent",TOOL_NAMESPACE="session.snapshot.tool",ACTIVE_AGENT_NAMESPACE="session.snapshot.active-agent",DELEGATION_CHAIN_NAMESPACE="session.snapshot.delegation-chain",SNAPSHOT_PROJECTION_SOURCE="session/state.sqlite-projection.json",SNAPSHOT_NAMESPACES,_snapshotStoreInternals,localSessionOwners;var init_snapshot_store=__esm(()=>{init_coordination_store();init_project_db();SNAPSHOT_NAMESPACES=[META_NAMESPACE,SESSION_NAMESPACE,TOOL_NAMESPACE,ACTIVE_AGENT_NAMESPACE,DELEGATION_CHAIN_NAMESPACE],_snapshotStoreInternals={afterSnapshotMetaRead:()=>{}},localSessionOwners=new Map});import{execFile as execFile2}from"node:child_process";function markSuggested(sessionId){if(_suggestedSessions.has(sessionId))return;if(_suggestedSessions.size>=MAX_SUGGESTED_SESSIONS){let oldest=_suggestedSessions.values().next().value;if(oldest!==void 0)_suggestedSessions.delete(oldest)}_suggestedSessions.add(sessionId)}async function countWorktrees(directory){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return 0}return new Promise((resolve47)=>{try{let child=execFile2(gitExecutable,["-C",directory,"worktree","list","--porcelain"],{timeout:GIT_TIMEOUT_MS2,windowsHide:!0,encoding:"utf-8"},(err,stdout)=>{if(err||typeof stdout!=="string"){resolve47(0);return}let count=0;for(let line of stdout.split(`
@@ -4899,6 +4900,14 @@ Mutation delegations are performed by calling the **Task** tool. Read-only advis
4899
4900
  All delegations MUST follow the receiving agent's INPUT FORMAT exactly. Do NOT invent fields, omit required fields, or force one agent's schema onto another. Every delegation MUST begin with the agent name, include \`TASK:\`, and include \`SKILLS:\` when that agent prompt supports skills.
4900
4901
  Do NOT add conversational preamble before the agent prefix. Begin directly with the agent name.
4901
4902
 
4903
+ TASK ATTRIBUTION: For task-scoped delegations, put the exact numeric plan task ID
4904
+ alone on a standalone \`TASK:\` line (for example, \`TASK: 1.1\`) and put the objective
4905
+ on the following line. When the Task arguments support an explicit field, set
4906
+ \`task_id\` to the same numeric value as a tool argument (not as prompt prose). Keep
4907
+ the numeric ID consistent across the TASK line, \`task_id\`, and any acceptance text.
4908
+ Plan-level critics and other project-wide reviews must omit task attribution rather
4909
+ than guessing from ambient prose or session state.
4910
+
4902
4911
  {{AGENT_PREFIX}}[agent]
4903
4912
  TASK: [single objective]
4904
4913
  [agent-specific fields required by that agent's INPUT FORMAT]