opencode-swarm 7.177.0 → 7.177.1
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.
- package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/agents/architect.d.ts +1 -1
- package/dist/cli/{coder-settlement-pm07553t.js → coder-settlement-c0kysest.js} +5 -5
- package/dist/cli/{config-doctor-3mwx2rwq.js → config-doctor-bqwse4pd.js} +3 -3
- package/dist/cli/{core-ty985ae1.js → core-e6vtme4x.js} +2 -2
- package/dist/cli/{curator-pch7ww87.js → curator-2xb1d80j.js} +21 -21
- package/dist/cli/{curator-llm-factory-zbs6hm60.js → curator-llm-factory-fywmb8jh.js} +21 -21
- package/dist/cli/{evidence-summary-service-cxed89n3.js → evidence-summary-service-9yxm6jkq.js} +8 -8
- package/dist/cli/{gate-evidence-ymye7yew.js → gate-evidence-43bnst3v.js} +3 -3
- package/dist/cli/{guardrail-explain-1zy8c3vn.js → guardrail-explain-gm69b76w.js} +22 -22
- package/dist/cli/{guardrail-log-pgggycf9.js → guardrail-log-j7cj3rjy.js} +5 -5
- package/dist/cli/{guardrail-reset-aghymhr5.js → guardrail-reset-jcsyfvf4.js} +21 -21
- package/dist/cli/{hive-promoter-3dp8qbqc.js → hive-promoter-hc0r0z9h.js} +21 -21
- package/dist/cli/{index-rgapg88w.js → index-1042jnb9.js} +2 -2
- package/dist/cli/{index-zbq9091c.js → index-4ygb35m1.js} +4 -4
- package/dist/cli/{index-hxdswvtv.js → index-634pjhe4.js} +4 -4
- package/dist/cli/{index-rz4gpt3n.js → index-67amf4my.js} +3 -3
- package/dist/cli/{index-nzz58tbs.js → index-7c24bb1r.js} +1 -1
- package/dist/cli/{index-5w51tawb.js → index-7ntcak58.js} +3 -3
- package/dist/cli/{index-4chr4gbq.js → index-822hhbkc.js} +4 -4
- package/dist/cli/{index-tzxk6ct7.js → index-bc4x76z7.js} +21 -21
- package/dist/cli/{index-ef2fa774.js → index-bqmxxbrw.js} +1 -1
- package/dist/cli/{index-w7aedfce.js → index-cv191ybt.js} +3 -3
- package/dist/cli/{index-zwam9stk.js → index-drgt81xf.js} +2 -2
- package/dist/cli/{index-73arkdgf.js → index-e48h8m73.js} +2 -2
- package/dist/cli/{index-0z5s71kn.js → index-epsy1rh1.js} +23 -23
- package/dist/cli/{index-by7xpk8f.js → index-fgv6qp10.js} +2 -2
- package/dist/cli/{index-r18n5f17.js → index-fnq5ac3f.js} +1 -1
- package/dist/cli/{index-9ftc8saz.js → index-fnw6zfh0.js} +1 -1
- package/dist/cli/{index-7bvzssz0.js → index-hp5eet6g.js} +4 -4
- package/dist/cli/{index-fnmt1ema.js → index-j82xdrqp.js} +2 -2
- package/dist/cli/{index-8dy3qf4q.js → index-k330631a.js} +5 -5
- package/dist/cli/{index-zzr7f594.js → index-m0cdjvtv.js} +1 -1
- package/dist/cli/{index-5frh43fj.js → index-n7nzwz0q.js} +4 -0
- package/dist/cli/{index-mcq6xs4k.js → index-qgf5xexz.js} +3 -3
- package/dist/cli/{index-z8j7jqxt.js → index-t2nf57mv.js} +2 -1
- package/dist/cli/{index-q1jterxw.js → index-t6q73twc.js} +2 -2
- package/dist/cli/{index-ebmep9me.js → index-yepxmq4f.js} +56 -56
- package/dist/cli/{index-gwnbprzk.js → index-yrs4wwfq.js} +1 -1
- package/dist/cli/index.js +22 -22
- package/dist/cli/{knowledge-escalator-praedffr.js → knowledge-escalator-j4jcpver.js} +7 -7
- package/dist/cli/{knowledge-events-sn5gs5q9.js → knowledge-events-fcpzfp2m.js} +5 -5
- package/dist/cli/{knowledge-store-838sgd97.js → knowledge-store-6evy197p.js} +1 -1
- package/dist/cli/{knowledge-validator-bsxgarqv.js → knowledge-validator-s28b1ddg.js} +2 -2
- package/dist/cli/{mcp-skh29erk.js → mcp-9kqsnehc.js} +1 -1
- package/dist/cli/{model-preflight-gk1jysa8.js → model-preflight-1pp1a4yf.js} +1 -1
- package/dist/cli/{pending-delegations-6zr5es4b.js → pending-delegations-e15f26e0.js} +2 -2
- package/dist/cli/{pr-subscriptions-x2rr3gva.js → pr-subscriptions-mqv51zvm.js} +1 -1
- package/dist/cli/{pr-workflow-gate-jx30c9vz.js → pr-workflow-gate-fj31btdv.js} +21 -21
- package/dist/cli/{scan-cursor-6h85e2g0.js → scan-cursor-tpnq7e56.js} +2 -2
- package/dist/cli/{schema-8h1b602y.js → schema-1wwcyaxp.js} +2 -2
- package/dist/cli/{scope-persistence-rb99xjr0.js → scope-persistence-332nvn9b.js} +7 -7
- package/dist/cli/{server-kdjc5aw8.js → server-19bpfaps.js} +21 -21
- package/dist/cli/{skill-generator-nz7wjabh.js → skill-generator-gn1k4yxj.js} +8 -8
- package/dist/cli/{snapshot-coordination-init-hexx2msp.js → snapshot-coordination-init-6ztt4v99.js} +21 -21
- package/dist/cli/{worktree-collision-ownership-ecwj3ehp.js → worktree-collision-ownership-q2ydb0ph.js} +2 -2
- package/dist/cli/{worktree-isolation-0x9fx30v.js → worktree-isolation-fsqe1qdv.js} +21 -21
- package/dist/events/core-events.d.ts +1 -1
- package/dist/hooks/delegation-gate.d.ts +26 -0
- package/dist/index.js +6 -6
- package/dist/tools/approve-retry-sounding-board.d.ts +5 -0
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/manifest.d.ts +1 -0
- package/dist/tools/tool-metadata.d.ts +4 -0
- package/dist/types/events.d.ts +5 -1
- 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.177.0",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"]},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",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"]},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, and profile hash. 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_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.177.1",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"]},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",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"]},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, and profile hash. 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_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
|
|
|
@@ -564,7 +564,7 @@ ${lines[i]}`),framingChecked=!0}else{let prefix=!framingChecked&&!fileEndsWithNe
|
|
|
564
564
|
`)){if(line.trim()==="")continue;try{let parsed=JSON.parse(line);if(typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)&&predicate(parsed))matches.push(parsed)}catch{}}return matches}function selfHealAuthorityKeys(directory,keys){try{let state2=loadAuthorityIndex(directory);if(state2.kind==="corrupt")return;mergeAuthorityKeys(directory,state2,keys)}catch{}}function getCoderRetryEscalationActions(directory,taskId,retryEpoch){let actions=new Set,prefix=`retry|${taskId}|${retryEpoch}|`,state2=loadAuthorityIndex(directory);if(state2.kind==="corrupt")throw Error("CORE_EVENT_AUTHORITY_INDEX_UNREADABLE");let heal=[];if(state2.kind==="ok"){for(let key of Object.keys(state2.index.entries))if(key.startsWith(prefix)){let action=key.slice(prefix.length);if(RETRY_ACTIONS.has(action))actions.add(action)}}for(let event of scanWindowFor(directory,(e)=>e.type===AUTHORITY_RETRY&&e.taskId===taskId&&e.retryEpoch===retryEpoch&&typeof e.action==="string"&&RETRY_ACTIONS.has(e.action))){let action=event.action;if(!actions.has(action)){actions.add(action);let key=authorityKeyFor(event);if(key)heal.push(key)}}if(heal.length>0)selfHealAuthorityKeys(directory,heal);return actions}function hasAuthorityEvent(directory,key,predicate){let state2=loadAuthorityIndex(directory);if(state2.kind==="corrupt")throw Error("CORE_EVENT_AUTHORITY_INDEX_UNREADABLE");if(state2.kind==="ok"&&state2.index.entries[key]!==void 0)return!0;if(scanWindowFor(directory,predicate).length>0)return selfHealAuthorityKeys(directory,[key]),!0;return!1}function hasSpecDriftAuditEvent(directory,kind,transitionId){return hasAuthorityEvent(directory,`drift|${kind}|${transitionId}`,(e)=>e.type===kind&&e.transitionId===transitionId)}function hasTaskRepairAuditEvent(directory,taskId,transitionId){return hasAuthorityEvent(directory,`repair|${taskId}|${transitionId}`,(e)=>e.type===AUTHORITY_REPAIR&&e.taskId===taskId&&e.transitionId===transitionId)}function foldPass(directory,trigger,forceFull,preloadedAuthorityState){let filePath=coreEventsFilePath(directory);if(!_internals31.existsSync(filePath))return;let view=readStoreFull(directory);if(view.manifest===null&&view.lines.length===0)return;let folded=view.manifest?cloneFolded(view.manifest.folded):emptyFolded(),now=_internals31.now(),agePruned=[],kept=[];for(let entry of view.lines){if(entry.event===null){agePruned.push(entry);continue}if(authorityKeyFor(entry.event)!==null){kept.push(entry);continue}let ts=eventTimestamp(entry.event);if(ts!==null&&now-Date.parse(ts)>_internals31.limits.ageMaxMs)agePruned.push(entry);else kept.push(entry)}let retained=[],bytes=Buffer.byteLength(JSON.stringify(view.manifest??emptyManifest()));for(let i=kept.length-1;i>=0;i-=1){let entry=kept[i],lineBytes=Buffer.byteLength(entry.line)+1;if(retained.length>=_internals31.limits.activeMaxEntries||bytes+lineBytes>_internals31.limits.activeMaxBytes)break;retained.push(entry),bytes+=lineBytes}retained.reverse();let retainedSet=new Set(retained),candidates=[];for(let entry of view.lines)if(entry.event===null)candidates.push(entry);else if(!retainedSet.has(entry))candidates.push(entry);let toFold=new Set,foldedBytes=0;for(let cand of candidates){let cb=Buffer.byteLength(cand.line)+1;if(!forceFull&&foldedBytes+cb>_internals31.limits.compactMaxBytes&&toFold.size>0)break;toFold.add(cand),foldedBytes+=cb}let indexKeys=[];for(let cand of toFold)if(cand.event!==null){let key=authorityKeyFor(cand.event);if(key)indexKeys.push(key)}if(indexKeys.length>0)mergeAuthorityKeys(directory,loadAuthorityIndex(directory),indexKeys);let agePrunedSet=new Set(agePruned),dropped=0;for(let cand of toFold)if(cand.event===null)folded.corrupt+=1;else if(foldLineInto(folded,cand.event),agePrunedSet.has(cand))dropped+=1;folded.dropped+=dropped,folded.corrupt+=view.corruptLines;let finalRetained=[];for(let entry of view.lines)if(!toFold.has(entry))finalRetained.push(entry);let manifest={...emptyManifest(),folded,updatedAt:new Date().toISOString()},outLines=[`${JSON.stringify(manifest)}`];for(let entry of finalRetained)outLines.push(entry.line);atomicReplace(directory,outLines.length>1?`${outLines.join(`
|
|
565
565
|
`)}
|
|
566
566
|
`:`${outLines[0]}
|
|
567
|
-
`),emitHealth(directory,{trigger,accepted:folded.totalEvents+finalRetained.length,compacted:toFold.size-dropped,retained:finalRetained.length,dropped,corrupt:folded.corrupt,oldest:folded.oldestTimestamp,newest:folded.newestTimestamp,bytes:fileSizeOrZero(filePath),limitBytes:_internals31.limits.activeMaxBytes},preloadedAuthorityState)}function runMaintenance(directory){try{let filePath=coreEventsFilePath(directory);if(!_internals31.existsSync(filePath))return;let drainThreshold=_internals31.limits.activeMaxBytes+_internals31.limits.headerMaxBytes+2048;withCoreEventStoreLock(directory,()=>{let authorityState=loadAuthorityIndex(directory);foldPass(directory,"compaction",!1,authorityState);let prevSize=Number.POSITIVE_INFINITY;for(let pass=0;pass<64;pass+=1){let size=fileSizeOrZero(filePath);if(size<=drainThreshold)break;if(size>=prevSize)break;prevSize=size,foldPass(directory,"compaction",!1,authorityState)}return!0})}catch{warnThrottled("maintenance pass failed")}}function finalizeCoreEventsForClose(directory){try{let filePath=coreEventsFilePath(directory);if(!_internals31.existsSync(filePath))return;withCoreEventStoreLock(directory,()=>{let authorityState=loadAuthorityIndex(directory),prev=Number.POSITIVE_INFINITY;for(let pass=0;pass<1e4;pass+=1){let view=readStoreFull(directory);if(view.manifest!==null)break;if(view.lines.length===0)break;if(view.lines.length>=prev)break;prev=view.lines.length,foldPass(directory,"close",!1,authorityState)}return foldPass(directory,"close",!0,authorityState),!0})}catch{warnThrottled("finalize failed")}}function emitCoreEventsHealth(directory,payload,preloadedAuthorityState){let authorityCount=0,authorityEvicted=0,state2=preloadedAuthorityState??loadAuthorityIndex(directory);if(state2.kind==="ok")authorityCount=Object.keys(state2.index.entries).length,authorityEvicted=state2.index.evicted;let healthPayload={trigger:payload.trigger,accepted_count:payload.accepted,compacted_count:payload.compacted,retained_count:payload.retained,dropped_count:payload.dropped,corrupt_count:payload.corrupt,authority_index_count:authorityCount,authority_evicted_count:authorityEvicted,oldest_timestamp:payload.oldest,newest_timestamp:payload.newest,bytes:payload.bytes,limit_bytes:payload.limitBytes};try{telemetry.coreEventsHealth(healthPayload),observeStoreHealth({directory,kind:"core_events_health",payload:healthPayload})}catch{}}function emitHealth(directory,payload,preloadedAuthorityState){_internals31.emitHealth(directory,payload,preloadedAuthorityState)}var CORE_EVENT_LIMITS,AUTHORITY_RETRY="coder_retry_circuit_breaker",AUTHORITY_REPAIR="task_workflow_repaired",AUTHORITY_DRIFT_ACK="spec_drift_acknowledged",AUTHORITY_DRIFT_REPAIR="spec_drift_repaired",PUBLICATION_LIVE_EVENT_TYPES,PUBLICATION_TERMINAL_EVENT_TYPES,RETRY_ACTIONS,MANIFEST_TYPE="swarm-events-manifest",MANIFEST_SCHEMA=1,BY_TYPE_MAX_KEYS=64,BY_TYPE_OTHER="__other__",_internals31,LOCK_RETRY_ATTEMPTS=20,LOCK_RETRY_DELAY_MS=5,LOCK_STALE_MS=300000,sleepScratch,RENAME_RETRY_DELAYS_MS2,RETRYABLE_RENAME_CODES2,_appendCount=0,_lastWarnAt=0,CORE_EVENT_LOCKED="CORE_EVENT_STORE_LOCKED",CORE_EVENT_LINE_TOO_LARGE="CORE_EVENT_LINE_TOO_LARGE",CORE_EVENT_NO_STORE="CORE_EVENT_NO_STORE";var init_core_events=__esm(()=>{init_learning_health();init_telemetry();init_logger();CORE_EVENT_LIMITS={activeMaxBytes:2097152,activeMaxEntries:20000,ageMaxMs:604800000,compactMaxBytes:524288,readMaxBytes:3145728,checkInterval:25,warnCooldownMs:60000,headerMaxBytes:65536,authorityIndexMaxEntries:20000,maxLineBytes:262144},PUBLICATION_LIVE_EVENT_TYPES=new Set(["pr_feedback_publication_armed","pr_feedback_publication_migrated","pr_feedback_push_attempt_started"]),PUBLICATION_TERMINAL_EVENT_TYPES=new Set(["pr_feedback_publication_invalidated","pr_feedback_published","pr_feedback_publication_cancelled"]),RETRY_ACTIONS=new Set(["sounding_board_consultation","simplification","user_escalation"]);_internals31={appendFileSync:fs14.appendFileSync,readFileSync:fs14.readFileSync,existsSync:fs14.existsSync,mkdirSync:fs14.mkdirSync,statSync:fs14.statSync,renameSync:fs14.renameSync,writeFileSync:fs14.writeFileSync,unlinkSync:fs14.unlinkSync,openSync:fs14.openSync,closeSync:fs14.closeSync,readSync:fs14.readSync,now:()=>Date.now(),limits:CORE_EVENT_LIMITS,emitHealth:emitCoreEventsHealth};sleepScratch=new Int32Array(new SharedArrayBuffer(4));RENAME_RETRY_DELAYS_MS2=[10,25,50,100,200],RETRYABLE_RENAME_CODES2=new Set(["EPERM","EBUSY","EACCES","EEXIST"])});import{createHash as createHash16}from"node:crypto";import*as fs15 from"node:fs";import*as path29 from"node:path";function samePath2(left,right){let normalize5=(value)=>process.platform==="win32"?path29.resolve(value).toLowerCase():path29.resolve(value);return normalize5(left)===normalize5(right)}function assertSafeRequirementsParent(directory,create){assertProjectRoot(directory,void 0,"task gate requirements");let rootStat=fs15.lstatSync(directory);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: project root is not a regular directory");let canonicalRoot=fs15.realpathSync(directory),segments=[".swarm","evidence","task-gate-requirements"],current=canonicalRoot;for(let segment of segments){current=path29.join(current,segment);let info;try{info=fs15.lstatSync(current)}catch(error49){if(error49.code==="ENOENT"){if(!create)return current;try{fs15.mkdirSync(current)}catch(mkdirError){if(mkdirError.code!=="EEXIST")throw mkdirError}info=fs15.lstatSync(current)}else throw error49}if(info.isSymbolicLink()||!info.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent is redirected or not a directory");let canonicalCurrent=fs15.realpathSync(current);if(!samePath2(canonicalCurrent,current))throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent escaped the project root")}return current}function safeTaskGateRequirementsReceiptPath(directory,taskId,createParent){let parent=assertSafeRequirementsParent(directory,createParent);return path29.join(parent,`${taskId}.jsonl`)}function sha256(value){return createHash16("sha256").update(value).digest("hex")}function canonicalReceiptPayload(receipt){let routeBinding=receipt.routeBinding?{role:receipt.routeBinding.role,identity:receipt.routeBinding.identity,sessionId:receipt.routeBinding.sessionId,taskId:receipt.routeBinding.taskId,slotId:receipt.routeBinding.slotId,callId:receipt.routeBinding.callId,childSessionId:receipt.routeBinding.childSessionId,generation:receipt.routeBinding.generation}:void 0;return JSON.stringify({schemaVersion:receipt.schemaVersion,taskId:receipt.taskId,generation:receipt.generation,normalizedRole:receipt.normalizedRole,testEngineerExempt:receipt.testEngineerExempt,requiredGates:[...receipt.requiredGates],sourceEvent:receipt.sourceEvent,sourceTransitionId:receipt.sourceTransitionId,recordedAt:receipt.recordedAt,...routeBinding?{routeBinding}:{},previousChainHash:receipt.previousChainHash})}function computeChainHash(receipt){return sha256(canonicalReceiptPayload(receipt))}function routeBindingFromEvent(event){if(event.type!=="stage_b_completed"||!event.routeBinding)return;let binding=event.routeBinding;if(binding.role!==event.gate||!binding.sessionId||!binding.taskId||!binding.slotId||!binding.callId||!binding.childSessionId||typeof binding.generation!=="number")return;return binding}function readBoundedTextFile(filePath){let pathStat;try{pathStat=fs15.lstatSync(filePath)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}if(pathStat.isSymbolicLink()||!pathStat.isFile())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt path is not a regular file");if(pathStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);let descriptor=fs15.openSync(filePath,fs15.constants.O_RDONLY|(fs15.constants.O_NOFOLLOW??0));try{let openedStat=fs15.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt changed while being opened");if(openedStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${openedStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);return fs15.readFileSync(descriptor,"utf-8")}finally{fs15.closeSync(descriptor)}}async function readTaskGateRequirementsReceipts(directory,taskId){let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!1),text=readBoundedTextFile(filePath);if(text===null)return[];let receipts=[];for(let line of text.split(`
|
|
567
|
+
`),emitHealth(directory,{trigger,accepted:folded.totalEvents+finalRetained.length,compacted:toFold.size-dropped,retained:finalRetained.length,dropped,corrupt:folded.corrupt,oldest:folded.oldestTimestamp,newest:folded.newestTimestamp,bytes:fileSizeOrZero(filePath),limitBytes:_internals31.limits.activeMaxBytes},preloadedAuthorityState)}function runMaintenance(directory){try{let filePath=coreEventsFilePath(directory);if(!_internals31.existsSync(filePath))return;let drainThreshold=_internals31.limits.activeMaxBytes+_internals31.limits.headerMaxBytes+2048;withCoreEventStoreLock(directory,()=>{let authorityState=loadAuthorityIndex(directory);foldPass(directory,"compaction",!1,authorityState);let prevSize=Number.POSITIVE_INFINITY;for(let pass=0;pass<64;pass+=1){let size=fileSizeOrZero(filePath);if(size<=drainThreshold)break;if(size>=prevSize)break;prevSize=size,foldPass(directory,"compaction",!1,authorityState)}return!0})}catch{warnThrottled("maintenance pass failed")}}function finalizeCoreEventsForClose(directory){try{let filePath=coreEventsFilePath(directory);if(!_internals31.existsSync(filePath))return;withCoreEventStoreLock(directory,()=>{let authorityState=loadAuthorityIndex(directory),prev=Number.POSITIVE_INFINITY;for(let pass=0;pass<1e4;pass+=1){let view=readStoreFull(directory);if(view.manifest!==null)break;if(view.lines.length===0)break;if(view.lines.length>=prev)break;prev=view.lines.length,foldPass(directory,"close",!1,authorityState)}return foldPass(directory,"close",!0,authorityState),!0})}catch{warnThrottled("finalize failed")}}function emitCoreEventsHealth(directory,payload,preloadedAuthorityState){let authorityCount=0,authorityEvicted=0,state2=preloadedAuthorityState??loadAuthorityIndex(directory);if(state2.kind==="ok")authorityCount=Object.keys(state2.index.entries).length,authorityEvicted=state2.index.evicted;let healthPayload={trigger:payload.trigger,accepted_count:payload.accepted,compacted_count:payload.compacted,retained_count:payload.retained,dropped_count:payload.dropped,corrupt_count:payload.corrupt,authority_index_count:authorityCount,authority_evicted_count:authorityEvicted,oldest_timestamp:payload.oldest,newest_timestamp:payload.newest,bytes:payload.bytes,limit_bytes:payload.limitBytes};try{telemetry.coreEventsHealth(healthPayload),observeStoreHealth({directory,kind:"core_events_health",payload:healthPayload})}catch{}}function emitHealth(directory,payload,preloadedAuthorityState){_internals31.emitHealth(directory,payload,preloadedAuthorityState)}var CORE_EVENT_LIMITS,AUTHORITY_RETRY="coder_retry_circuit_breaker",AUTHORITY_REPAIR="task_workflow_repaired",AUTHORITY_DRIFT_ACK="spec_drift_acknowledged",AUTHORITY_DRIFT_REPAIR="spec_drift_repaired",PUBLICATION_LIVE_EVENT_TYPES,PUBLICATION_TERMINAL_EVENT_TYPES,RETRY_ACTIONS,MANIFEST_TYPE="swarm-events-manifest",MANIFEST_SCHEMA=1,BY_TYPE_MAX_KEYS=64,BY_TYPE_OTHER="__other__",_internals31,LOCK_RETRY_ATTEMPTS=20,LOCK_RETRY_DELAY_MS=5,LOCK_STALE_MS=300000,sleepScratch,RENAME_RETRY_DELAYS_MS2,RETRYABLE_RENAME_CODES2,_appendCount=0,_lastWarnAt=0,CORE_EVENT_LOCKED="CORE_EVENT_STORE_LOCKED",CORE_EVENT_LINE_TOO_LARGE="CORE_EVENT_LINE_TOO_LARGE",CORE_EVENT_NO_STORE="CORE_EVENT_NO_STORE";var init_core_events=__esm(()=>{init_learning_health();init_telemetry();init_logger();CORE_EVENT_LIMITS={activeMaxBytes:2097152,activeMaxEntries:20000,ageMaxMs:604800000,compactMaxBytes:524288,readMaxBytes:3145728,checkInterval:25,warnCooldownMs:60000,headerMaxBytes:65536,authorityIndexMaxEntries:20000,maxLineBytes:262144},PUBLICATION_LIVE_EVENT_TYPES=new Set(["pr_feedback_publication_armed","pr_feedback_publication_migrated","pr_feedback_push_attempt_started"]),PUBLICATION_TERMINAL_EVENT_TYPES=new Set(["pr_feedback_publication_invalidated","pr_feedback_published","pr_feedback_publication_cancelled"]),RETRY_ACTIONS=new Set(["sounding_board_consultation","simplification","user_escalation","sounding_board_manual_approval"]);_internals31={appendFileSync:fs14.appendFileSync,readFileSync:fs14.readFileSync,existsSync:fs14.existsSync,mkdirSync:fs14.mkdirSync,statSync:fs14.statSync,renameSync:fs14.renameSync,writeFileSync:fs14.writeFileSync,unlinkSync:fs14.unlinkSync,openSync:fs14.openSync,closeSync:fs14.closeSync,readSync:fs14.readSync,now:()=>Date.now(),limits:CORE_EVENT_LIMITS,emitHealth:emitCoreEventsHealth};sleepScratch=new Int32Array(new SharedArrayBuffer(4));RENAME_RETRY_DELAYS_MS2=[10,25,50,100,200],RETRYABLE_RENAME_CODES2=new Set(["EPERM","EBUSY","EACCES","EEXIST"])});import{createHash as createHash16}from"node:crypto";import*as fs15 from"node:fs";import*as path29 from"node:path";function samePath2(left,right){let normalize5=(value)=>process.platform==="win32"?path29.resolve(value).toLowerCase():path29.resolve(value);return normalize5(left)===normalize5(right)}function assertSafeRequirementsParent(directory,create){assertProjectRoot(directory,void 0,"task gate requirements");let rootStat=fs15.lstatSync(directory);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: project root is not a regular directory");let canonicalRoot=fs15.realpathSync(directory),segments=[".swarm","evidence","task-gate-requirements"],current=canonicalRoot;for(let segment of segments){current=path29.join(current,segment);let info;try{info=fs15.lstatSync(current)}catch(error49){if(error49.code==="ENOENT"){if(!create)return current;try{fs15.mkdirSync(current)}catch(mkdirError){if(mkdirError.code!=="EEXIST")throw mkdirError}info=fs15.lstatSync(current)}else throw error49}if(info.isSymbolicLink()||!info.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent is redirected or not a directory");let canonicalCurrent=fs15.realpathSync(current);if(!samePath2(canonicalCurrent,current))throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent escaped the project root")}return current}function safeTaskGateRequirementsReceiptPath(directory,taskId,createParent){let parent=assertSafeRequirementsParent(directory,createParent);return path29.join(parent,`${taskId}.jsonl`)}function sha256(value){return createHash16("sha256").update(value).digest("hex")}function canonicalReceiptPayload(receipt){let routeBinding=receipt.routeBinding?{role:receipt.routeBinding.role,identity:receipt.routeBinding.identity,sessionId:receipt.routeBinding.sessionId,taskId:receipt.routeBinding.taskId,slotId:receipt.routeBinding.slotId,callId:receipt.routeBinding.callId,childSessionId:receipt.routeBinding.childSessionId,generation:receipt.routeBinding.generation}:void 0;return JSON.stringify({schemaVersion:receipt.schemaVersion,taskId:receipt.taskId,generation:receipt.generation,normalizedRole:receipt.normalizedRole,testEngineerExempt:receipt.testEngineerExempt,requiredGates:[...receipt.requiredGates],sourceEvent:receipt.sourceEvent,sourceTransitionId:receipt.sourceTransitionId,recordedAt:receipt.recordedAt,...routeBinding?{routeBinding}:{},previousChainHash:receipt.previousChainHash})}function computeChainHash(receipt){return sha256(canonicalReceiptPayload(receipt))}function routeBindingFromEvent(event){if(event.type!=="stage_b_completed"||!event.routeBinding)return;let binding=event.routeBinding;if(binding.role!==event.gate||!binding.sessionId||!binding.taskId||!binding.slotId||!binding.callId||!binding.childSessionId||typeof binding.generation!=="number")return;return binding}function readBoundedTextFile(filePath){let pathStat;try{pathStat=fs15.lstatSync(filePath)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}if(pathStat.isSymbolicLink()||!pathStat.isFile())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt path is not a regular file");if(pathStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);let descriptor=fs15.openSync(filePath,fs15.constants.O_RDONLY|(fs15.constants.O_NOFOLLOW??0));try{let openedStat=fs15.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt changed while being opened");if(openedStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${openedStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);return fs15.readFileSync(descriptor,"utf-8")}finally{fs15.closeSync(descriptor)}}async function readTaskGateRequirementsReceipts(directory,taskId){let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!1),text=readBoundedTextFile(filePath);if(text===null)return[];let receipts=[];for(let line of text.split(`
|
|
568
568
|
`)){if(!line.trim())continue;let parsed=TaskGateRequirementsReceiptSchema.parse(JSON.parse(line));if(parsed.taskId!==taskId||parsed.routeBinding!==void 0&&parsed.routeBinding.taskId!==taskId)throw Error(`TASK_GATE_REQUIREMENTS_IDENTITY_MISMATCH: expected ${taskId}, found ${parsed.taskId}`);let{chainHash,...withoutChainHash}=parsed;if(computeChainHash(withoutChainHash)!==chainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed hash validation`);let previousChainHash=receipts.at(-1)?.chainHash??null;if(parsed.previousChainHash!==previousChainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed linkage validation`);receipts.push(parsed)}return receipts}function readTaskGateRequirementsReceiptsSync(directory,taskId){let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!1),text=readBoundedTextFile(filePath);if(text===null)return[];let receipts=[];for(let line of text.split(`
|
|
569
569
|
`)){if(!line.trim())continue;let parsed=TaskGateRequirementsReceiptSchema.parse(JSON.parse(line));if(parsed.taskId!==taskId||parsed.routeBinding!==void 0&&parsed.routeBinding.taskId!==taskId)throw Error(`TASK_GATE_REQUIREMENTS_IDENTITY_MISMATCH: expected ${taskId}, found ${parsed.taskId}`);let{chainHash,...withoutChainHash}=parsed;if(computeChainHash(withoutChainHash)!==chainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed hash validation`);let previousChainHash=receipts.at(-1)?.chainHash??null;if(parsed.previousChainHash!==previousChainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed linkage validation`);receipts.push(parsed)}return receipts}function routeEvidenceFromTaskGateRequirements(receipts){let latestByDispatch=new Map;for(let receipt of receipts){let binding=receipt.routeBinding;if(!binding)continue;let dispatchKey=[binding.role,binding.sessionId,binding.taskId,binding.callId,binding.childSessionId,String(binding.generation)].join("\x00");latestByDispatch.set(dispatchKey,binding)}return[...latestByDispatch.values()]}function isLegacyTaskGateRequirementsChain(receipts){return receipts.length>0&&receipts.every((receipt)=>!receipt.routeBinding)}function deriveReceiptRole(event){switch(event.type){case"accepted_mutation":case"dispatch_attempted":case"dispatch_no_mutation":if(typeof event.agentType==="string"&&event.agentType.trim().length>0)return{normalizedRole:event.agentType.trim(),testEngineerExempt:event.agentType==="coder"?event.context?.testEngineerExempt===!0:null};return null;case"stage_b_completed":case"gate_recorded":return{normalizedRole:event.gate,testEngineerExempt:null};default:return null}}function shouldAppendReceipt(current,next,role){if(next.required_gates.length===0)return!1;let currentGeneration=current?.workflow?.generation??-1,nextGeneration=next.workflow?.generation??-1;if(current===null)return!0;if(JSON.stringify(current.required_gates)!==JSON.stringify(next.required_gates))return!0;if((current.test_engineer_exempt??null)!==role.testEngineerExempt)return!0;return currentGeneration!==nextGeneration}async function appendTaskGateRequirementsReceiptIfNeeded(directory,taskId,current,next,event){let role=deriveReceiptRole(event),routeBinding=routeBindingFromEvent(event);if(routeBinding&&routeBinding.taskId!==taskId)throw Error(`TASK_GATE_REQUIREMENTS_ROUTE_IDENTITY_MISMATCH: expected ${taskId}, found ${routeBinding.taskId}`);if(!role||!shouldAppendReceipt(current,next,role)&&!routeBinding)return;let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!0),receipts=await readTaskGateRequirementsReceipts(directory,taskId),latest=receipts.at(-1),baseReceipt={schemaVersion:1,taskId,generation:next.workflow?.generation??0,normalizedRole:role.normalizedRole,testEngineerExempt:role.testEngineerExempt,requiredGates:[...next.required_gates],sourceEvent:event.type,sourceTransitionId:event.transitionId??null,recordedAt:new Date().toISOString(),previousChainHash:latest?.chainHash??null,...routeBinding?{routeBinding}:{}},receipt={...baseReceipt,chainHash:computeChainHash(baseReceipt)};if(latest&&latest.generation===receipt.generation&&latest.normalizedRole===receipt.normalizedRole&&latest.testEngineerExempt===receipt.testEngineerExempt&&JSON.stringify(latest.requiredGates)===JSON.stringify(receipt.requiredGates)&&latest.sourceTransitionId===receipt.sourceTransitionId&&JSON.stringify(latest.routeBinding??null)===JSON.stringify(receipt.routeBinding??null))return;let lines=[...receipts,receipt].map((entry)=>JSON.stringify(entry));assertSafeRequirementsParent(directory,!1),await atomicWriteFile(filePath,`${lines.join(`
|
|
570
570
|
`)}
|
|
@@ -1205,7 +1205,7 @@ ${expectedBodyBlock}
|
|
|
1205
1205
|
`).slice(0,3).join(`
|
|
1206
1206
|
`),headingMatch=/^\s*(APPROVED|NEEDS_REVISION|REJECTED)\s*$/im.exec(nextLines);if(headingMatch)return headingMatch[1].toUpperCase()}let lines=text.split(`
|
|
1207
1207
|
`),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(`
|
|
1208
|
-
`).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((resolve46)=>setTimeout(resolve46,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);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=path86.join(directory,".swarm","plan.json");if(fs52.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}}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&&fs52.existsSync(path86.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&&isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0;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 currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;if(!scopeVerdictAllowsParallel(directory,plan))return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; the active phase's pending tasks are NOT provably file-disjoint (overlapping or unknown declared scopes) — SERIAL fallback active (v8 automatic safety). 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 isParallelGuidancePhaseComplete(phase){return phase.status==="complete"||phase.status==="completed"||phase.status==="closed"}function collectPendingTaskIdsForActivePhase(plan){let currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));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).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=path86.resolve(directory),planPath=path86.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path86.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path86.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs52.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 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 _internals79.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);if(preflightAgent.startsWith("critic")){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")throw telemetry.modelUnresolved(preflightAgent,criticModel,"plan-critic dispatch preflight"),Error(`PLAN_CRITIC_MODEL_UNRESOLVED: the ${exactPreflightAgent} agent's effective model "${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 "${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}}}}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),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),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),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(`
|
|
1208
|
+
`).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((resolve46)=>setTimeout(resolve46,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);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=path86.join(directory,".swarm","plan.json");if(fs52.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);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=path86.join(directory,".swarm","plan.json");if(fs52.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&&fs52.existsSync(path86.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&&isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0;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 currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;if(!scopeVerdictAllowsParallel(directory,plan))return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; the active phase's pending tasks are NOT provably file-disjoint (overlapping or unknown declared scopes) — SERIAL fallback active (v8 automatic safety). 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 isParallelGuidancePhaseComplete(phase){return phase.status==="complete"||phase.status==="completed"||phase.status==="closed"}function collectPendingTaskIdsForActivePhase(plan){let currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));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).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=path86.resolve(directory),planPath=path86.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path86.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path86.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs52.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 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 _internals79.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);if(preflightAgent.startsWith("critic")){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")throw telemetry.modelUnresolved(preflightAgent,criticModel,"plan-critic dispatch preflight"),Error(`PLAN_CRITIC_MODEL_UNRESOLVED: the ${exactPreflightAgent} agent's effective model "${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 "${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}}}}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),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),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),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(`
|
|
1209
1209
|
`),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 _internals79.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 fs52.promises.readFile(path86.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(`
|
|
1210
1210
|
`);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),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(`
|
|
1211
1211
|
`);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}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. `+`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.`+(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);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 _internals79.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 _internals79.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).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(`
|
|
@@ -3796,7 +3796,7 @@ Actionability (direct text only; required unless knowledge.promotion_require_act
|
|
|
3796
3796
|
`,"utf-8"),invalidateCachedArtifact(filePath)}catch{}}function deriveAction(tool3){let toolLower=normalizeToolNameLowerCase(tool3??"");if(isTaskToolId(tool3))return"delegate";if(["write","edit","apply_patch","swarm_apply_patch"].includes(toolLower))return"edit";if(["read","glob","grep","search"].includes(toolLower))return"read";if(["bash","shell"].includes(toolLower))return"execute";if(toolLower==="test_runner")return"test";return"tool_use"}function fnv1aHex(text){let hash5=2166136261;for(let i=0;i<text.length;i++)hash5^=text.charCodeAt(i),hash5=Math.imul(hash5,16777619)>>>0;return hash5.toString(16).padStart(8,"0")}function redactCommandSecrets(text){let redacted=redactSecrets(text).replace(URL_CREDENTIALS_PATTERN,"$1[REDACTED:url_credentials]@"),beginMarker=redacted.search(/-----BEGIN [A-Z ]*PRIVATE KEY-----/);return beginMarker===-1?redacted:`${redacted.slice(0,beginMarker)}[REDACTED:private_key_block]`}function normalizeCommandTarget(command){let normalized=command.trim().replace(/\s+/g," "),bounded=normalized.length>MAX_COMMAND_TARGET_LENGTH?`${normalized.slice(0,MAX_COMMAND_TARGET_LENGTH-3)}...`:normalized,redacted=redactCommandSecrets(bounded);if(redacted===bounded)return redacted;let prefix=`#${fnv1aHex(bounded)} `,room=MAX_COMMAND_TARGET_LENGTH-prefix.length,body=redacted.length>room?`${redacted.slice(0,room-3)}...`:redacted;return`${prefix}${body}`}function extractTarget(tool3,args2){if(!args2)return"";if(tool3.toLowerCase()==="task"){let subagentType=args2.subagent_type;if(typeof subagentType==="string"&&subagentType.length>0)return subagentType}let targetFields=["filePath","path","file","target"];for(let field of targetFields){let value=args2[field];if(typeof value==="string"&&value.length>0)return value}let toolLower=tool3.toLowerCase();if(toolLower==="bash"||toolLower==="shell"||toolLower==="execute"||toolLower==="command"){let command=args2.command;if(typeof command==="string"&&command.trim().length>0)return normalizeCommandTarget(command);let description=args2.description;if(typeof description==="string"&&description.length>0){let safeDescription=redactCommandSecrets(description.slice(0,REDACTION_SCAN_WINDOW));return safeDescription.length>30?`${safeDescription.slice(0,27)}...`:safeDescription}let argsStr=args2.args;if(typeof argsStr==="string"&&argsStr.trim().length>0)return normalizeCommandTarget(argsStr)}return""}function extractIntent(tool3,args2){if(!args2)return"";if(tool3.toLowerCase()==="task"){let{prompt,description}=args2,safeText=redactCommandSecrets((typeof prompt==="string"?prompt:typeof description==="string"?description:"").slice(0,REDACTION_SCAN_WINDOW));if(safeText.length>100)return`${safeText.slice(0,97)}...`;return safeText}let intentFields=["description","task"];for(let field of intentFields){let value=args2[field];if(typeof value==="string"&&value.length>0){let safe=redactCommandSecrets(value.slice(0,REDACTION_SCAN_WINDOW));return safe.length>200?`${safe.slice(0,197)}...`:safe}}return""}function mapResult(verdict){if(verdict==="success")return"success";if(verdict==="failure")return"failure";return"pending"}function stepSeedKey(sessionId,directory){return`${trajectoryStepGeneration()}:${compositeSessionKey(directory,sessionId)}`}function markStepSeedGate(gateKey){if(stepSeedGate.has(gateKey))return;while(stepSeedGate.size>=MAX_STEP_SEED_GATE_SESSIONS){let oldest=stepSeedGate.keys().next().value;if(oldest===void 0)break;stepSeedGate.delete(oldest)}stepSeedGate.set(gateKey,!0)}async function ensureSessionStepSeeded(sessionId,directory){let gateKey=stepSeedKey(sessionId,directory);if(stepSeedGate.has(gateKey))return;let inFlight=stepSeedPromises.get(gateKey);if(inFlight!==void 0){await inFlight;return}let promise3=(async()=>{let lastStep=await getCurrentStep(sessionId,directory);if(lastStep>0)seedTrajectoryStepCounter(sessionId,directory,lastStep);markStepSeedGate(gateKey)})().catch(()=>{markStepSeedGate(gateKey)}).finally(()=>{stepSeedPromises.delete(gateKey)});stepSeedPromises.set(gateKey,promise3),await promise3}function invalidateStepSeedGate(sessionId){if(sessionId===void 0){stepSeedGate.clear();return}let suffix=sessionKeySuffix(sessionId);for(let gateKey of stepSeedGate.keys())if(gateKey.endsWith(suffix))stepSeedGate.delete(gateKey)}function createTrajectoryLoggerHook(config3,_directory2){let enabled=config3.enabled??!0,maxLines=config3.max_lines??500;return{toolAfter:async(input,output)=>{if(!enabled)return;let sessionId=input.sessionID;if(consumeDeniedCallMarker(sessionId,input.callID)){callStartTimes.delete(`${sessionId}:${input.callID}`);return}let session=swarmState.agentSessions.get(sessionId);if(!session?.delegationActive)return;let taskId=session.currentTaskId;if(!taskId)return;let startKey=`${sessionId}:${input.callID}`,startTime=callStartTimes.get(startKey)??Date.now();callStartTimes.delete(startKey);let elapsed_ms=Date.now()-startTime,agentName=swarmState.activeAgent.get(sessionId)??session?.agentName??"unknown",args_summary=summarizeArgs(input.args,200),verdict=deriveVerdict(output);await ensureSessionStepSeeded(sessionId,_directory2);let step=nextTrajectoryStep(sessionId,_directory2),action2=deriveAction(input.tool),target=extractTarget(input.tool,input.args),intent=extractIntent(input.tool,input.args),result=mapResult(verdict),entry={step,agent:agentName,action:action2,target,intent,timestamp:new Date().toISOString(),result,tool:input.tool,args_summary,verdict,elapsed_ms},sanitized=sanitizeTaskId2(taskId),relativePath2=path229.join("evidence",sanitized,"trajectory.jsonl"),trajectoryPath=validateSwarmPath(_directory2,relativePath2);try{await fs131.mkdir(path229.dirname(trajectoryPath),{recursive:!0});let line=`${JSON.stringify(entry)}
|
|
3797
3797
|
`;await fs131.appendFile(trajectoryPath,line,"utf-8"),await truncateTrajectoryFile(trajectoryPath,maxLines)}catch{}try{await appendTrajectoryEntry(sessionId,entry,_directory2,maxLines)}catch{}}}}function markDeniedCall(sessionId,callID){if(!callID)return;let now2=Date.now();for(let[key3,expiresAt]of deniedCallMarkers)if(expiresAt<=now2)deniedCallMarkers.delete(key3);let key2=`${sessionId}:${callID}`;deniedCallMarkers.delete(key2),deniedCallMarkers.set(key2,now2+DENIED_CALL_TTL_MS);while(deniedCallMarkers.size>MAX_DENIED_CALL_MARKERS){let oldest=deniedCallMarkers.keys().next().value;if(oldest===void 0||oldest===key2)break;deniedCallMarkers.delete(oldest)}}function consumeDeniedCallMarker(sessionId,callID){if(!callID)return!1;let key2=`${sessionId}:${callID}`,expiresAt=deniedCallMarkers.get(key2);if(expiresAt===void 0)return!1;return deniedCallMarkers.delete(key2),expiresAt>Date.now()}async function recordDeniedToolCall(sessionID,input,errorMessage2,directory,options){try{let session=swarmState.agentSessions.get(sessionID);if(!session?.delegationActive)return;let maxLines=options?.maxLines??500,startKey=`${sessionID}:${input.callID}`,startTime=callStartTimes.get(startKey);if(startTime!==void 0)callStartTimes.delete(startKey);let elapsed_ms=startTime===void 0?0:Date.now()-startTime,agentName=swarmState.activeAgent.get(sessionID)??session.agentName??"unknown",code=deriveGateDenialCode(errorMessage2);await ensureSessionStepSeeded(sessionID,directory);let entry={step:nextTrajectoryStep(sessionID,directory),agent:agentName,action:deriveAction(input.tool),target:extractTarget(input.tool,input.args),intent:`denied: ${code}`,timestamp:new Date().toISOString(),result:"failure",tool:input.tool,args_summary:summarizeArgs(input.args,200),verdict:"failure",elapsed_ms,callID:input.callID};markDeniedCall(sessionID,input.callID);try{await appendTrajectoryEntry(sessionID,entry,directory,maxLines)}catch{}let taskId=session.currentTaskId;if(!taskId)return;try{let relativePath2=path229.join("evidence",sanitizeTaskId2(taskId),"trajectory.jsonl"),trajectoryPath=validateSwarmPath(directory,relativePath2);await fs131.mkdir(path229.dirname(trajectoryPath),{recursive:!0}),await fs131.appendFile(trajectoryPath,`${JSON.stringify(entry)}
|
|
3798
3798
|
`,"utf-8"),await truncateTrajectoryFile(trajectoryPath,maxLines)}catch{}}catch{}}function clearTrajectoryStep(sessionId){clearTrajectoryStepCounters(sessionId),invalidateStepSeedGate(sessionId)}function summarizeArgs(args2,maxLength){if(!args2||Object.keys(args2).length===0)return"";let summaries=[];for(let[key2,value]of Object.entries(args2)){if(SENSITIVE_FIELDS.has(key2)||isSensitiveKey(key2)){summaries.push(`${key2}:[REDACTED]`);continue}if(value===null||value===void 0)summaries.push(`${key2}:null`);else if(typeof value==="string"){let window2=value.slice(0,REDACTION_SCAN_WINDOW),redacted=redactCommandSecrets(window2),truncated=redacted.length>50?`${redacted.slice(0,50)}...`:redacted;summaries.push(`${key2}:"${truncated}"`)}else if(typeof value==="number"||typeof value==="boolean")summaries.push(`${key2}:${String(value)}`);else if(Array.isArray(value)){let itemSummary=value.length>3?`${value.slice(0,3).map(String).join(",")},...(+${value.length-3})`:value.map(String).join(",");summaries.push(`${key2}:[${itemSummary}]`)}else if(typeof value==="object"){let keys=Object.keys(value);summaries.push(`${key2}:{${keys.join(",")}}`)}else summaries.push(`${key2}:${typeof value}`)}let summary=summaries.join(" ");return summary.length>maxLength?`${summary.slice(0,maxLength-3)}...`:summary}function deriveVerdict(output){if(output.metadata&&typeof output.metadata==="object"&&!Array.isArray(output.metadata)){let meta3=output.metadata;if(typeof meta3.verdict==="string"&&meta3.verdict.length>0)return meta3.verdict;if(meta3.success===!1||meta3.passed===!1)return"failure";if(meta3.success===!0||meta3.passed===!0)return"success"}let outputStr=String(output.output??"");if(outputStr.startsWith("Error:")||outputStr.startsWith("error:")||outputStr.startsWith("Error: "))return"failure";return"success"}var callStartTimes,SENSITIVE_FIELDS,SENSITIVE_SUBSTRINGS,URL_CREDENTIALS_PATTERN,REDACTION_SCAN_WINDOW=4096,MAX_COMMAND_TARGET_LENGTH=200,stepSeedGate,MAX_STEP_SEED_GATE_SESSIONS=500,stepSeedPromises,MAX_DENIED_CALL_MARKERS=500,DENIED_CALL_TTL_MS=300000,deniedCallMarkers;var init_trajectory_logger=__esm(()=>{init_manager2();init_redaction();init_trajectory_store();init_state2();init_canonical_root();init_swarm_artifact_cache();init_gate_denial_tracker();init_normalize_tool_name();init_trajectory_step_state();init_utils2();callStartTimes=new Map,SENSITIVE_FIELDS=new Set(["password","token","secret","api_key","apikey","authorization","access_token","refresh_token","private_key","secret_key","credential","auth","bearer","x-api-key","session_id","cookie"]),SENSITIVE_SUBSTRINGS=["key","secret","token","password","auth","credential","private","certificate","bearer","session","cookie"];URL_CREDENTIALS_PATTERN=/\b([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/g;stepSeedGate=new Map,stepSeedPromises=new Map;deniedCallMarkers=new Map});import*as fs132 from"node:fs";import*as path230 from"node:path";function errorMessage2(err){if(err instanceof Error)return err.message;return String(err)}async function releaseKnowledgeGateObligations(directory,sessionID){let results=[],live;try{live=await _internals187.queryLiveMemberships(directory,{session_id:sessionID,include_terminal:!0})}catch(err){return[`⚠️ Knowledge gate state not cleared: receipt authority unavailable (${errorMessage2(err)})`]}if(!live.ok)return[`⚠️ Knowledge gate state not cleared: receipt authority unavailable (${live.code})`];let pending=live.memberships.filter((membership)=>membership.exposure_kind==="architect_directive"&&!membership.application_marker&&membership.gate_release?.membership_event_id!==membership.membership_event_id);if(pending.length===0)return["⏭️ No pending knowledge gate obligations for this session"];let byTrace=new Map;for(let membership of pending){let group=byTrace.get(membership.trace_id)??[];group.push(membership),byTrace.set(membership.trace_id,group)}let committedCount=0,releasedPairs=[];for(let[traceId,group]of byTrace){let committed=await _internals187.commitGateReleaseBatch(directory,{trace_id:traceId,session_id:sessionID,items:group.map((membership)=>({entry_id:membership.entry_id,source:"application_gate_session_reset_release",reason:"/swarm reset-session operator escape (#2398)"}))});if(!committed.ok){results.push(`⚠️ Failed to release knowledge gate obligations on trace ${sanitizeDiagnosticText(traceId,64)}: ${committed.code}`);continue}committedCount+=committed.committed.length;for(let item of committed.committed)releasedPairs.push(`${traceId}/${item.entry_id}`);if(committed.rejected.length>0)results.push(`⚠️ Partially released trace ${sanitizeDiagnosticText(traceId,64)}: ${committed.rejected.map((item)=>item.reason).join("; ")}`)}if(committedCount===0)return results;if(committedCount<pending.length)results.push(`⚠️ Released ${committedCount} of ${pending.length} pending knowledge gate obligation(s) — ${pending.length-committedCount} not released; see warnings above`);else results.push(`✅ Released ${committedCount} pending knowledge gate obligation(s) for this session`);try{appendCoreEventSync(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_session_reset_clear",sessionID,released_pairs:releasedPairs})}catch{}return results}async function handleResetSessionCommand(directory,args2,sessionID){let results=[],snapshotResetGuard;try{if(snapshotResetGuard=await _internals187.beginSnapshotCoordinationReset(directory),snapshotResetGuard.closeError){if(snapshotResetGuard.priorUnsettled)return results.push(`❌ Snapshot coordination close timed out; reset aborted to avoid racing an in-flight initializer: ${errorMessage2(snapshotResetGuard.closeError)}`),snapshotResetGuard.release(),results.join(`
|
|
3799
|
-
`);throw snapshotResetGuard.closeError}}catch(err){results.push(`⚠️ Snapshot coordination close failed (continuing with reset): ${errorMessage2(err)}`)}try{let backup=_internals187.backupSwarmStateBeforeReset(directory,"reset-session",["session"]);if(backup.backupDir&&backup.copied.length>0){let rel=path230.relative(directory,backup.backupDir);results.push(`\uD83D\uDCE6 Backed up session state to ${rel}/ (restore by copying files back into .swarm/session/)`)}for(let w of backup.warnings)results.push(`⚠️ Backup warning: ${w}`)}catch(err){results.push(`⚠️ Auto-backup failed (continuing with reset): ${err instanceof Error?err.message:String(err)}`)}let snapshotAuthorityCleared=!1;try{let removed=_internals187.clearSnapshotRows(directory);snapshotAuthorityCleared=!0,results.push(removed>0?`✅ Deleted ${removed} authoritative session snapshot row(s)`:"⏭️ SQLite session snapshot already clean")}catch(err){results.push(`❌ Failed to clear SQLite session snapshot: ${errorMessage2(err)}`)}let snapshotProjectionCleared=!0;try{let projectionPath=validateSwarmPath(directory,SNAPSHOT_PROJECTION_FILE);if(fs132.existsSync(projectionPath))fs132.unlinkSync(projectionPath),results.push(`✅ Deleted .swarm/${SNAPSHOT_PROJECTION_FILE}`)}catch(err){snapshotProjectionCleared=!1,results.push(`❌ Failed to delete ${SNAPSHOT_PROJECTION_FILE}: ${errorMessage2(err)}`)}let statePath2,legacySnapshotCleared=!0;try{if(statePath2=validateSwarmPath(directory,"session/state.json"),fs132.existsSync(statePath2))fs132.unlinkSync(statePath2),results.push("✅ Deleted .swarm/session/state.json");else results.push("⏭️ state.json not found (already clean)")}catch{legacySnapshotCleared=!1,results.push("❌ Failed to delete state.json")}let sessionDir=statePath2?path230.dirname(statePath2):void 0,sessionFiles=[];if(sessionDir&&fs132.existsSync(sessionDir))try{sessionFiles=fs132.readdirSync(sessionDir)}catch(err){results.push(`❌ Failed to read session directory: ${errorMessage2(err)}`)}for(let file3 of sessionFiles){if(file3==="state.json"||file3===path230.basename(SNAPSHOT_PROJECTION_FILE))continue;let filePath=path230.join(sessionDir,file3);try{if(!fs132.existsSync(filePath))continue;if(!fs132.lstatSync(filePath).isFile())continue;fs132.unlinkSync(filePath),results.push(`✓ Deleted ${file3}`)}catch(err){results.push(`❌ Failed to delete ${file3}: ${errorMessage2(err)}`)}}let sessionCount=swarmState.agentSessions.size;for(let[sessionId,session]of swarmState.agentSessions)resetPrmSessionState(session,sessionId),clearTrajectoryStep(sessionId);if(swarmState.agentSessions.clear(),clearSnapshotSessionOwnerships(),results.push(`✅ Cleared ${sessionCount} in-memory agent session(s)`),sessionID)clearSessionActionCircuits(sessionID),results.push("✅ Released this session’s guardrail circuit(s) (audited; re-delegate to re-arm)");let chainCount=swarmState.delegationChains.size;swarmState.delegationChains.clear(),results.push(`✅ Cleared ${chainCount} delegation chain(s)`);let activeAgentCount=swarmState.activeAgent.size;if(swarmState.activeAgent.clear(),results.push(`✅ Cleared ${activeAgentCount} active-agent mapping(s)`),snapshotResetGuard&&snapshotAuthorityCleared&&snapshotProjectionCleared&&legacySnapshotCleared)snapshotResetGuard.release();if(sessionID)try{results.push(...await _internals187.releaseKnowledgeGateObligations(directory,sessionID))}catch(err){results.push(`⚠️ Knowledge gate state not cleared: ${errorMessage2(err)}`)}else results.push("⚠️ Knowledge gate obligations not released: no session context on this invocation");swarmState.gateDenialCounts.clear(),swarmState.currentCriticalShownIds.clear(),results.push("✅ Cleared in-memory knowledge gate denial state");let preserveWorktrees=!1;try{let{results:settlementResults,truncated}=await _internals187.recoverStaleCoderSettlements(directory,{force:!0});if(settlementResults.length===0)results.push("⏭️ No coder settlements to recover");for(let outcome of settlementResults)switch(outcome.outcome){case"recovered":results.push(`✅ Recovered coder settlement ${outcome.taskId} (${outcome.accepted?"changes attributed":"no workspace change to attribute"})`);break;case"already_terminal":results.push(`⏭️ Coder settlement ${outcome.taskId} already ${outcome.state}`);break;case"owned_in_process":results.push(`ℹ️ Coder settlement ${outcome.taskId} still registered in flight (${sanitizeDiagnosticText(outcome.transitionId)}) — its dispatch may be genuinely running; not force-recovered`);break;case"owned_by_live_foreign_pid":results.push(`ℹ️ Coder settlement ${outcome.taskId} owned by live process pid ${outcome.processId} (another OpenCode instance) — not touched; run /swarm recover there after closing it`);break;case"unreadable_wal":results.push(`⚠️ Coder settlement WAL ${outcome.taskId} is unreadable — inspect .swarm/coder-settlements/${outcome.taskId}.json`);break;case"error":results.push(`⚠️ Coder settlement ${outcome.taskId} recovery failed: ${sanitizeDiagnosticText(outcome.message,512)}`);break;default:results.push(`⚠️ Coder settlement ${outcome.taskId}: unknown outcome`);break}if(truncated)results.push("⚠️ More settlement WALs exist than the recovery scan cap (200) — older settlements were NOT recovered. Re-run /swarm reset-session after the tasks above are settled.");let forcedRecovered=settlementResults.filter((outcome)=>outcome.outcome==="recovered"&&outcome.forced).length;if(forcedRecovered>0)results.push(`⚠️ Released in-process ownership for ${forcedRecovered} dispatch(es) before recovery — if any was genuinely still running, its completion will report CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT (safe to ignore; the settlement is already recovered).`);if(preserveWorktrees=settlementResults.some((outcome)=>outcome.outcome==="error"||outcome.outcome==="unreadable_wal"),preserveWorktrees)results.push("⚠️ Preserved .swarm-worktrees/ because at least one settlement recovery failed — a worktree referenced by an unsettled WAL would become unrecoverable if deleted. Resolve the failures above (re-run /swarm reset-session or /swarm recover) before clearing worktrees.")}catch(err){preserveWorktrees=!0,results.push(`⚠️ Coder settlement recovery failed (continuing with reset): ${errorMessage2(err)}`)}try{if(preserveWorktrees)results.push("⏭️ Skipped worktree reclamation (see above)");else{let confirmArg=args2.find((a)=>a.startsWith("--confirm=")),confirmToken=confirmArg?confirmArg.slice(10):void 0,candidates=[];for(let base of resolveWorktreeEnumerationBases(directory)){if(!fs132.existsSync(base))continue;for(let sessionEntry of fs132.readdirSync(base,{withFileTypes:!0})){if(!sessionEntry.isDirectory())continue;let sessionDir2=path230.join(base,sessionEntry.name);for(let laneEntry of fs132.readdirSync(sessionDir2,{withFileTypes:!0}))if(laneEntry.isDirectory())candidates.push(path230.join(sessionDir2,laneEntry.name))}}if(candidates.length===0)results.push("⏭️ No worktree lanes to reclaim");else{for(let lane of candidates)closeProjectDb(lane);let livePaths=new Set(_internals187.listLiveLaneOwners(directory).live.map((owner)=>owner.lanePath)),own=[],foreign=[],unprovable=[];for(let candidate of candidates){let marker=probeGitMarker(path230.join(candidate,".git"));if(marker==="uncertain"){unprovable.push(candidate);continue}if(marker==="gitless"){if(isPathUnderSwarmWorktreeBase(candidate,directory))own.push(candidate);else unprovable.push(candidate);continue}if(resolveWorktreeRepoOwnership(candidate,directory).owned)own.push(candidate);else foreign.push(candidate)}for(let lane of foreign)results.push(`ℹ️ Preserved "${lane}" — owned by a different repository; never deleted by this project.`);for(let lane of unprovable)results.push(`ℹ️ Preserved "${lane}" — ownership unprovable (git-less outside the project worktree base, or unreadable metadata); never deleted by this project.`);if(confirmToken){let scope=own.filter((lane)=>probeGitMarker(path230.join(lane,".git"))==="present"||isPathUnderSwarmWorktreeBase(lane,directory)).map((lane)=>({path:lane,reason:"confirmed reset-session purge"})),execution=executeDestructivePurge(own[0]??"",directory,confirmToken,{candidates:scope});if(execution.ok)results.push(`✅ Removed ${execution.purged?.length??0} confirmed worktree lane(s)`);else results.push(`⚠️ Confirmed purge rejected: ${execution.reason}`)}else{let removedCount=0,preservedOwn=[];for(let lane of own){if(livePaths.has(lane)){preservedOwn.push(lane);continue}if((await _internals187.removeOwnedWorktreeDir(lane,directory)).status==="removed")removedCount++;else preservedOwn.push(lane)}if(removedCount>0)results.push(`✅ Removed ${removedCount} clean worktree lane(s)`);if(preservedOwn.length>0){let scope=preservedOwn.map((lane)=>({path:lane,reason:"uncommitted or live-owned work"})),preview=previewDestructivePurge(preservedOwn[0],directory,{candidates:scope});for(let line of preview.previewLines)results.push(` ${line}`);let token=issueConfirmToken(preservedOwn[0],directory,{candidates:scope});results.push(`\uD83D\uDD10 Preserved ${preservedOwn.length} lane(s) containing uncommitted or live work. Destroying them requires confirmation: re-run /swarm reset-session with --confirm=${token} (valid 15 minutes).`)}}}}}catch(err){results.push(`⚠️ Failed to reclaim worktree lanes: ${errorMessage2(err)}`)}try{let branchResult=await _internals187.cleanupOrphanedBranches(directory,[]);if(branchResult.removed.length>0)results.push(`✅ Removed ${branchResult.removed.length} orphan swarm-lane branch(es)`);if(branchResult.errors.length>0)results.push(`⚠️ Failed to remove ${branchResult.errors.length} branch(es): ${branchResult.errors.map((e)=>e.error).join("; ")}`);if(branchResult.skippedRecoveryBranches&&branchResult.skippedRecoveryBranches.length>0)results.push(`ℹ️ Preserved ${branchResult.skippedRecoveryBranches.length} branch(es) with unresolved merge-back recovery records (run /swarm status to inspect)`);if(branchResult.recoveryReadError)results.push("⚠️ Skipped all lane-branch deletions: .swarm/recovery/ was unreadable (fail-safe). Resolve or clear corrupt recovery records and re-run.")}catch(err){results.push(`⚠️ Failed to cleanup orphan branches: ${errorMessage2(err)}`)}return["## Session State Reset","",...results,"","Session state cleared. Plan, evidence, and knowledge preserved.","","**All circuit breakers and revision limits have been cleared.** You can continue in this session — fresh state will be initialized automatically on the next tool call."].join(`
|
|
3799
|
+
`);throw snapshotResetGuard.closeError}}catch(err){results.push(`⚠️ Snapshot coordination close failed (continuing with reset): ${errorMessage2(err)}`)}try{let backup=_internals187.backupSwarmStateBeforeReset(directory,"reset-session",["session"]);if(backup.backupDir&&backup.copied.length>0){let rel=path230.relative(directory,backup.backupDir);results.push(`\uD83D\uDCE6 Backed up session state to ${rel}/ (restore by copying files back into .swarm/session/)`)}for(let w of backup.warnings)results.push(`⚠️ Backup warning: ${w}`)}catch(err){results.push(`⚠️ Auto-backup failed (continuing with reset): ${err instanceof Error?err.message:String(err)}`)}let snapshotAuthorityCleared=!1;try{let removed=_internals187.clearSnapshotRows(directory);snapshotAuthorityCleared=!0,results.push(removed>0?`✅ Deleted ${removed} authoritative session snapshot row(s)`:"⏭️ SQLite session snapshot already clean")}catch(err){results.push(`❌ Failed to clear SQLite session snapshot: ${errorMessage2(err)}`)}let snapshotProjectionCleared=!0;try{let projectionPath=validateSwarmPath(directory,SNAPSHOT_PROJECTION_FILE);if(fs132.existsSync(projectionPath))fs132.unlinkSync(projectionPath),results.push(`✅ Deleted .swarm/${SNAPSHOT_PROJECTION_FILE}`)}catch(err){snapshotProjectionCleared=!1,results.push(`❌ Failed to delete ${SNAPSHOT_PROJECTION_FILE}: ${errorMessage2(err)}`)}let statePath2,legacySnapshotCleared=!0;try{if(statePath2=validateSwarmPath(directory,"session/state.json"),fs132.existsSync(statePath2))fs132.unlinkSync(statePath2),results.push("✅ Deleted .swarm/session/state.json");else results.push("⏭️ state.json not found (already clean)")}catch{legacySnapshotCleared=!1,results.push("❌ Failed to delete state.json")}let sessionDir=statePath2?path230.dirname(statePath2):void 0,sessionFiles=[];if(sessionDir&&fs132.existsSync(sessionDir))try{sessionFiles=fs132.readdirSync(sessionDir)}catch(err){results.push(`❌ Failed to read session directory: ${errorMessage2(err)}`)}for(let file3 of sessionFiles){if(file3==="state.json"||file3===path230.basename(SNAPSHOT_PROJECTION_FILE))continue;let filePath=path230.join(sessionDir,file3);try{if(!fs132.existsSync(filePath))continue;if(!fs132.lstatSync(filePath).isFile())continue;fs132.unlinkSync(filePath),results.push(`✓ Deleted ${file3}`)}catch(err){results.push(`❌ Failed to delete ${file3}: ${errorMessage2(err)}`)}}let sessionCount=swarmState.agentSessions.size;for(let[sessionId,session]of swarmState.agentSessions)resetPrmSessionState(session,sessionId),clearTrajectoryStep(sessionId);if(swarmState.agentSessions.clear(),clearSnapshotSessionOwnerships(),results.push(`✅ Cleared ${sessionCount} in-memory agent session(s)`),sessionID)clearSessionActionCircuits(sessionID),results.push("✅ Released this session’s guardrail circuit(s) (audited; re-delegate to re-arm)");let chainCount=swarmState.delegationChains.size;swarmState.delegationChains.clear(),results.push(`✅ Cleared ${chainCount} delegation chain(s)`);let activeAgentCount=swarmState.activeAgent.size;if(swarmState.activeAgent.clear(),results.push(`✅ Cleared ${activeAgentCount} active-agent mapping(s)`),snapshotResetGuard&&snapshotAuthorityCleared&&snapshotProjectionCleared&&legacySnapshotCleared)snapshotResetGuard.release();if(sessionID)try{results.push(...await _internals187.releaseKnowledgeGateObligations(directory,sessionID))}catch(err){results.push(`⚠️ Knowledge gate state not cleared: ${errorMessage2(err)}`)}else results.push("⚠️ Knowledge gate obligations not released: no session context on this invocation");swarmState.gateDenialCounts.clear(),swarmState.currentCriticalShownIds.clear(),results.push("✅ Cleared in-memory knowledge gate denial state");let preserveWorktrees=!1;try{let{results:settlementResults,truncated}=await _internals187.recoverStaleCoderSettlements(directory,{force:!0});if(settlementResults.length===0)results.push("⏭️ No coder settlements to recover");for(let outcome of settlementResults)switch(outcome.outcome){case"recovered":results.push(`✅ Recovered coder settlement ${outcome.taskId} (${outcome.accepted?"changes attributed":"no workspace change to attribute"})`);break;case"already_terminal":results.push(`⏭️ Coder settlement ${outcome.taskId} already ${outcome.state}`);break;case"owned_in_process":results.push(`ℹ️ Coder settlement ${outcome.taskId} still registered in flight (${sanitizeDiagnosticText(outcome.transitionId)}) — its dispatch may be genuinely running; not force-recovered`);break;case"owned_by_live_foreign_pid":results.push(`ℹ️ Coder settlement ${outcome.taskId} owned by live process pid ${outcome.processId} (another OpenCode instance) — not touched; run /swarm recover there after closing it`);break;case"unreadable_wal":results.push(`⚠️ Coder settlement WAL ${outcome.taskId} is unreadable — inspect .swarm/coder-settlements/${outcome.taskId}.json`);break;case"error":results.push(`⚠️ Coder settlement ${outcome.taskId} recovery failed: ${sanitizeDiagnosticText(outcome.message,512)}`);break;default:results.push(`⚠️ Coder settlement ${outcome.taskId}: unknown outcome`);break}if(truncated)results.push("⚠️ More settlement WALs exist than the recovery scan cap (200) — older settlements were NOT recovered. Re-run /swarm reset-session after the tasks above are settled.");let forcedRecovered=settlementResults.filter((outcome)=>outcome.outcome==="recovered"&&outcome.forced).length;if(forcedRecovered>0)results.push(`⚠️ Released in-process ownership for ${forcedRecovered} dispatch(es) before recovery — if any was genuinely still running, its completion will report CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT (safe to ignore; the settlement is already recovered).`);if(preserveWorktrees=settlementResults.some((outcome)=>outcome.outcome==="error"||outcome.outcome==="unreadable_wal"),preserveWorktrees)results.push("⚠️ Preserved .swarm-worktrees/ because at least one settlement recovery failed — a worktree referenced by an unsettled WAL would become unrecoverable if deleted. Resolve the failures above (re-run /swarm reset-session or /swarm recover) before clearing worktrees.")}catch(err){preserveWorktrees=!0,results.push(`⚠️ Coder settlement recovery failed (continuing with reset): ${errorMessage2(err)}`)}try{if(preserveWorktrees)results.push("⏭️ Skipped worktree reclamation (see above)");else{let confirmArg=args2.find((a)=>a.startsWith("--confirm=")),confirmToken=confirmArg?confirmArg.slice(10):void 0,candidates=[];for(let base of resolveWorktreeEnumerationBases(directory)){if(!fs132.existsSync(base))continue;for(let sessionEntry of fs132.readdirSync(base,{withFileTypes:!0})){if(!sessionEntry.isDirectory())continue;let sessionDir2=path230.join(base,sessionEntry.name);for(let laneEntry of fs132.readdirSync(sessionDir2,{withFileTypes:!0}))if(laneEntry.isDirectory())candidates.push(path230.join(sessionDir2,laneEntry.name))}}if(candidates.length===0)results.push("⏭️ No worktree lanes to reclaim");else{for(let lane of candidates)closeProjectDb(lane);let livePaths=new Set(_internals187.listLiveLaneOwners(directory).live.map((owner)=>owner.lanePath)),own=[],foreign=[],unprovable=[];for(let candidate of candidates){let marker=probeGitMarker(path230.join(candidate,".git"));if(marker==="uncertain"){unprovable.push(candidate);continue}if(marker==="gitless"){if(isPathUnderSwarmWorktreeBase(candidate,directory))own.push(candidate);else unprovable.push(candidate);continue}if(resolveWorktreeRepoOwnership(candidate,directory).owned)own.push(candidate);else foreign.push(candidate)}for(let lane of foreign)results.push(`ℹ️ Preserved "${lane}" — owned by a different repository; never deleted by this project.`);for(let lane of unprovable)results.push(`ℹ️ Preserved "${lane}" — ownership unprovable (git-less outside the project worktree base, or unreadable metadata); never deleted by this project.`);if(confirmToken){let scope=own.filter((lane)=>probeGitMarker(path230.join(lane,".git"))==="present"||isPathUnderSwarmWorktreeBase(lane,directory)).map((lane)=>({path:lane,reason:"confirmed reset-session purge"})),execution=executeDestructivePurge(own[0]??"",directory,confirmToken,{candidates:scope});if(execution.ok)results.push(`✅ Removed ${execution.purged?.length??0} confirmed worktree lane(s)`);else results.push(`⚠️ Confirmed purge rejected: ${execution.reason}`)}else{let removedCount=0,preservedOwn=[];for(let lane of own){if(livePaths.has(lane)){preservedOwn.push(lane);continue}if((await _internals187.removeOwnedWorktreeDir(lane,directory)).status==="removed")removedCount++;else preservedOwn.push(lane)}if(removedCount>0)results.push(`✅ Removed ${removedCount} clean worktree lane(s)`);if(preservedOwn.length>0){let scope=preservedOwn.map((lane)=>({path:lane,reason:"uncommitted or live-owned work"})),preview=previewDestructivePurge(preservedOwn[0],directory,{candidates:scope});for(let line of preview.previewLines)results.push(` ${line}`);let token=issueConfirmToken(preservedOwn[0],directory,{candidates:scope});results.push(`\uD83D\uDD10 Preserved ${preservedOwn.length} lane(s) containing uncommitted or live work. Destroying them requires confirmation: re-run /swarm reset-session with --confirm=${token} (valid 15 minutes).`)}}}}}catch(err){results.push(`⚠️ Failed to reclaim worktree lanes: ${errorMessage2(err)}`)}try{let branchResult=await _internals187.cleanupOrphanedBranches(directory,[]);if(branchResult.removed.length>0)results.push(`✅ Removed ${branchResult.removed.length} orphan swarm-lane branch(es)`);if(branchResult.errors.length>0)results.push(`⚠️ Failed to remove ${branchResult.errors.length} branch(es): ${branchResult.errors.map((e)=>e.error).join("; ")}`);if(branchResult.skippedRecoveryBranches&&branchResult.skippedRecoveryBranches.length>0)results.push(`ℹ️ Preserved ${branchResult.skippedRecoveryBranches.length} branch(es) with unresolved merge-back recovery records (run /swarm status to inspect)`);if(branchResult.recoveryReadError)results.push("⚠️ Skipped all lane-branch deletions: .swarm/recovery/ was unreadable (fail-safe). Resolve or clear corrupt recovery records and re-run.")}catch(err){results.push(`⚠️ Failed to cleanup orphan branches: ${errorMessage2(err)}`)}return["## Session State Reset","",...results,"","Session state cleared. Plan, evidence, and knowledge preserved.","","In-memory circuit breakers and revision limits have been cleared. Durable per-task retry gates (the coder retry circuit breaker, bound to commit settlement in the events audit log and .swarm/evidence/) intentionally survive this reset. If a task is blocked with TASK_RETRY_CRITIC_REQUIRED waiting for a critic_sounding_board APPROVED verdict that was already obtained, have the architect record it with the approve_retry_sounding_board tool."].join(`
|
|
3800
3800
|
`)}var _internals187;var init_reset_session=__esm(()=>{init_lane_context();init_project_db();init_core_events();init_action_circuit();init_init_orphan_recovery();init_knowledge_receipt_ledger();init_trajectory_logger();init_utils2();init_lane_owners();init_prm();init_path_identity();init_snapshot_coordination_init();init_snapshot_store();init_snapshot_writer();init_state2();init_coder_settlement();init_core3();init_merge2();init_ownership();init_destructive_purge();init_reset_backup();_internals187={cleanupOrphanedBranches,removeOwnedWorktreeDir,listLiveLaneOwners,backupSwarmStateBeforeReset,recoverStaleCoderSettlements,queryLiveMemberships,commitGateReleaseBatch,beginSnapshotCoordinationReset,clearSnapshotRows,releaseKnowledgeGateObligations}});async function handleRetrieveCommand(directory,args2){let summaryId=args2[0];if(!summaryId)return["## Swarm Retrieve","","Usage: `/swarm retrieve <id>`","","Example: `/swarm retrieve S1`","","Retrieves the full output that was replaced by a summary."].join(`
|
|
3801
3801
|
`);try{let fullOutput=await loadFullOutput(directory,summaryId);if(fullOutput===null)return`## Summary Not Found
|
|
3802
3802
|
|
|
@@ -7273,7 +7273,7 @@ Did you mean one of these sections?
|
|
|
7273
7273
|
${hint}`}]}return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:errors5}}let resultContent=hunkResult.appliedLines.join(`
|
|
7274
7274
|
`);if(resultContent===""&&!dryRun&&!allowDeletes&&content.length>0)return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0,errors:[{hunkIndex:0,type:"delete-not-allowed",message:`Patch would delete all content from ${targetPath}. Set allowDeletes to true to permit file deletion.`}]};let finalContent;if(resultContent==="")finalContent="";else{let withLineEnding=originalLineEnding===`\r
|
|
7275
7275
|
`?resultContent.replace(/\n/g,`\r
|
|
7276
|
-
`):resultContent;finalContent=ensureFinalNewline(withLineEnding,originalEndsWithNewline)}if(finalContent===content)return{file:targetPath,status:"no-changes",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0};if(!dryRun)atomicWriteFileSync3(fullPath,finalContent);return{file:targetPath,status:"applied",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0}}function buildErrorResult(message){return{success:!1,files:[{file:"",status:"error",hunks:0,hunksApplied:0,hunksFailed:0,errors:[{hunkIndex:0,type:"context-mismatch",message}]}],summary:{totalFiles:0,applied:0,failed:1,totalHunks:0}}}function isUnsupportedPatchFormat(patchText){let trimmed=patchText.trimStart();return trimmed.startsWith("*** Begin Patch")||trimmed.startsWith("*** Update File")||trimmed.startsWith("*** Add File")||trimmed.startsWith("*** Delete File")||trimmed.startsWith("*** End Patch")}var swarmApplyPatch2=createSwarmTool({description:"Apply a unified diff patch to workspace files. Validates paths, matches context exactly, and writes atomically. Coder-scoped write tool. Use standard unified diff format (--- a/file / +++ b/file / @@ hunks). Indented patches (e.g. inside a fenced markdown/YAML block) are automatically dedented to column 0 before parsing — the diff body itself may be indented. Does NOT support *** Begin Patch / *** Update File payloads — use the native apply_patch tool for those. Accepts the payload as `patch` (canonical) or any of the aliases `patchText`, `patch_text`, `patchPayload` (#2206); the resolver picks the first non-empty one.",args:{patch:exports_external.string().optional().describe("Unified diff text to parse and apply (optional when an alias below carries the payload)"),patchText:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),patch_text:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),patchPayload:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),files:exports_external.array(exports_external.string()).min(1).describe("Array of target file paths the patch is expected to touch. Every parsed target must appear in this list."),dryRun:exports_external.boolean().optional().default(!1).describe("Validate without writing files (default: false)"),allowCreates:exports_external.boolean().optional().default(!1).describe("Allow creating new files from patches with --- /dev/null (default: false)"),allowDeletes:exports_external.boolean().optional().default(!1).describe("Allow deleting files from patches with +++ /dev/null (default: false)")},execute:async(args2,directory)=>{if(!args2||typeof args2!=="object")return JSON.stringify(buildErrorResult("Could not parse swarm_apply_patch arguments"),null,2);let obj=args2,patchText=[obj.patch,obj.patchText,obj.patch_text,obj.patchPayload].find((value)=>typeof value==="string"&&value.length>0)??"",files=obj.files??[],dryRun=obj.dryRun??!1,allowCreates=obj.allowCreates??!1,allowDeletes=obj.allowDeletes??!1,{config:config3}=_internals242.loadPluginConfigWithMeta(directory),fuzzyMatch=config3.apply_patch?.fuzzy_match===!0,fuzzyMatchContextAware=config3.apply_patch?.fuzzy_match_context_aware===!0,hunkOptions=fuzzyMatch||fuzzyMatchContextAware?{fuzzyMatch,fuzzyMatchContextAware}:void 0;if(!existsSync152(directory))return JSON.stringify(buildErrorResult("Workspace directory does not exist"),null,2);if(files.length===0)return JSON.stringify(buildErrorResult("files array cannot be empty"),null,2);if(!patchText||patchText.trim()==="")return JSON.stringify(buildErrorResult("patch text cannot be empty"),null,2);if(isUnsupportedPatchFormat(patchText))return JSON.stringify(buildErrorResult("Unsupported patch format: *** Begin Patch / *** Update File style payloads are not supported by swarm_apply_patch. Use the native apply_patch tool for this format, or provide a standard unified diff (--- a/file / +++ b/file / @@ hunks)."),null,2);for(let filePath of files){let validationError=validatePatchTargetPath(filePath,directory);if(validationError)return JSON.stringify(buildErrorResult(validationError),null,2)}let{files:parsedFiles,error:parseError}=parseUnifiedDiff2(patchText);if(parseError)return JSON.stringify(buildErrorResult(parseError),null,2);if(parsedFiles.length===0)return JSON.stringify({success:!0,dryRun,files:[],summary:{totalFiles:0,applied:0,failed:0,totalHunks:0}},null,2);let declaredFileSet=new Set(files),undeclaredTargets=[];for(let fileDiff of parsedFiles){let targetPath=fileDiff.isDelete?fileDiff.oldPath:fileDiff.newPath;if(targetPath&&targetPath!=="/dev/null"&&!declaredFileSet.has(targetPath))undeclaredTargets.push(targetPath)}if(undeclaredTargets.length>0)return JSON.stringify(buildErrorResult(`Patch targets files not in the declared files array: ${undeclaredTargets.join(", ")}`),null,2);let parsedTargetSet=new Set(parsedFiles.map((fd)=>fd.isDelete?fd.oldPath:fd.newPath).filter(Boolean)),extraFiles=files.filter((f)=>!parsedTargetSet.has(f)),fileResults=[],totalApplied=0,totalFailed=0,totalHunks=0;for(let fileDiff of parsedFiles){let targetPath=fileDiff.isDelete?fileDiff.oldPath:fileDiff.newPath,fullPath=path293.resolve(directory,targetPath);totalHunks+=fileDiff.hunks.length;let result=processFileDiff(fileDiff,targetPath,fullPath,directory,dryRun,allowCreates,allowDeletes,hunkOptions);if(fileResults.push(result),result.status==="applied"||result.status==="created")totalApplied++;else if(result.status==="error")totalFailed++}let output={success:totalFailed===0,dryRun,files:fileResults,summary:{totalFiles:fileResults.length,applied:totalApplied,failed:totalFailed,totalHunks}};if(extraFiles.length>0)return JSON.stringify({...output,warnings:[`files[] contains entries not targeted by the patch: ${extraFiles.join(", ")}`]},null,2);return JSON.stringify(output,null,2)}});init_zod();init_delegation_gate();init_create_tool();var ApprovePlanCriticArgsSchema=exports_external.object({reason:exports_external.string().trim().min(1).max(500).describe('Why a manual approval is being recorded (e.g. "critic returned APPROVED but the verdict format did not match the mechanical recorder"). Audited to .swarm/events.jsonl.')}).strict();async function executeApprovePlanCritic(args2,directory,context={}){let parsed=ApprovePlanCriticArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid approve_plan_critic call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"approve_plan_critic requires an active sessionID"});try{let summary=await forceRecordPlanCriticApproval(directory,context.sessionID,{reason:parsed.data.reason,userConfirmed:!1});return JSON.stringify({success:!0,plan_id:summary.planId,recorded_at:summary.recordedAt,method:"manual_override",user_confirmed:!1,message:"Recorded a manual plan_critic_gate approval snapshot. The critic_pre_plan execution gate will now allow coder delegation. An audit event was appended to .swarm/events.jsonl."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var approve_plan_critic=createSwarmTool({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 snapshot recorder failed to persist it (verdict-format mismatch, dispatch-signal miss, or a plan.json read race — issue #2012). The snapshot carries a distinct method: "manual_override" audit marker. Architect-only: the active session must be the architect. Prefer re-running MODE: CRITIC-GATE first; use this only as an escape hatch when a legitimate APPROVED was lost, or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (e.g. a files_touched-only scope reconciliation) — the reason must state which case applies. A reason is required and audited to .swarm/events.jsonl. The human-confirmed variant is /swarm approve-plan-critic.',args:{reason:ApprovePlanCriticArgsSchema.shape.reason},execute:executeApprovePlanCritic});init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs168 from"node:fs";import*as path294 from"node:path";var AST_GREP_TIMEOUT_MS=1e4,AST_GREP_MAX_STDOUT_BYTES=8388608,AST_GREP_MAX_STDERR_BYTES=65536,DEFAULT_MAX_RESULTS2=100,HARD_CAP_RESULTS2=1e4,MAX_PATTERN_LENGTH=20000;function splitGlobPatterns(value){return value?value.split(",").map((p)=>p.trim()).filter(Boolean):[]}function resolveAstGrepBinary(){return _internals243.resolveExecutableFromPath(["ast-grep","sg"])}function toWorkspaceRelativePath(filePath,workspace){try{let resolved=path294.resolve(workspace,filePath),realWorkspace=fs168.realpathSync(workspace),realResolved=fs168.realpathSync(resolved),relative74=path294.relative(realWorkspace,realResolved);if(!relative74||relative74.startsWith("..")||path294.isAbsolute(relative74))return null;return relative74.split(path294.sep).join("/")}catch{return null}}function parseAstGrepStream(stdout,workspace,maxResults){let matches=[],total=0;for(let line of stdout.split(`
|
|
7276
|
+
`):resultContent;finalContent=ensureFinalNewline(withLineEnding,originalEndsWithNewline)}if(finalContent===content)return{file:targetPath,status:"no-changes",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0};if(!dryRun)atomicWriteFileSync3(fullPath,finalContent);return{file:targetPath,status:"applied",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0}}function buildErrorResult(message){return{success:!1,files:[{file:"",status:"error",hunks:0,hunksApplied:0,hunksFailed:0,errors:[{hunkIndex:0,type:"context-mismatch",message}]}],summary:{totalFiles:0,applied:0,failed:1,totalHunks:0}}}function isUnsupportedPatchFormat(patchText){let trimmed=patchText.trimStart();return trimmed.startsWith("*** Begin Patch")||trimmed.startsWith("*** Update File")||trimmed.startsWith("*** Add File")||trimmed.startsWith("*** Delete File")||trimmed.startsWith("*** End Patch")}var swarmApplyPatch2=createSwarmTool({description:"Apply a unified diff patch to workspace files. Validates paths, matches context exactly, and writes atomically. Coder-scoped write tool. Use standard unified diff format (--- a/file / +++ b/file / @@ hunks). Indented patches (e.g. inside a fenced markdown/YAML block) are automatically dedented to column 0 before parsing — the diff body itself may be indented. Does NOT support *** Begin Patch / *** Update File payloads — use the native apply_patch tool for those. Accepts the payload as `patch` (canonical) or any of the aliases `patchText`, `patch_text`, `patchPayload` (#2206); the resolver picks the first non-empty one.",args:{patch:exports_external.string().optional().describe("Unified diff text to parse and apply (optional when an alias below carries the payload)"),patchText:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),patch_text:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),patchPayload:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),files:exports_external.array(exports_external.string()).min(1).describe("Array of target file paths the patch is expected to touch. Every parsed target must appear in this list."),dryRun:exports_external.boolean().optional().default(!1).describe("Validate without writing files (default: false)"),allowCreates:exports_external.boolean().optional().default(!1).describe("Allow creating new files from patches with --- /dev/null (default: false)"),allowDeletes:exports_external.boolean().optional().default(!1).describe("Allow deleting files from patches with +++ /dev/null (default: false)")},execute:async(args2,directory)=>{if(!args2||typeof args2!=="object")return JSON.stringify(buildErrorResult("Could not parse swarm_apply_patch arguments"),null,2);let obj=args2,patchText=[obj.patch,obj.patchText,obj.patch_text,obj.patchPayload].find((value)=>typeof value==="string"&&value.length>0)??"",files=obj.files??[],dryRun=obj.dryRun??!1,allowCreates=obj.allowCreates??!1,allowDeletes=obj.allowDeletes??!1,{config:config3}=_internals242.loadPluginConfigWithMeta(directory),fuzzyMatch=config3.apply_patch?.fuzzy_match===!0,fuzzyMatchContextAware=config3.apply_patch?.fuzzy_match_context_aware===!0,hunkOptions=fuzzyMatch||fuzzyMatchContextAware?{fuzzyMatch,fuzzyMatchContextAware}:void 0;if(!existsSync152(directory))return JSON.stringify(buildErrorResult("Workspace directory does not exist"),null,2);if(files.length===0)return JSON.stringify(buildErrorResult("files array cannot be empty"),null,2);if(!patchText||patchText.trim()==="")return JSON.stringify(buildErrorResult("patch text cannot be empty"),null,2);if(isUnsupportedPatchFormat(patchText))return JSON.stringify(buildErrorResult("Unsupported patch format: *** Begin Patch / *** Update File style payloads are not supported by swarm_apply_patch. Use the native apply_patch tool for this format, or provide a standard unified diff (--- a/file / +++ b/file / @@ hunks)."),null,2);for(let filePath of files){let validationError=validatePatchTargetPath(filePath,directory);if(validationError)return JSON.stringify(buildErrorResult(validationError),null,2)}let{files:parsedFiles,error:parseError}=parseUnifiedDiff2(patchText);if(parseError)return JSON.stringify(buildErrorResult(parseError),null,2);if(parsedFiles.length===0)return JSON.stringify({success:!0,dryRun,files:[],summary:{totalFiles:0,applied:0,failed:0,totalHunks:0}},null,2);let declaredFileSet=new Set(files),undeclaredTargets=[];for(let fileDiff of parsedFiles){let targetPath=fileDiff.isDelete?fileDiff.oldPath:fileDiff.newPath;if(targetPath&&targetPath!=="/dev/null"&&!declaredFileSet.has(targetPath))undeclaredTargets.push(targetPath)}if(undeclaredTargets.length>0)return JSON.stringify(buildErrorResult(`Patch targets files not in the declared files array: ${undeclaredTargets.join(", ")}`),null,2);let parsedTargetSet=new Set(parsedFiles.map((fd)=>fd.isDelete?fd.oldPath:fd.newPath).filter(Boolean)),extraFiles=files.filter((f)=>!parsedTargetSet.has(f)),fileResults=[],totalApplied=0,totalFailed=0,totalHunks=0;for(let fileDiff of parsedFiles){let targetPath=fileDiff.isDelete?fileDiff.oldPath:fileDiff.newPath,fullPath=path293.resolve(directory,targetPath);totalHunks+=fileDiff.hunks.length;let result=processFileDiff(fileDiff,targetPath,fullPath,directory,dryRun,allowCreates,allowDeletes,hunkOptions);if(fileResults.push(result),result.status==="applied"||result.status==="created")totalApplied++;else if(result.status==="error")totalFailed++}let output={success:totalFailed===0,dryRun,files:fileResults,summary:{totalFiles:fileResults.length,applied:totalApplied,failed:totalFailed,totalHunks}};if(extraFiles.length>0)return JSON.stringify({...output,warnings:[`files[] contains entries not targeted by the patch: ${extraFiles.join(", ")}`]},null,2);return JSON.stringify(output,null,2)}});init_zod();init_delegation_gate();init_create_tool();var ApprovePlanCriticArgsSchema=exports_external.object({reason:exports_external.string().trim().min(1).max(500).describe('Why a manual approval is being recorded (e.g. "critic returned APPROVED but the verdict format did not match the mechanical recorder"). Audited to .swarm/events.jsonl.')}).strict();async function executeApprovePlanCritic(args2,directory,context={}){let parsed=ApprovePlanCriticArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid approve_plan_critic call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"approve_plan_critic requires an active sessionID"});try{let summary=await forceRecordPlanCriticApproval(directory,context.sessionID,{reason:parsed.data.reason,userConfirmed:!1});return JSON.stringify({success:!0,plan_id:summary.planId,recorded_at:summary.recordedAt,method:"manual_override",user_confirmed:!1,message:"Recorded a manual plan_critic_gate approval snapshot. The critic_pre_plan execution gate will now allow coder delegation. An audit event was appended to .swarm/events.jsonl."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var approve_plan_critic=createSwarmTool({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 snapshot recorder failed to persist it (verdict-format mismatch, dispatch-signal miss, or a plan.json read race — issue #2012). The snapshot carries a distinct method: "manual_override" audit marker. Architect-only: the active session must be the architect. Prefer re-running MODE: CRITIC-GATE first; use this only as an escape hatch when a legitimate APPROVED was lost, or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (e.g. a files_touched-only scope reconciliation) — the reason must state which case applies. A reason is required and audited to .swarm/events.jsonl. The human-confirmed variant is /swarm approve-plan-critic.',args:{reason:ApprovePlanCriticArgsSchema.shape.reason},execute:executeApprovePlanCritic});init_zod();init_delegation_gate();init_create_tool();var ApproveRetrySoundingBoardArgsSchema=exports_external.object({task_id:exports_external.string().trim().min(1).describe('Exact plan task id of the wedged task (e.g. "2.1"). Must exist in the current plan and already have a durable sounding_board_consultation escalation.'),reason:exports_external.string().trim().min(1).max(500).describe('Why a manual approval is being recorded (e.g. "sounding board returned APPROVED but the verdict format did not match the mechanical recorder"). Audited to .swarm/events.jsonl.')}).strict();async function executeApproveRetrySoundingBoard(args2,directory,context={}){let parsed=ApproveRetrySoundingBoardArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid approve_retry_sounding_board call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"approve_retry_sounding_board requires an active sessionID"});try{let summary=await forceRecordRetrySoundingBoardApproval(directory,context.sessionID,{taskId:parsed.data.task_id,reason:parsed.data.reason});return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,retry_epoch:summary.retryEpoch,recorded_at:summary.recordedAt,audit_event_recorded:summary.auditEventRecorded,method:"manual_override",user_confirmed:!1,message:summary.auditEventRecorded?"Recorded a manual critic_sounding_board gate entry for the coder retry circuit breaker. The next coder dispatch for this task passes the TASK_RETRY_CRITIC_REQUIRED critic check (one bounded simplified retry). An audit event (action sounding_board_manual_approval) was appended to .swarm/events.jsonl.":"Recorded a manual critic_sounding_board gate entry for the coder retry circuit breaker. The next coder dispatch for this task passes the TASK_RETRY_CRITIC_REQUIRED critic check (one bounded simplified retry). WARNING: the audit event could NOT be appended to .swarm/events.jsonl (see the plugin log); the gate evidence itself records the override via the retry-sb-manual transition id."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var approve_retry_sounding_board=createSwarmTool({description:"Record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate (TASK_RETRY_CRITIC_REQUIRED) when the sounding board already returned APPROVED but the mechanical recorder failed to persist it — verdict-format miss (the sounding board echoed its enumerated RESPONSE FORMAT line), dispatch-task attribution miss, launch-generation binding miss, or a failed/error output state (issue #2703). Scoped to the exact plan task id, which must already carry a durable sounding_board_consultation escalation for the current retry epoch; the audit event (action sounding_board_manual_approval) distinguishes the override from a mechanical recording. Architect-only: the active session must be the architect. Prefer re-dispatching the sounding board first; use this only as an escape hatch when a legitimate APPROVED verdict was lost. A reason is required and audited to .swarm/events.jsonl.",args:{task_id:ApproveRetrySoundingBoardArgsSchema.shape.task_id,reason:ApproveRetrySoundingBoardArgsSchema.shape.reason},execute:executeApproveRetrySoundingBoard});init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs168 from"node:fs";import*as path294 from"node:path";var AST_GREP_TIMEOUT_MS=1e4,AST_GREP_MAX_STDOUT_BYTES=8388608,AST_GREP_MAX_STDERR_BYTES=65536,DEFAULT_MAX_RESULTS2=100,HARD_CAP_RESULTS2=1e4,MAX_PATTERN_LENGTH=20000;function splitGlobPatterns(value){return value?value.split(",").map((p)=>p.trim()).filter(Boolean):[]}function resolveAstGrepBinary(){return _internals243.resolveExecutableFromPath(["ast-grep","sg"])}function toWorkspaceRelativePath(filePath,workspace){try{let resolved=path294.resolve(workspace,filePath),realWorkspace=fs168.realpathSync(workspace),realResolved=fs168.realpathSync(resolved),relative74=path294.relative(realWorkspace,realResolved);if(!relative74||relative74.startsWith("..")||path294.isAbsolute(relative74))return null;return relative74.split(path294.sep).join("/")}catch{return null}}function parseAstGrepStream(stdout,workspace,maxResults){let matches=[],total=0;for(let line of stdout.split(`
|
|
7277
7277
|
`)){if(!line.trim())continue;try{let entry=JSON.parse(line),relativePath2=typeof entry.file==="string"?toWorkspaceRelativePath(entry.file,workspace):null;if(!relativePath2)continue;if(total++,matches.length>=maxResults)continue;let start=entry.range?.start??{},end=entry.range?.end??{};matches.push({file:relativePath2,lineNumber:typeof start.line==="number"?start.line+1:1,column:typeof start.column==="number"?start.column+1:1,endLineNumber:typeof end.line==="number"?end.line+1:1,endColumn:typeof end.column==="number"?end.column+1:1,text:typeof entry.text==="string"?entry.text:"",lines:typeof entry.lines==="string"?entry.lines.trimEnd():"",language:typeof entry.language==="string"?entry.language:void 0,metaVariables:entry.metaVariables&&typeof entry.metaVariables==="object"?entry.metaVariables:void 0})}catch{}}return{matches,total}}function validateGlobArg(kind,value){if(!value)return null;if(containsControlChars(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains invalid control characters`};if(containsPathTraversal(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains path traversal sequence`};return null}var ast_grep=createSwarmTool({description:"Read-only structural AST search using ast-grep. Searches code patterns with optional language and glob filters; does not rewrite files.",args:{pattern:exports_external.string().describe("ast-grep pattern to search for"),language:exports_external.string().optional().describe("Optional ast-grep language, e.g. ts, tsx, js, py, rust"),include:exports_external.string().optional().describe("Comma-separated include globs, passed to ast-grep --globs"),exclude:exports_external.string().optional().describe("Comma-separated exclude globs, passed to ast-grep as !glob"),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS2).describe("Maximum number of matches to return")},execute:async(args2,directory)=>{let pattern,language,include,exclude,maxResults=DEFAULT_MAX_RESULTS2;try{let obj=args2;pattern=typeof obj.pattern==="string"?obj.pattern:"",language=typeof obj.language==="string"?obj.language:void 0,include=typeof obj.include==="string"?obj.include:void 0,exclude=typeof obj.exclude==="string"?obj.exclude:void 0;let rawMaxResults=typeof obj.max_results==="number"?obj.max_results:DEFAULT_MAX_RESULTS2,sanitizedMaxResults=Number.isFinite(rawMaxResults)?rawMaxResults:DEFAULT_MAX_RESULTS2;maxResults=Math.min(Math.max(0,sanitizedMaxResults),HARD_CAP_RESULTS2)}catch{return JSON.stringify({error:!0,type:"invalid-pattern",message:"Could not parse ast_grep arguments"},null,2)}if(!pattern||pattern.trim()==="")return JSON.stringify({error:!0,type:"invalid-pattern",message:"Pattern cannot be empty"},null,2);if(pattern.length>MAX_PATTERN_LENGTH||containsControlChars(pattern))return JSON.stringify({error:!0,type:"invalid-pattern",message:`Pattern is invalid or exceeds ${MAX_PATTERN_LENGTH} characters`},null,2);if(language&&!/^[A-Za-z0-9_-]+$/.test(language))return JSON.stringify({error:!0,type:"invalid-pattern",message:"Language must contain only letters, numbers, _ or -"},null,2);let includeError=validateGlobArg("Include",include);if(includeError)return JSON.stringify(includeError,null,2);let excludeError=validateGlobArg("Exclude",exclude);if(excludeError)return JSON.stringify(excludeError,null,2);if(!fs168.existsSync(directory))return JSON.stringify({error:!0,type:"unknown",message:"Workspace directory does not exist"},null,2);let executable=_internals243.resolveAstGrepBinary();if(!executable)return JSON.stringify({error:!0,type:"ast-grep-not-found",message:"ast-grep executable not found. Install ast-grep and ensure ast-grep or sg is on PATH."},null,2);let sgArgs=["run","--pattern",pattern,"--json=stream","--color","never"];if(language)sgArgs.push("--lang",language);for(let glob of splitGlobPatterns(include))sgArgs.push("--globs",glob);for(let glob of splitGlobPatterns(exclude))sgArgs.push("--globs",`!${glob}`);sgArgs.push(".");let run=await _internals243.runExternalTool({executable,args:sgArgs,cwd:directory,timeoutMs:AST_GREP_TIMEOUT_MS,maxStdoutBytes:AST_GREP_MAX_STDOUT_BYTES,maxStderrBytes:AST_GREP_MAX_STDERR_BYTES});if(run.status==="timeout")return JSON.stringify({error:!0,type:"timeout",message:`ast-grep timed out after ${AST_GREP_TIMEOUT_MS}ms`},null,2);if(run.status==="spawn-error")return JSON.stringify({error:!0,type:"unknown",message:run.message??"ast-grep failed to start"},null,2);if(run.exitCode!==0&&run.stderr)return JSON.stringify({error:!0,type:"invalid-pattern",message:run.stderr.split(`
|
|
7278
7278
|
`)[0]},null,2);let{matches,total}=parseAstGrepStream(run.stdout,directory,maxResults);return JSON.stringify({matches,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,total,pattern,language,maxResults,outputTruncated:run.stdoutTruncated||run.stderrTruncated},null,2)}}),_internals243={resolveExecutableFromPath,resolveAstGrepBinary,runExternalTool,parseAstGrepStream};init_zod();init_authorization();init_create_tool();var AuthorizePrReviewReentryArgsSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),role:exports_external.enum(["reviewer","test_engineer"])}).strict();async function executeAuthorizePrReviewReentry(args2,directory,context={}){let parsed=AuthorizePrReviewReentryArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR-review re-entry authorization: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR-review re-entry authorization requires an active sessionID"});try{let record3=await issuePrReviewReentryAuthorization(directory,context.sessionID,{...parsed.data.run_id?{runId:parsed.data.run_id}:{},prHeadSha:parsed.data.pr_head_sha,role:parsed.data.role});return JSON.stringify({success:!0,authorization_id:record3.authorizationId,role:record3.role,pr_head_sha:record3.prHeadSha,run_id:record3.runId,generation:record3.generation,revision_digest:record3.revisionDigest,expires_at:record3.expiresAt,instructions:`Immediately dispatch exactly one direct subagent_type Task call with role "${record3.role}" for this PR-review re-entry; if a plan or task workflow state exists, include the exact task_id (or task identifier in the prompt). A taskless dispatch is allowed only for a plan-free standalone review and does not advance plan-task gate state. The PR workflow controller admits and reserves this authorization once, and the delegation gate verifies the same call-bound reservation; a later unrelated gate rejection still burns it. Any other dispatch falls back to normal gating.`},null,2)}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var authorize_pr_review_reentry=createSwarmTool({description:"Issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383). The authorization is reserved atomically by the PR workflow controller for the very next direct subagent_type Task dispatch of the declared role (admitting that one dispatch past the PR_REVIEW read-only restriction), then verified for that same call by the delegation gate, which bypasses ONLY the generic Stage-A task-workflow requirement; all other delegation gates remain authoritative. If a plan or task workflow state exists, the dispatch must include an exact task_id or task identifier; taskless dispatch is standalone-only and never guesses from plan/session state. Bound to the exact session, workflow, run, PR head SHA, worktree revision digest, role, and gate generation; replay, cross-session use, wrong role, expiry (10 minutes), or workflow progress since issuance fails closed. A dispatch the delegation gate later rejects for another reason still burns the authorization. Requires an active head-bound PR_REVIEW gate. Issue immediately before the Task dispatch; unconsumed same-role authorizations at the same generation are refused.",args:{run_id:AuthorizePrReviewReentryArgsSchema.shape.run_id,pr_head_sha:AuthorizePrReviewReentryArgsSchema.shape.pr_head_sha,role:AuthorizePrReviewReentryArgsSchema.shape.role},execute:executeAuthorizePrReviewReentry});init_dist();init_create_tool();init_symbols();init_path_security();import*as fs169 from"node:fs";import*as path295 from"node:path";var WINDOWS_RESERVED_NAMES4=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks3(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES4.test(part))return!0;return!1}function isPathInWorkspace2(filePath,workspace){try{let resolvedPath=path295.resolve(workspace,filePath);if(!fs169.existsSync(resolvedPath))return!0;let realWorkspace=fs169.realpathSync(workspace),realResolvedPath=fs169.realpathSync(resolvedPath),relativePath2=path295.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path295.isAbsolute(relativePath2))return!1;return!0}catch{return!1}}function processFile(file3,cwd,exportedOnly){let ext=path295.extname(file3);if(containsControlChars(file3))return{file:file3,success:!1,error:"Path contains invalid control characters",errorType:"invalid-path"};if(containsPathTraversal(file3))return{file:file3,success:!1,error:"Path contains path traversal sequence",errorType:"path-traversal"};if(containsWindowsAttacks3(file3))return{file:file3,success:!1,error:"Path contains invalid Windows-specific sequence",errorType:"invalid-path"};if(!isPathInWorkspace2(file3,cwd))return{file:file3,success:!1,error:"Path is outside workspace",errorType:"path-outside-workspace"};let fullPath=path295.join(cwd,file3);if(!fs169.existsSync(fullPath))return{file:file3,success:!1,error:`File not found: ${file3}`,errorType:"file-not-found"};let syms;switch(ext){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(file3,cwd);break;case".py":case".pyw":syms=extractPythonSymbols(file3,cwd);break;case".rs":syms=extractRustSymbols(file3,cwd);break;case".go":syms=extractGoSymbols(file3,cwd);break;default:return{file:file3,success:!1,error:`Unsupported file extension: ${ext}. Supported: .ts, .tsx, .js, .jsx, .mjs, .cjs, .py, .pyw, .rs, .go`,errorType:"unsupported-language"}}let isEmptyFile=!1;try{if(fs169.statSync(fullPath).size===0)isEmptyFile=!0}catch{}if(syms.length===0)try{if(fs169.readFileSync(fullPath,"utf-8").trim().length===0)isEmptyFile=!0}catch{}if(isEmptyFile)return{file:file3,success:!0,symbols:[],error:"empty-file",errorType:"empty-file"};if(exportedOnly)syms=syms.filter((s)=>s.exported);return{file:file3,success:!0,symbols:syms}}var batch_symbols=createSwarmTool({description:"Extract symbols from multiple files in a single batch call. Accepts an array of file paths and returns per-file symbol summaries. One bad file does not crash the batch. Use for surveying a module when you need symbol information from multiple files at once.",args:{files:tool.schema.array(tool.schema.string()).describe("Array of file paths to extract symbols from"),exported_only:tool.schema.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols.")},execute:async(args2,directory)=>{let files,exportedOnly=!0;try{let obj=args2;if(!Array.isArray(obj.files))return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: files must be an array"},null,2);files=obj.files.map((f)=>String(f)),exportedOnly=obj.exported_only!==!1}catch{return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: could not extract files array"},null,2)}let cwd=directory,results=[];for(let file3 of files){let result=processFile(file3,cwd,exportedOnly);results.push(result)}let successCount=results.filter((r)=>r.success).length,failureCount=results.filter((r)=>!r.success).length,batchResult={results,totalFiles:files.length,successCount,failureCount};return JSON.stringify(batchResult,null,2)}});init_zod();init_discovery();init_config();init_manager2();init_bun_compat();init_logger();init_create_tool();var _internals244={loadGateOverrides},DEFAULT_TIMEOUT_MS4=300000,MAX_OUTPUT_BYTES6=10240,MAX_OUTPUT_LINES=100,NO_BUILD_FILES_DISCOVERED_REASON="No build commands discovered (no supported build files found)";function truncateOutput(output,maxLines=MAX_OUTPUT_LINES,maxBytes=MAX_OUTPUT_BYTES6){if(!output)return"";let truncated=output;if(truncated.length>maxBytes)truncated=truncated.slice(-maxBytes);let lines=truncated.split(`
|
|
7279
7279
|
`);if(lines.length>maxLines)return lines.slice(-maxLines).join(`
|
|
@@ -7560,7 +7560,7 @@ ${scopeWarning}`:scopeWarning}}function recoverTaskStateFromDelegations(taskId,d
|
|
|
7560
7560
|
`)+(allRecords.length>0?`
|
|
7561
7561
|
`:""),findingsDigest=createHash106("sha256").update(serializedFindings,"utf8").digest("hex"),criticSettlements;if(findingsInput.boundary==="post_critic")try{let authoritativeCriticVerdicts=existing.some((record3)=>record3.boundary==="post_reviewer"&&record3.next_action==="route_to_critic")?await readAuthoritativePrReviewCriticVerdicts(directory,sessionID):new Map;criticSettlements=assertCriticSettlements(findingsInput.records,existing,authoritativeCriticVerdicts)}catch(error93){return withPartialAdmissionRollback(operationFailure("validate",relativeFindingsPath.split(path359.sep).join("/"),"an authoritative critic settlement matching the authenticated critic verdict map",error93))}if(!isExactReplay){let serializedBytes=Buffer.byteLength(serializedFindings,"utf8");if(serializedBytes>PR_REVIEW_FINDINGS_MAX_BYTES)return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError("records",`a complete findings artifact at most ${PR_REVIEW_FINDINGS_MAX_BYTES} UTF-8 bytes`,`${serializedBytes} bytes`)));try{await _internals299.atomicWrite(findingsPath,serializedFindings)}catch(error93){return withPartialAdmissionRollback(operationFailure("write",relativeFindingsPath.split(path359.sep).join("/"),"an atomic findings checkpoint write",error93))}}let latest2=latestFindings(allRecords);if(findingsInput.boundary==="post_critic")try{let synthesis=synthesizePrReviewFindings({candidates:policyCandidates([...latest2.values()],sessionID,findingsInput.boundary)});await persistReviewOutcome({projectRoot:directory,routeReceipt:{kind:"pr_review_finding_policy",version:1,sessionId:sessionID,taskId:resolvedRunId,boundary:findingsInput.boundary,prHeadSha:state2.prHeadSha,findingsPath:relativeFindingsPath.split(path359.sep).join("/"),findingsDigest},synthesis:{...synthesis,criticSettlements}})}catch(error93){return withPartialAdmissionRollback(operationFailure("persist",`pr-review/${resolvedRunId}/finding-policy.json`,"an authoritative version-1 critic settlement and finding-policy evidence record",error93))}let handoffRequired=deriveFeedbackHandoffFindingIds([...latest2.values()]).length>0;if(!isCommittedReplay)try{await markPrReviewArtifactBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,relativeFindingsPath.split(path359.sep).join("/"),findingIds,handoffRequired)}catch(error93){return withPartialAdmissionRollback(operationFailure("update",`pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,`a durable ${findingsInput.boundary} boundary receipt`,error93))}return JSON.stringify({success:!0,run_id:resolvedRunId,path:relativeFindingsPath.split(path359.sep).join("/"),boundary:findingsInput.boundary,appended:appended.length,replayed:isExactReplay,handoff_required:handoffRequired,...state2.prReviewPartialBaseCoverage?{partial_base_coverage:{unresolved_dimensions:normalizePrReviewPartialBaseCoverageRecord(state2.prReviewPartialBaseCoverage).unresolvedDimensions.map((entry)=>({dimension:entry.dimension,terminal_state:entry.terminalState,reason_kind:entry.reasonKind,failure_class:entry.failureClass})),path:state2.prReviewCoverageDisclosurePath,digest:state2.prReviewCoverageDisclosureDigest}}:{}},null,2)}let latest=latestFindings(existing),actionableIds=deriveFeedbackHandoffFindingIds([...latest.values()]),requestedIds=[...new Set(parsed.data.handoff.finding_ids)].sort();if(actionableIds.length===0||JSON.stringify(actionableIds)!==JSON.stringify(requestedIds))return failure3(`field handoff.finding_ids: expected authoritative actionable set [${actionableIds.join(", ")||"(none)"}], got requested [${requestedIds.join(", ")||"(none)"}]`);let relativeHandoffPath=path359.join("pr-review",resolvedRunId,"feedback-handoff.json"),handoffPath;try{handoffPath=validateSwarmPath(directory,relativeHandoffPath)}catch(error93){return operationFailure("resolve",relativeHandoffPath.split(path359.sep).join("/"),"a contained path below the project .swarm directory",error93)}let handoffRecord={schema_version:1,run_id:resolvedRunId,pr_head_sha:state2.prHeadSha,created_at:new Date().toISOString(),...parsed.data.handoff},comparableHandoff=(record3)=>({schema_version:record3.schema_version,run_id:record3.run_id,pr_head_sha:record3.pr_head_sha,pr_url:record3.pr_url,finding_ids:record3.finding_ids,summary:record3.summary,provenance:record3.provenance}),handoffsMatch=(existing2)=>JSON.stringify(comparableHandoff(existing2))===JSON.stringify(comparableHandoff(handoffRecord)),readPersistedHandoff=async()=>{let raw=await readBoundedUtf8File(handoffPath,PR_REVIEW_HANDOFF_MAX_BYTES,"handoff artifact"),decoded;try{decoded=JSON.parse(raw)}catch(error93){throw Error(`invalid JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}let validated=PersistedHandoffSchema.safeParse(decoded);if(!validated.success)throw Error(`schema mismatch: ${formatPrReviewValidationIssues(validated.error.issues,decoded).join("; ")}`);return validated.data},existingHandoff=null;try{existingHandoff=await readPersistedHandoff()}catch(error93){if(error93.code!=="ENOENT")return failure3(`operation read path "${relativeHandoffPath.split(path359.sep).join("/")}": expected bounded JSON matching the persisted handoff schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(existingHandoff){if(!handoffsMatch(existingHandoff))return failure3("field handoff: expected an exact retry of the persisted handoff, got conflicting handoff content")}else{let serializedHandoff=`${JSON.stringify(handoffRecord,null,2)}
|
|
7562
7562
|
`,serializedHandoffBytes=Buffer.byteLength(serializedHandoff,"utf8");if(serializedHandoffBytes>PR_REVIEW_HANDOFF_MAX_BYTES)return failure3(formatPrReviewRuntimeFieldError("handoff",`a persisted handoff artifact at most ${PR_REVIEW_HANDOFF_MAX_BYTES} UTF-8 bytes`,`${serializedHandoffBytes} bytes`));let created;try{created=await _internals299.atomicCreate(handoffPath,serializedHandoff)}catch(error93){return operationFailure("create",relativeHandoffPath.split(path359.sep).join("/"),"an atomic create-only handoff artifact",error93)}if(!created){let raced;try{raced=await readPersistedHandoff()}catch(error93){return failure3(`operation read path "${relativeHandoffPath.split(path359.sep).join("/")}": expected the concurrently persisted handoff schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(!handoffsMatch(raced))return failure3("field handoff: expected an exact retry of the persisted handoff, got conflicting concurrent handoff content")}}let alreadyOffered;try{alreadyOffered=(await markPrReviewHandoffComplete(directory,sessionID,resolvedRunId,relativeHandoffPath.split(path359.sep).join("/"))).alreadyOffered}catch(error93){return operationFailure("update",`pr-review/${resolvedRunId}/feedback-consent.json and pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,"a matching durable consent offer and handoff receipt",error93)}return JSON.stringify({success:!0,run_id:resolvedRunId,path:relativeHandoffPath.split(path359.sep).join("/"),finding_count:actionableIds.length,already_offered:alreadyOffered,confirmation_command:`/swarm pr-feedback ${parsed.data.handoff.pr_url} continue from .swarm/${relativeHandoffPath.split(path359.sep).join("/")}`},null,2)}var write_pr_review_artifact=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run.",args:{kind:exports_external.enum(["findings","handoff"]),run_id:PrReviewRunIdSchema.optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]).optional(),records:exports_external.array(PrReviewFindingSchema).min(1).max(1000).optional(),partial_base_coverage:PrReviewPartialBaseCoverageSchema.optional(),handoff:PrReviewHandoffSchema.optional()},execute:executeWritePrReviewArtifact});init_zod();init_lane_output_store();init_pending_delegations();init_pr_review_contract();init_pr_review_trigger_contract();init_workspace_snapshot();init_pr_workflow_gate();init_utils2();init_logger();init_create_tool();init_pr_review_trigger_contract();import{randomUUID as randomUUID45}from"node:crypto";import fs225 from"node:fs";import path360 from"node:path";var _internals300={resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,resolveMergeBase:resolveExactMergeBase,resolveMergeBaseAsync:resolveExactMergeBaseAsync,markPrReviewTriggerEvaluationComplete};function comparableTriggerReceipt(receipt){return JSON.stringify({...receipt,evaluated_at:void 0,base_verification:void 0})}async function readBoundedTriggerReceipt(destination){let stat24=await fs225.promises.stat(destination);if(!stat24.isFile()||stat24.size>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error(`trigger evaluation receipt is not a bounded regular file (max ${PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES} bytes)`);let raw=await fs225.promises.readFile(destination,"utf8"),bytes=Buffer.byteLength(raw,"utf8");if(bytes>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error(`trigger evaluation receipt exceeds ${PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES} bytes after read (got ${bytes})`);let decoded;try{decoded=JSON.parse(raw)}catch(error93){throw Error(`trigger evaluation receipt is not valid JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}if(parsePrReviewTriggerReceipt(decoded),decoded.schema_version!==2)throw Error("trigger evaluation receipt must use schema_version 2");return decoded}async function createTriggerReceipt(destination,content){let parent=path360.dirname(destination),tempPath=path360.join(parent,`.trigger-eval.${randomUUID45()}.tmp`);await fs225.promises.mkdir(parent,{recursive:!0});try{await fs225.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"});try{return await fs225.promises.link(tempPath,destination),!0}catch(error93){if(error93.code==="EEXIST")return!1;throw error93}}finally{await fs225.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}async function resolveCurrentRevisionDigest(directory,prHeadSha){if(_internals300.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _internals300.resolvePrWorkflowRevisionDigest(directory,prHeadSha);return _internals300.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha)}var REVISION_DIGEST_RESOLUTION_ATTEMPTS=2;async function resolveCurrentRevisionDigestWithRetry(directory,prHeadSha){for(let attempt=1;attempt<=REVISION_DIGEST_RESOLUTION_ATTEMPTS;attempt+=1){let digest5=await resolveCurrentRevisionDigest(directory,prHeadSha);if(digest5)return digest5}return null}async function resolveReviewMergeBase(directory,baseRef,prHeadSha){if(_internals300.resolveMergeBase!==resolveExactMergeBase)return _internals300.resolveMergeBase(directory,baseRef,prHeadSha);return _internals300.resolveMergeBaseAsync(directory,baseRef,prHeadSha)}var WritePrReviewTriggerEvalArgsSchema=exports_external.object({run_id:PrReviewRunIdSchema.optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i).optional(),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional(),rows:exports_external.array(PrReviewWriterInputRowSchema).min(1)}).strict();function failure4(message){return JSON.stringify({success:!1,message},null,2)}async function executeWritePrReviewTriggerEval(args2,directory,context={}){let writerLedger;try{writerLedger=validatePrReviewWriterInputLedger(typeof args2==="object"&&args2!==null?args2.rows:void 0)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let parsed=WritePrReviewTriggerEvalArgsSchema.safeParse(args2);if(!parsed.success)return failure4(`Invalid trigger evaluation: ${formatPrReviewValidationIssues(parsed.error.issues,args2).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");let gateState;try{gateState=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(gateState?.mode!=="PR_REVIEW"||!gateState.prHeadSha)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");if(gateState.prHeadSha!==parsed.data.pr_head_sha)return failure4(formatPrReviewRuntimeFieldError("pr_head_sha",`"${gateState.prHeadSha}"`,parsed.data.pr_head_sha));try{await assertPrReviewBaseCoverageSettled2(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(!gateState.prReviewTriggerLedger)return failure4("PR_REVIEW trigger evaluation requires the canonical ledger frozen by the first micro dispatch");let frozenLedger;try{frozenLedger=validatePrReviewInlineTriggerLedger(gateState.prReviewTriggerLedger)}catch(error93){return failure4(`Persisted PR_REVIEW trigger ledger is invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}let classificationDrift=frozenLedger.rows.filter((row,index)=>writerLedger.rows[index]?.result!==row.result).map((row)=>row.trigger_id);if(classificationDrift.length>0)return failure4(`PR_REVIEW trigger classification drift from the canonical ledger frozen across micro dispatches: ${classificationDrift.join(", ")}`);let triggerLedger;try{triggerLedger=validatePrReviewPersistedInputLedger(frozenLedger.rows.map((frozenRow,index)=>{let writerRow=writerLedger.rows[index];if(frozenRow.result==="NOT_TRIGGERED")return frozenRow;if(!writerRow||writerRow.result!=="MATCHED")throw Error(`missing MATCHED provenance for ${frozenRow.trigger_id}`);return{...frozenRow,source_batch_id:writerRow.source_batch_id,source_lane_id:writerRow.source_lane_id}}))}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let validatedRows=triggerLedger.rows,currentRevisionDigest=await resolveCurrentRevisionDigestWithRetry(directory,parsed.data.pr_head_sha);if(!currentRevisionDigest)return failure4(`Active PR_REVIEW trigger evaluation could not bind the current exact revision digest for pr_head_sha "${parsed.data.pr_head_sha}" after ${REVISION_DIGEST_RESOLUTION_ATTEMPTS} attempts. A null digest collapses several causes: the bounded git call timed out, the git process failed to spawn, the working tree could not be read, or pr_head_sha was rejected as an unsafe revision token. This fails closed on purpose and has no bound-value fallback — no independently-bound durable PR_REVIEW revision digest exists to compare against, so accepting an unresolved digest would let a lane artifact self-certify its own revision. Nothing was persisted, so this call is retryable as-is. Recovery: confirm the checkout is readable and pr_head_sha exists here (git rev-parse), retry once the environment settles, or restart with abort_pr_workflow (kind "recovery").`);let citedLaneOwnership=new Map,coverageDegradations=[];for(let row of validatedRows){if(row.result!=="MATCHED")continue;let batchRead=findByBatchIdDetailed(directory,row.source_batch_id,{parentSessionId:sessionID});if(batchRead.status==="uncertain")return failure4(`MATCHED trigger ${row.trigger_id} cannot be validated: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); the batch's records are UNKNOWN, not absent. Nothing was persisted, so this call is retryable as-is once the store is readable.`);let record3=batchRead.value.find((candidate2)=>candidate2.laneId===row.source_lane_id),recordOwnedLanes=record3?.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3?.workflowLane?[record3.workflowLane]:[];citedLaneOwnership.set(`${row.source_batch_id}\x00${row.source_lane_id}`,recordOwnedLanes);let outputRef=record3?.result?.outputRef?.trim(),outputArtifact=outputRef?readLaneOutput(directory,outputRef):null;if(!record3||record3.mode!=="swarm-pr-review:micro"||!recordOwnedLanes.includes(row.trigger_id)||!record3.result?.digest?.trim()||!record3.result?.outputRef?.trim()||!outputArtifact||outputArtifact.artifact.batchId!==row.source_batch_id||outputArtifact.artifact.laneId!==row.source_lane_id||outputArtifact.artifact.mode!=="swarm-pr-review:micro"||outputArtifact.artifact.sessionId!==record3.subagentSessionId||outputArtifact.artifact.parentSessionId!==record3.parentSessionId||outputArtifact.artifact.agent!==record3.swarmPrefixedAgent||outputArtifact.artifact.role!==record3.normalizedAgent||outputArtifact.artifact.source!=="collect_lane_results"||outputArtifact.artifact.workflowLane!==record3.workflowLane||outputArtifact.artifact.prHeadSha!==record3.workspace?.prHeadSha||outputArtifact.artifact.gitHead!==record3.workspace?.gitHead||outputArtifact.artifact.revisionDigest!==currentRevisionDigest||outputArtifact.artifact.digest!==record3.result?.digest||outputArtifact.artifact.chars!==record3.result?.chars||record3.workspace?.prHeadSha!==parsed.data.pr_head_sha||record3.workspace?.gitHead!==parsed.data.pr_head_sha)return failure4(`MATCHED trigger ${row.trigger_id} does not reference a verifiable micro-lane provenance chain`);let degradationReasons=[];if(record3.status!=="completed")degradationReasons.push(`lane status ${record3.status}`);if(record3.result?.outputDegraded===!0)degradationReasons.push("output degraded");if(record3.result?.transcriptIncomplete===!0)degradationReasons.push("transcript incomplete");if(record3.result?.truncated===!0)degradationReasons.push("output truncated");if((record3.result?.chars??0)<=0)degradationReasons.push("empty output");if(!prReviewDiscoveryArtifactCoversLane(outputArtifact.artifact.text,row.trigger_id,recordOwnedLanes,record3.mode))degradationReasons.push(`no covered candidate or clean row for: ${row.trigger_id}`);for(let reason of degradationReasons)coverageDegradations.push({trigger_id:row.trigger_id,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id,reason})}let citedLaneEntries=[...citedLaneOwnership.entries()];for(let i=0;i<citedLaneEntries.length;i++)for(let j=i+1;j<citedLaneEntries.length;j++){let[keyA,ownedA]=citedLaneEntries[i],[keyB,ownedB]=citedLaneEntries[j],overlap2=ownedA.filter((family)=>ownedB.includes(family));if(overlap2.length>0)return failure4(`PR_REVIEW trigger evaluation cites two lanes with overlapping ownership: "${keyA}" and "${keyB}" both declare ${overlap2.join(", ")}`)}let matchedFamilySet=new Set(triggerLedger.matchedIds),citedOwnershipSet=new Set(citedLaneEntries.flatMap(([,owned])=>owned)),ownershipOutsideMatchedLedger=[...citedOwnershipSet].filter((family)=>!matchedFamilySet.has(family)),matchedWithoutOwnedLane=[...matchedFamilySet].filter((family)=>!citedOwnershipSet.has(family));if(ownershipOutsideMatchedLedger.length>0||matchedWithoutOwnedLane.length>0)return failure4(`PR_REVIEW cited lane ownership must equal the MATCHED trigger set; owned but NOT_TRIGGERED/unlisted: ${ownershipOutsideMatchedLedger.join(", ")||"(none)"}; MATCHED without cited ownership: ${matchedWithoutOwnedLane.join(", ")||"(none)"}`);if(!parsed.data.base_sha)return failure4("Active PR_REVIEW trigger evaluation requires the exact merge-base base_sha");if(!parsed.data.base_ref)return failure4("Active PR_REVIEW trigger evaluation requires the exact live base_ref used to verify base_sha");if(!gateState.prReviewBaseRef||!gateState.prReviewBaseSha)return failure4('Active PR_REVIEW trigger evaluation requires a durably bound review base; the active PR_REVIEW gate has no bound base_ref/base_sha, so the received scope cannot be verified against anything. Re-bind the review scope by dispatching the review lanes for this PR, or restart with abort_pr_workflow (kind "recovery").');let resolvedMergeBase=await resolveReviewMergeBase(directory,parsed.data.base_ref,parsed.data.pr_head_sha),baseVerification="live";if(resolvedMergeBase){if(resolvedMergeBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW merge-base mismatch: expected ${resolvedMergeBase}, received ${parsed.data.base_sha}`);if(gateState.prReviewBaseRef!==parsed.data.base_ref||gateState.prReviewBaseSha!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW trigger evaluation scope mismatch: workflow is bound to ${gateState.prReviewBaseRef??"(unbound)"} at ${gateState.prReviewBaseSha??"(unbound)"}, received ${parsed.data.base_ref} at ${parsed.data.base_sha}`)}else if(parsed.data.base_ref===gateState.prReviewBaseRef&&parsed.data.base_sha.toLowerCase()===gateState.prReviewBaseSha)baseVerification="bound_fallback",criticalWarn(`PR_REVIEW trigger evaluation could not re-derive the merge base for base_ref "${parsed.data.base_ref}" at pr_head_sha "${parsed.data.pr_head_sha}"; proceeding on the durably bound, bind-time-verified review scope (${gateState.prReviewBaseRef} at ${gateState.prReviewBaseSha}). The receipt discloses base_verification: bound_fallback and the final review report must disclose it too.`);else return failure4(`Active PR_REVIEW trigger evaluation could not resolve the exact merge base from base_ref "${parsed.data.base_ref}" and pr_head_sha "${parsed.data.pr_head_sha}", and the received scope does not equal the durably bound review scope (${gateState.prReviewBaseRef} at ${gateState.prReviewBaseSha}), so the bound-scope fallback does not apply. A null resolution collapses several causes: the bounded git call timed out, the git process failed to spawn, base_ref is not resolvable in this checkout, or base_ref/pr_head_sha was rejected as an unsafe revision token. Recovery: verify both revisions exist here (git rev-parse), retry once the environment settles, or restart with abort_pr_workflow (kind "recovery").`);let matchedCount=validatedRows.filter((row)=>row.result==="MATCHED").length,dispatchedMicroLaneCount2=new Set(validatedRows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size,microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[gateState.prReviewDepthTier??"L"],matchedCount);if(dispatchedMicroLaneCount2<microFloor)return failure4(`PR_REVIEW micro lane floor unmet: depth tier ${gateState.prReviewDepthTier??"L"} requires at least ${microFloor} dispatched micro lane(s) across the attestation; the ledger attributes ${matchedCount} matched families to only ${dispatchedMicroLaneCount2}`);let resolvedRunId;try{resolvedRunId=await resolvePrReviewWriterRunId(directory,sessionID,parsed.data.run_id)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let artifact=buildPrReviewTriggerReceiptV2({run_id:resolvedRunId,pr_head_sha:parsed.data.pr_head_sha,base_ref:parsed.data.base_ref,base_sha:parsed.data.base_sha,evaluated_at:new Date().toISOString(),dispatched_micro_lane_count:dispatchedMicroLaneCount2,rows:validatedRows,coverage_degradations:coverageDegradations,base_verification:baseVerification}),relativePath2=path360.join("pr-review",resolvedRunId,"trigger-eval.json"),destination;try{destination=validateSwarmPath(directory,relativePath2)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let replayed=!1;try{let existing=null;try{existing=await readBoundedTriggerReceipt(destination)}catch(error93){if(error93.code!=="ENOENT")throw error93}if(existing){if(comparableTriggerReceipt(existing)!==comparableTriggerReceipt(artifact))return failure4(`PR_REVIEW trigger evaluation receipt already exists for run "${resolvedRunId}" with conflicting content`);artifact=existing,replayed=!0}else if(!await createTriggerReceipt(destination,`${JSON.stringify(artifact,null,2)}
|
|
7563
|
-
`)){let raced=await readBoundedTriggerReceipt(destination);if(comparableTriggerReceipt(raced)!==comparableTriggerReceipt(artifact))return failure4(`PR_REVIEW trigger evaluation receipt concurrently appeared for run "${resolvedRunId}" with conflicting content`);artifact=raced,replayed=!0}}catch(error93){return failure4(`Failed to read or persist trigger evaluation at "${relativePath2.split(path360.sep).join("/")}": ${error93 instanceof Error?error93.message:String(error93)}`)}try{await _internals300.markPrReviewTriggerEvaluationComplete(directory,sessionID,resolvedRunId,relativePath2.split(path360.sep).join("/"))}catch(error93){return failure4(`Failed to persist trigger evaluation gate receipt for "${relativePath2.split(path360.sep).join("/")}": ${error93 instanceof Error?error93.message:String(error93)}`)}return JSON.stringify({success:!0,replayed,run_id:resolvedRunId,path:relativePath2.split(path360.sep).join("/"),trigger_count:artifact.trigger_count,matched_count:artifact.matched_count,not_triggered_count:artifact.not_triggered_count,no_match_count:artifact.no_match_count,dispatched_micro_lane_count:dispatchedMicroLaneCount2,base_verification:baseVerification,...baseVerification==="bound_fallback"?{base_verification_note:"live merge-base re-derivation was unavailable; the bound review scope was used and MUST be disclosed in the final review report"}:{},coverage_degradation_count:coverageDegradations.length,...coverageDegradations.length>0?{coverage_degradations:coverageDegradations,note:"degraded families recorded on the receipt; disclose them in the final review report"}:{}},null,2)}var write_pr_review_trigger_eval=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Persist the complete, exact-set PR-review trigger receipt after every MATCHED family has completed. Supply classifications and MATCHED provenance; evidence is optional and non-authoritative because the receipt reuses evidence frozen by the first micro dispatch. NOT_TRIGGERED families remain provenance-free.",args:{run_id:WritePrReviewTriggerEvalArgsSchema.shape.run_id,pr_head_sha:WritePrReviewTriggerEvalArgsSchema.shape.pr_head_sha,base_sha:WritePrReviewTriggerEvalArgsSchema.shape.base_sha,base_ref:WritePrReviewTriggerEvalArgsSchema.shape.base_ref,rows:WritePrReviewTriggerEvalArgsSchema.shape.rows},execute:executeWritePrReviewTriggerEval});init_write_retro();function defineHandlers(handlers){return handlers}var TOOL_MANIFEST=defineHandlers({diff:()=>diff,diff_summary:()=>diff_summary,syntax_check:()=>syntax_check,placeholder_scan:()=>placeholder_scan,imports:()=>imports,lint:()=>lint,secretscan:()=>secretscan,sast_scan:()=>sast_scan,build_check:()=>build_check,pre_check_batch:()=>pre_check_batch,quality_budget:()=>quality_budget,symbols:()=>symbols,complexity_hotspots:()=>complexity_hotspots,schema_drift:()=>schema_drift,todo_extract:()=>todo_extract,evidence_check:()=>evidence_check,check_gate_status:()=>check_gate_status,completion_verify:()=>completion_verify,complete_pr_workflow:()=>complete_pr_workflow,abort_pr_workflow:()=>abort_pr_workflow,authorize_pr_review_reentry:()=>authorize_pr_review_reentry,submit_pr_review_result:()=>submit_pr_review_result,approve_plan_critic:()=>approve_plan_critic,prepare_pr_workflow_checkout:()=>prepare_pr_workflow_checkout,record_implementation_review:()=>record_implementation_review,record_issue_publication:()=>record_issue_publication,record_issue_reproduction:()=>record_issue_reproduction,record_recurrence_sweep:()=>record_recurrence_sweep,invalidate_pr_feedback_publication:()=>invalidate_pr_feedback_publication,rebind_pr_feedback_head:()=>rebind_pr_feedback_head,run_pr_feedback_stage_a:()=>run_pr_feedback_stage_a,submit_council_verdicts:()=>submit_council_verdicts,submit_phase_council_verdicts:()=>submit_phase_council_verdicts,declare_council_criteria:()=>declare_council_criteria,sbom_generate:()=>sbom_generate,checkpoint:()=>checkpoint,pkg_audit:()=>pkg_audit,parse_lane_candidates:()=>parse_lane_candidates,plan_conflict_check:()=>plan_conflict_check,prepare_pr_feedback_scope:()=>prepare_pr_feedback_scope,write_pr_review_artifact:()=>write_pr_review_artifact,write_pr_review_trigger_eval:()=>write_pr_review_trigger_eval,test_runner:()=>test_runner,test_impact:()=>test_impact,mutation_test:()=>mutation_test,generate_mutants:()=>generate_mutants,detect_domains:()=>detect_domains,git_blame:()=>git_blame,gitingest:()=>gitingest,retrieve_summary:()=>retrieve_summary,retrieve_lane_output:()=>retrieve_lane_output,extract_code_blocks:()=>extract_code_blocks,phase_complete:()=>phase_complete,run_phase_review:()=>run_phase_review,repair_gate_evidence:()=>repair_gate_evidence,repair_knowledge_receipt_ledger:()=>repair_knowledge_receipt_ledger,record_directive_override:()=>record_directive_override,save_plan:()=>save_plan,update_task_status:()=>update_task_status,lint_spec:()=>lint_spec,write_retro:()=>write_retro,write_drift_evidence:()=>write_drift_evidence,write_hallucination_evidence:()=>write_hallucination_evidence,write_mutation_evidence:()=>write_mutation_evidence,declare_scope:()=>declare_scope,knowledge_query:()=>knowledge_query,doc_scan:()=>doc_scan,doc_extract:()=>doc_extract,curator_analyze:()=>curator_analyze,consensus_mine:()=>consensus_mine,knowledge_add:()=>knowledge_add,knowledge_recall:()=>knowledge_recall,knowledge_remove:()=>knowledge_remove,co_change_analyzer:()=>co_change_analyzer,context_status:()=>context_status,search:()=>search,ast_grep:()=>ast_grep,actionlint_scan:()=>actionlint_scan,osv_scan:()=>osv_scan,gh_evidence:()=>gh_evidence,pr_workflow_status:()=>pr_workflow_status,batch_symbols:()=>batch_symbols,suggest_patch:()=>suggestPatch,req_coverage:()=>req_coverage,get_approved_plan:()=>get_approved_plan,repo_map:()=>repo_map,get_qa_gate_profile:()=>get_qa_gate_profile,set_qa_gates:()=>set_qa_gates,web_search:()=>web_search,web_fetch:()=>web_fetch,convene_general_council:()=>convene_general_council,write_final_council_evidence:()=>write_final_council_evidence,skill_generate:()=>skill_generate,skill_list:()=>skill_list,skill_apply:()=>skill_apply,skill_inspect:()=>skill_inspect,run_stale_reconciliation:()=>run_stale_reconciliation,skill_regenerate:()=>skill_regenerate,skill_retire:()=>skill_retire,skill_improve:()=>skill_improve,spec_write:()=>spec_write,knowledge_receipt:()=>knowledge_receipt,knowledge_archive:()=>knowledge_archive,swarm_memory_recall:()=>swarm_memory_recall,swarm_memory_propose:()=>swarm_memory_propose,swarm_memory_outcome:()=>swarm_memory_outcome,swarm_command:()=>swarm_command,dispatch_lanes:()=>dispatch_lanes,dispatch_lanes_async:()=>dispatch_lanes_async,collect_lane_results:()=>collect_lane_results,summarize_work:()=>summarize_work,write_architecture_supervisor_evidence:()=>write_architecture_supervisor_evidence,lean_turbo_plan_lanes:()=>lean_turbo_plan_lanes,lean_turbo_acquire_locks:()=>lean_turbo_acquire_locks,lean_turbo_critic:()=>lean_turbo_critic,lean_turbo_runner_status:()=>lean_turbo_runner_status,lean_turbo_review:()=>lean_turbo_review,lean_turbo_run_phase:()=>lean_turbo_run_phase,lean_turbo_status:()=>lean_turbo_status,swarm_apply_patch:()=>swarmApplyPatch2,external_skill_discover:()=>external_skill_discover,external_skill_list:()=>external_skill_list,external_skill_inspect:()=>external_skill_inspect,external_skill_promote:()=>external_skill_promote,external_skill_reject:()=>external_skill_reject,external_skill_delete:()=>external_skill_delete,external_skill_revoke:()=>external_skill_revoke,epic_decide_phase:()=>epic_decide_phase,epic_plan_waves:()=>epic_plan_waves,epic_record_divergence:()=>epic_record_divergence});function buildPluginToolObject(agents,config3,evaluationModelDispatcher,reviewModelDispatcher,generatedAgentNames=Object.keys(agents),reviewAgentModelRegistry,getActiveAgentName){let tools={},reviewAgentNames=Object.freeze([...generatedAgentNames]),knowledgeEnabled=config3?.knowledge?.enabled!==!1,knowledgeTools=new Set(["knowledge_add","knowledge_recall","knowledge_remove","knowledge_query","knowledge_receipt","knowledge_archive"]);for(let[name,handler]of Object.entries(TOOL_MANIFEST)){if(!knowledgeEnabled&&knowledgeTools.has(name))continue;tools[name]=handler()}tools.swarm_command=createSwarmCommandTool(agents,evaluationModelDispatcher,reviewModelDispatcher,config3?.auto_review,reviewAgentModelRegistry,getActiveAgentName),tools.phase_complete=createPhaseCompleteTool({reviewModelDispatcher,generatedAgentNames:reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName}),tools.run_phase_review=createRunPhaseReviewTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_review=createLeanTurboReviewTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_critic=createLeanTurboCriticTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_run_phase=createLeanTurboRunPhaseTool(reviewAgentNames);let tracked={};for(let[name,def]of Object.entries(tools)){let execute2=def.execute;if(typeof execute2==="function")tracked[name]={...def,execute:withStartupFirstToolTracking(name,execute2)};else tracked[name]=def}return tracked}init_package();init_consent();init_vault();var PLUGIN_VERSION=package_default.version,MAX_DEDUP_PER_SESSION=4096,MAX_TRACKED_DEDUP_SESSIONS=500,GUIDANCE_CARRIER_ID_PREFIX="swarm-guidance:",DIRECTIVE_TEXT_PREFIX="<swarm_system_directive";function safeStringify(value){try{return JSON.stringify(value)??""}catch{return String(value)}}var _internals301={appendRecord:appendTrainingVaultRecord,readConsent:(directory)=>readActiveTrainingConsent(directory),buildRecord:buildTrainingVaultRecord};function kindForRole(role){if(role==="user")return"user_message";if(role==="assistant")return"assistant_message";return null}function createTrainingCaptureObserver(directory){let dedupBySession=new Map;function markSeen(sessionId,recordId){let entry=dedupBySession.get(sessionId);if(!entry){entry={order:[],seen:new Set},dedupBySession.set(sessionId,entry);while(dedupBySession.size>MAX_TRACKED_DEDUP_SESSIONS){let oldest=dedupBySession.keys().next().value;if(oldest===void 0)break;dedupBySession.delete(oldest)}}if(entry.seen.has(recordId))return!1;if(entry.seen.add(recordId),entry.order.push(recordId),entry.order.length>MAX_DEDUP_PER_SESSION){let evicted=entry.order.shift();if(evicted!==void 0)entry.seen.delete(evicted)}return!0}function capture(kind,role,content,sessionId,source){let consent=_internals301.readConsent(directory);if(!consent)return;let record3=_internals301.buildRecord({directory,kind,role,content,sessionId,pluginVersion:PLUGIN_VERSION,source,consent});if(!markSeen(sessionId,record3.record_id))return;_internals301.appendRecord(directory,record3)}return{async observeMessages(output){try{let messages=output?.messages;if(!Array.isArray(messages))return;for(let message of messages)try{let info=message?.info;if(!info)continue;let sessionId=info.sessionID;if(typeof sessionId!=="string"||sessionId.length===0)continue;if(typeof info.id==="string"&&info.id.startsWith(GUIDANCE_CARRIER_ID_PREFIX))continue;let kind=kindForRole(info.role??"");if(!kind)continue;let parts=message.parts;if(!Array.isArray(parts))continue;for(let part of parts)try{if(part?.type!=="text")continue;let text=typeof part.text==="string"?part.text:"";if(text.length===0)continue;if(text.startsWith(DIRECTIVE_TEXT_PREFIX))continue;capture(kind,info.role??"",text,sessionId,"chat")}catch{}}catch{}}catch{}},async observeToolExecution(event){try{let sessionId=event?.sessionID;if(typeof sessionId!=="string"||sessionId.length===0)return;let tool3=typeof event?.tool==="string"?event.tool:"unknown",inputSummary=safeStringify(event?.input);if(inputSummary.length>0)capture("tool_call","tool",inputSummary,sessionId,"tool");let outputSummary=safeStringify(event?.error??event?.output??"");if(outputSummary.length>0&&outputSummary!=='""')capture("tool_result","tool",`${tool3}
|
|
7563
|
+
`)){let raced=await readBoundedTriggerReceipt(destination);if(comparableTriggerReceipt(raced)!==comparableTriggerReceipt(artifact))return failure4(`PR_REVIEW trigger evaluation receipt concurrently appeared for run "${resolvedRunId}" with conflicting content`);artifact=raced,replayed=!0}}catch(error93){return failure4(`Failed to read or persist trigger evaluation at "${relativePath2.split(path360.sep).join("/")}": ${error93 instanceof Error?error93.message:String(error93)}`)}try{await _internals300.markPrReviewTriggerEvaluationComplete(directory,sessionID,resolvedRunId,relativePath2.split(path360.sep).join("/"))}catch(error93){return failure4(`Failed to persist trigger evaluation gate receipt for "${relativePath2.split(path360.sep).join("/")}": ${error93 instanceof Error?error93.message:String(error93)}`)}return JSON.stringify({success:!0,replayed,run_id:resolvedRunId,path:relativePath2.split(path360.sep).join("/"),trigger_count:artifact.trigger_count,matched_count:artifact.matched_count,not_triggered_count:artifact.not_triggered_count,no_match_count:artifact.no_match_count,dispatched_micro_lane_count:dispatchedMicroLaneCount2,base_verification:baseVerification,...baseVerification==="bound_fallback"?{base_verification_note:"live merge-base re-derivation was unavailable; the bound review scope was used and MUST be disclosed in the final review report"}:{},coverage_degradation_count:coverageDegradations.length,...coverageDegradations.length>0?{coverage_degradations:coverageDegradations,note:"degraded families recorded on the receipt; disclose them in the final review report"}:{}},null,2)}var write_pr_review_trigger_eval=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Persist the complete, exact-set PR-review trigger receipt after every MATCHED family has completed. Supply classifications and MATCHED provenance; evidence is optional and non-authoritative because the receipt reuses evidence frozen by the first micro dispatch. NOT_TRIGGERED families remain provenance-free.",args:{run_id:WritePrReviewTriggerEvalArgsSchema.shape.run_id,pr_head_sha:WritePrReviewTriggerEvalArgsSchema.shape.pr_head_sha,base_sha:WritePrReviewTriggerEvalArgsSchema.shape.base_sha,base_ref:WritePrReviewTriggerEvalArgsSchema.shape.base_ref,rows:WritePrReviewTriggerEvalArgsSchema.shape.rows},execute:executeWritePrReviewTriggerEval});init_write_retro();function defineHandlers(handlers){return handlers}var TOOL_MANIFEST=defineHandlers({diff:()=>diff,diff_summary:()=>diff_summary,syntax_check:()=>syntax_check,placeholder_scan:()=>placeholder_scan,imports:()=>imports,lint:()=>lint,secretscan:()=>secretscan,sast_scan:()=>sast_scan,build_check:()=>build_check,pre_check_batch:()=>pre_check_batch,quality_budget:()=>quality_budget,symbols:()=>symbols,complexity_hotspots:()=>complexity_hotspots,schema_drift:()=>schema_drift,todo_extract:()=>todo_extract,evidence_check:()=>evidence_check,check_gate_status:()=>check_gate_status,completion_verify:()=>completion_verify,complete_pr_workflow:()=>complete_pr_workflow,abort_pr_workflow:()=>abort_pr_workflow,authorize_pr_review_reentry:()=>authorize_pr_review_reentry,submit_pr_review_result:()=>submit_pr_review_result,approve_plan_critic:()=>approve_plan_critic,approve_retry_sounding_board:()=>approve_retry_sounding_board,prepare_pr_workflow_checkout:()=>prepare_pr_workflow_checkout,record_implementation_review:()=>record_implementation_review,record_issue_publication:()=>record_issue_publication,record_issue_reproduction:()=>record_issue_reproduction,record_recurrence_sweep:()=>record_recurrence_sweep,invalidate_pr_feedback_publication:()=>invalidate_pr_feedback_publication,rebind_pr_feedback_head:()=>rebind_pr_feedback_head,run_pr_feedback_stage_a:()=>run_pr_feedback_stage_a,submit_council_verdicts:()=>submit_council_verdicts,submit_phase_council_verdicts:()=>submit_phase_council_verdicts,declare_council_criteria:()=>declare_council_criteria,sbom_generate:()=>sbom_generate,checkpoint:()=>checkpoint,pkg_audit:()=>pkg_audit,parse_lane_candidates:()=>parse_lane_candidates,plan_conflict_check:()=>plan_conflict_check,prepare_pr_feedback_scope:()=>prepare_pr_feedback_scope,write_pr_review_artifact:()=>write_pr_review_artifact,write_pr_review_trigger_eval:()=>write_pr_review_trigger_eval,test_runner:()=>test_runner,test_impact:()=>test_impact,mutation_test:()=>mutation_test,generate_mutants:()=>generate_mutants,detect_domains:()=>detect_domains,git_blame:()=>git_blame,gitingest:()=>gitingest,retrieve_summary:()=>retrieve_summary,retrieve_lane_output:()=>retrieve_lane_output,extract_code_blocks:()=>extract_code_blocks,phase_complete:()=>phase_complete,run_phase_review:()=>run_phase_review,repair_gate_evidence:()=>repair_gate_evidence,repair_knowledge_receipt_ledger:()=>repair_knowledge_receipt_ledger,record_directive_override:()=>record_directive_override,save_plan:()=>save_plan,update_task_status:()=>update_task_status,lint_spec:()=>lint_spec,write_retro:()=>write_retro,write_drift_evidence:()=>write_drift_evidence,write_hallucination_evidence:()=>write_hallucination_evidence,write_mutation_evidence:()=>write_mutation_evidence,declare_scope:()=>declare_scope,knowledge_query:()=>knowledge_query,doc_scan:()=>doc_scan,doc_extract:()=>doc_extract,curator_analyze:()=>curator_analyze,consensus_mine:()=>consensus_mine,knowledge_add:()=>knowledge_add,knowledge_recall:()=>knowledge_recall,knowledge_remove:()=>knowledge_remove,co_change_analyzer:()=>co_change_analyzer,context_status:()=>context_status,search:()=>search,ast_grep:()=>ast_grep,actionlint_scan:()=>actionlint_scan,osv_scan:()=>osv_scan,gh_evidence:()=>gh_evidence,pr_workflow_status:()=>pr_workflow_status,batch_symbols:()=>batch_symbols,suggest_patch:()=>suggestPatch,req_coverage:()=>req_coverage,get_approved_plan:()=>get_approved_plan,repo_map:()=>repo_map,get_qa_gate_profile:()=>get_qa_gate_profile,set_qa_gates:()=>set_qa_gates,web_search:()=>web_search,web_fetch:()=>web_fetch,convene_general_council:()=>convene_general_council,write_final_council_evidence:()=>write_final_council_evidence,skill_generate:()=>skill_generate,skill_list:()=>skill_list,skill_apply:()=>skill_apply,skill_inspect:()=>skill_inspect,run_stale_reconciliation:()=>run_stale_reconciliation,skill_regenerate:()=>skill_regenerate,skill_retire:()=>skill_retire,skill_improve:()=>skill_improve,spec_write:()=>spec_write,knowledge_receipt:()=>knowledge_receipt,knowledge_archive:()=>knowledge_archive,swarm_memory_recall:()=>swarm_memory_recall,swarm_memory_propose:()=>swarm_memory_propose,swarm_memory_outcome:()=>swarm_memory_outcome,swarm_command:()=>swarm_command,dispatch_lanes:()=>dispatch_lanes,dispatch_lanes_async:()=>dispatch_lanes_async,collect_lane_results:()=>collect_lane_results,summarize_work:()=>summarize_work,write_architecture_supervisor_evidence:()=>write_architecture_supervisor_evidence,lean_turbo_plan_lanes:()=>lean_turbo_plan_lanes,lean_turbo_acquire_locks:()=>lean_turbo_acquire_locks,lean_turbo_critic:()=>lean_turbo_critic,lean_turbo_runner_status:()=>lean_turbo_runner_status,lean_turbo_review:()=>lean_turbo_review,lean_turbo_run_phase:()=>lean_turbo_run_phase,lean_turbo_status:()=>lean_turbo_status,swarm_apply_patch:()=>swarmApplyPatch2,external_skill_discover:()=>external_skill_discover,external_skill_list:()=>external_skill_list,external_skill_inspect:()=>external_skill_inspect,external_skill_promote:()=>external_skill_promote,external_skill_reject:()=>external_skill_reject,external_skill_delete:()=>external_skill_delete,external_skill_revoke:()=>external_skill_revoke,epic_decide_phase:()=>epic_decide_phase,epic_plan_waves:()=>epic_plan_waves,epic_record_divergence:()=>epic_record_divergence});function buildPluginToolObject(agents,config3,evaluationModelDispatcher,reviewModelDispatcher,generatedAgentNames=Object.keys(agents),reviewAgentModelRegistry,getActiveAgentName){let tools={},reviewAgentNames=Object.freeze([...generatedAgentNames]),knowledgeEnabled=config3?.knowledge?.enabled!==!1,knowledgeTools=new Set(["knowledge_add","knowledge_recall","knowledge_remove","knowledge_query","knowledge_receipt","knowledge_archive"]);for(let[name,handler]of Object.entries(TOOL_MANIFEST)){if(!knowledgeEnabled&&knowledgeTools.has(name))continue;tools[name]=handler()}tools.swarm_command=createSwarmCommandTool(agents,evaluationModelDispatcher,reviewModelDispatcher,config3?.auto_review,reviewAgentModelRegistry,getActiveAgentName),tools.phase_complete=createPhaseCompleteTool({reviewModelDispatcher,generatedAgentNames:reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName}),tools.run_phase_review=createRunPhaseReviewTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_review=createLeanTurboReviewTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_critic=createLeanTurboCriticTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_run_phase=createLeanTurboRunPhaseTool(reviewAgentNames);let tracked={};for(let[name,def]of Object.entries(tools)){let execute2=def.execute;if(typeof execute2==="function")tracked[name]={...def,execute:withStartupFirstToolTracking(name,execute2)};else tracked[name]=def}return tracked}init_package();init_consent();init_vault();var PLUGIN_VERSION=package_default.version,MAX_DEDUP_PER_SESSION=4096,MAX_TRACKED_DEDUP_SESSIONS=500,GUIDANCE_CARRIER_ID_PREFIX="swarm-guidance:",DIRECTIVE_TEXT_PREFIX="<swarm_system_directive";function safeStringify(value){try{return JSON.stringify(value)??""}catch{return String(value)}}var _internals301={appendRecord:appendTrainingVaultRecord,readConsent:(directory)=>readActiveTrainingConsent(directory),buildRecord:buildTrainingVaultRecord};function kindForRole(role){if(role==="user")return"user_message";if(role==="assistant")return"assistant_message";return null}function createTrainingCaptureObserver(directory){let dedupBySession=new Map;function markSeen(sessionId,recordId){let entry=dedupBySession.get(sessionId);if(!entry){entry={order:[],seen:new Set},dedupBySession.set(sessionId,entry);while(dedupBySession.size>MAX_TRACKED_DEDUP_SESSIONS){let oldest=dedupBySession.keys().next().value;if(oldest===void 0)break;dedupBySession.delete(oldest)}}if(entry.seen.has(recordId))return!1;if(entry.seen.add(recordId),entry.order.push(recordId),entry.order.length>MAX_DEDUP_PER_SESSION){let evicted=entry.order.shift();if(evicted!==void 0)entry.seen.delete(evicted)}return!0}function capture(kind,role,content,sessionId,source){let consent=_internals301.readConsent(directory);if(!consent)return;let record3=_internals301.buildRecord({directory,kind,role,content,sessionId,pluginVersion:PLUGIN_VERSION,source,consent});if(!markSeen(sessionId,record3.record_id))return;_internals301.appendRecord(directory,record3)}return{async observeMessages(output){try{let messages=output?.messages;if(!Array.isArray(messages))return;for(let message of messages)try{let info=message?.info;if(!info)continue;let sessionId=info.sessionID;if(typeof sessionId!=="string"||sessionId.length===0)continue;if(typeof info.id==="string"&&info.id.startsWith(GUIDANCE_CARRIER_ID_PREFIX))continue;let kind=kindForRole(info.role??"");if(!kind)continue;let parts=message.parts;if(!Array.isArray(parts))continue;for(let part of parts)try{if(part?.type!=="text")continue;let text=typeof part.text==="string"?part.text:"";if(text.length===0)continue;if(text.startsWith(DIRECTIVE_TEXT_PREFIX))continue;capture(kind,info.role??"",text,sessionId,"chat")}catch{}}catch{}}catch{}},async observeToolExecution(event){try{let sessionId=event?.sessionID;if(typeof sessionId!=="string"||sessionId.length===0)return;let tool3=typeof event?.tool==="string"?event.tool:"unknown",inputSummary=safeStringify(event?.input);if(inputSummary.length>0)capture("tool_call","tool",inputSummary,sessionId,"tool");let outputSummary=safeStringify(event?.error??event?.output??"");if(outputSummary.length>0&&outputSummary!=='""')capture("tool_result","tool",`${tool3}
|
|
7564
7564
|
${outputSummary}`,sessionId,"tool")}catch{}}}}init_utils();init_git_executable();init_timeout();function truncateToolOutput(output,maxLines,toolName,tailLines=10){if(!output)return output;if(tailLines>=maxLines)tailLines=Math.floor(maxLines/2);let lines=output.split(`
|
|
7565
7565
|
`);if(lines.length<=maxLines)return output;let omittedCount=lines.length-maxLines,headLines=lines.slice(0,maxLines-tailLines),tailContent=lines.slice(-tailLines),footerLines=[];if(footerLines.push(""),footerLines.push(`[... ${omittedCount} line${omittedCount===1?"":"s"} omitted ...]`),toolName)footerLines.push(`Tool: ${toolName}`);return footerLines.push("Use /swarm retrieve <id> to get the full content"),`${headLines.join(`
|
|
7566
7566
|
`)}
|