opencode-swarm 7.113.4 → 7.114.0

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/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.113.4",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},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",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/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/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/swarm",".opencode/skills/swarm-ci-monitor",".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","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && 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","drift:check":"bun run scripts/drift-check.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:1144":"bun scripts/repro-1144.mjs"},dependencies:{"@opencode-ai/plugin":"^1.1.53","@opencode-ai/sdk":"^1.1.53","@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.1.8"},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"}}});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"],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]});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_oversight","coder","test_engineer"]},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"]},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"]},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"]},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","coder","test_engineer"]},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"]},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"]},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"]},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"]},quality_budget:{description:"code quality budget check",agents:["architect"]},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","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","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"]},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"]},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"]},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_oversight","test_engineer"]},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"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"]},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","explorer","architect"]},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"]},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","coder","test_engineer"]},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"]},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:"mark a phase as complete and track dispatched agents",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"]},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","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, model-limit, 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_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"]},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"]},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"]},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_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"]},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","critic_oversight","explorer","coder"]},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: 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.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is 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.",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","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_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","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 so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates.",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_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 deepMergeInternal(base,override,depth){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);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS 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("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS 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,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,WRITE_TOOL_NAMES,DEFAULT_MODELS,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.114.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"},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",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/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/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/swarm",".opencode/skills/swarm-ci-monitor",".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","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && 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","drift:check":"bun run scripts/drift-check.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm",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:1144":"bun scripts/repro-1144.mjs"},dependencies:{"@opencode-ai/plugin":"^1.1.53","@opencode-ai/sdk":"^1.1.53","@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.1.8"},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"}}});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"],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]});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_oversight","coder","test_engineer"]},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"]},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"]},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"]},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","coder","test_engineer"]},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"]},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"]},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"]},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"]},quality_budget:{description:"code quality budget check",agents:["architect"]},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","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","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"]},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"]},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"]},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_oversight","test_engineer"]},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"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"]},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","explorer","architect"]},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"]},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","coder","test_engineer"]},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"]},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:"mark a phase as complete and track dispatched agents",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"]},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","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, model-limit, 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_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"]},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"]},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"]},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_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"]},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","critic_oversight","explorer","coder"]},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: 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.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is 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.",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","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_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","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 so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates.",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_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 deepMergeInternal(base,override,depth){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);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS 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("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS 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,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,WRITE_TOOL_NAMES,DEFAULT_MODELS,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
 
@@ -647,7 +647,7 @@ ${warnings.map((w)=>`Detected signal: ${w}`).join(`
647
647
  `),validStartMs=[];for(let line of lines){if(!line.trim())continue;try{let parsed=JSON.parse(line);if(typeof parsed.startMs==="number"&&Number.isFinite(parsed.startMs))validStartMs.push(parsed.startMs)}catch{}}if(validStartMs.length===0)return null;return new Date(Math.min(...validStartMs)).toISOString()}catch{return null}}var SESSION_START_FILE="session-start.jsonl";var init_session_start_store=()=>{};import{existsSync as existsSync21,lstatSync as lstatSync5,mkdirSync as mkdirSync17,readFileSync as readFileSync15,rmSync as rmSync3}from"node:fs";import*as os12 from"node:os";import*as path47 from"node:path";function resolveDataDir(){let platform=process.platform,home=process.env.HOME||os12.homedir();if(platform==="win32")return path47.join(process.env.LOCALAPPDATA||path47.join(home,"AppData","Local"),"opencode-swarm","Data");else if(platform==="darwin")return path47.join(home,"Library","Application Support","opencode-swarm");return path47.join(process.env.XDG_DATA_HOME||path47.join(home,".local","share"),"opencode-swarm")}function resolveLinkBaseDir(){return path47.join(resolveDataDir(),"links")}function resolveLinkDir(linkId){return path47.join(resolveLinkBaseDir(),linkId)}function sanitizeLinkId(name){if(typeof name!=="string")return null;let cleaned=name.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,MAX_LINK_ID_LENGTH).replace(/[-.]+$/g,"");if(cleaned.length===0)return null;let base=cleaned.split(".")[0];if(WINDOWS_RESERVED_NAMES.has(base))return null;return cleaned}function resolveLinkPointerPath(directory){return path47.join(directory,".swarm",LINK_POINTER_FILENAME)}function readLinkPointer(directory){let pointerPath=resolveLinkPointerPath(directory);if(!existsSync21(pointerPath))return null;try{let raw=JSON.parse(readFileSync15(pointerPath,"utf-8"));if(!raw||typeof raw!=="object")return null;let obj=raw,linkId=obj.linkId;if(typeof linkId!=="string"||linkId.length===0)return null;let safeId=sanitizeLinkId(linkId);if(!safeId)return null;return{version:1,linkId:safeId,name:typeof obj.name==="string"?obj.name:void 0,createdAt:typeof obj.createdAt==="string"?obj.createdAt:new Date(0).toISOString(),source:obj.source==="auto"?"auto":"manual"}}catch{return null}}function getLinkedLocalKnowledgeStatus(directory){let localKnowledgePath=path47.join(directory,".swarm","knowledge.jsonl"),pointer=readLinkPointer(directory);if(!pointer)return{linked:!1,orphaned:!1,localKnowledgePath,resolvedKnowledgePath:localKnowledgePath,reason:"not_linked"};let resolvedKnowledgePath=path47.join(path47.resolve(resolveLinkDir(pointer.linkId)),"knowledge.jsonl");if(!existsSync21(localKnowledgePath))return{linked:!0,orphaned:!1,localKnowledgePath,resolvedKnowledgePath,reason:"local_missing"};try{if(lstatSync5(localKnowledgePath).isSymbolicLink())return{linked:!0,orphaned:!1,localKnowledgePath,resolvedKnowledgePath,reason:"local_symlink"}}catch{return{linked:!0,orphaned:!1,localKnowledgePath,resolvedKnowledgePath,reason:"local_missing"}}return{linked:!0,orphaned:!0,localKnowledgePath,resolvedKnowledgePath,reason:"local_regular_file"}}async function writeLinkPointer(directory,pointer){let swarmDir=path47.join(directory,".swarm");mkdirSync17(swarmDir,{recursive:!0});let pointerPath=resolveLinkPointerPath(directory);await atomicWriteFile(pointerPath,JSON.stringify(pointer,null,2)),invalidateKnowledgeStoreDirCache(directory)}async function removeLinkPointer(directory){let pointerPath=resolveLinkPointerPath(directory);try{rmSync3(pointerPath,{force:!0})}finally{invalidateKnowledgeStoreDirCache(directory)}}function resolveKnowledgeStoreDir(directory){let localSwarm=path47.join(directory,".swarm"),now=Date.now(),cached2=_resolutionCache.get(directory);if(cached2&&now<cached2.expires)return cached2.linkDir??localSwarm;let linkDir=null;try{let pointer=readLinkPointer(directory);if(pointer){linkDir=path47.resolve(resolveLinkDir(pointer.linkId));let orphanStatus=getLinkedLocalKnowledgeStatus(directory);if(orphanStatus.orphaned)warn("[knowledge-link] local knowledge file is orphaned by link store",{localKnowledgePath:orphanStatus.localKnowledgePath,resolvedKnowledgePath:orphanStatus.resolvedKnowledgePath})}}catch{linkDir=null}if(!_resolutionCache.has(directory)&&_resolutionCache.size>=MAX_CACHE_ENTRIES2){let oldest=_resolutionCache.keys().next().value;if(oldest!==void 0)_resolutionCache.delete(oldest)}return _resolutionCache.set(directory,{linkDir,expires:now+CACHE_TTL_MS}),linkDir??localSwarm}function invalidateKnowledgeStoreDirCache(directory){if(directory===void 0){_resolutionCache.clear();return}_resolutionCache.delete(directory)}function isLinked(directory){return readLinkPointer(directory)!==null}var LINK_POINTER_FILENAME="link.json",MAX_LINK_ID_LENGTH=64,WINDOWS_RESERVED_NAMES,CACHE_TTL_MS=2000,MAX_CACHE_ENTRIES2=500,_resolutionCache;var init_knowledge_link=__esm(()=>{init_task_file();init_logger();WINDOWS_RESERVED_NAMES=new Set(["con","prn","aux","nul","com0","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt0","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);_resolutionCache=new Map});import{execFile as execFile2}from"node:child_process";function markSuggested(sessionId){if(_suggestedSessions.has(sessionId))return;if(_suggestedSessions.size>=MAX_SUGGESTED_SESSIONS){let oldest=_suggestedSessions.values().next().value;if(oldest!==void 0)_suggestedSessions.delete(oldest)}_suggestedSessions.add(sessionId)}function countWorktrees(directory){return new Promise((resolve25)=>{try{let child=execFile2("git",["-C",directory,"worktree","list","--porcelain"],{timeout:GIT_TIMEOUT_MS2,windowsHide:!0,encoding:"utf-8"},(err,stdout)=>{if(err||typeof stdout!=="string"){resolve25(0);return}let count=0;for(let line of stdout.split(`
648
648
  `))if(line.startsWith("worktree "))count++;resolve25(count)});try{child.stdin?.end()}catch{}child.on("error",()=>resolve25(0))}catch{resolve25(0)}})}async function maybeSuggestWorktreeLink(directory,sessionId){try{if(!directory||!sessionId)return;if(_suggestedSessions.has(sessionId))return;if(markSuggested(sessionId),isLinked(directory))return;let worktrees=await countWorktrees(directory);if(worktrees>1)console.warn(`[opencode-swarm] Detected ${worktrees} git worktrees of this repo. Run \`/swarm link\` in each to share swarm knowledge across them (or \`/swarm link <name>\` to share with similar projects).`)}catch{}}var GIT_TIMEOUT_MS2=1500,MAX_SUGGESTED_SESSIONS=500,_suggestedSessions;var init_worktree_link_suggestion=__esm(()=>{init_knowledge_link();_suggestedSessions=new Set});class AgentRunContext{runId;activeToolCalls;activeAgent;delegationChains;agentSessions;environmentProfiles;toolAggregates;constructor(runId,toolAggregates){this.runId=runId,this.activeToolCalls=new Map,this.activeAgent=new Map,this.delegationChains=new Map,this.agentSessions=new Map,this.environmentProfiles=new Map,this.toolAggregates=toolAggregates}}var exports_pr_subscriptions={};__export(exports_pr_subscriptions,{updateSnapshot:()=>updateSnapshot,unsubscribe:()=>unsubscribe,sweepStale:()=>sweepStale,subscribe:()=>subscribe,setOnSubscriptionCreated:()=>setOnSubscriptionCreated,lookupByPr:()=>lookupByPr,listActive:()=>listActive,buildCorrelationId:()=>buildCorrelationId,PR_SUBSCRIPTIONS_FILE:()=>PR_SUBSCRIPTIONS_FILE});import*as fs22 from"node:fs";import*as path48 from"node:path";function setOnSubscriptionCreated(callback){onSubscriptionCreated=callback}function storePath2(directory){return validateSwarmPath(directory,PR_SUBSCRIPTIONS_FILE)}function ensureSwarmDir3(directory){fs22.mkdirSync(path48.resolve(directory,".swarm","pr-monitor"),{recursive:!0})}function buildCorrelationId(sessionID,repoFullName,prNumber){return`${sessionID}::${repoFullName}::${prNumber}`}function readAllRecords(directory){let raw;try{raw=fs22.readFileSync(storePath2(directory),"utf-8")}catch(err){if(err.code==="ENOENT")return[];return log(`[pr-monitor] readAllRecords failed: ${err instanceof Error?err.message:String(err)}`),[]}let folded=new Map;for(let line of raw.split(`
649
649
  `)){let trimmed=line.trim();if(trimmed.length===0)continue;let parsedJson;try{parsedJson=JSON.parse(trimmed)}catch{continue}let result=RecordSchema2.safeParse(parsedJson);if(!result.success)continue;folded.set(result.data.correlationId,result.data)}return[...folded.values()]}function appendRecord2(directory,record2){let result=RecordSchema2.safeParse(record2);if(!result.success)throw Error(`Invalid subscription record: ${result.error.message}`);ensureSwarmDir3(directory),fs22.appendFileSync(storePath2(directory),`${JSON.stringify(record2)}
650
- `,"utf-8")}async function subscribe(directory,input){if(!directory||directory.trim()==="")throw Error("directory is required");if(!input.sessionID||input.sessionID.trim()==="")throw Error("sessionID is required and must be non-empty");if(!input.repoFullName||input.repoFullName.trim()==="")throw Error("repoFullName is required and must be non-empty");if(!input.prUrl||input.prUrl.trim()==="")throw Error("prUrl is required and must be non-empty");if(!input.prNumber||!Number.isInteger(input.prNumber)||input.prNumber<=0)throw Error("prNumber is required and must be a positive integer");let correlationId=buildCorrelationId(input.sessionID,input.repoFullName,input.prNumber),now=Date.now();return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let existing=readAllRecords(directory),match=existing.find((r)=>r.correlationId===correlationId&&r.status==="active");if(match)return onSubscriptionCreated?.(directory,match),match;if(input.maxSubscriptions!==void 0&&input.maxSubscriptions>0){let activeCount=existing.filter((r)=>r.status==="active").length;if(activeCount>=input.maxSubscriptions)throw Error(`PR subscription limit reached: ${activeCount}/${input.maxSubscriptions}`)}let record2={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return appendRecord2(directory,record2),onSubscriptionCreated?.(directory,record2),record2})}async function unsubscribe(directory,correlationId){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let match=readAllRecords(directory).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return null;let now=Date.now(),removed={...match,status:"removed",isWatching:!1,updatedAt:now};return appendRecord2(directory,removed),removed})}async function listActive(directory){return readAllRecords(directory).filter((r)=>r.status==="active")}async function lookupByPr(directory,repoFullName,prNumber){for(let record2 of readAllRecords(directory))if(record2.status==="active"&&record2.repoFullName===repoFullName&&record2.prNumber===prNumber)return record2;return null}async function updateSnapshot(directory,correlationId,updates){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let match=readAllRecords(directory).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return null;let updated={...match,...updates,correlationId,sessionID:match.sessionID,repoFullName:match.repoFullName,prNumber:match.prNumber,prUrl:match.prUrl,createdAt:match.createdAt,updatedAt:Date.now()};return appendRecord2(directory,updated),updated})}async function sweepStale(directory,ttlDays,mergedPrs){if(!ttlDays||ttlDays<=0)return 0;let ttlMs=ttlDays*86400000,now=Date.now();try{return await withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let swept=0;for(let record2 of readAllRecords(directory)){if(record2.status!=="active")continue;let prKey=`${record2.repoFullName}::${record2.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now-record2.updatedAt>ttlMs;if(isMerged){appendRecord2(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now}),swept+=1,log(`[pr-monitor] Swept subscription: merged/closed: ${prKey}`);continue}if(isStale&&!record2.hasUnaddressedEvents)appendRecord2(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now}),swept+=1,log(`[pr-monitor] Swept subscription: stale (TTL ${ttlDays}d): ${prKey}`)}return swept})}catch(err){return log(`[pr-monitor] sweepStale failed: ${err instanceof Error?err.message:String(err)}`),0}}var PR_SUBSCRIPTIONS_FILE="pr-monitor/subscriptions.jsonl",STORE_LOCK_AGENT2="pr-monitor",STORE_LOCK_TASK2="pr-subscriptions",onSubscriptionCreated=null,RecordSchema2;var init_pr_subscriptions=__esm(()=>{init_zod();init_lock();init_utils2();init_utils();RecordSchema2=exports_external.object({correlationId:exports_external.string().min(1),sessionID:exports_external.string().min(1),prNumber:exports_external.number().int().positive(),repoFullName:exports_external.string().regex(/^[^/]+\/[^/]+$/,"Must be owner/repo format"),prUrl:exports_external.string().min(1).regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/,"Must be a valid GitHub PR URL"),headRefOid:exports_external.string().optional(),lastCheckedAt:exports_external.number(),lastCommentId:exports_external.string().optional(),lastCheckRunSet:exports_external.string().optional(),mergeableState:exports_external.string().optional(),mergeGroupRunStatus:exports_external.string().optional(),mergeGroupRunConclusion:exports_external.string().optional(),mergeGroupRunHtmlUrl:exports_external.string().optional(),isWatching:exports_external.boolean(),hasUnaddressedEvents:exports_external.boolean(),status:exports_external.enum(["active","removed","expired"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),errorCount:exports_external.number().int().min(0),customPollIntervalSeconds:exports_external.number().int().positive().optional(),customFailureThreshold:exports_external.number().int().min(0).optional(),customCooldownSeconds:exports_external.number().int().min(0).optional()}).strict()});var exports_state={};__export(exports_state,{updateAgentEventTime:()=>updateAgentEventTime,sweepStaleSessions:()=>sweepStaleSessions,swarmState:()=>swarmState,startAgentSession:()=>startAgentSession,setSessionEnvironment:()=>setSessionEnvironment,setCriticalShownIds:()=>setCriticalShownIds,resetSwarmStatePreservingSingletons:()=>resetSwarmStatePreservingSingletons,resetSwarmState:()=>resetSwarmState,rehydrateSessionFromDisk:()=>rehydrateSessionFromDisk,rehydratePrSubscriptions:()=>rehydratePrSubscriptions,recordStageBCompletion:()=>recordStageBCompletion,recordPhaseAgentDispatch:()=>recordPhaseAgentDispatch,pruneOldWindows:()=>pruneOldWindows,maybeSweepStaleSessions:()=>maybeSweepStaleSessions,isCouncilGateActive:()=>isCouncilGateActive,hasBothStageBCompletions:()=>hasBothStageBCompletions,hasActiveTurboMode:()=>hasActiveTurboMode,hasActiveLeanTurbo:()=>hasActiveLeanTurbo,hasActiveFullAuto:()=>hasActiveFullAuto,hasActiveEpicMode:()=>hasActiveEpicMode,getTaskState:()=>getTaskState,getSessionEnvironment:()=>getSessionEnvironment,getRunContext:()=>getRunContext,getResolvedAutoProceed:()=>getResolvedAutoProceed,getAgentSession:()=>getAgentSession,getActiveWindow:()=>getActiveWindow,ensureSessionEnvironment:()=>ensureSessionEnvironment,ensureAgentSession:()=>ensureAgentSession,endAgentSession:()=>endAgentSession,defaultRunContext:()=>defaultRunContext,clearCriticalShownIds:()=>clearCriticalShownIds,canAdvanceTaskState:()=>canAdvanceTaskState,buildRehydrationCache:()=>buildRehydrationCache,beginInvocation:()=>beginInvocation,applyRehydrationCache:()=>applyRehydrationCache,advanceTaskStateAndPersist:()=>advanceTaskStateAndPersist,advanceTaskState:()=>advanceTaskState,addKnowledgeAckDedup:()=>addKnowledgeAckDedup,_resetCouncilDisagreementWarnings:()=>_resetCouncilDisagreementWarnings,_internals:()=>_internals26,MAX_TRACKED_KNOWLEDGE_ACKS:()=>MAX_TRACKED_KNOWLEDGE_ACKS,MAX_TRACKED_CRITICAL_SHOWN:()=>MAX_TRACKED_CRITICAL_SHOWN,AgentRunContext:()=>AgentRunContext});import*as fs23 from"node:fs/promises";import*as path49 from"node:path";function getRunContext(runId){if(!runId)return defaultRunContext;return _runContexts.get(runId)??defaultRunContext}function resetSwarmState(){swarmState.activeToolCalls.clear(),swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.pendingEvents=0,swarmState.lastBudgetPct=0,swarmState.agentSessions.clear(),_lastIdleSweepAtMs=0,clearTrajectoryCache(),clearTrajectoryStepCounters(),swarmState.pendingRehydrations.clear(),swarmState.opencodeClient=null,swarmState.curatorInitAgentNames=[],swarmState.curatorPhaseAgentNames=[],swarmState.curatorPostmortemAgentNames=[],swarmState.curatorConsolidationAgentNames=[],swarmState.skillImproverAgentNames=[],swarmState.specWriterAgentNames=[],swarmState.currentCriticalShownIds.clear(),swarmState.knowledgeAckDedup.clear(),swarmState.generatedAgentNames=[],_rehydrationCache=null,swarmState.fullAutoEnabledInConfig=!1,swarmState.environmentProfiles.clear(),clearPendingCoderScope(),resetStandardWorktreeIsolationState(),resetRealtimeLearningNudgeState(),_councilDisagreementWarned.clear()}function resetSwarmStatePreservingSingletons(){let{opencodeClient:preservedOpencodeClient,fullAutoEnabledInConfig:preservedFullAutoEnabledInConfig,curatorInitAgentNames:preservedCuratorInitAgentNames,curatorPhaseAgentNames:preservedCuratorPhaseAgentNames,curatorPostmortemAgentNames:preservedCuratorPostmortemAgentNames,curatorConsolidationAgentNames:preservedCuratorConsolidationAgentNames,skillImproverAgentNames:preservedSkillImproverAgentNames,specWriterAgentNames:preservedSpecWriterAgentNames,generatedAgentNames:preservedGeneratedAgentNames}=swarmState;resetSwarmState(),swarmState.opencodeClient=preservedOpencodeClient,swarmState.fullAutoEnabledInConfig=preservedFullAutoEnabledInConfig,swarmState.curatorInitAgentNames=preservedCuratorInitAgentNames,swarmState.curatorPhaseAgentNames=preservedCuratorPhaseAgentNames,swarmState.curatorPostmortemAgentNames=preservedCuratorPostmortemAgentNames,swarmState.curatorConsolidationAgentNames=preservedCuratorConsolidationAgentNames,swarmState.skillImproverAgentNames=preservedSkillImproverAgentNames,swarmState.specWriterAgentNames=preservedSpecWriterAgentNames,swarmState.generatedAgentNames=preservedGeneratedAgentNames}function sweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now()){let staleIds=[];for(let[id,session]of swarmState.agentSessions)if(now-session.lastToolCallTime>staleDurationMs)staleIds.push(id);for(let id of staleIds)swarmState.agentSessions.delete(id),swarmState.delegationChains.delete(id);return staleIds}function maybeSweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now()){if(now-_lastIdleSweepAtMs<IDLE_SWEEP_COOLDOWN_MS)return[];return _lastIdleSweepAtMs=now,sweepStaleSessions(staleDurationMs,now)}function startAgentSession(sessionId,agentName,staleDurationMs=STALE_SESSION_TTL_MS,directory){let now=Date.now();sweepStaleSessions(staleDurationMs,now);let sessionState={agentName,lastToolCallTime:now,lastAgentEventTime:now,delegationActive:!1,activeInvocationId:0,lastInvocationIdByAgent:{},windows:{},lastCompactionHint:0,architectWriteCount:0,lastCoderDelegationTaskId:null,currentTaskId:null,gateLog:new Map,reviewerCallCount:new Map,lastGateFailure:null,partialGateWarningsIssuedForTask:new Set,selfFixAttempted:!1,selfCodingWarnedAtCount:0,catastrophicPhaseWarnings:new Set,lastPhaseCompleteTimestamp:0,lastPhaseCompletePhase:0,phaseAgentsDispatched:new Set,lastCompletedPhaseAgentsDispatched:new Set,qaSkipCount:0,qaSkipTaskIds:[],taskWorkflowStates:new Map,stageBCompletion:new Map,taskCouncilApproved:new Map,pendingCouncilRequirements:new Map,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:!1,modifiedFilesThisCoderTask:[],turboMode:!1,turboStrategy:void 0,leanTurboActive:!1,leanTurboCurrentPhase:void 0,maxConcurrencyOverride:void 0,epicModeActive:!1,qaGateSessionOverrides:{},fullAutoMode:!1,fullAutoInteractionCount:0,fullAutoDeadlockCount:0,fullAutoLastQuestionHash:null,model_fallback_index:0,modelFallbackExhausted:!1,coderRevisions:0,revisionLimitHit:!1,loopDetectionWindow:[],pendingAdvisoryMessages:[],sessionRehydratedAt:0,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prSubscriptions:new Map};if(swarmState.agentSessions.set(sessionId,sessionState),directory){try{recordSessionStart(directory,now)}catch{}queueMicrotask(()=>{maybeSuggestWorktreeLink(directory,sessionId)})}if(telemetry.sessionStarted(sessionId,agentName),swarmState.activeAgent.set(sessionId,agentName),_internals26.applyRehydrationCache(sessionState),directory){let rehydrationPromise;rehydrationPromise=_internals26.rehydrateSessionFromDisk(directory,sessionState).then(async()=>{try{sessionState.prSubscriptions=await rehydratePrSubscriptions(sessionId,directory)}catch(err){warn("[state] PR subscription rehydration failed, starting with empty subscriptions:",err instanceof Error?err.message:String(err))}}).catch((err)=>{warn("[state] Rehydration failed:",err instanceof Error?err.message:String(err))}).finally(()=>{swarmState.pendingRehydrations.delete(rehydrationPromise)}),swarmState.pendingRehydrations.add(rehydrationPromise)}}function endAgentSession(sessionId){swarmState.agentSessions.delete(sessionId),clearRealtimeLearningNudgeSession(sessionId)}function getAgentSession(sessionId){return swarmState.agentSessions.get(sessionId)}function ensureAgentSession(sessionId,agentName,directory){let now=Date.now(),session=swarmState.agentSessions.get(sessionId);if(session){if(agentName&&agentName!==session.agentName){let oldName=session.agentName;if(session.agentName=agentName,telemetry.agentActivated(sessionId,agentName,oldName),session.delegationActive=!1,session.lastAgentEventTime=now,!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={}}if(!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={};if(session.lastCompactionHint===void 0)session.lastCompactionHint=0;if(session.architectWriteCount===void 0)session.architectWriteCount=0;if(session.lastCoderDelegationTaskId===void 0)session.lastCoderDelegationTaskId=null;if(session.currentTaskId===void 0)session.currentTaskId=null;if(!session.gateLog)session.gateLog=new Map;if(!session.reviewerCallCount)session.reviewerCallCount=new Map;if(session.lastGateFailure===void 0)session.lastGateFailure=null;if(!session.partialGateWarningsIssuedForTask)session.partialGateWarningsIssuedForTask=new Set;if(session.selfFixAttempted===void 0)session.selfFixAttempted=!1;if(session.selfCodingWarnedAtCount===void 0)session.selfCodingWarnedAtCount=0;if(!session.catastrophicPhaseWarnings)session.catastrophicPhaseWarnings=new Set;if(session.lastPhaseCompleteTimestamp===void 0)session.lastPhaseCompleteTimestamp=0;if(session.lastPhaseCompletePhase===void 0)session.lastPhaseCompletePhase=0;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;if(!session.lastCompletedPhaseAgentsDispatched)session.lastCompletedPhaseAgentsDispatched=new Set;if(session.qaSkipCount===void 0)session.qaSkipCount=0;if(!session.qaSkipTaskIds)session.qaSkipTaskIds=[];if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.stageBCompletion)session.stageBCompletion=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;if(!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;if(session.lastGateOutcome===void 0)session.lastGateOutcome=null;if(session.declaredCoderScope===void 0)session.declaredCoderScope=null;if(session.lastScopeViolation===void 0)session.lastScopeViolation=null;if(session.modifiedFilesThisCoderTask===void 0)session.modifiedFilesThisCoderTask=[];if(session.scopeViolationDetected===void 0)session.scopeViolationDetected=!1;if(session.turboMode===void 0)session.turboMode=!1;if(session.turboStrategy===void 0)session.turboStrategy=void 0;if(session.leanTurboActive===void 0)session.leanTurboActive=!1;if(session.leanTurboCurrentPhase===void 0)session.leanTurboCurrentPhase=void 0;if(session.epicModeActive===void 0)session.epicModeActive=!1;if(session.qaGateSessionOverrides===void 0)session.qaGateSessionOverrides={};if(session.model_fallback_index===void 0)session.model_fallback_index=0;if(session.modelFallbackExhausted===void 0)session.modelFallbackExhausted=!1;if(session.loopDetectionWindow===void 0)session.loopDetectionWindow=[];if(session.pendingAdvisoryMessages===void 0)session.pendingAdvisoryMessages=[];if(session.coderRevisions===void 0)session.coderRevisions=0;if(session.revisionLimitHit===void 0)session.revisionLimitHit=!1;if(session.sessionRehydratedAt===void 0)session.sessionRehydratedAt=0;if(session.prmPatternCounts===void 0)session.prmPatternCounts=new Map;if(session.prmEscalationLevel===void 0)session.prmEscalationLevel=0;if(session.prmLastPatternDetected===void 0)session.prmLastPatternDetected=null;if(session.prmTrajectoryStep===void 0)session.prmTrajectoryStep=0;if(session.prmHardStopPending===void 0)session.prmHardStopPending=!1;if(!session.prSubscriptions)session.prSubscriptions=new Map;return session.lastToolCallTime=now,maybeSweepStaleSessions(),session}if(_internals26.startAgentSession(sessionId,agentName??"unknown",7200000,directory),session=swarmState.agentSessions.get(sessionId),!session)throw Error(`Failed to create guardrail session for ${sessionId}`);return session}function updateAgentEventTime(sessionId){let session=swarmState.agentSessions.get(sessionId);if(session)session.lastAgentEventTime=Date.now()}function beginInvocation(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)throw Error(`Cannot begin invocation: session ${sessionId} does not exist`);let stripped=stripKnownSwarmPrefix(agentName);if(stripped===ORCHESTRATOR_NAME)return null;let newId=(session.lastInvocationIdByAgent[stripped]||0)+1;session.lastInvocationIdByAgent[stripped]=newId,session.activeInvocationId=newId;let now=Date.now(),window2={id:newId,agentName:stripped,startedAtMs:now,toolCalls:0,consecutiveErrors:0,hardLimitHit:!1,lastSuccessTimeMs:now,recentToolCalls:[],warningIssued:!1,warningReason:"",transientRetryCount:0},key=`${stripped}:${newId}`;return session.windows[key]=window2,pruneOldWindows(sessionId,86400000,50),telemetry.delegationBegin(sessionId,stripped,session.currentTaskId??"unknown"),window2}function getActiveWindow(sessionId){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let key=`${stripKnownSwarmPrefix(session.agentName)}:${session.activeInvocationId}`;return session.windows[key]}function pruneOldWindows(sessionId,maxAgeMs=86400000,maxWindows=50){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let now=Date.now(),toKeep=Object.entries(session.windows).filter(([_,window2])=>now-window2.startedAtMs<maxAgeMs).sort((a,b)=>b[1].startedAtMs-a[1].startedAtMs).slice(0,maxWindows);session.windows=Object.fromEntries(toKeep)}function recordPhaseAgentDispatch(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)return;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;let normalizedName=stripKnownSwarmPrefix(agentName);session.phaseAgentsDispatched.add(normalizedName)}function isValidTaskId2(taskId){if(taskId===null||taskId===void 0)return!1;if(typeof taskId!=="string")return!1;return taskId.trim().length>0}function advanceTaskState(session,taskId,newState,options,councilConfig){if(!isValidTaskId2(taskId))return;if(!session||!(session.taskWorkflowStates instanceof Map))throw Error("INVALID_SESSION: session.taskWorkflowStates must be a Map instance");let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=STATE_ORDER.indexOf(current);if(STATE_ORDER.indexOf(newState)<=currentIndex)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} ${current} → ${newState}`);if(newState==="complete"&&current!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} cannot reach complete from ${current} — must pass through tests_run first (or have council APPROVE after pre_check)`)}if(session.taskWorkflowStates.set(taskId,newState),newState==="complete")session.stageBCompletion?.delete(taskId);if(options?.emitTelemetry!==!1)telemetry.taskStateChanged(options?.telemetrySessionId??session.agentName,taskId,newState,current)}function canAdvanceTaskState(session,taskId,newState,councilConfig){if(!isValidTaskId2(taskId))return!1;if(!session||!(session.taskWorkflowStates instanceof Map))return!1;let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=STATE_ORDER.indexOf(current);if(STATE_ORDER.indexOf(newState)<=currentIndex)return!1;if(newState==="complete"&&current!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)return!1}return!0}async function advanceTaskStateAndPersist(session,taskId,newState,directory,options,councilConfig){if(newState==="coder_delegated"){if(await isTaskSettled(directory,taskId)){warn(`[advanceTaskStateAndPersist] refusing to re-dispatch settled task ${taskId}; skipping in-memory advance + persist`);return}}if(advanceTaskState(session,taskId,newState,options,councilConfig),newState!=="coder_delegated"&&newState!=="complete")return;let planStatus=newState==="complete"?"completed":"in_progress";try{await updateTaskStatus(directory,taskId,planStatus,{force:!1})}catch(err){warn(`[advanceTaskStateAndPersist] persist ${taskId} → ${planStatus} failed (in-memory state still advanced): ${err instanceof Error?err.message:String(err)}`)}}function getTaskState(session,taskId){if(!isValidTaskId2(taskId))return"idle";if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;return session.taskWorkflowStates.get(taskId)??"idle"}function recordStageBCompletion(session,taskId,agent){if(!isValidTaskId2(taskId))return;if(!session.stageBCompletion)session.stageBCompletion=new Map;let existing=session.stageBCompletion.get(taskId);if(existing)existing.add(agent);else session.stageBCompletion.set(taskId,new Set([agent]))}function hasBothStageBCompletions(session,taskId){if(!isValidTaskId2(taskId))return!1;let completions=session.stageBCompletion?.get(taskId);if(!completions)return!1;return completions.has("reviewer")&&completions.has("test_engineer")}async function isCouncilGateActive(directory,council,sessionOverrides={}){let enabled=council?.enabled===!0,plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{plan=null}if(!plan)return!1;let planId=derivePlanId(plan),profile=null;try{profile=getProfile(directory,planId)}catch(err){let msg=err instanceof Error?err.message:String(err);if(!(msg.includes("SQLITE_CANTOPEN")||msg.includes("ENOENT")))warn(`[isCouncilGateActive] getProfile threw unexpectedly for plan ${planId}: ${msg}. Treating council as inactive.`);profile=null}if(!profile)return!1;let councilMode=getEffectiveGates(profile,sessionOverrides).council_mode===!0;if(enabled&&councilMode)return!0;if(enabled!==councilMode&&!_councilDisagreementWarned.has(planId))_councilDisagreementWarned.add(planId),warn(`[delegation-gate] Council mode mismatch for plan ${planId}: pluginConfig.council.enabled=${enabled}, QaGates.council_mode=${councilMode}. Falling back to Stage B (non-council) per-task advancement.`);return!1}function _resetCouncilDisagreementWarnings(){_councilDisagreementWarned.clear()}function planStatusToWorkflowState(status){switch(status){case"in_progress":return"coder_delegated";case"completed":return"complete";default:return"idle"}}function evidenceToWorkflowState(evidence){let gates=evidence.gates??{},requiredGates=evidence.required_gates??[];if(requiredGates.length>0){if(requiredGates.every((gate)=>gates[gate]!=null))return"complete"}if(gates.test_engineer!=null)return"tests_run";if(gates.reviewer!=null)return"reviewer_run";if(Object.keys(gates).length>0)return"coder_delegated";return"idle"}async function readPlanFromDisk(directory){try{let planPath=path49.join(directory,".swarm","plan.json"),content=await fs23.readFile(planPath,"utf-8"),parsed=JSON.parse(content);return PlanSchema.parse(parsed)}catch{return null}}async function readGateEvidenceFromDisk(directory){let evidenceMap=new Map;try{let evidenceDir=path49.join(directory,".swarm","evidence"),entries=await fs23.readdir(evidenceDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let taskId=entry.name.replace(/\.json$/,"");if(!/^\d+\.\d+(\.\d+)*$/.test(taskId))continue;try{let filePath=path49.join(evidenceDir,entry.name),content=await fs23.readFile(filePath,"utf-8"),parsed=JSON.parse(content);if(parsed&&typeof parsed.taskId==="string"&&Array.isArray(parsed.required_gates))evidenceMap.set(taskId,parsed)}catch{}}}catch{}return evidenceMap}async function buildRehydrationCache(directory){let planTaskStates=new Map,plan=await readPlanFromDisk(directory);if(plan)for(let phase of plan.phases??[])for(let task of phase.tasks??[])planTaskStates.set(task.id,planStatusToWorkflowState(task.status));let evidenceMap=await readGateEvidenceFromDisk(directory);_rehydrationCache={planTaskStates,evidenceMap}}function applyRehydrationCache(session){if(!_rehydrationCache)return;if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let{planTaskStates,evidenceMap}=_rehydrationCache;for(let[taskId,planState]of planTaskStates){let existingState=session.taskWorkflowStates.get(taskId),evidence=evidenceMap.get(taskId);if(evidence){let derivedState=evidenceToWorkflowState(evidence),existingIndex=existingState?STATE_ORDER.indexOf(existingState):-1;if(STATE_ORDER.indexOf(derivedState)>existingIndex)session.taskWorkflowStates.set(taskId,derivedState)}else{let existingIndex=existingState?STATE_ORDER.indexOf(existingState):-1;if(STATE_ORDER.indexOf(planState)>existingIndex)session.taskWorkflowStates.set(taskId,planState)}}let VALID_COUNCIL_VERDICTS=new Set(["APPROVE","REJECT","CONCERNS"]);for(let[taskId,evidence]of evidenceMap){if(session.taskCouncilApproved.has(taskId))continue;let council=evidence.gates?.council;if(!council)continue;let rawVerdict=council.verdict;if(!rawVerdict||typeof rawVerdict!=="string")continue;if(!VALID_COUNCIL_VERDICTS.has(rawVerdict))continue;let verdict=rawVerdict,roundNumber=council.roundNumber;if(typeof roundNumber!=="number"||!Number.isFinite(roundNumber))roundNumber=1;let rawQuorumSize=council.quorumSize,quorumSize=typeof rawQuorumSize==="number"&&Number.isFinite(rawQuorumSize)&&rawQuorumSize>=1?rawQuorumSize:1;session.taskCouncilApproved.set(taskId,{verdict,roundNumber,quorumSize})}}async function rehydrateSessionFromDisk(directory,session){await _internals26.buildRehydrationCache(directory),_internals26.applyRehydrationCache(session)}function hasActiveTurboMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.turboMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0)return!0;return!1}function hasActiveFullAuto(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.fullAutoMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.fullAutoMode===!0)return!0;return!1}function hasActiveLeanTurbo(sessionID){if(sessionID){let session=swarmState.agentSessions.get(sessionID);return session?.turboMode===!0&&session?.turboStrategy==="lean"&&session?.leanTurboActive===!0}for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0&&session.turboStrategy==="lean"&&session.leanTurboActive===!0)return!0;return!1}function hasActiveEpicMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.epicModeActive===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.epicModeActive===!0)return!0;return!1}function getResolvedAutoProceed(session,planAutoProceed){return session.autoProceedOverride??planAutoProceed??!1}function setSessionEnvironment(sessionId,profile){swarmState.environmentProfiles.set(sessionId,profile)}function getSessionEnvironment(sessionId){return swarmState.environmentProfiles.get(sessionId)}function ensureSessionEnvironment(sessionId){let existing=swarmState.environmentProfiles.get(sessionId);if(existing)return existing;let profile=detectEnvironmentProfile();return swarmState.environmentProfiles.set(sessionId,profile),Promise.resolve().then(() => (init_telemetry(),exports_telemetry)).then(({telemetry:telemetry2})=>{telemetry2.environmentDetected(sessionId,profile.hostOS,profile.shellFamily,profile.executionMode)}).catch(()=>{}),profile}function setCriticalShownIds(sessionID,value){let map2=swarmState.currentCriticalShownIds;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,value),map2.size>MAX_TRACKED_CRITICAL_SHOWN){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function clearCriticalShownIds(sessionID){return swarmState.currentCriticalShownIds.delete(sessionID)}function addKnowledgeAckDedup(key){let set2=swarmState.knowledgeAckDedup;if(set2.has(key))return;if(set2.add(key),set2.size>MAX_TRACKED_KNOWLEDGE_ACKS){let oldest=set2.values().next().value;if(oldest!==void 0)set2.delete(oldest)}}async function rehydratePrSubscriptions(sessionID,directory){let map2=new Map;try{let{listActive:listActive2}=await Promise.resolve().then(() => (init_pr_subscriptions(),exports_pr_subscriptions)),records=await listActive2(directory);for(let record2 of records){if(record2.sessionID!==sessionID)continue;let key=`${record2.repoFullName}::${record2.prNumber}`;map2.set(key,{prNumber:record2.prNumber,repoFullName:record2.repoFullName,prUrl:record2.prUrl,lastKnownStatus:record2.mergeableState??"unknown",lastPollTime:record2.lastCheckedAt,errorCount:record2.errorCount,isWatching:record2.isWatching})}}catch(err){warn(`[state] rehydratePrSubscriptions failed for session ${sessionID}: ${err instanceof Error?err.message:String(err)}`)}return map2}var _rehydrationCache=null,_councilDisagreementWarned,STATE_ORDER,_toolAggregates,defaultRunContext,_runContexts,swarmState,STALE_SESSION_TTL_MS=7200000,IDLE_SWEEP_COOLDOWN_MS=60000,_lastIdleSweepAtMs=0,MAX_TRACKED_CRITICAL_SHOWN=500,MAX_TRACKED_KNOWLEDGE_ACKS=5000,_internals26;var init_state2=__esm(()=>{init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_delegation_gate();init_realtime_learning_nudge();init_trajectory_step_state();init_manager();init_utils3();init_trajectory_store();init_session_start_store();init_worktree_link_suggestion();init_telemetry();init_logger();_councilDisagreementWarned=new Set,STATE_ORDER=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","complete"],_toolAggregates=new Map,defaultRunContext=new AgentRunContext("default",_toolAggregates),_runContexts=new Map;swarmState={activeToolCalls:defaultRunContext.activeToolCalls,toolAggregates:defaultRunContext.toolAggregates,activeAgent:defaultRunContext.activeAgent,delegationChains:defaultRunContext.delegationChains,pendingEvents:0,opencodeClient:null,curatorInitAgentNames:[],curatorPhaseAgentNames:[],curatorPostmortemAgentNames:[],curatorConsolidationAgentNames:[],skillImproverAgentNames:[],specWriterAgentNames:[],currentCriticalShownIds:new Map,knowledgeAckDedup:new Set,generatedAgentNames:[],lastBudgetPct:0,agentSessions:defaultRunContext.agentSessions,pendingRehydrations:new Set,fullAutoEnabledInConfig:!1,environmentProfiles:defaultRunContext.environmentProfiles};_internals26={swarmState,resetSwarmState,ensureAgentSession,startAgentSession,getAgentSession,beginInvocation,getActiveWindow,advanceTaskState,getTaskState,hasActiveFullAuto,hasActiveTurboMode,hasActiveLeanTurbo,hasActiveEpicMode,buildRehydrationCache,applyRehydrationCache,rehydrateSessionFromDisk,isCouncilGateActive,defaultRunContext}});async function handleAutoProceedCommand(_directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Auto-proceed requires an active session. Use /swarm auto-proceed from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Auto-proceed requires an active session to operate.";if(stripKnownSwarmPrefix(session.agentName)!=="architect")return`Error: Auto-proceed can only be toggled from the architect session. Currently active session is: ${session.agentName}`;let arg=args2[0]?.toLowerCase(),wasUndefinedBefore=session.autoProceedOverride===void 0,newAutoProceedOverride;if(arg==="on")newAutoProceedOverride=!0;else if(arg==="off")newAutoProceedOverride=!1;else if(arg===void 0)newAutoProceedOverride=!session.autoProceedOverride;else return'Error: Invalid argument for /swarm auto-proceed. Valid options: "on", "off", or omit the argument to toggle.';if(session.autoProceedOverride=newAutoProceedOverride,arg==="on"||arg==="off"||arg===void 0&&wasUndefinedBefore)session.autoProceedNudgeDone=!0;if(newAutoProceedOverride)return"Auto-proceed is now ON. Phase boundaries will advance automatically.";else return"Auto-proceed is now OFF. You will be asked before advancing to the next phase."}var init_auto_proceed=__esm(()=>{init_schema();init_state2()});import*as fs24 from"node:fs";import*as os13 from"node:os";import*as path50 from"node:path";function buildDelegationCostFields(input={}){let extracted=extractUsageAndCost(input.raw),usage=extracted.usage,model=extracted.model??input.model,reportedCost=extracted.cost_usd;if(reportedCost!==null)return{...usage,cost_usd:roundUsd(reportedCost),cost_source:"reported",model,gate:input.gate,retry_index:input.retry_index};let estimated=estimateCostUsd(usage,model,input.pricing);if(estimated!==null)return{...usage,cost_usd:roundUsd(estimated),cost_source:"estimated",model,gate:input.gate,retry_index:input.retry_index};return{...usage,cost_usd:null,cost_source:"unavailable",model,gate:input.gate,retry_index:input.retry_index}}function summarizeTelemetryCosts(directory){let summary=createEmptySummary();for(let event of readTelemetryEvents(directory)){if(event.event!=="delegation_end")continue;addDelegationEvent(summary,event)}return finalizeSummary(summary)}function readTelemetryEvents(directory){let swarmDir=path50.join(directory,".swarm"),files=[path50.join(swarmDir,"telemetry.jsonl.1"),path50.join(swarmDir,"telemetry.jsonl")],tmpDir=fs24.mkdtempSync(path50.join(os13.tmpdir(),"telemetry-snapshot-")),snapshotFiles=[];try{for(let file2 of files){if(!fs24.existsSync(file2))continue;let snap=path50.join(tmpDir,path50.basename(file2));try{fs24.copyFileSync(file2,snap),snapshotFiles.push(snap)}catch{}}}catch{}let events=[];for(let file2 of snapshotFiles){let content="";try{content=fs24.readFileSync(file2,"utf-8")}catch{continue}for(let line of content.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed)continue;try{let parsed=JSON.parse(trimmed);if(isRecord(parsed))events.push(parsed)}catch{}}}try{for(let f of snapshotFiles)try{fs24.unlinkSync(f)}catch{}fs24.rmdirSync(tmpDir)}catch{}return events}function estimateCostUsd(usage,model,pricing){if(!model)return null;let table={...BUNDLED_MODEL_PRICING,...pricing?.models??{}},entry=table[model]??table[model.toLowerCase()];if(!entry)return null;let cost=usage.tokens_input/1e6*entry.input_per_million+usage.tokens_output/1e6*entry.output_per_million+usage.tokens_reasoning/1e6*(entry.reasoning_per_million??entry.output_per_million)+usage.tokens_cache/1e6*(entry.cache_per_million??entry.input_per_million);return cost>0?cost:null}function extractUsageAndCost(raw){let candidates=collectCandidateRecords(raw),usage={...ZERO_USAGE},cost_usd=null,model;for(let candidate of candidates){model??=readModelIdentifier(candidate),cost_usd??=readNumber(candidate,["cost_usd","total_cost_usd","cost","totalCost"]);let directInput=readNumber(candidate,["tokens_input","input_tokens","input","prompt_tokens"]),directOutput=readNumber(candidate,["tokens_output","output_tokens","output","completion_tokens"]),directReasoning=readNumber(candidate,["tokens_reasoning","reasoning_tokens","reasoning"]),directCache=readNumber(candidate,["tokens_cache","cache_tokens","cache_read_input_tokens","cached_input_tokens","cache_write_input_tokens","cache"]),nestedCache=readCacheTokens(candidate);usage.tokens_input||=directInput??0,usage.tokens_output||=directOutput??0,usage.tokens_reasoning||=directReasoning??0,usage.tokens_cache||=directCache??nestedCache??0}return{usage,cost_usd,model}}function collectCandidateRecords(raw){let records=[],visit=(value,depth)=>{if(depth>3||!isRecord(value))return;records.push(value);for(let key of["usage","tokens","cache","cost","metadata","data","info","message","assistant","task","part","response","output"])visit(value[key],depth+1)};return visit(raw,0),records}function readNumber(record2,keys){for(let key of keys){let value=record2[key];if(typeof value==="number"&&Number.isFinite(value)&&value>=0)return value;if(typeof value==="string"&&value.trim()!==""){let parsed=Number(value);if(Number.isFinite(parsed)&&parsed>=0)return parsed}}return null}function readString(record2,keys){for(let key of keys){let value=record2[key];if(typeof value==="string"&&value.trim()!=="")return value.trim()}return}function readModelIdentifier(record2){let direct=readString(record2,["model","model_id"]);if(direct)return direct;let modelID=readString(record2,["modelID"]),providerID=readString(record2,["providerID"]);if(modelID&&providerID)return`${providerID}/${modelID}`;return modelID}function readCacheTokens(record2){let cacheRecord=isRecord(record2.cache)?record2.cache:record2,read=readNumber(cacheRecord,["read","cache_read_input_tokens"]),write=readNumber(cacheRecord,["write","cache_write_input_tokens","write_input_tokens"]);if(read===null&&write===null)return null;return(read??0)+(write??0)}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function createEmptySummary(){return{total_cost_usd:0,total_reported_usd:0,total_estimated_usd:0,total_input_tokens:0,total_output_tokens:0,total_reasoning_tokens:0,total_cache_tokens:0,delegations:0,unavailable_delegations:0,by_agent:[],by_task:[],by_gate:[],by_retry:[],by_source:{reported:{delegations:0,cost_usd:0},estimated:{delegations:0,cost_usd:0},unavailable:{delegations:0,cost_usd:0}}}}function addDelegationEvent(summary,event){let costSource=parseCostSource(event.cost_source),cost=readNumber(event,["cost_usd"])??0,usage={tokens_input:readNumber(event,["tokens_input"])??0,tokens_output:readNumber(event,["tokens_output"])??0,tokens_reasoning:readNumber(event,["tokens_reasoning"])??0,tokens_cache:readNumber(event,["tokens_cache"])??0};if(summary.delegations++,summary.total_cost_usd+=cost,summary.total_input_tokens+=usage.tokens_input,summary.total_output_tokens+=usage.tokens_output,summary.total_reasoning_tokens+=usage.tokens_reasoning,summary.total_cache_tokens+=usage.tokens_cache,summary.by_source[costSource].delegations++,summary.by_source[costSource].cost_usd+=cost,costSource==="reported")summary.total_reported_usd+=cost;if(costSource==="estimated")summary.total_estimated_usd+=cost;if(costSource==="unavailable")summary.unavailable_delegations++;addRow(summary.by_agent,String(event.agentName??event.agent??"unknown"),{cost,costSource,usage}),addRow(summary.by_task,String(event.taskId??event.task_id??"unknown"),{cost,costSource,usage}),addRow(summary.by_gate,String(event.gate??"unknown"),{cost,costSource,usage}),addRow(summary.by_retry,String(readNumber(event,["retry_index","retryIndex"])??0),{cost,costSource,usage})}function addRow(rows,name,input){let row=rows.find((candidate)=>candidate.name===name);if(!row)row={name,delegations:0,cost_usd:0,input_tokens:0,output_tokens:0,reasoning_tokens:0,cache_tokens:0,unavailable_delegations:0},rows.push(row);if(row.delegations++,row.cost_usd+=input.cost,row.input_tokens+=input.usage.tokens_input,row.output_tokens+=input.usage.tokens_output,row.reasoning_tokens+=input.usage.tokens_reasoning,row.cache_tokens+=input.usage.tokens_cache,input.costSource==="unavailable")row.unavailable_delegations++}function finalizeSummary(summary){summary.total_cost_usd=roundUsd(summary.total_cost_usd),summary.total_reported_usd=roundUsd(summary.total_reported_usd),summary.total_estimated_usd=roundUsd(summary.total_estimated_usd);for(let source of Object.values(summary.by_source))source.cost_usd=roundUsd(source.cost_usd);for(let rows of[summary.by_agent,summary.by_task,summary.by_gate,summary.by_retry]){for(let row of rows)row.cost_usd=roundUsd(row.cost_usd);rows.sort((a,b)=>b.cost_usd-a.cost_usd||b.delegations-a.delegations)}return summary}function parseCostSource(value){return value==="reported"||value==="estimated"||value==="unavailable"?value:"unavailable"}function roundUsd(value){return Math.round(value*1e6)/1e6}var ZERO_USAGE,BUNDLED_MODEL_PRICING;var init_cost_accounting=__esm(()=>{ZERO_USAGE={tokens_input:0,tokens_output:0,tokens_reasoning:0,tokens_cache:0},BUNDLED_MODEL_PRICING={}});async function handleBenchmarkCommand(directory,args2){let cumulative=args2.includes("--cumulative");if(args2.includes("--ci-gate"))cumulative=!0;let maxCostUsd=parseMaxCostUsd(args2),mode=cumulative?"cumulative":"in-memory",costSummary=cumulative?summarizeTelemetryCosts(directory):void 0,agentMap=new Map;for(let[,s]of swarmState.agentSessions){let e=agentMap.get(s.agentName)||{toolCalls:0,hardLimits:0,warnings:0},windows=Object.values(s.windows);e.toolCalls+=windows.reduce((sum,w)=>sum+w.toolCalls,0),e.hardLimits+=windows.filter((w)=>w.hardLimitHit).length,e.warnings+=windows.filter((w)=>w.warningIssued).length,agentMap.set(s.agentName,e)}let agentHealth=Array.from(agentMap.entries()).map(([a,v])=>({agent:a,...v})),toolPerf=[];for(let[,a]of swarmState.toolAggregates){let successRate=a.count?a.successCount/a.count*100:0;toolPerf.push({tool:a.tool,calls:a.count,successRate:Math.round(successRate*10)/10,avg:a.count?Math.round(a.totalDuration/a.count):0})}toolPerf.sort((a,b)=>b.calls-a.calls);let delegationCount=0;for(let c of swarmState.delegationChains.values())delegationCount+=c.length;let quality,qualityMetrics;if(cumulative){let reviewPasses=0,reviewFails=0,testPasses=0,testFails=0,additions=0,deletions=0,totalComplexityDelta=0,totalPublicApiDelta=0,totalDuplicationRatio=0,totalTestToCodeRatio=0,qualityEvidenceCount=0;for(let tid of await listEvidenceTaskIds(directory)){let result;try{result=await loadEvidence(directory,tid)}catch(_evidenceErr){warn("benchmark: skipping corrupt or unreadable evidence for task",tid);continue}if(result.status!=="found")continue;for(let e of result.bundle.entries){if(!isValidEvidenceType(e.type)){warn(`Unknown evidence type '${e.type}' in task ${tid}, skipping`);continue}if(e.type==="review"){if(e.verdict==="approved")reviewPasses++;else if(e.verdict==="rejected")reviewFails++}else if(e.type==="test")testPasses+=e.tests_passed,testFails+=e.tests_failed;else if(e.type==="diff")additions+=e.additions,deletions+=e.deletions;else if(e.type==="quality_budget"){let qe=e;totalComplexityDelta+=qe.metrics.complexity_delta,totalPublicApiDelta+=qe.metrics.public_api_delta,totalDuplicationRatio+=qe.metrics.duplication_ratio*100,totalTestToCodeRatio+=qe.metrics.test_to_code_ratio*100,qualityEvidenceCount++}}}let totalReviews=reviewPasses+reviewFails,totalTests=testPasses+testFails;if(quality={reviewPassRate:totalReviews?Math.round(reviewPasses/totalReviews*1000)/10:null,testPassRate:totalTests?Math.round(testPasses/totalTests*1000)/10:null,totalReviews,testsPassed:testPasses,testsFailed:testFails,additions,deletions},qualityEvidenceCount>0)qualityMetrics={complexityDelta:Math.round(totalComplexityDelta/qualityEvidenceCount*10)/10,publicApiDelta:Math.round(totalPublicApiDelta/qualityEvidenceCount*10)/10,duplicationRatio:Math.round(totalDuplicationRatio/qualityEvidenceCount*10)/10,testToCodeRatio:Math.round(totalTestToCodeRatio/qualityEvidenceCount*10)/10,thresholds:{maxComplexityDelta:CI.max_complexity_delta,maxPublicApiDelta:CI.max_public_api_delta,maxDuplicationRatio:CI.max_duplication_ratio,minTestToCodeRatio:CI.min_test_to_code_ratio},hasEvidence:!0};else qualityMetrics={complexityDelta:0,publicApiDelta:0,duplicationRatio:0,testToCodeRatio:0,thresholds:{maxComplexityDelta:CI.max_complexity_delta,maxPublicApiDelta:CI.max_public_api_delta,maxDuplicationRatio:CI.max_duplication_ratio,minTestToCodeRatio:CI.min_test_to_code_ratio},hasEvidence:!1}}let ciGate;if(args2.includes("--ci-gate")){let totalCalls=0,totalFailures=0;for(let[,a]of swarmState.toolAggregates)totalCalls+=a.count,totalFailures+=a.failureCount;let agentErrorRate=totalCalls?totalFailures/totalCalls*100:0,maxHardLimits=0;for(let v of agentMap.values())if(v.hardLimits>maxHardLimits)maxHardLimits=v.hardLimits;let hasQualityEvidence=qualityMetrics?.hasEvidence??!1,complexityDelta=qualityMetrics?.complexityDelta??0,publicApiDelta=qualityMetrics?.publicApiDelta??0,duplicationRatio=qualityMetrics?.duplicationRatio??0,testToCodeRatio=qualityMetrics?.testToCodeRatio??0,checks3=[{name:"Review pass rate",value:quality?.reviewPassRate??0,threshold:CI.review_pass_rate,operator:">=",passed:(quality?.reviewPassRate??0)>=CI.review_pass_rate},{name:"Test pass rate",value:quality?.testPassRate??0,threshold:CI.test_pass_rate,operator:">=",passed:(quality?.testPassRate??0)>=CI.test_pass_rate},{name:"Agent error rate",value:Math.round(agentErrorRate*10)/10,threshold:CI.max_agent_error_rate,operator:"<=",passed:agentErrorRate<=CI.max_agent_error_rate},{name:"Hard limit hits",value:maxHardLimits,threshold:CI.max_hard_limit_hits,operator:"<=",passed:maxHardLimits<=CI.max_hard_limit_hits},{name:"Complexity Delta",value:complexityDelta,threshold:CI.max_complexity_delta,operator:"<=",passed:!hasQualityEvidence||complexityDelta<=CI.max_complexity_delta},{name:"Public API Delta",value:publicApiDelta,threshold:CI.max_public_api_delta,operator:"<=",passed:!hasQualityEvidence||publicApiDelta<=CI.max_public_api_delta},{name:"Duplication Ratio",value:duplicationRatio,threshold:CI.max_duplication_ratio,operator:"<=",passed:!hasQualityEvidence||duplicationRatio<=CI.max_duplication_ratio},{name:"Test-to-Code Ratio",value:testToCodeRatio,threshold:CI.min_test_to_code_ratio,operator:">=",passed:!hasQualityEvidence||testToCodeRatio>=CI.min_test_to_code_ratio}];if(maxCostUsd!==null)checks3.push({name:"Total cost",value:costSummary?.total_cost_usd??0,threshold:maxCostUsd,operator:"<=",passed:(costSummary?.total_cost_usd??0)<=maxCostUsd});ciGate={passed:checks3.every((c)=>c.passed),checks:checks3}}let lines=[`## Swarm Benchmark (mode: ${mode})`,"","### Agent Health"];if(!agentHealth.length)lines.push("No agent sessions recorded");else for(let{agent,toolCalls,hardLimits,warnings}of agentHealth){let parts=[`${toolCalls} tool calls`];if(warnings>0)parts.push(`${warnings} warning${warnings>1?"s":""}`);parts.push(hardLimits?`${hardLimits} hard limit hit${hardLimits>1?"s":""}`:"0 hard limits"),lines.push(`- ${hardLimits?"⚠️":"✅"} **${agent}**: ${parts.join(", ")}`)}if(lines.push("","### Tool Performance"),!toolPerf.length)lines.push("No tool data recorded");else{lines.push("| Tool | Calls | Success Rate | Avg Duration |","|------|-------|-------------|-------------|");for(let{tool,calls,successRate,avg}of toolPerf)lines.push(`| ${tool} | ${calls} | ${successRate}% | ${avg}ms |`)}if(lines.push("","### Delegations",delegationCount?`Total: ${delegationCount} delegations`:"No delegations recorded",""),quality){if(lines.push("### Quality Signals"),!quality.totalReviews&&!quality.testsPassed&&!quality.additions)lines.push("No evidence data found");else{if(quality.reviewPassRate!==null)lines.push(`- Review pass rate: ${quality.reviewPassRate}% (${quality.totalReviews}) ${quality.reviewPassRate>=70?"✅":"❌"}`);else lines.push("- Review pass rate: N/A (no reviews)");if(quality.testPassRate!==null)lines.push(`- Test pass rate: ${quality.testPassRate}% (${quality.testsPassed}/${quality.testsPassed+quality.testsFailed}) ${quality.testPassRate>=80?"✅":"❌"}`);else lines.push("- Test pass rate: N/A (no tests)");lines.push(`- Code churn: +${quality.additions} / -${quality.deletions} lines`)}lines.push("")}if(qualityMetrics?.hasEvidence)lines.push("### Quality Metrics"),lines.push(`- Complexity Delta: ${qualityMetrics.complexityDelta} (max: ${qualityMetrics.thresholds.maxComplexityDelta}) ${qualityMetrics.complexityDelta<=qualityMetrics.thresholds.maxComplexityDelta?"✅":"❌"}`),lines.push(`- Public API Delta: ${qualityMetrics.publicApiDelta} (max: ${qualityMetrics.thresholds.maxPublicApiDelta}) ${qualityMetrics.publicApiDelta<=qualityMetrics.thresholds.maxPublicApiDelta?"✅":"❌"}`),lines.push(`- Duplication Ratio: ${qualityMetrics.duplicationRatio}% (max: ${qualityMetrics.thresholds.maxDuplicationRatio}%) ${qualityMetrics.duplicationRatio<=qualityMetrics.thresholds.maxDuplicationRatio?"✅":"❌"}`),lines.push(`- Test-to-Code Ratio: ${qualityMetrics.testToCodeRatio}% (min: ${qualityMetrics.thresholds.minTestToCodeRatio}%) ${qualityMetrics.testToCodeRatio>=qualityMetrics.thresholds.minTestToCodeRatio?"✅":"❌"}`),lines.push("");if(costSummary)lines.push("### Cost Signals"),lines.push(`- Total tracked cost: $${costSummary.total_cost_usd.toFixed(6)} (${costSummary.delegations} delegations)`,`- Reported: $${costSummary.total_reported_usd.toFixed(6)}; estimated: $${costSummary.total_estimated_usd.toFixed(6)}; unavailable: ${costSummary.unavailable_delegations}`),lines.push("");if(ciGate){lines.push("### CI Gate",ciGate.passed?"✅ PASSED":"❌ FAILED");for(let c of ciGate.checks){let valueStr;if(c.name==="Complexity Delta"||c.name==="Public API Delta")valueStr=`${c.value}`;else if(c.name==="Total cost")valueStr=`$${c.value.toFixed(6)}`;else valueStr=`${c.value}%`;let thresholdStr=c.name==="Complexity Delta"||c.name==="Public API Delta"?`${c.threshold}`:c.name==="Total cost"?`$${c.threshold.toFixed(6)}`:`${c.threshold}%`;lines.push(`- ${c.name}: ${valueStr} ${c.operator} ${thresholdStr} ${c.passed?"✅":"❌"}`)}lines.push("")}let json2={mode,timestamp:new Date().toISOString(),agent_health:agentHealth.map((a)=>({agent:a.agent,tool_calls:a.toolCalls,hard_limit_hits:a.hardLimits,warnings:a.warnings})),tool_performance:toolPerf.map((t)=>({tool:t.tool,calls:t.calls,success_rate:t.successRate,avg_duration_ms:t.avg})),delegations:delegationCount};if(quality)json2.quality={review_pass_rate:quality.reviewPassRate,test_pass_rate:quality.testPassRate,total_reviews:quality.totalReviews,total_tests_passed:quality.testsPassed,total_tests_failed:quality.testsFailed,additions:quality.additions,deletions:quality.deletions};if(qualityMetrics)json2.quality_metrics={complexity_delta:qualityMetrics.complexityDelta,public_api_delta:qualityMetrics.publicApiDelta,duplication_ratio:qualityMetrics.duplicationRatio,test_to_code_ratio:qualityMetrics.testToCodeRatio,thresholds:qualityMetrics.thresholds,has_evidence:qualityMetrics.hasEvidence};if(costSummary)json2.costs={total_cost_usd:costSummary.total_cost_usd,total_reported_usd:costSummary.total_reported_usd,total_estimated_usd:costSummary.total_estimated_usd,total_input_tokens:costSummary.total_input_tokens,total_output_tokens:costSummary.total_output_tokens,total_reasoning_tokens:costSummary.total_reasoning_tokens,total_cache_tokens:costSummary.total_cache_tokens,delegations:costSummary.delegations,unavailable_delegations:costSummary.unavailable_delegations};if(ciGate)json2.ci_gate={passed:ciGate.passed,checks:ciGate.checks.map((c)=>({name:c.name,value:c.value,threshold:c.threshold,operator:c.operator,passed:c.passed}))};return lines.push("[BENCHMARK_JSON]",JSON.stringify(json2,null,2),"[/BENCHMARK_JSON]"),lines.join(`
650
+ `,"utf-8")}async function subscribe(directory,input){if(!directory||directory.trim()==="")throw Error("directory is required");if(!input.sessionID||input.sessionID.trim()==="")throw Error("sessionID is required and must be non-empty");if(!input.repoFullName||input.repoFullName.trim()==="")throw Error("repoFullName is required and must be non-empty");if(!input.prUrl||input.prUrl.trim()==="")throw Error("prUrl is required and must be non-empty");if(!input.prNumber||!Number.isInteger(input.prNumber)||input.prNumber<=0)throw Error("prNumber is required and must be a positive integer");let correlationId=buildCorrelationId(input.sessionID,input.repoFullName,input.prNumber),now=Date.now();return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let existing=readAllRecords(directory),match=existing.find((r)=>r.correlationId===correlationId&&r.status==="active");if(match)return onSubscriptionCreated?.(directory,match),match;if(input.maxSubscriptions!==void 0&&input.maxSubscriptions>0){let activeCount=existing.filter((r)=>r.status==="active").length;if(activeCount>=input.maxSubscriptions)throw Error(`PR subscription limit reached: ${activeCount}/${input.maxSubscriptions}`)}let record2={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return appendRecord2(directory,record2),onSubscriptionCreated?.(directory,record2),record2})}async function unsubscribe(directory,correlationId){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let match=readAllRecords(directory).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return null;let now=Date.now(),removed={...match,status:"removed",isWatching:!1,updatedAt:now};return appendRecord2(directory,removed),removed})}async function listActive(directory){return readAllRecords(directory).filter((r)=>r.status==="active")}async function lookupByPr(directory,repoFullName,prNumber){for(let record2 of readAllRecords(directory))if(record2.status==="active"&&record2.repoFullName===repoFullName&&record2.prNumber===prNumber)return record2;return null}async function updateSnapshot(directory,correlationId,updates){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let match=readAllRecords(directory).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return null;let updated={...match,...updates,correlationId,sessionID:match.sessionID,repoFullName:match.repoFullName,prNumber:match.prNumber,prUrl:match.prUrl,createdAt:match.createdAt,updatedAt:Date.now()};return appendRecord2(directory,updated),updated})}async function sweepStale(directory,ttlDays,mergedPrs){if(!ttlDays||ttlDays<=0)return 0;let ttlMs=ttlDays*86400000,now=Date.now();try{return await withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let swept=0;for(let record2 of readAllRecords(directory)){if(record2.status!=="active")continue;let prKey=`${record2.repoFullName}::${record2.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now-record2.updatedAt>ttlMs;if(isMerged){appendRecord2(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now}),swept+=1,log(`[pr-monitor] Swept subscription: merged/closed: ${prKey}`);continue}if(isStale&&!record2.hasUnaddressedEvents)appendRecord2(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now}),swept+=1,log(`[pr-monitor] Swept subscription: stale (TTL ${ttlDays}d): ${prKey}`)}return swept})}catch(err){return log(`[pr-monitor] sweepStale failed: ${err instanceof Error?err.message:String(err)}`),0}}var PR_SUBSCRIPTIONS_FILE="pr-monitor/subscriptions.jsonl",STORE_LOCK_AGENT2="pr-monitor",STORE_LOCK_TASK2="pr-subscriptions",onSubscriptionCreated=null,RecordSchema2;var init_pr_subscriptions=__esm(()=>{init_zod();init_lock();init_utils2();init_utils();RecordSchema2=exports_external.object({correlationId:exports_external.string().min(1),sessionID:exports_external.string().min(1),prNumber:exports_external.number().int().positive(),repoFullName:exports_external.string().regex(/^[^/]+\/[^/]+$/,"Must be owner/repo format"),prUrl:exports_external.string().min(1).regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/,"Must be a valid GitHub PR URL"),headRefOid:exports_external.string().optional(),lastCheckedAt:exports_external.number(),lastCommentId:exports_external.string().optional(),lastCheckRunSet:exports_external.string().optional(),mergeableState:exports_external.string().optional(),mergeGroupRunStatus:exports_external.string().optional(),mergeGroupRunConclusion:exports_external.string().optional(),mergeGroupRunHtmlUrl:exports_external.string().optional(),isWatching:exports_external.boolean(),hasUnaddressedEvents:exports_external.boolean(),status:exports_external.enum(["active","removed","expired"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),errorCount:exports_external.number().int().min(0),customPollIntervalSeconds:exports_external.number().int().positive().optional(),customFailureThreshold:exports_external.number().int().min(0).optional(),customCooldownSeconds:exports_external.number().int().min(0).optional()}).strict()});var exports_state={};__export(exports_state,{updateAgentEventTime:()=>updateAgentEventTime,sweepStaleSessions:()=>sweepStaleSessions,swarmState:()=>swarmState,startAgentSession:()=>startAgentSession,setSessionEnvironment:()=>setSessionEnvironment,setCriticalShownIds:()=>setCriticalShownIds,resetSwarmStatePreservingSingletons:()=>resetSwarmStatePreservingSingletons,resetSwarmState:()=>resetSwarmState,rehydrateSessionFromDisk:()=>rehydrateSessionFromDisk,rehydratePrSubscriptions:()=>rehydratePrSubscriptions,recordStageBCompletion:()=>recordStageBCompletion,recordPhaseAgentDispatch:()=>recordPhaseAgentDispatch,pruneOldWindows:()=>pruneOldWindows,maybeSweepStaleSessions:()=>maybeSweepStaleSessions,isCouncilGateActive:()=>isCouncilGateActive,hasBothStageBCompletions:()=>hasBothStageBCompletions,hasActiveTurboMode:()=>hasActiveTurboMode,hasActiveLeanTurbo:()=>hasActiveLeanTurbo,hasActiveFullAuto:()=>hasActiveFullAuto,hasActiveEpicMode:()=>hasActiveEpicMode,getTaskState:()=>getTaskState,getSessionEnvironment:()=>getSessionEnvironment,getRunContext:()=>getRunContext,getResolvedAutoProceed:()=>getResolvedAutoProceed,getAgentSession:()=>getAgentSession,getActiveWindow:()=>getActiveWindow,getActiveFullAutoSessionID:()=>getActiveFullAutoSessionID,ensureSessionEnvironment:()=>ensureSessionEnvironment,ensureAgentSession:()=>ensureAgentSession,endAgentSession:()=>endAgentSession,defaultRunContext:()=>defaultRunContext,clearCriticalShownIds:()=>clearCriticalShownIds,canAdvanceTaskState:()=>canAdvanceTaskState,buildRehydrationCache:()=>buildRehydrationCache,beginInvocation:()=>beginInvocation,applyRehydrationCache:()=>applyRehydrationCache,advanceTaskStateAndPersist:()=>advanceTaskStateAndPersist,advanceTaskState:()=>advanceTaskState,addKnowledgeAckDedup:()=>addKnowledgeAckDedup,_resetCouncilDisagreementWarnings:()=>_resetCouncilDisagreementWarnings,_internals:()=>_internals26,MAX_TRACKED_KNOWLEDGE_ACKS:()=>MAX_TRACKED_KNOWLEDGE_ACKS,MAX_TRACKED_CRITICAL_SHOWN:()=>MAX_TRACKED_CRITICAL_SHOWN,AgentRunContext:()=>AgentRunContext});import*as fs23 from"node:fs/promises";import*as path49 from"node:path";function getRunContext(runId){if(!runId)return defaultRunContext;return _runContexts.get(runId)??defaultRunContext}function resetSwarmState(){swarmState.activeToolCalls.clear(),swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.pendingEvents=0,swarmState.lastBudgetPct=0,swarmState.agentSessions.clear(),_lastIdleSweepAtMs=0,clearTrajectoryCache(),clearTrajectoryStepCounters(),swarmState.pendingRehydrations.clear(),swarmState.opencodeClient=null,swarmState.curatorInitAgentNames=[],swarmState.curatorPhaseAgentNames=[],swarmState.curatorPostmortemAgentNames=[],swarmState.curatorConsolidationAgentNames=[],swarmState.skillImproverAgentNames=[],swarmState.specWriterAgentNames=[],swarmState.currentCriticalShownIds.clear(),swarmState.knowledgeAckDedup.clear(),swarmState.generatedAgentNames=[],_rehydrationCache=null,swarmState.fullAutoEnabledInConfig=!1,swarmState.environmentProfiles.clear(),clearPendingCoderScope(),resetStandardWorktreeIsolationState(),resetRealtimeLearningNudgeState(),_councilDisagreementWarned.clear()}function resetSwarmStatePreservingSingletons(){let{opencodeClient:preservedOpencodeClient,fullAutoEnabledInConfig:preservedFullAutoEnabledInConfig,curatorInitAgentNames:preservedCuratorInitAgentNames,curatorPhaseAgentNames:preservedCuratorPhaseAgentNames,curatorPostmortemAgentNames:preservedCuratorPostmortemAgentNames,curatorConsolidationAgentNames:preservedCuratorConsolidationAgentNames,skillImproverAgentNames:preservedSkillImproverAgentNames,specWriterAgentNames:preservedSpecWriterAgentNames,generatedAgentNames:preservedGeneratedAgentNames}=swarmState;resetSwarmState(),swarmState.opencodeClient=preservedOpencodeClient,swarmState.fullAutoEnabledInConfig=preservedFullAutoEnabledInConfig,swarmState.curatorInitAgentNames=preservedCuratorInitAgentNames,swarmState.curatorPhaseAgentNames=preservedCuratorPhaseAgentNames,swarmState.curatorPostmortemAgentNames=preservedCuratorPostmortemAgentNames,swarmState.curatorConsolidationAgentNames=preservedCuratorConsolidationAgentNames,swarmState.skillImproverAgentNames=preservedSkillImproverAgentNames,swarmState.specWriterAgentNames=preservedSpecWriterAgentNames,swarmState.generatedAgentNames=preservedGeneratedAgentNames}function sweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now()){let staleIds=[];for(let[id,session]of swarmState.agentSessions)if(now-session.lastToolCallTime>staleDurationMs)staleIds.push(id);for(let id of staleIds)swarmState.agentSessions.delete(id),swarmState.delegationChains.delete(id);return staleIds}function maybeSweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now()){if(now-_lastIdleSweepAtMs<IDLE_SWEEP_COOLDOWN_MS)return[];return _lastIdleSweepAtMs=now,sweepStaleSessions(staleDurationMs,now)}function startAgentSession(sessionId,agentName,staleDurationMs=STALE_SESSION_TTL_MS,directory){let now=Date.now();sweepStaleSessions(staleDurationMs,now);let sessionState={agentName,lastToolCallTime:now,lastAgentEventTime:now,delegationActive:!1,activeInvocationId:0,lastInvocationIdByAgent:{},windows:{},lastCompactionHint:0,architectWriteCount:0,lastCoderDelegationTaskId:null,currentTaskId:null,gateLog:new Map,reviewerCallCount:new Map,lastGateFailure:null,partialGateWarningsIssuedForTask:new Set,selfFixAttempted:!1,selfCodingWarnedAtCount:0,catastrophicPhaseWarnings:new Set,lastPhaseCompleteTimestamp:0,lastPhaseCompletePhase:0,phaseAgentsDispatched:new Set,lastCompletedPhaseAgentsDispatched:new Set,qaSkipCount:0,qaSkipTaskIds:[],taskWorkflowStates:new Map,stageBCompletion:new Map,taskCouncilApproved:new Map,pendingCouncilRequirements:new Map,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:!1,modifiedFilesThisCoderTask:[],turboMode:!1,turboStrategy:void 0,leanTurboActive:!1,leanTurboCurrentPhase:void 0,maxConcurrencyOverride:void 0,epicModeActive:!1,qaGateSessionOverrides:{},fullAutoMode:!1,fullAutoInteractionCount:0,fullAutoDeadlockCount:0,fullAutoLastQuestionHash:null,model_fallback_index:0,modelFallbackExhausted:!1,coderRevisions:0,revisionLimitHit:!1,loopDetectionWindow:[],pendingAdvisoryMessages:[],sessionRehydratedAt:0,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prSubscriptions:new Map};if(swarmState.agentSessions.set(sessionId,sessionState),directory){try{recordSessionStart(directory,now)}catch{}queueMicrotask(()=>{maybeSuggestWorktreeLink(directory,sessionId)})}if(telemetry.sessionStarted(sessionId,agentName),swarmState.activeAgent.set(sessionId,agentName),_internals26.applyRehydrationCache(sessionState),directory){let rehydrationPromise;rehydrationPromise=_internals26.rehydrateSessionFromDisk(directory,sessionState).then(async()=>{try{sessionState.prSubscriptions=await rehydratePrSubscriptions(sessionId,directory)}catch(err){warn("[state] PR subscription rehydration failed, starting with empty subscriptions:",err instanceof Error?err.message:String(err))}}).catch((err)=>{warn("[state] Rehydration failed:",err instanceof Error?err.message:String(err))}).finally(()=>{swarmState.pendingRehydrations.delete(rehydrationPromise)}),swarmState.pendingRehydrations.add(rehydrationPromise)}}function endAgentSession(sessionId){swarmState.agentSessions.delete(sessionId),clearRealtimeLearningNudgeSession(sessionId)}function getAgentSession(sessionId){return swarmState.agentSessions.get(sessionId)}function ensureAgentSession(sessionId,agentName,directory){let now=Date.now(),session=swarmState.agentSessions.get(sessionId);if(session){if(agentName&&agentName!==session.agentName){let oldName=session.agentName;if(session.agentName=agentName,telemetry.agentActivated(sessionId,agentName,oldName),session.delegationActive=!1,session.lastAgentEventTime=now,!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={}}if(!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={};if(session.lastCompactionHint===void 0)session.lastCompactionHint=0;if(session.architectWriteCount===void 0)session.architectWriteCount=0;if(session.lastCoderDelegationTaskId===void 0)session.lastCoderDelegationTaskId=null;if(session.currentTaskId===void 0)session.currentTaskId=null;if(!session.gateLog)session.gateLog=new Map;if(!session.reviewerCallCount)session.reviewerCallCount=new Map;if(session.lastGateFailure===void 0)session.lastGateFailure=null;if(!session.partialGateWarningsIssuedForTask)session.partialGateWarningsIssuedForTask=new Set;if(session.selfFixAttempted===void 0)session.selfFixAttempted=!1;if(session.selfCodingWarnedAtCount===void 0)session.selfCodingWarnedAtCount=0;if(!session.catastrophicPhaseWarnings)session.catastrophicPhaseWarnings=new Set;if(session.lastPhaseCompleteTimestamp===void 0)session.lastPhaseCompleteTimestamp=0;if(session.lastPhaseCompletePhase===void 0)session.lastPhaseCompletePhase=0;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;if(!session.lastCompletedPhaseAgentsDispatched)session.lastCompletedPhaseAgentsDispatched=new Set;if(session.qaSkipCount===void 0)session.qaSkipCount=0;if(!session.qaSkipTaskIds)session.qaSkipTaskIds=[];if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.stageBCompletion)session.stageBCompletion=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;if(!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;if(session.lastGateOutcome===void 0)session.lastGateOutcome=null;if(session.declaredCoderScope===void 0)session.declaredCoderScope=null;if(session.lastScopeViolation===void 0)session.lastScopeViolation=null;if(session.modifiedFilesThisCoderTask===void 0)session.modifiedFilesThisCoderTask=[];if(session.scopeViolationDetected===void 0)session.scopeViolationDetected=!1;if(session.turboMode===void 0)session.turboMode=!1;if(session.turboStrategy===void 0)session.turboStrategy=void 0;if(session.leanTurboActive===void 0)session.leanTurboActive=!1;if(session.leanTurboCurrentPhase===void 0)session.leanTurboCurrentPhase=void 0;if(session.epicModeActive===void 0)session.epicModeActive=!1;if(session.qaGateSessionOverrides===void 0)session.qaGateSessionOverrides={};if(session.model_fallback_index===void 0)session.model_fallback_index=0;if(session.modelFallbackExhausted===void 0)session.modelFallbackExhausted=!1;if(session.loopDetectionWindow===void 0)session.loopDetectionWindow=[];if(session.pendingAdvisoryMessages===void 0)session.pendingAdvisoryMessages=[];if(session.coderRevisions===void 0)session.coderRevisions=0;if(session.revisionLimitHit===void 0)session.revisionLimitHit=!1;if(session.sessionRehydratedAt===void 0)session.sessionRehydratedAt=0;if(session.prmPatternCounts===void 0)session.prmPatternCounts=new Map;if(session.prmEscalationLevel===void 0)session.prmEscalationLevel=0;if(session.prmLastPatternDetected===void 0)session.prmLastPatternDetected=null;if(session.prmTrajectoryStep===void 0)session.prmTrajectoryStep=0;if(session.prmHardStopPending===void 0)session.prmHardStopPending=!1;if(!session.prSubscriptions)session.prSubscriptions=new Map;return session.lastToolCallTime=now,maybeSweepStaleSessions(),session}if(_internals26.startAgentSession(sessionId,agentName??"unknown",7200000,directory),session=swarmState.agentSessions.get(sessionId),!session)throw Error(`Failed to create guardrail session for ${sessionId}`);return session}function updateAgentEventTime(sessionId){let session=swarmState.agentSessions.get(sessionId);if(session)session.lastAgentEventTime=Date.now()}function beginInvocation(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)throw Error(`Cannot begin invocation: session ${sessionId} does not exist`);let stripped=stripKnownSwarmPrefix(agentName);if(stripped===ORCHESTRATOR_NAME)return null;let newId=(session.lastInvocationIdByAgent[stripped]||0)+1;session.lastInvocationIdByAgent[stripped]=newId,session.activeInvocationId=newId;let now=Date.now(),window2={id:newId,agentName:stripped,startedAtMs:now,toolCalls:0,consecutiveErrors:0,hardLimitHit:!1,lastSuccessTimeMs:now,recentToolCalls:[],warningIssued:!1,warningReason:"",transientRetryCount:0},key=`${stripped}:${newId}`;return session.windows[key]=window2,pruneOldWindows(sessionId,86400000,50),telemetry.delegationBegin(sessionId,stripped,session.currentTaskId??"unknown"),window2}function getActiveWindow(sessionId){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let key=`${stripKnownSwarmPrefix(session.agentName)}:${session.activeInvocationId}`;return session.windows[key]}function pruneOldWindows(sessionId,maxAgeMs=86400000,maxWindows=50){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let now=Date.now(),toKeep=Object.entries(session.windows).filter(([_,window2])=>now-window2.startedAtMs<maxAgeMs).sort((a,b)=>b[1].startedAtMs-a[1].startedAtMs).slice(0,maxWindows);session.windows=Object.fromEntries(toKeep)}function recordPhaseAgentDispatch(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)return;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;let normalizedName=stripKnownSwarmPrefix(agentName);session.phaseAgentsDispatched.add(normalizedName)}function isValidTaskId2(taskId){if(taskId===null||taskId===void 0)return!1;if(typeof taskId!=="string")return!1;return taskId.trim().length>0}function advanceTaskState(session,taskId,newState,options,councilConfig){if(!isValidTaskId2(taskId))return;if(!session||!(session.taskWorkflowStates instanceof Map))throw Error("INVALID_SESSION: session.taskWorkflowStates must be a Map instance");let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=STATE_ORDER.indexOf(current);if(STATE_ORDER.indexOf(newState)<=currentIndex)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} ${current} → ${newState}`);if(newState==="complete"&&current!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} cannot reach complete from ${current} — must pass through tests_run first (or have council APPROVE after pre_check)`)}if(session.taskWorkflowStates.set(taskId,newState),newState==="complete")session.stageBCompletion?.delete(taskId);if(options?.emitTelemetry!==!1)telemetry.taskStateChanged(options?.telemetrySessionId??session.agentName,taskId,newState,current)}function canAdvanceTaskState(session,taskId,newState,councilConfig){if(!isValidTaskId2(taskId))return!1;if(!session||!(session.taskWorkflowStates instanceof Map))return!1;let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=STATE_ORDER.indexOf(current);if(STATE_ORDER.indexOf(newState)<=currentIndex)return!1;if(newState==="complete"&&current!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)return!1}return!0}async function advanceTaskStateAndPersist(session,taskId,newState,directory,options,councilConfig){if(newState==="coder_delegated"){if(await isTaskSettled(directory,taskId)){warn(`[advanceTaskStateAndPersist] refusing to re-dispatch settled task ${taskId}; skipping in-memory advance + persist`);return}}if(advanceTaskState(session,taskId,newState,options,councilConfig),newState!=="coder_delegated"&&newState!=="complete")return;let planStatus=newState==="complete"?"completed":"in_progress";try{await updateTaskStatus(directory,taskId,planStatus,{force:!1})}catch(err){warn(`[advanceTaskStateAndPersist] persist ${taskId} → ${planStatus} failed (in-memory state still advanced): ${err instanceof Error?err.message:String(err)}`)}}function getTaskState(session,taskId){if(!isValidTaskId2(taskId))return"idle";if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;return session.taskWorkflowStates.get(taskId)??"idle"}function recordStageBCompletion(session,taskId,agent){if(!isValidTaskId2(taskId))return;if(!session.stageBCompletion)session.stageBCompletion=new Map;let existing=session.stageBCompletion.get(taskId);if(existing)existing.add(agent);else session.stageBCompletion.set(taskId,new Set([agent]))}function hasBothStageBCompletions(session,taskId){if(!isValidTaskId2(taskId))return!1;let completions=session.stageBCompletion?.get(taskId);if(!completions)return!1;return completions.has("reviewer")&&completions.has("test_engineer")}async function isCouncilGateActive(directory,council,sessionOverrides={}){let enabled=council?.enabled===!0,plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{plan=null}if(!plan)return!1;let planId=derivePlanId(plan),profile=null;try{profile=getProfile(directory,planId)}catch(err){let msg=err instanceof Error?err.message:String(err);if(!(msg.includes("SQLITE_CANTOPEN")||msg.includes("ENOENT")))warn(`[isCouncilGateActive] getProfile threw unexpectedly for plan ${planId}: ${msg}. Treating council as inactive.`);profile=null}if(!profile)return!1;let councilMode=getEffectiveGates(profile,sessionOverrides).council_mode===!0;if(enabled&&councilMode)return!0;if(enabled!==councilMode&&!_councilDisagreementWarned.has(planId))_councilDisagreementWarned.add(planId),warn(`[delegation-gate] Council mode mismatch for plan ${planId}: pluginConfig.council.enabled=${enabled}, QaGates.council_mode=${councilMode}. Falling back to Stage B (non-council) per-task advancement.`);return!1}function _resetCouncilDisagreementWarnings(){_councilDisagreementWarned.clear()}function planStatusToWorkflowState(status){switch(status){case"in_progress":return"coder_delegated";case"completed":return"complete";default:return"idle"}}function evidenceToWorkflowState(evidence){let gates=evidence.gates??{},requiredGates=evidence.required_gates??[];if(requiredGates.length>0){if(requiredGates.every((gate)=>gates[gate]!=null))return"complete"}if(gates.test_engineer!=null)return"tests_run";if(gates.reviewer!=null)return"reviewer_run";if(Object.keys(gates).length>0)return"coder_delegated";return"idle"}async function readPlanFromDisk(directory){try{let planPath=path49.join(directory,".swarm","plan.json"),content=await fs23.readFile(planPath,"utf-8"),parsed=JSON.parse(content);return PlanSchema.parse(parsed)}catch{return null}}async function readGateEvidenceFromDisk(directory){let evidenceMap=new Map;try{let evidenceDir=path49.join(directory,".swarm","evidence"),entries=await fs23.readdir(evidenceDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let taskId=entry.name.replace(/\.json$/,"");if(!/^\d+\.\d+(\.\d+)*$/.test(taskId))continue;try{let filePath=path49.join(evidenceDir,entry.name),content=await fs23.readFile(filePath,"utf-8"),parsed=JSON.parse(content);if(parsed&&typeof parsed.taskId==="string"&&Array.isArray(parsed.required_gates))evidenceMap.set(taskId,parsed)}catch{}}}catch{}return evidenceMap}async function buildRehydrationCache(directory){let planTaskStates=new Map,plan=await readPlanFromDisk(directory);if(plan)for(let phase of plan.phases??[])for(let task of phase.tasks??[])planTaskStates.set(task.id,planStatusToWorkflowState(task.status));let evidenceMap=await readGateEvidenceFromDisk(directory);_rehydrationCache={planTaskStates,evidenceMap}}function applyRehydrationCache(session){if(!_rehydrationCache)return;if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let{planTaskStates,evidenceMap}=_rehydrationCache;for(let[taskId,planState]of planTaskStates){let existingState=session.taskWorkflowStates.get(taskId),evidence=evidenceMap.get(taskId);if(evidence){let derivedState=evidenceToWorkflowState(evidence),existingIndex=existingState?STATE_ORDER.indexOf(existingState):-1;if(STATE_ORDER.indexOf(derivedState)>existingIndex)session.taskWorkflowStates.set(taskId,derivedState)}else{let existingIndex=existingState?STATE_ORDER.indexOf(existingState):-1;if(STATE_ORDER.indexOf(planState)>existingIndex)session.taskWorkflowStates.set(taskId,planState)}}let VALID_COUNCIL_VERDICTS=new Set(["APPROVE","REJECT","CONCERNS"]);for(let[taskId,evidence]of evidenceMap){if(session.taskCouncilApproved.has(taskId))continue;let council=evidence.gates?.council;if(!council)continue;let rawVerdict=council.verdict;if(!rawVerdict||typeof rawVerdict!=="string")continue;if(!VALID_COUNCIL_VERDICTS.has(rawVerdict))continue;let verdict=rawVerdict,roundNumber=council.roundNumber;if(typeof roundNumber!=="number"||!Number.isFinite(roundNumber))roundNumber=1;let rawQuorumSize=council.quorumSize,quorumSize=typeof rawQuorumSize==="number"&&Number.isFinite(rawQuorumSize)&&rawQuorumSize>=1?rawQuorumSize:1;session.taskCouncilApproved.set(taskId,{verdict,roundNumber,quorumSize})}}async function rehydrateSessionFromDisk(directory,session){await _internals26.buildRehydrationCache(directory),_internals26.applyRehydrationCache(session)}function hasActiveTurboMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.turboMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0)return!0;return!1}function hasActiveFullAuto(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.fullAutoMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.fullAutoMode===!0)return!0;return!1}function getActiveFullAutoSessionID(){let activeId,activeLastToolCall=-1;for(let[id,session]of swarmState.agentSessions){if(session.fullAutoMode!==!0)continue;let lastToolCall=session.lastToolCallTime??0;if(activeId===void 0||lastToolCall>activeLastToolCall)activeId=id,activeLastToolCall=lastToolCall}return activeId}function hasActiveLeanTurbo(sessionID){if(sessionID){let session=swarmState.agentSessions.get(sessionID);return session?.turboMode===!0&&session?.turboStrategy==="lean"&&session?.leanTurboActive===!0}for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0&&session.turboStrategy==="lean"&&session.leanTurboActive===!0)return!0;return!1}function hasActiveEpicMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.epicModeActive===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.epicModeActive===!0)return!0;return!1}function getResolvedAutoProceed(session,planAutoProceed){return session.autoProceedOverride??planAutoProceed??!1}function setSessionEnvironment(sessionId,profile){swarmState.environmentProfiles.set(sessionId,profile)}function getSessionEnvironment(sessionId){return swarmState.environmentProfiles.get(sessionId)}function ensureSessionEnvironment(sessionId){let existing=swarmState.environmentProfiles.get(sessionId);if(existing)return existing;let profile=detectEnvironmentProfile();return swarmState.environmentProfiles.set(sessionId,profile),Promise.resolve().then(() => (init_telemetry(),exports_telemetry)).then(({telemetry:telemetry2})=>{telemetry2.environmentDetected(sessionId,profile.hostOS,profile.shellFamily,profile.executionMode)}).catch(()=>{}),profile}function setCriticalShownIds(sessionID,value){let map2=swarmState.currentCriticalShownIds;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,value),map2.size>MAX_TRACKED_CRITICAL_SHOWN){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function clearCriticalShownIds(sessionID){return swarmState.currentCriticalShownIds.delete(sessionID)}function addKnowledgeAckDedup(key){let set2=swarmState.knowledgeAckDedup;if(set2.has(key))return;if(set2.add(key),set2.size>MAX_TRACKED_KNOWLEDGE_ACKS){let oldest=set2.values().next().value;if(oldest!==void 0)set2.delete(oldest)}}async function rehydratePrSubscriptions(sessionID,directory){let map2=new Map;try{let{listActive:listActive2}=await Promise.resolve().then(() => (init_pr_subscriptions(),exports_pr_subscriptions)),records=await listActive2(directory);for(let record2 of records){if(record2.sessionID!==sessionID)continue;let key=`${record2.repoFullName}::${record2.prNumber}`;map2.set(key,{prNumber:record2.prNumber,repoFullName:record2.repoFullName,prUrl:record2.prUrl,lastKnownStatus:record2.mergeableState??"unknown",lastPollTime:record2.lastCheckedAt,errorCount:record2.errorCount,isWatching:record2.isWatching})}}catch(err){warn(`[state] rehydratePrSubscriptions failed for session ${sessionID}: ${err instanceof Error?err.message:String(err)}`)}return map2}var _rehydrationCache=null,_councilDisagreementWarned,STATE_ORDER,_toolAggregates,defaultRunContext,_runContexts,swarmState,STALE_SESSION_TTL_MS=7200000,IDLE_SWEEP_COOLDOWN_MS=60000,_lastIdleSweepAtMs=0,MAX_TRACKED_CRITICAL_SHOWN=500,MAX_TRACKED_KNOWLEDGE_ACKS=5000,_internals26;var init_state2=__esm(()=>{init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_delegation_gate();init_realtime_learning_nudge();init_trajectory_step_state();init_manager();init_utils3();init_trajectory_store();init_session_start_store();init_worktree_link_suggestion();init_telemetry();init_logger();_councilDisagreementWarned=new Set,STATE_ORDER=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","complete"],_toolAggregates=new Map,defaultRunContext=new AgentRunContext("default",_toolAggregates),_runContexts=new Map;swarmState={activeToolCalls:defaultRunContext.activeToolCalls,toolAggregates:defaultRunContext.toolAggregates,activeAgent:defaultRunContext.activeAgent,delegationChains:defaultRunContext.delegationChains,pendingEvents:0,opencodeClient:null,curatorInitAgentNames:[],curatorPhaseAgentNames:[],curatorPostmortemAgentNames:[],curatorConsolidationAgentNames:[],skillImproverAgentNames:[],specWriterAgentNames:[],currentCriticalShownIds:new Map,knowledgeAckDedup:new Set,generatedAgentNames:[],lastBudgetPct:0,agentSessions:defaultRunContext.agentSessions,pendingRehydrations:new Set,fullAutoEnabledInConfig:!1,environmentProfiles:defaultRunContext.environmentProfiles};_internals26={swarmState,resetSwarmState,ensureAgentSession,startAgentSession,getAgentSession,beginInvocation,getActiveWindow,advanceTaskState,getTaskState,hasActiveFullAuto,hasActiveTurboMode,hasActiveLeanTurbo,hasActiveEpicMode,buildRehydrationCache,applyRehydrationCache,rehydrateSessionFromDisk,isCouncilGateActive,defaultRunContext}});async function handleAutoProceedCommand(_directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Auto-proceed requires an active session. Use /swarm auto-proceed from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Auto-proceed requires an active session to operate.";if(stripKnownSwarmPrefix(session.agentName)!=="architect")return`Error: Auto-proceed can only be toggled from the architect session. Currently active session is: ${session.agentName}`;let arg=args2[0]?.toLowerCase(),wasUndefinedBefore=session.autoProceedOverride===void 0,newAutoProceedOverride;if(arg==="on")newAutoProceedOverride=!0;else if(arg==="off")newAutoProceedOverride=!1;else if(arg===void 0)newAutoProceedOverride=!session.autoProceedOverride;else return'Error: Invalid argument for /swarm auto-proceed. Valid options: "on", "off", or omit the argument to toggle.';if(session.autoProceedOverride=newAutoProceedOverride,arg==="on"||arg==="off"||arg===void 0&&wasUndefinedBefore)session.autoProceedNudgeDone=!0;if(newAutoProceedOverride)return"Auto-proceed is now ON. Phase boundaries will advance automatically.";else return"Auto-proceed is now OFF. You will be asked before advancing to the next phase."}var init_auto_proceed=__esm(()=>{init_schema();init_state2()});import*as fs24 from"node:fs";import*as os13 from"node:os";import*as path50 from"node:path";function buildDelegationCostFields(input={}){let extracted=extractUsageAndCost(input.raw),usage=extracted.usage,model=extracted.model??input.model,reportedCost=extracted.cost_usd;if(reportedCost!==null)return{...usage,cost_usd:roundUsd(reportedCost),cost_source:"reported",model,gate:input.gate,retry_index:input.retry_index};let estimated=estimateCostUsd(usage,model,input.pricing);if(estimated!==null)return{...usage,cost_usd:roundUsd(estimated),cost_source:"estimated",model,gate:input.gate,retry_index:input.retry_index};return{...usage,cost_usd:null,cost_source:"unavailable",model,gate:input.gate,retry_index:input.retry_index}}function summarizeTelemetryCosts(directory){let summary=createEmptySummary();for(let event of readTelemetryEvents(directory)){if(event.event!=="delegation_end")continue;addDelegationEvent(summary,event)}return finalizeSummary(summary)}function readTelemetryEvents(directory){let swarmDir=path50.join(directory,".swarm"),files=[path50.join(swarmDir,"telemetry.jsonl.1"),path50.join(swarmDir,"telemetry.jsonl")],tmpDir=fs24.mkdtempSync(path50.join(os13.tmpdir(),"telemetry-snapshot-")),snapshotFiles=[];try{for(let file2 of files){if(!fs24.existsSync(file2))continue;let snap=path50.join(tmpDir,path50.basename(file2));try{fs24.copyFileSync(file2,snap),snapshotFiles.push(snap)}catch{}}}catch{}let events=[];for(let file2 of snapshotFiles){let content="";try{content=fs24.readFileSync(file2,"utf-8")}catch{continue}for(let line of content.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed)continue;try{let parsed=JSON.parse(trimmed);if(isRecord(parsed))events.push(parsed)}catch{}}}try{for(let f of snapshotFiles)try{fs24.unlinkSync(f)}catch{}fs24.rmdirSync(tmpDir)}catch{}return events}function estimateCostUsd(usage,model,pricing){if(!model)return null;let table={...BUNDLED_MODEL_PRICING,...pricing?.models??{}},entry=table[model]??table[model.toLowerCase()];if(!entry)return null;let cost=usage.tokens_input/1e6*entry.input_per_million+usage.tokens_output/1e6*entry.output_per_million+usage.tokens_reasoning/1e6*(entry.reasoning_per_million??entry.output_per_million)+usage.tokens_cache/1e6*(entry.cache_per_million??entry.input_per_million);return cost>0?cost:null}function extractUsageAndCost(raw){let candidates=collectCandidateRecords(raw),usage={...ZERO_USAGE},cost_usd=null,model;for(let candidate of candidates){model??=readModelIdentifier(candidate),cost_usd??=readNumber(candidate,["cost_usd","total_cost_usd","cost","totalCost"]);let directInput=readNumber(candidate,["tokens_input","input_tokens","input","prompt_tokens"]),directOutput=readNumber(candidate,["tokens_output","output_tokens","output","completion_tokens"]),directReasoning=readNumber(candidate,["tokens_reasoning","reasoning_tokens","reasoning"]),directCache=readNumber(candidate,["tokens_cache","cache_tokens","cache_read_input_tokens","cached_input_tokens","cache_write_input_tokens","cache"]),nestedCache=readCacheTokens(candidate);usage.tokens_input||=directInput??0,usage.tokens_output||=directOutput??0,usage.tokens_reasoning||=directReasoning??0,usage.tokens_cache||=directCache??nestedCache??0}return{usage,cost_usd,model}}function collectCandidateRecords(raw){let records=[],visit=(value,depth)=>{if(depth>3||!isRecord(value))return;records.push(value);for(let key of["usage","tokens","cache","cost","metadata","data","info","message","assistant","task","part","response","output"])visit(value[key],depth+1)};return visit(raw,0),records}function readNumber(record2,keys){for(let key of keys){let value=record2[key];if(typeof value==="number"&&Number.isFinite(value)&&value>=0)return value;if(typeof value==="string"&&value.trim()!==""){let parsed=Number(value);if(Number.isFinite(parsed)&&parsed>=0)return parsed}}return null}function readString(record2,keys){for(let key of keys){let value=record2[key];if(typeof value==="string"&&value.trim()!=="")return value.trim()}return}function readModelIdentifier(record2){let direct=readString(record2,["model","model_id"]);if(direct)return direct;let modelID=readString(record2,["modelID"]),providerID=readString(record2,["providerID"]);if(modelID&&providerID)return`${providerID}/${modelID}`;return modelID}function readCacheTokens(record2){let cacheRecord=isRecord(record2.cache)?record2.cache:record2,read=readNumber(cacheRecord,["read","cache_read_input_tokens"]),write=readNumber(cacheRecord,["write","cache_write_input_tokens","write_input_tokens"]);if(read===null&&write===null)return null;return(read??0)+(write??0)}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function createEmptySummary(){return{total_cost_usd:0,total_reported_usd:0,total_estimated_usd:0,total_input_tokens:0,total_output_tokens:0,total_reasoning_tokens:0,total_cache_tokens:0,delegations:0,unavailable_delegations:0,by_agent:[],by_task:[],by_gate:[],by_retry:[],by_source:{reported:{delegations:0,cost_usd:0},estimated:{delegations:0,cost_usd:0},unavailable:{delegations:0,cost_usd:0}}}}function addDelegationEvent(summary,event){let costSource=parseCostSource(event.cost_source),cost=readNumber(event,["cost_usd"])??0,usage={tokens_input:readNumber(event,["tokens_input"])??0,tokens_output:readNumber(event,["tokens_output"])??0,tokens_reasoning:readNumber(event,["tokens_reasoning"])??0,tokens_cache:readNumber(event,["tokens_cache"])??0};if(summary.delegations++,summary.total_cost_usd+=cost,summary.total_input_tokens+=usage.tokens_input,summary.total_output_tokens+=usage.tokens_output,summary.total_reasoning_tokens+=usage.tokens_reasoning,summary.total_cache_tokens+=usage.tokens_cache,summary.by_source[costSource].delegations++,summary.by_source[costSource].cost_usd+=cost,costSource==="reported")summary.total_reported_usd+=cost;if(costSource==="estimated")summary.total_estimated_usd+=cost;if(costSource==="unavailable")summary.unavailable_delegations++;addRow(summary.by_agent,String(event.agentName??event.agent??"unknown"),{cost,costSource,usage}),addRow(summary.by_task,String(event.taskId??event.task_id??"unknown"),{cost,costSource,usage}),addRow(summary.by_gate,String(event.gate??"unknown"),{cost,costSource,usage}),addRow(summary.by_retry,String(readNumber(event,["retry_index","retryIndex"])??0),{cost,costSource,usage})}function addRow(rows,name,input){let row=rows.find((candidate)=>candidate.name===name);if(!row)row={name,delegations:0,cost_usd:0,input_tokens:0,output_tokens:0,reasoning_tokens:0,cache_tokens:0,unavailable_delegations:0},rows.push(row);if(row.delegations++,row.cost_usd+=input.cost,row.input_tokens+=input.usage.tokens_input,row.output_tokens+=input.usage.tokens_output,row.reasoning_tokens+=input.usage.tokens_reasoning,row.cache_tokens+=input.usage.tokens_cache,input.costSource==="unavailable")row.unavailable_delegations++}function finalizeSummary(summary){summary.total_cost_usd=roundUsd(summary.total_cost_usd),summary.total_reported_usd=roundUsd(summary.total_reported_usd),summary.total_estimated_usd=roundUsd(summary.total_estimated_usd);for(let source of Object.values(summary.by_source))source.cost_usd=roundUsd(source.cost_usd);for(let rows of[summary.by_agent,summary.by_task,summary.by_gate,summary.by_retry]){for(let row of rows)row.cost_usd=roundUsd(row.cost_usd);rows.sort((a,b)=>b.cost_usd-a.cost_usd||b.delegations-a.delegations)}return summary}function parseCostSource(value){return value==="reported"||value==="estimated"||value==="unavailable"?value:"unavailable"}function roundUsd(value){return Math.round(value*1e6)/1e6}var ZERO_USAGE,BUNDLED_MODEL_PRICING;var init_cost_accounting=__esm(()=>{ZERO_USAGE={tokens_input:0,tokens_output:0,tokens_reasoning:0,tokens_cache:0},BUNDLED_MODEL_PRICING={}});async function handleBenchmarkCommand(directory,args2){let cumulative=args2.includes("--cumulative");if(args2.includes("--ci-gate"))cumulative=!0;let maxCostUsd=parseMaxCostUsd(args2),mode=cumulative?"cumulative":"in-memory",costSummary=cumulative?summarizeTelemetryCosts(directory):void 0,agentMap=new Map;for(let[,s]of swarmState.agentSessions){let e=agentMap.get(s.agentName)||{toolCalls:0,hardLimits:0,warnings:0},windows=Object.values(s.windows);e.toolCalls+=windows.reduce((sum,w)=>sum+w.toolCalls,0),e.hardLimits+=windows.filter((w)=>w.hardLimitHit).length,e.warnings+=windows.filter((w)=>w.warningIssued).length,agentMap.set(s.agentName,e)}let agentHealth=Array.from(agentMap.entries()).map(([a,v])=>({agent:a,...v})),toolPerf=[];for(let[,a]of swarmState.toolAggregates){let successRate=a.count?a.successCount/a.count*100:0;toolPerf.push({tool:a.tool,calls:a.count,successRate:Math.round(successRate*10)/10,avg:a.count?Math.round(a.totalDuration/a.count):0})}toolPerf.sort((a,b)=>b.calls-a.calls);let delegationCount=0;for(let c of swarmState.delegationChains.values())delegationCount+=c.length;let quality,qualityMetrics;if(cumulative){let reviewPasses=0,reviewFails=0,testPasses=0,testFails=0,additions=0,deletions=0,totalComplexityDelta=0,totalPublicApiDelta=0,totalDuplicationRatio=0,totalTestToCodeRatio=0,qualityEvidenceCount=0;for(let tid of await listEvidenceTaskIds(directory)){let result;try{result=await loadEvidence(directory,tid)}catch(_evidenceErr){warn("benchmark: skipping corrupt or unreadable evidence for task",tid);continue}if(result.status!=="found")continue;for(let e of result.bundle.entries){if(!isValidEvidenceType(e.type)){warn(`Unknown evidence type '${e.type}' in task ${tid}, skipping`);continue}if(e.type==="review"){if(e.verdict==="approved")reviewPasses++;else if(e.verdict==="rejected")reviewFails++}else if(e.type==="test")testPasses+=e.tests_passed,testFails+=e.tests_failed;else if(e.type==="diff")additions+=e.additions,deletions+=e.deletions;else if(e.type==="quality_budget"){let qe=e;totalComplexityDelta+=qe.metrics.complexity_delta,totalPublicApiDelta+=qe.metrics.public_api_delta,totalDuplicationRatio+=qe.metrics.duplication_ratio*100,totalTestToCodeRatio+=qe.metrics.test_to_code_ratio*100,qualityEvidenceCount++}}}let totalReviews=reviewPasses+reviewFails,totalTests=testPasses+testFails;if(quality={reviewPassRate:totalReviews?Math.round(reviewPasses/totalReviews*1000)/10:null,testPassRate:totalTests?Math.round(testPasses/totalTests*1000)/10:null,totalReviews,testsPassed:testPasses,testsFailed:testFails,additions,deletions},qualityEvidenceCount>0)qualityMetrics={complexityDelta:Math.round(totalComplexityDelta/qualityEvidenceCount*10)/10,publicApiDelta:Math.round(totalPublicApiDelta/qualityEvidenceCount*10)/10,duplicationRatio:Math.round(totalDuplicationRatio/qualityEvidenceCount*10)/10,testToCodeRatio:Math.round(totalTestToCodeRatio/qualityEvidenceCount*10)/10,thresholds:{maxComplexityDelta:CI.max_complexity_delta,maxPublicApiDelta:CI.max_public_api_delta,maxDuplicationRatio:CI.max_duplication_ratio,minTestToCodeRatio:CI.min_test_to_code_ratio},hasEvidence:!0};else qualityMetrics={complexityDelta:0,publicApiDelta:0,duplicationRatio:0,testToCodeRatio:0,thresholds:{maxComplexityDelta:CI.max_complexity_delta,maxPublicApiDelta:CI.max_public_api_delta,maxDuplicationRatio:CI.max_duplication_ratio,minTestToCodeRatio:CI.min_test_to_code_ratio},hasEvidence:!1}}let ciGate;if(args2.includes("--ci-gate")){let totalCalls=0,totalFailures=0;for(let[,a]of swarmState.toolAggregates)totalCalls+=a.count,totalFailures+=a.failureCount;let agentErrorRate=totalCalls?totalFailures/totalCalls*100:0,maxHardLimits=0;for(let v of agentMap.values())if(v.hardLimits>maxHardLimits)maxHardLimits=v.hardLimits;let hasQualityEvidence=qualityMetrics?.hasEvidence??!1,complexityDelta=qualityMetrics?.complexityDelta??0,publicApiDelta=qualityMetrics?.publicApiDelta??0,duplicationRatio=qualityMetrics?.duplicationRatio??0,testToCodeRatio=qualityMetrics?.testToCodeRatio??0,checks3=[{name:"Review pass rate",value:quality?.reviewPassRate??0,threshold:CI.review_pass_rate,operator:">=",passed:(quality?.reviewPassRate??0)>=CI.review_pass_rate},{name:"Test pass rate",value:quality?.testPassRate??0,threshold:CI.test_pass_rate,operator:">=",passed:(quality?.testPassRate??0)>=CI.test_pass_rate},{name:"Agent error rate",value:Math.round(agentErrorRate*10)/10,threshold:CI.max_agent_error_rate,operator:"<=",passed:agentErrorRate<=CI.max_agent_error_rate},{name:"Hard limit hits",value:maxHardLimits,threshold:CI.max_hard_limit_hits,operator:"<=",passed:maxHardLimits<=CI.max_hard_limit_hits},{name:"Complexity Delta",value:complexityDelta,threshold:CI.max_complexity_delta,operator:"<=",passed:!hasQualityEvidence||complexityDelta<=CI.max_complexity_delta},{name:"Public API Delta",value:publicApiDelta,threshold:CI.max_public_api_delta,operator:"<=",passed:!hasQualityEvidence||publicApiDelta<=CI.max_public_api_delta},{name:"Duplication Ratio",value:duplicationRatio,threshold:CI.max_duplication_ratio,operator:"<=",passed:!hasQualityEvidence||duplicationRatio<=CI.max_duplication_ratio},{name:"Test-to-Code Ratio",value:testToCodeRatio,threshold:CI.min_test_to_code_ratio,operator:">=",passed:!hasQualityEvidence||testToCodeRatio>=CI.min_test_to_code_ratio}];if(maxCostUsd!==null)checks3.push({name:"Total cost",value:costSummary?.total_cost_usd??0,threshold:maxCostUsd,operator:"<=",passed:(costSummary?.total_cost_usd??0)<=maxCostUsd});ciGate={passed:checks3.every((c)=>c.passed),checks:checks3}}let lines=[`## Swarm Benchmark (mode: ${mode})`,"","### Agent Health"];if(!agentHealth.length)lines.push("No agent sessions recorded");else for(let{agent,toolCalls,hardLimits,warnings}of agentHealth){let parts=[`${toolCalls} tool calls`];if(warnings>0)parts.push(`${warnings} warning${warnings>1?"s":""}`);parts.push(hardLimits?`${hardLimits} hard limit hit${hardLimits>1?"s":""}`:"0 hard limits"),lines.push(`- ${hardLimits?"⚠️":"✅"} **${agent}**: ${parts.join(", ")}`)}if(lines.push("","### Tool Performance"),!toolPerf.length)lines.push("No tool data recorded");else{lines.push("| Tool | Calls | Success Rate | Avg Duration |","|------|-------|-------------|-------------|");for(let{tool,calls,successRate,avg}of toolPerf)lines.push(`| ${tool} | ${calls} | ${successRate}% | ${avg}ms |`)}if(lines.push("","### Delegations",delegationCount?`Total: ${delegationCount} delegations`:"No delegations recorded",""),quality){if(lines.push("### Quality Signals"),!quality.totalReviews&&!quality.testsPassed&&!quality.additions)lines.push("No evidence data found");else{if(quality.reviewPassRate!==null)lines.push(`- Review pass rate: ${quality.reviewPassRate}% (${quality.totalReviews}) ${quality.reviewPassRate>=70?"✅":"❌"}`);else lines.push("- Review pass rate: N/A (no reviews)");if(quality.testPassRate!==null)lines.push(`- Test pass rate: ${quality.testPassRate}% (${quality.testsPassed}/${quality.testsPassed+quality.testsFailed}) ${quality.testPassRate>=80?"✅":"❌"}`);else lines.push("- Test pass rate: N/A (no tests)");lines.push(`- Code churn: +${quality.additions} / -${quality.deletions} lines`)}lines.push("")}if(qualityMetrics?.hasEvidence)lines.push("### Quality Metrics"),lines.push(`- Complexity Delta: ${qualityMetrics.complexityDelta} (max: ${qualityMetrics.thresholds.maxComplexityDelta}) ${qualityMetrics.complexityDelta<=qualityMetrics.thresholds.maxComplexityDelta?"✅":"❌"}`),lines.push(`- Public API Delta: ${qualityMetrics.publicApiDelta} (max: ${qualityMetrics.thresholds.maxPublicApiDelta}) ${qualityMetrics.publicApiDelta<=qualityMetrics.thresholds.maxPublicApiDelta?"✅":"❌"}`),lines.push(`- Duplication Ratio: ${qualityMetrics.duplicationRatio}% (max: ${qualityMetrics.thresholds.maxDuplicationRatio}%) ${qualityMetrics.duplicationRatio<=qualityMetrics.thresholds.maxDuplicationRatio?"✅":"❌"}`),lines.push(`- Test-to-Code Ratio: ${qualityMetrics.testToCodeRatio}% (min: ${qualityMetrics.thresholds.minTestToCodeRatio}%) ${qualityMetrics.testToCodeRatio>=qualityMetrics.thresholds.minTestToCodeRatio?"✅":"❌"}`),lines.push("");if(costSummary)lines.push("### Cost Signals"),lines.push(`- Total tracked cost: $${costSummary.total_cost_usd.toFixed(6)} (${costSummary.delegations} delegations)`,`- Reported: $${costSummary.total_reported_usd.toFixed(6)}; estimated: $${costSummary.total_estimated_usd.toFixed(6)}; unavailable: ${costSummary.unavailable_delegations}`),lines.push("");if(ciGate){lines.push("### CI Gate",ciGate.passed?"✅ PASSED":"❌ FAILED");for(let c of ciGate.checks){let valueStr;if(c.name==="Complexity Delta"||c.name==="Public API Delta")valueStr=`${c.value}`;else if(c.name==="Total cost")valueStr=`$${c.value.toFixed(6)}`;else valueStr=`${c.value}%`;let thresholdStr=c.name==="Complexity Delta"||c.name==="Public API Delta"?`${c.threshold}`:c.name==="Total cost"?`$${c.threshold.toFixed(6)}`:`${c.threshold}%`;lines.push(`- ${c.name}: ${valueStr} ${c.operator} ${thresholdStr} ${c.passed?"✅":"❌"}`)}lines.push("")}let json2={mode,timestamp:new Date().toISOString(),agent_health:agentHealth.map((a)=>({agent:a.agent,tool_calls:a.toolCalls,hard_limit_hits:a.hardLimits,warnings:a.warnings})),tool_performance:toolPerf.map((t)=>({tool:t.tool,calls:t.calls,success_rate:t.successRate,avg_duration_ms:t.avg})),delegations:delegationCount};if(quality)json2.quality={review_pass_rate:quality.reviewPassRate,test_pass_rate:quality.testPassRate,total_reviews:quality.totalReviews,total_tests_passed:quality.testsPassed,total_tests_failed:quality.testsFailed,additions:quality.additions,deletions:quality.deletions};if(qualityMetrics)json2.quality_metrics={complexity_delta:qualityMetrics.complexityDelta,public_api_delta:qualityMetrics.publicApiDelta,duplication_ratio:qualityMetrics.duplicationRatio,test_to_code_ratio:qualityMetrics.testToCodeRatio,thresholds:qualityMetrics.thresholds,has_evidence:qualityMetrics.hasEvidence};if(costSummary)json2.costs={total_cost_usd:costSummary.total_cost_usd,total_reported_usd:costSummary.total_reported_usd,total_estimated_usd:costSummary.total_estimated_usd,total_input_tokens:costSummary.total_input_tokens,total_output_tokens:costSummary.total_output_tokens,total_reasoning_tokens:costSummary.total_reasoning_tokens,total_cache_tokens:costSummary.total_cache_tokens,delegations:costSummary.delegations,unavailable_delegations:costSummary.unavailable_delegations};if(ciGate)json2.ci_gate={passed:ciGate.passed,checks:ciGate.checks.map((c)=>({name:c.name,value:c.value,threshold:c.threshold,operator:c.operator,passed:c.passed}))};return lines.push("[BENCHMARK_JSON]",JSON.stringify(json2,null,2),"[/BENCHMARK_JSON]"),lines.join(`
651
651
  `)}function parseMaxCostUsd(args2){let index=args2.indexOf("--max-cost-usd");if(index===-1)return null;let raw=args2[index+1];if(!raw||raw.startsWith("--"))throw Error("Invalid --max-cost-usd value: expected a non-negative number.");let parsed=Number(raw);if(!Number.isFinite(parsed)||parsed<0)throw Error("Invalid --max-cost-usd value: expected a non-negative number.");return parsed}var CI;var init_benchmark=__esm(()=>{init_manager2();init_cost_accounting();init_state2();init_utils();CI={review_pass_rate:70,test_pass_rate:80,max_agent_error_rate:20,max_hard_limit_hits:1,max_complexity_delta:5,max_public_api_delta:10,max_duplication_ratio:5,min_test_to_code_ratio:30}});function sanitizeTopic(raw){let normalized=raw.replace(/\s+/g," ").trim().replace(/\[\s*MODE\s*:[^\]]*\]/gi,"").replace(/\s+/g," ").trim(),MAX_TOPIC_LEN=2000;if(normalized.length<=2000)return normalized;return`${normalized.slice(0,2000)}…`}async function handleBrainstormCommand(_directory,args2){let description=sanitizeTopic(args2.join(" "));if(description)return`[MODE: BRAINSTORM] ${description}`;return"[MODE: BRAINSTORM] Please enter MODE: BRAINSTORM and begin the structured brainstorm workflow (CONTEXT SCAN → DIALOGUE → APPROACHES → DESIGN SECTIONS → SPEC WRITE + SELF-REVIEW → QA GATE SELECTION → TRANSITION)."}function $constructor2(name,initializer3,params){function init(inst,def){var _a2;Object.defineProperty(inst,"_zod",{value:inst._zod??{},enumerable:!1}),(_a2=inst._zod).traits??(_a2.traits=new Set),inst._zod.traits.add(name),initializer3(inst,def);for(let k in _.prototype)if(!(k in inst))Object.defineProperty(inst,k,{value:_.prototype[k].bind(inst)});inst._zod.constr=_,inst._zod.def=def}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){var _a2;let inst=params?.Parent?new Definition:this;init(inst,def),(_a2=inst._zod).deferred??(_a2.deferred=[]);for(let fn2 of inst._zod.deferred)fn2();return inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:(inst)=>{if(params?.Parent&&inst instanceof params.Parent)return!0;return inst?._zod?.traits?.has(name)}}),Object.defineProperty(_,"name",{value:name}),_}function config2(newConfig){if(newConfig)Object.assign(globalConfig2,newConfig);return globalConfig2}var NEVER2,$brand2,$ZodAsyncError2,$ZodEncodeError2,globalConfig2;var init_core4=__esm(()=>{NEVER2=Object.freeze({status:"aborted"});$brand2=Symbol("zod_brand");$ZodAsyncError2=class $ZodAsyncError2 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};$ZodEncodeError2=class $ZodEncodeError2 extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`);this.name="ZodEncodeError"}};globalConfig2={}});var exports_util2={};__export(exports_util2,{unwrapMessage:()=>unwrapMessage2,uint8ArrayToHex:()=>uint8ArrayToHex2,uint8ArrayToBase64url:()=>uint8ArrayToBase64url2,uint8ArrayToBase64:()=>uint8ArrayToBase642,stringifyPrimitive:()=>stringifyPrimitive2,shallowClone:()=>shallowClone2,safeExtend:()=>safeExtend2,required:()=>required2,randomString:()=>randomString2,propertyKeyTypes:()=>propertyKeyTypes2,promiseAllObject:()=>promiseAllObject2,primitiveTypes:()=>primitiveTypes2,prefixIssues:()=>prefixIssues2,pick:()=>pick2,partial:()=>partial2,optionalKeys:()=>optionalKeys2,omit:()=>omit2,objectClone:()=>objectClone2,numKeys:()=>numKeys2,nullish:()=>nullish3,normalizeParams:()=>normalizeParams2,mergeDefs:()=>mergeDefs2,merge:()=>merge2,jsonStringifyReplacer:()=>jsonStringifyReplacer2,joinValues:()=>joinValues2,issue:()=>issue2,isPlainObject:()=>isPlainObject4,isObject:()=>isObject2,hexToUint8Array:()=>hexToUint8Array2,getSizableOrigin:()=>getSizableOrigin2,getParsedType:()=>getParsedType2,getLengthableOrigin:()=>getLengthableOrigin2,getEnumValues:()=>getEnumValues2,getElementAtPath:()=>getElementAtPath2,floatSafeRemainder:()=>floatSafeRemainder2,finalizeIssue:()=>finalizeIssue2,extend:()=>extend2,escapeRegex:()=>escapeRegex3,esc:()=>esc2,defineLazy:()=>defineLazy2,createTransparentProxy:()=>createTransparentProxy2,cloneDef:()=>cloneDef2,clone:()=>clone2,cleanRegex:()=>cleanRegex2,cleanEnum:()=>cleanEnum2,captureStackTrace:()=>captureStackTrace2,cached:()=>cached2,base64urlToUint8Array:()=>base64urlToUint8Array2,base64ToUint8Array:()=>base64ToUint8Array2,assignProp:()=>assignProp2,assertNotEqual:()=>assertNotEqual2,assertNever:()=>assertNever2,assertIs:()=>assertIs2,assertEqual:()=>assertEqual2,assert:()=>assert2,allowsEval:()=>allowsEval2,aborted:()=>aborted2,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES2,Class:()=>Class2,BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES2});function assertEqual2(val){return val}function assertNotEqual2(val){return val}function assertIs2(_arg){}function assertNever2(_x){throw Error()}function assert2(_){}function getEnumValues2(entries){let numericValues=Object.values(entries).filter((v)=>typeof v==="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v)}function joinValues2(array2,separator="|"){return array2.map((val)=>stringifyPrimitive2(val)).join(separator)}function jsonStringifyReplacer2(_,value){if(typeof value==="bigint")return value.toString();return value}function cached2(getter){return{get value(){{let value=getter();return Object.defineProperty(this,"value",{value}),value}throw Error("cached value already set")}}}function nullish3(input){return input===null||input===void 0}function cleanRegex2(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder2(val,step){let valDecCount=(val.toString().split(".")[1]||"").length,stepString=step.toString(),stepDecCount=(stepString.split(".")[1]||"").length;if(stepDecCount===0&&/\d?e-\d?/.test(stepString)){let match=stepString.match(/\d?e-(\d?)/);if(match?.[1])stepDecCount=Number.parseInt(match[1])}let decCount=valDecCount>stepDecCount?valDecCount:stepDecCount,valInt=Number.parseInt(val.toFixed(decCount).replace(".","")),stepInt=Number.parseInt(step.toFixed(decCount).replace(".",""));return valInt%stepInt/10**decCount}function defineLazy2(object2,key,getter){let value=void 0;Object.defineProperty(object2,key,{get(){if(value===EVALUATING2)return;if(value===void 0)value=EVALUATING2,value=getter();return value},set(v){Object.defineProperty(object2,key,{value:v})},configurable:!0})}function objectClone2(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp2(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs2(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef2(schema){return mergeDefs2(schema._zod.def)}function getElementAtPath2(obj,path51){if(!path51)return obj;return path51.reduce((acc,key)=>acc?.[key],obj)}function promiseAllObject2(promisesObj){let keys=Object.keys(promisesObj),promises4=keys.map((key)=>promisesObj[key]);return Promise.all(promises4).then((results)=>{let resolvedObj={};for(let i=0;i<keys.length;i++)resolvedObj[keys[i]]=results[i];return resolvedObj})}function randomString2(length=10){let str="";for(let i=0;i<length;i++)str+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return str}function esc2(str){return JSON.stringify(str)}function isObject2(data){return typeof data==="object"&&data!==null&&!Array.isArray(data)}function isPlainObject4(o){if(isObject2(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0)return!0;let prot=ctor.prototype;if(isObject2(prot)===!1)return!1;if(Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)return!1;return!0}function shallowClone2(o){if(isPlainObject4(o))return{...o};if(Array.isArray(o))return[...o];return o}function numKeys2(data){let keyCount=0;for(let key in data)if(Object.prototype.hasOwnProperty.call(data,key))keyCount++;return keyCount}function escapeRegex3(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone2(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);if(!def||params?.parent)cl._zod.parent=inst;return cl}function normalizeParams2(_params){let params=_params;if(!params)return{};if(typeof params==="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");params.error=params.message}if(delete params.message,typeof params.error==="string")return{...params,error:()=>params.error};return params}function createTransparentProxy2(getter){let target;return new Proxy({},{get(_,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive2(value){if(typeof value==="bigint")return value.toString()+"n";if(typeof value==="string")return`"${value}"`;return`${value}`}function optionalKeys2(shape){return Object.keys(shape).filter((k)=>{return shape[k]._zod.optin==="optional"&&shape[k]._zod.optout==="optional"})}function pick2(schema,mask){let currDef=schema._zod.def,def=mergeDefs2(schema._zod.def,{get shape(){let newShape={};for(let key in mask){if(!(key in currDef.shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;newShape[key]=currDef.shape[key]}return assignProp2(this,"shape",newShape),newShape},checks:[]});return clone2(schema,def)}function omit2(schema,mask){let currDef=schema._zod.def,def=mergeDefs2(schema._zod.def,{get shape(){let newShape={...schema._zod.def.shape};for(let key in mask){if(!(key in currDef.shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;delete newShape[key]}return assignProp2(this,"shape",newShape),newShape},checks:[]});return clone2(schema,def)}function extend2(schema,shape){if(!isPlainObject4(shape))throw Error("Invalid input to extend: expected a plain object");let checks3=schema._zod.def.checks;if(checks3&&checks3.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let def=mergeDefs2(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp2(this,"shape",_shape),_shape},checks:[]});return clone2(schema,def)}function safeExtend2(schema,shape){if(!isPlainObject4(shape))throw Error("Invalid input to safeExtend: expected a plain object");let def={...schema._zod.def,get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp2(this,"shape",_shape),_shape},checks:schema._zod.def.checks};return clone2(schema,def)}function merge2(a,b){let def=mergeDefs2(a._zod.def,{get shape(){let _shape={...a._zod.def.shape,...b._zod.def.shape};return assignProp2(this,"shape",_shape),_shape},get catchall(){return b._zod.def.catchall},checks:[]});return clone2(a,def)}function partial2(Class2,schema,mask){let def=mergeDefs2(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in oldShape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key]}else for(let key in oldShape)shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key];return assignProp2(this,"shape",shape),shape},checks:[]});return clone2(schema,def)}function required2(Class2,schema,mask){let def=mergeDefs2(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]})}else for(let key in oldShape)shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]});return assignProp2(this,"shape",shape),shape},checks:[]});return clone2(schema,def)}function aborted2(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function prefixIssues2(path51,issues){return issues.map((iss)=>{var _a2;return(_a2=iss).path??(_a2.path=[]),iss.path.unshift(path51),iss})}function unwrapMessage2(message){return typeof message==="string"?message:message?.message}function finalizeIssue2(iss,ctx,config3){let full={...iss,path:iss.path??[]};if(!iss.message){let message=unwrapMessage2(iss.inst?._zod.def?.error?.(iss))??unwrapMessage2(ctx?.error?.(iss))??unwrapMessage2(config3.customError?.(iss))??unwrapMessage2(config3.localeError?.(iss))??"Invalid input";full.message=message}if(delete full.inst,delete full.continue,!ctx?.reportInput)delete full.input;return full}function getSizableOrigin2(input){if(input instanceof Set)return"set";if(input instanceof Map)return"map";if(input instanceof File)return"file";return"unknown"}function getLengthableOrigin2(input){if(Array.isArray(input))return"array";if(typeof input==="string")return"string";return"unknown"}function issue2(...args2){let[iss,input,inst]=args2;if(typeof iss==="string")return{message:iss,code:"custom",input,inst};return{...iss}}function cleanEnum2(obj){return Object.entries(obj).filter(([k,_])=>{return Number.isNaN(Number.parseInt(k,10))}).map((el)=>el[1])}function base64ToUint8Array2(base643){let binaryString=atob(base643),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return bytes}function uint8ArrayToBase642(bytes){let binaryString="";for(let i=0;i<bytes.length;i++)binaryString+=String.fromCharCode(bytes[i]);return btoa(binaryString)}function base64urlToUint8Array2(base64url3){let base643=base64url3.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base643.length%4)%4);return base64ToUint8Array2(base643+padding)}function uint8ArrayToBase64url2(bytes){return uint8ArrayToBase642(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array2(hex3){let cleanHex=hex3.replace(/^0x/,"");if(cleanHex.length%2!==0)throw Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2)bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16);return bytes}function uint8ArrayToHex2(bytes){return Array.from(bytes).map((b)=>b.toString(16).padStart(2,"0")).join("")}class Class2{constructor(..._args){}}var EVALUATING2,captureStackTrace2,allowsEval2,getParsedType2=(data)=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(data))return"array";if(data===null)return"null";if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function")return"promise";if(typeof Map<"u"&&data instanceof Map)return"map";if(typeof Set<"u"&&data instanceof Set)return"set";if(typeof Date<"u"&&data instanceof Date)return"date";if(typeof File<"u"&&data instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},propertyKeyTypes2,primitiveTypes2,NUMBER_FORMAT_RANGES2,BIGINT_FORMAT_RANGES2;var init_util2=__esm(()=>{EVALUATING2=Symbol("evaluating");captureStackTrace2="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval2=cached2(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(_){return!1}});propertyKeyTypes2=new Set(["string","number","symbol"]),primitiveTypes2=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES2={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES2={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function flattenError2(error49,mapper=(issue3)=>issue3.message){let fieldErrors={},formErrors=[];for(let sub of error49.issues)if(sub.path.length>0)fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub));else formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError2(error49,_mapper){let mapper=_mapper||function(issue3){return issue3.message},fieldErrors={_errors:[]},processError=(error50)=>{for(let issue3 of error50.issues)if(issue3.code==="invalid_union"&&issue3.errors.length)issue3.errors.map((issues)=>processError({issues}));else if(issue3.code==="invalid_key")processError({issues:issue3.issues});else if(issue3.code==="invalid_element")processError({issues:issue3.issues});else if(issue3.path.length===0)fieldErrors._errors.push(mapper(issue3));else{let curr=fieldErrors,i=0;while(i<issue3.path.length){let el=issue3.path[i];if(i!==issue3.path.length-1)curr[el]=curr[el]||{_errors:[]};else curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue3));curr=curr[el],i++}}};return processError(error49),fieldErrors}function treeifyError2(error49,_mapper){let mapper=_mapper||function(issue3){return issue3.message},result={errors:[]},processError=(error50,path51=[])=>{var _a2,_b;for(let issue3 of error50.issues)if(issue3.code==="invalid_union"&&issue3.errors.length)issue3.errors.map((issues)=>processError({issues},issue3.path));else if(issue3.code==="invalid_key")processError({issues:issue3.issues},issue3.path);else if(issue3.code==="invalid_element")processError({issues:issue3.issues},issue3.path);else{let fullpath=[...path51,...issue3.path];if(fullpath.length===0){result.errors.push(mapper(issue3));continue}let curr=result,i=0;while(i<fullpath.length){let el=fullpath[i],terminal=i===fullpath.length-1;if(typeof el==="string")curr.properties??(curr.properties={}),(_a2=curr.properties)[el]??(_a2[el]={errors:[]}),curr=curr.properties[el];else curr.items??(curr.items=[]),(_b=curr.items)[el]??(_b[el]={errors:[]}),curr=curr.items[el];if(terminal)curr.errors.push(mapper(issue3));i++}}};return processError(error49),result}function toDotPath2(_path){let segs=[],path51=_path.map((seg)=>typeof seg==="object"?seg.key:seg);for(let seg of path51)if(typeof seg==="number")segs.push(`[${seg}]`);else if(typeof seg==="symbol")segs.push(`[${JSON.stringify(String(seg))}]`);else if(/[^\w$]/.test(seg))segs.push(`[${JSON.stringify(seg)}]`);else{if(segs.length)segs.push(".");segs.push(seg)}return segs.join("")}function prettifyError2(error49){let lines=[],issues=[...error49.issues].sort((a,b)=>(a.path??[]).length-(b.path??[]).length);for(let issue3 of issues)if(lines.push(`✖ ${issue3.message}`),issue3.path?.length)lines.push(` → at ${toDotPath2(issue3.path)}`);return lines.join(`
652
652
  `)}var initializer3=(inst,def)=>{inst.name="$ZodError",Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),inst.message=JSON.stringify(def,jsonStringifyReplacer2,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError2,$ZodRealError2;var init_errors5=__esm(()=>{init_core4();init_util2();$ZodError2=$constructor2("$ZodError",initializer3),$ZodRealError2=$constructor2("$ZodError",initializer3,{Parent:Error})});var _parse2=(_Err)=>(schema,value,_ctx,_params)=>{let ctx=_ctx?Object.assign(_ctx,{async:!1}):{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError2;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())));throw captureStackTrace2(e,_params?.callee),e}return result.value},parse6,_parseAsync2=(_Err)=>async(schema,value,_ctx,params)=>{let ctx=_ctx?Object.assign(_ctx,{async:!0}):{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;if(result.issues.length){let e=new(params?.Err??_Err)(result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())));throw captureStackTrace2(e,params?.callee),e}return result.value},parseAsync3,_safeParse2=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError2;return result.issues.length?{success:!1,error:new(_Err??$ZodError2)(result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())))}:{success:!0,data:result.value}},safeParse3,_safeParseAsync2=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{async:!0}):{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;return result.issues.length?{success:!1,error:new _Err(result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())))}:{success:!0,data:result.value}},safeParseAsync3,_encode2=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _parse2(_Err)(schema,value,ctx)},encode3,_decode2=(_Err)=>(schema,value,_ctx)=>{return _parse2(_Err)(schema,value,_ctx)},decode3,_encodeAsync2=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _parseAsync2(_Err)(schema,value,ctx)},encodeAsync3,_decodeAsync2=(_Err)=>async(schema,value,_ctx)=>{return _parseAsync2(_Err)(schema,value,_ctx)},decodeAsync3,_safeEncode2=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _safeParse2(_Err)(schema,value,ctx)},safeEncode3,_safeDecode2=(_Err)=>(schema,value,_ctx)=>{return _safeParse2(_Err)(schema,value,_ctx)},safeDecode3,_safeEncodeAsync2=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _safeParseAsync2(_Err)(schema,value,ctx)},safeEncodeAsync3,_safeDecodeAsync2=(_Err)=>async(schema,value,_ctx)=>{return _safeParseAsync2(_Err)(schema,value,_ctx)},safeDecodeAsync3;var init_parse3=__esm(()=>{init_core4();init_errors5();init_util2();parse6=_parse2($ZodRealError2),parseAsync3=_parseAsync2($ZodRealError2),safeParse3=_safeParse2($ZodRealError2),safeParseAsync3=_safeParseAsync2($ZodRealError2),encode3=_encode2($ZodRealError2),decode3=_decode2($ZodRealError2),encodeAsync3=_encodeAsync2($ZodRealError2),decodeAsync3=_decodeAsync2($ZodRealError2),safeEncode3=_safeEncode2($ZodRealError2),safeDecode3=_safeDecode2($ZodRealError2),safeEncodeAsync3=_safeEncodeAsync2($ZodRealError2),safeDecodeAsync3=_safeDecodeAsync2($ZodRealError2)});var exports_regexes2={};__export(exports_regexes2,{xid:()=>xid3,uuid7:()=>uuid72,uuid6:()=>uuid62,uuid4:()=>uuid42,uuid:()=>uuid3,uppercase:()=>uppercase2,unicodeEmail:()=>unicodeEmail2,undefined:()=>_undefined4,ulid:()=>ulid3,time:()=>time3,string:()=>string4,sha512_hex:()=>sha512_hex2,sha512_base64url:()=>sha512_base64url2,sha512_base64:()=>sha512_base642,sha384_hex:()=>sha384_hex2,sha384_base64url:()=>sha384_base64url2,sha384_base64:()=>sha384_base642,sha256_hex:()=>sha256_hex2,sha256_base64url:()=>sha256_base64url2,sha256_base64:()=>sha256_base642,sha1_hex:()=>sha1_hex2,sha1_base64url:()=>sha1_base64url2,sha1_base64:()=>sha1_base642,rfc5322Email:()=>rfc5322Email2,number:()=>number4,null:()=>_null4,nanoid:()=>nanoid3,md5_hex:()=>md5_hex2,md5_base64url:()=>md5_base64url2,md5_base64:()=>md5_base642,lowercase:()=>lowercase2,ksuid:()=>ksuid3,ipv6:()=>ipv63,ipv4:()=>ipv43,integer:()=>integer2,idnEmail:()=>idnEmail2,html5Email:()=>html5Email2,hostname:()=>hostname3,hex:()=>hex3,guid:()=>guid3,extendedDuration:()=>extendedDuration2,emoji:()=>emoji3,email:()=>email3,e164:()=>e1643,duration:()=>duration3,domain:()=>domain2,datetime:()=>datetime3,date:()=>date5,cuid2:()=>cuid23,cuid:()=>cuid5,cidrv6:()=>cidrv63,cidrv4:()=>cidrv43,browserEmail:()=>browserEmail2,boolean:()=>boolean4,bigint:()=>bigint4,base64url:()=>base64url3,base64:()=>base643});function emoji3(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}function timeSource2(args2){return typeof args2.precision==="number"?args2.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":args2.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${args2.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function time3(args2){return new RegExp(`^${timeSource2(args2)}$`)}function datetime3(args2){let time4=timeSource2({precision:args2.precision}),opts=["Z"];if(args2.local)opts.push("");if(args2.offset)opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let timeRegex=`${time4}(?:${opts.join("|")})`;return new RegExp(`^${dateSource2}T(?:${timeRegex})$`)}function fixedBase642(bodyLength,padding){return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`)}function fixedBase64url2(length){return new RegExp(`^[A-Za-z0-9_-]{${length}}$`)}var cuid5,cuid23,ulid3,xid3,ksuid3,nanoid3,duration3,extendedDuration2,guid3,uuid3=(version2)=>{if(!version2)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},uuid42,uuid62,uuid72,email3,html5Email2,rfc5322Email2,unicodeEmail2,idnEmail2,browserEmail2,ipv43,ipv63,cidrv43,cidrv63,base643,base64url3,hostname3,domain2,e1643,dateSource2="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date5,string4=(params)=>{let regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${regex}$`)},bigint4,integer2,number4,boolean4,_null4,_undefined4,lowercase2,uppercase2,hex3,md5_hex2,md5_base642,md5_base64url2,sha1_hex2,sha1_base642,sha1_base64url2,sha256_hex2,sha256_base642,sha256_base64url2,sha384_hex2,sha384_base642,sha384_base64url2,sha512_hex2,sha512_base642,sha512_base64url2;var init_regexes2=__esm(()=>{cuid5=/^[cC][^\s-]{8,}$/,cuid23=/^[0-9a-z]+$/,ulid3=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid3=/^[0-9a-vA-V]{20}$/,ksuid3=/^[A-Za-z0-9]{27}$/,nanoid3=/^[a-zA-Z0-9_-]{21}$/,duration3=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,extendedDuration2=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,guid3=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid42=uuid3(4),uuid62=uuid3(6),uuid72=uuid3(7),email3=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,html5Email2=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,rfc5322Email2=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,unicodeEmail2=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,idnEmail2=unicodeEmail2,browserEmail2=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;ipv43=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv63=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv43=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv63=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base643=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url3=/^[A-Za-z0-9_-]*$/,hostname3=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,domain2=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,e1643=/^\+(?:[0-9]){6,14}[0-9]$/,date5=new RegExp(`^${dateSource2}$`);bigint4=/^-?\d+n?$/,integer2=/^-?\d+$/,number4=/^-?\d+(?:\.\d+)?/,boolean4=/^(?:true|false)$/i,_null4=/^null$/i,_undefined4=/^undefined$/i,lowercase2=/^[^A-Z]*$/,uppercase2=/^[^a-z]*$/,hex3=/^[0-9a-fA-F]*$/;md5_hex2=/^[0-9a-fA-F]{32}$/,md5_base642=fixedBase642(22,"=="),md5_base64url2=fixedBase64url2(22),sha1_hex2=/^[0-9a-fA-F]{40}$/,sha1_base642=fixedBase642(27,"="),sha1_base64url2=fixedBase64url2(27),sha256_hex2=/^[0-9a-fA-F]{64}$/,sha256_base642=fixedBase642(43,"="),sha256_base64url2=fixedBase64url2(43),sha384_hex2=/^[0-9a-fA-F]{96}$/,sha384_base642=fixedBase642(64,""),sha384_base64url2=fixedBase64url2(64),sha512_hex2=/^[0-9a-fA-F]{128}$/,sha512_base642=fixedBase642(86,"=="),sha512_base64url2=fixedBase64url2(86)});function handleCheckPropertyResult2(result,payload,property){if(result.issues.length)payload.issues.push(...prefixIssues2(property,result.issues))}var $ZodCheck2,numericOriginMap2,$ZodCheckLessThan2,$ZodCheckGreaterThan2,$ZodCheckMultipleOf2,$ZodCheckNumberFormat2,$ZodCheckBigIntFormat2,$ZodCheckMaxSize2,$ZodCheckMinSize2,$ZodCheckSizeEquals2,$ZodCheckMaxLength2,$ZodCheckMinLength2,$ZodCheckLengthEquals2,$ZodCheckStringFormat2,$ZodCheckRegex2,$ZodCheckLowerCase2,$ZodCheckUpperCase2,$ZodCheckIncludes2,$ZodCheckStartsWith2,$ZodCheckEndsWith2,$ZodCheckProperty2,$ZodCheckMimeType2,$ZodCheckOverwrite2;var init_checks3=__esm(()=>{init_core4();init_regexes2();init_util2();$ZodCheck2=$constructor2("$ZodCheck",(inst,def)=>{var _a2;inst._zod??(inst._zod={}),inst._zod.def=def,(_a2=inst._zod).onattach??(_a2.onattach=[])}),numericOriginMap2={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan2=$constructor2("$ZodCheckLessThan",(inst,def)=>{$ZodCheck2.init(inst,def);let origin=numericOriginMap2[typeof def.value];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.maximum:bag.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(def.value<curr)if(def.inclusive)bag.maximum=def.value;else bag.exclusiveMaximum=def.value}),inst._zod.check=(payload)=>{if(def.inclusive?payload.value<=def.value:payload.value<def.value)return;payload.issues.push({origin,code:"too_big",maximum:def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckGreaterThan2=$constructor2("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck2.init(inst,def);let origin=numericOriginMap2[typeof def.value];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.minimum:bag.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(def.value>curr)if(def.inclusive)bag.minimum=def.value;else bag.exclusiveMinimum=def.value}),inst._zod.check=(payload)=>{if(def.inclusive?payload.value>=def.value:payload.value>def.value)return;payload.issues.push({origin,code:"too_small",minimum:def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckMultipleOf2=$constructor2("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck2.init(inst,def),inst._zod.onattach.push((inst2)=>{var _a2;(_a2=inst2._zod.bag).multipleOf??(_a2.multipleOf=def.value)}),inst._zod.check=(payload)=>{if(typeof payload.value!==typeof def.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof payload.value==="bigint"?payload.value%def.value===BigInt(0):floatSafeRemainder2(payload.value,def.value)===0)return;payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat2=$constructor2("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck2.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES2[def.format];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;if(bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum,isInt)bag.pattern=integer2}),inst._zod.check=(payload)=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,input,inst});return}if(!Number.isSafeInteger(input)){if(input>0)payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,continue:!def.abort});else payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,continue:!def.abort});return}}if(input<minimum)payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort});if(input>maximum)payload.issues.push({origin:"number",input,code:"too_big",maximum,inst})}}),$ZodCheckBigIntFormat2=$constructor2("$ZodCheckBigIntFormat",(inst,def)=>{$ZodCheck2.init(inst,def);let[minimum,maximum]=BIGINT_FORMAT_RANGES2[def.format];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum}),inst._zod.check=(payload)=>{let input=payload.value;if(input<minimum)payload.issues.push({origin:"bigint",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort});if(input>maximum)payload.issues.push({origin:"bigint",input,code:"too_big",maximum,inst})}}),$ZodCheckMaxSize2=$constructor2("$ZodCheckMaxSize",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.size!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;if(def.maximum<curr)inst2._zod.bag.maximum=def.maximum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.size<=def.maximum)return;payload.issues.push({origin:getSizableOrigin2(input),code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinSize2=$constructor2("$ZodCheckMinSize",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.size!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(def.minimum>curr)inst2._zod.bag.minimum=def.minimum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.size>=def.minimum)return;payload.issues.push({origin:getSizableOrigin2(input),code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckSizeEquals2=$constructor2("$ZodCheckSizeEquals",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.size!==void 0}),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.minimum=def.size,bag.maximum=def.size,bag.size=def.size}),inst._zod.check=(payload)=>{let input=payload.value,size=input.size;if(size===def.size)return;let tooBig=size>def.size;payload.issues.push({origin:getSizableOrigin2(input),...tooBig?{code:"too_big",maximum:def.size}:{code:"too_small",minimum:def.size},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckMaxLength2=$constructor2("$ZodCheckMaxLength",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.length!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;if(def.maximum<curr)inst2._zod.bag.maximum=def.maximum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.length<=def.maximum)return;let origin=getLengthableOrigin2(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength2=$constructor2("$ZodCheckMinLength",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.length!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(def.minimum>curr)inst2._zod.bag.minimum=def.minimum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.length>=def.minimum)return;let origin=getLengthableOrigin2(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals2=$constructor2("$ZodCheckLengthEquals",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.length!==void 0}),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.minimum=def.length,bag.maximum=def.length,bag.length=def.length}),inst._zod.check=(payload)=>{let input=payload.value,length=input.length;if(length===def.length)return;let origin=getLengthableOrigin2(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat2=$constructor2("$ZodCheckStringFormat",(inst,def)=>{var _a2,_b;if($ZodCheck2.init(inst,def),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;if(bag.format=def.format,def.pattern)bag.patterns??(bag.patterns=new Set),bag.patterns.add(def.pattern)}),def.pattern)(_a2=inst._zod).check??(_a2.check=(payload)=>{if(def.pattern.lastIndex=0,def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})});else(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex2=$constructor2("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat2.init(inst,def),inst._zod.check=(payload)=>{if(def.pattern.lastIndex=0,def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase2=$constructor2("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase2),$ZodCheckStringFormat2.init(inst,def)}),$ZodCheckUpperCase2=$constructor2("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase2),$ZodCheckStringFormat2.init(inst,def)}),$ZodCheckIncludes2=$constructor2("$ZodCheckIncludes",(inst,def)=>{$ZodCheck2.init(inst,def);let escapedRegex=escapeRegex3(def.includes),pattern=new RegExp(typeof def.position==="number"?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=(payload)=>{if(payload.value.includes(def.includes,def.position))return;payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith2=$constructor2("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck2.init(inst,def);let pattern=new RegExp(`^${escapeRegex3(def.prefix)}.*`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=(payload)=>{if(payload.value.startsWith(def.prefix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith2=$constructor2("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck2.init(inst,def);let pattern=new RegExp(`.*${escapeRegex3(def.suffix)}$`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=(payload)=>{if(payload.value.endsWith(def.suffix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}});$ZodCheckProperty2=$constructor2("$ZodCheckProperty",(inst,def)=>{$ZodCheck2.init(inst,def),inst._zod.check=(payload)=>{let result=def.schema._zod.run({value:payload.value[def.property],issues:[]},{});if(result instanceof Promise)return result.then((result2)=>handleCheckPropertyResult2(result2,payload,def.property));handleCheckPropertyResult2(result,payload,def.property);return}}),$ZodCheckMimeType2=$constructor2("$ZodCheckMimeType",(inst,def)=>{$ZodCheck2.init(inst,def);let mimeSet=new Set(def.mime);inst._zod.onattach.push((inst2)=>{inst2._zod.bag.mime=def.mime}),inst._zod.check=(payload)=>{if(mimeSet.has(payload.value.type))return;payload.issues.push({code:"invalid_value",values:def.mime,input:payload.value.type,inst,continue:!def.abort})}}),$ZodCheckOverwrite2=$constructor2("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck2.init(inst,def),inst._zod.check=(payload)=>{payload.value=def.tx(payload.value)}})});class Doc2{constructor(args2=[]){if(this.content=[],this.indent=0,this)this.args=args2}indented(fn2){this.indent+=1,fn2(this),this.indent-=1}write(arg){if(typeof arg==="function"){arg(this,{execution:"sync"}),arg(this,{execution:"async"});return}let lines=arg.split(`
653
653
  `).filter((x)=>x),minIndent=Math.min(...lines.map((x)=>x.length-x.trimStart().length)),dedented=lines.map((x)=>x.slice(minIndent)).map((x)=>" ".repeat(this.indent*2)+x);for(let line of dedented)this.content.push(line)}compile(){let F=Function,args2=this?.args,lines=[...(this?.content??[""]).map((x)=>` ${x}`)];return new F(...args2,lines.join(`
@@ -1570,7 +1570,7 @@ Usage:
1570
1570
  `)}var _internals56;var init_evidence_service=__esm(()=>{init_manager2();_internals56={loadEvidence,listEvidenceTaskIds}});var init_evidence=__esm(()=>{init_evidence_service()});async function getExportData(directory){let planStructured=await loadPlanJsonOnly(directory),planContent=await readSwarmFileAsync(directory,"plan.md"),contextContent=await readSwarmFileAsync(directory,"context.md");return{version:"4.5.0",exported:new Date().toISOString(),plan:planStructured||planContent,context:contextContent,execution_profile:planStructured?.execution_profile??null}}function formatExportMarkdown(exportData){return["## Swarm Export","","```json",JSON.stringify(exportData,null,2),"```"].join(`
1571
1571
  `)}async function handleExportCommand(directory,_args){let exportData=await getExportData(directory);return formatExportMarkdown(exportData)}var init_export_service=__esm(()=>{init_utils2();init_manager()});var init_export=__esm(()=>{init_export_service()});import*as fs41 from"node:fs";import*as path89 from"node:path";function nowISO3(){return new Date().toISOString()}function ensureSwarmDir4(directory){let swarmDir=path89.resolve(directory,".swarm");if(!fs41.existsSync(swarmDir))fs41.mkdirSync(swarmDir,{recursive:!0});return swarmDir}function emptyCounters(){return{architectTurns:0,toolCalls:0,coderDelegations:0,reviewerRejections:0,testFailures:0,oversightChecks:0,consecutiveNoProgressTurns:0,consecutiveOversightFailures:0}}function sanitizeRunState(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return null;let r=raw;if(typeof r.sessionID!=="string"||!r.sessionID)return null;let mode=VALID_RUN_MODES.has(r.mode)?r.mode:"supervised",status=VALID_RUN_STATUSES.has(r.status)?r.status:"idle";return{...raw,mode,status}}function sanitizeSessions(raw){let result={};for(let[id,session]of Object.entries(raw)){let sanitized=sanitizeRunState(session);if(sanitized)result[id]=sanitized}return result}function emptyState(sessionID,mode="supervised"){let now=nowISO3();return{status:"idle",sessionID,mode,startedAt:now,updatedAt:now,denialCounters:{consecutive:0,total:0},denialHistory:[],counters:emptyCounters()}}function withStateLock(directory,fn2){let release;try{let lockTarget=validateSwarmPath(directory,STATE_FILE3);if(!fs41.existsSync(lockTarget)){ensureSwarmDir4(directory);let seed={version:2,updatedAt:nowISO3(),oversightSequence:0,sessions:{}};fs41.writeFileSync(lockTarget,`${JSON.stringify(seed,null,2)}
1572
1572
  `,"utf-8")}release=lockfile8.lockSync(lockTarget,{retries:{retries:5,minTimeout:5,maxTimeout:50},stale:5000})}catch(error93){warn(`[full-auto/state] cross-process lock unavailable; proceeding unlocked: ${error93 instanceof Error?error93.message:String(error93)}`)}try{return fn2()}finally{if(release)try{release()}catch(releaseError){warn(`[full-auto/state] lock release failed: ${releaseError instanceof Error?releaseError.message:String(releaseError)}`)}}}function emptyPersisted2(){return{version:2,updatedAt:nowISO3(),oversightSequence:0,sessions:{}}}function markStateUnreadable2(reason){stateUnreadable=!0,stateUnreadableReason=reason,error48(`[full-auto/state] state file unreadable: ${reason} — failing closed`)}function clearStateUnreadable(){stateUnreadable=!1,stateUnreadableReason=""}function isFullAutoStateUnreadable(){return{unreadable:stateUnreadable,reason:stateUnreadableReason}}function readPersisted2(directory){try{let filePath=validateSwarmPath(directory,STATE_FILE3),stats2;try{stats2=fs41.statSync(filePath)}catch{return clearStateUnreadable(),readCache.delete(filePath),emptyPersisted2()}let cached3=readCache.get(filePath);if(cached3&&cached3.mtimeMs===stats2.mtimeMs&&cached3.size===stats2.size)return clearStateUnreadable(),structuredClone(cached3.state);let raw=fs41.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed)||parsed.version!==2||!parsed.sessions||typeof parsed.sessions!=="object"||Array.isArray(parsed.sessions))return markStateUnreadable2(`malformed shape (version=${parsed?.version}, sessions type=${Array.isArray(parsed?.sessions)?"array":typeof parsed?.sessions})`),readCache.delete(filePath),emptyPersisted2();clearStateUnreadable();let state={version:2,updatedAt:parsed.updatedAt??nowISO3(),oversightSequence:typeof parsed.oversightSequence==="number"?parsed.oversightSequence:0,sessions:sanitizeSessions(parsed.sessions)};return readCache.set(filePath,{mtimeMs:stats2.mtimeMs,size:stats2.size,state:structuredClone(state)}),state}catch(error93){let reason=error93 instanceof Error?error93.message:String(error93);error48(`[full-auto/state] Failed to read ${STATE_FILE3}: ${reason} — attempting .bak recovery`);try{let bakPath=validateSwarmPath(directory,`${STATE_FILE3}.bak`);if(fs41.existsSync(bakPath)){let raw=fs41.readFileSync(bakPath,"utf-8"),parsed=JSON.parse(raw);if(parsed?.version===2&&parsed.sessions&&!Array.isArray(parsed.sessions))return warn(`[full-auto/state] Recovered from ${STATE_FILE3}.bak`),clearStateUnreadable(),{version:2,updatedAt:parsed.updatedAt??nowISO3(),oversightSequence:typeof parsed.oversightSequence==="number"?parsed.oversightSequence:0,sessions:sanitizeSessions(parsed.sessions)}}}catch(bakError){error48(`[full-auto/state] .bak recovery also failed: ${bakError instanceof Error?bakError.message:String(bakError)}`)}return markStateUnreadable2(`canonical=${reason}; .bak=missing-or-corrupt`),readCache.clear(),emptyPersisted2()}}function writePersisted2(directory,persisted){let filePath,tmpPath,bakPath,payload;try{ensureSwarmDir4(directory),filePath=validateSwarmPath(directory,STATE_FILE3),tmpPath=validateSwarmPath(directory,`${STATE_FILE3}.tmp`),bakPath=validateSwarmPath(directory,`${STATE_FILE3}.bak`),persisted.updatedAt=nowISO3(),payload=`${JSON.stringify(persisted,null,2)}
1573
- `}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);throw error48(`[full-auto/state] Failed to prepare ${STATE_FILE3} write: ${msg}`),Error(`Full-Auto state persistence prepare failed: ${msg}`)}try{if(fs41.existsSync(filePath))fs41.copyFileSync(filePath,bakPath)}catch{}try{fs41.writeFileSync(tmpPath,payload,"utf-8");try{let fd=fs41.openSync(tmpPath,"r+");try{fs41.fsyncSync(fd)}finally{fs41.closeSync(fd)}}catch{}fs41.renameSync(tmpPath,filePath),readCache.delete(filePath);let readback=fs41.readFileSync(filePath,"utf-8");if(JSON.parse(readback)?.version!==2)throw Error("Round-trip readback returned wrong version")}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);throw error48(`[full-auto/state] Failed to persist ${STATE_FILE3} atomically: ${msg}`),Error(`Full-Auto state persistence failed: ${msg}`)}}function loadFullAutoRunState(directory,sessionID){return readPersisted2(directory).sessions[sessionID]}function saveFullAutoRunState(directory,state){withStateLock(directory,()=>{let persisted=readPersisted2(directory);state.updatedAt=nowISO3(),persisted.sessions[state.sessionID]=state,writePersisted2(directory,persisted)})}function startFullAutoRun(directory,sessionID,config3,options={}){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),existing=persisted.sessions[sessionID],mode=config3?.mode??existing?.mode??"supervised",state=existing?{...existing,status:"running",mode,planID:options.planID??existing.planID,currentPhase:options.phase??existing.currentPhase,currentTaskID:options.taskID??existing.currentTaskID,pauseReason:void 0,terminateReason:void 0,updatedAt:nowISO3(),denialCounters:{consecutive:0,total:existing.denialCounters.total},consecutiveOversightFailures:0,counters:{...existing.counters,consecutiveOversightFailures:0}}:{...emptyState(sessionID,mode),status:"running",planID:options.planID,currentPhase:options.phase,currentTaskID:options.taskID};return persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function pauseFullAutoRun(directory,sessionID,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.status="paused",state.pauseReason=reason,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function disarmFullAutoRun(directory,sessionID,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.status="idle",state.pauseReason=reason,state.terminateReason=void 0,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function terminateFullAutoRun(directory,sessionID,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.status="terminated",state.terminateReason=reason,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function isFullAutoRunActive(directory,sessionID){return loadFullAutoRunState(directory,sessionID)?.status==="running"}function incrementFullAutoCounter(directory,sessionID,counter,delta=1){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.counters[counter]=(state.counters[counter]??0)+delta,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function incrementOversightFailureCounter(directory,sessionID){let result=0;return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;state.counters.consecutiveOversightFailures=(state.counters.consecutiveOversightFailures??0)+1,state.consecutiveOversightFailures=state.counters.consecutiveOversightFailures,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),result=state.counters.consecutiveOversightFailures}),result}function resetOversightFailureCounter(directory,sessionID){withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;state.counters.consecutiveOversightFailures=0,state.consecutiveOversightFailures=0,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted)})}function recordFullAutoDenial(directory,sessionID,denial){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;if(state.denialCounters.consecutive+=1,state.denialCounters.total+=1,state.denialHistory.push({timestamp:nowISO3(),tool:denial.tool,code:denial.code,reason:denial.reason}),state.denialHistory.length>MAX_DENIAL_HISTORY)state.denialHistory.splice(0,state.denialHistory.length-MAX_DENIAL_HISTORY);return state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function resetFullAutoDenials(directory,sessionID){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.denialCounters.consecutive=0,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function nextFullAutoOversightSequence(directory){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),next=(persisted.oversightSequence??0)+1;return persisted.oversightSequence=next,writePersisted2(directory,persisted),next})}function recordFullAutoOversight(directory,sessionID,verdict,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.lastOversightAt=nowISO3(),state.lastOversightVerdict=verdict,state.lastOversightReason=reason,state.counters.oversightChecks+=1,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function shouldPauseForDenials(state,config3){let denials=config3?.denials??{},maxConsecutive=denials.max_consecutive??3,maxTotal=denials.max_total??20,onLimit=denials.on_limit??"pause";if(state.denialCounters.consecutive>=maxConsecutive)return{pause:!0,reason:`denial-limit:consecutive>=${maxConsecutive}`,mode:onLimit};if(state.denialCounters.total>=maxTotal)return{pause:!0,reason:`denial-limit:total>=${maxTotal}`,mode:onLimit};return{pause:!1}}var import_proper_lockfile8,lockfile8,STATE_FILE3="full-auto-state.json",MAX_DENIAL_HISTORY=100,VALID_RUN_MODES,VALID_RUN_STATUSES,stateUnreadable=!1,stateUnreadableReason="",readCache;var init_state3=__esm(()=>{init_utils2();init_logger();import_proper_lockfile8=__toESM(require_proper_lockfile(),1),lockfile8=import_proper_lockfile8.default;VALID_RUN_MODES=new Set(["assisted","supervised","strict"]),VALID_RUN_STATUSES=new Set(["idle","running","paused","terminated"]);readCache=new Map});function isValidMode(value){return VALID_MODES.includes(value)}async function handleFullAutoCommand(directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Full-Auto Mode requires an active session. Use /swarm-full-auto from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Full-Auto Mode requires an active session to operate.";let arg=args2[0]?.toLowerCase();if(arg==="status")return buildStatusReport(directory,sessionID,session.fullAutoMode);let newFullAutoMode,modeOverride;if(arg==="on"){newFullAutoMode=!0;let modeArg=args2[1]?.toLowerCase();if(modeArg){if(!isValidMode(modeArg))return`Error: invalid Full-Auto mode '${args2[1]}'. Valid modes: ${VALID_MODES.join(", ")}.`;modeOverride=modeArg}}else if(arg==="off")newFullAutoMode=!1;else if(arg&&isValidMode(arg))newFullAutoMode=!0,modeOverride=arg;else newFullAutoMode=!session.fullAutoMode;let v2Status="unavailable",modeLabel="supervised",denialMaxConsecutive=3,denialMaxTotal=20,failClosed=!0,durableError,criticModelAdvisory="";try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory),fullAutoConfig=config3.full_auto;if(newFullAutoMode&&configHadErrors)return"Error: Full-Auto Mode cannot be enabled — a swarm plugin config file exists but could not be loaded, so full_auto.locked cannot be verified. Fix the config file (see warnings above) and retry.";if(newFullAutoMode&&fullAutoConfig?.locked===!0)return"Error: Full-Auto Mode is locked for this project (full_auto.locked is true in the swarm plugin config). Runtime activation is disabled by configuration; remove the lock to use /swarm full-auto on.";let effectiveMode=modeOverride??fullAutoConfig?.mode??"supervised";if(modeLabel=effectiveMode,denialMaxConsecutive=fullAutoConfig?.denials?.max_consecutive??3,denialMaxTotal=fullAutoConfig?.denials?.max_total??20,failClosed=fullAutoConfig?.fail_closed!==!1,newFullAutoMode){startFullAutoRun(directory,sessionID,fullAutoConfig?{...fullAutoConfig,mode:effectiveMode}:void 0),v2Status="running";let criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model,architectModel=config3.agents?.architect?.model;if(criticModel&&architectModel&&criticModel===architectModel)criticModelAdvisory=" WARNING: critic model matches architect model — set full_auto.critic_model (or agents.critic.model) to a different model for independent oversight."}else{if(!disarmFullAutoRun(directory,sessionID,"/swarm full-auto off"))terminateFullAutoRun(directory,sessionID,"never started");v2Status="idle"}}catch(error93){durableError=error93 instanceof Error?error93.message:String(error93),error48(`[full-auto] durable run-state write failed: ${durableError}`)}if(newFullAutoMode&&durableError)return["Error: Full-Auto Mode could NOT be enabled — durable run-state write failed.",`Reason: ${durableError}.`,"Inspect .swarm/ permissions and disk space, then retry."].join(" ");if(session.fullAutoMode=newFullAutoMode,!newFullAutoMode)session.fullAutoInteractionCount=0,session.fullAutoDeadlockCount=0,session.fullAutoLastQuestionHash=null;if(!newFullAutoMode)return["Full-Auto Mode disabled",`(v2 run-state: ${v2Status}; mode=${modeLabel})`].join(" ");return["Full-Auto Mode enabled",`(v2 mode=${modeLabel}, fail_closed=${failClosed},`,`denials max ${denialMaxConsecutive} consecutive / ${denialMaxTotal} total)`].join(" ")+criticModelAdvisory}function buildStatusReport(directory,sessionID,sessionFlag){let lines=[];lines.push(`Full-Auto session flag: ${sessionFlag?"on":"off"}`);try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory);if(configHadErrors)lines.push("Config: UNREADABLE (a config file exists but could not be loaded; `full_auto.locked` cannot be verified, so runtime activation refuses by fail-closed default). Fix the config file to restore normal status.");if(config3.full_auto?.locked===!0)lines.push("Config: locked (runtime activation disabled via full_auto.locked)")}catch{}try{let runState=loadFullAutoRunState(directory,sessionID),stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable)lines.push(`Durable run-state: UNREADABLE (${stateHealth.reason}). Non-read-only tools are blocked fail-closed until .swarm/full-auto-state.json (or .bak) is restored or deleted.`);else if(!runState)lines.push("Durable run-state: none (no Full-Auto run for this session)");else{if(lines.push(`Durable run-state: ${runState.status} (mode=${runState.mode})`),runState.pauseReason)lines.push(`Pause reason: ${runState.pauseReason}`);if(runState.terminateReason)lines.push(`Terminate reason: ${runState.terminateReason}`);if(lines.push(`Counters: ${runState.counters.toolCalls} tool calls, ${runState.counters.architectTurns} architect turns, ${runState.counters.oversightChecks} oversight checks`),lines.push(`Denials: ${runState.denialCounters.consecutive} consecutive / ${runState.denialCounters.total} total`),runState.lastOversightVerdict)lines.push(`Last oversight verdict: ${runState.lastOversightVerdict}${runState.lastOversightAt?` at ${runState.lastOversightAt}`:""}`)}}catch(error93){lines.push(`Durable run-state: unreadable (${error93 instanceof Error?error93.message:String(error93)})`)}return lines.join(`
1573
+ `}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);throw error48(`[full-auto/state] Failed to prepare ${STATE_FILE3} write: ${msg}`),Error(`Full-Auto state persistence prepare failed: ${msg}`)}try{if(fs41.existsSync(filePath))fs41.copyFileSync(filePath,bakPath)}catch{}try{fs41.writeFileSync(tmpPath,payload,"utf-8");try{let fd=fs41.openSync(tmpPath,"r+");try{fs41.fsyncSync(fd)}finally{fs41.closeSync(fd)}}catch{}fs41.renameSync(tmpPath,filePath),readCache.delete(filePath);let readback=fs41.readFileSync(filePath,"utf-8");if(JSON.parse(readback)?.version!==2)throw Error("Round-trip readback returned wrong version")}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);throw error48(`[full-auto/state] Failed to persist ${STATE_FILE3} atomically: ${msg}`),Error(`Full-Auto state persistence failed: ${msg}`)}}function loadFullAutoRunState(directory,sessionID){return readPersisted2(directory).sessions[sessionID]}function saveFullAutoRunState(directory,state){withStateLock(directory,()=>{let persisted=readPersisted2(directory);state.updatedAt=nowISO3(),persisted.sessions[state.sessionID]=state,writePersisted2(directory,persisted)})}function startFullAutoRun(directory,sessionID,config3,options={}){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),existing=persisted.sessions[sessionID],mode=config3?.mode??existing?.mode??"supervised",state=existing?{...existing,status:"running",mode,planID:options.planID??existing.planID,currentPhase:options.phase??existing.currentPhase,currentTaskID:options.taskID??existing.currentTaskID,pauseReason:void 0,terminateReason:void 0,updatedAt:nowISO3(),denialCounters:{consecutive:0,total:existing.denialCounters.total},consecutiveOversightFailures:0,counters:{...existing.counters,consecutiveOversightFailures:0}}:{...emptyState(sessionID,mode),status:"running",planID:options.planID,currentPhase:options.phase,currentTaskID:options.taskID};return persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function pauseFullAutoRun(directory,sessionID,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.status="paused",state.pauseReason=reason,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function disarmFullAutoRun(directory,sessionID,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.status="idle",state.pauseReason=reason,state.terminateReason=void 0,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function terminateFullAutoRun(directory,sessionID,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.status="terminated",state.terminateReason=reason,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function isFullAutoRunActive(directory,sessionID){return loadFullAutoRunState(directory,sessionID)?.status==="running"}function incrementFullAutoCounter(directory,sessionID,counter,delta=1){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.counters[counter]=(state.counters[counter]??0)+delta,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function incrementOversightFailureCounter(directory,sessionID){let result=0;return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;state.counters.consecutiveOversightFailures=(state.counters.consecutiveOversightFailures??0)+1,state.consecutiveOversightFailures=state.counters.consecutiveOversightFailures,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),result=state.counters.consecutiveOversightFailures}),result}function resetOversightFailureCounter(directory,sessionID){withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;state.counters.consecutiveOversightFailures=0,state.consecutiveOversightFailures=0,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted)})}function recordFullAutoDenial(directory,sessionID,denial){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;if(state.denialCounters.consecutive+=1,state.denialCounters.total+=1,state.denialHistory.push({timestamp:nowISO3(),tool:denial.tool,code:denial.code,reason:denial.reason}),state.denialHistory.length>MAX_DENIAL_HISTORY)state.denialHistory.splice(0,state.denialHistory.length-MAX_DENIAL_HISTORY);return state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function resetFullAutoDenials(directory,sessionID){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.denialCounters.consecutive=0,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function nextFullAutoOversightSequence(directory){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),next=(persisted.oversightSequence??0)+1;return persisted.oversightSequence=next,writePersisted2(directory,persisted),next})}function recordFullAutoOversight(directory,sessionID,verdict,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.lastOversightAt=nowISO3(),state.lastOversightVerdict=verdict,state.lastOversightReason=reason,state.counters.oversightChecks+=1,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function recordFullAutoEscalation(directory,sessionID,detail){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.lastEscalation={reason:detail.reason,interactionCount:detail.interactionCount,deadlockCount:detail.deadlockCount,phase:detail.phase,escalatedAt:nowISO3()},state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function shouldPauseForDenials(state,config3){let denials=config3?.denials??{},maxConsecutive=denials.max_consecutive??3,maxTotal=denials.max_total??20,onLimit=denials.on_limit??"pause";if(state.denialCounters.consecutive>=maxConsecutive)return{pause:!0,reason:`denial-limit:consecutive>=${maxConsecutive}`,mode:onLimit};if(state.denialCounters.total>=maxTotal)return{pause:!0,reason:`denial-limit:total>=${maxTotal}`,mode:onLimit};return{pause:!1}}var import_proper_lockfile8,lockfile8,STATE_FILE3="full-auto-state.json",MAX_DENIAL_HISTORY=100,VALID_RUN_MODES,VALID_RUN_STATUSES,stateUnreadable=!1,stateUnreadableReason="",readCache;var init_state3=__esm(()=>{init_utils2();init_logger();import_proper_lockfile8=__toESM(require_proper_lockfile(),1),lockfile8=import_proper_lockfile8.default;VALID_RUN_MODES=new Set(["assisted","supervised","strict"]),VALID_RUN_STATUSES=new Set(["idle","running","paused","terminated"]);readCache=new Map});function isValidMode(value){return VALID_MODES.includes(value)}async function handleFullAutoCommand(directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Full-Auto Mode requires an active session. Use /swarm-full-auto from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Full-Auto Mode requires an active session to operate.";let arg=args2[0]?.toLowerCase();if(arg==="status")return buildStatusReport(directory,sessionID,session.fullAutoMode);let newFullAutoMode,modeOverride;if(arg==="on"){newFullAutoMode=!0;let modeArg=args2[1]?.toLowerCase();if(modeArg){if(!isValidMode(modeArg))return`Error: invalid Full-Auto mode '${args2[1]}'. Valid modes: ${VALID_MODES.join(", ")}.`;modeOverride=modeArg}}else if(arg==="off")newFullAutoMode=!1;else if(arg&&isValidMode(arg))newFullAutoMode=!0,modeOverride=arg;else newFullAutoMode=!session.fullAutoMode;let v2Status="unavailable",modeLabel="supervised",denialMaxConsecutive=3,denialMaxTotal=20,failClosed=!0,durableError,criticModelAdvisory="";try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory),fullAutoConfig=config3.full_auto;if(newFullAutoMode&&configHadErrors)return"Error: Full-Auto Mode cannot be enabled — a swarm plugin config file exists but could not be loaded, so full_auto.locked cannot be verified. Fix the config file (see warnings above) and retry.";if(newFullAutoMode&&fullAutoConfig?.locked===!0)return"Error: Full-Auto Mode is locked for this project (full_auto.locked is true in the swarm plugin config). Runtime activation is disabled by configuration; remove the lock to use /swarm full-auto on.";let effectiveMode=modeOverride??fullAutoConfig?.mode??"supervised";if(modeLabel=effectiveMode,denialMaxConsecutive=fullAutoConfig?.denials?.max_consecutive??3,denialMaxTotal=fullAutoConfig?.denials?.max_total??20,failClosed=fullAutoConfig?.fail_closed!==!1,newFullAutoMode){startFullAutoRun(directory,sessionID,fullAutoConfig?{...fullAutoConfig,mode:effectiveMode}:void 0),v2Status="running";let criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model,architectModel=config3.agents?.architect?.model;if(criticModel&&architectModel&&criticModel===architectModel)criticModelAdvisory=" WARNING: critic model matches architect model — set full_auto.critic_model (or agents.critic.model) to a different model for independent oversight."}else{if(!disarmFullAutoRun(directory,sessionID,"/swarm full-auto off"))terminateFullAutoRun(directory,sessionID,"never started");v2Status="idle"}}catch(error93){durableError=error93 instanceof Error?error93.message:String(error93),error48(`[full-auto] durable run-state write failed: ${durableError}`)}if(newFullAutoMode&&durableError)return["Error: Full-Auto Mode could NOT be enabled — durable run-state write failed.",`Reason: ${durableError}.`,"Inspect .swarm/ permissions and disk space, then retry."].join(" ");if(session.fullAutoMode=newFullAutoMode,!newFullAutoMode)session.fullAutoInteractionCount=0,session.fullAutoDeadlockCount=0,session.fullAutoLastQuestionHash=null;if(!newFullAutoMode)return["Full-Auto Mode disabled",`(v2 run-state: ${v2Status}; mode=${modeLabel})`].join(" ");return["Full-Auto Mode enabled",`(v2 mode=${modeLabel}, fail_closed=${failClosed},`,`denials max ${denialMaxConsecutive} consecutive / ${denialMaxTotal} total)`].join(" ")+criticModelAdvisory}function buildStatusReport(directory,sessionID,sessionFlag){let lines=[];lines.push(`Full-Auto session flag: ${sessionFlag?"on":"off"}`);try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory);if(configHadErrors)lines.push("Config: UNREADABLE (a config file exists but could not be loaded; `full_auto.locked` cannot be verified, so runtime activation refuses by fail-closed default). Fix the config file to restore normal status.");if(config3.full_auto?.locked===!0)lines.push("Config: locked (runtime activation disabled via full_auto.locked)")}catch{}try{let runState=loadFullAutoRunState(directory,sessionID),stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable)lines.push(`Durable run-state: UNREADABLE (${stateHealth.reason}). Non-read-only tools are blocked fail-closed until .swarm/full-auto-state.json (or .bak) is restored or deleted.`);else if(!runState)lines.push("Durable run-state: none (no Full-Auto run for this session)");else{if(lines.push(`Durable run-state: ${runState.status} (mode=${runState.mode})`),runState.pauseReason)lines.push(`Pause reason: ${runState.pauseReason}`);if(runState.terminateReason)lines.push(`Terminate reason: ${runState.terminateReason}`);if(lines.push(`Counters: ${runState.counters.toolCalls} tool calls, ${runState.counters.architectTurns} architect turns, ${runState.counters.oversightChecks} oversight checks`),lines.push(`Denials: ${runState.denialCounters.consecutive} consecutive / ${runState.denialCounters.total} total`),runState.lastOversightVerdict)lines.push(`Last oversight verdict: ${runState.lastOversightVerdict}${runState.lastOversightAt?` at ${runState.lastOversightAt}`:""}`)}}catch(error93){lines.push(`Durable run-state: unreadable (${error93 instanceof Error?error93.message:String(error93)})`)}return lines.join(`
1574
1574
  `)}var VALID_MODES;var init_full_auto=__esm(()=>{init_config();init_state3();init_state2();init_logger();VALID_MODES=["assisted","supervised","strict"]});function escapeHtml(str){return str.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function sanitizeString(str,maxLength){if(!str)return"";let sanitized=String(str).replace(RTL_OVERRIDE_PATTERN,"");if(sanitized.length>maxLength)return`${sanitized.substring(0,maxLength-3)}...`;return sanitized}function validatePlanPhases(plan){if(!plan||typeof plan!=="object")return!1;let p=plan;if(!Array.isArray(p.phases))return!1;for(let phase of p.phases){if(!phase||typeof phase!=="object")return!1;if(!Array.isArray(phase.tasks))return!1}return!0}function extractCurrentPhaseFromPlan2(plan){if(!plan)return{currentPhase:null,currentTask:null,incompleteTasks:[]};if(!_internals57.validatePlanPhases(plan))return{currentPhase:null,currentTask:null,incompleteTasks:[]};let currentPhase=null,currentPhaseNum=plan.current_phase;if(currentPhaseNum){let phase=plan.phases.find((p)=>p.id===currentPhaseNum);currentPhase=phase?`Phase ${phase.id}: ${phase.name}`:null}else{let inProgressPhase=plan.phases.find((p)=>p.status==="in_progress");if(inProgressPhase)currentPhase=`Phase ${inProgressPhase.id}: ${inProgressPhase.name}`;else if(plan.phases.length>0)currentPhase=`Phase ${plan.phases[0].id}: ${plan.phases[0].name}`}let currentTask=null,incompleteTasks=[];for(let phase of plan.phases)for(let task of phase.tasks){if(task.status==="in_progress")currentTask=sanitizeString(task.id,MAX_TASK_ID_LENGTH);if(task.status!=="completed"){if(incompleteTasks.length<MAX_INCOMPLETE_TASKS)incompleteTasks.push(sanitizeString(task.id,MAX_TASK_ID_LENGTH))}}if(!currentTask&&incompleteTasks.length>0)currentTask=incompleteTasks[0];return{currentPhase,currentTask,incompleteTasks}}function parseSessionState(content){if(!content)return null;try{let state=JSON.parse(content),activeAgent=null;if(state.activeAgent&&typeof state.activeAgent==="object"){let entries=Object.entries(state.activeAgent);if(entries.length>0)activeAgent=sanitizeString(entries[entries.length-1][1],MAX_TASK_ID_LENGTH)}let delegationState=null;if(state.delegationChains&&typeof state.delegationChains==="object"){let chains=Object.entries(state.delegationChains),activeChains=[],maxDepth=0;for(let[,chain]of chains)if(Array.isArray(chain)&&chain.length>0){let sanitizedChain=chain.map((e)=>`${sanitizeString(e.from,MAX_TASK_ID_LENGTH)}->${sanitizeString(e.to,MAX_TASK_ID_LENGTH)}`).join(" | ");activeChains.push(sanitizedChain),maxDepth=Math.max(maxDepth,chain.length)}if(activeChains.length>0)delegationState={activeChains,delegationDepth:maxDepth,pendingHandoffs:[]}}let pendingQA=null;if(state.agentSessions&&typeof state.agentSessions==="object")for(let[,session]of Object.entries(state.agentSessions)){let sess=session;if(sess.lastGateFailure&&sess.currentTaskId){pendingQA={taskId:sanitizeString(sess.lastGateFailure.taskId,MAX_TASK_ID_LENGTH),lastFailure:sanitizeString(sess.lastGateFailure.tool,MAX_TASK_ID_LENGTH)};break}}return{activeAgent,delegationState,pendingQA}}catch(error93){return log("[HandoffService] state extraction failed",{error:error93 instanceof Error?error93.message:String(error93)}),null}}function extractDecisions2(content){if(!content)return[];let decisions=[],lines=content.split(`
1575
1575
  `),inDecisionsSection=!1;for(let line of lines){if(line.trim()==="## Decisions"){inDecisionsSection=!0;continue}if(inDecisionsSection&&line.startsWith("## ")&&line.trim()!=="## Decisions")break;if(inDecisionsSection&&line.trim().startsWith("- ")){let cleaned=line.trim().substring(2).replace(/\s*\[.*?\]\s*/g,"").replace(/✅/g,"").replace(/\[confirmed\]/g,"").trim();if(cleaned){let sanitized=sanitizeString(cleaned,MAX_DECISION_LENGTH);if(sanitized)decisions.push(sanitized)}}}return decisions.slice(-5)}function extractPhaseMetrics(content){if(!content)return"";let lines=content.split(`
1576
1576
  `),inPhaseMetrics=!1,metricsLines=[];for(let line of lines){if(line.trim()==="## Phase Metrics"){inPhaseMetrics=!0;continue}if(inPhaseMetrics&&line.startsWith("## "))break;if(inPhaseMetrics)metricsLines.push(line)}return metricsLines.slice(-5).join(`
@@ -1849,10 +1849,10 @@ INSTRUCTIONS: Retain ONLY the system prompt, the current task context, and the l
1849
1849
  [/CONTEXT COMPACTION]`}function createCompactionService(config3,directory,injectMessage){return{toolAfter:async(_input,_output)=>{if(!config3.enabled)return;let budgetPct=swarmState.lastBudgetPct??0;if(budgetPct<=0)return;let sessionId=_input.sessionID,state=getSessionState(sessionId);try{if(budgetPct>=config3.emergencyThreshold&&budgetPct>state.lastEmergencyAt+5){state.lastEmergencyAt=budgetPct,state.emergencyCount++;let msg=buildEmergencyMessage(budgetPct,config3.preserveLastNTurns);appendSnapshot(directory,"emergency",budgetPct,msg),state.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg);return}if(budgetPct>=config3.reflectionThreshold&&budgetPct>state.lastReflectionAt+5){state.lastReflectionAt=budgetPct,state.reflectionCount++;let msg=buildReflectionMessage(budgetPct);appendSnapshot(directory,"reflection",budgetPct,msg),state.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg);return}if(budgetPct>=config3.observationThreshold&&budgetPct>state.lastObservationAt+5){state.lastObservationAt=budgetPct,state.observationCount++;let msg=buildObservationMessage(budgetPct);appendSnapshot(directory,"observation",budgetPct,msg),state.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg)}}catch{}}}}function getCompactionMetrics(sessionId){if(sessionId){let state=getSessionState(sessionId);return{compactionCount:state.observationCount+state.reflectionCount+state.emergencyCount,lastSnapshotAt:state.lastSnapshotAt}}let total=0,lastSnapshot=null;for(let state of sessionStates.values())if(total+=state.observationCount+state.reflectionCount+state.emergencyCount,state.lastSnapshotAt&&(!lastSnapshot||state.lastSnapshotAt>lastSnapshot))lastSnapshot=state.lastSnapshotAt;return{compactionCount:total,lastSnapshotAt:lastSnapshot}}var sessionStates;var init_compaction_service=__esm(()=>{init_state2();sessionStates=new Map});async function readFileOrEmpty(filePath){for(let attempt=0;attempt<5;attempt++)try{return await readCachedTextFile(filePath,async()=>bunFile(filePath).text())??""}catch(err){if(err?.code!=="ENOENT"||attempt===4)return"";await new Promise((resolve48)=>setTimeout(resolve48,10))}return""}function estimateTokens2(text){if(!text||typeof text!=="string")return 0;return Math.ceil(text.length/3.5)}async function readBudgetState(directory){let content=await readSwarmFileAsync(directory,"session/budget-state.json");if(!content)return null;try{return JSON.parse(content)}catch{return null}}async function writeBudgetState(directory,state){try{let resolvedPath=validateSwarmPath(directory,"session/budget-state.json"),content=JSON.stringify(state,null,2);await bunWrite(resolvedPath,content)}catch(error93){console.warn("[context-budget] Failed to write budget state:",error93 instanceof Error?error93.message:String(error93))}}async function countEvents(directory){let content=await readSwarmFileAsync(directory,"events.jsonl");if(!content)return 0;return content.split(`
1850
1850
  `).filter((line)=>line.trim().length>0).length}async function getPlanCursorContent(directory){let planContent=await readSwarmFileAsync(directory,"plan.md");if(!planContent)return"";let lines=planContent.split(`
1851
1851
  `),cursorLines=[],inCurrentSection=!1;for(let line of lines){if(line.includes("in_progress")||line.includes("**Current**"))inCurrentSection=!0;if(inCurrentSection){if(cursorLines.push(line),cursorLines.length>30)break}}return cursorLines.join(`
1852
- `)||planContent.substring(0,1000)}async function getContextBudgetReport(directory,assembledSystemPrompt,config3){validateDirectory(directory);let timestamp=new Date().toISOString(),systemPromptTokens=estimateTokens2(assembledSystemPrompt),planCursorContent=await getPlanCursorContent(directory),planCursorTokens=estimateTokens2(planCursorContent),knowledgeContent=await readFileOrEmpty(resolveSwarmKnowledgePath(directory)),knowledgeTokens=estimateTokens2(knowledgeContent),runMemoryContent=await readSwarmFileAsync(directory,"run-memory.jsonl"),runMemoryTokens=estimateTokens2(runMemoryContent||""),handoffContent=await readSwarmFileAsync(directory,"handoff.md"),handoffTokens=estimateTokens2(handoffContent||""),contextMdContent=await readSwarmFileAsync(directory,"context.md"),contextMdTokens=estimateTokens2(contextMdContent||""),swarmTotalTokens=systemPromptTokens+planCursorTokens+knowledgeTokens+runMemoryTokens+handoffTokens+contextMdTokens,estimatedTurnCount=await countEvents(directory),budgetPct=swarmTotalTokens/config3.budgetTokens*100,status,recommendation=null;if(budgetPct<config3.warningPct)status="ok";else if(budgetPct<config3.criticalPct)status="warning",recommendation="Consider wrapping up current phase and running /swarm handoff before starting new work.";else status="critical",recommendation="Run /swarm handoff and start a new session to avoid cost escalation.";let estimatedSessionTokens=swarmTotalTokens*Math.max(1,estimatedTurnCount);return{timestamp,systemPromptTokens,planCursorTokens,knowledgeTokens,runMemoryTokens,handoffTokens,contextMdTokens,swarmTotalTokens,estimatedTurnCount,estimatedSessionTokens,budgetPct,status,recommendation}}async function formatBudgetWarning(report,directory,config3){if(validateDirectory(directory),report.status==="ok")return null;if(!directory||directory.trim()==="")return formatWarningMessage(report);let state=await readBudgetState(directory)||{warningFiredAtTurn:null,criticalFiredAtTurn:null,lastInjectedAtTurn:null},currentTurn=report.estimatedTurnCount;if(report.status==="warning"){if(config3.warningMode==="once"&&state.warningFiredAtTurn!==null)return null;if(config3.warningMode==="interval"&&state.warningFiredAtTurn!==null&&currentTurn-state.warningFiredAtTurn<config3.warningIntervalTurns)return null;state.warningFiredAtTurn=currentTurn,state.lastInjectedAtTurn=currentTurn,await writeBudgetState(directory,state)}else if(report.status==="critical")state.criticalFiredAtTurn=currentTurn,state.lastInjectedAtTurn=currentTurn;return formatWarningMessage(report)}function formatWarningMessage(report){let budgetPctStr=report.budgetPct.toFixed(1),tokensPerTurn=report.swarmTotalTokens.toLocaleString();if(report.status==="warning")return`[CONTEXT BUDGET: ${budgetPctStr}% — swarm injecting ~${tokensPerTurn} tokens/turn. Consider wrapping current phase and running /swarm handoff before starting new work.]`;let costPerTurn=(report.swarmTotalTokens/1000*COST_PER_1K_TOKENS).toFixed(3);return`[CONTEXT BUDGET: ${budgetPctStr}% CRITICAL — swarm injecting ~${tokensPerTurn} tokens/turn. Run /swarm handoff and start a new session to avoid cost escalation. Estimated session cost scaling: ~$${costPerTurn}/turn at current context size.]`}var DEFAULT_CONTEXT_BUDGET_CONFIG,COST_PER_1K_TOKENS=0.003;var init_context_budget_service=__esm(()=>{init_knowledge_store();init_utils2();init_bun_compat();init_path_security();init_swarm_artifact_cache();DEFAULT_CONTEXT_BUDGET_CONFIG={enabled:!0,budgetTokens:40000,warningPct:70,criticalPct:90,warningMode:"once",warningIntervalTurns:20}});import*as fsSync9 from"node:fs";import{readFile as readFile27}from"node:fs/promises";import*as path123 from"node:path";function readSpecStalenessSnapshot(directory){try{let p=path123.join(directory,".swarm","spec-staleness.json");if(!fsSync9.existsSync(p))return{stale:!1};let raw=fsSync9.readFileSync(p,"utf-8"),parsed=JSON.parse(raw);return{stale:!0,reason:typeof parsed?.reason==="string"?parsed.reason:void 0,storedHash:typeof parsed?.specHash_plan==="string"?parsed.specHash_plan:void 0,currentHash:typeof parsed?.specHash_current==="string"||parsed?.specHash_current===null?parsed.specHash_current:void 0}}catch{return{stale:!1}}}async function getStatusData(directory,agents){let plan=await loadPlan(directory),status;if(plan&&plan.migration_status!=="migration_failed"){let currentPhase=extractCurrentPhaseFromPlan(plan)||"Unknown",completedTasks=0,totalTasks=0;for(let phase of plan.phases)for(let task of phase.tasks)if(totalTasks++,task.status==="completed")completedTasks++;let agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!1,turboMode:hasActiveTurboMode(),contextBudgetPct:swarmState.lastBudgetPct>0?swarmState.lastBudgetPct:null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let planContent=await readSwarmFileAsync(directory,"plan.md");if(!planContent){let metrics=getCompactionMetrics();status={hasPlan:!1,currentPhase:"Unknown",completedTasks:0,totalTasks:0,agentCount:Object.keys(agents).length,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:swarmState.lastBudgetPct>0?swarmState.lastBudgetPct:null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let currentPhase=extractCurrentPhase(planContent)||"Unknown",completedTasks=(planContent.match(/^- \[x\]/gm)||[]).length,incompleteTasks=(planContent.match(/^- \[ \]/gm)||[]).length,totalTasks=completedTasks+incompleteTasks,agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:swarmState.lastBudgetPct>0?swarmState.lastBudgetPct:null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}}let drift=readSpecStalenessSnapshot(directory);if(drift.stale)status.specStale=!0,status.specStaleReason=drift.reason,status.specStaleStoredHash=drift.storedHash,status.specStaleCurrentHash=drift.currentHash;else if(plan&&plan._specStale)status.specStale=!0,status.specStaleReason=plan._specStaleReason;return status.recentEscalations=await readRecentEscalations(directory),status.pendingProposals=await countProposals(directory),status.unactionableQueueDepth=await safeLineCount(resolveUnactionablePath(directory)),status.insightCandidatesPending=await safeLineCount(validateSwarmPath(directory,"insight-candidates.jsonl")),enrichWithLeanTurbo(status,directory)}function enrichWithLeanTurbo(status,directory){let turboMode=hasActiveTurboMode(),leanActive=_internals80.hasActiveLeanTurbo(),turboStrategy="off";if(leanActive)turboStrategy="lean";else if(turboMode)turboStrategy="standard";if(status.turboStrategy=turboStrategy,!leanActive)return status;let leanSessionID=null;for(let[sessionId,session]of swarmState.agentSessions)if(session.turboStrategy==="lean"&&session.leanTurboActive===!0){leanSessionID=sessionId;break}if(leanSessionID){let runState=_internals80.loadLeanTurboRunState(directory,leanSessionID);if(runState){if(status.leanTurboPhase=runState.phase,status.leanMaxParallelCoders=runState.maxParallelCoders,status.leanPauseReason=runState.pauseReason,!Array.isArray(runState.lanes))runState.lanes=[];let activeLanes=0,completedLanes=0;for(let lane of runState.lanes){if(lane.status==="running")activeLanes++;if(lane.status==="completed")completedLanes++}if(status.leanActiveLaneCount=activeLanes,status.leanCompletedLanes=completedLanes,!Array.isArray(runState.degradedTasks))runState.degradedTasks=[],status.leanDegradedTasks=0;if(runState.degradedTasks.length>0){status.leanDegradedTasks=runState.degradedTasks.length;let summaryParts=[];for(let dt of runState.degradedTasks)summaryParts.push(`${dt.taskId} (${dt.reason})`);status.leanDegradationSummary=summaryParts.join("; ")}}}return status.fullAutoActive=_internals80.hasActiveFullAuto(),status}function formatStatusMarkdown(status){let lines=["## Swarm Status","",`**Current Phase**: ${status.currentPhase}`,`**Tasks**: ${status.completedTasks}/${status.totalTasks} complete`,`**Agents**: ${status.agentCount} registered`];if(status.specStale){let reason=status.specStaleReason??"spec.md changed since plan saved",stored=status.specStaleStoredHash??"unknown",current=status.specStaleCurrentHash??"(spec.md missing)";lines.push("",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to update the spec or `/swarm acknowledge-spec-drift` to dismiss.")}if(status.turboStrategy&&status.turboStrategy!=="off"){if(lines.push(""),status.turboStrategy==="lean"){let parts=["lean"];if(status.leanTurboPhase!==void 0)parts.push(`Phase ${status.leanTurboPhase}`);if(status.leanActiveLaneCount!==void 0){let totalLanes=(status.leanActiveLaneCount??0)+(status.leanCompletedLanes??0);parts.push(`${status.leanActiveLaneCount}/${totalLanes} lanes active`)}if(status.leanDegradedTasks!==void 0&&status.leanDegradedTasks>0)parts.push(`${status.leanDegradedTasks} degraded`);if(lines.push(`**Turbo**: ${parts.join(", ")}`),status.leanDegradationSummary)lines.push(` - ${status.leanDegradationSummary}`);if(status.leanPauseReason)lines.push(`**Lean paused**: ${status.leanPauseReason}`)}else lines.push("**Turbo**: standard");if(status.fullAutoActive)lines.push("**Full-Auto**: active")}else if(status.turboStrategy===void 0&&status.turboMode===!0)lines.push(""),lines.push("**TURBO MODE**: active");if(status.contextBudgetPct!==null&&status.contextBudgetPct>0){let pct=status.contextBudgetPct.toFixed(1),budgetTokens=DEFAULT_CONTEXT_BUDGET_CONFIG.budgetTokens,est=Math.round(status.contextBudgetPct/100*budgetTokens);if(lines.push("",`**Context**: ${pct}% used (est. ${est.toLocaleString()} / ${budgetTokens.toLocaleString()} tokens)`),status.compactionCount>0)lines.push(`**Compaction events**: ${status.compactionCount} triggered`);if(status.lastSnapshotAt)lines.push(`**Last snapshot**: ${status.lastSnapshotAt}`)}if(status.recentEscalations&&status.recentEscalations.length>0){lines.push("","**Recently Escalated (last 7 days)**:");for(let e of status.recentEscalations)lines.push(` - ${e.entry_id} (${e.from}→${e.to}) reason=${e.reason}`)}let proposals=status.pendingProposals??0,unactionable=status.unactionableQueueDepth??0,insights=status.insightCandidatesPending??0;if(proposals>0||unactionable>0||insights>0){if(lines.push("","**Learning Queues**:"),proposals>0)lines.push(` - Pending proposals: ${proposals} (review with \`/swarm skill list\`)`);if(unactionable>0)lines.push(` - Unactionable queue: ${unactionable} (inspect with \`/swarm knowledge unactionable\`)`);if(insights>0)lines.push(` - Insight candidates: ${insights} (consumed at phase end)`)}return lines.join(`
1852
+ `)||planContent.substring(0,1000)}async function getContextBudgetReport(directory,assembledSystemPrompt,config3){validateDirectory(directory);let timestamp=new Date().toISOString(),systemPromptTokens=estimateTokens2(assembledSystemPrompt),planCursorContent=await getPlanCursorContent(directory),planCursorTokens=estimateTokens2(planCursorContent),knowledgeContent=await readFileOrEmpty(resolveSwarmKnowledgePath(directory)),knowledgeTokens=estimateTokens2(knowledgeContent),runMemoryContent=await readSwarmFileAsync(directory,"run-memory.jsonl"),runMemoryTokens=estimateTokens2(runMemoryContent||""),handoffContent=await readSwarmFileAsync(directory,"handoff.md"),handoffTokens=estimateTokens2(handoffContent||""),contextMdContent=await readSwarmFileAsync(directory,"context.md"),contextMdTokens=estimateTokens2(contextMdContent||""),swarmTotalTokens=systemPromptTokens+planCursorTokens+knowledgeTokens+runMemoryTokens+handoffTokens+contextMdTokens,estimatedTurnCount=await countEvents(directory),budgetPct=swarmTotalTokens/config3.budgetTokens*100,status,recommendation=null;if(budgetPct<config3.warningPct)status="ok";else if(budgetPct<config3.criticalPct)status="warning",recommendation="Consider wrapping up current phase and running /swarm handoff before starting new work.";else status="critical",recommendation="Run /swarm handoff and start a new session to avoid cost escalation.";let estimatedSessionTokens=swarmTotalTokens*Math.max(1,estimatedTurnCount);return{timestamp,systemPromptTokens,planCursorTokens,knowledgeTokens,runMemoryTokens,handoffTokens,contextMdTokens,swarmTotalTokens,estimatedTurnCount,estimatedSessionTokens,budgetPct,status,recommendation}}async function formatBudgetWarning(report,directory,config3){if(validateDirectory(directory),report.status==="ok")return null;if(!directory||directory.trim()==="")return formatWarningMessage(report);let state=await readBudgetState(directory)||{warningFiredAtTurn:null,criticalFiredAtTurn:null,lastInjectedAtTurn:null},currentTurn=report.estimatedTurnCount;if(report.status==="warning"){if(config3.warningMode==="once"&&state.warningFiredAtTurn!==null)return null;if(config3.warningMode==="interval"&&state.warningFiredAtTurn!==null&&currentTurn-state.warningFiredAtTurn<config3.warningIntervalTurns)return null;state.warningFiredAtTurn=currentTurn,state.lastInjectedAtTurn=currentTurn,await writeBudgetState(directory,state)}else if(report.status==="critical")state.criticalFiredAtTurn=currentTurn,state.lastInjectedAtTurn=currentTurn;return formatWarningMessage(report)}function formatWarningMessage(report){let budgetPctStr=report.budgetPct.toFixed(1),tokensPerTurn=report.swarmTotalTokens.toLocaleString();if(report.status==="warning")return`[CONTEXT BUDGET: ${budgetPctStr}% — swarm injecting ~${tokensPerTurn} tokens/turn. Consider wrapping current phase and running /swarm handoff before starting new work.]`;let costPerTurn=(report.swarmTotalTokens/1000*COST_PER_1K_TOKENS).toFixed(3);return`[CONTEXT BUDGET: ${budgetPctStr}% CRITICAL — swarm injecting ~${tokensPerTurn} tokens/turn. Run /swarm handoff and start a new session to avoid cost escalation. Estimated session cost scaling: ~$${costPerTurn}/turn at current context size.]`}var DEFAULT_CONTEXT_BUDGET_CONFIG,COST_PER_1K_TOKENS=0.003;var init_context_budget_service=__esm(()=>{init_knowledge_store();init_utils2();init_bun_compat();init_path_security();init_swarm_artifact_cache();DEFAULT_CONTEXT_BUDGET_CONFIG={enabled:!0,budgetTokens:40000,warningPct:70,criticalPct:90,warningMode:"once",warningIntervalTurns:20}});import*as fsSync9 from"node:fs";import{readFile as readFile27}from"node:fs/promises";import*as path123 from"node:path";function readSpecStalenessSnapshot(directory){try{let p=path123.join(directory,".swarm","spec-staleness.json");if(!fsSync9.existsSync(p))return{stale:!1};let raw=fsSync9.readFileSync(p,"utf-8"),parsed=JSON.parse(raw);return{stale:!0,reason:typeof parsed?.reason==="string"?parsed.reason:void 0,storedHash:typeof parsed?.specHash_plan==="string"?parsed.specHash_plan:void 0,currentHash:typeof parsed?.specHash_current==="string"||parsed?.specHash_current===null?parsed.specHash_current:void 0}}catch{return{stale:!1}}}async function getStatusData(directory,agents){let plan=await loadPlan(directory),status;if(plan&&plan.migration_status!=="migration_failed"){let currentPhase=extractCurrentPhaseFromPlan(plan)||"Unknown",completedTasks=0,totalTasks=0;for(let phase of plan.phases)for(let task of phase.tasks)if(totalTasks++,task.status==="completed")completedTasks++;let agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!1,turboMode:hasActiveTurboMode(),contextBudgetPct:swarmState.lastBudgetPct>0?swarmState.lastBudgetPct:null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let planContent=await readSwarmFileAsync(directory,"plan.md");if(!planContent){let metrics=getCompactionMetrics();status={hasPlan:!1,currentPhase:"Unknown",completedTasks:0,totalTasks:0,agentCount:Object.keys(agents).length,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:swarmState.lastBudgetPct>0?swarmState.lastBudgetPct:null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let currentPhase=extractCurrentPhase(planContent)||"Unknown",completedTasks=(planContent.match(/^- \[x\]/gm)||[]).length,incompleteTasks=(planContent.match(/^- \[ \]/gm)||[]).length,totalTasks=completedTasks+incompleteTasks,agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:swarmState.lastBudgetPct>0?swarmState.lastBudgetPct:null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}}let drift=readSpecStalenessSnapshot(directory);if(drift.stale)status.specStale=!0,status.specStaleReason=drift.reason,status.specStaleStoredHash=drift.storedHash,status.specStaleCurrentHash=drift.currentHash;else if(plan&&plan._specStale)status.specStale=!0,status.specStaleReason=plan._specStaleReason;if(status.recentEscalations=await readRecentEscalations(directory),status.pendingProposals=await countProposals(directory),status.unactionableQueueDepth=await safeLineCount(resolveUnactionablePath(directory)),status.insightCandidatesPending=await safeLineCount(validateSwarmPath(directory,"insight-candidates.jsonl")),status.fullAutoActive=_internals80.hasActiveFullAuto(),status.fullAutoActive){let sid=_internals80.getActiveFullAutoSessionID();if(sid){let runState=_internals80.loadFullAutoRunState(directory,sid);if(runState?.lastEscalation)status.fullAutoEscalation={reason:runState.lastEscalation.reason,interactionCount:runState.lastEscalation.interactionCount,deadlockCount:runState.lastEscalation.deadlockCount,phase:runState.lastEscalation.phase}}}return enrichWithLeanTurbo(status,directory)}function enrichWithLeanTurbo(status,directory){let turboMode=hasActiveTurboMode(),leanActive=_internals80.hasActiveLeanTurbo(),turboStrategy="off";if(leanActive)turboStrategy="lean";else if(turboMode)turboStrategy="standard";if(status.turboStrategy=turboStrategy,!leanActive)return status;let leanSessionID=null;for(let[sessionId,session]of swarmState.agentSessions)if(session.turboStrategy==="lean"&&session.leanTurboActive===!0){leanSessionID=sessionId;break}if(leanSessionID){let runState=_internals80.loadLeanTurboRunState(directory,leanSessionID);if(runState){if(status.leanTurboPhase=runState.phase,status.leanMaxParallelCoders=runState.maxParallelCoders,status.leanPauseReason=runState.pauseReason,!Array.isArray(runState.lanes))runState.lanes=[];let activeLanes=0,completedLanes=0;for(let lane of runState.lanes){if(lane.status==="running")activeLanes++;if(lane.status==="completed")completedLanes++}if(status.leanActiveLaneCount=activeLanes,status.leanCompletedLanes=completedLanes,!Array.isArray(runState.degradedTasks))runState.degradedTasks=[],status.leanDegradedTasks=0;if(runState.degradedTasks.length>0){status.leanDegradedTasks=runState.degradedTasks.length;let summaryParts=[];for(let dt of runState.degradedTasks)summaryParts.push(`${dt.taskId} (${dt.reason})`);status.leanDegradationSummary=summaryParts.join("; ")}}}return status}function formatStatusMarkdown(status){let lines=["## Swarm Status","",`**Current Phase**: ${status.currentPhase}`,`**Tasks**: ${status.completedTasks}/${status.totalTasks} complete`,`**Agents**: ${status.agentCount} registered`];if(status.specStale){let reason=status.specStaleReason??"spec.md changed since plan saved",stored=status.specStaleStoredHash??"unknown",current=status.specStaleCurrentHash??"(spec.md missing)";lines.push("",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to update the spec or `/swarm acknowledge-spec-drift` to dismiss.")}if(status.turboStrategy&&status.turboStrategy!=="off")if(lines.push(""),status.turboStrategy==="lean"){let parts=["lean"];if(status.leanTurboPhase!==void 0)parts.push(`Phase ${status.leanTurboPhase}`);if(status.leanActiveLaneCount!==void 0){let totalLanes=(status.leanActiveLaneCount??0)+(status.leanCompletedLanes??0);parts.push(`${status.leanActiveLaneCount}/${totalLanes} lanes active`)}if(status.leanDegradedTasks!==void 0&&status.leanDegradedTasks>0)parts.push(`${status.leanDegradedTasks} degraded`);if(lines.push(`**Turbo**: ${parts.join(", ")}`),status.leanDegradationSummary)lines.push(` - ${status.leanDegradationSummary}`);if(status.leanPauseReason)lines.push(`**Lean paused**: ${status.leanPauseReason}`)}else lines.push("**Turbo**: standard");else if(status.turboStrategy===void 0&&status.turboMode===!0)lines.push(""),lines.push("**TURBO MODE**: active");if(status.fullAutoActive){if(lines.push(""),lines.push("**Full-Auto**: active"),status.fullAutoEscalation){let e=status.fullAutoEscalation,phaseStr=e.phase!==void 0?` | Phase ${e.phase}`:"";lines.push(` - Escalation: ${e.reason} (interactions=${e.interactionCount}, deadlocks=${e.deadlockCount}${phaseStr})`)}}if(status.contextBudgetPct!==null&&status.contextBudgetPct>0){let pct=status.contextBudgetPct.toFixed(1),budgetTokens=DEFAULT_CONTEXT_BUDGET_CONFIG.budgetTokens,est=Math.round(status.contextBudgetPct/100*budgetTokens);if(lines.push("",`**Context**: ${pct}% used (est. ${est.toLocaleString()} / ${budgetTokens.toLocaleString()} tokens)`),status.compactionCount>0)lines.push(`**Compaction events**: ${status.compactionCount} triggered`);if(status.lastSnapshotAt)lines.push(`**Last snapshot**: ${status.lastSnapshotAt}`)}if(status.recentEscalations&&status.recentEscalations.length>0){lines.push("","**Recently Escalated (last 7 days)**:");for(let e of status.recentEscalations)lines.push(` - ${e.entry_id} (${e.from}→${e.to}) reason=${e.reason}`)}let proposals=status.pendingProposals??0,unactionable=status.unactionableQueueDepth??0,insights=status.insightCandidatesPending??0;if(proposals>0||unactionable>0||insights>0){if(lines.push("","**Learning Queues**:"),proposals>0)lines.push(` - Pending proposals: ${proposals} (review with \`/swarm skill list\`)`);if(unactionable>0)lines.push(` - Unactionable queue: ${unactionable} (inspect with \`/swarm knowledge unactionable\`)`);if(insights>0)lines.push(` - Insight candidates: ${insights} (consumed at phase end)`)}return lines.join(`
1853
1853
  `)}async function handleStatusCommand(directory,agents){let statusData=await getStatusData(directory,agents);if(!statusData.hasPlan){if(statusData.specStale){let reason=statusData.specStaleReason??"spec.md changed since plan saved",stored=statusData.specStaleStoredHash??"unknown",current=statusData.specStaleCurrentHash??"(spec.md missing)";return["No active swarm plan found.","",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to update the spec or `/swarm acknowledge-spec-drift` to dismiss."].join(`
1854
1854
  `)}return"No active swarm plan found."}return formatStatusMarkdown(statusData)}async function safeLineCount(filePath){try{if(!fsSync9.existsSync(filePath))return 0;let content=await readFile27(filePath,"utf-8"),n=0;for(let line of content.split(`
1855
- `))if(line.trim())n++;return n}catch{return 0}}async function countProposals(directory){try{let proposalsDir=validateSwarmPath(directory,"skills/proposals");if(!fsSync9.existsSync(proposalsDir))return 0;let{readdir:readdir8}=await import("node:fs/promises");return(await readdir8(proposalsDir)).filter((f)=>f.endsWith(".md")).length}catch{return 0}}var _internals80;var init_status_service=__esm(()=>{init_extractors();init_knowledge_escalator();init_knowledge_validator();init_utils2();init_manager();init_state2();init_state4();init_compaction_service();init_context_budget_service();_internals80={loadLeanTurboRunState,hasActiveLeanTurbo,hasActiveFullAuto}});var init_status=__esm(()=>{init_status_service()});async function handleSyncPlanCommand(directory,_args){let plan=await loadPlan(directory);if(!plan)return`## Plan Sync Report
1855
+ `))if(line.trim())n++;return n}catch{return 0}}async function countProposals(directory){try{let proposalsDir=validateSwarmPath(directory,"skills/proposals");if(!fsSync9.existsSync(proposalsDir))return 0;let{readdir:readdir8}=await import("node:fs/promises");return(await readdir8(proposalsDir)).filter((f)=>f.endsWith(".md")).length}catch{return 0}}var _internals80;var init_status_service=__esm(()=>{init_state3();init_extractors();init_knowledge_escalator();init_knowledge_validator();init_utils2();init_manager();init_state2();init_state4();init_compaction_service();init_context_budget_service();_internals80={loadLeanTurboRunState,hasActiveLeanTurbo,hasActiveFullAuto,getActiveFullAutoSessionID,loadFullAutoRunState}});var init_status=__esm(()=>{init_status_service()});async function handleSyncPlanCommand(directory,_args){let plan=await loadPlan(directory);if(!plan)return`## Plan Sync Report
1856
1856
 
1857
1857
  No active swarm plan found. Nothing to sync.`;return["## Plan Sync Report","","**Status**: ✅ Synced","","The plan.json and plan.md are now synchronized.","","### Current Plan","",derivePlanMarkdown(plan)].join(`
1858
1858
  `)}var init_sync_plan=__esm(()=>{init_manager()});async function handleTurboCommand(directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Turbo Mode requires an active session. Use /swarm turbo from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Turbo Mode requires an active session to operate.";let arg0=args2[0]?.toLowerCase(),arg1=args2[1]?.toLowerCase();if(arg0==="status")return buildStatusMessage2(session,directory,sessionID);let isTurboOn=session.turboMode,isLeanActive=session.leanTurboActive===!0,disableTurbo=(reason)=>{if(isLeanActive)try{pauseLeanTurboRun(directory,sessionID,reason)}catch(error93){error48(`[turbo] pauseLeanTurboRun failed: ${error93 instanceof Error?error93.message:String(error93)}`)}try{disableEpicMode(directory,sessionID)}catch(error93){error48(`[turbo] disableEpicMode (cross-clear) failed: ${error93 instanceof Error?error93.message:String(error93)}`)}session.epicModeActive=!1,session.turboMode=!1,session.turboStrategy=void 0,session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0};if(arg0==="off"||arg0==="lean"&&arg1==="off")return disableTurbo("/swarm turbo off"),"Turbo Mode disabled";if(arg0==="standard"&&arg1==="off")return disableTurbo("/swarm turbo standard off"),"Turbo Mode disabled";if(arg0===void 0)if(isTurboOn)return disableTurbo("/swarm turbo (toggle off)"),"Turbo Mode disabled";else return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,"Turbo Mode enabled";if(arg0==="on"){let strategy="standard";try{let{config:config3}=_internals81.loadPluginConfigWithMeta(directory);if(config3.turbo?.strategy==="lean")strategy="lean"}catch(error93){warn(`[turbo] could not read config for strategy default: ${error93 instanceof Error?error93.message:String(error93)}`)}if(strategy==="lean")return enableLeanTurbo(session,directory,sessionID);if(isLeanActive)disableTurbo("/swarm turbo on (switching from lean)");return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,"Turbo Mode enabled"}if(arg0==="standard"&&arg1==="on"){if(isLeanActive)disableTurbo("/swarm turbo standard on (switching from lean)");return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,"Turbo Mode enabled (standard)"}if(arg0==="lean"&&arg1==="on")return enableLeanTurbo(session,directory,sessionID);if(arg0==="lean"&&arg1===void 0)if(isLeanActive)return disableTurbo("/swarm turbo lean (toggle off)"),"Turbo Mode disabled";else return enableLeanTurbo(session,directory,sessionID);if(arg0==="epic"&&arg1==="on"){let leanMsg=enableLeanTurbo(session,directory,sessionID);if(!session.leanTurboActive)return`${leanMsg}
@@ -5311,7 +5311,7 @@ ${currentPhase!==void 0?"- **Phase Status**: Pending completion":""}
5311
5311
  ## Resolution
5312
5312
  This escalation requires human intervention. The swarm has been paused.
5313
5313
  Please review the architect's output above and provide guidance.
5314
- `;fs81.writeFileSync(reportPath,reportContent,"utf-8"),log(`[full-auto-intercept] Escalation report written to: ${reportPath}`)}catch(error93){error48("[full-auto-intercept] Failed to write escalation report:",error93 instanceof Error?error93.message:String(error93))}}async function handleEscalation(directory,reason,sessionID,architectOutput,interactionCount,deadlockCount,escalationMode,phase){if(telemetry.autoOversightEscalation(sessionID??"unknown",reason,interactionCount,deadlockCount,phase),await writeEscalationReport(directory,reason,architectOutput,interactionCount,deadlockCount,phase),escalationMode==="terminate"){if(error48(`[full-auto-intercept] ESCALATION (terminate mode) — reason: ${reason}, session: ${sessionID}`),sessionID){if(!loadFullAutoRunState(directory,sessionID))startFullAutoRun(directory,sessionID,{enabled:!0});terminateFullAutoRun(directory,sessionID,reason)}return!0}if(warn(`[full-auto-intercept] ESCALATION (pause mode) — reason: ${reason}, session: ${sessionID}`),sessionID){if(!loadFullAutoRunState(directory,sessionID))startFullAutoRun(directory,sessionID,{enabled:!0});pauseFullAutoRun(directory,sessionID,reason)}return!0}var reactiveOversightSequence=0;async function mirrorReactiveVerdictToV2(params){reactiveOversightSequence+=1;let triggerSource=params.escalationType==="phase_completion"?"phase_boundary":"text_pattern",sessionID="",phase,planID;try{let filePath=validateSwarmPath(params.directory,"full-auto-state.json");if(fs81.existsSync(filePath)){let raw=fs81.readFileSync(filePath,"utf-8"),persisted=JSON.parse(raw);if(persisted.sessions){let callerSid=params.sessionID;if(callerSid&&persisted.sessions[callerSid]){let rec=persisted.sessions[callerSid];if(rec.status==="running")sessionID=callerSid,phase=rec.currentPhase,planID=rec.planID}else if(!callerSid)for(let sid of Object.keys(persisted.sessions)){let rec=persisted.sessions[sid];if(rec?.status==="running"){sessionID=sid,phase=rec.currentPhase,planID=rec.planID;break}}}}}catch{}if(!sessionID)return;let decision=(()=>{if(params.parsed.escalationNeeded||params.parsed.verdict==="ESCALATE_TO_HUMAN")return"escalate_human";if(params.parsed.verdict==="APPROVED"||params.parsed.verdict==="ANSWER")return"allow";if(params.parsed.verdict==="BLOCKED")return"pause";if(params.parsed.verdict==="PENDING")return"pending";return"deny"})(),beforeStatus=sessionID?loadFullAutoRunState(params.directory,sessionID)?.status:void 0,event={type:"full_auto_oversight",timestamp:new Date().toISOString(),session_id:sessionID,plan_id:planID,phase,trigger_source:triggerSource,trigger_reason:`reactive intercept (${params.escalationType})`,critic_agent:params.oversightAgentName,critic_model:params.criticModel,verdict:params.parsed.verdict,reasoning:params.parsed.reasoning,evidence_checked:params.parsed.evidenceChecked,anti_patterns_detected:params.parsed.antiPatternsDetected,escalation_needed:params.parsed.escalationNeeded,decision,full_auto_status_before:beforeStatus,full_auto_status_after:beforeStatus,oversight_sequence:reactiveOversightSequence};if(sessionID){if(decision==="pause")pauseFullAutoRun(params.directory,sessionID,`reactive verdict ${params.parsed.verdict}`),event.full_auto_status_after="paused";else if(decision==="escalate_human")terminateFullAutoRun(params.directory,sessionID,"reactive ESCALATE_TO_HUMAN"),event.full_auto_status_after="terminated";recordFullAutoOversight(params.directory,sessionID,params.parsed.verdict,`reactive ${params.escalationType}`)}if(await writeFullAutoOversightEvent(params.directory,event),params.escalationType==="phase_completion"&&params.parsed.verdict==="APPROVED"&&typeof phase==="number")await writeFullAutoOversightEvidence(params.directory,phase,event)}init_guardrails2();function isPartsShape(message){let info=message.info;return typeof info==="object"&&info!==null&&typeof info.role==="string"&&Array.isArray(message.parts)}function getRole(message){if(isPartsShape(message))return message.info.role;return message.role}function isToolResultSystemMessage(message){if(isPartsShape(message))return!1;let flat=message;return flat.tool_call_id!==void 0||flat.name!==void 0}function getSystemText(message){if(isPartsShape(message)){let texts=message.parts.filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text.trim()).filter((t)=>t.length>0);return texts.length>0?texts.join(`
5314
+ `;fs81.writeFileSync(reportPath,reportContent,"utf-8"),log(`[full-auto-intercept] Escalation report written to: ${reportPath}`)}catch(error93){error48("[full-auto-intercept] Failed to write escalation report:",error93 instanceof Error?error93.message:String(error93))}}async function handleEscalation(directory,reason,sessionID,architectOutput,interactionCount,deadlockCount,escalationMode,phase){if(telemetry.autoOversightEscalation(sessionID??"unknown",reason,interactionCount,deadlockCount,phase),await writeEscalationReport(directory,reason,architectOutput,interactionCount,deadlockCount,phase),sessionID){if(!loadFullAutoRunState(directory,sessionID))startFullAutoRun(directory,sessionID,{enabled:!0});recordFullAutoEscalation(directory,sessionID,{reason,interactionCount,deadlockCount,phase})}if(escalationMode==="terminate"){if(error48(`[full-auto-intercept] ESCALATION (terminate mode) — reason: ${reason}, session: ${sessionID}`),sessionID){if(!loadFullAutoRunState(directory,sessionID))startFullAutoRun(directory,sessionID,{enabled:!0});terminateFullAutoRun(directory,sessionID,reason)}return!0}if(warn(`[full-auto-intercept] ESCALATION (pause mode) — reason: ${reason}, session: ${sessionID}`),sessionID){if(!loadFullAutoRunState(directory,sessionID))startFullAutoRun(directory,sessionID,{enabled:!0});pauseFullAutoRun(directory,sessionID,reason)}return!0}var reactiveOversightSequence=0;async function mirrorReactiveVerdictToV2(params){reactiveOversightSequence+=1;let triggerSource=params.escalationType==="phase_completion"?"phase_boundary":"text_pattern",sessionID="",phase,planID;try{let filePath=validateSwarmPath(params.directory,"full-auto-state.json");if(fs81.existsSync(filePath)){let raw=fs81.readFileSync(filePath,"utf-8"),persisted=JSON.parse(raw);if(persisted.sessions){let callerSid=params.sessionID;if(callerSid&&persisted.sessions[callerSid]){let rec=persisted.sessions[callerSid];if(rec.status==="running")sessionID=callerSid,phase=rec.currentPhase,planID=rec.planID}else if(!callerSid)for(let sid of Object.keys(persisted.sessions)){let rec=persisted.sessions[sid];if(rec?.status==="running"){sessionID=sid,phase=rec.currentPhase,planID=rec.planID;break}}}}}catch{}if(!sessionID)return;let decision=(()=>{if(params.parsed.escalationNeeded||params.parsed.verdict==="ESCALATE_TO_HUMAN")return"escalate_human";if(params.parsed.verdict==="APPROVED"||params.parsed.verdict==="ANSWER")return"allow";if(params.parsed.verdict==="BLOCKED")return"pause";if(params.parsed.verdict==="PENDING")return"pending";return"deny"})(),beforeStatus=sessionID?loadFullAutoRunState(params.directory,sessionID)?.status:void 0,event={type:"full_auto_oversight",timestamp:new Date().toISOString(),session_id:sessionID,plan_id:planID,phase,trigger_source:triggerSource,trigger_reason:`reactive intercept (${params.escalationType})`,critic_agent:params.oversightAgentName,critic_model:params.criticModel,verdict:params.parsed.verdict,reasoning:params.parsed.reasoning,evidence_checked:params.parsed.evidenceChecked,anti_patterns_detected:params.parsed.antiPatternsDetected,escalation_needed:params.parsed.escalationNeeded,decision,full_auto_status_before:beforeStatus,full_auto_status_after:beforeStatus,oversight_sequence:reactiveOversightSequence};if(sessionID){if(decision==="pause")pauseFullAutoRun(params.directory,sessionID,`reactive verdict ${params.parsed.verdict}`),event.full_auto_status_after="paused";else if(decision==="escalate_human")terminateFullAutoRun(params.directory,sessionID,"reactive ESCALATE_TO_HUMAN"),event.full_auto_status_after="terminated";recordFullAutoOversight(params.directory,sessionID,params.parsed.verdict,`reactive ${params.escalationType}`)}if(await writeFullAutoOversightEvent(params.directory,event),params.escalationType==="phase_completion"&&params.parsed.verdict==="APPROVED"&&typeof phase==="number")await writeFullAutoOversightEvidence(params.directory,phase,event)}init_guardrails2();function isPartsShape(message){let info=message.info;return typeof info==="object"&&info!==null&&typeof info.role==="string"&&Array.isArray(message.parts)}function getRole(message){if(isPartsShape(message))return message.info.role;return message.role}function isToolResultSystemMessage(message){if(isPartsShape(message))return!1;let flat=message;return flat.tool_call_id!==void 0||flat.name!==void 0}function getSystemText(message){if(isPartsShape(message)){let texts=message.parts.filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text.trim()).filter((t)=>t.length>0);return texts.length>0?texts.join(`
5315
5315
  `):null}let content=message.content;if(typeof content==="string"){let trimmed=content.trim();return trimmed.length>0?trimmed:null}if(Array.isArray(content)){let texts=content.filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text.trim()).filter((t)=>t.length>0);return texts.length>0?texts.join(`
5316
5316
  `):null}return null}function isWhitespaceOnlySystem(message){if(getRole(message)!=="system")return!1;if(isPartsShape(message))return message.parts.length>0&&message.parts.every((part)=>part.type!=="text"||typeof part.text!=="string"||part.text.trim().length===0);let content=message.content;return typeof content==="string"&&content.trim().length===0}function buildConsolidatedSystem(firstSystem,mergedText){if(isPartsShape(firstSystem))return{...firstSystem,info:{...firstSystem.info,role:"system"},parts:[{type:"text",text:mergedText}]};return{role:"system",content:mergedText,...Object.fromEntries(Object.entries(firstSystem).filter(([key])=>key!=="role"&&key!=="content"&&key!=="name"&&key!=="tool_call_id"))}}function consolidateSystemMessages(messages){if(messages.length>0&&getRole(messages[0])==="system"&&getSystemText(messages[0])!==null&&(isPartsShape(messages[0])||typeof messages[0].content==="string")){if(messages.filter((m)=>getRole(m)==="system").length===1)return[...messages]}let systemMessageIndices=[],systemContents=[];for(let i=0;i<messages.length;i++){let message=messages[i];if(getRole(message)!=="system")continue;if(isToolResultSystemMessage(message))continue;let textContent=getSystemText(message);if(systemMessageIndices.push(i),textContent)systemContents.push(textContent)}if(systemContents.length===0)return messages.filter((m,idx)=>{if(getRole(m)!=="system")return!0;return idx===0});let mergedSystemContent=systemContents.join(`
5317
5317