opencode-swarm 7.138.0 → 7.138.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/{config-doctor-mb81xytp.js → config-doctor-m79sx8b2.js} +2 -2
- package/dist/cli/{curation-policy-qx23sc8b.js → curation-policy-dkx4s5va.js} +2 -2
- package/dist/cli/{curator-b9ascpbh.js → curator-jjf5x6bn.js} +14 -14
- package/dist/cli/{curator-llm-factory-r47q1hbd.js → curator-llm-factory-sprc6pm3.js} +14 -14
- package/dist/cli/{evidence-summary-service-1azhyeft.js → evidence-summary-service-6cttrkzw.js} +2 -2
- package/dist/cli/{guardrail-explain-ph1n3ryc.js → guardrail-explain-zs3hq02c.js} +15 -15
- package/dist/cli/{guardrail-log-ghgqaw3w.js → guardrail-log-90dnv508.js} +3 -3
- package/dist/cli/{hive-promoter-7x2zzhb7.js → hive-promoter-zkay2ffy.js} +14 -14
- package/dist/cli/{index-9zf5gfca.js → index-06zw53mf.js} +1 -1
- package/dist/cli/{index-bf0j2wd2.js → index-5fdztrpt.js} +2 -2
- package/dist/cli/{index-ag7ppc40.js → index-6f6nt0c9.js} +16 -16
- package/dist/cli/{index-7wzyf4dr.js → index-8xqnp3gw.js} +4 -4
- package/dist/cli/{index-7kgfvt3h.js → index-9vvskh03.js} +1 -1
- package/dist/cli/{index-whf5ecbw.js → index-aeyktf9q.js} +1 -1
- package/dist/cli/{index-z55s5719.js → index-d4t92fa3.js} +2 -2
- package/dist/cli/{index-xz0zjrdr.js → index-e2eedz1b.js} +1 -1
- package/dist/cli/{index-6nenabrm.js → index-e78pqbkj.js} +1 -1
- package/dist/cli/{index-k5jrywpr.js → index-gprxjmm7.js} +6 -1
- package/dist/cli/{index-cdx3aqj5.js → index-kqzzdxc1.js} +1 -1
- package/dist/cli/{index-sp7s1vk3.js → index-mnw8g9bs.js} +609 -213
- package/dist/cli/{index-4xs9e82s.js → index-mzqgtzxq.js} +3 -3
- package/dist/cli/{index-hmapndcz.js → index-navw2ezf.js} +5 -5
- package/dist/cli/{index-npgjk6vc.js → index-p7fn5byt.js} +1 -1
- package/dist/cli/{index-2vzgvscz.js → index-vmff7b40.js} +3 -3
- package/dist/cli/{index-ca6qmxd8.js → index-vp3mwsd1.js} +1 -1
- package/dist/cli/{index-fmh15wxb.js → index-y06a43sk.js} +1 -1
- package/dist/cli/index.js +14 -14
- package/dist/cli/{knowledge-escalator-pqskjp6y.js → knowledge-escalator-6y5x8vat.js} +3 -3
- package/dist/cli/{knowledge-events-ahpxnqjd.js → knowledge-events-bnr4weyn.js} +1 -1
- package/dist/cli/{knowledge-store-27aynbeg.js → knowledge-store-4mcmb2rj.js} +1 -1
- package/dist/cli/{knowledge-validator-4saz53kh.js → knowledge-validator-pf377mtx.js} +4 -4
- package/dist/cli/{scan-cursor-ngykkd7f.js → scan-cursor-we0561wc.js} +2 -2
- package/dist/cli/{schema-p82ntfy9.js → schema-1xtxr4d9.js} +1 -1
- package/dist/cli/{skill-generator-r19a1zje.js → skill-generator-kns0dae2.js} +5 -5
- package/dist/config/evidence-schema.d.ts +15 -0
- package/dist/index.js +20 -20
- package/dist/services/preflight-service.d.ts +2 -0
- package/dist/tools/pre-check-batch.d.ts +2 -0
- package/dist/tools/secretscan.d.ts +17 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.138.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","evaluation-fixtures",".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/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","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","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.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","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"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"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, 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_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},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_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately 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. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_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)}var MAX_MERGE_DEPTH=10;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,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.138.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/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/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","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","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.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","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"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"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, 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_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},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_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately 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. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_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)}var MAX_MERGE_DEPTH=10;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,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -155,7 +155,7 @@ Audit (no architect needed): \`/swarm epic status | last | decide | calibration\
|
|
|
155
155
|
|
|
156
156
|
`)}doc.write("payload.value = newResult;"),doc.write("return payload;");let fn2=doc.compile();return(payload,ctx)=>fn2(shape,payload,ctx)},fastpass,isObject2=isObject,jit=!globalConfig.jitless,fastEnabled=jit&&allowsEval.value,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject2(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;if(jit&&fastEnabled&&ctx?.async===!1&&ctx.jitless!==!0){if(!fastpass)fastpass=generateFastpass(def.shape);if(payload=fastpass(payload,ctx),!catchall)return payload;return handleCatchall([],input,payload,ctx,value,inst)}return superParse(payload,ctx)}});$ZodUnion=$constructor("$ZodUnion",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),defineLazy(inst._zod,"optout",()=>def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),defineLazy(inst._zod,"values",()=>{if(def.options.every((o)=>o._zod.values))return new Set(def.options.flatMap((option)=>Array.from(option._zod.values)));return}),defineLazy(inst._zod,"pattern",()=>{if(def.options.every((o)=>o._zod.pattern)){let patterns=def.options.map((o)=>o._zod.pattern);return new RegExp(`^(${patterns.map((p)=>cleanRegex(p.source)).join("|")})$`)}return});let single=def.options.length===1,first=def.options[0]._zod.run;inst._zod.parse=(payload,ctx)=>{if(single)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else{if(result.issues.length===0)return result;results.push(result)}}if(!async)return handleUnionResults(results,payload,inst,ctx);return Promise.all(results).then((results2)=>{return handleUnionResults(results2,payload,inst,ctx)})}});$ZodXor=$constructor("$ZodXor",(inst,def)=>{$ZodUnion.init(inst,def),def.inclusive=!1;let single=def.options.length===1,first=def.options[0]._zod.run;inst._zod.parse=(payload,ctx)=>{if(single)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else results.push(result)}if(!async)return handleExclusiveUnionResults(results,payload,inst,ctx);return Promise.all(results).then((results2)=>{return handleExclusiveUnionResults(results2,payload,inst,ctx)})}}),$ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(inst,def)=>{def.inclusive=!1,$ZodUnion.init(inst,def);let _super=inst._zod.parse;defineLazy(inst._zod,"propValues",()=>{let propValues={};for(let option of def.options){let pv=option._zod.propValues;if(!pv||Object.keys(pv).length===0)throw Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(let[k,v]of Object.entries(pv)){if(!propValues[k])propValues[k]=new Set;for(let val of v)propValues[k].add(val)}}return propValues});let disc=cached(()=>{let opts=def.options,map=new Map;for(let o of opts){let values=o._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);for(let v of values){if(map.has(v))throw Error(`Duplicate discriminator value "${String(v)}"`);map.set(v,o)}}return map});inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isObject(input))return payload.issues.push({code:"invalid_type",expected:"object",input,inst}),payload;let opt=disc.value.get(input?.[def.discriminator]);if(opt)return opt._zod.run(payload,ctx);if(def.unionFallback)return _super(payload,ctx);return payload.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:def.discriminator,input,path:[def.discriminator],inst}),payload}}),$ZodIntersection=$constructor("$ZodIntersection",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value,left=def.left._zod.run({value:input,issues:[]},ctx),right=def.right._zod.run({value:input,issues:[]},ctx);if(left instanceof Promise||right instanceof Promise)return Promise.all([left,right]).then(([left2,right2])=>{return handleIntersectionResults(payload,left2,right2)});return handleIntersectionResults(payload,left,right)}});$ZodTuple=$constructor("$ZodTuple",(inst,def)=>{$ZodType.init(inst,def);let items=def.items;inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({input,inst,expected:"tuple",code:"invalid_type"}),payload;payload.value=[];let proms=[],reversedIndex=[...items].reverse().findIndex((item)=>item._zod.optin!=="optional"),optStart=reversedIndex===-1?0:items.length-reversedIndex;if(!def.rest){let tooBig=input.length>items.length,tooSmall=input.length<optStart-1;if(tooBig||tooSmall)return payload.issues.push({...tooBig?{code:"too_big",maximum:items.length,inclusive:!0}:{code:"too_small",minimum:items.length},input,inst,origin:"array"}),payload}let i=-1;for(let item of items){if(i++,i>=input.length){if(i>=optStart)continue}let result=item._zod.run({value:input[i],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleTupleResult(result2,payload,i)));else handleTupleResult(result,payload,i)}if(def.rest){let rest=input.slice(items.length);for(let el of rest){i++;let result=def.rest._zod.run({value:el,issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleTupleResult(result2,payload,i)));else handleTupleResult(result,payload,i)}}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodRecord=$constructor("$ZodRecord",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isPlainObject(input))return payload.issues.push({expected:"record",code:"invalid_type",input,inst}),payload;let proms=[],values=def.keyType._zod.values;if(values){payload.value={};let recordKeys=new Set;for(let key of values)if(typeof key==="string"||typeof key==="number"||typeof key==="symbol"){recordKeys.add(typeof key==="number"?key.toString():key);let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>{if(result2.issues.length)payload.issues.push(...prefixIssues(key,result2.issues));payload.value[key]=result2.value}));else{if(result.issues.length)payload.issues.push(...prefixIssues(key,result.issues));payload.value[key]=result.value}}let unrecognized;for(let key in input)if(!recordKeys.has(key))unrecognized=unrecognized??[],unrecognized.push(key);if(unrecognized&&unrecognized.length>0)payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized})}else{payload.value={};for(let key of Reflect.ownKeys(input)){if(key==="__proto__")continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof key==="string"&&number.test(key)&&keyResult.issues.length){let retryResult=def.keyType._zod.run({value:Number(key),issues:[]},ctx);if(retryResult instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(retryResult.issues.length===0)keyResult=retryResult}if(keyResult.issues.length){if(def.mode==="loose")payload.value[key]=input[key];else payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map((iss)=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>{if(result2.issues.length)payload.issues.push(...prefixIssues(key,result2.issues));payload.value[keyResult.value]=result2.value}));else{if(result.issues.length)payload.issues.push(...prefixIssues(key,result.issues));payload.value[keyResult.value]=result.value}}}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}}),$ZodMap=$constructor("$ZodMap",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!(input instanceof Map))return payload.issues.push({expected:"map",code:"invalid_type",input,inst}),payload;let proms=[];payload.value=new Map;for(let[key,value]of input){let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx),valueResult=def.valueType._zod.run({value,issues:[]},ctx);if(keyResult instanceof Promise||valueResult instanceof Promise)proms.push(Promise.all([keyResult,valueResult]).then(([keyResult2,valueResult2])=>{handleMapResult(keyResult2,valueResult2,payload,key,input,inst,ctx)}));else handleMapResult(keyResult,valueResult,payload,key,input,inst,ctx)}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodSet=$constructor("$ZodSet",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!(input instanceof Set))return payload.issues.push({input,inst,expected:"set",code:"invalid_type"}),payload;let proms=[];payload.value=new Set;for(let item of input){let result=def.valueType._zod.run({value:item,issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleSetResult(result2,payload)));else handleSetResult(result,payload)}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodEnum=$constructor("$ZodEnum",(inst,def)=>{$ZodType.init(inst,def);let values=getEnumValues(def.entries),valuesSet=new Set(values);inst._zod.values=valuesSet,inst._zod.pattern=new RegExp(`^(${values.filter((k)=>propertyKeyTypes.has(typeof k)).map((o)=>typeof o==="string"?escapeRegex(o):o.toString()).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(valuesSet.has(input))return payload;return payload.issues.push({code:"invalid_value",values,input,inst}),payload}}),$ZodLiteral=$constructor("$ZodLiteral",(inst,def)=>{if($ZodType.init(inst,def),def.values.length===0)throw Error("Cannot create literal schema with no valid values");let values=new Set(def.values);inst._zod.values=values,inst._zod.pattern=new RegExp(`^(${def.values.map((o)=>typeof o==="string"?escapeRegex(o):o?escapeRegex(o.toString()):String(o)).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(values.has(input))return payload;return payload.issues.push({code:"invalid_value",values:def.values,input,inst}),payload}}),$ZodFile=$constructor("$ZodFile",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(input instanceof File)return payload;return payload.issues.push({expected:"file",code:"invalid_type",input,inst}),payload}}),$ZodTransform=$constructor("$ZodTransform",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);let _out=def.transform(payload.value,payload);if(ctx.async)return(_out instanceof Promise?_out:Promise.resolve(_out)).then((output2)=>{return payload.value=output2,payload});if(_out instanceof Promise)throw new $ZodAsyncError;return payload.value=_out,payload}});$ZodOptional=$constructor("$ZodOptional",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",inst._zod.optout="optional",defineLazy(inst._zod,"values",()=>{return def.innerType._zod.values?new Set([...def.innerType._zod.values,void 0]):void 0}),defineLazy(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)})?$`):void 0}),inst._zod.parse=(payload,ctx)=>{if(def.innerType._zod.optin==="optional"){let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((r)=>handleOptionalResult(r,payload.value));return handleOptionalResult(result,payload.value)}if(payload.value===void 0)return payload;return def.innerType._zod.run(payload,ctx)}}),$ZodExactOptional=$constructor("$ZodExactOptional",(inst,def)=>{$ZodOptional.init(inst,def),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),defineLazy(inst._zod,"pattern",()=>def.innerType._zod.pattern),inst._zod.parse=(payload,ctx)=>{return def.innerType._zod.run(payload,ctx)}}),$ZodNullable=$constructor("$ZodNullable",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.innerType._zod.optin),defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)}|null)$`):void 0}),defineLazy(inst._zod,"values",()=>{return def.innerType._zod.values?new Set([...def.innerType._zod.values,null]):void 0}),inst._zod.parse=(payload,ctx)=>{if(payload.value===null)return payload;return def.innerType._zod.run(payload,ctx)}}),$ZodDefault=$constructor("$ZodDefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)return payload.value=def.defaultValue,payload;let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>handleDefaultResult(result2,def));return handleDefaultResult(result,def)}});$ZodPrefault=$constructor("$ZodPrefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)payload.value=def.defaultValue;return def.innerType._zod.run(payload,ctx)}}),$ZodNonOptional=$constructor("$ZodNonOptional",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>{let v=def.innerType._zod.values;return v?new Set([...v].filter((x)=>x!==void 0)):void 0}),inst._zod.parse=(payload,ctx)=>{let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>handleNonOptionalResult(result2,inst));return handleNonOptionalResult(result,inst)}});$ZodSuccess=$constructor("$ZodSuccess",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError("ZodSuccess");let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>{return payload.value=result2.issues.length===0,payload});return payload.value=result.issues.length===0,payload}}),$ZodCatch=$constructor("$ZodCatch",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.innerType._zod.optin),defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>{if(payload.value=result2.value,result2.issues.length)payload.value=def.catchValue({...payload,error:{issues:result2.issues.map((iss)=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[];return payload});if(payload.value=result.value,result.issues.length)payload.value=def.catchValue({...payload,error:{issues:result.issues.map((iss)=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[];return payload}}),$ZodNaN=$constructor("$ZodNaN",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="number"||!Number.isNaN(payload.value))return payload.issues.push({input:payload.value,inst,expected:"nan",code:"invalid_type"}),payload;return payload}}),$ZodPipe=$constructor("$ZodPipe",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>def.in._zod.values),defineLazy(inst._zod,"optin",()=>def.in._zod.optin),defineLazy(inst._zod,"optout",()=>def.out._zod.optout),defineLazy(inst._zod,"propValues",()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){let right=def.out._zod.run(payload,ctx);if(right instanceof Promise)return right.then((right2)=>handlePipeResult(right2,def.in,ctx));return handlePipeResult(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);if(left instanceof Promise)return left.then((left2)=>handlePipeResult(left2,def.out,ctx));return handlePipeResult(left,def.out,ctx)}});$ZodCodec=$constructor("$ZodCodec",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>def.in._zod.values),defineLazy(inst._zod,"optin",()=>def.in._zod.optin),defineLazy(inst._zod,"optout",()=>def.out._zod.optout),defineLazy(inst._zod,"propValues",()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if((ctx.direction||"forward")==="forward"){let left=def.in._zod.run(payload,ctx);if(left instanceof Promise)return left.then((left2)=>handleCodecAResult(left2,def,ctx));return handleCodecAResult(left,def,ctx)}else{let right=def.out._zod.run(payload,ctx);if(right instanceof Promise)return right.then((right2)=>handleCodecAResult(right2,def,ctx));return handleCodecAResult(right,def,ctx)}}});$ZodReadonly=$constructor("$ZodReadonly",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"propValues",()=>def.innerType._zod.propValues),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),defineLazy(inst._zod,"optin",()=>def.innerType?._zod?.optin),defineLazy(inst._zod,"optout",()=>def.innerType?._zod?.optout),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then(handleReadonlyResult);return handleReadonlyResult(result)}});$ZodTemplateLiteral=$constructor("$ZodTemplateLiteral",(inst,def)=>{$ZodType.init(inst,def);let regexParts=[];for(let part of def.parts)if(typeof part==="object"&&part!==null){if(!part._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);let source=part._zod.pattern instanceof RegExp?part._zod.pattern.source:part._zod.pattern;if(!source)throw Error(`Invalid template literal part: ${part._zod.traits}`);let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;regexParts.push(source.slice(start,end))}else if(part===null||primitiveTypes.has(typeof part))regexParts.push(escapeRegex(`${part}`));else throw Error(`Invalid template literal part: ${part}`);inst._zod.pattern=new RegExp(`^${regexParts.join("")}$`),inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="string")return payload.issues.push({input:payload.value,inst,expected:"string",code:"invalid_type"}),payload;if(inst._zod.pattern.lastIndex=0,!inst._zod.pattern.test(payload.value))return payload.issues.push({input:payload.value,inst,code:"invalid_format",format:def.format??"template_literal",pattern:inst._zod.pattern.source}),payload;return payload}}),$ZodFunction=$constructor("$ZodFunction",(inst,def)=>{return $ZodType.init(inst,def),inst._def=def,inst._zod.def=def,inst.implement=(func)=>{if(typeof func!=="function")throw Error("implement() must be called with a function");return function(...args2){let parsedArgs=inst._def.input?parse(inst._def.input,args2):args2,result=Reflect.apply(func,this,parsedArgs);if(inst._def.output)return parse(inst._def.output,result);return result}},inst.implementAsync=(func)=>{if(typeof func!=="function")throw Error("implementAsync() must be called with a function");return async function(...args2){let parsedArgs=inst._def.input?await parseAsync(inst._def.input,args2):args2,result=await Reflect.apply(func,this,parsedArgs);if(inst._def.output)return await parseAsync(inst._def.output,result);return result}},inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="function")return payload.issues.push({code:"invalid_type",expected:"function",input:payload.value,inst}),payload;if(inst._def.output&&inst._def.output._zod.def.type==="promise")payload.value=inst.implementAsync(payload.value);else payload.value=inst.implement(payload.value);return payload},inst.input=(...args2)=>{let F=inst.constructor;if(Array.isArray(args2[0]))return new F({type:"function",input:new $ZodTuple({type:"tuple",items:args2[0],rest:args2[1]}),output:inst._def.output});return new F({type:"function",input:args2[0],output:inst._def.output})},inst.output=(output)=>{return new inst.constructor({type:"function",input:inst._def.input,output})},inst}),$ZodPromise=$constructor("$ZodPromise",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{return Promise.resolve(payload.value).then((inner)=>def.innerType._zod.run({value:inner,issues:[]},ctx))}}),$ZodLazy=$constructor("$ZodLazy",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"innerType",()=>def.getter()),defineLazy(inst._zod,"pattern",()=>inst._zod.innerType?._zod?.pattern),defineLazy(inst._zod,"propValues",()=>inst._zod.innerType?._zod?.propValues),defineLazy(inst._zod,"optin",()=>inst._zod.innerType?._zod?.optin??void 0),defineLazy(inst._zod,"optout",()=>inst._zod.innerType?._zod?.optout??void 0),inst._zod.parse=(payload,ctx)=>{return inst._zod.innerType._zod.run(payload,ctx)}}),$ZodCustom=$constructor("$ZodCustom",(inst,def)=>{$ZodCheck.init(inst,def),$ZodType.init(inst,def),inst._zod.parse=(payload,_)=>{return payload},inst._zod.check=(payload)=>{let input=payload.value,r=def.fn(input);if(r instanceof Promise)return r.then((r2)=>handleRefineResult(r2,payload,input,inst));handleRefineResult(r,payload,input,inst);return}})});function ar_default(){return{localeError:error()}}var error=()=>{let Sizable={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${issue2.expected}، ولكن تم إدخال ${received}`;return`مدخلات غير مقبولة: يفترض إدخال ${expected}، ولكن تم إدخال ${received}`}case"invalid_value":if(issue2.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive(issue2.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return` أكبر من اللازم: يفترض أن تكون ${issue2.origin??"القيمة"} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${issue2.origin??"القيمة"} ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`أصغر من اللازم: يفترض لـ ${issue2.origin} أن يكون ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`أصغر من اللازم: يفترض لـ ${issue2.origin} أن يكون ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${issue2.prefix}"`;if(_issue.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`;if(_issue.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`;if(_issue.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${issue2.divisor}`;case"unrecognized_keys":return`معرف${issue2.keys.length>1?"ات":""} غريب${issue2.keys.length>1?"ة":""}: ${joinValues(issue2.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${issue2.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${issue2.origin}`;default:return"مدخل غير مقبول"}}};var init_ar=__esm(()=>{init_util()});function az_default(){return{localeError:error2()}}var error2=()=>{let Sizable={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Yanlış dəyər: gözlənilən instanceof ${issue2.expected}, daxil olan ${received}`;return`Yanlış dəyər: gözlənilən ${expected}, daxil olan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Yanlış dəyər: gözlənilən ${stringifyPrimitive(issue2.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Çox böyük: gözlənilən ${issue2.origin??"dəyər"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"element"}`;return`Çox böyük: gözlənilən ${issue2.origin??"dəyər"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Çox kiçik: gözlənilən ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Çox kiçik: gözlənilən ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`;if(_issue.format==="ends_with")return`Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`;if(_issue.format==="includes")return`Yanlış mətn: "${_issue.includes}" daxil olmalıdır`;if(_issue.format==="regex")return`Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Yanlış ədəd: ${issue2.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${issue2.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};var init_az=__esm(()=>{init_util()});function getBelarusianPlural(count,one,few,many){let absCount=Math.abs(count),lastDigit=absCount%10,lastTwoDigits=absCount%100;if(lastTwoDigits>=11&&lastTwoDigits<=19)return many;if(lastDigit===1)return one;if(lastDigit>=2&&lastDigit<=4)return few;return many}function be_default(){return{localeError:error3()}}var error3=()=>{let Sizable={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},TypeDictionary={nan:"NaN",number:"лік",array:"масіў"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Няправільны ўвод: чакаўся instanceof ${issue2.expected}, атрымана ${received}`;return`Няправільны ўвод: чакаўся ${expected}, атрымана ${received}`}case"invalid_value":if(issue2.values.length===1)return`Няправільны ўвод: чакалася ${stringifyPrimitive(issue2.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing){let maxValue=Number(issue2.maximum),unit=getBelarusianPlural(maxValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Занадта вялікі: чакалася, што ${issue2.origin??"значэнне"} павінна ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`}return`Занадта вялікі: чакалася, што ${issue2.origin??"значэнне"} павінна быць ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing){let minValue=Number(issue2.minimum),unit=getBelarusianPlural(minValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Занадта малы: чакалася, што ${issue2.origin} павінна ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`}return`Занадта малы: чакалася, што ${issue2.origin} павінна быць ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`;if(_issue.format==="includes")return`Няправільны радок: павінен змяшчаць "${_issue.includes}"`;if(_issue.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`;return`Няправільны ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${issue2.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${issue2.keys.length>1?"ключы":"ключ"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${issue2.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${issue2.origin}`;default:return"Няправільны ўвод"}}};var init_be=__esm(()=>{init_util()});function bg_default(){return{localeError:error4()}}var error4=()=>{let Sizable={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},TypeDictionary={nan:"NaN",number:"число",array:"масив"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Невалиден вход: очакван instanceof ${issue2.expected}, получен ${received}`;return`Невалиден вход: очакван ${expected}, получен ${received}`}case"invalid_value":if(issue2.values.length===1)return`Невалиден вход: очакван ${stringifyPrimitive(issue2.values[0])}`;return`Невалидна опция: очаквано едно от ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Твърде голямо: очаква се ${issue2.origin??"стойност"} да съдържа ${adj}${issue2.maximum.toString()} ${sizing.unit??"елемента"}`;return`Твърде голямо: очаква се ${issue2.origin??"стойност"} да бъде ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Твърде малко: очаква се ${issue2.origin} да съдържа ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Твърде малко: очаква се ${issue2.origin} да бъде ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Невалиден низ: трябва да започва с "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Невалиден низ: трябва да завършва с "${_issue.suffix}"`;if(_issue.format==="includes")return`Невалиден низ: трябва да включва "${_issue.includes}"`;if(_issue.format==="regex")return`Невалиден низ: трябва да съвпада с ${_issue.pattern}`;let invalid_adj="Невалиден";if(_issue.format==="emoji")invalid_adj="Невалидно";if(_issue.format==="datetime")invalid_adj="Невалидно";if(_issue.format==="date")invalid_adj="Невалидна";if(_issue.format==="time")invalid_adj="Невалидно";if(_issue.format==="duration")invalid_adj="Невалидна";return`${invalid_adj} ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${issue2.divisor}`;case"unrecognized_keys":return`Неразпознат${issue2.keys.length>1?"и":""} ключ${issue2.keys.length>1?"ове":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${issue2.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${issue2.origin}`;default:return"Невалиден вход"}}};var init_bg=__esm(()=>{init_util()});function ca_default(){return{localeError:error5()}}var error5=()=>{let Sizable={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Tipus invàlid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`;return`Tipus invàlid: s'esperava ${expected}, s'ha rebut ${received}`}case"invalid_value":if(issue2.values.length===1)return`Valor invàlid: s'esperava ${stringifyPrimitive(issue2.values[0])}`;return`Opció invàlida: s'esperava una de ${joinValues(issue2.values," o ")}`;case"too_big":{let adj=issue2.inclusive?"com a màxim":"menys de",sizing=getSizing(issue2.origin);if(sizing)return`Massa gran: s'esperava que ${issue2.origin??"el valor"} contingués ${adj} ${issue2.maximum.toString()} ${sizing.unit??"elements"}`;return`Massa gran: s'esperava que ${issue2.origin??"el valor"} fos ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?"com a mínim":"més de",sizing=getSizing(issue2.origin);if(sizing)return`Massa petit: s'esperava que ${issue2.origin} contingués ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Format invàlid: ha de començar amb "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Format invàlid: ha d'acabar amb "${_issue.suffix}"`;if(_issue.format==="includes")return`Format invàlid: ha d'incloure "${_issue.includes}"`;if(_issue.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`;return`Format invàlid per a ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${issue2.divisor}`;case"unrecognized_keys":return`Clau${issue2.keys.length>1?"s":""} no reconeguda${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${issue2.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${issue2.origin}`;default:return"Entrada invàlida"}}};var init_ca=__esm(()=>{init_util()});function cs_default(){return{localeError:error6()}}var error6=()=>{let Sizable={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},TypeDictionary={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Neplatný vstup: očekáváno instanceof ${issue2.expected}, obdrženo ${received}`;return`Neplatný vstup: očekáváno ${expected}, obdrženo ${received}`}case"invalid_value":if(issue2.values.length===1)return`Neplatný vstup: očekáváno ${stringifyPrimitive(issue2.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Hodnota je příliš velká: ${issue2.origin??"hodnota"} musí mít ${adj}${issue2.maximum.toString()} ${sizing.unit??"prvků"}`;return`Hodnota je příliš velká: ${issue2.origin??"hodnota"} musí být ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Hodnota je příliš malá: ${issue2.origin??"hodnota"} musí mít ${adj}${issue2.minimum.toString()} ${sizing.unit??"prvků"}`;return`Hodnota je příliš malá: ${issue2.origin??"hodnota"} musí být ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Neplatný řetězec: musí začínat na "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Neplatný řetězec: musí končit na "${_issue.suffix}"`;if(_issue.format==="includes")return`Neplatný řetězec: musí obsahovat "${_issue.includes}"`;if(_issue.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`;return`Neplatný formát ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${issue2.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${issue2.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${issue2.origin}`;default:return"Neplatný vstup"}}};var init_cs=__esm(()=>{init_util()});function da_default(){return{localeError:error7()}}var error7=()=>{let Sizable={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`;return`Ugyldigt input: forventede ${expected}, fik ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ugyldig værdi: forventede ${stringifyPrimitive(issue2.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`For stor: forventede ${origin??"value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"elementer"}`;return`For stor: forventede ${origin??"value"} havde ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ugyldig streng: skal starte med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ugyldig streng: skal ende med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ugyldig streng: skal indeholde "${_issue.includes}"`;if(_issue.format==="regex")return`Ugyldig streng: skal matche mønsteret ${_issue.pattern}`;return`Ugyldig ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${issue2.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${issue2.origin}`;default:return"Ugyldigt input"}}};var init_da=__esm(()=>{init_util()});function de_default(){return{localeError:error8()}}var error8=()=>{let Sizable={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},TypeDictionary={nan:"NaN",number:"Zahl",array:"Array"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ungültige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`;return`Ungültige Eingabe: erwartet ${expected}, erhalten ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ungültige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`;return`Ungültige Option: erwartet eine von ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Zu groß: erwartet, dass ${issue2.origin??"Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${issue2.origin??"Wert"} ${adj}${issue2.maximum.toString()} ist`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`;return`Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ungültiger String: muss mit "${_issue.prefix}" beginnen`;if(_issue.format==="ends_with")return`Ungültiger String: muss mit "${_issue.suffix}" enden`;if(_issue.format==="includes")return`Ungültiger String: muss "${_issue.includes}" enthalten`;if(_issue.format==="regex")return`Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`;return`Ungültig: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;case"unrecognized_keys":return`${issue2.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${issue2.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${issue2.origin}`;default:return"Ungültige Eingabe"}}};var init_de=__esm(()=>{init_util()});function en_default(){return{localeError:error9()}}var error9=()=>{let Sizable={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return`Invalid input: expected ${expected}, received ${received}`}case"invalid_value":if(issue2.values.length===1)return`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;return`Invalid option: expected one of ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Too big: expected ${issue2.origin??"value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"}`;return`Too big: expected ${issue2.origin??"value"} to be ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Invalid string: must start with "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Invalid string: must end with "${_issue.suffix}"`;if(_issue.format==="includes")return`Invalid string: must include "${_issue.includes}"`;if(_issue.format==="regex")return`Invalid string: must match pattern ${_issue.pattern}`;return`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${issue2.divisor}`;case"unrecognized_keys":return`Unrecognized key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Invalid key in ${issue2.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${issue2.origin}`;default:return"Invalid input"}}};var init_en=__esm(()=>{init_util()});function eo_default(){return{localeError:error10()}}var error10=()=>{let Sizable={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},TypeDictionary={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Nevalida enigo: atendiĝis instanceof ${issue2.expected}, riceviĝis ${received}`;return`Nevalida enigo: atendiĝis ${expected}, riceviĝis ${received}`}case"invalid_value":if(issue2.values.length===1)return`Nevalida enigo: atendiĝis ${stringifyPrimitive(issue2.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Tro granda: atendiĝis ke ${issue2.origin??"valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${issue2.origin??"valoro"} havu ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Tro malgranda: atendiĝis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Tro malgranda: atendiĝis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${_issue.suffix}"`;if(_issue.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;if(_issue.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;return`Nevalida ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${issue2.divisor}`;case"unrecognized_keys":return`Nekonata${issue2.keys.length>1?"j":""} ŝlosilo${issue2.keys.length>1?"j":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${issue2.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${issue2.origin}`;default:return"Nevalida enigo"}}};var init_eo=__esm(()=>{init_util()});function es_default(){return{localeError:error11()}}var error11=()=>{let Sizable={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},TypeDictionary={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Entrada inválida: se esperaba instanceof ${issue2.expected}, recibido ${received}`;return`Entrada inválida: se esperaba ${expected}, recibido ${received}`}case"invalid_value":if(issue2.values.length===1)return`Entrada inválida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;return`Opción inválida: se esperaba una de ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`Demasiado grande: se esperaba que ${origin??"valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${origin??"valor"} fuera ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`Demasiado pequeño: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Demasiado pequeño: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Cadena inválida: debe comenzar con "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Cadena inválida: debe terminar en "${_issue.suffix}"`;if(_issue.format==="includes")return`Cadena inválida: debe incluir "${_issue.includes}"`;if(_issue.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`;return`Inválido ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${issue2.divisor}`;case"unrecognized_keys":return`Llave${issue2.keys.length>1?"s":""} desconocida${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Llave inválida en ${TypeDictionary[issue2.origin]??issue2.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${TypeDictionary[issue2.origin]??issue2.origin}`;default:return"Entrada inválida"}}};var init_es=__esm(()=>{init_util()});function fa_default(){return{localeError:error12()}}var error12=()=>{let Sizable={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},TypeDictionary={nan:"NaN",number:"عدد",array:"آرایه"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`ورودی نامعتبر: میبایست instanceof ${issue2.expected} میبود، ${received} دریافت شد`;return`ورودی نامعتبر: میبایست ${expected} میبود، ${received} دریافت شد`}case"invalid_value":if(issue2.values.length===1)return`ورودی نامعتبر: میبایست ${stringifyPrimitive(issue2.values[0])} میبود`;return`گزینه نامعتبر: میبایست یکی از ${joinValues(issue2.values,"|")} میبود`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`خیلی بزرگ: ${issue2.origin??"مقدار"} باید ${adj}${issue2.maximum.toString()} ${sizing.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${issue2.origin??"مقدار"} باید ${adj}${issue2.maximum.toString()} باشد`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`خیلی کوچک: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} ${sizing.unit} باشد`;return`خیلی کوچک: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} باشد`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`;if(_issue.format==="ends_with")return`رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`;if(_issue.format==="includes")return`رشته نامعتبر: باید شامل "${_issue.includes}" باشد`;if(_issue.format==="regex")return`رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`;return`${FormatDictionary[_issue.format]??issue2.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${issue2.divisor} باشد`;case"unrecognized_keys":return`کلید${issue2.keys.length>1?"های":""} ناشناس: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${issue2.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${issue2.origin}`;default:return"ورودی نامعتبر"}}};var init_fa=__esm(()=>{init_util()});function fi_default(){return{localeError:error13()}}var error13=()=>{let Sizable={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`;return`Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`}case"invalid_value":if(issue2.values.length===1)return`Virheellinen syöte: täytyy olla ${stringifyPrimitive(issue2.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim();return`Liian suuri: arvon täytyy olla ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim();return`Liian pieni: arvon täytyy olla ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${_issue.suffix}"`;if(_issue.format==="includes")return`Virheellinen syöte: täytyy sisältää "${_issue.includes}"`;if(_issue.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`;return`Virheellinen ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${issue2.divisor} monikerta`;case"unrecognized_keys":return`${issue2.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};var init_fi=__esm(()=>{init_util()});function fr_default(){return{localeError:error14()}}var error14=()=>{let Sizable={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},TypeDictionary={nan:"NaN",number:"nombre",array:"tableau"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Entrée invalide : instanceof ${issue2.expected} attendu, ${received} reçu`;return`Entrée invalide : ${expected} attendu, ${received} reçu`}case"invalid_value":if(issue2.values.length===1)return`Entrée invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;return`Option invalide : une valeur parmi ${joinValues(issue2.values,"|")} attendue`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Trop grand : ${issue2.origin??"valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"élément(s)"}`;return`Trop grand : ${issue2.origin??"valeur"} doit être ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Trop petit : ${issue2.origin} doit être ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Chaîne invalide : doit commencer par "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chaîne invalide : doit se terminer par "${_issue.suffix}"`;if(_issue.format==="includes")return`Chaîne invalide : doit inclure "${_issue.includes}"`;if(_issue.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${issue2.divisor}`;case"unrecognized_keys":return`Clé${issue2.keys.length>1?"s":""} non reconnue${issue2.keys.length>1?"s":""} : ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${issue2.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${issue2.origin}`;default:return"Entrée invalide"}}};var init_fr=__esm(()=>{init_util()});function fr_CA_default(){return{localeError:error15()}}var error15=()=>{let Sizable={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Entrée invalide : attendu instanceof ${issue2.expected}, reçu ${received}`;return`Entrée invalide : attendu ${expected}, reçu ${received}`}case"invalid_value":if(issue2.values.length===1)return`Entrée invalide : attendu ${stringifyPrimitive(issue2.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"≤":"<",sizing=getSizing(issue2.origin);if(sizing)return`Trop grand : attendu que ${issue2.origin??"la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`;return`Trop grand : attendu que ${issue2.origin??"la valeur"} soit ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?"≥":">",sizing=getSizing(issue2.origin);if(sizing)return`Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Chaîne invalide : doit commencer par "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chaîne invalide : doit se terminer par "${_issue.suffix}"`;if(_issue.format==="includes")return`Chaîne invalide : doit inclure "${_issue.includes}"`;if(_issue.format==="regex")return`Chaîne invalide : doit correspondre au motif ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${issue2.divisor}`;case"unrecognized_keys":return`Clé${issue2.keys.length>1?"s":""} non reconnue${issue2.keys.length>1?"s":""} : ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${issue2.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${issue2.origin}`;default:return"Entrée invalide"}}};var init_fr_CA=__esm(()=>{init_util()});function he_default(){return{localeError:error16()}}var error16=()=>{let TypeNames={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},Sizable={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},typeEntry=(t)=>t?TypeNames[t]:void 0,typeLabel=(t)=>{let e=typeEntry(t);if(e)return e.label;return t??TypeNames.unknown.label},withDefinite=(t)=>`ה${typeLabel(t)}`,verbFor=(t)=>{return(typeEntry(t)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},getSizing=(origin)=>{if(!origin)return null;return Sizable[origin]??null},FormatDictionary={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expectedKey=issue2.expected,expected=TypeDictionary[expectedKey??""]??typeLabel(expectedKey),receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??TypeNames[receivedType]?.label??receivedType;if(/^[A-Z]/.test(issue2.expected))return`קלט לא תקין: צריך להיות instanceof ${issue2.expected}, התקבל ${received}`;return`קלט לא תקין: צריך להיות ${expected}, התקבל ${received}`}case"invalid_value":{if(issue2.values.length===1)return`ערך לא תקין: הערך חייב להיות ${stringifyPrimitive(issue2.values[0])}`;let stringified=issue2.values.map((v)=>stringifyPrimitive(v));if(issue2.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${stringified[0]} או ${stringified[1]}`;let lastValue=stringified[stringified.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${stringified.slice(0,-1).join(", ")} או ${lastValue}`}case"too_big":{let sizing=getSizing(issue2.origin),subject=withDefinite(issue2.origin??"value");if(issue2.origin==="string")return`${sizing?.longLabel??"ארוך"} מדי: ${subject} צריכה להכיל ${issue2.maximum.toString()} ${sizing?.unit??""} ${issue2.inclusive?"או פחות":"לכל היותר"}`.trim();if(issue2.origin==="number"){let comparison=issue2.inclusive?`קטן או שווה ל-${issue2.maximum}`:`קטן מ-${issue2.maximum}`;return`גדול מדי: ${subject} צריך להיות ${comparison}`}if(issue2.origin==="array"||issue2.origin==="set"){let verb=issue2.origin==="set"?"צריכה":"צריך",comparison=issue2.inclusive?`${issue2.maximum} ${sizing?.unit??""} או פחות`:`פחות מ-${issue2.maximum} ${sizing?.unit??""}`;return`גדול מדי: ${subject} ${verb} להכיל ${comparison}`.trim()}let adj=issue2.inclusive?"<=":"<",be=verbFor(issue2.origin??"value");if(sizing?.unit)return`${sizing.longLabel} מדי: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;return`${sizing?.longLabel??"גדול"} מדי: ${subject} ${be} ${adj}${issue2.maximum.toString()}`}case"too_small":{let sizing=getSizing(issue2.origin),subject=withDefinite(issue2.origin??"value");if(issue2.origin==="string")return`${sizing?.shortLabel??"קצר"} מדי: ${subject} צריכה להכיל ${issue2.minimum.toString()} ${sizing?.unit??""} ${issue2.inclusive?"או יותר":"לפחות"}`.trim();if(issue2.origin==="number"){let comparison=issue2.inclusive?`גדול או שווה ל-${issue2.minimum}`:`גדול מ-${issue2.minimum}`;return`קטן מדי: ${subject} צריך להיות ${comparison}`}if(issue2.origin==="array"||issue2.origin==="set"){let verb=issue2.origin==="set"?"צריכה":"צריך";if(issue2.minimum===1&&issue2.inclusive){let singularPhrase=issue2.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${subject} ${verb} להכיל ${singularPhrase}`}let comparison=issue2.inclusive?`${issue2.minimum} ${sizing?.unit??""} או יותר`:`יותר מ-${issue2.minimum} ${sizing?.unit??""}`;return`קטן מדי: ${subject} ${verb} להכיל ${comparison}`.trim()}let adj=issue2.inclusive?">=":">",be=verbFor(issue2.origin??"value");if(sizing?.unit)return`${sizing.shortLabel} מדי: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`${sizing?.shortLabel??"קטן"} מדי: ${subject} ${be} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${_issue.prefix}"`;if(_issue.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${_issue.suffix}"`;if(_issue.format==="includes")return`המחרוזת חייבת לכלול "${_issue.includes}"`;if(_issue.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${_issue.pattern}`;let nounEntry=FormatDictionary[_issue.format],noun=nounEntry?.label??_issue.format,adjective=(nounEntry?.gender??"m")==="f"?"תקינה":"תקין";return`${noun} לא ${adjective}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${issue2.divisor}`;case"unrecognized_keys":return`מפתח${issue2.keys.length>1?"ות":""} לא מזוה${issue2.keys.length>1?"ים":"ה"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${withDefinite(issue2.origin??"array")}`;default:return"קלט לא תקין"}}};var init_he=__esm(()=>{init_util()});function hu_default(){return{localeError:error17()}}var error17=()=>{let Sizable={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},TypeDictionary={nan:"NaN",number:"szám",array:"tömb"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Érvénytelen bemenet: a várt érték instanceof ${issue2.expected}, a kapott érték ${received}`;return`Érvénytelen bemenet: a várt érték ${expected}, a kapott érték ${received}`}case"invalid_value":if(issue2.values.length===1)return`Érvénytelen bemenet: a várt érték ${stringifyPrimitive(issue2.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Túl nagy: ${issue2.origin??"érték"} mérete túl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${issue2.origin??"érték"} túl nagy: ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Túl kicsi: a bemeneti érték ${issue2.origin} mérete túl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Túl kicsi: a bemeneti érték ${issue2.origin} túl kicsi ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`;if(_issue.format==="ends_with")return`Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`;if(_issue.format==="includes")return`Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`;if(_issue.format==="regex")return`Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`;return`Érvénytelen ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Érvénytelen szám: ${issue2.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${issue2.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${issue2.origin}`;default:return"Érvénytelen bemenet"}}};var init_hu=__esm(()=>{init_util()});function getArmenianPlural(count,one,many){return Math.abs(count)===1?one:many}function withDefiniteArticle(word){if(!word)return"";let vowels=["ա","ե","ը","ի","ո","ու","օ"],lastChar=word[word.length-1];return word+(vowels.includes(lastChar)?"ն":"ը")}function hy_default(){return{localeError:error18()}}var error18=()=>{let Sizable={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},TypeDictionary={nan:"NaN",number:"թիվ",array:"զանգված"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${issue2.expected}, ստացվել է ${received}`;return`Սխալ մուտքագրում․ սպասվում էր ${expected}, ստացվել է ${received}`}case"invalid_value":if(issue2.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${stringifyPrimitive(issue2.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing){let maxValue=Number(issue2.maximum),unit=getArmenianPlural(maxValue,sizing.unit.one,sizing.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin??"արժեք")} կունենա ${adj}${issue2.maximum.toString()} ${unit}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin??"արժեք")} լինի ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing){let minValue=Number(issue2.minimum),unit=getArmenianPlural(minValue,sizing.unit.one,sizing.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin)} կունենա ${adj}${issue2.minimum.toString()} ${unit}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin)} լինի ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${_issue.prefix}"-ով`;if(_issue.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${_issue.suffix}"-ով`;if(_issue.format==="includes")return`Սխալ տող․ պետք է պարունակի "${_issue.includes}"`;if(_issue.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${_issue.pattern} ձևաչափին`;return`Սխալ ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${issue2.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${issue2.keys.length>1?"ներ":""}. ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${withDefiniteArticle(issue2.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${withDefiniteArticle(issue2.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};var init_hy=__esm(()=>{init_util()});function id_default(){return{localeError:error19()}}var error19=()=>{let Sizable={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`;return`Input tidak valid: diharapkan ${expected}, diterima ${received}`}case"invalid_value":if(issue2.values.length===1)return`Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Terlalu besar: diharapkan ${issue2.origin??"value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemen"}`;return`Terlalu besar: diharapkan ${issue2.origin??"value"} menjadi ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`String tidak valid: harus dimulai dengan "${_issue.prefix}"`;if(_issue.format==="ends_with")return`String tidak valid: harus berakhir dengan "${_issue.suffix}"`;if(_issue.format==="includes")return`String tidak valid: harus menyertakan "${_issue.includes}"`;if(_issue.format==="regex")return`String tidak valid: harus sesuai pola ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${issue2.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${issue2.origin}`;default:return"Input tidak valid"}}};var init_id=__esm(()=>{init_util()});function is_default(){return{localeError:error20()}}var error20=()=>{let Sizable={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},TypeDictionary={nan:"NaN",number:"númer",array:"fylki"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Rangt gildi: Þú slóst inn ${received} þar sem á að vera instanceof ${issue2.expected}`;return`Rangt gildi: Þú slóst inn ${received} þar sem á að vera ${expected}`}case"invalid_value":if(issue2.values.length===1)return`Rangt gildi: gert ráð fyrir ${stringifyPrimitive(issue2.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Of stórt: gert er ráð fyrir að ${issue2.origin??"gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${issue2.origin??"gildi"} sé ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Of lítið: gert er ráð fyrir að ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Of lítið: gert er ráð fyrir að ${issue2.origin} sé ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ógildur strengur: verður að byrja á "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ógildur strengur: verður að enda á "${_issue.suffix}"`;if(_issue.format==="includes")return`Ógildur strengur: verður að innihalda "${_issue.includes}"`;if(_issue.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${_issue.pattern}`;return`Rangt ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${issue2.divisor}`;case"unrecognized_keys":return`Óþekkt ${issue2.keys.length>1?"ir lyklar":"ur lykill"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${issue2.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${issue2.origin}`;default:return"Rangt gildi"}}};var init_is=__esm(()=>{init_util()});function it_default(){return{localeError:error21()}}var error21=()=>{let Sizable={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"numero",array:"vettore"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`;return`Input non valido: atteso ${expected}, ricevuto ${received}`}case"invalid_value":if(issue2.values.length===1)return`Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`;return`Opzione non valida: atteso uno tra ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Troppo grande: ${issue2.origin??"valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementi"}`;return`Troppo grande: ${issue2.origin??"valore"} deve essere ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Stringa non valida: deve iniziare con "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Stringa non valida: deve terminare con "${_issue.suffix}"`;if(_issue.format==="includes")return`Stringa non valida: deve includere "${_issue.includes}"`;if(_issue.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;return`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${issue2.divisor}`;case"unrecognized_keys":return`Chiav${issue2.keys.length>1?"i":"e"} non riconosciut${issue2.keys.length>1?"e":"a"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${issue2.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${issue2.origin}`;default:return"Input non valido"}}};var init_it=__esm(()=>{init_util()});function ja_default(){return{localeError:error22()}}var error22=()=>{let Sizable={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},TypeDictionary={nan:"NaN",number:"数値",array:"配列"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`無効な入力: instanceof ${issue2.expected}が期待されましたが、${received}が入力されました`;return`無効な入力: ${expected}が期待されましたが、${received}が入力されました`}case"invalid_value":if(issue2.values.length===1)return`無効な入力: ${stringifyPrimitive(issue2.values[0])}が期待されました`;return`無効な選択: ${joinValues(issue2.values,"、")}のいずれかである必要があります`;case"too_big":{let adj=issue2.inclusive?"以下である":"より小さい",sizing=getSizing(issue2.origin);if(sizing)return`大きすぎる値: ${issue2.origin??"値"}は${issue2.maximum.toString()}${sizing.unit??"要素"}${adj}必要があります`;return`大きすぎる値: ${issue2.origin??"値"}は${issue2.maximum.toString()}${adj}必要があります`}case"too_small":{let adj=issue2.inclusive?"以上である":"より大きい",sizing=getSizing(issue2.origin);if(sizing)return`小さすぎる値: ${issue2.origin}は${issue2.minimum.toString()}${sizing.unit}${adj}必要があります`;return`小さすぎる値: ${issue2.origin}は${issue2.minimum.toString()}${adj}必要があります`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`無効な文字列: "${_issue.prefix}"で始まる必要があります`;if(_issue.format==="ends_with")return`無効な文字列: "${_issue.suffix}"で終わる必要があります`;if(_issue.format==="includes")return`無効な文字列: "${_issue.includes}"を含む必要があります`;if(_issue.format==="regex")return`無効な文字列: パターン${_issue.pattern}に一致する必要があります`;return`無効な${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`無効な数値: ${issue2.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${issue2.keys.length>1?"群":""}: ${joinValues(issue2.keys,"、")}`;case"invalid_key":return`${issue2.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${issue2.origin}内の無効な値`;default:return"無効な入力"}}};var init_ja=__esm(()=>{init_util()});function ka_default(){return{localeError:error23()}}var error23=()=>{let Sizable={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული სტრინგი",base64url:"base64url-კოდირებული სტრინგი",json_string:"JSON სტრინგი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},TypeDictionary={nan:"NaN",number:"რიცხვი",string:"სტრინგი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${issue2.expected}, მიღებული ${received}`;return`არასწორი შეყვანა: მოსალოდნელი ${expected}, მიღებული ${received}`}case"invalid_value":if(issue2.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${stringifyPrimitive(issue2.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${joinValues(issue2.values,"|")}-დან`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`ზედმეტად დიდი: მოსალოდნელი ${issue2.origin??"მნიშვნელობა"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${issue2.origin??"მნიშვნელობა"} იყოს ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`ზედმეტად პატარა: მოსალოდნელი ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${issue2.origin} იყოს ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`არასწორი სტრინგი: უნდა იწყებოდეს "${_issue.prefix}"-ით`;if(_issue.format==="ends_with")return`არასწორი სტრინგი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`;if(_issue.format==="includes")return`არასწორი სტრინგი: უნდა შეიცავდეს "${_issue.includes}"-ს`;if(_issue.format==="regex")return`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`;return`არასწორი ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${issue2.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${issue2.keys.length>1?"ები":"ი"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${issue2.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${issue2.origin}-ში`;default:return"არასწორი შეყვანა"}}};var init_ka=__esm(()=>{init_util()});function km_default(){return{localeError:error24()}}var error24=()=>{let Sizable={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},TypeDictionary={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${issue2.expected} ប៉ុន្តែទទួលបាន ${received}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${expected} ប៉ុន្តែទទួលបាន ${received}`}case"invalid_value":if(issue2.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive(issue2.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`ធំពេក៖ ត្រូវការ ${issue2.origin??"តម្លៃ"} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${issue2.origin??"តម្លៃ"} ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`តូចពេក៖ ត្រូវការ ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`តូចពេក៖ ត្រូវការ ${issue2.origin} ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`;if(_issue.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`;if(_issue.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`;if(_issue.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`;return`មិនត្រឹមត្រូវ៖ ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue2.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${issue2.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue2.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};var init_km=__esm(()=>{init_util()});function kh_default(){return km_default()}var init_kh=__esm(()=>{init_km()});function ko_default(){return{localeError:error25()}}var error25=()=>{let Sizable={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`잘못된 입력: 예상 타입은 instanceof ${issue2.expected}, 받은 타입은 ${received}입니다`;return`잘못된 입력: 예상 타입은 ${expected}, 받은 타입은 ${received}입니다`}case"invalid_value":if(issue2.values.length===1)return`잘못된 입력: 값은 ${stringifyPrimitive(issue2.values[0])} 이어야 합니다`;return`잘못된 옵션: ${joinValues(issue2.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let adj=issue2.inclusive?"이하":"미만",suffix=adj==="미만"?"이어야 합니다":"여야 합니다",sizing=getSizing(issue2.origin),unit=sizing?.unit??"요소";if(sizing)return`${issue2.origin??"값"}이 너무 큽니다: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`;return`${issue2.origin??"값"}이 너무 큽니다: ${issue2.maximum.toString()} ${adj}${suffix}`}case"too_small":{let adj=issue2.inclusive?"이상":"초과",suffix=adj==="이상"?"이어야 합니다":"여야 합니다",sizing=getSizing(issue2.origin),unit=sizing?.unit??"요소";if(sizing)return`${issue2.origin??"값"}이 너무 작습니다: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`;return`${issue2.origin??"값"}이 너무 작습니다: ${issue2.minimum.toString()} ${adj}${suffix}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`;if(_issue.format==="ends_with")return`잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`;if(_issue.format==="includes")return`잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`;if(_issue.format==="regex")return`잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`잘못된 숫자: ${issue2.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`잘못된 키: ${issue2.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${issue2.origin}`;default:return"잘못된 입력"}}};var init_ko=__esm(()=>{init_util()});function getUnitTypeFromNumber(number2){let abs=Math.abs(number2),last=abs%10,last2=abs%100;if(last2>=11&&last2<=19||last===0)return"many";if(last===1)return"one";return"few"}function lt_default(){return{localeError:error26()}}var capitalizeFirstCharacter=(text)=>{return text.charAt(0).toUpperCase()+text.slice(1)},error26=()=>{let Sizable={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function getSizing(origin,unitType,inclusive,targetShouldBe){let result=Sizable[origin]??null;if(result===null)return result;return{unit:result.unit[unitType],verb:result.verb[targetShouldBe][inclusive?"inclusive":"notInclusive"]}}let FormatDictionary={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},TypeDictionary={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Gautas tipas ${received}, o tikėtasi - instanceof ${issue2.expected}`;return`Gautas tipas ${received}, o tikėtasi - ${expected}`}case"invalid_value":if(issue2.values.length===1)return`Privalo būti ${stringifyPrimitive(issue2.values[0])}`;return`Privalo būti vienas iš ${joinValues(issue2.values,"|")} pasirinkimų`;case"too_big":{let origin=TypeDictionary[issue2.origin]??issue2.origin,sizing=getSizing(issue2.origin,getUnitTypeFromNumber(Number(issue2.maximum)),issue2.inclusive??!1,"smaller");if(sizing?.verb)return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit??"elementų"}`;let adj=issue2.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} turi būti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`}case"too_small":{let origin=TypeDictionary[issue2.origin]??issue2.origin,sizing=getSizing(issue2.origin,getUnitTypeFromNumber(Number(issue2.minimum)),issue2.inclusive??!1,"bigger");if(sizing?.verb)return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit??"elementų"}`;let adj=issue2.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} turi būti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Eilutė privalo prasidėti "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Eilutė privalo pasibaigti "${_issue.suffix}"`;if(_issue.format==="includes")return`Eilutė privalo įtraukti "${_issue.includes}"`;if(_issue.format==="regex")return`Eilutė privalo atitikti ${_issue.pattern}`;return`Neteisingas ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Skaičius privalo būti ${issue2.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${issue2.keys.length>1?"i":"as"} rakt${issue2.keys.length>1?"ai":"as"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let origin=TypeDictionary[issue2.origin]??issue2.origin;return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};var init_lt=__esm(()=>{init_util()});function mk_default(){return{localeError:error27()}}var error27=()=>{let Sizable={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},TypeDictionary={nan:"NaN",number:"број",array:"низа"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Грешен внес: се очекува instanceof ${issue2.expected}, примено ${received}`;return`Грешен внес: се очекува ${expected}, примено ${received}`}case"invalid_value":if(issue2.values.length===1)return`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;return`Грешана опција: се очекува една ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Премногу голем: се очекува ${issue2.origin??"вредноста"} да има ${adj}${issue2.maximum.toString()} ${sizing.unit??"елементи"}`;return`Премногу голем: се очекува ${issue2.origin??"вредноста"} да биде ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Премногу мал: се очекува ${issue2.origin} да има ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Премногу мал: се очекува ${issue2.origin} да биде ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Неважечка низа: мора да започнува со "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Неважечка низа: мора да завршува со "${_issue.suffix}"`;if(_issue.format==="includes")return`Неважечка низа: мора да вклучува "${_issue.includes}"`;if(_issue.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`;return`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${issue2.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${issue2.origin}`;default:return"Грешен внес"}}};var init_mk=__esm(()=>{init_util()});function ms_default(){return{localeError:error28()}}var error28=()=>{let Sizable={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"nombor"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`;return`Input tidak sah: dijangka ${expected}, diterima ${received}`}case"invalid_value":if(issue2.values.length===1)return`Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Terlalu besar: dijangka ${issue2.origin??"nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemen"}`;return`Terlalu besar: dijangka ${issue2.origin??"nilai"} adalah ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`String tidak sah: mesti bermula dengan "${_issue.prefix}"`;if(_issue.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;if(_issue.format==="includes")return`String tidak sah: mesti mengandungi "${_issue.includes}"`;if(_issue.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${issue2.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${issue2.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${issue2.origin}`;default:return"Input tidak sah"}}};var init_ms=__esm(()=>{init_util()});function nl_default(){return{localeError:error29()}}var error29=()=>{let Sizable={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},TypeDictionary={nan:"NaN",number:"getal"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`;return`Ongeldige invoer: verwacht ${expected}, ontving ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;return`Ongeldige optie: verwacht één van ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),longName=issue2.origin==="date"?"laat":issue2.origin==="string"?"lang":"groot";if(sizing)return`Te ${longName}: verwacht dat ${issue2.origin??"waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementen"} ${sizing.verb}`;return`Te ${longName}: verwacht dat ${issue2.origin??"waarde"} ${adj}${issue2.maximum.toString()} is`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),shortName=issue2.origin==="date"?"vroeg":issue2.origin==="string"?"kort":"klein";if(sizing)return`Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;return`Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;if(_issue.format==="ends_with")return`Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;if(_issue.format==="includes")return`Ongeldige tekst: moet "${_issue.includes}" bevatten`;if(_issue.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;return`Ongeldig: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${issue2.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${issue2.origin}`;default:return"Ongeldige invoer"}}};var init_nl=__esm(()=>{init_util()});function no_default(){return{localeError:error30()}}var error30=()=>{let Sizable={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"tall",array:"liste"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`;return`Ugyldig input: forventet ${expected}, fikk ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`;return`Ugyldig valg: forventet en av ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`For stor(t): forventet ${issue2.origin??"value"} til å ha ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementer"}`;return`For stor(t): forventet ${issue2.origin??"value"} til å ha ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`For lite(n): forventet ${issue2.origin} til å ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`For lite(n): forventet ${issue2.origin} til å ha ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ugyldig streng: må starte med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ugyldig streng: må ende med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ugyldig streng: må inneholde "${_issue.includes}"`;if(_issue.format==="regex")return`Ugyldig streng: må matche mønsteret ${_issue.pattern}`;return`Ugyldig ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${issue2.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${issue2.origin}`;default:return"Ugyldig input"}}};var init_no=__esm(()=>{init_util()});function ota_default(){return{localeError:error31()}}var error31=()=>{let Sizable={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},TypeDictionary={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Fâsit giren: umulan instanceof ${issue2.expected}, alınan ${received}`;return`Fâsit giren: umulan ${expected}, alınan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Fâsit giren: umulan ${stringifyPrimitive(issue2.values[0])}`;return`Fâsit tercih: mûteberler ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Fazla büyük: ${issue2.origin??"value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${issue2.origin??"value"}, ${adj}${issue2.maximum.toString()} olmalıydı.`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Fazla küçük: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmalıydı.`;return`Fazla küçük: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmalıydı.`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Fâsit metin: "${_issue.prefix}" ile başlamalı.`;if(_issue.format==="ends_with")return`Fâsit metin: "${_issue.suffix}" ile bitmeli.`;if(_issue.format==="includes")return`Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`;if(_issue.format==="regex")return`Fâsit metin: ${_issue.pattern} nakşına uymalı.`;return`Fâsit ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Fâsit sayı: ${issue2.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${issue2.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};var init_ota=__esm(()=>{init_util()});function ps_default(){return{localeError:error32()}}var error32=()=>{let Sizable={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},TypeDictionary={nan:"NaN",number:"عدد",array:"ارې"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`ناسم ورودي: باید instanceof ${issue2.expected} وای, مګر ${received} ترلاسه شو`;return`ناسم ورودي: باید ${expected} وای, مګر ${received} ترلاسه شو`}case"invalid_value":if(issue2.values.length===1)return`ناسم ورودي: باید ${stringifyPrimitive(issue2.values[0])} وای`;return`ناسم انتخاب: باید یو له ${joinValues(issue2.values,"|")} څخه وای`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`ډیر لوی: ${issue2.origin??"ارزښت"} باید ${adj}${issue2.maximum.toString()} ${sizing.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${issue2.origin??"ارزښت"} باید ${adj}${issue2.maximum.toString()} وي`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`ډیر کوچنی: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} ${sizing.unit} ولري`;return`ډیر کوچنی: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} وي`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`ناسم متن: باید د "${_issue.prefix}" سره پیل شي`;if(_issue.format==="ends_with")return`ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`;if(_issue.format==="includes")return`ناسم متن: باید "${_issue.includes}" ولري`;if(_issue.format==="regex")return`ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`;return`${FormatDictionary[_issue.format]??issue2.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${issue2.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${issue2.keys.length>1?"کلیډونه":"کلیډ"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${issue2.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${issue2.origin} کې`;default:return"ناسمه ورودي"}}};var init_ps=__esm(()=>{init_util()});function pl_default(){return{localeError:error33()}}var error33=()=>{let Sizable={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},TypeDictionary={nan:"NaN",number:"liczba",array:"tablica"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${expected}, otrzymano ${received}`}case"invalid_value":if(issue2.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Za duża wartość: oczekiwano, że ${issue2.origin??"wartość"} będzie mieć ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${issue2.origin??"wartość"} będzie wynosić ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Za mała wartość: oczekiwano, że ${issue2.origin??"wartość"} będzie mieć ${adj}${issue2.minimum.toString()} ${sizing.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${issue2.origin??"wartość"} będzie wynosić ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`;if(_issue.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`;if(_issue.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`;return`Nieprawidłow(y/a/e) ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${issue2.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${issue2.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${issue2.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};var init_pl=__esm(()=>{init_util()});function pt_default(){return{localeError:error34()}}var error34=()=>{let Sizable={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},TypeDictionary={nan:"NaN",number:"número",null:"nulo"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Tipo inválido: esperado instanceof ${issue2.expected}, recebido ${received}`;return`Tipo inválido: esperado ${expected}, recebido ${received}`}case"invalid_value":if(issue2.values.length===1)return`Entrada inválida: esperado ${stringifyPrimitive(issue2.values[0])}`;return`Opção inválida: esperada uma das ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Muito grande: esperado que ${issue2.origin??"valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementos"}`;return`Muito grande: esperado que ${issue2.origin??"valor"} fosse ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Texto inválido: deve começar com "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Texto inválido: deve terminar com "${_issue.suffix}"`;if(_issue.format==="includes")return`Texto inválido: deve incluir "${_issue.includes}"`;if(_issue.format==="regex")return`Texto inválido: deve corresponder ao padrão ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${issue2.divisor}`;case"unrecognized_keys":return`Chave${issue2.keys.length>1?"s":""} desconhecida${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Chave inválida em ${issue2.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${issue2.origin}`;default:return"Campo inválido"}}};var init_pt=__esm(()=>{init_util()});function getRussianPlural(count,one,few,many){let absCount=Math.abs(count),lastDigit=absCount%10,lastTwoDigits=absCount%100;if(lastTwoDigits>=11&&lastTwoDigits<=19)return many;if(lastDigit===1)return one;if(lastDigit>=2&&lastDigit<=4)return few;return many}function ru_default(){return{localeError:error35()}}var error35=()=>{let Sizable={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},TypeDictionary={nan:"NaN",number:"число",array:"массив"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Неверный ввод: ожидалось instanceof ${issue2.expected}, получено ${received}`;return`Неверный ввод: ожидалось ${expected}, получено ${received}`}case"invalid_value":if(issue2.values.length===1)return`Неверный ввод: ожидалось ${stringifyPrimitive(issue2.values[0])}`;return`Неверный вариант: ожидалось одно из ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing){let maxValue=Number(issue2.maximum),unit=getRussianPlural(maxValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Слишком большое значение: ожидалось, что ${issue2.origin??"значение"} будет иметь ${adj}${issue2.maximum.toString()} ${unit}`}return`Слишком большое значение: ожидалось, что ${issue2.origin??"значение"} будет ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing){let minValue=Number(issue2.minimum),unit=getRussianPlural(minValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Слишком маленькое значение: ожидалось, что ${issue2.origin} будет иметь ${adj}${issue2.minimum.toString()} ${unit}`}return`Слишком маленькое значение: ожидалось, что ${issue2.origin} будет ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Неверная строка: должна начинаться с "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Неверная строка: должна заканчиваться на "${_issue.suffix}"`;if(_issue.format==="includes")return`Неверная строка: должна содержать "${_issue.includes}"`;if(_issue.format==="regex")return`Неверная строка: должна соответствовать шаблону ${_issue.pattern}`;return`Неверный ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${issue2.divisor}`;case"unrecognized_keys":return`Нераспознанн${issue2.keys.length>1?"ые":"ый"} ключ${issue2.keys.length>1?"и":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${issue2.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${issue2.origin}`;default:return"Неверные входные данные"}}};var init_ru=__esm(()=>{init_util()});function sl_default(){return{localeError:error36()}}var error36=()=>{let Sizable={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},TypeDictionary={nan:"NaN",number:"število",array:"tabela"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Neveljaven vnos: pričakovano instanceof ${issue2.expected}, prejeto ${received}`;return`Neveljaven vnos: pričakovano ${expected}, prejeto ${received}`}case"invalid_value":if(issue2.values.length===1)return`Neveljaven vnos: pričakovano ${stringifyPrimitive(issue2.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Preveliko: pričakovano, da bo ${issue2.origin??"vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${issue2.origin??"vrednost"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Premajhno: pričakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Premajhno: pričakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Neveljaven niz: mora se začeti z "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Neveljaven niz: mora se končati z "${_issue.suffix}"`;if(_issue.format==="includes")return`Neveljaven niz: mora vsebovati "${_issue.includes}"`;if(_issue.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;return`Neveljaven ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${issue2.divisor}`;case"unrecognized_keys":return`Neprepoznan${issue2.keys.length>1?"i ključi":" ključ"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${issue2.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${issue2.origin}`;default:return"Neveljaven vnos"}}};var init_sl=__esm(()=>{init_util()});function sv_default(){return{localeError:error37()}}var error37=()=>{let Sizable={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},TypeDictionary={nan:"NaN",number:"antal",array:"lista"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ogiltig inmatning: förväntat instanceof ${issue2.expected}, fick ${received}`;return`Ogiltig inmatning: förväntat ${expected}, fick ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ogiltig inmatning: förväntat ${stringifyPrimitive(issue2.values[0])}`;return`Ogiltigt val: förväntade en av ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`För stor(t): förväntade ${issue2.origin??"värdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit??"element"}`;return`För stor(t): förväntat ${issue2.origin??"värdet"} att ha ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`För lite(t): förväntade ${issue2.origin??"värdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`För lite(t): förväntade ${issue2.origin??"värdet"} att ha ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ogiltig sträng: måste börja med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ogiltig sträng: måste sluta med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ogiltig sträng: måste innehålla "${_issue.includes}"`;if(_issue.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`;return`Ogiltig(t) ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${issue2.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${issue2.origin??"värdet"}`;default:return"Ogiltig input"}}};var init_sv=__esm(()=>{init_util()});function ta_default(){return{localeError:error38()}}var error38=()=>{let Sizable={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${issue2.expected}, பெறப்பட்டது ${received}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${expected}, பெறப்பட்டது ${received}`}case"invalid_value":if(issue2.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive(issue2.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues(issue2.values,"|")} இல் ஒன்று`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue2.origin??"மதிப்பு"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue2.origin??"மதிப்பு"} ${adj}${issue2.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue2.origin} ${adj}${issue2.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`;if(_issue.format==="ends_with")return`தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`;if(_issue.format==="includes")return`தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`;if(_issue.format==="regex")return`தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`தவறான எண்: ${issue2.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${issue2.keys.length>1?"கள்":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${issue2.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};var init_ta=__esm(()=>{init_util()});function th_default(){return{localeError:error39()}}var error39=()=>{let Sizable={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},TypeDictionary={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${issue2.expected} แต่ได้รับ ${received}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${expected} แต่ได้รับ ${received}`}case"invalid_value":if(issue2.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive(issue2.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"ไม่เกิน":"น้อยกว่า",sizing=getSizing(issue2.origin);if(sizing)return`เกินกำหนด: ${issue2.origin??"ค่า"} ควรมี${adj} ${issue2.maximum.toString()} ${sizing.unit??"รายการ"}`;return`เกินกำหนด: ${issue2.origin??"ค่า"} ควรมี${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?"อย่างน้อย":"มากกว่า",sizing=getSizing(issue2.origin);if(sizing)return`น้อยกว่ากำหนด: ${issue2.origin} ควรมี${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`น้อยกว่ากำหนด: ${issue2.origin} ควรมี${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`;if(_issue.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`;if(_issue.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`;if(_issue.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`;return`รูปแบบไม่ถูกต้อง: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue2.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${issue2.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${issue2.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};var init_th=__esm(()=>{init_util()});function tr_default(){return{localeError:error40()}}var error40=()=>{let Sizable={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Geçersiz değer: beklenen instanceof ${issue2.expected}, alınan ${received}`;return`Geçersiz değer: beklenen ${expected}, alınan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Geçersiz değer: beklenen ${stringifyPrimitive(issue2.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Çok büyük: beklenen ${issue2.origin??"değer"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"öğe"}`;return`Çok büyük: beklenen ${issue2.origin??"değer"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Çok küçük: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Çok küçük: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Geçersiz metin: "${_issue.prefix}" ile başlamalı`;if(_issue.format==="ends_with")return`Geçersiz metin: "${_issue.suffix}" ile bitmeli`;if(_issue.format==="includes")return`Geçersiz metin: "${_issue.includes}" içermeli`;if(_issue.format==="regex")return`Geçersiz metin: ${_issue.pattern} desenine uymalı`;return`Geçersiz ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Geçersiz sayı: ${issue2.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${issue2.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};var init_tr=__esm(()=>{init_util()});function uk_default(){return{localeError:error41()}}var error41=()=>{let Sizable={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},TypeDictionary={nan:"NaN",number:"число",array:"масив"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Неправильні вхідні дані: очікується instanceof ${issue2.expected}, отримано ${received}`;return`Неправильні вхідні дані: очікується ${expected}, отримано ${received}`}case"invalid_value":if(issue2.values.length===1)return`Неправильні вхідні дані: очікується ${stringifyPrimitive(issue2.values[0])}`;return`Неправильна опція: очікується одне з ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Занадто велике: очікується, що ${issue2.origin??"значення"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"елементів"}`;return`Занадто велике: очікується, що ${issue2.origin??"значення"} буде ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Занадто мале: очікується, що ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Занадто мале: очікується, що ${issue2.origin} буде ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Неправильний рядок: повинен починатися з "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`;if(_issue.format==="includes")return`Неправильний рядок: повинен містити "${_issue.includes}"`;if(_issue.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`;return`Неправильний ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${issue2.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${issue2.keys.length>1?"і":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${issue2.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${issue2.origin}`;default:return"Неправильні вхідні дані"}}};var init_uk=__esm(()=>{init_util()});function ua_default(){return uk_default()}var init_ua=__esm(()=>{init_uk()});function ur_default(){return{localeError:error42()}}var error42=()=>{let Sizable={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},TypeDictionary={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`غلط ان پٹ: instanceof ${issue2.expected} متوقع تھا، ${received} موصول ہوا`;return`غلط ان پٹ: ${expected} متوقع تھا، ${received} موصول ہوا`}case"invalid_value":if(issue2.values.length===1)return`غلط ان پٹ: ${stringifyPrimitive(issue2.values[0])} متوقع تھا`;return`غلط آپشن: ${joinValues(issue2.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`بہت بڑا: ${issue2.origin??"ویلیو"} کے ${adj}${issue2.maximum.toString()} ${sizing.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${issue2.origin??"ویلیو"} کا ${adj}${issue2.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`بہت چھوٹا: ${issue2.origin} کے ${adj}${issue2.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${issue2.origin} کا ${adj}${issue2.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`;if(_issue.format==="ends_with")return`غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`;if(_issue.format==="includes")return`غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`;if(_issue.format==="regex")return`غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`;return`غلط ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`غلط نمبر: ${issue2.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${issue2.keys.length>1?"ز":""}: ${joinValues(issue2.keys,"، ")}`;case"invalid_key":return`${issue2.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${issue2.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};var init_ur=__esm(()=>{init_util()});function uz_default(){return{localeError:error43()}}var error43=()=>{let Sizable={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},TypeDictionary={nan:"NaN",number:"raqam",array:"massiv"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`;return`Noto‘g‘ri kirish: kutilgan ${expected}, qabul qilingan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Juda katta: kutilgan ${issue2.origin??"qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`;return`Juda katta: kutilgan ${issue2.origin??"qiymat"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;return`Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Noto‘g‘ri satr: "${_issue.prefix}" bilan boshlanishi kerak`;if(_issue.format==="ends_with")return`Noto‘g‘ri satr: "${_issue.suffix}" bilan tugashi kerak`;if(_issue.format==="includes")return`Noto‘g‘ri satr: "${_issue.includes}" ni o‘z ichiga olishi kerak`;if(_issue.format==="regex")return`Noto‘g‘ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${issue2.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${issue2.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};var init_uz=__esm(()=>{init_util()});function vi_default(){return{localeError:error44()}}var error44=()=>{let Sizable={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},TypeDictionary={nan:"NaN",number:"số",array:"mảng"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${issue2.expected}, nhận được ${received}`;return`Đầu vào không hợp lệ: mong đợi ${expected}, nhận được ${received}`}case"invalid_value":if(issue2.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive(issue2.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Quá lớn: mong đợi ${issue2.origin??"giá trị"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"phần tử"}`;return`Quá lớn: mong đợi ${issue2.origin??"giá trị"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Quá nhỏ: mong đợi ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Quá nhỏ: mong đợi ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`;if(_issue.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`;if(_issue.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${issue2.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${issue2.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${issue2.origin}`;default:return"Đầu vào không hợp lệ"}}};var init_vi=__esm(()=>{init_util()});function zh_CN_default(){return{localeError:error45()}}var error45=()=>{let Sizable={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},TypeDictionary={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`无效输入:期望 instanceof ${issue2.expected},实际接收 ${received}`;return`无效输入:期望 ${expected},实际接收 ${received}`}case"invalid_value":if(issue2.values.length===1)return`无效输入:期望 ${stringifyPrimitive(issue2.values[0])}`;return`无效选项:期望以下之一 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`数值过大:期望 ${issue2.origin??"值"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"个元素"}`;return`数值过大:期望 ${issue2.origin??"值"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`数值过小:期望 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`数值过小:期望 ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`无效字符串:必须以 "${_issue.prefix}" 开头`;if(_issue.format==="ends_with")return`无效字符串:必须以 "${_issue.suffix}" 结尾`;if(_issue.format==="includes")return`无效字符串:必须包含 "${_issue.includes}"`;if(_issue.format==="regex")return`无效字符串:必须满足正则表达式 ${_issue.pattern}`;return`无效${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`无效数字:必须是 ${issue2.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${issue2.origin} 中包含无效值(value)`;default:return"无效输入"}}};var init_zh_CN=__esm(()=>{init_util()});function zh_TW_default(){return{localeError:error46()}}var error46=()=>{let Sizable={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`無效的輸入值:預期為 instanceof ${issue2.expected},但收到 ${received}`;return`無效的輸入值:預期為 ${expected},但收到 ${received}`}case"invalid_value":if(issue2.values.length===1)return`無效的輸入值:預期為 ${stringifyPrimitive(issue2.values[0])}`;return`無效的選項:預期為以下其中之一 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`數值過大:預期 ${issue2.origin??"值"} 應為 ${adj}${issue2.maximum.toString()} ${sizing.unit??"個元素"}`;return`數值過大:預期 ${issue2.origin??"值"} 應為 ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`數值過小:預期 ${issue2.origin} 應為 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`數值過小:預期 ${issue2.origin} 應為 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`無效的字串:必須以 "${_issue.prefix}" 開頭`;if(_issue.format==="ends_with")return`無效的字串:必須以 "${_issue.suffix}" 結尾`;if(_issue.format==="includes")return`無效的字串:必須包含 "${_issue.includes}"`;if(_issue.format==="regex")return`無效的字串:必須符合格式 ${_issue.pattern}`;return`無效的 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`無效的數字:必須為 ${issue2.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${issue2.keys.length>1?"們":""}:${joinValues(issue2.keys,"、")}`;case"invalid_key":return`${issue2.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${issue2.origin} 中有無效的值`;default:return"無效的輸入值"}}};var init_zh_TW=__esm(()=>{init_util()});function yo_default(){return{localeError:error47()}}var error47=()=>{let Sizable={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},TypeDictionary={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${issue2.expected}, àmọ̀ a rí ${received}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${expected}, àmọ̀ a rí ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${stringifyPrimitive(issue2.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${issue2.origin??"iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${adj}${issue2.maximum}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Kéré ju: a ní láti jẹ́ pé ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`;return`Kéré ju: a ní láti jẹ́ ${adj}${issue2.minimum}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${_issue.suffix}"`;if(_issue.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${_issue.includes}"`;if(_issue.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${_issue.pattern}`;return`Aṣìṣe: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${issue2.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${issue2.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${issue2.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};var init_yo=__esm(()=>{init_util()});var exports_locales={};__export(exports_locales,{zhTW:()=>zh_TW_default,zhCN:()=>zh_CN_default,yo:()=>yo_default,vi:()=>vi_default,uz:()=>uz_default,ur:()=>ur_default,uk:()=>uk_default,ua:()=>ua_default,tr:()=>tr_default,th:()=>th_default,ta:()=>ta_default,sv:()=>sv_default,sl:()=>sl_default,ru:()=>ru_default,pt:()=>pt_default,ps:()=>ps_default,pl:()=>pl_default,ota:()=>ota_default,no:()=>no_default,nl:()=>nl_default,ms:()=>ms_default,mk:()=>mk_default,lt:()=>lt_default,ko:()=>ko_default,km:()=>km_default,kh:()=>kh_default,ka:()=>ka_default,ja:()=>ja_default,it:()=>it_default,is:()=>is_default,id:()=>id_default,hy:()=>hy_default,hu:()=>hu_default,he:()=>he_default,frCA:()=>fr_CA_default,fr:()=>fr_default,fi:()=>fi_default,fa:()=>fa_default,es:()=>es_default,eo:()=>eo_default,en:()=>en_default,de:()=>de_default,da:()=>da_default,cs:()=>cs_default,ca:()=>ca_default,bg:()=>bg_default,be:()=>be_default,az:()=>az_default,ar:()=>ar_default});var init_locales=__esm(()=>{init_ar();init_az();init_be();init_bg();init_ca();init_cs();init_da();init_de();init_en();init_eo();init_es();init_fa();init_fi();init_fr();init_fr_CA();init_he();init_hu();init_hy();init_id();init_is();init_it();init_ja();init_ka();init_kh();init_km();init_ko();init_lt();init_mk();init_ms();init_nl();init_no();init_ota();init_ps();init_pl();init_pt();init_ru();init_sl();init_sv();init_ta();init_th();init_tr();init_ua();init_uk();init_ur();init_uz();init_vi();init_zh_CN();init_zh_TW();init_yo()});class $ZodRegistry{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema,..._meta){let meta=_meta[0];if(this._map.set(schema,meta),meta&&typeof meta==="object"&&"id"in meta)this._idmap.set(meta.id,schema);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema){let meta=this._map.get(schema);if(meta&&typeof meta==="object"&&"id"in meta)this._idmap.delete(meta.id);return this._map.delete(schema),this}get(schema){let p=schema._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f={...pm,...this._map.get(schema)};return Object.keys(f).length?f:void 0}return this._map.get(schema)}has(schema){return this._map.has(schema)}}function registry(){return new $ZodRegistry}var _a,$output,$input,globalRegistry;var init_registries=__esm(()=>{$output=Symbol("ZodOutput"),$input=Symbol("ZodInput");(_a=globalThis).__zod_globalRegistry??(_a.__zod_globalRegistry=registry());globalRegistry=globalThis.__zod_globalRegistry});function _string(Class2,params){return new Class2({type:"string",...normalizeParams(params)})}function _coercedString(Class2,params){return new Class2({type:"string",coerce:!0,...normalizeParams(params)})}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _mac(Class2,params){return new Class2({type:"string",format:"mac",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(params)})}function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2({type:"number",checks:[],...normalizeParams(params)})}function _coercedNumber(Class2,params){return new Class2({type:"number",coerce:!0,checks:[],...normalizeParams(params)})}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(params)})}function _float32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float32",...normalizeParams(params)})}function _float64(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float64",...normalizeParams(params)})}function _int32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"int32",...normalizeParams(params)})}function _uint32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"uint32",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class2,params){return new Class2({type:"boolean",coerce:!0,...normalizeParams(params)})}function _bigint(Class2,params){return new Class2({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class2,params){return new Class2({type:"bigint",coerce:!0,...normalizeParams(params)})}function _int64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...normalizeParams(params)})}function _uint64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...normalizeParams(params)})}function _symbol(Class2,params){return new Class2({type:"symbol",...normalizeParams(params)})}function _undefined2(Class2,params){return new Class2({type:"undefined",...normalizeParams(params)})}function _null2(Class2,params){return new Class2({type:"null",...normalizeParams(params)})}function _any(Class2){return new Class2({type:"any"})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _void(Class2,params){return new Class2({type:"void",...normalizeParams(params)})}function _date(Class2,params){return new Class2({type:"date",...normalizeParams(params)})}function _coercedDate(Class2,params){return new Class2({type:"date",coerce:!0,...normalizeParams(params)})}function _nan(Class2,params){return new Class2({type:"nan",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!1})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!0})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!1})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!0})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite((input)=>input.normalize(form))}function _trim(){return _overwrite((input)=>input.trim())}function _toLowerCase(){return _overwrite((input)=>input.toLowerCase())}function _toUpperCase(){return _overwrite((input)=>input.toUpperCase())}function _slugify(){return _overwrite((input)=>slugify(input))}function _array(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _union(Class2,options,params){return new Class2({type:"union",options,...normalizeParams(params)})}function _xor(Class2,options,params){return new Class2({type:"union",options,inclusive:!1,...normalizeParams(params)})}function _discriminatedUnion(Class2,discriminator,options,params){return new Class2({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class2,left,right){return new Class2({type:"intersection",left,right})}function _tuple(Class2,items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType;return new Class2({type:"tuple",items,rest:hasRest?_paramsOrRest:null,...normalizeParams(hasRest?_params:_paramsOrRest)})}function _record(Class2,keyType,valueType,params){return new Class2({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class2,keyType,valueType,params){return new Class2({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class2,valueType,params){return new Class2({type:"set",valueType,...normalizeParams(params)})}function _enum(Class2,values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new Class2({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class2,entries,params){return new Class2({type:"enum",entries,...normalizeParams(params)})}function _literal(Class2,value,params){return new Class2({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function _file(Class2,params){return new Class2({type:"file",...normalizeParams(params)})}function _transform(Class2,fn2){return new Class2({type:"transform",transform:fn2})}function _optional(Class2,innerType){return new Class2({type:"optional",innerType})}function _nullable(Class2,innerType){return new Class2({type:"nullable",innerType})}function _default(Class2,innerType,defaultValue){return new Class2({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class2,innerType,params){return new Class2({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class2,innerType){return new Class2({type:"success",innerType})}function _catch(Class2,innerType,catchValue){return new Class2({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function _pipe(Class2,in_,out){return new Class2({type:"pipe",in:in_,out})}function _readonly(Class2,innerType){return new Class2({type:"readonly",innerType})}function _templateLiteral(Class2,parts,params){return new Class2({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class2,getter){return new Class2({type:"lazy",getter})}function _promise(Class2,innerType){return new Class2({type:"promise",innerType})}function _custom(Class2,fn2,_params){let norm=normalizeParams(_params);return norm.abort??(norm.abort=!0),new Class2({type:"custom",check:"custom",fn:fn2,...norm})}function _refine(Class2,fn2,_params){return new Class2({type:"custom",check:"custom",fn:fn2,...normalizeParams(_params)})}function _superRefine(fn2){let ch=_check((payload)=>{return payload.addIssue=(issue2)=>{if(typeof issue2==="string")payload.issues.push(issue(issue2,payload.value,ch._zod.def));else{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=ch),_issue.continue??(_issue.continue=!ch._zod.def.abort),payload.issues.push(issue(_issue))}},fn2(payload.value,payload)});return ch}function _check(fn2,params){let ch=new $ZodCheck({check:"custom",...normalizeParams(params)});return ch._zod.check=fn2,ch}function describe(description){let ch=new $ZodCheck({check:"describe"});return ch._zod.onattach=[(inst)=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}],ch._zod.check=()=>{},ch}function meta(metadata){let ch=new $ZodCheck({check:"meta"});return ch._zod.onattach=[(inst)=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}],ch._zod.check=()=>{},ch}function _stringbool(Classes,_params){let params=normalizeParams(_params),truthyArray=params.truthy??["true","1","yes","on","y","enabled"],falsyArray=params.falsy??["false","0","no","off","n","disabled"];if(params.case!=="sensitive")truthyArray=truthyArray.map((v)=>typeof v==="string"?v.toLowerCase():v),falsyArray=falsyArray.map((v)=>typeof v==="string"?v.toLowerCase():v);let truthySet=new Set(truthyArray),falsySet=new Set(falsyArray),_Codec=Classes.Codec??$ZodCodec,_Boolean=Classes.Boolean??$ZodBoolean,stringSchema=new(Classes.String??$ZodString)({type:"string",error:params.error}),booleanSchema=new _Boolean({type:"boolean",error:params.error}),codec=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:(input,payload)=>{let data=input;if(params.case!=="sensitive")data=data.toLowerCase();if(truthySet.has(data))return!0;else if(falsySet.has(data))return!1;else return payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec,continue:!1}),{}},reverseTransform:(input,_payload)=>{if(input===!0)return truthyArray[0]||"true";else return falsyArray[0]||"false"},error:params.error});return codec}function _stringFormat(Class2,format,fnOrRegex,_params={}){let params=normalizeParams(_params),def={...normalizeParams(_params),check:"string_format",type:"string",format,fn:typeof fnOrRegex==="function"?fnOrRegex:(val)=>fnOrRegex.test(val),...params};if(fnOrRegex instanceof RegExp)def.pattern=fnOrRegex;return new Class2(def)}var TimePrecision;var init_api=__esm(()=>{init_checks();init_registries();init_schemas();init_util();TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function initializeContext(params){let target=params?.target??"draft-2020-12";if(target==="draft-4")target="draft-04";if(target==="draft-7")target="draft-07";return{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,cycles:params?.cycles??"ref",reused:params?.reused??"inline",external:params?.external??void 0}}function process2(schema,ctx,_params={path:[],schemaPath:[]}){var _a2;let def=schema._zod.def,seen=ctx.seen.get(schema);if(seen){if(seen.count++,_params.schemaPath.includes(schema))seen.cycle=_params.path;return seen.schema}let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result);let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema)schema._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema,ctx,_json,params)}let parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;process2(parent,ctx,params),ctx.seen.get(parent).isParent=!0}}let meta2=ctx.metadataRegistry.get(schema);if(meta2)Object.assign(result.schema,meta2);if(ctx.io==="input"&&isTransforming(schema))delete result.schema.examples,delete result.schema.default;if(ctx.io==="input"&&result.schema._prefault)(_a2=result.schema).default??(_a2.default=result.schema._prefault);return delete result.schema._prefault,ctx.seen.get(schema).schema}function extractDefs(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry[0])throw Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id,entry[0])}}let makeURI=(entry)=>{let defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??((id2)=>id2);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${id}`}}if(entry[1]===root)return{ref:"#"};let defUriPrefix=`${"#"}/${defsSegment}/`,defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+defId}},extractToDef=(entry)=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);if(seen.def={...seen.schema},defId)seen.defId=defId;let schema2=seen.schema;for(let key in schema2)delete schema2[key];schema2.$ref=ref};if(ctx.cycles==="throw")for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
|
|
157
157
|
|
|
158
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry);continue}}}}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=(zodSchema)=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"))schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema);else Object.assign(schema2,refSchema);if(Object.assign(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached))delete schema2[key]}if(refSchema.$ref&&refSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key]))delete schema2[key]}}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){if(schema2.$ref=parentSeen.schema.$ref,parentSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key]))delete schema2[key]}}}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);let result={};if(ctx.target==="draft-2020-12")result.$schema="https://json-schema.org/draft/2020-12/schema";else if(ctx.target==="draft-07")result.$schema="http://json-schema.org/draft-07/schema#";else if(ctx.target==="draft-04")result.$schema="http://json-schema.org/draft-04/schema#";else if(ctx.target==="openapi-3.0");if(ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);let defs=ctx.external?.defs??{};for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.def&&seen.defId)defs[seen.defId]=seen.def}if(ctx.external);else if(Object.keys(defs).length>0)if(ctx.target==="draft-2020-12")result.$defs=defs;else result.definitions=defs;try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch(_err){throw Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;if(def.rest&&isTransforming(def.rest,ctx))return!0;return!1}return!1}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{let ctx=initializeContext({...params,processors});return process2(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return process2(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var init_to_json_schema=__esm(()=>{init_registries()});function toJSONSchema(input,params){if("_idmap"in input){let registry2=input,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema]=entry;process2(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema]=entry;extractDefs(ctx2,schema),schemas[key]=finalize(ctx2,schema)}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return process2(input,ctx),extractDefs(ctx,input),finalize(ctx,input)}var formatMap,stringProcessor=(schema,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){if(json.format=formatMap[format]??format,json.format==="")delete json.format;if(format==="time")delete json.format}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){let regexes=[...patterns];if(regexes.length===1)json.pattern=regexes[0].source;else if(regexes.length>1)json.allOf=[...regexes.map((regex)=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}},numberProcessor=(schema,ctx,_json,_params)=>{let json=_json,{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema._zod.bag;if(typeof format==="string"&&format.includes("int"))json.type="integer";else json.type="number";if(typeof exclusiveMinimum==="number")if(ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0;else json.exclusiveMinimum=exclusiveMinimum;if(typeof minimum==="number"){if(json.minimum=minimum,typeof exclusiveMinimum==="number"&&ctx.target!=="draft-04")if(exclusiveMinimum>=minimum)delete json.minimum;else delete json.exclusiveMinimum}if(typeof exclusiveMaximum==="number")if(ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0;else json.exclusiveMaximum=exclusiveMaximum;if(typeof maximum==="number"){if(json.maximum=maximum,typeof exclusiveMaximum==="number"&&ctx.target!=="draft-04")if(exclusiveMaximum<=maximum)delete json.maximum;else delete json.exclusiveMaximum}if(typeof multipleOf==="number")json.multipleOf=multipleOf},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0")json.type="string",json.nullable=!0,json.enum=[null];else json.type="null"},undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json,_params)=>{let def=schema._zod.def,values=getEnumValues(def.entries);if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values},literalProcessor=(schema,ctx,json,_params)=>{let def=schema._zod.def,vals=[];for(let val of def.values)if(val===void 0){if(ctx.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof val==="bigint")if(ctx.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else vals.push(Number(val));else vals.push(val);if(vals.length===0);else if(vals.length===1){let val=vals[0];if(json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.enum=[val];else json.const=val}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}},nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json,_params)=>{let _json=json,pattern=schema._zod.pattern;if(!pattern)throw Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json,_params)=>{let _json=json,file={type:"string",format:"binary",contentEncoding:"binary"},{minimum,maximum,mime}=schema._zod.bag;if(minimum!==void 0)file.minLength=minimum;if(maximum!==void 0)file.maxLength=maximum;if(mime)if(mime.length===1)file.contentMediaType=mime[0],Object.assign(_json,file);else Object.assign(_json,file),_json.anyOf=mime.map((m)=>({contentMediaType:m}));else Object.assign(_json,file)},successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array",json.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})},objectProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object",json.properties={};let shape=def.shape;for(let key in shape)json.properties[key]=process2(shape[key],ctx,{...params,path:[...params.path,"properties",key]});let allKeys=new Set(Object.keys(shape)),requiredKeys=new Set([...allKeys].filter((key)=>{let v=def.shape[key]._zod;if(ctx.io==="input")return v.optin===void 0;else return v.optout===void 0}));if(requiredKeys.size>0)json.required=Array.from(requiredKeys);if(def.catchall?._zod.def.type==="never")json.additionalProperties=!1;else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=!1}else if(def.catchall)json.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive)json.oneOf=options;else json.anyOf=options},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf},tupleProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?process2(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;if(ctx.target==="draft-2020-12"){if(json.prefixItems=prefixItems,rest)json.items=rest}else if(ctx.target==="openapi-3.0"){if(json.items={anyOf:prefixItems},rest)json.items.anyOf.push(rest);if(json.minItems=prefixItems.length,!rest)json.maxItems=prefixItems.length}else if(json.items=prefixItems,rest)json.additionalItems=rest;let{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum},recordProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object";let keyType=def.keyType,patterns=keyType._zod.bag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let pattern of patterns)json.patternProperties[pattern.source]=valueSchema}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12")json.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});json.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values;if(keyValues){let validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0)json.required=validKeyValues}},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=process2(def.innerType,ctx,params),seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0")seen.ref=def.innerType,json.nullable=!0;else json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.default=JSON.parse(JSON.stringify(def.defaultValue))},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io==="input")json._prefault=JSON.parse(JSON.stringify(def.defaultValue))},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,innerType=ctx.io==="input"?def.in._zod.def.type==="transform"?def.out:def.in:def.out;process2(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;process2(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors;var init_json_schema_processors=__esm(()=>{init_to_json_schema();init_util();formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}});class JSONSchemaGenerator{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return process2(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_,...plainResult}=result;return plainResult}}var init_json_schema_generator=__esm(()=>{init_json_schema_processors();init_to_json_schema()});var exports_json_schema={};var init_json_schema=()=>{};var exports_core2={};__export(exports_core2,{version:()=>version,util:()=>exports_util,treeifyError:()=>treeifyError,toJSONSchema:()=>toJSONSchema,toDotPath:()=>toDotPath,safeParseAsync:()=>safeParseAsync,safeParse:()=>safeParse,safeEncodeAsync:()=>safeEncodeAsync,safeEncode:()=>safeEncode,safeDecodeAsync:()=>safeDecodeAsync,safeDecode:()=>safeDecode,registry:()=>registry,regexes:()=>exports_regexes,process:()=>process2,prettifyError:()=>prettifyError,parseAsync:()=>parseAsync,parse:()=>parse,meta:()=>meta,locales:()=>exports_locales,isValidJWT:()=>isValidJWT,isValidBase64URL:()=>isValidBase64URL,isValidBase64:()=>isValidBase64,initializeContext:()=>initializeContext,globalRegistry:()=>globalRegistry,globalConfig:()=>globalConfig,formatError:()=>formatError,flattenError:()=>flattenError,finalize:()=>finalize,extractDefs:()=>extractDefs,encodeAsync:()=>encodeAsync,encode:()=>encode,describe:()=>describe,decodeAsync:()=>decodeAsync,decode:()=>decode,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,config:()=>config,clone:()=>clone,_xor:()=>_xor,_xid:()=>_xid,_void:()=>_void,_uuidv7:()=>_uuidv7,_uuidv6:()=>_uuidv6,_uuidv4:()=>_uuidv4,_uuid:()=>_uuid,_url:()=>_url,_uppercase:()=>_uppercase,_unknown:()=>_unknown,_union:()=>_union,_undefined:()=>_undefined2,_ulid:()=>_ulid,_uint64:()=>_uint64,_uint32:()=>_uint32,_tuple:()=>_tuple,_trim:()=>_trim,_transform:()=>_transform,_toUpperCase:()=>_toUpperCase,_toLowerCase:()=>_toLowerCase,_templateLiteral:()=>_templateLiteral,_symbol:()=>_symbol,_superRefine:()=>_superRefine,_success:()=>_success,_stringbool:()=>_stringbool,_stringFormat:()=>_stringFormat,_string:()=>_string,_startsWith:()=>_startsWith,_slugify:()=>_slugify,_size:()=>_size,_set:()=>_set,_safeParseAsync:()=>_safeParseAsync,_safeParse:()=>_safeParse,_safeEncodeAsync:()=>_safeEncodeAsync,_safeEncode:()=>_safeEncode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeDecode:()=>_safeDecode,_regex:()=>_regex,_refine:()=>_refine,_record:()=>_record,_readonly:()=>_readonly,_property:()=>_property,_promise:()=>_promise,_positive:()=>_positive,_pipe:()=>_pipe,_parseAsync:()=>_parseAsync,_parse:()=>_parse,_overwrite:()=>_overwrite,_optional:()=>_optional,_number:()=>_number,_nullable:()=>_nullable,_null:()=>_null2,_normalize:()=>_normalize,_nonpositive:()=>_nonpositive,_nonoptional:()=>_nonoptional,_nonnegative:()=>_nonnegative,_never:()=>_never,_negative:()=>_negative,_nativeEnum:()=>_nativeEnum,_nanoid:()=>_nanoid,_nan:()=>_nan,_multipleOf:()=>_multipleOf,_minSize:()=>_minSize,_minLength:()=>_minLength,_min:()=>_gte,_mime:()=>_mime,_maxSize:()=>_maxSize,_maxLength:()=>_maxLength,_max:()=>_lte,_map:()=>_map,_mac:()=>_mac,_lte:()=>_lte,_lt:()=>_lt,_lowercase:()=>_lowercase,_literal:()=>_literal,_length:()=>_length,_lazy:()=>_lazy,_ksuid:()=>_ksuid,_jwt:()=>_jwt,_isoTime:()=>_isoTime,_isoDuration:()=>_isoDuration,_isoDateTime:()=>_isoDateTime,_isoDate:()=>_isoDate,_ipv6:()=>_ipv6,_ipv4:()=>_ipv4,_intersection:()=>_intersection,_int64:()=>_int64,_int32:()=>_int32,_int:()=>_int,_includes:()=>_includes,_guid:()=>_guid,_gte:()=>_gte,_gt:()=>_gt,_float64:()=>_float64,_float32:()=>_float32,_file:()=>_file,_enum:()=>_enum,_endsWith:()=>_endsWith,_encodeAsync:()=>_encodeAsync,_encode:()=>_encode,_emoji:()=>_emoji2,_email:()=>_email,_e164:()=>_e164,_discriminatedUnion:()=>_discriminatedUnion,_default:()=>_default,_decodeAsync:()=>_decodeAsync,_decode:()=>_decode,_date:()=>_date,_custom:()=>_custom,_cuid2:()=>_cuid2,_cuid:()=>_cuid,_coercedString:()=>_coercedString,_coercedNumber:()=>_coercedNumber,_coercedDate:()=>_coercedDate,_coercedBoolean:()=>_coercedBoolean,_coercedBigint:()=>_coercedBigint,_cidrv6:()=>_cidrv6,_cidrv4:()=>_cidrv4,_check:()=>_check,_catch:()=>_catch,_boolean:()=>_boolean,_bigint:()=>_bigint,_base64url:()=>_base64url,_base64:()=>_base64,_array:()=>_array,_any:()=>_any,TimePrecision:()=>TimePrecision,NEVER:()=>NEVER,JSONSchemaGenerator:()=>JSONSchemaGenerator,JSONSchema:()=>exports_json_schema,Doc:()=>Doc,$output:()=>$output,$input:()=>$input,$constructor:()=>$constructor,$brand:()=>$brand,$ZodXor:()=>$ZodXor,$ZodXID:()=>$ZodXID,$ZodVoid:()=>$ZodVoid,$ZodUnknown:()=>$ZodUnknown,$ZodUnion:()=>$ZodUnion,$ZodUndefined:()=>$ZodUndefined,$ZodUUID:()=>$ZodUUID,$ZodURL:()=>$ZodURL,$ZodULID:()=>$ZodULID,$ZodType:()=>$ZodType,$ZodTuple:()=>$ZodTuple,$ZodTransform:()=>$ZodTransform,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodSymbol:()=>$ZodSymbol,$ZodSuccess:()=>$ZodSuccess,$ZodStringFormat:()=>$ZodStringFormat,$ZodString:()=>$ZodString,$ZodSet:()=>$ZodSet,$ZodRegistry:()=>$ZodRegistry,$ZodRecord:()=>$ZodRecord,$ZodRealError:()=>$ZodRealError,$ZodReadonly:()=>$ZodReadonly,$ZodPromise:()=>$ZodPromise,$ZodPrefault:()=>$ZodPrefault,$ZodPipe:()=>$ZodPipe,$ZodOptional:()=>$ZodOptional,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodObject:()=>$ZodObject,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodNumber:()=>$ZodNumber,$ZodNullable:()=>$ZodNullable,$ZodNull:()=>$ZodNull,$ZodNonOptional:()=>$ZodNonOptional,$ZodNever:()=>$ZodNever,$ZodNanoID:()=>$ZodNanoID,$ZodNaN:()=>$ZodNaN,$ZodMap:()=>$ZodMap,$ZodMAC:()=>$ZodMAC,$ZodLiteral:()=>$ZodLiteral,$ZodLazy:()=>$ZodLazy,$ZodKSUID:()=>$ZodKSUID,$ZodJWT:()=>$ZodJWT,$ZodIntersection:()=>$ZodIntersection,$ZodISOTime:()=>$ZodISOTime,$ZodISODuration:()=>$ZodISODuration,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODate:()=>$ZodISODate,$ZodIPv6:()=>$ZodIPv6,$ZodIPv4:()=>$ZodIPv4,$ZodGUID:()=>$ZodGUID,$ZodFunction:()=>$ZodFunction,$ZodFile:()=>$ZodFile,$ZodExactOptional:()=>$ZodExactOptional,$ZodError:()=>$ZodError,$ZodEnum:()=>$ZodEnum,$ZodEncodeError:()=>$ZodEncodeError,$ZodEmoji:()=>$ZodEmoji,$ZodEmail:()=>$ZodEmail,$ZodE164:()=>$ZodE164,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodDefault:()=>$ZodDefault,$ZodDate:()=>$ZodDate,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodCustom:()=>$ZodCustom,$ZodCodec:()=>$ZodCodec,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheck:()=>$ZodCheck,$ZodCatch:()=>$ZodCatch,$ZodCUID2:()=>$ZodCUID2,$ZodCUID:()=>$ZodCUID,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodBoolean:()=>$ZodBoolean,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBigInt:()=>$ZodBigInt,$ZodBase64URL:()=>$ZodBase64URL,$ZodBase64:()=>$ZodBase64,$ZodAsyncError:()=>$ZodAsyncError,$ZodArray:()=>$ZodArray,$ZodAny:()=>$ZodAny});var init_core2=__esm(()=>{init_util();init_regexes();init_locales();init_json_schema_processors();init_json_schema_generator();init_json_schema();init_core();init_parse();init_errors();init_schemas();init_checks();init_versions();init_registries();init_api();init_to_json_schema()});var exports_checks2={};__export(exports_checks2,{uppercase:()=>_uppercase,trim:()=>_trim,toUpperCase:()=>_toUpperCase,toLowerCase:()=>_toLowerCase,startsWith:()=>_startsWith,slugify:()=>_slugify,size:()=>_size,regex:()=>_regex,property:()=>_property,positive:()=>_positive,overwrite:()=>_overwrite,normalize:()=>_normalize,nonpositive:()=>_nonpositive,nonnegative:()=>_nonnegative,negative:()=>_negative,multipleOf:()=>_multipleOf,minSize:()=>_minSize,minLength:()=>_minLength,mime:()=>_mime,maxSize:()=>_maxSize,maxLength:()=>_maxLength,lte:()=>_lte,lt:()=>_lt,lowercase:()=>_lowercase,length:()=>_length,includes:()=>_includes,gte:()=>_gte,gt:()=>_gt,endsWith:()=>_endsWith});var init_checks2=__esm(()=>{init_core2()});var exports_iso={};__export(exports_iso,{time:()=>time2,duration:()=>duration2,datetime:()=>datetime2,date:()=>date2,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration;var init_iso=__esm(()=>{init_core2();init_schemas2();ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)})});var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:(mapper)=>formatError(inst,mapper)},flatten:{value:(mapper)=>flattenError(inst,mapper)},addIssue:{value:(issue2)=>{inst.issues.push(issue2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:(issues2)=>{inst.issues.push(...issues2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})},ZodError,ZodRealError;var init_errors2=__esm(()=>{init_core2();init_core2();init_util();ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,{Parent:Error})});var parse3,parseAsync2,safeParse2,safeParseAsync2,encode2,decode2,encodeAsync2,decodeAsync2,safeEncode2,safeDecode2,safeEncodeAsync2,safeDecodeAsync2;var init_parse2=__esm(()=>{init_core2();init_errors2();parse3=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError)});var exports_schemas2={};__export(exports_schemas2,{xor:()=>xor,xid:()=>xid2,void:()=>_void2,uuidv7:()=>uuidv7,uuidv6:()=>uuidv6,uuidv4:()=>uuidv4,uuid:()=>uuid2,url:()=>url,unknown:()=>unknown,union:()=>union,undefined:()=>_undefined3,ulid:()=>ulid2,uint64:()=>uint64,uint32:()=>uint32,tuple:()=>tuple,transform:()=>transform,templateLiteral:()=>templateLiteral,symbol:()=>symbol,superRefine:()=>superRefine,success:()=>success,stringbool:()=>stringbool,stringFormat:()=>stringFormat,string:()=>string2,strictObject:()=>strictObject,set:()=>set,refine:()=>refine,record:()=>record,readonly:()=>readonly,promise:()=>promise,preprocess:()=>preprocess,prefault:()=>prefault,pipe:()=>pipe,partialRecord:()=>partialRecord,optional:()=>optional,object:()=>object,number:()=>number2,nullish:()=>nullish2,nullable:()=>nullable,null:()=>_null3,nonoptional:()=>nonoptional,never:()=>never,nativeEnum:()=>nativeEnum,nanoid:()=>nanoid2,nan:()=>nan,meta:()=>meta2,map:()=>map,mac:()=>mac2,looseRecord:()=>looseRecord,looseObject:()=>looseObject,literal:()=>literal,lazy:()=>lazy,ksuid:()=>ksuid2,keyof:()=>keyof,jwt:()=>jwt,json:()=>json,ipv6:()=>ipv62,ipv4:()=>ipv42,intersection:()=>intersection,int64:()=>int64,int32:()=>int32,int:()=>int,instanceof:()=>_instanceof,httpUrl:()=>httpUrl,hostname:()=>hostname2,hex:()=>hex2,hash:()=>hash,guid:()=>guid2,function:()=>_function,float64:()=>float64,float32:()=>float32,file:()=>file,exactOptional:()=>exactOptional,enum:()=>_enum2,emoji:()=>emoji2,email:()=>email2,e164:()=>e1642,discriminatedUnion:()=>discriminatedUnion,describe:()=>describe2,date:()=>date3,custom:()=>custom,cuid2:()=>cuid22,cuid:()=>cuid3,codec:()=>codec,cidrv6:()=>cidrv62,cidrv4:()=>cidrv42,check:()=>check,catch:()=>_catch2,boolean:()=>boolean2,bigint:()=>bigint2,base64url:()=>base64url2,base64:()=>base642,array:()=>array,any:()=>any,_function:()=>_function,_default:()=>_default2,_ZodString:()=>_ZodString,ZodXor:()=>ZodXor,ZodXID:()=>ZodXID,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodUUID:()=>ZodUUID,ZodURL:()=>ZodURL,ZodULID:()=>ZodULID,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransform:()=>ZodTransform,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodSymbol:()=>ZodSymbol,ZodSuccess:()=>ZodSuccess,ZodStringFormat:()=>ZodStringFormat,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodRecord:()=>ZodRecord,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPrefault:()=>ZodPrefault,ZodPipe:()=>ZodPipe,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumberFormat:()=>ZodNumberFormat,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNonOptional:()=>ZodNonOptional,ZodNever:()=>ZodNever,ZodNanoID:()=>ZodNanoID,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodMAC:()=>ZodMAC,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodKSUID:()=>ZodKSUID,ZodJWT:()=>ZodJWT,ZodIntersection:()=>ZodIntersection,ZodIPv6:()=>ZodIPv6,ZodIPv4:()=>ZodIPv4,ZodGUID:()=>ZodGUID,ZodFunction:()=>ZodFunction,ZodFile:()=>ZodFile,ZodExactOptional:()=>ZodExactOptional,ZodEnum:()=>ZodEnum,ZodEmoji:()=>ZodEmoji,ZodEmail:()=>ZodEmail,ZodE164:()=>ZodE164,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodCustom:()=>ZodCustom,ZodCodec:()=>ZodCodec,ZodCatch:()=>ZodCatch,ZodCUID2:()=>ZodCUID2,ZodCUID:()=>ZodCUID,ZodCIDRv6:()=>ZodCIDRv6,ZodCIDRv4:()=>ZodCIDRv4,ZodBoolean:()=>ZodBoolean,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBigInt:()=>ZodBigInt,ZodBase64URL:()=>ZodBase64URL,ZodBase64:()=>ZodBase64,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny});function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function guid2(params){return _guid(ZodGUID,params)}function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:/^https?$/,hostname:exports_regexes.domain,...exports_util.normalizeParams(params)})}function emoji2(params){return _emoji2(ZodEmoji,params)}function nanoid2(params){return _nanoid(ZodNanoID,params)}function cuid3(params){return _cuid(ZodCUID,params)}function cuid22(params){return _cuid2(ZodCUID2,params)}function ulid2(params){return _ulid(ZodULID,params)}function xid2(params){return _xid(ZodXID,params)}function ksuid2(params){return _ksuid(ZodKSUID,params)}function ipv42(params){return _ipv4(ZodIPv4,params)}function mac2(params){return _mac(ZodMAC,params)}function ipv62(params){return _ipv6(ZodIPv6,params)}function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}function base642(params){return _base64(ZodBase64,params)}function base64url2(params){return _base64url(ZodBase64URL,params)}function e1642(params){return _e164(ZodE164,params)}function jwt(params){return _jwt(ZodJWT,params)}function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",exports_regexes.hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",exports_regexes.hex,_params)}function hash(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=exports_regexes[format];if(!regex)throw Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function bigint2(params){return _bigint(ZodBigInt,params)}function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}function symbol(params){return _symbol(ZodSymbol,params)}function _undefined3(params){return _undefined2(ZodUndefined,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function _void2(params){return _void(ZodVoid,params)}function date3(params){return _date(ZodDate,params)}function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}function object(shape,params){let def={type:"object",shape:shape??{},...exports_util.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...exports_util.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...exports_util.normalizeParams(params)})}function union(options,params){return new ZodUnion({type:"union",options,...exports_util.normalizeParams(params)})}function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...exports_util.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...exports_util.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest;return new ZodTuple({type:"tuple",items,rest:hasRest?_paramsOrRest:null,...exports_util.normalizeParams(params)})}function record(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...exports_util.normalizeParams(params)})}function partialRecord(keyType,valueType,params){let k=clone(keyType);return k._zod.values=void 0,new ZodRecord({type:"record",keyType:k,valueType,...exports_util.normalizeParams(params)})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...exports_util.normalizeParams(params)})}function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...exports_util.normalizeParams(params)})}function set(valueType,params){return new ZodSet({type:"set",valueType,...exports_util.normalizeParams(params)})}function _enum2(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...exports_util.normalizeParams(params)})}function file(params){return _file(ZodFile,params)}function transform(fn2){return new ZodTransform({type:"transform",transform:fn2})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...exports_util.normalizeParams(params)})}function success(innerType){return new ZodSuccess({type:"success",innerType})}function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function nan(params){return _nan(ZodNaN,params)}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...exports_util.normalizeParams(params)})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function promise(innerType){return new ZodPromise({type:"promise",innerType})}function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}function check(fn2){let ch=new $ZodCheck({check:"custom"});return ch._zod.check=fn2,ch}function custom(fn2,_params){return _custom(ZodCustom,fn2??(()=>!0),_params)}function refine(fn2,_params={}){return _refine(ZodCustom,fn2,_params)}function superRefine(fn2){return _superRefine(fn2)}function _instanceof(cls,params={}){let inst=new ZodCustom({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:!0,...exports_util.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=(payload)=>{if(!(payload.value instanceof cls))payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}function json(params){let jsonSchema=lazy(()=>{return union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn2,schema){return pipe(transform(fn2),schema)}var ZodType,_ZodString,ZodString,ZodStringFormat,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodMAC,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodJWT,ZodCustomStringFormat,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodBigIntFormat,ZodSymbol,ZodUndefined,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodVoid,ZodDate,ZodArray,ZodObject,ZodUnion,ZodXor,ZodDiscriminatedUnion,ZodIntersection,ZodTuple,ZodRecord,ZodMap,ZodSet,ZodEnum,ZodLiteral,ZodFile,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodSuccess,ZodCatch,ZodNaN,ZodPipe,ZodCodec,ZodReadonly,ZodTemplateLiteral,ZodLazy,ZodPromise,ZodFunction,ZodCustom,describe2,meta2,stringbool=(...args2)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args2);var init_schemas2=__esm(()=>{init_core2();init_core2();init_json_schema_processors();init_to_json_schema();init_checks2();init_iso();init_parse2();ZodType=$constructor("ZodType",(inst,def)=>{return $ZodType.init(inst,def),Object.assign(inst["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,"input"),output:createStandardJSONSchemaMethod(inst,"output")}}),inst.toJSONSchema=createToJSONSchemaMethod(inst,{}),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.check=(...checks2)=>{return inst.clone(exports_util.mergeDefs(def,{checks:[...def.checks??[],...checks2.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},inst.with=inst.check,inst.clone=(def2,params)=>clone(inst,def2,params),inst.brand=()=>inst,inst.register=(reg,meta2)=>{return reg.add(inst,meta2),inst},inst.parse=(data,params)=>parse3(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse2(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync2(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync2(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode2(inst,data,params),inst.decode=(data,params)=>decode2(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync2(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync2(inst,data,params),inst.safeEncode=(data,params)=>safeEncode2(inst,data,params),inst.safeDecode=(data,params)=>safeDecode2(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync2(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync2(inst,data,params),inst.refine=(check,params)=>inst.check(refine(check,params)),inst.superRefine=(refinement)=>inst.check(superRefine(refinement)),inst.overwrite=(fn2)=>inst.check(_overwrite(fn2)),inst.optional=()=>optional(inst),inst.exactOptional=()=>exactOptional(inst),inst.nullable=()=>nullable(inst),inst.nullish=()=>optional(nullable(inst)),inst.nonoptional=(params)=>nonoptional(inst,params),inst.array=()=>array(inst),inst.or=(arg)=>union([inst,arg]),inst.and=(arg)=>intersection(inst,arg),inst.transform=(tx)=>pipe(inst,transform(tx)),inst.default=(def2)=>_default2(inst,def2),inst.prefault=(def2)=>prefault(inst,def2),inst.catch=(params)=>_catch2(inst,params),inst.pipe=(target)=>pipe(inst,target),inst.readonly=()=>readonly(inst),inst.describe=(description)=>{let cl=inst.clone();return globalRegistry.add(cl,{description}),cl},Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst.meta=(...args2)=>{if(args2.length===0)return globalRegistry.get(inst);let cl=inst.clone();return globalRegistry.add(cl,args2[0]),cl},inst.isOptional=()=>inst.safeParse(void 0).success,inst.isNullable=()=>inst.safeParse(null).success,inst.apply=(fn2)=>fn2(inst),inst}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,inst.regex=(...args2)=>inst.check(_regex(...args2)),inst.includes=(...args2)=>inst.check(_includes(...args2)),inst.startsWith=(...args2)=>inst.check(_startsWith(...args2)),inst.endsWith=(...args2)=>inst.check(_endsWith(...args2)),inst.min=(...args2)=>inst.check(_minLength(...args2)),inst.max=(...args2)=>inst.check(_maxLength(...args2)),inst.length=(...args2)=>inst.check(_length(...args2)),inst.nonempty=(...args2)=>inst.check(_minLength(1,...args2)),inst.lowercase=(params)=>inst.check(_lowercase(params)),inst.uppercase=(params)=>inst.check(_uppercase(params)),inst.trim=()=>inst.check(_trim()),inst.normalize=(...args2)=>inst.check(_normalize(...args2)),inst.toLowerCase=()=>inst.check(_toLowerCase()),inst.toUpperCase=()=>inst.check(_toUpperCase()),inst.slugify=()=>inst.check(_slugify())}),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=(params)=>inst.check(_email(ZodEmail,params)),inst.url=(params)=>inst.check(_url(ZodURL,params)),inst.jwt=(params)=>inst.check(_jwt(ZodJWT,params)),inst.emoji=(params)=>inst.check(_emoji2(ZodEmoji,params)),inst.guid=(params)=>inst.check(_guid(ZodGUID,params)),inst.uuid=(params)=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=(params)=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=(params)=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=(params)=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=(params)=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=(params)=>inst.check(_guid(ZodGUID,params)),inst.cuid=(params)=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=(params)=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=(params)=>inst.check(_ulid(ZodULID,params)),inst.base64=(params)=>inst.check(_base64(ZodBase64,params)),inst.base64url=(params)=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=(params)=>inst.check(_xid(ZodXID,params)),inst.ksuid=(params)=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=(params)=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=(params)=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=(params)=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=(params)=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=(params)=>inst.check(_e164(ZodE164,params)),inst.datetime=(params)=>inst.check(datetime2(params)),inst.date=(params)=>inst.check(date2(params)),inst.time=(params)=>inst.check(time2(params)),inst.duration=(params)=>inst.check(duration2(params))});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.int=(params)=>inst.check(int(params)),inst.safe=(params)=>inst.check(int(params)),inst.positive=(params)=>inst.check(_gt(0,params)),inst.nonnegative=(params)=>inst.check(_gte(0,params)),inst.negative=(params)=>inst.check(_lt(0,params)),inst.nonpositive=(params)=>inst.check(_lte(0,params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params)),inst.step=(value,params)=>inst.check(_multipleOf(value,params)),inst.finite=()=>inst;let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??0.5),inst.isFinite=!0,inst.format=bag.format??null});ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>bigintProcessor(inst,ctx,json,params),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.positive=(params)=>inst.check(_gt(BigInt(0),params)),inst.negative=(params)=>inst.check(_lt(BigInt(0),params)),inst.nonpositive=(params)=>inst.check(_lte(BigInt(0),params)),inst.nonnegative=(params)=>inst.check(_gte(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null});ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>symbolProcessor(inst,ctx,json,params)});ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>undefinedProcessor(inst,ctx,json,params)});ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>anyProcessor(inst,ctx,json,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>voidProcessor(inst,ctx,json,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>dateProcessor(inst,ctx,json,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null});ZodArray=$constructor("ZodArray",(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element,inst.min=(minLength,params)=>inst.check(_minLength(minLength,params)),inst.nonempty=(params)=>inst.check(_minLength(1,params)),inst.max=(maxLength,params)=>inst.check(_maxLength(maxLength,params)),inst.length=(len,params)=>inst.check(_length(len,params)),inst.unwrap=()=>inst.element});ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),exports_util.defineLazy(inst,"shape",()=>{return def.shape}),inst.keyof=()=>_enum2(Object.keys(inst._zod.def.shape)),inst.catchall=(catchall)=>inst.clone({...inst._zod.def,catchall}),inst.passthrough=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.loose=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.strict=()=>inst.clone({...inst._zod.def,catchall:never()}),inst.strip=()=>inst.clone({...inst._zod.def,catchall:void 0}),inst.extend=(incoming)=>{return exports_util.extend(inst,incoming)},inst.safeExtend=(incoming)=>{return exports_util.safeExtend(inst,incoming)},inst.merge=(other)=>exports_util.merge(inst,other),inst.pick=(mask)=>exports_util.pick(inst,mask),inst.omit=(mask)=>exports_util.omit(inst,mask),inst.partial=(...args2)=>exports_util.partial(ZodOptional,inst,args2[0]),inst.required=(...args2)=>exports_util.required(ZodNonOptional,inst,args2[0])});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});ZodTuple=$constructor("ZodTuple",(inst,def)=>{$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>tupleProcessor(inst,ctx,json,params),inst.rest=(rest)=>inst.clone({...inst._zod.def,rest})});ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodMap=$constructor("ZodMap",(inst,def)=>{$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>mapProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args2)=>inst.check(_minSize(...args2)),inst.nonempty=(params)=>inst.check(_minSize(1,params)),inst.max=(...args2)=>inst.check(_maxSize(...args2)),inst.size=(...args2)=>inst.check(_size(...args2))});ZodSet=$constructor("ZodSet",(inst,def)=>{$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>setProcessor(inst,ctx,json,params),inst.min=(...args2)=>inst.check(_minSize(...args2)),inst.nonempty=(params)=>inst.check(_minSize(1,params)),inst.max=(...args2)=>inst.check(_maxSize(...args2)),inst.size=(...args2)=>inst.check(_size(...args2))});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>fileProcessor(inst,ctx,json,params),inst.min=(size,params)=>inst.check(_minSize(size,params)),inst.max=(size,params)=>inst.check(_maxSize(size,params)),inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});ZodTransform=$constructor("ZodTransform",(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=(issue2)=>{if(typeof issue2==="string")payload.issues.push(exports_util.issue(issue2,payload.value,def));else{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(exports_util.issue(_issue))}};let output=def.transform(payload.value,payload);if(output instanceof Promise)return output.then((output2)=>{return payload.value=output2,payload});return payload.value=output,payload}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>successProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nanProcessor(inst,ctx,json,params)});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>templateLiteralProcessor(inst,ctx,json,params)});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>lazyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.getter()});ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>promiseProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>functionProcessor(inst,ctx,json,params)});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});describe2=describe,meta2=meta});function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodIssueCode,ZodFirstPartyTypeKind;var init_compat=__esm(()=>{init_core2();ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(ZodFirstPartyTypeKind2){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}))});function detectVersion(schema,defaultTarget){let $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if($schema==="http://json-schema.org/draft-07/schema#")return"draft-7";if($schema==="http://json-schema.org/draft-04/schema#")return"draft-4";return defaultTarget??"draft-2020-12"}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let path=ref.slice(1).split("/").filter(Boolean);if(path.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){let key=path[1];if(!key||!ctx.defs[key])throw Error(`Reference not found: ${ref}`);return ctx.defs[key]}throw Error(`Reference not found: ${ref}`)}function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0)return z.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z.lazy(()=>{if(!ctx.refs.has(refPath))throw Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z.null();if(enumValues.length===0)return z.never();if(enumValues.length===1)return z.literal(enumValues[0]);if(enumValues.every((v)=>typeof v==="string"))return z.enum(enumValues);let literalSchemas=enumValues.map((v)=>z.literal(v));if(literalSchemas.length<2)return literalSchemas[0];return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z.literal(schema.const);let type=schema.type;if(Array.isArray(type)){let typeSchemas=type.map((t)=>{let typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0)return z.never();if(typeSchemas.length===1)return typeSchemas[0];return z.union(typeSchemas)}if(!type)return z.any();let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){let format=schema.format;if(format==="email")stringSchema=stringSchema.check(z.email());else if(format==="uri"||format==="uri-reference")stringSchema=stringSchema.check(z.url());else if(format==="uuid"||format==="guid")stringSchema=stringSchema.check(z.uuid());else if(format==="date-time")stringSchema=stringSchema.check(z.iso.datetime());else if(format==="date")stringSchema=stringSchema.check(z.iso.date());else if(format==="time")stringSchema=stringSchema.check(z.iso.time());else if(format==="duration")stringSchema=stringSchema.check(z.iso.duration());else if(format==="ipv4")stringSchema=stringSchema.check(z.ipv4());else if(format==="ipv6")stringSchema=stringSchema.check(z.ipv6());else if(format==="mac")stringSchema=stringSchema.check(z.mac());else if(format==="cidr")stringSchema=stringSchema.check(z.cidrv4());else if(format==="cidr-v6")stringSchema=stringSchema.check(z.cidrv6());else if(format==="base64")stringSchema=stringSchema.check(z.base64());else if(format==="base64url")stringSchema=stringSchema.check(z.base64url());else if(format==="e164")stringSchema=stringSchema.check(z.e164());else if(format==="jwt")stringSchema=stringSchema.check(z.jwt());else if(format==="emoji")stringSchema=stringSchema.check(z.emoji());else if(format==="nanoid")stringSchema=stringSchema.check(z.nanoid());else if(format==="cuid")stringSchema=stringSchema.check(z.cuid());else if(format==="cuid2")stringSchema=stringSchema.check(z.cuid2());else if(format==="ulid")stringSchema=stringSchema.check(z.ulid());else if(format==="xid")stringSchema=stringSchema.check(z.xid());else if(format==="ksuid")stringSchema=stringSchema.check(z.ksuid())}if(typeof schema.minLength==="number")stringSchema=stringSchema.min(schema.minLength);if(typeof schema.maxLength==="number")stringSchema=stringSchema.max(schema.maxLength);if(schema.pattern)stringSchema=stringSchema.regex(new RegExp(schema.pattern));zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number")numberSchema=numberSchema.min(schema.minimum);if(typeof schema.maximum==="number")numberSchema=numberSchema.max(schema.maximum);if(typeof schema.exclusiveMinimum==="number")numberSchema=numberSchema.gt(schema.exclusiveMinimum);else if(schema.exclusiveMinimum===!0&&typeof schema.minimum==="number")numberSchema=numberSchema.gt(schema.minimum);if(typeof schema.exclusiveMaximum==="number")numberSchema=numberSchema.lt(schema.exclusiveMaximum);else if(schema.exclusiveMaximum===!0&&typeof schema.maximum==="number")numberSchema=numberSchema.lt(schema.maximum);if(typeof schema.multipleOf==="number")numberSchema=numberSchema.multipleOf(schema.multipleOf);zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{let shape={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]);for(let[key,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);shape[key]=requiredSet.has(key)?propZodSchema:propZodSchema.optional()}if(schema.propertyNames){let keySchema=convertSchema(schema.propertyNames,ctx),valueSchema=schema.additionalProperties&&typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):z.any();if(Object.keys(shape).length===0){zodSchema=z.record(keySchema,valueSchema);break}let objectSchema2=z.object(shape).passthrough(),recordSchema=z.looseRecord(keySchema,valueSchema);zodSchema=z.intersection(objectSchema2,recordSchema);break}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape).length>0)schemasToIntersect.push(z.object(shape).passthrough());if(schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++)result=z.intersection(result,schemasToIntersect[i]);zodSchema=result}break}let objectSchema=z.object(shape);if(schema.additionalProperties===!1)zodSchema=objectSchema.strict();else if(typeof schema.additionalProperties==="object")zodSchema=objectSchema.catchall(convertSchema(schema.additionalProperties,ctx));else zodSchema=objectSchema.passthrough();break}case"array":{let{prefixItems,items}=schema;if(prefixItems&&Array.isArray(prefixItems)){let tupleItems=prefixItems.map((item)=>convertSchema(item,ctx)),rest=items&&typeof items==="object"&&!Array.isArray(items)?convertSchema(items,ctx):void 0;if(rest)zodSchema=z.tuple(tupleItems).rest(rest);else zodSchema=z.tuple(tupleItems);if(typeof schema.minItems==="number")zodSchema=zodSchema.check(z.minLength(schema.minItems));if(typeof schema.maxItems==="number")zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}else if(Array.isArray(items)){let tupleItems=items.map((item)=>convertSchema(item,ctx)),rest=schema.additionalItems&&typeof schema.additionalItems==="object"?convertSchema(schema.additionalItems,ctx):void 0;if(rest)zodSchema=z.tuple(tupleItems).rest(rest);else zodSchema=z.tuple(tupleItems);if(typeof schema.minItems==="number")zodSchema=zodSchema.check(z.minLength(schema.minItems));if(typeof schema.maxItems==="number")zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z.array(element);if(typeof schema.minItems==="number")arraySchema=arraySchema.min(schema.minItems);if(typeof schema.maxItems==="number")arraySchema=arraySchema.max(schema.maxItems);zodSchema=arraySchema}else zodSchema=z.array(z.any());break}default:throw Error(`Unsupported type: ${type}`)}if(schema.description)zodSchema=zodSchema.describe(schema.description);if(schema.default!==void 0)zodSchema=zodSchema.default(schema.default);return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean")return schema?z.any():z.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map((s)=>convertSchema(s,ctx)),anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map((s)=>convertSchema(s,ctx)),oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++)result=z.intersection(result,convertSchema(schema.allOf[i],ctx));baseSchema=result}if(schema.nullable===!0&&ctx.version==="openapi-3.0")baseSchema=z.nullable(baseSchema);if(schema.readOnly===!0)baseSchema=z.readonly(baseSchema);let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key of coreMetadataKeys)if(key in schema)extraMeta[key]=schema[key];let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key of contentMetadataKeys)if(key in schema)extraMeta[key]=schema[key];for(let key of Object.keys(schema))if(!RECOGNIZED_KEYS.has(key))extraMeta[key]=schema[key];if(Object.keys(extraMeta).length>0)ctx.registry.add(baseSchema,extraMeta);return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean")return schema?z.any():z.never();let version2=detectVersion(schema,params?.defaultTarget),defs=schema.$defs||schema.definitions||{},ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:schema,registry:params?.registry??globalRegistry};return convertSchema(schema,ctx)}var z,RECOGNIZED_KEYS;var init_from_json_schema=__esm(()=>{init_registries();init_checks2();init_iso();init_schemas2();z={...exports_schemas2,...exports_checks2,iso:exports_iso},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var exports_coerce={};__export(exports_coerce,{string:()=>string3,number:()=>number3,date:()=>date4,boolean:()=>boolean3,bigint:()=>bigint3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm(()=>{init_core2();init_schemas2()});var exports_external={};__export(exports_external,{xor:()=>xor,xid:()=>xid2,void:()=>_void2,uuidv7:()=>uuidv7,uuidv6:()=>uuidv6,uuidv4:()=>uuidv4,uuid:()=>uuid2,util:()=>exports_util,url:()=>url,uppercase:()=>_uppercase,unknown:()=>unknown,union:()=>union,undefined:()=>_undefined3,ulid:()=>ulid2,uint64:()=>uint64,uint32:()=>uint32,tuple:()=>tuple,trim:()=>_trim,treeifyError:()=>treeifyError,transform:()=>transform,toUpperCase:()=>_toUpperCase,toLowerCase:()=>_toLowerCase,toJSONSchema:()=>toJSONSchema,templateLiteral:()=>templateLiteral,symbol:()=>symbol,superRefine:()=>superRefine,success:()=>success,stringbool:()=>stringbool,stringFormat:()=>stringFormat,string:()=>string2,strictObject:()=>strictObject,startsWith:()=>_startsWith,slugify:()=>_slugify,size:()=>_size,setErrorMap:()=>setErrorMap,set:()=>set,safeParseAsync:()=>safeParseAsync2,safeParse:()=>safeParse2,safeEncodeAsync:()=>safeEncodeAsync2,safeEncode:()=>safeEncode2,safeDecodeAsync:()=>safeDecodeAsync2,safeDecode:()=>safeDecode2,registry:()=>registry,regexes:()=>exports_regexes,regex:()=>_regex,refine:()=>refine,record:()=>record,readonly:()=>readonly,property:()=>_property,promise:()=>promise,prettifyError:()=>prettifyError,preprocess:()=>preprocess,prefault:()=>prefault,positive:()=>_positive,pipe:()=>pipe,partialRecord:()=>partialRecord,parseAsync:()=>parseAsync2,parse:()=>parse3,overwrite:()=>_overwrite,optional:()=>optional,object:()=>object,number:()=>number2,nullish:()=>nullish2,nullable:()=>nullable,null:()=>_null3,normalize:()=>_normalize,nonpositive:()=>_nonpositive,nonoptional:()=>nonoptional,nonnegative:()=>_nonnegative,never:()=>never,negative:()=>_negative,nativeEnum:()=>nativeEnum,nanoid:()=>nanoid2,nan:()=>nan,multipleOf:()=>_multipleOf,minSize:()=>_minSize,minLength:()=>_minLength,mime:()=>_mime,meta:()=>meta2,maxSize:()=>_maxSize,maxLength:()=>_maxLength,map:()=>map,mac:()=>mac2,lte:()=>_lte,lt:()=>_lt,lowercase:()=>_lowercase,looseRecord:()=>looseRecord,looseObject:()=>looseObject,locales:()=>exports_locales,literal:()=>literal,length:()=>_length,lazy:()=>lazy,ksuid:()=>ksuid2,keyof:()=>keyof,jwt:()=>jwt,json:()=>json,iso:()=>exports_iso,ipv6:()=>ipv62,ipv4:()=>ipv42,intersection:()=>intersection,int64:()=>int64,int32:()=>int32,int:()=>int,instanceof:()=>_instanceof,includes:()=>_includes,httpUrl:()=>httpUrl,hostname:()=>hostname2,hex:()=>hex2,hash:()=>hash,guid:()=>guid2,gte:()=>_gte,gt:()=>_gt,globalRegistry:()=>globalRegistry,getErrorMap:()=>getErrorMap,function:()=>_function,fromJSONSchema:()=>fromJSONSchema,formatError:()=>formatError,float64:()=>float64,float32:()=>float32,flattenError:()=>flattenError,file:()=>file,exactOptional:()=>exactOptional,enum:()=>_enum2,endsWith:()=>_endsWith,encodeAsync:()=>encodeAsync2,encode:()=>encode2,emoji:()=>emoji2,email:()=>email2,e164:()=>e1642,discriminatedUnion:()=>discriminatedUnion,describe:()=>describe2,decodeAsync:()=>decodeAsync2,decode:()=>decode2,date:()=>date3,custom:()=>custom,cuid2:()=>cuid22,cuid:()=>cuid3,core:()=>exports_core2,config:()=>config,coerce:()=>exports_coerce,codec:()=>codec,clone:()=>clone,cidrv6:()=>cidrv62,cidrv4:()=>cidrv42,check:()=>check,catch:()=>_catch2,boolean:()=>boolean2,bigint:()=>bigint2,base64url:()=>base64url2,base64:()=>base642,array:()=>array,any:()=>any,_function:()=>_function,_default:()=>_default2,_ZodString:()=>_ZodString,ZodXor:()=>ZodXor,ZodXID:()=>ZodXID,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodUUID:()=>ZodUUID,ZodURL:()=>ZodURL,ZodULID:()=>ZodULID,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransform:()=>ZodTransform,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodSymbol:()=>ZodSymbol,ZodSuccess:()=>ZodSuccess,ZodStringFormat:()=>ZodStringFormat,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodRecord:()=>ZodRecord,ZodRealError:()=>ZodRealError,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPrefault:()=>ZodPrefault,ZodPipe:()=>ZodPipe,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumberFormat:()=>ZodNumberFormat,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNonOptional:()=>ZodNonOptional,ZodNever:()=>ZodNever,ZodNanoID:()=>ZodNanoID,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodMAC:()=>ZodMAC,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodKSUID:()=>ZodKSUID,ZodJWT:()=>ZodJWT,ZodIssueCode:()=>ZodIssueCode,ZodIntersection:()=>ZodIntersection,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate,ZodIPv6:()=>ZodIPv6,ZodIPv4:()=>ZodIPv4,ZodGUID:()=>ZodGUID,ZodFunction:()=>ZodFunction,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFile:()=>ZodFile,ZodExactOptional:()=>ZodExactOptional,ZodError:()=>ZodError,ZodEnum:()=>ZodEnum,ZodEmoji:()=>ZodEmoji,ZodEmail:()=>ZodEmail,ZodE164:()=>ZodE164,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodCustom:()=>ZodCustom,ZodCodec:()=>ZodCodec,ZodCatch:()=>ZodCatch,ZodCUID2:()=>ZodCUID2,ZodCUID:()=>ZodCUID,ZodCIDRv6:()=>ZodCIDRv6,ZodCIDRv4:()=>ZodCIDRv4,ZodBoolean:()=>ZodBoolean,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBigInt:()=>ZodBigInt,ZodBase64URL:()=>ZodBase64URL,ZodBase64:()=>ZodBase64,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny,TimePrecision:()=>TimePrecision,NEVER:()=>NEVER,$output:()=>$output,$input:()=>$input,$brand:()=>$brand});var init_external=__esm(()=>{init_core2();init_core2();init_en();init_core2();init_json_schema_processors();init_from_json_schema();init_locales();init_iso();init_iso();init_coerce();init_schemas2();init_checks2();init_errors2();init_parse2();init_compat();config(en_default())});var init_zod=__esm(()=>{init_external();init_external()});var EVIDENCE_MAX_JSON_BYTES=512000,EVIDENCE_MAX_PATCH_BYTES=5242880,EVIDENCE_MAX_TASK_BYTES=20971520,EvidenceTypeSchema,EvidenceVerdictSchema,BaseEvidenceSchema,ReviewEvidenceSchema,TestEvidenceSchema,DiffEvidenceSchema,ApprovalEvidenceSchema,NoteEvidenceSchema,RetrospectiveEvidenceSchema,SyntaxEvidenceSchema,PlaceholderEvidenceSchema,SastFindingSchema,SastEvidenceSchema,SbomEvidenceSchema,BuildEvidenceSchema,QualityBudgetEvidenceSchema,SecretscanEvidenceSchema,GateEvidenceBaseSchema,MutationGateEvidenceSchema,DriftVerificationEvidenceSchema,HallucinationVerificationEvidenceSchema,EvidenceSchema,EvidenceBundleSchema;var init_evidence_schema=__esm(()=>{init_zod();EvidenceTypeSchema=exports_external.enum(["review","test","diff","approval","note","retrospective","syntax","placeholder","sast","sbom","build","quality_budget","secretscan","mutation-gate","drift-verification","hallucination-verification"]),EvidenceVerdictSchema=exports_external.enum(["pass","fail","warn","skip","approved","rejected","info"]),BaseEvidenceSchema=exports_external.object({task_id:exports_external.string().min(1),type:EvidenceTypeSchema,timestamp:exports_external.string().datetime(),agent:exports_external.string().min(1),verdict:EvidenceVerdictSchema,summary:exports_external.string().min(1),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}),ReviewEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("review"),risk:exports_external.enum(["low","medium","high","critical"]),issues:exports_external.array(exports_external.object({severity:exports_external.enum(["error","warning","info"]),message:exports_external.string().min(1),file:exports_external.string().optional(),line:exports_external.number().int().optional()})).default([])}),TestEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("test"),tests_passed:exports_external.number().int().min(0),tests_failed:exports_external.number().int().min(0),test_file:exports_external.string().optional(),failures:exports_external.array(exports_external.object({name:exports_external.string().min(1),message:exports_external.string().min(1)})).default([])}),DiffEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("diff"),files_changed:exports_external.array(exports_external.string()).default([]),additions:exports_external.number().int().min(0).default(0),deletions:exports_external.number().int().min(0).default(0),patch_path:exports_external.string().optional()}),ApprovalEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("approval")}),NoteEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("note")}),RetrospectiveEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("retrospective"),phase_number:exports_external.number().int().min(1).max(99),total_tool_calls:exports_external.number().int().min(0).max(9999),coder_revisions:exports_external.number().int().min(0).max(999),reviewer_rejections:exports_external.number().int().min(0).max(999),loop_detections:exports_external.number().int().min(0).max(9999).optional(),circuit_breaker_trips:exports_external.number().int().min(0).max(9999).optional(),test_failures:exports_external.number().int().min(0).max(9999),security_findings:exports_external.number().int().min(0).max(999),integration_issues:exports_external.number().int().min(0).max(999),task_count:exports_external.number().int().min(1).max(9999),task_complexity:exports_external.enum(["trivial","simple","moderate","complex"]),top_rejection_reasons:exports_external.array(exports_external.string()).default([]),lessons_learned:exports_external.array(exports_external.string()).max(5).default([]),user_directives:exports_external.array(exports_external.object({directive:exports_external.string().min(1),category:exports_external.enum(["tooling","code_style","architecture","process","other"]),scope:exports_external.enum(["session","project","global"])})).default([]),approaches_tried:exports_external.array(exports_external.object({approach:exports_external.string().min(1),result:exports_external.enum(["success","failure","partial"]),abandoned_reason:exports_external.string().optional()})).max(10).default([]),error_taxonomy:exports_external.array(exports_external.enum(["planning_error","interface_mismatch","logic_error","scope_creep","gate_evasion"])).default([])}),SyntaxEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("syntax"),files_checked:exports_external.number().int(),files_failed:exports_external.number().int(),skipped_count:exports_external.number().int().default(0),files:exports_external.array(exports_external.object({path:exports_external.string(),language:exports_external.string(),ok:exports_external.boolean(),errors:exports_external.array(exports_external.object({line:exports_external.number().int(),column:exports_external.number().int(),message:exports_external.string()})).default([]),skipped_reason:exports_external.string().optional()})).default([])}),PlaceholderEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("placeholder"),findings:exports_external.array(exports_external.object({path:exports_external.string(),line:exports_external.number().int(),kind:exports_external.enum(["comment","string","function_body","other"]),excerpt:exports_external.string(),rule_id:exports_external.string()})).default([]),files_scanned:exports_external.number().int(),files_with_findings:exports_external.number().int(),findings_count:exports_external.number().int()}),SastFindingSchema=exports_external.object({rule_id:exports_external.string(),severity:exports_external.enum(["critical","high","medium","low"]),message:exports_external.string(),location:exports_external.object({file:exports_external.string(),line:exports_external.number().int(),column:exports_external.number().int().optional()}),remediation:exports_external.string().optional()}),SastEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("sast"),findings:exports_external.array(SastFindingSchema).default([]),engine:exports_external.enum(["tier_a","tier_a+tier_b"]),files_scanned:exports_external.number().int(),findings_count:exports_external.number().int(),findings_by_severity:exports_external.object({critical:exports_external.number().int(),high:exports_external.number().int(),medium:exports_external.number().int(),low:exports_external.number().int()}),new_findings:exports_external.array(SastFindingSchema).optional(),pre_existing_findings:exports_external.array(SastFindingSchema).optional(),baseline_used:exports_external.boolean().optional()}),SbomEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("sbom"),components:exports_external.array(exports_external.object({name:exports_external.string(),version:exports_external.string(),type:exports_external.enum(["library","framework","application"]),purl:exports_external.string().optional(),license:exports_external.string().optional()})).default([]),metadata:exports_external.object({timestamp:exports_external.string().datetime(),tool:exports_external.string(),tool_version:exports_external.string()}),files:exports_external.array(exports_external.string()),components_count:exports_external.number().int(),output_path:exports_external.string()}),BuildEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("build"),runs:exports_external.array(exports_external.object({kind:exports_external.enum(["build","typecheck","test"]),command:exports_external.string(),cwd:exports_external.string(),exit_code:exports_external.number().int(),duration_ms:exports_external.number().int(),stdout_tail:exports_external.string(),stderr_tail:exports_external.string()})).default([]),files_scanned:exports_external.number().int(),runs_count:exports_external.number().int(),failed_count:exports_external.number().int(),skipped_reason:exports_external.string().optional()}),QualityBudgetEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("quality_budget"),metrics:exports_external.object({complexity_delta:exports_external.number(),public_api_delta:exports_external.number(),duplication_ratio:exports_external.number(),test_to_code_ratio:exports_external.number()}),thresholds:exports_external.object({max_complexity_delta:exports_external.number(),max_public_api_delta:exports_external.number(),max_duplication_ratio:exports_external.number(),min_test_to_code_ratio:exports_external.number()}),violations:exports_external.array(exports_external.object({type:exports_external.enum(["complexity","api","duplication","test_ratio"]),message:exports_external.string(),severity:exports_external.enum(["error","warning"]),files:exports_external.array(exports_external.string())})).default([]),files_analyzed:exports_external.array(exports_external.string())}),SecretscanEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("secretscan"),findings_count:exports_external.number().int().min(0).default(0),scan_directory:exports_external.string().optional(),files_scanned:exports_external.number().int().min(0).default(0),skipped_files:exports_external.number().int().min(0).default(0)}),GateEvidenceBaseSchema=exports_external.object({task_id:exports_external.string().optional(),agent:exports_external.string().optional(),timestamp:exports_external.string().datetime(),summary:exports_external.string().min(1),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}),MutationGateEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("mutation-gate"),verdict:exports_external.enum(["pass","warn","fail","skip"]),killRate:exports_external.number().min(0).max(1).optional(),adjustedKillRate:exports_external.number().min(0).max(1).optional(),survivedMutants:exports_external.string().optional()}),DriftVerificationEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("drift-verification"),verdict:exports_external.enum(["approved","rejected"]),requirementCoverage:exports_external.string().optional()}),HallucinationVerificationEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("hallucination-verification"),verdict:exports_external.enum(["approved","rejected"]),findings:exports_external.string().optional()}),EvidenceSchema=exports_external.discriminatedUnion("type",[ReviewEvidenceSchema,TestEvidenceSchema,DiffEvidenceSchema,ApprovalEvidenceSchema,NoteEvidenceSchema,RetrospectiveEvidenceSchema,SyntaxEvidenceSchema,PlaceholderEvidenceSchema,SastEvidenceSchema,SbomEvidenceSchema,BuildEvidenceSchema,QualityBudgetEvidenceSchema,SecretscanEvidenceSchema,MutationGateEvidenceSchema,DriftVerificationEvidenceSchema,HallucinationVerificationEvidenceSchema]),EvidenceBundleSchema=exports_external.object({schema_version:exports_external.literal("1.0.0"),task_id:exports_external.string().min(1),entries:exports_external.array(EvidenceSchema).default([]),created_at:exports_external.string().datetime(),updated_at:exports_external.string().datetime()})});function isDebug(){return process.env.OPENCODE_SWARM_DEBUG==="1"}function log(message,data){if(!isDebug())return;let timestamp=new Date().toISOString();if(data!==void 0)console.log(`[opencode-swarm ${timestamp}] ${message}`,data);else console.log(`[opencode-swarm ${timestamp}] ${message}`)}function warn(message,data){if(!isDebug())return;let timestamp=new Date().toISOString();if(data!==void 0)console.warn(`[opencode-swarm ${timestamp}] WARN: ${message}`,data);else console.warn(`[opencode-swarm ${timestamp}] WARN: ${message}`)}function criticalWarn(message,data){let timestamp=new Date().toISOString();if(data!==void 0)console.warn(`[opencode-swarm ${timestamp}] CRITICAL-WARN: ${message}`,data);else console.warn(`[opencode-swarm ${timestamp}] CRITICAL-WARN: ${message}`)}function error48(message,data){let timestamp=new Date().toISOString();if(data!==void 0)console.error(`[opencode-swarm ${timestamp}] ERROR: ${message}`,data);else console.error(`[opencode-swarm ${timestamp}] ERROR: ${message}`)}var init_logger=()=>{};function sanitizeBufferedLine(s){return s.replace(/\s+/g," ").replace(CONTROL_CHARS_RE,"").replace(/\s+/g," ").trim()}function addDeferredWarning(warning){let sanitized=sanitizeBufferedLine(warning);if(deferredWarnings.length<MAX_DEFERRED_WARNINGS-1){deferredWarnings.push(sanitized);return}if(!deferredWarningsTruncated)deferredWarnings.push(`[opencode-swarm] ${MAX_DEFERRED_WARNINGS-1} deferred warnings buffered; additional advisories were dropped (cap reached). Run with OPENCODE_SWARM_DEBUG=1 to see all advisories in the debug log.`),deferredWarningsTruncated=!0}function renderAdvisoryDetail(data){if(data===void 0||data===null)return"";let raw;if(typeof data==="string")raw=data;else if(data instanceof Error)raw=data.message;else if(Array.isArray(data)&&data.every((d)=>typeof d==="string"))raw=data.join("; ");else try{raw=JSON.stringify(data)??String(data)}catch{raw=String(data)}let collapsed=sanitizeBufferedLine(raw);if(collapsed==="")return"";return collapsed.length>MAX_ADVISORY_DETAIL_CHARS?`${collapsed.slice(0,MAX_ADVISORY_DETAIL_CHARS-1)}…`:collapsed}function advisoryWarn(message,data){let detail=renderAdvisoryDetail(data);addDeferredWarning(detail?`${message} ${detail}`:message),log(message,data)}function getDeferredWarnings(){return[...deferredWarnings]}function clearDeferredWarnings(){deferredWarnings.length=0,deferredWarningsTruncated=!1}var deferredWarnings,MAX_DEFERRED_WARNINGS=50,deferredWarningsTruncated=!1,CONTROL_CHARS_RE,MAX_ADVISORY_DETAIL_CHARS=600;var init_warning_buffer=__esm(()=>{init_logger();deferredWarnings=[],CONTROL_CHARS_RE=/[\x00-\x1F\x7F-\x9F]/g});function dotted(p){return p.map(String).join(".")}function deepClone(obj){try{return structuredClone(obj)}catch{return JSON.parse(JSON.stringify(obj))}}function countNodes(obj){if(obj===null||obj===void 0)return 0;if(typeof obj!=="object")return 1;if(Array.isArray(obj)){let count2=0;for(let el of obj)count2+=1+countNodes(el);return count2}let count=0;for(let _key of Object.keys(obj))count+=1;for(let val of Object.values(obj))count+=countNodes(val);return count}function selectDeepest(paths){let sorted=[...paths].sort((a,b)=>b.length-a.length),kept=[];for(let p of sorted)if(!kept.some((q)=>q.length>p.length&&startsWith(q,p)))kept.push(p);return kept}function startsWith(path,prefix){if(prefix.length>path.length)return!1;for(let i=0;i<prefix.length;i++)if(path[i]!==prefix[i])return!1;return!0}function removeAtPath(obj,path){if(path.length===0)return!1;let node=obj;for(let i=0;i<path.length-1;i++){if(node===null||node===void 0||typeof node!=="object")return!1;let key=path[i];if(Array.isArray(node)){let idx=Number(key);if(!Number.isInteger(idx)||idx<0||idx>=node.length)return!1;node=node[idx]}else node=node[String(key)]}if(node===null||node===void 0||typeof node!=="object")return!1;let lastSegment=path[path.length-1];if(Array.isArray(node)){let idx=Number(lastSegment);if(!Number.isInteger(idx)||idx<0||idx>=node.length)return!1;node.splice(idx,1)}else delete node[String(lastSegment)];return!0}function hasRemovedAncestor(p,removed){for(let len=1;len<p.length;len++)if(removed.has(keyOf(p.slice(0,len))))return!0;return!1}function dedupeByKey(paths){let seen=new Set,result=[];for(let p of paths){let k=keyOf(p);if(!seen.has(k))seen.add(k),result.push(p)}return result}function recordFor(path,issues){let key=keyOf(path);for(let issue2 of issues)if(keyOf(issue2.path)===key)return{path,code:issue2.code,message:issue2.message};return{path,code:"unknown",message:"no matching issue found"}}function sanitizeMalformedValues(schema,rawConfig){if(rawConfig===null||rawConfig===void 0||typeof rawConfig!=="object"||Array.isArray(rawConfig))return{config:{},recoveryWarnings:[{section:"<root>",severity:"warn",message:"Config input is not a plain object (received "+String(rawConfig===null?"null":typeof rawConfig)+"); schema defaults will apply."}]};if(schema.safeParse(rawConfig).success)return{config:rawConfig,recoveryWarnings:[]};let current=deepClone(rawConfig),removed=new Map,fuel=2*countNodes(rawConfig)+8,recovered=!1;for(let iter=0;iter<fuel;iter++){let res=schema.safeParse(current);if(res.success){recovered=!0;break}let issues=res.error.issues,leafCandidates=[],anyPathIssue=!1;for(let issue2 of issues){let p=issue2.path;if(p.length===0)continue;if(anyPathIssue=!0,issue2.code==="unrecognized_keys"&&Array.isArray(issue2.keys))for(let k of issue2.keys)leafCandidates.push([...p,k]);else leafCandidates.push(p)}let batch=selectDeepest(leafCandidates).filter((p)=>!removed.has(keyOf(p)));if(batch.length===0&&anyPathIssue){for(let issue2 of issues){let q=issue2.path;while(q!==null&&removed.has(keyOf(q)))q=q.length>1?q.slice(0,-1):null;if(q!==null&&!removed.has(keyOf(q)))batch.push(q)}batch=dedupeByKey(batch)}if(batch.length===0){let sections=dedupeByKey(issues.filter((i)=>i.path.length>0).map((i)=>[i.path[0]])).filter((p)=>!removed.has(keyOf(p)));if(sections.length===0)break;batch=sections}for(let p of batch)if(removeAtPath(current,p))removed.set(keyOf(p),recordFor(p,issues))}if(!recovered){if(!schema.safeParse(current).success){let topLevelKeys=[...Object.keys(current)];for(let key of topLevelKeys)if(key in current)delete current[key];if(!schema.safeParse(current).success);}}let surviving=[...removed.values()].filter((r)=>!hasRemovedAncestor(r.path,removed)).sort((a,b)=>a.path.length-b.path.length||keyOf(a.path).localeCompare(keyOf(b.path))).map((r)=>({section:dotted(r.path),severity:"warn",message:`Config ${r.path.length===1?"section":"field"} "${dotted(r.path)}" was invalid (${r.code}) and was dropped; schema defaults will apply.`,path:dotted(r.path)}));return{config:current,recoveryWarnings:surviving}}var keyOf=(p)=>JSON.stringify(p);function isActiveStatus(status){return!INACTIVE_STATUSES.has(status??"")}var KNOWLEDGE_SCHEMA_VERSION=3,INACTIVE_STATUSES,OUTCOME_BLOCK_THRESHOLD=-0.3;var init_knowledge_types=__esm(()=>{INACTIVE_STATUSES=new Set(["archived","quarantined","quarantined_unactionable"])});var exports_schema={};__export(exports_schema,{stripKnownSwarmPrefix:()=>stripKnownSwarmPrefix,resolveGuardrailsConfig:()=>resolveGuardrailsConfig,resolveGeneratedAgentRole:()=>resolveGeneratedAgentRole,resolveExternalSkillsConfig:()=>resolveExternalSkillsConfig,resolveAutoReviewConfig:()=>resolveAutoReviewConfig,isKnownCanonicalRole:()=>isKnownCanonicalRole,getCanonicalAgentRole:()=>getCanonicalAgentRole,_internals:()=>_internals,WorktreeIsolationConfigSchema:()=>WorktreeIsolationConfigSchema,WatchdogConfigSchema:()=>WatchdogConfigSchema,UIReviewConfigSchema:()=>UIReviewConfigSchema,TurboConfigSchema:()=>TurboConfigSchema,ToolFilterConfigSchema:()=>ToolFilterConfigSchema,TokenRatiosSchema:()=>TokenRatiosSchema,SwarmConfigSchema:()=>SwarmConfigSchema,SummaryConfigSchema:()=>SummaryConfigSchema,StandardTurboConfigSchema:()=>StandardTurboConfigSchema,SpecWriterConfigSchema:()=>SpecWriterConfigSchema,SlopDetectorConfigSchema:()=>SlopDetectorConfigSchema,SkillsConfigSchema:()=>SkillsConfigSchema,SkillPropagationConfigSchema:()=>SkillPropagationConfigSchema,SkillOptConfigSchema:()=>SkillOptConfigSchema,SkillImproverConfigSchema:()=>SkillImproverConfigSchema,SelfReviewConfigSchema:()=>SelfReviewConfigSchema,SecretscanConfigSchema:()=>SecretscanConfigSchema,ScoringWeightsSchema:()=>ScoringWeightsSchema,ScoringConfigSchema:()=>ScoringConfigSchema,ReviewPassesConfigSchema:()=>ReviewPassesConfigSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QualityBudgetConfigSchema:()=>QualityBudgetConfigSchema,PrmConfigSchema:()=>PrmConfigSchema,PricingConfigSchema:()=>PricingConfigSchema,PrMonitorConfigSchema:()=>PrMonitorConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanCursorConfigSchema:()=>PlanCursorConfigSchema,PlaceholderScanConfigSchema:()=>PlaceholderScanConfigSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,ParallelizationConfigSchema:()=>ParallelizationConfigSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LintConfigSchema:()=>LintConfigSchema,LearningConfigSchema:()=>LearningConfigSchema,LeanTurboStrategyConfigSchema:()=>LeanTurboStrategyConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,KnowledgeConfigSchema:()=>KnowledgeConfigSchema,KnowledgeApplicationConfigSchema:()=>KnowledgeApplicationConfigSchema,IntegrationAnalysisConfigSchema:()=>IntegrationAnalysisConfigSchema,IncrementalVerifyConfigSchema:()=>IncrementalVerifyConfigSchema,HooksConfigSchema:()=>HooksConfigSchema,GuardrailsProfileSchema:()=>GuardrailsProfileSchema,GuardrailsConfigSchema:()=>GuardrailsConfigSchema,GeneralCouncilConfigSchema:()=>GeneralCouncilConfigSchema,GateFeatureSchema:()=>GateFeatureSchema,GateConfigSchema:()=>GateConfigSchema,GATE_CONFIG_KNOWN_SECTION_KEYS:()=>GATE_CONFIG_KNOWN_SECTION_KEYS,FALLBACK_MODELS_MAX:()=>FALLBACK_MODELS_MAX,ExternalSkillsConfigSchema:()=>ExternalSkillsConfigSchema,ExternalSkillCandidateSourceTypeSchema:()=>ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateSchema:()=>ExternalSkillCandidateSchema,ExternalSkillCandidateEvaluationVerdictSchema:()=>ExternalSkillCandidateEvaluationVerdictSchema,EvidenceConfigSchema:()=>EvidenceConfigSchema,EpicConfigSchema:()=>EpicConfigSchema,DocsConfigSchema:()=>DocsConfigSchema,DiscoverySourceSchema:()=>DiscoverySourceSchema,DesignDocsConfigSchema:()=>DesignDocsConfigSchema,DecisionDecaySchema:()=>DecisionDecaySchema,DEFAULT_SKILL_OPT_CONFIG:()=>DEFAULT_SKILL_OPT_CONFIG,DEFAULT_SKILLS_CONFIG:()=>DEFAULT_SKILLS_CONFIG,DEFAULT_EXTERNAL_SKILLS_CONFIG:()=>DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_ARCHITECT_PROFILE:()=>DEFAULT_ARCHITECT_PROFILE,DEFAULT_AGENT_PROFILES:()=>DEFAULT_AGENT_PROFILES,CuratorConfigSchema:()=>CuratorConfigSchema,CouncilConfigSchema:()=>CouncilConfigSchema,ContextMapConfigSchema:()=>ContextMapConfigSchema,ContextBudgetConfigSchema:()=>ContextBudgetConfigSchema,ConsensusConfigSchema:()=>ConsensusConfigSchema,CompactionConfigSchema:()=>CompactionConfigSchema,CompactionAdvisoryConfigSchema:()=>CompactionAdvisoryConfigSchema,CheckpointConfigSchema:()=>CheckpointConfigSchema,AutomationModeSchema:()=>AutomationModeSchema,AutomationConfigSchema:()=>AutomationConfigSchema,AutomationCapabilitiesSchema:()=>AutomationCapabilitiesSchema,AutoReviewConfigSchema:()=>AutoReviewConfigSchema,AuthorityConfigSchema:()=>AuthorityConfigSchema,ArchitecturalSupervisionConfigSchema:()=>ArchitecturalSupervisionConfigSchema,ApplyPatchConfigSchema:()=>ApplyPatchConfigSchema,AgentThinkingConfigSchema:()=>AgentThinkingConfigSchema,AgentReasoningConfigSchema:()=>AgentReasoningConfigSchema,AgentOverrideConfigSchema:()=>AgentOverrideConfigSchema,AgentAuthorityRuleSchema:()=>AgentAuthorityRuleSchema,AdversarialTestingConfigSchema:()=>AdversarialTestingConfigSchema,AdversarialDetectionConfigSchema:()=>AdversarialDetectionConfigSchema,AUTO_REVIEW_V8_BURN_IN_DECISION:()=>AUTO_REVIEW_V8_BURN_IN_DECISION});function isKnownCanonicalRole(role){if(!role)return!1;return CANONICAL_ROLES_SET.has(role)}function getCanonicalAgentRole(agentName,generatedAgentNames){if(!agentName)return agentName;let normalized=agentName.toLowerCase();if(CANONICAL_ROLES_SET.has(normalized))return normalized;if(generatedAgentNames){let registry2=new Set;for(let n of generatedAgentNames)registry2.add(n.toLowerCase());if(!registry2.has(normalized))return agentName}for(let role of CANONICAL_ROLES_LONGEST_FIRST)for(let sep of SEPARATORS){let suffix=sep+role;if(normalized.length>suffix.length&&normalized.endsWith(suffix))return role}return agentName}function resolveGeneratedAgentRole(agentName,generatedAgentNames){return _internals.getCanonicalAgentRole(agentName,generatedAgentNames)}function stripKnownSwarmPrefix(agentName){return getCanonicalAgentRole(agentName)}function hasApprovedAutoReviewBurnIn(decision){return Boolean(decision?.approved===!0&&decision.artifact_path===AUTO_REVIEW_V8_BURN_IN_DECISION.artifact_path&&decision.artifact_sha256===AUTO_REVIEW_V8_BURN_IN_DECISION.artifact_sha256)}function autoReviewEnabledByRelease(context={}){let version2=context.packageVersion??package_default.version,major=Number.parseInt(version2.split(".")[0]??"",10);return Number.isInteger(major)&&major>=8&&hasApprovedAutoReviewBurnIn(context.burnInDecision??AUTO_REVIEW_V8_BURN_IN_DECISION)}function isPlainRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function normalizeAutoReviewInput(value,context={}){if(!isPlainRecord(value))return value;let normalized={...value};if(!Object.hasOwn(value,"enabled"))normalized.enabled=autoReviewEnabledByRelease(context);if(Object.hasOwn(value,"final_review")&&!isPlainRecord(value.final_review))return normalized;let nested=isPlainRecord(value.final_review)?{...value.final_review}:{};if(!Object.hasOwn(nested,"max_diff_bytes"))nested.max_diff_bytes=typeof value.max_diff_kb==="number"?value.max_diff_kb*1024:262144;if(!Object.hasOwn(nested,"timeout_ms"))nested.timeout_ms=typeof value.timeout_ms==="number"?value.timeout_ms:300000;return normalized.final_review=nested,normalized}function resolveAutoReviewConfig(raw={},context={}){let parsed=AutoReviewConfigObjectSchema.parse(normalizeAutoReviewInput(raw,context));if(parsed.final_review.mode==="gate"&&parsed.structured_findings===!1)throw Error('auto_review.final_review.mode="gate" requires auto_review.structured_findings=true');return parsed}function resolveGuardrailsConfig(config2,agentName){if(!agentName)return config2;let canonicalName=_internals.stripKnownSwarmPrefix(agentName),hasBuiltInProfile=canonicalName in DEFAULT_AGENT_PROFILES,userProfile=config2.profiles?.[agentName]??config2.profiles?.[canonicalName];if(!hasBuiltInProfile){if(userProfile)return{...config2,...userProfile};return config2}let builtInProfile=DEFAULT_AGENT_PROFILES[canonicalName];return{...config2,...builtInProfile,...userProfile||{}}}function rejectCheckpointPrototypePollution(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return raw;try{if(Object.getPrototypeOf(raw)!==Object.prototype)return{[INVALID_CHECKPOINT_PROTO_FIELD]:!0};for(let key of Reflect.ownKeys(raw))if(typeof key==="string"&&FORBIDDEN_CHECKPOINT_CONFIG_KEYS.has(key))return{[INVALID_CHECKPOINT_PROTO_FIELD]:!0}}catch{return{[INVALID_CHECKPOINT_PROTO_FIELD]:!0}}return raw}function resolveExternalSkillsConfig(input){if(input===void 0||input===null||typeof input!=="object"||Array.isArray(input))return{...DEFAULT_EXTERNAL_SKILLS_CONFIG};let config2=input;return{curation_enabled:config2.curation_enabled??DEFAULT_EXTERNAL_SKILLS_CONFIG.curation_enabled,max_candidates:config2.max_candidates??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_candidates,max_bytes_per_candidate:config2.max_bytes_per_candidate??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_bytes_per_candidate,eviction_policy:config2.eviction_policy??DEFAULT_EXTERNAL_SKILLS_CONFIG.eviction_policy,ttl_days:config2.ttl_days??DEFAULT_EXTERNAL_SKILLS_CONFIG.ttl_days,evaluation_enabled:config2.evaluation_enabled??DEFAULT_EXTERNAL_SKILLS_CONFIG.evaluation_enabled,sources:Array.isArray(config2.sources)?config2.sources:[],max_candidates_per_discovery:config2.max_candidates_per_discovery??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_candidates_per_discovery,max_concurrent_fetches:config2.max_concurrent_fetches??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_concurrent_fetches,fetch_timeout_ms:config2.fetch_timeout_ms??DEFAULT_EXTERNAL_SKILLS_CONFIG.fetch_timeout_ms}}var _internals,SEPARATORS,CANONICAL_ROLES_LONGEST_FIRST,CANONICAL_ROLES_SET,AgentReasoningConfigSchema,AgentThinkingConfigSchema,FALLBACK_MODELS_MAX=3,AgentOverrideConfigSchema,SwarmConfigSchema,ModelPricingConfigSchema,PricingConfigSchema,HooksConfigSchema,ScoringWeightsSchema,DecisionDecaySchema,TokenRatiosSchema,ScoringConfigSchema,ContextBudgetConfigSchema,EvidenceConfigSchema,GateFeatureSchema,PlaceholderScanConfigSchema,QualityBudgetConfigSchema,GATE_CONFIG_KNOWN_SECTION_KEYS,GateConfigSchema,PipelineConfigSchema,PhaseCompleteConfigSchema,SummaryConfigSchema,ReviewPassesConfigSchema,AUTO_REVIEW_V8_BURN_IN_DECISION,AutoReviewFinalConfigSchema,AutoReviewConfigObjectSchema,AutoReviewConfigSchema,AdversarialDetectionConfigSchema,AdversarialTestingConfigSchemaBase,AdversarialTestingConfigSchema,IntegrationAnalysisConfigSchema,DocsConfigSchema,DesignDocsConfigSchema,UIReviewConfigSchema,CompactionAdvisoryConfigSchema,LintConfigSchema,SecretscanConfigSchema,GuardrailsProfileSchema,DEFAULT_AGENT_PROFILES,DEFAULT_ARCHITECT_PROFILE,GuardrailsConfigSchema,WatchdogConfigSchema,SelfReviewConfigSchema,ToolFilterConfigSchema,PlanCursorConfigSchema,ContextMapConfigSchema,RepoGraphConfigSchema,INVALID_CHECKPOINT_PROTO_FIELD="__swarm_invalid_checkpoint_proto__",FORBIDDEN_CHECKPOINT_CONFIG_KEYS,CheckpointConfigSchema,ApplyPatchConfigSchema,AutomationModeSchema,AutomationCapabilitiesSchema,AutomationConfigSchemaBase,AutomationConfigSchema,KnowledgeConfigSchema,LearningConfigSchema,ConsensusConfigSchema,MemoryConfigSchema,CuratorConfigSchema,ArchitecturalSupervisionConfigSchema,KnowledgeApplicationConfigSchema,SkillPropagationAudienceSchema,SkillPropagationConfigSchema,SkillImproverConfigSchema,SkillsConfigSchema,SkillOptConfigSchema,DEFAULT_SKILL_OPT_CONFIG,SpecWriterConfigSchema,SlopDetectorConfigSchema,IncrementalVerifyConfigSchema,CompactionConfigSchema,PrmConfigSchema,AgentAuthorityRuleSchema,AuthorityConfigSchema,GeneralCouncilMemberConfigSchema,GeneralCouncilConfigSchema,CouncilConfigSchema,PrMonitorConfigSchema,ParallelizationConfigSchema,WorktreeIsolationConfigSchema,LeanTurboConfigSchema,EpicConfigSchema,StandardTurboConfigSchema,LeanTurboStrategyConfigSchema,TurboConfigSchema,ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateEvaluationVerdictSchema,DiscoverySourceSchema,ExternalSkillCandidateSchema,ExternalSkillsConfigSchema,DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_SKILLS_CONFIG,PluginConfigSchema;var init_schema=__esm(()=>{init_zod();init_package();init_knowledge_types();init_constants();_internals={stripKnownSwarmPrefix,getCanonicalAgentRole,resolveGuardrailsConfig},SEPARATORS=["_","-"," "],CANONICAL_ROLES_LONGEST_FIRST=[...ALL_AGENT_NAMES].sort((a,b)=>b.length-a.length),CANONICAL_ROLES_SET=new Set(ALL_AGENT_NAMES);AgentReasoningConfigSchema=exports_external.object({effort:exports_external.enum(["low","medium","high","max"]).optional()}),AgentThinkingConfigSchema=exports_external.object({type:exports_external.enum(["enabled","disabled"]).optional(),budget_tokens:exports_external.number().int().positive().optional()}),AgentOverrideConfigSchema=exports_external.object({model:exports_external.string().optional(),variant:exports_external.string().min(1).optional(),temperature:exports_external.number().min(0).max(2).optional(),disabled:exports_external.boolean().optional(),fallback_models:exports_external.array(exports_external.string()).max(FALLBACK_MODELS_MAX).optional(),reasoning:AgentReasoningConfigSchema.optional(),thinking:AgentThinkingConfigSchema.optional()}),SwarmConfigSchema=exports_external.object({name:exports_external.string().optional(),agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional()}),ModelPricingConfigSchema=exports_external.object({input_per_million:exports_external.number().min(0),output_per_million:exports_external.number().min(0),reasoning_per_million:exports_external.number().min(0).optional(),cache_per_million:exports_external.number().min(0).optional()}),PricingConfigSchema=exports_external.object({models:exports_external.record(exports_external.string().min(1),ModelPricingConfigSchema).optional().default({})}),HooksConfigSchema=exports_external.object({system_enhancer:exports_external.boolean().default(!0),compaction:exports_external.boolean().default(!0),agent_activity:exports_external.boolean().default(!0),delegation_tracker:exports_external.boolean().default(!1),agent_awareness_max_chars:exports_external.number().min(50).max(2000).default(300),delegation_gate:exports_external.boolean().default(!0),delegation_max_chars:exports_external.number().min(500).max(20000).default(4000),background_subagents:exports_external.boolean().default(!1),background_pending_timeout_minutes:exports_external.number().int().min(1).max(1440).default(30)}),ScoringWeightsSchema=exports_external.object({phase:exports_external.number().min(0).max(5).default(1),current_task:exports_external.number().min(0).max(5).default(2),blocked_task:exports_external.number().min(0).max(5).default(1.5),recent_failure:exports_external.number().min(0).max(5).default(2.5),recent_success:exports_external.number().min(0).max(5).default(0.5),evidence_presence:exports_external.number().min(0).max(5).default(1),decision_recency:exports_external.number().min(0).max(5).default(1.5),dependency_proximity:exports_external.number().min(0).max(5).default(1)}),DecisionDecaySchema=exports_external.object({mode:exports_external.enum(["linear","exponential"]).default("exponential"),half_life_hours:exports_external.number().min(1).max(168).default(24)}),TokenRatiosSchema=exports_external.object({prose:exports_external.number().min(0.1).max(1).default(0.25),code:exports_external.number().min(0.1).max(1).default(0.4),markdown:exports_external.number().min(0.1).max(1).default(0.3),json:exports_external.number().min(0.1).max(1).default(0.35)}),ScoringConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),max_candidates:exports_external.number().min(10).max(500).default(100),weights:ScoringWeightsSchema.optional(),decision_decay:DecisionDecaySchema.optional(),token_ratios:TokenRatiosSchema.optional()}),ContextBudgetConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),warn_threshold:exports_external.number().min(0).max(1).default(0.7),critical_threshold:exports_external.number().min(0).max(1).default(0.9),model_limits:exports_external.record(exports_external.string(),exports_external.number().min(1000)).default({default:128000}),max_injection_tokens:exports_external.number().min(100).max(50000).default(4000),unified_injection_tokens:exports_external.number().min(100).max(50000).optional(),tracked_agents:exports_external.array(exports_external.string()).default(["architect"]),scoring:ScoringConfigSchema.optional(),enforce:exports_external.boolean().default(!0),prune_target:exports_external.number().min(0).max(1).default(0.7),preserve_last_n_turns:exports_external.number().min(0).max(100).default(4),recent_window:exports_external.number().min(1).max(100).default(10),enforce_on_agent_switch:exports_external.boolean().default(!0),tool_output_mask_threshold:exports_external.number().min(100).max(1e5).default(2000)}),EvidenceConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_age_days:exports_external.number().min(1).max(365).default(90),max_bundles:exports_external.number().min(10).max(1e4).default(1000),auto_archive:exports_external.boolean().default(!1),cache_max_bytes:exports_external.number().min(512).max(52428800).optional(),cache_max_records:exports_external.number().min(10).max(1e5).optional()}),GateFeatureSchema=exports_external.object({enabled:exports_external.boolean().default(!0)}),PlaceholderScanConfigSchema=GateFeatureSchema.extend({deny_patterns:exports_external.array(exports_external.string()).default(["TODO","FIXME","TBD","XXX","placeholder","stub","wip","not implemented"]),allow_globs:exports_external.array(exports_external.string()).default(["docs/**","examples/**","tests/**","**/*.test.*","**/*.spec.*","**/mocks/**","**/__tests__/**"]),max_allowed_findings:exports_external.number().min(0).default(0),sentinel_allowlist:exports_external.array(exports_external.string()).default([])}),QualityBudgetConfigSchema=GateFeatureSchema.extend({max_complexity_delta:exports_external.number().default(5),max_public_api_delta:exports_external.number().default(10),max_duplication_ratio:exports_external.number().default(0.05),min_test_to_code_ratio:exports_external.number().default(0.3),enforce_on_globs:exports_external.array(exports_external.string()).default(["src/**"]),exclude_globs:exports_external.array(exports_external.string()).default(["docs/**","tests/**","**/*.test.*"])}),GATE_CONFIG_KNOWN_SECTION_KEYS={syntax_check:["enabled"],placeholder_scan:["enabled","deny_patterns","allow_globs","max_allowed_findings"],sast_scan:["enabled"],sbom_generate:["enabled"],build_check:["enabled"],quality_budget:["enabled","max_complexity_delta","max_public_api_delta","max_duplication_ratio","min_test_to_code_ratio","enforce_on_globs","exclude_globs"]},GateConfigSchema=exports_external.object({syntax_check:GateFeatureSchema.default({enabled:!0}),placeholder_scan:PlaceholderScanConfigSchema.default({enabled:!0,deny_patterns:["TODO","FIXME","TBD","XXX","placeholder","stub","wip","not implemented"],allow_globs:["docs/**","examples/**","tests/**","**/*.test.*","**/*.spec.*","**/mocks/**","**/__tests__/**"],max_allowed_findings:0,sentinel_allowlist:[]}),sast_scan:GateFeatureSchema.default({enabled:!0}),sbom_generate:GateFeatureSchema.default({enabled:!0}),build_check:GateFeatureSchema.default({enabled:!0}),quality_budget:QualityBudgetConfigSchema.default(()=>QualityBudgetConfigSchema.parse({}))}),PipelineConfigSchema=exports_external.object({parallel_precheck:exports_external.boolean().default(!0)}),PhaseCompleteConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),required_agents:exports_external.array(exports_external.enum(["coder","reviewer","test_engineer"])).default(["coder","reviewer","test_engineer"]),require_docs:exports_external.boolean().default(!0),policy:exports_external.enum(["enforce","warn"]).default("enforce"),regression_sweep:exports_external.object({enforce:exports_external.boolean().default(!1)}).optional()}),SummaryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),threshold_bytes:exports_external.number().min(1024).max(1048576).default(16384),max_summary_chars:exports_external.number().min(100).max(5000).default(1000),max_stored_bytes:exports_external.number().min(10240).max(104857600).default(10485760),retention_days:exports_external.number().min(1).max(365).default(7),exempt_tools:exports_external.array(exports_external.string()).default([...SUMMARIZER_EXEMPT_TOOL_NAMES])}),ReviewPassesConfigSchema=exports_external.object({always_security_review:exports_external.boolean().default(!1),security_globs:exports_external.array(exports_external.string()).default(["**/auth/**","**/api/**","**/crypto/**","**/security/**","**/middleware/**","**/session/**","**/token/**"])}),AUTO_REVIEW_V8_BURN_IN_DECISION={approved:!0,artifact_path:"docs/benchmarks/auto-review-v8-cost-baseline.json",artifact_sha256:"b4e981d4d87e3de80f6d7dd4ae782b08159d385019c4d8b0d300c0443f1984ce"};AutoReviewFinalConfigSchema=exports_external.object({on_phase_complete:exports_external.boolean().default(!0),on_plan_complete:exports_external.boolean().default(!0),model:exports_external.string().min(1).nullable().default(null),mode:exports_external.enum(["advisory","gate"]).default("advisory"),max_diff_bytes:exports_external.number().int().min(16384).max(2097152).default(262144),timeout_ms:exports_external.number().int().min(1e4).max(1800000).default(300000)}),AutoReviewConfigObjectSchema=exports_external.object({enabled:exports_external.boolean(),trigger:exports_external.enum(["task_completion","phase_boundary","both"]).default("phase_boundary"),timeout_ms:exports_external.number().int().min(1e4).max(1800000).default(300000),max_diff_kb:exports_external.number().int().min(16).max(2048).default(256),min_confidence:exports_external.number().min(0).max(1).default(0.7),structured_findings:exports_external.boolean().default(!0),validate_findings:exports_external.boolean().default(!1),validation_model:exports_external.string().min(1).nullable().default(null),validation_timeout_ms:exports_external.number().int().min(1e4).max(1800000).default(120000),final_review:AutoReviewFinalConfigSchema.default({on_phase_complete:!0,on_plan_complete:!0,model:null,mode:"advisory",max_diff_bytes:262144,timeout_ms:300000})});AutoReviewConfigSchema=exports_external.preprocess((value)=>normalizeAutoReviewInput(value),AutoReviewConfigObjectSchema);AdversarialDetectionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),policy:exports_external.enum(["warn","gate","ignore"]).default("warn"),pairs:exports_external.array(exports_external.tuple([exports_external.string(),exports_external.string()])).default([["coder","reviewer"]])}),AdversarialTestingConfigSchemaBase=exports_external.object({enabled:exports_external.boolean().default(!0),scope:exports_external.enum(["all","security-only"]).default("all")}),AdversarialTestingConfigSchema=AdversarialTestingConfigSchemaBase.default(()=>({enabled:!0,scope:"all"})),IntegrationAnalysisConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0)}),DocsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),doc_patterns:exports_external.array(exports_external.string()).default(["README.md","CONTRIBUTING.md","docs/**/*.md","docs/**/*.rst","**/CHANGELOG.md"])}),DesignDocsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),out_dir:exports_external.string().default("docs").refine((v)=>v.length>0&&v!=="."&&!v.includes("..")&&!v.startsWith("/")&&!v.startsWith("\\")&&!/^[A-Za-z]:/.test(v),{message:'design_docs.out_dir must be a non-empty project-relative path with no "..", leading slash, or drive letter'}),language:exports_external.string().optional()}),UIReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),trigger_paths:exports_external.array(exports_external.string()).default(["**/pages/**","**/components/**","**/views/**","**/screens/**","**/ui/**","**/layouts/**"]),trigger_keywords:exports_external.array(exports_external.string()).default(["new page","new screen","new component","redesign","layout change","form","modal","dialog","dropdown","sidebar","navbar","dashboard","landing page","signup","login form","settings page","profile page"])}),CompactionAdvisoryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),thresholds:exports_external.array(exports_external.number().int().min(10).max(500)).default([50,75,100,125,150]),message:exports_external.string().default("[SWARM HINT] Session has ${totalToolCalls} tool calls. Consider compacting at next phase boundary to maintain context quality.")}),LintConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),mode:exports_external.enum(["check","fix"]).default("check"),linter:exports_external.enum(["biome","eslint","auto"]).default("auto"),patterns:exports_external.array(exports_external.string()).default(["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/biome.json","**/biome.jsonc"]),exclude:exports_external.array(exports_external.string()).default(["**/node_modules/**","**/dist/**","**/.git/**","**/coverage/**","**/*.min.js"])}),SecretscanConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),patterns:exports_external.array(exports_external.string()).default(["**/*.{env,properties,yml,yaml,json,js,ts}","**/.env*","**/secrets/**","**/credentials/**","**/config/**/*.ts","**/config/**/*.js"]),exclude:exports_external.array(exports_external.string()).default(["**/node_modules/**","**/dist/**","**/.git/**","**/coverage/**","**/test/**","**/tests/**","**/__tests__/**","**/*.test.ts","**/*.test.js","**/*.spec.ts","**/*.spec.js"]),extensions:exports_external.array(exports_external.string()).default([".env",".properties",".yml",".yaml",".json",".js",".ts",".py",".rb",".go",".java",".cs",".php"])}),GuardrailsProfileSchema=exports_external.object({max_tool_calls:exports_external.number().min(0).max(1000).optional(),max_duration_minutes:exports_external.number().min(0).max(480).optional(),max_repetitions:exports_external.number().min(3).max(50).optional(),max_consecutive_errors:exports_external.number().min(2).max(20).optional(),warning_threshold:exports_external.number().min(0.1).max(0.9).optional(),idle_timeout_minutes:exports_external.number().min(5).max(240).optional(),max_transient_retries:exports_external.number().min(0).max(20).optional()}),DEFAULT_AGENT_PROFILES={architect:{max_tool_calls:0,max_duration_minutes:0,max_consecutive_errors:8,warning_threshold:0.75},coder:{max_tool_calls:400,max_duration_minutes:45,max_consecutive_errors:8,warning_threshold:0.85},test_engineer:{max_tool_calls:400,max_duration_minutes:45,max_consecutive_errors:8,warning_threshold:0.85},explorer:{max_tool_calls:150,max_duration_minutes:20,max_consecutive_errors:8,warning_threshold:0.75},reviewer:{max_tool_calls:200,max_duration_minutes:30,max_consecutive_errors:8,warning_threshold:0.65},critic:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.65},sme:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.65},docs:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.75},designer:{max_tool_calls:150,max_duration_minutes:20,warning_threshold:0.75}},DEFAULT_ARCHITECT_PROFILE=DEFAULT_AGENT_PROFILES.architect,GuardrailsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_tool_calls:exports_external.number().min(0).max(1000).default(200),max_duration_minutes:exports_external.number().min(0).max(480).default(30),max_repetitions:exports_external.number().min(3).max(50).default(10),max_consecutive_errors:exports_external.number().min(2).max(20).default(5),max_transient_retries:exports_external.number().min(0).max(20).default(5),warning_threshold:exports_external.number().min(0.1).max(0.9).default(0.75),idle_timeout_minutes:exports_external.number().min(5).max(240).default(60),no_op_warning_threshold:exports_external.number().min(1).max(100).default(15),max_coder_revisions:exports_external.number().int().min(1).max(20).default(5),runaway_output_max_turns:exports_external.number().int().min(1).max(20).default(5),qa_gates:exports_external.object({required_tools:exports_external.array(exports_external.string().min(1)).default(["diff","syntax_check","placeholder_scan","lint","pre_check_batch"]),require_reviewer_test_engineer:exports_external.boolean().default(!0)}).optional(),profiles:exports_external.record(exports_external.string(),GuardrailsProfileSchema).optional(),block_destructive_commands:exports_external.boolean().default(!0),interpreter_allowed_agents:exports_external.array(exports_external.string().min(1)).optional(),shell_audit_log:exports_external.boolean().default(!0),gate_denial_warn_threshold:exports_external.number().int().min(1).default(3),gate_denial_stop_threshold:exports_external.number().int().min(1).default(5),execution_stall_warn_calls:exports_external.number().int().min(1).default(30),execution_stall_stop_calls:exports_external.number().int().min(1).default(60),execution_stall_episode_minutes:exports_external.number().int().min(1).default(30)}),WatchdogConfigSchema=exports_external.object({scope_guard:exports_external.boolean().default(!0),skip_in_turbo:exports_external.boolean().default(!1),delegation_ledger:exports_external.boolean().default(!0)}),SelfReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),skip_in_turbo:exports_external.boolean().default(!0)});ToolFilterConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),overrides:exports_external.record(exports_external.string(),exports_external.array(exports_external.string())).default({})}),PlanCursorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_tokens:exports_external.number().min(500).max(4000).default(1500),lookahead_tasks:exports_external.number().min(0).max(5).default(2)}),ContextMapConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),mode:exports_external.enum(["conservative","balanced","aggressive"]).default("balanced"),max_capsule_tokens:exports_external.number().int().positive().default(2000),invalidate_on_hash_change:exports_external.boolean().default(!0),agent_profiles:exports_external.record(exports_external.string(),exports_external.string()).default({})}),RepoGraphConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),init_refresh:exports_external.boolean().default(!0),refresh_cap:exports_external.number().int().min(0).max(500).default(50),walk_budget_ms:exports_external.number().int().min(1000).max(60000).default(5000),max_files:exports_external.number().int().min(100).max(1e5).default(1e4),exclude_dirs:exports_external.array(exports_external.string().trim().min(1)).default([])}),FORBIDDEN_CHECKPOINT_CONFIG_KEYS=new Set(["__proto__","prototype","constructor"]);CheckpointConfigSchema=exports_external.preprocess(rejectCheckpointPrototypePollution,exports_external.object({enabled:exports_external.boolean().default(!0),auto_checkpoint_threshold:exports_external.number().int().min(1).max(20).default(3).describe("Maximum number of checkpoints to retain. Oldest checkpoints are evicted when this limit is exceeded."),max_retention:exports_external.number().int().min(1).max(100).default(20),allow_empty_commits:exports_external.boolean().default(!1)}).strict()),ApplyPatchConfigSchema=exports_external.object({fuzzy_match:exports_external.boolean().default(!1),fuzzy_match_context_aware:exports_external.boolean().default(!1)}).strict(),AutomationModeSchema=exports_external.enum(["manual","hybrid","auto"]),AutomationCapabilitiesSchema=exports_external.object({plan_sync:exports_external.boolean().default(!0),phase_preflight:exports_external.boolean().default(!1),config_doctor_on_startup:exports_external.boolean().default(!1),config_doctor_autofix:exports_external.boolean().default(!1),evidence_auto_summaries:exports_external.boolean().default(!0),decision_drift_detection:exports_external.boolean().default(!0)}),AutomationConfigSchemaBase=exports_external.object({mode:AutomationModeSchema.default("manual"),capabilities:AutomationCapabilitiesSchema.default({plan_sync:!0,phase_preflight:!1,config_doctor_on_startup:!1,config_doctor_autofix:!1,evidence_auto_summaries:!0,decision_drift_detection:!0})}),AutomationConfigSchema=AutomationConfigSchemaBase,KnowledgeConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),swarm_max_entries:exports_external.number().min(1).max(1e4).default(100),hive_max_entries:exports_external.number().min(1).max(1e5).default(200),auto_promote_days:exports_external.number().min(1).max(3650).default(90),max_inject_count:exports_external.number().min(0).max(50).default(5),delegate_max_inject_count:exports_external.number().min(0).max(50).default(8),inject_char_budget:exports_external.number().min(200).max(1e4).default(2000),context_budget_threshold:exports_external.number().int().positive().optional(),max_lesson_display_chars:exports_external.number().min(40).max(280).default(120),dedup_threshold:exports_external.number().min(0).max(1).default(0.6),scope_filter:exports_external.array(exports_external.string()).default(["global"]),hive_enabled:exports_external.boolean().default(!0),rejected_max_entries:exports_external.number().min(1).max(1000).default(20),validation_enabled:exports_external.boolean().default(!0),evergreen_confidence:exports_external.number().min(0).max(1).default(0.9),evergreen_utility:exports_external.number().min(0).max(1).default(0.8),low_utility_threshold:exports_external.number().min(0).max(1).default(0.3),min_retrievals_for_utility:exports_external.number().min(1).max(100).default(3),schema_version:exports_external.number().int().min(1).default(1),directive_min_confidence:exports_external.number().min(0).max(1).default(0.75),same_project_weight:exports_external.number().min(0).max(5).default(1),cross_project_weight:exports_external.number().min(0).max(5).default(0.5),min_encounter_score:exports_external.number().min(0).max(1).default(0.1),initial_encounter_score:exports_external.number().min(0).max(5).default(1),encounter_increment:exports_external.number().min(0).max(1).default(0.1),max_encounter_score:exports_external.number().min(1).max(20).default(10),default_max_phases:exports_external.number().int().positive().default(10),todo_max_phases:exports_external.number().int().positive().default(3),sweep_enabled:exports_external.boolean().default(!0),confidence_floor_action:exports_external.enum(["none","demote","quarantine"]).default("demote"),confidence_floor_min_outcomes:exports_external.number().int().min(0).default(3),confidence_floor_signal_threshold:exports_external.number().min(-1).max(1).default(0),contradiction_threshold_action:exports_external.enum(["tag_only","quarantine"]).default("quarantine"),contradiction_quarantine_threshold:exports_external.number().int().positive().default(3),contradiction_quarantine_window_days:exports_external.number().int().positive().default(30),promoted_demotion_min_negative_phases:exports_external.number().int().positive().default(3),promoted_demotion_signal_threshold:exports_external.number().min(-1).max(1).default(OUTCOME_BLOCK_THRESHOLD),promotion_min_terminal_applications:exports_external.number().min(0).max(100).default(0),promotion_min_distinct_cohorts:exports_external.number().min(0).max(50).default(0),promotion_require_actionable:exports_external.boolean().default(!0),realtime_learning_nudge:exports_external.object({enabled:exports_external.boolean().default(!0),first_after_tool_calls:exports_external.number().int().min(1).max(1000).default(10),repeat_after_tool_calls:exports_external.number().int().min(1).max(1000).default(25)}).default({enabled:!0,first_after_tool_calls:10,repeat_after_tool_calls:25}),retrieval:exports_external.object({mmr_lambda:exports_external.number().min(0).max(1).default(0.5),cold_start_bonus:exports_external.number().min(0).max(0.5).default(0.08),cold_start_max_age_phases:exports_external.number().int().min(0).max(100).default(3),synonym_min_cooccurrence:exports_external.number().int().min(1).max(100).default(3),synonym_map_max_pairs:exports_external.number().int().min(1).max(1e4).default(500)}).optional(),enrichment:exports_external.object({max_calls_per_day:exports_external.number().int().min(0).max(1000).default(30),quota_window:exports_external.enum(["utc","local"]).default("utc"),batch_size:exports_external.number().int().min(1).max(100).optional()}).default({max_calls_per_day:30,quota_window:"utc"})}),LearningConfigSchema=exports_external.object({realtime_admission:exports_external.object({enabled:exports_external.boolean().default(!0),max_queue_size:exports_external.number().int().min(1).max(500).default(50),min_drain:exports_external.number().int().min(1).max(50).default(1),max_drain:exports_external.number().int().min(1).max(100).default(10),drain_depth_factor:exports_external.number().min(0).max(1).default(0.5),drain_velocity_factor:exports_external.number().min(0).max(1).default(0.25),max_llm_calls_per_session:exports_external.number().int().min(0).max(500).default(20),max_tokens_per_session:exports_external.number().int().min(0).default(50000),max_concurrent_admissions:exports_external.number().int().min(1).max(16).default(2),max_retries_per_candidate:exports_external.number().int().min(0).max(5).default(1),per_candidate_llm_timeout_ms:exports_external.number().int().min(0).default(60000),max_drain_wall_time_ms:exports_external.number().int().min(0).default(1e4),supersede_nudge:exports_external.boolean().default(!0)}).prefault({}),prm_persistence:exports_external.object({enabled:exports_external.boolean().default(!0),min_support:exports_external.number().int().min(1).max(20).default(3),cooldown_ms:exports_external.number().int().min(0).default(900000)}).prefault({}),dedup_sweep:exports_external.object({enabled:exports_external.boolean().default(!0),max_comparisons:exports_external.number().int().min(0).default(2000),max_merges_per_sweep:exports_external.number().int().min(0).default(10)}).prefault({})}),ConsensusConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),default_min_support:exports_external.number().int().min(1).default(3),default_min_successful_runs:exports_external.number().int().min(0).default(2),default_max_evidence_items:exports_external.number().int().min(1).default(50),max_excerpt_chars:exports_external.number().int().min(1).default(500),llm_summarization_enabled:exports_external.boolean().default(!0),llm_timeout_ms:exports_external.number().int().min(0).default(60000),report_retention:exports_external.number().int().min(0).default(50)}),MemoryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),provider:exports_external.enum(["local-jsonl","sqlite"]).default("sqlite"),storageDir:exports_external.string().default(".swarm/memory"),sqlite:exports_external.object({path:exports_external.string().default(".swarm/memory/memory.db"),busyTimeoutMs:exports_external.number().int().min(0).max(60000).default(5000)}).default({path:".swarm/memory/memory.db",busyTimeoutMs:5000}),link:exports_external.object({enabled:exports_external.boolean().default(!1)}).default({enabled:!1}),recall:exports_external.object({defaultMaxItems:exports_external.number().int().min(1).max(20).default(8),defaultTokenBudget:exports_external.number().int().min(100).max(5000).default(1200),minScore:exports_external.number().min(0).max(1).default(0.05),injection:exports_external.object({enabled:exports_external.boolean().default(!0),minScore:exports_external.number().min(0).max(1).default(0.25),requireQuerySignal:exports_external.boolean().default(!0),maxItems:exports_external.number().int().min(1).max(20).default(6),tokenBudget:exports_external.number().int().min(100).max(5000).default(1000)}).default({enabled:!0,minScore:0.25,requireQuerySignal:!0,maxItems:6,tokenBudget:1000})}).default({defaultMaxItems:8,defaultTokenBudget:1200,minScore:0.05,injection:{enabled:!0,minScore:0.25,requireQuerySignal:!0,maxItems:6,tokenBudget:1000}}),learning:exports_external.object({learningRate:exports_external.number().min(0).max(1).default(0.1),propagationFactor:exports_external.number().min(0).max(1).default(0.3),qValueBoostWeight:exports_external.number().min(0).max(1).default(0.1),suppressionThreshold:exports_external.number().min(0).max(1).default(0.15),promotionThreshold:exports_external.number().min(0).max(1).default(0.85),propagationTokenOverlapThreshold:exports_external.number().min(0).max(1).default(0.4),propagationEmbeddingCosineThreshold:exports_external.number().min(0).max(1).default(0.7),propagationFanout:exports_external.number().int().min(0).max(1000).default(20),propagationLookbackDays:exports_external.number().int().min(1).max(3650).default(30)}).default({learningRate:0.1,propagationFactor:0.3,qValueBoostWeight:0.1,suppressionThreshold:0.15,promotionThreshold:0.85,propagationTokenOverlapThreshold:0.4,propagationEmbeddingCosineThreshold:0.7,propagationFanout:20,propagationLookbackDays:30}),writes:exports_external.object({mode:exports_external.literal("propose").default("propose")}).default({mode:"propose"}),redaction:exports_external.object({rejectDurableSecrets:exports_external.boolean().default(!0)}).default({rejectDurableSecrets:!0}),maintenance:exports_external.object({lowUtilityMaxConfidence:exports_external.number().min(0).max(1).default(0.45),lowUtilityMinAgeDays:exports_external.number().int().min(1).max(3650).default(30),importance:exports_external.object({wRecency:exports_external.number().min(0).max(1).default(0.2),wFrequency:exports_external.number().min(0).max(1).default(0.2),wFreshness:exports_external.number().min(0).max(1).default(0.15),wConfidence:exports_external.number().min(0).max(1).default(0.25),lambda:exports_external.number().min(0).max(10).default(0.05),mu:exports_external.number().min(0).max(10).default(0.01),n:exports_external.number().int().min(1).max(1e5).default(50),threshold:exports_external.number().min(0).max(1).default(0.2)}).default({wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2})}).default({lowUtilityMaxConfidence:0.45,lowUtilityMinAgeDays:30,importance:{wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2}}),qLearning:exports_external.object({learningRate:exports_external.number().min(0).max(1).default(0.1),qValueBoostWeight:exports_external.number().min(0).max(1).default(0.1),suppressionThreshold:exports_external.number().min(0).max(1).default(0.15),promotionThreshold:exports_external.number().min(0).max(1).default(0.85),promotionMinRetrievals:exports_external.number().int().min(0).max(1e5).default(5),propagationFraction:exports_external.number().min(0).max(1).default(0.3),propagationFanoutCap:exports_external.number().int().min(0).max(1e4).default(20),propagationWindowDays:exports_external.number().int().min(0).max(3650).default(30),propagationRelatednessThreshold:exports_external.number().min(0).max(1).default(0.7),explorationRate:exports_external.number().min(0).max(1).default(0.05),verdictPayloadCapBytes:exports_external.number().int().min(0).max(1048576).default(8192),initialQValue:exports_external.number().min(0).max(1).default(0.5)}).default({learningRate:0.1,qValueBoostWeight:0.1,suppressionThreshold:0.15,promotionThreshold:0.85,promotionMinRetrievals:5,propagationFraction:0.3,propagationFanoutCap:20,propagationWindowDays:30,propagationRelatednessThreshold:0.7,explorationRate:0.05,verdictPayloadCapBytes:8192,initialQValue:0.5}),consolidation:exports_external.object({enabled:exports_external.boolean().default(!1),maxClustersPerPass:exports_external.number().int().min(1).max(100).default(10),jaccardThreshold:exports_external.number().min(0).max(1).default(0.3),autoApplyMinConfidence:exports_external.number().min(0).max(1).default(0.6),decayHalfLifeDays:exports_external.object({user_preference:exports_external.number().int().min(0).max(36500).default(0),project_fact:exports_external.number().int().min(0).max(36500).default(0),architecture_decision:exports_external.number().int().min(0).max(36500).default(0),repo_convention:exports_external.number().int().min(0).max(36500).default(0),api_finding:exports_external.number().int().min(0).max(36500).default(180),code_pattern:exports_external.number().int().min(0).max(36500).default(90),test_pattern:exports_external.number().int().min(0).max(36500).default(90),failure_pattern:exports_external.number().int().min(0).max(36500).default(90),security_note:exports_external.number().int().min(0).max(36500).default(0),evidence:exports_external.number().int().min(0).max(36500).default(180),todo:exports_external.number().int().min(0).max(36500).default(30),scratch:exports_external.number().int().min(0).max(36500).default(7)}).default({user_preference:0,project_fact:0,architecture_decision:0,repo_convention:0,api_finding:180,code_pattern:90,test_pattern:90,failure_pattern:90,security_note:0,evidence:180,todo:30,scratch:7})}).default({enabled:!1,maxClustersPerPass:10,jaccardThreshold:0.3,autoApplyMinConfidence:0.6,decayHalfLifeDays:{user_preference:0,project_fact:0,architecture_decision:0,repo_convention:0,api_finding:180,code_pattern:90,test_pattern:90,failure_pattern:90,security_note:0,evidence:180,todo:30,scratch:7}}),hardDelete:exports_external.boolean().default(!1),embeddings:exports_external.object({enabled:exports_external.boolean().default(!1),model:exports_external.string().default("Xenova/all-MiniLM-L6-v2"),dimension:exports_external.number().int().min(1).default(384),version:exports_external.string().optional(),cacheSize:exports_external.number().int().min(1).default(256)}).default({enabled:!1,model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheSize:256}),retrieval:exports_external.object({rrfK:exports_external.number().int().min(1).default(60),weights:exports_external.object({lexical:exports_external.number().min(0).max(1).default(0.5),dense:exports_external.number().min(0).max(1).default(0.4),metadata:exports_external.number().min(0).max(1).default(0.1)}).default({lexical:0.5,dense:0.4,metadata:0.1}),rerank:exports_external.object({enabled:exports_external.boolean().default(!1),model:exports_external.string().optional()}).default({enabled:!1}),latencyBudgetMs:exports_external.number().int().min(0).default(250)}).default({rrfK:60,weights:{lexical:0.5,dense:0.4,metadata:0.1},rerank:{enabled:!1},latencyBudgetMs:250})}),CuratorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),init_enabled:exports_external.boolean().default(!0),phase_enabled:exports_external.boolean().default(!0),postmortem_enabled:exports_external.boolean().default(!0),max_summary_tokens:exports_external.number().min(500).max(8000).default(2000),min_knowledge_confidence:exports_external.number().min(0).max(1).default(0.7),compliance_report:exports_external.boolean().default(!0),suppress_warnings:exports_external.boolean().default(!0),drift_inject_max_chars:exports_external.number().min(100).max(2000).default(500),llm_timeout_ms:exports_external.number().int().min(5000).max(600000).default(300000),skill_generation_enabled:exports_external.boolean().default(!0),skill_generation_mode:exports_external.enum(["draft","active"]).default("draft"),min_skill_confidence:exports_external.number().min(0).max(1).default(0.7),min_skill_confirmations:exports_external.number().int().min(1).max(50).default(2)}),ArchitecturalSupervisionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),mode:exports_external.enum(["advisory","gate"]).default("advisory"),run_on:exports_external.enum(["phase_complete"]).default("phase_complete"),summary_model:exports_external.string().min(1).optional(),max_agent_summary_words:exports_external.number().int().min(20).max(500).default(100),max_phase_summary_words:exports_external.number().int().min(50).max(1000).default(250),allow_concerns_to_complete:exports_external.boolean().default(!0),persist_knowledge_recommendations:exports_external.boolean().default(!1),provenance_verify:exports_external.boolean().default(!1)}),KnowledgeApplicationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),mode:exports_external.enum(["warn","enforce"]).default("warn"),min_confidence:exports_external.number().min(0).max(1).default(0.85),critical_requires_ack:exports_external.boolean().default(!0),require_skill_refs:exports_external.boolean().default(!0),high_risk_tools:exports_external.array(exports_external.string()).default(["save_plan","update_task_status","phase_complete","task","Task"]),max_gate_denials:exports_external.number().int().min(1).max(100).default(5),gate_staleness_ms:exports_external.number().int().min(1e4).max(3600000).default(600000)}),SkillPropagationAudienceSchema=exports_external.string().max(64).refine((value)=>value!=="swarm-plugin",{message:"swarm-plugin is reserved for plugin-internal skill routing"}).refine((value)=>!value.startsWith("runner:"),{message:"runner:* values are derived from the active runner"}).regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,{message:"audiences must be lowercase domain tokens"}),SkillPropagationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),enforce:exports_external.boolean().default(!1),audiences:exports_external.array(SkillPropagationAudienceSchema).max(16).transform((values)=>[...new Set(values)]).default([])}),SkillImproverConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),model:exports_external.string().nullable().default(null),fallback_models:exports_external.array(exports_external.string()).default([]),max_calls_per_day:exports_external.number().int().min(1).max(1000).default(10),trigger:exports_external.enum(["manual","scheduled"]).default("manual"),consolidation_interval_hours:exports_external.number().int().min(1).max(720).default(24),consolidation_max_calls_per_run:exports_external.number().int().min(1).max(100).default(1),targets:exports_external.array(exports_external.enum(["skills","spec","architect_prompt","knowledge"])).default(["skills","spec","architect_prompt","knowledge"]),write_mode:exports_external.enum(["proposal","draft_skills"]).default("proposal"),require_user_approval:exports_external.boolean().default(!0),quota_window:exports_external.enum(["utc","local"]).default("utc"),allow_deterministic_fallback:exports_external.boolean().default(!0)}),SkillsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1)}),SkillOptConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),max_rounds:exports_external.number().int().min(1).max(50).default(5),max_candidates_per_round:exports_external.number().int().min(1).max(20).default(3),max_validations_per_round:exports_external.number().int().min(1).max(10).default(1),max_round_time_ms:exports_external.number().int().min(1e4).max(86400000).default(3600000),max_tokens_per_round:exports_external.number().int().min(1000).max(2000000).default(50000),max_rejections:exports_external.number().int().min(1).max(50).default(5),max_inconclusive_rounds:exports_external.number().int().min(0).max(10).default(2),max_transient_retries:exports_external.number().int().min(0).max(20).default(5),convergence_non_improvements:exports_external.number().int().min(1).max(20).default(3),max_changed_lines:exports_external.number().int().min(1).max(2000).default(200),max_changed_bytes:exports_external.number().int().min(64).max(200000).default(20000),max_changed_sections:exports_external.number().int().min(1).max(40).default(6),deadband:exports_external.number().min(0).max(1).default(0),retirement_min_age_days:exports_external.number().int().min(1).max(3650).default(60)}).strict(),DEFAULT_SKILL_OPT_CONFIG={enabled:!1,max_rounds:5,max_candidates_per_round:3,max_validations_per_round:1,max_round_time_ms:3600000,max_tokens_per_round:50000,max_rejections:5,max_inconclusive_rounds:2,max_transient_retries:5,convergence_non_improvements:3,max_changed_lines:200,max_changed_bytes:20000,max_changed_sections:6,deadband:0,retirement_min_age_days:60},SpecWriterConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),model:exports_external.string().nullable().default(null),fallback_models:exports_external.array(exports_external.string()).default([]),allow_spec_write:exports_external.boolean().default(!0)}),SlopDetectorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),classThreshold:exports_external.number().int().min(1).default(3),commentStripThreshold:exports_external.number().int().min(1).default(5),diffLineThreshold:exports_external.number().int().min(10).default(200),importHygieneThreshold:exports_external.number().int().min(1).default(2)}),IncrementalVerifyConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),command:exports_external.union([exports_external.string(),exports_external.array(exports_external.string())]).nullable().default(null),timeoutMs:exports_external.number().int().min(1000).max(300000).default(30000),triggerAgents:exports_external.array(exports_external.string()).default(["coder"])}),CompactionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),observationThreshold:exports_external.number().min(1).max(99).default(40),reflectionThreshold:exports_external.number().min(1).max(99).default(60),emergencyThreshold:exports_external.number().min(1).max(99).default(80),preserveLastNTurns:exports_external.number().int().min(1).default(5)}),PrmConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),pattern_thresholds:exports_external.object({repetition_loop:exports_external.number().min(1).default(2),ping_pong:exports_external.number().min(1).default(2),expansion_drift:exports_external.number().min(1).default(3),stuck_on_test:exports_external.number().min(1).default(3),context_thrash:exports_external.number().min(1).default(3)}).default(()=>({repetition_loop:2,ping_pong:2,expansion_drift:3,stuck_on_test:3,context_thrash:3})),max_trajectory_lines:exports_external.number().min(10).default(1000),escalation_enabled:exports_external.boolean().default(!0),detection_timeout_ms:exports_external.number().min(10).default(100)}),AgentAuthorityRuleSchema=exports_external.object({readOnly:exports_external.boolean().optional(),blockedExact:exports_external.array(exports_external.string()).optional(),allowedExact:exports_external.array(exports_external.string()).optional(),blockedPrefix:exports_external.array(exports_external.string()).optional(),allowedPrefix:exports_external.array(exports_external.string()).optional(),blockedZones:exports_external.array(exports_external.enum(["production","test","config","generated","docs","build"])).optional(),blockedGlobs:exports_external.array(exports_external.string()).optional(),allowedGlobs:exports_external.array(exports_external.string()).optional(),allowedCaseSensitiveGlobs:exports_external.array(exports_external.string()).optional()}),AuthorityConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),rules:exports_external.record(exports_external.string(),AgentAuthorityRuleSchema).default({}),universal_deny_prefixes:exports_external.array(exports_external.string().min(1)).default([]),verifier_config_paths:exports_external.array(exports_external.string()).optional().describe("Additional glob patterns for verifier config files that are merged into the architect agent's blockedGlobs at plugin init. Writes to matching files are blocked by the authority layer.")}),GeneralCouncilMemberConfigSchema=exports_external.object({memberId:exports_external.string().min(1),model:exports_external.string().min(1),role:exports_external.enum(["generalist","skeptic","domain_expert","devil_advocate","synthesizer"]),persona:exports_external.string().optional()}).strict(),GeneralCouncilConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),searchProvider:exports_external.enum(["tavily","brave"]).default("tavily"),searchApiKey:exports_external.string().optional(),members:exports_external.array(GeneralCouncilMemberConfigSchema).default([]),presets:exports_external.record(exports_external.string(),exports_external.array(GeneralCouncilMemberConfigSchema)).default({}),deliberate:exports_external.boolean().default(!0),moderator:exports_external.boolean().default(!0),moderatorModel:exports_external.string().optional(),maxSourcesPerMember:exports_external.number().int().min(1).max(20).default(5)}).strict(),CouncilConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),maxRounds:exports_external.number().int().min(1).max(10).default(3),parallelTimeoutMs:exports_external.number().int().min(5000).max(120000).default(30000),vetoPriority:exports_external.boolean().default(!0),requireAllMembers:exports_external.boolean().default(!1).describe("When true, submit_council_verdicts rejects if fewer than 5 member verdicts are provided. Equivalent to minimumMembers: 5."),minimumMembers:exports_external.number().int().min(1).max(5).default(3).describe("Minimum distinct council member verdicts required for synthesis. Default 3. Set to 1 to disable quorum enforcement. requireAllMembers: true overrides this to 5 (stricter constraint wins)."),escalateOnMaxRounds:exports_external.string().optional().describe("Optional webhook URL or handler name invoked when maxRounds is reached without APPROVE. Declared for forward compatibility; no behavior is implemented yet."),phaseConcernsAllowComplete:exports_external.boolean().default(!0).describe("When true, a phase-level council CONCERNS verdict with only MEDIUM/LOW findings does NOT block phase completion — the advisory notes are logged as warnings and the phase proceeds. When false, CONCERNS blocks like REJECT. Note: HIGH/CRITICAL findings from CONCERNS members are always promoted to requiredFixes and block at the tool level regardless of this setting. Default: true."),general:GeneralCouncilConfigSchema.optional()}).strict(),PrMonitorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),poll_interval_seconds:exports_external.number().int().min(30).max(300).default(60),max_subscriptions:exports_external.number().int().min(1).max(100).default(20),max_prs_per_cycle:exports_external.number().int().min(1).max(20).default(5),max_concurrent_pr_polls:exports_external.number().int().min(1).max(10).default(3),poll_timeout_ms:exports_external.number().int().min(5000).max(120000).default(30000),failure_threshold:exports_external.number().int().min(1).max(20).default(5),cooldown_seconds:exports_external.number().int().min(5).max(600).default(30),max_cooldown_seconds:exports_external.number().int().min(30).max(3600).default(300),cleanup_ttl_days:exports_external.number().int().min(1).max(90).default(7),auto_unsubscribe_on_merge:exports_external.boolean().default(!0),auto_unsubscribe_on_close:exports_external.boolean().default(!0),notify_ci_failure:exports_external.boolean().default(!0),notify_new_comments:exports_external.boolean().default(!0),notify_merge_conflict:exports_external.boolean().default(!0),notify_review_activity:exports_external.boolean().default(!0),notify_merged:exports_external.boolean().default(!0),notify_closed:exports_external.boolean().default(!0),notify_ci_success:exports_external.boolean().default(!1),auto_pr_feedback:exports_external.boolean().default(!1),event_delivery:exports_external.enum(["advisory","prompt"]).default("prompt"),auto_subscribe_on_pr_create:exports_external.boolean().default(!0)}).strict(),ParallelizationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),maxConcurrentTasks:exports_external.number().int().min(1).max(64).default(1),evidenceLockTimeoutMs:exports_external.number().int().min(1000).max(300000).default(60000),max_coders:exports_external.number().int().min(1).max(16).default(3),max_reviewers:exports_external.number().int().min(1).max(16).default(2)}),WorktreeIsolationConfigSchema=exports_external.object({policy:exports_external.enum(["auto","required","disabled"]).default("auto"),merge_strategy:exports_external.enum(["merge","rebase","cherry-pick"]).default("merge"),worktree_dir:exports_external.string().optional(),deps_strategy:exports_external.enum(["skip","copy","link"]).default("skip"),lane_permissions:exports_external.enum(["scoped_allow","deny","off"]).default("scoped_allow"),serialization_release_after_dispatches:exports_external.number().int().positive().default(5),serialization_release_after_ms:exports_external.number().int().positive().default(60000),runtime_isolation:exports_external.object({enabled:exports_external.boolean().default(!1),port_base:exports_external.number().int().nonnegative().max(65535).optional(),port_stride:exports_external.number().int().positive().default(1),env_overrides:exports_external.record(exports_external.string(),exports_external.string()).optional(),cache_redirects:exports_external.record(exports_external.string(),exports_external.string()).optional()}).optional()}),LeanTurboConfigSchema=exports_external.object({max_parallel_coders:exports_external.number().int().min(1).max(6).default(4),require_declared_scope:exports_external.boolean().default(!0),conflict_policy:exports_external.enum(["serialize","degrade"]).default("serialize"),degrade_on_risk:exports_external.boolean().default(!0),phase_reviewer:exports_external.boolean().default(!0),phase_critic:exports_external.boolean().default(!0),integrated_diff_required:exports_external.boolean().default(!0),allow_docs_only_without_reviewer:exports_external.boolean().default(!1),worktree_isolation:exports_external.boolean().default(!0),merge_strategy:exports_external.enum(["merge","rebase","cherry-pick"]).default("merge").optional(),worktree_dir:exports_external.string().optional(),deps_strategy:exports_external.enum(["skip","copy","link"]).optional(),runtime_isolation:exports_external.object({enabled:exports_external.boolean().default(!1),port_base:exports_external.number().int().nonnegative().max(65535).optional(),port_stride:exports_external.number().int().positive().default(1),env_overrides:exports_external.record(exports_external.string(),exports_external.string()).optional(),cache_redirects:exports_external.record(exports_external.string(),exports_external.string()).optional()}).optional()}),EpicConfigSchema=exports_external.object({cochange:exports_external.object({enabled:exports_external.boolean().default(!1),threshold:exports_external.number().min(-1).max(1).default(0.6),min_co_changes:exports_external.number().int().min(1).default(5)}).strict().optional(),mode:exports_external.object({enabled:exports_external.boolean().default(!1),activation_threshold:exports_external.number().min(0).max(1).default(0.3),min_commits_for_signal:exports_external.number().int().min(1).default(20)}).strict().optional(),calibration:exports_external.object({enabled:exports_external.boolean().default(!0),floor_threshold:exports_external.number().min(0).max(1).default(0.05),tighten_step:exports_external.number().min(0).max(1).default(0.02),loosen_step:exports_external.number().min(0).max(1).default(0.01),loosen_window:exports_external.number().int().min(1).default(10)}).strict().optional()}).strict(),StandardTurboConfigSchema=exports_external.object({strategy:exports_external.literal("standard"),lean:LeanTurboConfigSchema.optional(),epic:EpicConfigSchema.optional()}),LeanTurboStrategyConfigSchema=exports_external.object({strategy:exports_external.literal("lean"),lean:LeanTurboConfigSchema,epic:EpicConfigSchema.optional()}),TurboConfigSchema=exports_external.discriminatedUnion("strategy",[StandardTurboConfigSchema,LeanTurboStrategyConfigSchema]),ExternalSkillCandidateSourceTypeSchema=exports_external.enum(["github","url","collection","manual_import"]),ExternalSkillCandidateEvaluationVerdictSchema=exports_external.enum(["pending","in_review","quarantined","passed","rejected","promoted","revoked"]),DiscoverySourceSchema=exports_external.object({type:ExternalSkillCandidateSourceTypeSchema,location:exports_external.string().min(1),enabled:exports_external.boolean().default(!0),trust_level:exports_external.enum(["low","medium","high"]).default("low").optional()}),ExternalSkillCandidateSchema=exports_external.object({id:exports_external.string().uuid(),source_url:exports_external.string().url(),source_type:ExternalSkillCandidateSourceTypeSchema,publisher:exports_external.string().min(1),sha256:exports_external.string().regex(/^[a-f0-9]{64}$/),fetched_at:exports_external.string().datetime(),skill_name:exports_external.string().optional(),skill_description:exports_external.string().optional(),skill_body:exports_external.string(),risk_flags:exports_external.array(exports_external.string()).default([]),evaluation_verdict:ExternalSkillCandidateEvaluationVerdictSchema.default("pending"),evaluation_history:exports_external.array(exports_external.object({verdict:ExternalSkillCandidateEvaluationVerdictSchema,timestamp:exports_external.string().datetime(),actor:exports_external.string(),reason:exports_external.string().optional(),candidate_id:exports_external.string().optional(),original_verdict:ExternalSkillCandidateEvaluationVerdictSchema.optional(),gate_results:exports_external.array(exports_external.object({gate:exports_external.string(),verdict:exports_external.string()})).optional(),risk_assessment:exports_external.object({total_flags:exports_external.number().int().nonnegative(),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["error","warning"]),category:exports_external.string()}))}).optional(),risk_flags_count:exports_external.number().int().nonnegative().optional(),provenance_snapshot:exports_external.object({sha256:exports_external.string(),source_url:exports_external.string(),publisher:exports_external.string(),fetched_at:exports_external.string().datetime().optional()}).optional(),target_path:exports_external.string().optional(),promoted_content_hash:exports_external.string().regex(/^[a-f0-9]{64}$/).optional(),original_evaluation:exports_external.record(exports_external.string(),exports_external.unknown()).optional()})).default([])}),ExternalSkillsConfigSchema=exports_external.object({curation_enabled:exports_external.boolean().default(!1),max_candidates:exports_external.number().int().min(1).max(1e4).default(500),max_bytes_per_candidate:exports_external.number().int().min(1024).max(10485760).default(1048576),eviction_policy:exports_external.enum(["fifo"]).default("fifo"),ttl_days:exports_external.number().int().min(1).max(3650).default(90),evaluation_enabled:exports_external.boolean().default(!1),sources:exports_external.array(DiscoverySourceSchema).default([]),max_candidates_per_discovery:exports_external.number().int().min(1).max(1000).default(50),max_concurrent_fetches:exports_external.number().int().min(1).max(20).default(5),fetch_timeout_ms:exports_external.number().int().min(1000).max(300000).default(30000)}),DEFAULT_EXTERNAL_SKILLS_CONFIG={curation_enabled:!1,max_candidates:500,max_bytes_per_candidate:1048576,eviction_policy:"fifo",ttl_days:90,evaluation_enabled:!1,sources:[],max_candidates_per_discovery:50,max_concurrent_fetches:5,fetch_timeout_ms:30000},DEFAULT_SKILLS_CONFIG={enabled:!1};PluginConfigSchema=exports_external.object({config_format_version:exports_external.number().int().min(0).default(1),agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional(),default_agent:exports_external.string().optional().transform((v)=>{if(v===void 0)return;let trimmed=v.trim();return trimmed===""?void 0:trimmed}),auto_select_architect:exports_external.union([exports_external.boolean(),exports_external.string()]).optional().transform((v)=>{if(v===void 0)return;if(typeof v==="boolean")return v;let trimmed=v.trim();return trimmed===""?!1:trimmed}),swarms:exports_external.record(exports_external.string().regex(/^[^_]+$/,"Swarm ID must not contain underscores"),SwarmConfigSchema).optional(),max_iterations:exports_external.number().min(1).max(10).default(5),pipeline:PipelineConfigSchema.optional(),phase_complete:PhaseCompleteConfigSchema.optional(),qa_retry_limit:exports_external.number().min(1).max(10).default(3),execution_mode:exports_external.enum(["strict","balanced","fast"]).default("balanced"),inject_phase_reminders:exports_external.boolean().default(!0),hooks:HooksConfigSchema.optional(),gates:GateConfigSchema.optional(),context_budget:ContextBudgetConfigSchema.optional(),pricing:PricingConfigSchema.optional(),guardrails:GuardrailsConfigSchema.optional(),watchdog:WatchdogConfigSchema.optional(),self_review:SelfReviewConfigSchema.optional(),auto_review:AutoReviewConfigSchema.optional(),tool_filter:ToolFilterConfigSchema.optional(),authority:AuthorityConfigSchema.optional(),plan_cursor:PlanCursorConfigSchema.optional(),context_map:ContextMapConfigSchema.optional(),repo_graph:RepoGraphConfigSchema.prefault({}),evidence:EvidenceConfigSchema.optional(),summaries:SummaryConfigSchema.optional(),review_passes:ReviewPassesConfigSchema.optional(),adversarial_detection:AdversarialDetectionConfigSchema.optional(),adversarial_testing:AdversarialTestingConfigSchema.optional(),integration_analysis:IntegrationAnalysisConfigSchema.optional(),docs:DocsConfigSchema.optional(),design_docs:DesignDocsConfigSchema.optional(),ui_review:UIReviewConfigSchema.optional(),compaction_advisory:CompactionAdvisoryConfigSchema.optional(),lint:LintConfigSchema.optional(),secretscan:SecretscanConfigSchema.optional(),checkpoint:CheckpointConfigSchema.optional(),apply_patch:ApplyPatchConfigSchema.optional(),automation:AutomationConfigSchema.optional(),knowledge:KnowledgeConfigSchema.optional(),memory:MemoryConfigSchema.optional(),learning:LearningConfigSchema.optional(),consensus:ConsensusConfigSchema.optional(),curator:CuratorConfigSchema.optional(),architectural_supervision:ArchitecturalSupervisionConfigSchema.optional(),knowledge_application:KnowledgeApplicationConfigSchema.optional(),skillPropagation:SkillPropagationConfigSchema.optional(),skill_improver:SkillImproverConfigSchema.optional(),spec_writer:SpecWriterConfigSchema.optional(),tool_output:exports_external.object({truncation_enabled:exports_external.boolean().default(!0),max_lines:exports_external.number().min(10).max(500).default(150),per_tool:exports_external.record(exports_external.string(),exports_external.number()).optional(),truncation_tools:exports_external.array(exports_external.string()).optional().describe("Tools to apply output truncation to. Defaults to diff, symbols, bash, shell, test_runner, lint, pre_check_batch, complexity_hotspots, pkg_audit, sbom_generate, schema_drift.")}).optional(),slop_detector:SlopDetectorConfigSchema.optional(),todo_gate:exports_external.object({enabled:exports_external.boolean().default(!0),max_high_priority:exports_external.number().int().min(-1).default(0).describe("Max new high-priority TODOs (FIXME/HACK/XXX) before warning. 0 = warn on any. Set to -1 to disable."),block_on_threshold:exports_external.boolean().default(!1).describe("If true, block phase completion when threshold exceeded. Default: advisory only.")}).optional(),incremental_verify:IncrementalVerifyConfigSchema.optional(),compaction_service:CompactionConfigSchema.optional(),prm:PrmConfigSchema.optional(),council:CouncilConfigSchema.optional(),parallelization:ParallelizationConfigSchema.optional(),worktree:WorktreeIsolationConfigSchema.optional(),turbo:TurboConfigSchema.optional(),turbo_mode:exports_external.boolean().default(!1).optional(),quiet:exports_external.boolean().default(!0).optional(),version_check:exports_external.boolean().default(!0).optional(),full_auto:exports_external.object({enabled:exports_external.boolean().default(!1),locked:exports_external.boolean().default(!1),critic_model:exports_external.string().optional(),max_interactions_per_phase:exports_external.number().int().min(5).max(200).default(50),deadlock_threshold:exports_external.number().int().min(2).max(10).default(3),escalation_mode:exports_external.enum(["pause","terminate"]).default("pause"),mode:exports_external.enum(["assisted","supervised","strict"]).default("supervised"),fail_closed:exports_external.boolean().default(!0),permission_policy:exports_external.object({enabled:exports_external.boolean().default(!0),trusted_roots:exports_external.array(exports_external.string()).default(["."]),trusted_domains:exports_external.array(exports_external.string()).default([]),protected_paths:exports_external.array(exports_external.string()).default([".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"]),allow_defaults:exports_external.boolean().default(!0)}).default(()=>({enabled:!0,trusted_roots:["."],trusted_domains:[],protected_paths:[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"],allow_defaults:!0})),denials:exports_external.object({max_consecutive:exports_external.number().int().min(1).max(50).default(3),max_total:exports_external.number().int().min(1).max(500).default(20),on_limit:exports_external.enum(["pause","terminate"]).default("pause")}).default(()=>({max_consecutive:3,max_total:20,on_limit:"pause"})),oversight:exports_external.object({on_plan_change:exports_external.boolean().default(!0),on_task_completion:exports_external.boolean().default(!1),on_phase_boundary:exports_external.boolean().default(!0),on_high_risk_action:exports_external.boolean().default(!0),on_subagent_return_warning:exports_external.boolean().default(!0),every_tool_calls:exports_external.number().int().min(0).max(1e4).default(25),every_architect_turns:exports_external.number().int().min(0).max(1000).default(5),every_minutes:exports_external.number().int().min(0).max(1440).default(20),max_dispatch_retries:exports_external.number().int().min(0).max(10).default(2),max_consecutive_dispatch_failures:exports_external.number().int().min(0).max(50).default(3)}).default(()=>({on_plan_change:!0,on_task_completion:!1,on_phase_boundary:!0,on_high_risk_action:!0,on_subagent_return_warning:!0,every_tool_calls:25,every_architect_turns:5,every_minutes:20,max_dispatch_retries:2,max_consecutive_dispatch_failures:3}))}).optional().default(()=>({enabled:!1,locked:!1,max_interactions_per_phase:50,deadlock_threshold:3,escalation_mode:"pause",mode:"supervised",fail_closed:!0,permission_policy:{enabled:!0,trusted_roots:["."],trusted_domains:[],protected_paths:[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"],allow_defaults:!0},denials:{max_consecutive:3,max_total:20,on_limit:"pause"},oversight:{on_plan_change:!0,on_task_completion:!1,on_phase_boundary:!0,on_high_risk_action:!0,on_subagent_return_warning:!0,every_tool_calls:25,every_architect_turns:5,every_minutes:20,max_dispatch_retries:2,max_consecutive_dispatch_failures:3}})),pr_monitor:PrMonitorConfigSchema.optional(),external_skills:ExternalSkillsConfigSchema.optional(),skills:SkillsConfigSchema.optional(),skill_opt:SkillOptConfigSchema.optional()})});var exports_loader={};__export(exports_loader,{loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadAgentPrompt:()=>loadAgentPrompt,getSafeDefaultConfigLoadResult:()=>getSafeDefaultConfigLoadResult,formatZodIssues:()=>formatZodIssues,deepMerge:()=>deepMerge,MAX_MERGE_DEPTH:()=>MAX_MERGE_DEPTH,MAX_CONFIG_FILE_BYTES:()=>MAX_CONFIG_FILE_BYTES});import*as fs from"node:fs";import*as fsPromises from"node:fs/promises";import*as os from"node:os";import*as path from"node:path";function getUserConfigDir(){return process.env.XDG_CONFIG_HOME||path.join(os.homedir(),".config")}function loadRawConfigFromPath(configPath){try{if(fs.statSync(configPath).size>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let content=fs.readFileSync(configPath,"utf-8");if(content.length>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let sanitizedContent=content;if(content.charCodeAt(0)===65279)sanitizedContent=content.slice(1);let rawConfig=JSON.parse(sanitizedContent);if(typeof rawConfig!=="object"||rawConfig===null||Array.isArray(rawConfig))return advisoryWarn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config format invalid. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};return{config:rawConfig,fileExisted:!0,hadError:!1}}catch(error49){if(!(error49 instanceof Error&&("code"in error49)&&error49.code==="ENOENT")){let errorMessage=error49 instanceof Error?error49.message:String(error49);return advisoryWarn(`[opencode-swarm] ⚠️ CONFIG LOAD FAILURE — config exists at ${configPath} but could not be loaded: ${errorMessage}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config load failed. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0}}return{config:null,fileExisted:!1,hadError:!1}}}function migratePresetsConfig(raw){if(raw.presets&&typeof raw.presets==="object"&&!raw.agents){let presetName=raw.preset||"remote",presets=raw.presets,activePreset=presets[presetName]||Object.values(presets)[0];if(activePreset&&typeof activePreset==="object"){let migrated={...raw,agents:activePreset};return delete migrated.preset,delete migrated.presets,delete migrated.swarm_mode,advisoryWarn("[opencode-swarm] Migrated v6.12 presets config to agents format. Consider updating your opencode-swarm.json."),migrated}}return raw}function sanitizeExternalSkillsConfig(raw){if(!("external_skills"in raw)||raw.external_skills===void 0)return{result:raw,strippedKeys:[]};let esResult=ExternalSkillsConfigSchema.safeParse(raw.external_skills);if(esResult.success)return{result:{...raw,external_skills:resolveExternalSkillsConfig(esResult.data)},strippedKeys:[]};advisoryWarn("[opencode-swarm] external_skills config validation failed:",formatZodIssues(esResult.error)),advisoryWarn("[opencode-swarm] External skills curation disabled due to invalid config. Fix the external_skills section to enable it.");let cleaned={...raw};return delete cleaned.external_skills,{result:cleaned,strippedKeys:["external_skills"]}}function sanitizeGatesConfig(raw){let strippedKeys=[];if(!("gates"in raw)||raw.gates===void 0)return{result:raw,strippedKeys};if(typeof raw.gates!=="object"||raw.gates===null||Array.isArray(raw.gates)){advisoryWarn("[opencode-swarm] gates config validation failed: expected an object. Quality gates will use defaults; other config sections remain active.");let cleaned2={...raw};return delete cleaned2.gates,strippedKeys.push("gates"),{result:cleaned2,strippedKeys}}let gateSchemas=GateConfigSchema.shape,cleanedGates={...raw.gates};for(let[key,value]of Object.entries(cleanedGates)){let schema=gateSchemas[key];if(!schema){advisoryWarn(`[opencode-swarm] Unknown gates config section "gates.${key}" ignored. Other config sections remain active.`),delete cleanedGates[key],strippedKeys.push(`gates.${key}`);continue}let knownFields=GATE_CONFIG_KNOWN_SECTION_KEYS[key],sectionValue=value;if(knownFields&&typeof value==="object"&&value!==null&&!Array.isArray(value)){let cleanedSection={...value},knownFieldSet=new Set(knownFields);for(let fieldName of Object.keys(cleanedSection))if(!knownFieldSet.has(fieldName))advisoryWarn(`[opencode-swarm] Unknown gates config key "gates.${key}.${fieldName}" ignored. Other config sections remain active.`),delete cleanedSection[fieldName],strippedKeys.push(`gates.${key}.${fieldName}`);sectionValue=cleanedSection,cleanedGates[key]=cleanedSection}let sectionResult=schema.safeParse(sectionValue);if(!sectionResult.success){if(advisoryWarn(`[opencode-swarm] gates.${key} config validation failed; that gate section will use defaults and other config sections remain active:`,formatZodIssues(sectionResult.error)),delete cleanedGates[key],!strippedKeys.includes(`gates.${key}`))strippedKeys.push(`gates.${key}`)}}let gatesResult=GateConfigSchema.safeParse(cleanedGates);if(gatesResult.success)return{result:{...raw,gates:gatesResult.data},strippedKeys};advisoryWarn("[opencode-swarm] gates config validation failed after section cleanup; quality gates will use defaults and other config sections remain active:",formatZodIssues(gatesResult.error));let cleaned={...raw};if(delete cleaned.gates,!strippedKeys.includes("gates"))strippedKeys.push("gates");return{result:cleaned,strippedKeys}}function sanitizeSectionConfigs(raw){let{result:afterExternal,strippedKeys:externalStripped}=sanitizeExternalSkillsConfig(raw),{result,strippedKeys:gatesStripped}=sanitizeGatesConfig(afterExternal);return{result,strippedKeys:[...externalStripped,...gatesStripped]}}function formatZodIssues(error49){if(error49.issues.length===0)return"";return error49.issues.map((issue2)=>{let dotted2=issue2.path.map(String).join(".");return dotted2?`${dotted2}: ${issue2.message}`:issue2.message}).join("; ")}function stripUnrecognizedKeys(raw,error49){let removed=[],cleaned=structuredClone(raw);for(let issue2 of error49.issues){if(issue2.code!=="unrecognized_keys")continue;let keys=issue2.keys??[],node=cleaned;for(let seg of issue2.path)if(node&&typeof node==="object")node=node[seg];else{node=void 0;break}if(!node||typeof node!=="object")continue;for(let key of keys)if(key in node){delete node[key];let dotted2=[...issue2.path.map(String),key].join(".");removed.push(dotted2)}}return{cleaned,removed}}function rawFullAutoLocked(raw){if(!raw||typeof raw!=="object")return!1;let fullAuto=raw.full_auto;if(!fullAuto||typeof fullAuto!=="object"||Array.isArray(fullAuto))return!1;return fullAuto.locked===!0}function buildConfigWithMeta(rawUserConfig,rawProjectConfig,loadedFromFile,configHadErrors){let mergedRaw=rawUserConfig??{};if(rawProjectConfig)mergedRaw=deepMerge(mergedRaw,rawProjectConfig);if(rawFullAutoLocked(rawUserConfig)||rawFullAutoLocked(rawProjectConfig)){let fa=mergedRaw.full_auto&&typeof mergedRaw.full_auto==="object"&&!Array.isArray(mergedRaw.full_auto)?mergedRaw.full_auto:{};mergedRaw={...mergedRaw,full_auto:{...fa,locked:!0}}}mergedRaw=migratePresetsConfig(mergedRaw);let{result:sanitized,strippedKeys:gatesStripped}=sanitizeSectionConfigs(mergedRaw);mergedRaw=sanitized;let secure=(cfg)=>loadedFromFile&&configHadErrors?PluginConfigSchema.parse({...cfg,guardrails:{enabled:!0}}):cfg,firstResult=PluginConfigSchema.safeParse(mergedRaw);if(firstResult.success){let config2=secure(firstResult.data);if(loadedFromFile&&configHadErrors)return advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."),{config:config2,recovery:"guardrails_defaults",removedKeys:[...gatesStripped],warnings:[]};return{config:config2,recovery:gatesStripped.length>0?"stripped_keys":"none",removedKeys:[...gatesStripped],warnings:[]}}let{cleaned,removed}=stripUnrecognizedKeys(mergedRaw,firstResult.error);if(removed.length>0){let recovered=PluginConfigSchema.safeParse(cleaned);if(recovered.success)return advisoryWarn(`[opencode-swarm] Ignored ${removed.length} unrecognized config key(s): ${removed.join(", ")}. The rest of your configuration was preserved. Fix or remove these keys.`),{config:secure(recovered.data),recovery:"stripped_keys",removedKeys:[...gatesStripped,...removed],warnings:[]}}if(rawUserConfig){let{result:userSanitized,strippedKeys:userGatesStripped}=sanitizeSectionConfigs(rawUserConfig),userParseResult=PluginConfigSchema.safeParse(userSanitized);if(userParseResult.success)return advisoryWarn("[opencode-swarm] Project config ignored due to validation errors. Using user config."),{config:secure(userParseResult.data),recovery:"user_only",removedKeys:[...gatesStripped,...userGatesStripped],warnings:["Project config ignored due to validation errors; using user config."]};let userStripped=stripUnrecognizedKeys(userSanitized,userParseResult.error);if(userStripped.removed.length>0){let userRecovered=PluginConfigSchema.safeParse(userStripped.cleaned);if(userRecovered.success)return advisoryWarn(`[opencode-swarm] Project config ignored; also ignored ${userStripped.removed.length} unrecognized user-config key(s): ${userStripped.removed.join(", ")}.`),{config:secure(userRecovered.data),recovery:"user_only",removedKeys:[...gatesStripped,...userGatesStripped,...userStripped.removed],warnings:["Project config ignored due to validation errors; using user config."]}}}if(!(mergedRaw.guardrails&&typeof mergedRaw.guardrails==="object"&&!Array.isArray(mergedRaw.guardrails)&&mergedRaw.guardrails.enabled===!1)){let valueRecovery=sanitizeMalformedValues(PluginConfigSchema,mergedRaw);if(valueRecovery.recoveryWarnings.length>0){let recoveredParse=PluginConfigSchema.safeParse(valueRecovery.config);if(recoveredParse.success){let removedKeys=[...gatesStripped,...valueRecovery.recoveryWarnings.map((w)=>w.section)],secureParse=PluginConfigSchema.safeParse({...recoveredParse.data,guardrails:{...recoveredParse.data.guardrails,enabled:!0}});if(secureParse.success)return advisoryWarn(`[opencode-swarm] Ignored ${removedKeys.length} invalid or unrecognized config key(s): ${removedKeys.join(", ")}. The rest of your configuration was preserved. Fix or remove these keys.`),{config:secure(secureParse.data),recovery:"sanitized_values",removedKeys,warnings:[]}}}}let offending=stripUnrecognizedKeys(mergedRaw,firstResult.error).removed;if(offending.length>0)advisoryWarn(`[opencode-swarm] Merged config validation failed. Unrecognized key(s): ${offending.join(", ")}.`);else advisoryWarn("[opencode-swarm] Merged config validation failed:",formatZodIssues(firstResult.error));return advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."),{config:PluginConfigSchema.parse({guardrails:{enabled:!0}}),recovery:"guardrails_defaults",removedKeys:[...gatesStripped],warnings:["Config failed validation; using safe defaults with guardrails enabled."]}}function loadPluginConfig(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),userResult=loadRawConfigFromPath(userConfigPath),projectResult=loadRawConfigFromPath(projectConfigPath),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError;return buildConfigWithMeta(userResult.config,projectResult.config,loadedFromFile,configHadErrors).config}function loadPluginConfigWithMeta(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),userResult=loadRawConfigFromPath(userConfigPath),projectResult=loadRawConfigFromPath(projectConfigPath),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError,{config:config2,recovery,removedKeys,warnings}=buildConfigWithMeta(userResult.config,projectResult.config,loadedFromFile,configHadErrors);return{config:config2,loadedFromFile,configHadErrors,recovery,removedKeys,warnings}}function getSafeDefaultConfigLoadResult(){let{config:config2,recovery,removedKeys,warnings}=buildConfigWithMeta(null,null,!1,!1);return{config:config2,recovery,removedKeys,warnings,loadedFromFile:!1,configHadErrors:!1}}async function loadRawConfigFromPathAsync(configPath){try{if((await fsPromises.stat(configPath)).size>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let content=await fsPromises.readFile(configPath,"utf-8");if(content.length>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let sanitizedContent=content;if(content.charCodeAt(0)===65279)sanitizedContent=content.slice(1);let rawConfig=JSON.parse(sanitizedContent);if(typeof rawConfig!=="object"||rawConfig===null||Array.isArray(rawConfig))return advisoryWarn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config format invalid. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};return{config:rawConfig,fileExisted:!0,hadError:!1}}catch(error49){if(error49.code==="ENOENT")return{config:null,fileExisted:!1,hadError:!1};return advisoryWarn(`[opencode-swarm] Failed to load config from ${configPath}:`,error49 instanceof Error?error49.message:String(error49)),{config:null,fileExisted:!0,hadError:!0}}}async function loadPluginConfigWithMetaAsync(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),[userResult,projectResult]=await Promise.all([loadRawConfigFromPathAsync(userConfigPath),loadRawConfigFromPathAsync(projectConfigPath)]),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError,{config:config2,recovery,removedKeys,warnings}=buildConfigWithMeta(userResult.config,projectResult.config,loadedFromFile,configHadErrors);return{config:config2,loadedFromFile,configHadErrors,recovery,removedKeys,warnings}}function loadAgentPrompt(agentName){let promptsDir=path.join(getUserConfigDir(),"opencode",PROMPTS_DIR_NAME),result={},promptPath=path.join(promptsDir,`${agentName}.md`);if(fs.existsSync(promptPath))try{result.prompt=fs.readFileSync(promptPath,"utf-8")}catch(error49){advisoryWarn(`[opencode-swarm] Error reading prompt file ${promptPath}:`,error49 instanceof Error?error49.message:String(error49))}let appendPromptPath=path.join(promptsDir,`${agentName}_append.md`);if(fs.existsSync(appendPromptPath))try{result.appendPrompt=fs.readFileSync(appendPromptPath,"utf-8")}catch(error49){advisoryWarn(`[opencode-swarm] Error reading append prompt ${appendPromptPath}:`,error49 instanceof Error?error49.message:String(error49))}return result}var CONFIG_FILENAME="opencode-swarm.json",PROMPTS_DIR_NAME="opencode-swarm",MAX_CONFIG_FILE_BYTES=102400;var init_loader=__esm(()=>{init_warning_buffer();init_schema()});var ExecutionProfileSchema,TaskStatusSchema,TaskSizeSchema,PhaseStatusSchema,MigrationStatusSchema,TaskSchema,PhaseSchema,PlanSchema;var init_plan_schema=__esm(()=>{init_zod();ExecutionProfileSchema=exports_external.object({parallelization_enabled:exports_external.boolean().default(!1),max_concurrent_tasks:exports_external.number().int().min(1).max(64).default(10),council_parallel:exports_external.boolean().default(!0),locked:exports_external.boolean().default(!1),auto_proceed:exports_external.boolean().default(!1)}),TaskStatusSchema=exports_external.enum(["pending","in_progress","completed","blocked","closed"]),TaskSizeSchema=exports_external.enum(["small","medium","large"]),PhaseStatusSchema=exports_external.enum(["pending","in_progress","complete","completed","blocked","closed"]),MigrationStatusSchema=exports_external.enum(["native","migrated","migration_failed"]),TaskSchema=exports_external.object({id:exports_external.string(),phase:exports_external.number().int().min(1),status:TaskStatusSchema.default("pending"),size:TaskSizeSchema.default("small"),description:exports_external.string().min(1),depends:exports_external.array(exports_external.string()).default([]),acceptance:exports_external.string().optional(),files_touched:exports_external.array(exports_external.string()).default([]),evidence_path:exports_external.string().optional(),blocked_reason:exports_external.string().optional(),fr_refs:exports_external.array(exports_external.string()).optional()}),PhaseSchema=exports_external.object({id:exports_external.number().int().min(1),name:exports_external.string().min(1),status:PhaseStatusSchema.default("pending"),tasks:exports_external.array(TaskSchema).default([]),type:exports_external.enum(["code","non-code"]).optional(),required_agents:exports_external.array(exports_external.string()).optional()}),PlanSchema=exports_external.object({schema_version:exports_external.literal("1.0.0"),title:exports_external.string().min(1),swarm:exports_external.string().min(1),current_phase:exports_external.number().int().min(1).optional(),phases:exports_external.array(PhaseSchema).min(1),migration_status:MigrationStatusSchema.optional(),specMtime:exports_external.string().optional(),specHash:exports_external.string().optional(),execution_profile:ExecutionProfileSchema.optional()})});function stripCodeBlocks(content){return content.replace(FENCED_BLOCK_PATTERN,"").replace(INLINE_CODE_PATTERN,"")}function getLineNumber(content,position){return(content.substring(0,position).match(/\n/g)||[]).length+1}function validateSpecContent(content){let issues=[];if(!content||content.trim().length===0)return{valid:!1,issues:[{line:1,message:"Content is empty"}]};let strippedContent=stripCodeBlocks(content),frMatches=strippedContent.match(FR_ID_PATTERN);if(!frMatches||frMatches.length===0)issues.push({line:1,message:"No FR-### requirement IDs found in spec content"});let obligationMatches=strippedContent.match(OBLIGATION_PATTERN);if(!obligationMatches||obligationMatches.length===0)issues.push({line:1,message:"No obligation keywords (MUST, SHALL, SHOULD, MAY) found in spec content"});let sectionMatches=strippedContent.match(SECTION_HEADER_PATTERN);if(!sectionMatches||sectionMatches.length===0)issues.push({line:1,message:"No section headers (## Section Name) found in spec content"});let idMatches=strippedContent.matchAll(/\bFR-(\d{3})\b/g);for(let idMatch of idMatches)if(parseInt(idMatch[1],10)===0){let pos=idMatch.index;issues.push({line:getLineNumber(strippedContent,pos),message:`Invalid FR-ID "${idMatch[0]}" — number must be 001-999`})}return{valid:issues.length===0,issues}}var ObligationSchema,SpecRequirementSchema,SpecScenarioSchema,SpecSectionSchema,SwarmSpecSchema,SpecDeltaSchema,DeltaSpecSchema,FENCED_BLOCK_PATTERN,INLINE_CODE_PATTERN,FR_ID_PATTERN,OBLIGATION_PATTERN,SECTION_HEADER_PATTERN;var init_spec_schema=__esm(()=>{init_zod();ObligationSchema=exports_external.enum(["MUST","SHALL","SHOULD","MAY"]),SpecRequirementSchema=exports_external.object({id:exports_external.string().regex(/^FR-(?!000)\d{3}$/,"Requirement ID must match FR-### pattern (e.g., FR-001)"),obligation:ObligationSchema,text:exports_external.string().min(1)}),SpecScenarioSchema=exports_external.object({name:exports_external.string().min(1),given:exports_external.array(exports_external.string()).optional().default([]),when:exports_external.array(exports_external.string()).min(1,'Scenario must have at least one "when" clause'),thenClauses:exports_external.array(exports_external.string()).min(1,'Scenario must have at least one "then" clause')}),SpecSectionSchema=exports_external.object({name:exports_external.string().min(1),requirements:exports_external.array(SpecRequirementSchema).default([])}),SwarmSpecSchema=exports_external.object({title:exports_external.string().min(1),purpose:exports_external.string().min(1),sections:exports_external.array(SpecSectionSchema).min(1,"Spec must have at least one section")}),SpecDeltaSchema=exports_external.object({added:exports_external.array(SpecRequirementSchema).default([]),modified:exports_external.array(SpecRequirementSchema).default([]),removed:exports_external.array(SpecRequirementSchema).default([])}),DeltaSpecSchema=exports_external.union([SwarmSpecSchema,SpecDeltaSchema]),FENCED_BLOCK_PATTERN=/```[\s\S]*?```/g,INLINE_CODE_PATTERN=/`[^`]*`/g,FR_ID_PATTERN=/\bFR-\d{3}\b/g,OBLIGATION_PATTERN=/\b(MUST|SHALL|SHOULD|MAY)\b/g,SECTION_HEADER_PATTERN=/^##\s+.+$/gm});function resolveWorktreeIsolationConfig(config2){if(config2.worktree)return{...DEFAULT_WORKTREE_ISOLATION_CONFIG,...config2.worktree};let lean=config2.turbo?.strategy==="lean"?config2.turbo.lean:void 0;if(lean?.worktree_isolation)return{...DEFAULT_WORKTREE_ISOLATION_CONFIG,policy:"auto",merge_strategy:lean.merge_strategy??"merge",worktree_dir:lean.worktree_dir,deps_strategy:lean.deps_strategy??"skip",runtime_isolation:lean.runtime_isolation??DEFAULT_WORKTREE_ISOLATION_CONFIG.runtime_isolation};return DEFAULT_WORKTREE_ISOLATION_CONFIG}var init_worktree_isolation_config=__esm(()=>{init_constants()});var exports_config={};__export(exports_config,{validateSpecContent:()=>validateSpecContent,resolveWorktreeIsolationConfig:()=>resolveWorktreeIsolationConfig,resolveAutoReviewConfig:()=>resolveAutoReviewConfig,loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadAgentPrompt:()=>loadAgentPrompt,isSubagent:()=>isSubagent,isQAAgent:()=>isQAAgent,getSafeDefaultConfigLoadResult:()=>getSafeDefaultConfigLoadResult,_internals:()=>_internals2,WorktreeIsolationConfigSchema:()=>WorktreeIsolationConfigSchema,TurboConfigSchema:()=>TurboConfigSchema,TestEvidenceSchema:()=>TestEvidenceSchema,TaskStatusSchema:()=>TaskStatusSchema,TaskSizeSchema:()=>TaskSizeSchema,TaskSchema:()=>TaskSchema,SwarmSpecSchema:()=>SwarmSpecSchema,SwarmConfigSchema:()=>SwarmConfigSchema,SpecSectionSchema:()=>SpecSectionSchema,SpecScenarioSchema:()=>SpecScenarioSchema,SpecRequirementSchema:()=>SpecRequirementSchema,SpecDeltaSchema:()=>SpecDeltaSchema,SkillPropagationConfigSchema:()=>SkillPropagationConfigSchema,ReviewEvidenceSchema:()=>ReviewEvidenceSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QA_AGENTS:()=>QA_AGENTS,PricingConfigSchema:()=>PricingConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanSchema:()=>PlanSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseStatusSchema:()=>PhaseStatusSchema,PhaseSchema:()=>PhaseSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,PIPELINE_AGENTS:()=>PIPELINE_AGENTS,ObligationSchema:()=>ObligationSchema,ORCHESTRATOR_NAME:()=>ORCHESTRATOR_NAME,NoteEvidenceSchema:()=>NoteEvidenceSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MigrationStatusSchema:()=>MigrationStatusSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,EvidenceVerdictSchema:()=>EvidenceVerdictSchema,EvidenceTypeSchema:()=>EvidenceTypeSchema,EvidenceSchema:()=>EvidenceSchema,EvidenceBundleSchema:()=>EvidenceBundleSchema,EVIDENCE_MAX_TASK_BYTES:()=>EVIDENCE_MAX_TASK_BYTES,EVIDENCE_MAX_PATCH_BYTES:()=>EVIDENCE_MAX_PATCH_BYTES,EVIDENCE_MAX_JSON_BYTES:()=>EVIDENCE_MAX_JSON_BYTES,DiffEvidenceSchema:()=>DiffEvidenceSchema,DeltaSpecSchema:()=>DeltaSpecSchema,DEFAULT_MODELS:()=>DEFAULT_MODELS,BaseEvidenceSchema:()=>BaseEvidenceSchema,AutomationModeSchema:()=>AutomationModeSchema,AutomationConfigSchema:()=>AutomationConfigSchema,AutomationCapabilitiesSchema:()=>AutomationCapabilitiesSchema,AutoReviewConfigSchema:()=>AutoReviewConfigSchema,ApprovalEvidenceSchema:()=>ApprovalEvidenceSchema,ApplyPatchConfigSchema:()=>ApplyPatchConfigSchema,AgentOverrideConfigSchema:()=>AgentOverrideConfigSchema,AUTO_REVIEW_V8_BURN_IN_DECISION:()=>AUTO_REVIEW_V8_BURN_IN_DECISION,ALL_SUBAGENT_NAMES:()=>ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES:()=>ALL_AGENT_NAMES});var _internals2;var init_config=__esm(()=>{init_constants();init_evidence_schema();init_loader();init_loader();init_plan_schema();init_schema();init_spec_schema();init_worktree_isolation_config();_internals2={loadPluginConfigWithMeta}});function resolvePrompt(base,custom2,append){if(custom2)return custom2;if(append)return`${base}
|
|
158
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry);continue}}}}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=(zodSchema)=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"))schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema);else Object.assign(schema2,refSchema);if(Object.assign(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached))delete schema2[key]}if(refSchema.$ref&&refSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key]))delete schema2[key]}}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){if(schema2.$ref=parentSeen.schema.$ref,parentSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key]))delete schema2[key]}}}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);let result={};if(ctx.target==="draft-2020-12")result.$schema="https://json-schema.org/draft/2020-12/schema";else if(ctx.target==="draft-07")result.$schema="http://json-schema.org/draft-07/schema#";else if(ctx.target==="draft-04")result.$schema="http://json-schema.org/draft-04/schema#";else if(ctx.target==="openapi-3.0");if(ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);let defs=ctx.external?.defs??{};for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.def&&seen.defId)defs[seen.defId]=seen.def}if(ctx.external);else if(Object.keys(defs).length>0)if(ctx.target==="draft-2020-12")result.$defs=defs;else result.definitions=defs;try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch(_err){throw Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;if(def.rest&&isTransforming(def.rest,ctx))return!0;return!1}return!1}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{let ctx=initializeContext({...params,processors});return process2(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return process2(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var init_to_json_schema=__esm(()=>{init_registries()});function toJSONSchema(input,params){if("_idmap"in input){let registry2=input,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema]=entry;process2(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema]=entry;extractDefs(ctx2,schema),schemas[key]=finalize(ctx2,schema)}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return process2(input,ctx),extractDefs(ctx,input),finalize(ctx,input)}var formatMap,stringProcessor=(schema,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){if(json.format=formatMap[format]??format,json.format==="")delete json.format;if(format==="time")delete json.format}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){let regexes=[...patterns];if(regexes.length===1)json.pattern=regexes[0].source;else if(regexes.length>1)json.allOf=[...regexes.map((regex)=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}},numberProcessor=(schema,ctx,_json,_params)=>{let json=_json,{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema._zod.bag;if(typeof format==="string"&&format.includes("int"))json.type="integer";else json.type="number";if(typeof exclusiveMinimum==="number")if(ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0;else json.exclusiveMinimum=exclusiveMinimum;if(typeof minimum==="number"){if(json.minimum=minimum,typeof exclusiveMinimum==="number"&&ctx.target!=="draft-04")if(exclusiveMinimum>=minimum)delete json.minimum;else delete json.exclusiveMinimum}if(typeof exclusiveMaximum==="number")if(ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0;else json.exclusiveMaximum=exclusiveMaximum;if(typeof maximum==="number"){if(json.maximum=maximum,typeof exclusiveMaximum==="number"&&ctx.target!=="draft-04")if(exclusiveMaximum<=maximum)delete json.maximum;else delete json.exclusiveMaximum}if(typeof multipleOf==="number")json.multipleOf=multipleOf},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0")json.type="string",json.nullable=!0,json.enum=[null];else json.type="null"},undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json,_params)=>{let def=schema._zod.def,values=getEnumValues(def.entries);if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values},literalProcessor=(schema,ctx,json,_params)=>{let def=schema._zod.def,vals=[];for(let val of def.values)if(val===void 0){if(ctx.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof val==="bigint")if(ctx.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else vals.push(Number(val));else vals.push(val);if(vals.length===0);else if(vals.length===1){let val=vals[0];if(json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.enum=[val];else json.const=val}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}},nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json,_params)=>{let _json=json,pattern=schema._zod.pattern;if(!pattern)throw Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json,_params)=>{let _json=json,file={type:"string",format:"binary",contentEncoding:"binary"},{minimum,maximum,mime}=schema._zod.bag;if(minimum!==void 0)file.minLength=minimum;if(maximum!==void 0)file.maxLength=maximum;if(mime)if(mime.length===1)file.contentMediaType=mime[0],Object.assign(_json,file);else Object.assign(_json,file),_json.anyOf=mime.map((m)=>({contentMediaType:m}));else Object.assign(_json,file)},successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array",json.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})},objectProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object",json.properties={};let shape=def.shape;for(let key in shape)json.properties[key]=process2(shape[key],ctx,{...params,path:[...params.path,"properties",key]});let allKeys=new Set(Object.keys(shape)),requiredKeys=new Set([...allKeys].filter((key)=>{let v=def.shape[key]._zod;if(ctx.io==="input")return v.optin===void 0;else return v.optout===void 0}));if(requiredKeys.size>0)json.required=Array.from(requiredKeys);if(def.catchall?._zod.def.type==="never")json.additionalProperties=!1;else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=!1}else if(def.catchall)json.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive)json.oneOf=options;else json.anyOf=options},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf},tupleProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?process2(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;if(ctx.target==="draft-2020-12"){if(json.prefixItems=prefixItems,rest)json.items=rest}else if(ctx.target==="openapi-3.0"){if(json.items={anyOf:prefixItems},rest)json.items.anyOf.push(rest);if(json.minItems=prefixItems.length,!rest)json.maxItems=prefixItems.length}else if(json.items=prefixItems,rest)json.additionalItems=rest;let{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum},recordProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object";let keyType=def.keyType,patterns=keyType._zod.bag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let pattern of patterns)json.patternProperties[pattern.source]=valueSchema}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12")json.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});json.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values;if(keyValues){let validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0)json.required=validKeyValues}},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=process2(def.innerType,ctx,params),seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0")seen.ref=def.innerType,json.nullable=!0;else json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.default=JSON.parse(JSON.stringify(def.defaultValue))},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io==="input")json._prefault=JSON.parse(JSON.stringify(def.defaultValue))},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,innerType=ctx.io==="input"?def.in._zod.def.type==="transform"?def.out:def.in:def.out;process2(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;process2(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors;var init_json_schema_processors=__esm(()=>{init_to_json_schema();init_util();formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}});class JSONSchemaGenerator{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return process2(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_,...plainResult}=result;return plainResult}}var init_json_schema_generator=__esm(()=>{init_json_schema_processors();init_to_json_schema()});var exports_json_schema={};var init_json_schema=()=>{};var exports_core2={};__export(exports_core2,{version:()=>version,util:()=>exports_util,treeifyError:()=>treeifyError,toJSONSchema:()=>toJSONSchema,toDotPath:()=>toDotPath,safeParseAsync:()=>safeParseAsync,safeParse:()=>safeParse,safeEncodeAsync:()=>safeEncodeAsync,safeEncode:()=>safeEncode,safeDecodeAsync:()=>safeDecodeAsync,safeDecode:()=>safeDecode,registry:()=>registry,regexes:()=>exports_regexes,process:()=>process2,prettifyError:()=>prettifyError,parseAsync:()=>parseAsync,parse:()=>parse,meta:()=>meta,locales:()=>exports_locales,isValidJWT:()=>isValidJWT,isValidBase64URL:()=>isValidBase64URL,isValidBase64:()=>isValidBase64,initializeContext:()=>initializeContext,globalRegistry:()=>globalRegistry,globalConfig:()=>globalConfig,formatError:()=>formatError,flattenError:()=>flattenError,finalize:()=>finalize,extractDefs:()=>extractDefs,encodeAsync:()=>encodeAsync,encode:()=>encode,describe:()=>describe,decodeAsync:()=>decodeAsync,decode:()=>decode,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,config:()=>config,clone:()=>clone,_xor:()=>_xor,_xid:()=>_xid,_void:()=>_void,_uuidv7:()=>_uuidv7,_uuidv6:()=>_uuidv6,_uuidv4:()=>_uuidv4,_uuid:()=>_uuid,_url:()=>_url,_uppercase:()=>_uppercase,_unknown:()=>_unknown,_union:()=>_union,_undefined:()=>_undefined2,_ulid:()=>_ulid,_uint64:()=>_uint64,_uint32:()=>_uint32,_tuple:()=>_tuple,_trim:()=>_trim,_transform:()=>_transform,_toUpperCase:()=>_toUpperCase,_toLowerCase:()=>_toLowerCase,_templateLiteral:()=>_templateLiteral,_symbol:()=>_symbol,_superRefine:()=>_superRefine,_success:()=>_success,_stringbool:()=>_stringbool,_stringFormat:()=>_stringFormat,_string:()=>_string,_startsWith:()=>_startsWith,_slugify:()=>_slugify,_size:()=>_size,_set:()=>_set,_safeParseAsync:()=>_safeParseAsync,_safeParse:()=>_safeParse,_safeEncodeAsync:()=>_safeEncodeAsync,_safeEncode:()=>_safeEncode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeDecode:()=>_safeDecode,_regex:()=>_regex,_refine:()=>_refine,_record:()=>_record,_readonly:()=>_readonly,_property:()=>_property,_promise:()=>_promise,_positive:()=>_positive,_pipe:()=>_pipe,_parseAsync:()=>_parseAsync,_parse:()=>_parse,_overwrite:()=>_overwrite,_optional:()=>_optional,_number:()=>_number,_nullable:()=>_nullable,_null:()=>_null2,_normalize:()=>_normalize,_nonpositive:()=>_nonpositive,_nonoptional:()=>_nonoptional,_nonnegative:()=>_nonnegative,_never:()=>_never,_negative:()=>_negative,_nativeEnum:()=>_nativeEnum,_nanoid:()=>_nanoid,_nan:()=>_nan,_multipleOf:()=>_multipleOf,_minSize:()=>_minSize,_minLength:()=>_minLength,_min:()=>_gte,_mime:()=>_mime,_maxSize:()=>_maxSize,_maxLength:()=>_maxLength,_max:()=>_lte,_map:()=>_map,_mac:()=>_mac,_lte:()=>_lte,_lt:()=>_lt,_lowercase:()=>_lowercase,_literal:()=>_literal,_length:()=>_length,_lazy:()=>_lazy,_ksuid:()=>_ksuid,_jwt:()=>_jwt,_isoTime:()=>_isoTime,_isoDuration:()=>_isoDuration,_isoDateTime:()=>_isoDateTime,_isoDate:()=>_isoDate,_ipv6:()=>_ipv6,_ipv4:()=>_ipv4,_intersection:()=>_intersection,_int64:()=>_int64,_int32:()=>_int32,_int:()=>_int,_includes:()=>_includes,_guid:()=>_guid,_gte:()=>_gte,_gt:()=>_gt,_float64:()=>_float64,_float32:()=>_float32,_file:()=>_file,_enum:()=>_enum,_endsWith:()=>_endsWith,_encodeAsync:()=>_encodeAsync,_encode:()=>_encode,_emoji:()=>_emoji2,_email:()=>_email,_e164:()=>_e164,_discriminatedUnion:()=>_discriminatedUnion,_default:()=>_default,_decodeAsync:()=>_decodeAsync,_decode:()=>_decode,_date:()=>_date,_custom:()=>_custom,_cuid2:()=>_cuid2,_cuid:()=>_cuid,_coercedString:()=>_coercedString,_coercedNumber:()=>_coercedNumber,_coercedDate:()=>_coercedDate,_coercedBoolean:()=>_coercedBoolean,_coercedBigint:()=>_coercedBigint,_cidrv6:()=>_cidrv6,_cidrv4:()=>_cidrv4,_check:()=>_check,_catch:()=>_catch,_boolean:()=>_boolean,_bigint:()=>_bigint,_base64url:()=>_base64url,_base64:()=>_base64,_array:()=>_array,_any:()=>_any,TimePrecision:()=>TimePrecision,NEVER:()=>NEVER,JSONSchemaGenerator:()=>JSONSchemaGenerator,JSONSchema:()=>exports_json_schema,Doc:()=>Doc,$output:()=>$output,$input:()=>$input,$constructor:()=>$constructor,$brand:()=>$brand,$ZodXor:()=>$ZodXor,$ZodXID:()=>$ZodXID,$ZodVoid:()=>$ZodVoid,$ZodUnknown:()=>$ZodUnknown,$ZodUnion:()=>$ZodUnion,$ZodUndefined:()=>$ZodUndefined,$ZodUUID:()=>$ZodUUID,$ZodURL:()=>$ZodURL,$ZodULID:()=>$ZodULID,$ZodType:()=>$ZodType,$ZodTuple:()=>$ZodTuple,$ZodTransform:()=>$ZodTransform,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodSymbol:()=>$ZodSymbol,$ZodSuccess:()=>$ZodSuccess,$ZodStringFormat:()=>$ZodStringFormat,$ZodString:()=>$ZodString,$ZodSet:()=>$ZodSet,$ZodRegistry:()=>$ZodRegistry,$ZodRecord:()=>$ZodRecord,$ZodRealError:()=>$ZodRealError,$ZodReadonly:()=>$ZodReadonly,$ZodPromise:()=>$ZodPromise,$ZodPrefault:()=>$ZodPrefault,$ZodPipe:()=>$ZodPipe,$ZodOptional:()=>$ZodOptional,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodObject:()=>$ZodObject,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodNumber:()=>$ZodNumber,$ZodNullable:()=>$ZodNullable,$ZodNull:()=>$ZodNull,$ZodNonOptional:()=>$ZodNonOptional,$ZodNever:()=>$ZodNever,$ZodNanoID:()=>$ZodNanoID,$ZodNaN:()=>$ZodNaN,$ZodMap:()=>$ZodMap,$ZodMAC:()=>$ZodMAC,$ZodLiteral:()=>$ZodLiteral,$ZodLazy:()=>$ZodLazy,$ZodKSUID:()=>$ZodKSUID,$ZodJWT:()=>$ZodJWT,$ZodIntersection:()=>$ZodIntersection,$ZodISOTime:()=>$ZodISOTime,$ZodISODuration:()=>$ZodISODuration,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODate:()=>$ZodISODate,$ZodIPv6:()=>$ZodIPv6,$ZodIPv4:()=>$ZodIPv4,$ZodGUID:()=>$ZodGUID,$ZodFunction:()=>$ZodFunction,$ZodFile:()=>$ZodFile,$ZodExactOptional:()=>$ZodExactOptional,$ZodError:()=>$ZodError,$ZodEnum:()=>$ZodEnum,$ZodEncodeError:()=>$ZodEncodeError,$ZodEmoji:()=>$ZodEmoji,$ZodEmail:()=>$ZodEmail,$ZodE164:()=>$ZodE164,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodDefault:()=>$ZodDefault,$ZodDate:()=>$ZodDate,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodCustom:()=>$ZodCustom,$ZodCodec:()=>$ZodCodec,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheck:()=>$ZodCheck,$ZodCatch:()=>$ZodCatch,$ZodCUID2:()=>$ZodCUID2,$ZodCUID:()=>$ZodCUID,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodBoolean:()=>$ZodBoolean,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBigInt:()=>$ZodBigInt,$ZodBase64URL:()=>$ZodBase64URL,$ZodBase64:()=>$ZodBase64,$ZodAsyncError:()=>$ZodAsyncError,$ZodArray:()=>$ZodArray,$ZodAny:()=>$ZodAny});var init_core2=__esm(()=>{init_util();init_regexes();init_locales();init_json_schema_processors();init_json_schema_generator();init_json_schema();init_core();init_parse();init_errors();init_schemas();init_checks();init_versions();init_registries();init_api();init_to_json_schema()});var exports_checks2={};__export(exports_checks2,{uppercase:()=>_uppercase,trim:()=>_trim,toUpperCase:()=>_toUpperCase,toLowerCase:()=>_toLowerCase,startsWith:()=>_startsWith,slugify:()=>_slugify,size:()=>_size,regex:()=>_regex,property:()=>_property,positive:()=>_positive,overwrite:()=>_overwrite,normalize:()=>_normalize,nonpositive:()=>_nonpositive,nonnegative:()=>_nonnegative,negative:()=>_negative,multipleOf:()=>_multipleOf,minSize:()=>_minSize,minLength:()=>_minLength,mime:()=>_mime,maxSize:()=>_maxSize,maxLength:()=>_maxLength,lte:()=>_lte,lt:()=>_lt,lowercase:()=>_lowercase,length:()=>_length,includes:()=>_includes,gte:()=>_gte,gt:()=>_gt,endsWith:()=>_endsWith});var init_checks2=__esm(()=>{init_core2()});var exports_iso={};__export(exports_iso,{time:()=>time2,duration:()=>duration2,datetime:()=>datetime2,date:()=>date2,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration;var init_iso=__esm(()=>{init_core2();init_schemas2();ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)})});var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:(mapper)=>formatError(inst,mapper)},flatten:{value:(mapper)=>flattenError(inst,mapper)},addIssue:{value:(issue2)=>{inst.issues.push(issue2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:(issues2)=>{inst.issues.push(...issues2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})},ZodError,ZodRealError;var init_errors2=__esm(()=>{init_core2();init_core2();init_util();ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,{Parent:Error})});var parse3,parseAsync2,safeParse2,safeParseAsync2,encode2,decode2,encodeAsync2,decodeAsync2,safeEncode2,safeDecode2,safeEncodeAsync2,safeDecodeAsync2;var init_parse2=__esm(()=>{init_core2();init_errors2();parse3=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError)});var exports_schemas2={};__export(exports_schemas2,{xor:()=>xor,xid:()=>xid2,void:()=>_void2,uuidv7:()=>uuidv7,uuidv6:()=>uuidv6,uuidv4:()=>uuidv4,uuid:()=>uuid2,url:()=>url,unknown:()=>unknown,union:()=>union,undefined:()=>_undefined3,ulid:()=>ulid2,uint64:()=>uint64,uint32:()=>uint32,tuple:()=>tuple,transform:()=>transform,templateLiteral:()=>templateLiteral,symbol:()=>symbol,superRefine:()=>superRefine,success:()=>success,stringbool:()=>stringbool,stringFormat:()=>stringFormat,string:()=>string2,strictObject:()=>strictObject,set:()=>set,refine:()=>refine,record:()=>record,readonly:()=>readonly,promise:()=>promise,preprocess:()=>preprocess,prefault:()=>prefault,pipe:()=>pipe,partialRecord:()=>partialRecord,optional:()=>optional,object:()=>object,number:()=>number2,nullish:()=>nullish2,nullable:()=>nullable,null:()=>_null3,nonoptional:()=>nonoptional,never:()=>never,nativeEnum:()=>nativeEnum,nanoid:()=>nanoid2,nan:()=>nan,meta:()=>meta2,map:()=>map,mac:()=>mac2,looseRecord:()=>looseRecord,looseObject:()=>looseObject,literal:()=>literal,lazy:()=>lazy,ksuid:()=>ksuid2,keyof:()=>keyof,jwt:()=>jwt,json:()=>json,ipv6:()=>ipv62,ipv4:()=>ipv42,intersection:()=>intersection,int64:()=>int64,int32:()=>int32,int:()=>int,instanceof:()=>_instanceof,httpUrl:()=>httpUrl,hostname:()=>hostname2,hex:()=>hex2,hash:()=>hash,guid:()=>guid2,function:()=>_function,float64:()=>float64,float32:()=>float32,file:()=>file,exactOptional:()=>exactOptional,enum:()=>_enum2,emoji:()=>emoji2,email:()=>email2,e164:()=>e1642,discriminatedUnion:()=>discriminatedUnion,describe:()=>describe2,date:()=>date3,custom:()=>custom,cuid2:()=>cuid22,cuid:()=>cuid3,codec:()=>codec,cidrv6:()=>cidrv62,cidrv4:()=>cidrv42,check:()=>check,catch:()=>_catch2,boolean:()=>boolean2,bigint:()=>bigint2,base64url:()=>base64url2,base64:()=>base642,array:()=>array,any:()=>any,_function:()=>_function,_default:()=>_default2,_ZodString:()=>_ZodString,ZodXor:()=>ZodXor,ZodXID:()=>ZodXID,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodUUID:()=>ZodUUID,ZodURL:()=>ZodURL,ZodULID:()=>ZodULID,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransform:()=>ZodTransform,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodSymbol:()=>ZodSymbol,ZodSuccess:()=>ZodSuccess,ZodStringFormat:()=>ZodStringFormat,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodRecord:()=>ZodRecord,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPrefault:()=>ZodPrefault,ZodPipe:()=>ZodPipe,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumberFormat:()=>ZodNumberFormat,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNonOptional:()=>ZodNonOptional,ZodNever:()=>ZodNever,ZodNanoID:()=>ZodNanoID,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodMAC:()=>ZodMAC,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodKSUID:()=>ZodKSUID,ZodJWT:()=>ZodJWT,ZodIntersection:()=>ZodIntersection,ZodIPv6:()=>ZodIPv6,ZodIPv4:()=>ZodIPv4,ZodGUID:()=>ZodGUID,ZodFunction:()=>ZodFunction,ZodFile:()=>ZodFile,ZodExactOptional:()=>ZodExactOptional,ZodEnum:()=>ZodEnum,ZodEmoji:()=>ZodEmoji,ZodEmail:()=>ZodEmail,ZodE164:()=>ZodE164,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodCustom:()=>ZodCustom,ZodCodec:()=>ZodCodec,ZodCatch:()=>ZodCatch,ZodCUID2:()=>ZodCUID2,ZodCUID:()=>ZodCUID,ZodCIDRv6:()=>ZodCIDRv6,ZodCIDRv4:()=>ZodCIDRv4,ZodBoolean:()=>ZodBoolean,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBigInt:()=>ZodBigInt,ZodBase64URL:()=>ZodBase64URL,ZodBase64:()=>ZodBase64,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny});function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function guid2(params){return _guid(ZodGUID,params)}function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:/^https?$/,hostname:exports_regexes.domain,...exports_util.normalizeParams(params)})}function emoji2(params){return _emoji2(ZodEmoji,params)}function nanoid2(params){return _nanoid(ZodNanoID,params)}function cuid3(params){return _cuid(ZodCUID,params)}function cuid22(params){return _cuid2(ZodCUID2,params)}function ulid2(params){return _ulid(ZodULID,params)}function xid2(params){return _xid(ZodXID,params)}function ksuid2(params){return _ksuid(ZodKSUID,params)}function ipv42(params){return _ipv4(ZodIPv4,params)}function mac2(params){return _mac(ZodMAC,params)}function ipv62(params){return _ipv6(ZodIPv6,params)}function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}function base642(params){return _base64(ZodBase64,params)}function base64url2(params){return _base64url(ZodBase64URL,params)}function e1642(params){return _e164(ZodE164,params)}function jwt(params){return _jwt(ZodJWT,params)}function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",exports_regexes.hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",exports_regexes.hex,_params)}function hash(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=exports_regexes[format];if(!regex)throw Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function bigint2(params){return _bigint(ZodBigInt,params)}function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}function symbol(params){return _symbol(ZodSymbol,params)}function _undefined3(params){return _undefined2(ZodUndefined,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function _void2(params){return _void(ZodVoid,params)}function date3(params){return _date(ZodDate,params)}function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}function object(shape,params){let def={type:"object",shape:shape??{},...exports_util.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...exports_util.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...exports_util.normalizeParams(params)})}function union(options,params){return new ZodUnion({type:"union",options,...exports_util.normalizeParams(params)})}function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...exports_util.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...exports_util.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest;return new ZodTuple({type:"tuple",items,rest:hasRest?_paramsOrRest:null,...exports_util.normalizeParams(params)})}function record(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...exports_util.normalizeParams(params)})}function partialRecord(keyType,valueType,params){let k=clone(keyType);return k._zod.values=void 0,new ZodRecord({type:"record",keyType:k,valueType,...exports_util.normalizeParams(params)})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...exports_util.normalizeParams(params)})}function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...exports_util.normalizeParams(params)})}function set(valueType,params){return new ZodSet({type:"set",valueType,...exports_util.normalizeParams(params)})}function _enum2(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...exports_util.normalizeParams(params)})}function file(params){return _file(ZodFile,params)}function transform(fn2){return new ZodTransform({type:"transform",transform:fn2})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...exports_util.normalizeParams(params)})}function success(innerType){return new ZodSuccess({type:"success",innerType})}function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function nan(params){return _nan(ZodNaN,params)}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...exports_util.normalizeParams(params)})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function promise(innerType){return new ZodPromise({type:"promise",innerType})}function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}function check(fn2){let ch=new $ZodCheck({check:"custom"});return ch._zod.check=fn2,ch}function custom(fn2,_params){return _custom(ZodCustom,fn2??(()=>!0),_params)}function refine(fn2,_params={}){return _refine(ZodCustom,fn2,_params)}function superRefine(fn2){return _superRefine(fn2)}function _instanceof(cls,params={}){let inst=new ZodCustom({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:!0,...exports_util.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=(payload)=>{if(!(payload.value instanceof cls))payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}function json(params){let jsonSchema=lazy(()=>{return union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn2,schema){return pipe(transform(fn2),schema)}var ZodType,_ZodString,ZodString,ZodStringFormat,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodMAC,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodJWT,ZodCustomStringFormat,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodBigIntFormat,ZodSymbol,ZodUndefined,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodVoid,ZodDate,ZodArray,ZodObject,ZodUnion,ZodXor,ZodDiscriminatedUnion,ZodIntersection,ZodTuple,ZodRecord,ZodMap,ZodSet,ZodEnum,ZodLiteral,ZodFile,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodSuccess,ZodCatch,ZodNaN,ZodPipe,ZodCodec,ZodReadonly,ZodTemplateLiteral,ZodLazy,ZodPromise,ZodFunction,ZodCustom,describe2,meta2,stringbool=(...args2)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args2);var init_schemas2=__esm(()=>{init_core2();init_core2();init_json_schema_processors();init_to_json_schema();init_checks2();init_iso();init_parse2();ZodType=$constructor("ZodType",(inst,def)=>{return $ZodType.init(inst,def),Object.assign(inst["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,"input"),output:createStandardJSONSchemaMethod(inst,"output")}}),inst.toJSONSchema=createToJSONSchemaMethod(inst,{}),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.check=(...checks2)=>{return inst.clone(exports_util.mergeDefs(def,{checks:[...def.checks??[],...checks2.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},inst.with=inst.check,inst.clone=(def2,params)=>clone(inst,def2,params),inst.brand=()=>inst,inst.register=(reg,meta2)=>{return reg.add(inst,meta2),inst},inst.parse=(data,params)=>parse3(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse2(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync2(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync2(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode2(inst,data,params),inst.decode=(data,params)=>decode2(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync2(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync2(inst,data,params),inst.safeEncode=(data,params)=>safeEncode2(inst,data,params),inst.safeDecode=(data,params)=>safeDecode2(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync2(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync2(inst,data,params),inst.refine=(check,params)=>inst.check(refine(check,params)),inst.superRefine=(refinement)=>inst.check(superRefine(refinement)),inst.overwrite=(fn2)=>inst.check(_overwrite(fn2)),inst.optional=()=>optional(inst),inst.exactOptional=()=>exactOptional(inst),inst.nullable=()=>nullable(inst),inst.nullish=()=>optional(nullable(inst)),inst.nonoptional=(params)=>nonoptional(inst,params),inst.array=()=>array(inst),inst.or=(arg)=>union([inst,arg]),inst.and=(arg)=>intersection(inst,arg),inst.transform=(tx)=>pipe(inst,transform(tx)),inst.default=(def2)=>_default2(inst,def2),inst.prefault=(def2)=>prefault(inst,def2),inst.catch=(params)=>_catch2(inst,params),inst.pipe=(target)=>pipe(inst,target),inst.readonly=()=>readonly(inst),inst.describe=(description)=>{let cl=inst.clone();return globalRegistry.add(cl,{description}),cl},Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst.meta=(...args2)=>{if(args2.length===0)return globalRegistry.get(inst);let cl=inst.clone();return globalRegistry.add(cl,args2[0]),cl},inst.isOptional=()=>inst.safeParse(void 0).success,inst.isNullable=()=>inst.safeParse(null).success,inst.apply=(fn2)=>fn2(inst),inst}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,inst.regex=(...args2)=>inst.check(_regex(...args2)),inst.includes=(...args2)=>inst.check(_includes(...args2)),inst.startsWith=(...args2)=>inst.check(_startsWith(...args2)),inst.endsWith=(...args2)=>inst.check(_endsWith(...args2)),inst.min=(...args2)=>inst.check(_minLength(...args2)),inst.max=(...args2)=>inst.check(_maxLength(...args2)),inst.length=(...args2)=>inst.check(_length(...args2)),inst.nonempty=(...args2)=>inst.check(_minLength(1,...args2)),inst.lowercase=(params)=>inst.check(_lowercase(params)),inst.uppercase=(params)=>inst.check(_uppercase(params)),inst.trim=()=>inst.check(_trim()),inst.normalize=(...args2)=>inst.check(_normalize(...args2)),inst.toLowerCase=()=>inst.check(_toLowerCase()),inst.toUpperCase=()=>inst.check(_toUpperCase()),inst.slugify=()=>inst.check(_slugify())}),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=(params)=>inst.check(_email(ZodEmail,params)),inst.url=(params)=>inst.check(_url(ZodURL,params)),inst.jwt=(params)=>inst.check(_jwt(ZodJWT,params)),inst.emoji=(params)=>inst.check(_emoji2(ZodEmoji,params)),inst.guid=(params)=>inst.check(_guid(ZodGUID,params)),inst.uuid=(params)=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=(params)=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=(params)=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=(params)=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=(params)=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=(params)=>inst.check(_guid(ZodGUID,params)),inst.cuid=(params)=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=(params)=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=(params)=>inst.check(_ulid(ZodULID,params)),inst.base64=(params)=>inst.check(_base64(ZodBase64,params)),inst.base64url=(params)=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=(params)=>inst.check(_xid(ZodXID,params)),inst.ksuid=(params)=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=(params)=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=(params)=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=(params)=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=(params)=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=(params)=>inst.check(_e164(ZodE164,params)),inst.datetime=(params)=>inst.check(datetime2(params)),inst.date=(params)=>inst.check(date2(params)),inst.time=(params)=>inst.check(time2(params)),inst.duration=(params)=>inst.check(duration2(params))});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.int=(params)=>inst.check(int(params)),inst.safe=(params)=>inst.check(int(params)),inst.positive=(params)=>inst.check(_gt(0,params)),inst.nonnegative=(params)=>inst.check(_gte(0,params)),inst.negative=(params)=>inst.check(_lt(0,params)),inst.nonpositive=(params)=>inst.check(_lte(0,params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params)),inst.step=(value,params)=>inst.check(_multipleOf(value,params)),inst.finite=()=>inst;let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??0.5),inst.isFinite=!0,inst.format=bag.format??null});ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>bigintProcessor(inst,ctx,json,params),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.positive=(params)=>inst.check(_gt(BigInt(0),params)),inst.negative=(params)=>inst.check(_lt(BigInt(0),params)),inst.nonpositive=(params)=>inst.check(_lte(BigInt(0),params)),inst.nonnegative=(params)=>inst.check(_gte(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null});ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>symbolProcessor(inst,ctx,json,params)});ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>undefinedProcessor(inst,ctx,json,params)});ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>anyProcessor(inst,ctx,json,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>voidProcessor(inst,ctx,json,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>dateProcessor(inst,ctx,json,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null});ZodArray=$constructor("ZodArray",(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element,inst.min=(minLength,params)=>inst.check(_minLength(minLength,params)),inst.nonempty=(params)=>inst.check(_minLength(1,params)),inst.max=(maxLength,params)=>inst.check(_maxLength(maxLength,params)),inst.length=(len,params)=>inst.check(_length(len,params)),inst.unwrap=()=>inst.element});ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),exports_util.defineLazy(inst,"shape",()=>{return def.shape}),inst.keyof=()=>_enum2(Object.keys(inst._zod.def.shape)),inst.catchall=(catchall)=>inst.clone({...inst._zod.def,catchall}),inst.passthrough=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.loose=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.strict=()=>inst.clone({...inst._zod.def,catchall:never()}),inst.strip=()=>inst.clone({...inst._zod.def,catchall:void 0}),inst.extend=(incoming)=>{return exports_util.extend(inst,incoming)},inst.safeExtend=(incoming)=>{return exports_util.safeExtend(inst,incoming)},inst.merge=(other)=>exports_util.merge(inst,other),inst.pick=(mask)=>exports_util.pick(inst,mask),inst.omit=(mask)=>exports_util.omit(inst,mask),inst.partial=(...args2)=>exports_util.partial(ZodOptional,inst,args2[0]),inst.required=(...args2)=>exports_util.required(ZodNonOptional,inst,args2[0])});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});ZodTuple=$constructor("ZodTuple",(inst,def)=>{$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>tupleProcessor(inst,ctx,json,params),inst.rest=(rest)=>inst.clone({...inst._zod.def,rest})});ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodMap=$constructor("ZodMap",(inst,def)=>{$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>mapProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args2)=>inst.check(_minSize(...args2)),inst.nonempty=(params)=>inst.check(_minSize(1,params)),inst.max=(...args2)=>inst.check(_maxSize(...args2)),inst.size=(...args2)=>inst.check(_size(...args2))});ZodSet=$constructor("ZodSet",(inst,def)=>{$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>setProcessor(inst,ctx,json,params),inst.min=(...args2)=>inst.check(_minSize(...args2)),inst.nonempty=(params)=>inst.check(_minSize(1,params)),inst.max=(...args2)=>inst.check(_maxSize(...args2)),inst.size=(...args2)=>inst.check(_size(...args2))});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>fileProcessor(inst,ctx,json,params),inst.min=(size,params)=>inst.check(_minSize(size,params)),inst.max=(size,params)=>inst.check(_maxSize(size,params)),inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});ZodTransform=$constructor("ZodTransform",(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=(issue2)=>{if(typeof issue2==="string")payload.issues.push(exports_util.issue(issue2,payload.value,def));else{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(exports_util.issue(_issue))}};let output=def.transform(payload.value,payload);if(output instanceof Promise)return output.then((output2)=>{return payload.value=output2,payload});return payload.value=output,payload}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>successProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nanProcessor(inst,ctx,json,params)});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>templateLiteralProcessor(inst,ctx,json,params)});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>lazyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.getter()});ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>promiseProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>functionProcessor(inst,ctx,json,params)});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});describe2=describe,meta2=meta});function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodIssueCode,ZodFirstPartyTypeKind;var init_compat=__esm(()=>{init_core2();ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(ZodFirstPartyTypeKind2){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}))});function detectVersion(schema,defaultTarget){let $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if($schema==="http://json-schema.org/draft-07/schema#")return"draft-7";if($schema==="http://json-schema.org/draft-04/schema#")return"draft-4";return defaultTarget??"draft-2020-12"}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let path=ref.slice(1).split("/").filter(Boolean);if(path.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){let key=path[1];if(!key||!ctx.defs[key])throw Error(`Reference not found: ${ref}`);return ctx.defs[key]}throw Error(`Reference not found: ${ref}`)}function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0)return z.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z.lazy(()=>{if(!ctx.refs.has(refPath))throw Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z.null();if(enumValues.length===0)return z.never();if(enumValues.length===1)return z.literal(enumValues[0]);if(enumValues.every((v)=>typeof v==="string"))return z.enum(enumValues);let literalSchemas=enumValues.map((v)=>z.literal(v));if(literalSchemas.length<2)return literalSchemas[0];return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z.literal(schema.const);let type=schema.type;if(Array.isArray(type)){let typeSchemas=type.map((t)=>{let typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0)return z.never();if(typeSchemas.length===1)return typeSchemas[0];return z.union(typeSchemas)}if(!type)return z.any();let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){let format=schema.format;if(format==="email")stringSchema=stringSchema.check(z.email());else if(format==="uri"||format==="uri-reference")stringSchema=stringSchema.check(z.url());else if(format==="uuid"||format==="guid")stringSchema=stringSchema.check(z.uuid());else if(format==="date-time")stringSchema=stringSchema.check(z.iso.datetime());else if(format==="date")stringSchema=stringSchema.check(z.iso.date());else if(format==="time")stringSchema=stringSchema.check(z.iso.time());else if(format==="duration")stringSchema=stringSchema.check(z.iso.duration());else if(format==="ipv4")stringSchema=stringSchema.check(z.ipv4());else if(format==="ipv6")stringSchema=stringSchema.check(z.ipv6());else if(format==="mac")stringSchema=stringSchema.check(z.mac());else if(format==="cidr")stringSchema=stringSchema.check(z.cidrv4());else if(format==="cidr-v6")stringSchema=stringSchema.check(z.cidrv6());else if(format==="base64")stringSchema=stringSchema.check(z.base64());else if(format==="base64url")stringSchema=stringSchema.check(z.base64url());else if(format==="e164")stringSchema=stringSchema.check(z.e164());else if(format==="jwt")stringSchema=stringSchema.check(z.jwt());else if(format==="emoji")stringSchema=stringSchema.check(z.emoji());else if(format==="nanoid")stringSchema=stringSchema.check(z.nanoid());else if(format==="cuid")stringSchema=stringSchema.check(z.cuid());else if(format==="cuid2")stringSchema=stringSchema.check(z.cuid2());else if(format==="ulid")stringSchema=stringSchema.check(z.ulid());else if(format==="xid")stringSchema=stringSchema.check(z.xid());else if(format==="ksuid")stringSchema=stringSchema.check(z.ksuid())}if(typeof schema.minLength==="number")stringSchema=stringSchema.min(schema.minLength);if(typeof schema.maxLength==="number")stringSchema=stringSchema.max(schema.maxLength);if(schema.pattern)stringSchema=stringSchema.regex(new RegExp(schema.pattern));zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number")numberSchema=numberSchema.min(schema.minimum);if(typeof schema.maximum==="number")numberSchema=numberSchema.max(schema.maximum);if(typeof schema.exclusiveMinimum==="number")numberSchema=numberSchema.gt(schema.exclusiveMinimum);else if(schema.exclusiveMinimum===!0&&typeof schema.minimum==="number")numberSchema=numberSchema.gt(schema.minimum);if(typeof schema.exclusiveMaximum==="number")numberSchema=numberSchema.lt(schema.exclusiveMaximum);else if(schema.exclusiveMaximum===!0&&typeof schema.maximum==="number")numberSchema=numberSchema.lt(schema.maximum);if(typeof schema.multipleOf==="number")numberSchema=numberSchema.multipleOf(schema.multipleOf);zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{let shape={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]);for(let[key,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);shape[key]=requiredSet.has(key)?propZodSchema:propZodSchema.optional()}if(schema.propertyNames){let keySchema=convertSchema(schema.propertyNames,ctx),valueSchema=schema.additionalProperties&&typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):z.any();if(Object.keys(shape).length===0){zodSchema=z.record(keySchema,valueSchema);break}let objectSchema2=z.object(shape).passthrough(),recordSchema=z.looseRecord(keySchema,valueSchema);zodSchema=z.intersection(objectSchema2,recordSchema);break}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape).length>0)schemasToIntersect.push(z.object(shape).passthrough());if(schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++)result=z.intersection(result,schemasToIntersect[i]);zodSchema=result}break}let objectSchema=z.object(shape);if(schema.additionalProperties===!1)zodSchema=objectSchema.strict();else if(typeof schema.additionalProperties==="object")zodSchema=objectSchema.catchall(convertSchema(schema.additionalProperties,ctx));else zodSchema=objectSchema.passthrough();break}case"array":{let{prefixItems,items}=schema;if(prefixItems&&Array.isArray(prefixItems)){let tupleItems=prefixItems.map((item)=>convertSchema(item,ctx)),rest=items&&typeof items==="object"&&!Array.isArray(items)?convertSchema(items,ctx):void 0;if(rest)zodSchema=z.tuple(tupleItems).rest(rest);else zodSchema=z.tuple(tupleItems);if(typeof schema.minItems==="number")zodSchema=zodSchema.check(z.minLength(schema.minItems));if(typeof schema.maxItems==="number")zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}else if(Array.isArray(items)){let tupleItems=items.map((item)=>convertSchema(item,ctx)),rest=schema.additionalItems&&typeof schema.additionalItems==="object"?convertSchema(schema.additionalItems,ctx):void 0;if(rest)zodSchema=z.tuple(tupleItems).rest(rest);else zodSchema=z.tuple(tupleItems);if(typeof schema.minItems==="number")zodSchema=zodSchema.check(z.minLength(schema.minItems));if(typeof schema.maxItems==="number")zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z.array(element);if(typeof schema.minItems==="number")arraySchema=arraySchema.min(schema.minItems);if(typeof schema.maxItems==="number")arraySchema=arraySchema.max(schema.maxItems);zodSchema=arraySchema}else zodSchema=z.array(z.any());break}default:throw Error(`Unsupported type: ${type}`)}if(schema.description)zodSchema=zodSchema.describe(schema.description);if(schema.default!==void 0)zodSchema=zodSchema.default(schema.default);return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean")return schema?z.any():z.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map((s)=>convertSchema(s,ctx)),anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map((s)=>convertSchema(s,ctx)),oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++)result=z.intersection(result,convertSchema(schema.allOf[i],ctx));baseSchema=result}if(schema.nullable===!0&&ctx.version==="openapi-3.0")baseSchema=z.nullable(baseSchema);if(schema.readOnly===!0)baseSchema=z.readonly(baseSchema);let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key of coreMetadataKeys)if(key in schema)extraMeta[key]=schema[key];let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key of contentMetadataKeys)if(key in schema)extraMeta[key]=schema[key];for(let key of Object.keys(schema))if(!RECOGNIZED_KEYS.has(key))extraMeta[key]=schema[key];if(Object.keys(extraMeta).length>0)ctx.registry.add(baseSchema,extraMeta);return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean")return schema?z.any():z.never();let version2=detectVersion(schema,params?.defaultTarget),defs=schema.$defs||schema.definitions||{},ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:schema,registry:params?.registry??globalRegistry};return convertSchema(schema,ctx)}var z,RECOGNIZED_KEYS;var init_from_json_schema=__esm(()=>{init_registries();init_checks2();init_iso();init_schemas2();z={...exports_schemas2,...exports_checks2,iso:exports_iso},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var exports_coerce={};__export(exports_coerce,{string:()=>string3,number:()=>number3,date:()=>date4,boolean:()=>boolean3,bigint:()=>bigint3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm(()=>{init_core2();init_schemas2()});var exports_external={};__export(exports_external,{xor:()=>xor,xid:()=>xid2,void:()=>_void2,uuidv7:()=>uuidv7,uuidv6:()=>uuidv6,uuidv4:()=>uuidv4,uuid:()=>uuid2,util:()=>exports_util,url:()=>url,uppercase:()=>_uppercase,unknown:()=>unknown,union:()=>union,undefined:()=>_undefined3,ulid:()=>ulid2,uint64:()=>uint64,uint32:()=>uint32,tuple:()=>tuple,trim:()=>_trim,treeifyError:()=>treeifyError,transform:()=>transform,toUpperCase:()=>_toUpperCase,toLowerCase:()=>_toLowerCase,toJSONSchema:()=>toJSONSchema,templateLiteral:()=>templateLiteral,symbol:()=>symbol,superRefine:()=>superRefine,success:()=>success,stringbool:()=>stringbool,stringFormat:()=>stringFormat,string:()=>string2,strictObject:()=>strictObject,startsWith:()=>_startsWith,slugify:()=>_slugify,size:()=>_size,setErrorMap:()=>setErrorMap,set:()=>set,safeParseAsync:()=>safeParseAsync2,safeParse:()=>safeParse2,safeEncodeAsync:()=>safeEncodeAsync2,safeEncode:()=>safeEncode2,safeDecodeAsync:()=>safeDecodeAsync2,safeDecode:()=>safeDecode2,registry:()=>registry,regexes:()=>exports_regexes,regex:()=>_regex,refine:()=>refine,record:()=>record,readonly:()=>readonly,property:()=>_property,promise:()=>promise,prettifyError:()=>prettifyError,preprocess:()=>preprocess,prefault:()=>prefault,positive:()=>_positive,pipe:()=>pipe,partialRecord:()=>partialRecord,parseAsync:()=>parseAsync2,parse:()=>parse3,overwrite:()=>_overwrite,optional:()=>optional,object:()=>object,number:()=>number2,nullish:()=>nullish2,nullable:()=>nullable,null:()=>_null3,normalize:()=>_normalize,nonpositive:()=>_nonpositive,nonoptional:()=>nonoptional,nonnegative:()=>_nonnegative,never:()=>never,negative:()=>_negative,nativeEnum:()=>nativeEnum,nanoid:()=>nanoid2,nan:()=>nan,multipleOf:()=>_multipleOf,minSize:()=>_minSize,minLength:()=>_minLength,mime:()=>_mime,meta:()=>meta2,maxSize:()=>_maxSize,maxLength:()=>_maxLength,map:()=>map,mac:()=>mac2,lte:()=>_lte,lt:()=>_lt,lowercase:()=>_lowercase,looseRecord:()=>looseRecord,looseObject:()=>looseObject,locales:()=>exports_locales,literal:()=>literal,length:()=>_length,lazy:()=>lazy,ksuid:()=>ksuid2,keyof:()=>keyof,jwt:()=>jwt,json:()=>json,iso:()=>exports_iso,ipv6:()=>ipv62,ipv4:()=>ipv42,intersection:()=>intersection,int64:()=>int64,int32:()=>int32,int:()=>int,instanceof:()=>_instanceof,includes:()=>_includes,httpUrl:()=>httpUrl,hostname:()=>hostname2,hex:()=>hex2,hash:()=>hash,guid:()=>guid2,gte:()=>_gte,gt:()=>_gt,globalRegistry:()=>globalRegistry,getErrorMap:()=>getErrorMap,function:()=>_function,fromJSONSchema:()=>fromJSONSchema,formatError:()=>formatError,float64:()=>float64,float32:()=>float32,flattenError:()=>flattenError,file:()=>file,exactOptional:()=>exactOptional,enum:()=>_enum2,endsWith:()=>_endsWith,encodeAsync:()=>encodeAsync2,encode:()=>encode2,emoji:()=>emoji2,email:()=>email2,e164:()=>e1642,discriminatedUnion:()=>discriminatedUnion,describe:()=>describe2,decodeAsync:()=>decodeAsync2,decode:()=>decode2,date:()=>date3,custom:()=>custom,cuid2:()=>cuid22,cuid:()=>cuid3,core:()=>exports_core2,config:()=>config,coerce:()=>exports_coerce,codec:()=>codec,clone:()=>clone,cidrv6:()=>cidrv62,cidrv4:()=>cidrv42,check:()=>check,catch:()=>_catch2,boolean:()=>boolean2,bigint:()=>bigint2,base64url:()=>base64url2,base64:()=>base642,array:()=>array,any:()=>any,_function:()=>_function,_default:()=>_default2,_ZodString:()=>_ZodString,ZodXor:()=>ZodXor,ZodXID:()=>ZodXID,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodUUID:()=>ZodUUID,ZodURL:()=>ZodURL,ZodULID:()=>ZodULID,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransform:()=>ZodTransform,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodSymbol:()=>ZodSymbol,ZodSuccess:()=>ZodSuccess,ZodStringFormat:()=>ZodStringFormat,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodRecord:()=>ZodRecord,ZodRealError:()=>ZodRealError,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPrefault:()=>ZodPrefault,ZodPipe:()=>ZodPipe,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumberFormat:()=>ZodNumberFormat,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNonOptional:()=>ZodNonOptional,ZodNever:()=>ZodNever,ZodNanoID:()=>ZodNanoID,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodMAC:()=>ZodMAC,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodKSUID:()=>ZodKSUID,ZodJWT:()=>ZodJWT,ZodIssueCode:()=>ZodIssueCode,ZodIntersection:()=>ZodIntersection,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate,ZodIPv6:()=>ZodIPv6,ZodIPv4:()=>ZodIPv4,ZodGUID:()=>ZodGUID,ZodFunction:()=>ZodFunction,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFile:()=>ZodFile,ZodExactOptional:()=>ZodExactOptional,ZodError:()=>ZodError,ZodEnum:()=>ZodEnum,ZodEmoji:()=>ZodEmoji,ZodEmail:()=>ZodEmail,ZodE164:()=>ZodE164,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodCustom:()=>ZodCustom,ZodCodec:()=>ZodCodec,ZodCatch:()=>ZodCatch,ZodCUID2:()=>ZodCUID2,ZodCUID:()=>ZodCUID,ZodCIDRv6:()=>ZodCIDRv6,ZodCIDRv4:()=>ZodCIDRv4,ZodBoolean:()=>ZodBoolean,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBigInt:()=>ZodBigInt,ZodBase64URL:()=>ZodBase64URL,ZodBase64:()=>ZodBase64,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny,TimePrecision:()=>TimePrecision,NEVER:()=>NEVER,$output:()=>$output,$input:()=>$input,$brand:()=>$brand});var init_external=__esm(()=>{init_core2();init_core2();init_en();init_core2();init_json_schema_processors();init_from_json_schema();init_locales();init_iso();init_iso();init_coerce();init_schemas2();init_checks2();init_errors2();init_parse2();init_compat();config(en_default())});var init_zod=__esm(()=>{init_external();init_external()});var EVIDENCE_MAX_JSON_BYTES=512000,EVIDENCE_MAX_PATCH_BYTES=5242880,EVIDENCE_MAX_TASK_BYTES=20971520,EvidenceTypeSchema,EvidenceVerdictSchema,BaseEvidenceSchema,ReviewEvidenceSchema,TestEvidenceSchema,DiffEvidenceSchema,ApprovalEvidenceSchema,NoteEvidenceSchema,RetrospectiveEvidenceSchema,SyntaxEvidenceSchema,PlaceholderEvidenceSchema,SastFindingSchema,SastEvidenceSchema,SbomEvidenceSchema,BuildEvidenceSchema,QualityBudgetEvidenceSchema,SecretscanEvidenceSchema,GateEvidenceBaseSchema,MutationGateEvidenceSchema,DriftVerificationEvidenceSchema,HallucinationVerificationEvidenceSchema,EvidenceSchema,EvidenceBundleSchema;var init_evidence_schema=__esm(()=>{init_zod();EvidenceTypeSchema=exports_external.enum(["review","test","diff","approval","note","retrospective","syntax","placeholder","sast","sbom","build","quality_budget","secretscan","mutation-gate","drift-verification","hallucination-verification"]),EvidenceVerdictSchema=exports_external.enum(["pass","fail","warn","skip","approved","rejected","info"]),BaseEvidenceSchema=exports_external.object({task_id:exports_external.string().min(1),type:EvidenceTypeSchema,timestamp:exports_external.string().datetime(),agent:exports_external.string().min(1),verdict:EvidenceVerdictSchema,summary:exports_external.string().min(1),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}),ReviewEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("review"),risk:exports_external.enum(["low","medium","high","critical"]),issues:exports_external.array(exports_external.object({severity:exports_external.enum(["error","warning","info"]),message:exports_external.string().min(1),file:exports_external.string().optional(),line:exports_external.number().int().optional()})).default([])}),TestEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("test"),tests_passed:exports_external.number().int().min(0),tests_failed:exports_external.number().int().min(0),test_file:exports_external.string().optional(),failures:exports_external.array(exports_external.object({name:exports_external.string().min(1),message:exports_external.string().min(1)})).default([])}),DiffEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("diff"),files_changed:exports_external.array(exports_external.string()).default([]),additions:exports_external.number().int().min(0).default(0),deletions:exports_external.number().int().min(0).default(0),patch_path:exports_external.string().optional()}),ApprovalEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("approval")}),NoteEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("note")}),RetrospectiveEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("retrospective"),phase_number:exports_external.number().int().min(1).max(99),total_tool_calls:exports_external.number().int().min(0).max(9999),coder_revisions:exports_external.number().int().min(0).max(999),reviewer_rejections:exports_external.number().int().min(0).max(999),loop_detections:exports_external.number().int().min(0).max(9999).optional(),circuit_breaker_trips:exports_external.number().int().min(0).max(9999).optional(),test_failures:exports_external.number().int().min(0).max(9999),security_findings:exports_external.number().int().min(0).max(999),integration_issues:exports_external.number().int().min(0).max(999),task_count:exports_external.number().int().min(1).max(9999),task_complexity:exports_external.enum(["trivial","simple","moderate","complex"]),top_rejection_reasons:exports_external.array(exports_external.string()).default([]),lessons_learned:exports_external.array(exports_external.string()).max(5).default([]),user_directives:exports_external.array(exports_external.object({directive:exports_external.string().min(1),category:exports_external.enum(["tooling","code_style","architecture","process","other"]),scope:exports_external.enum(["session","project","global"])})).default([]),approaches_tried:exports_external.array(exports_external.object({approach:exports_external.string().min(1),result:exports_external.enum(["success","failure","partial"]),abandoned_reason:exports_external.string().optional()})).max(10).default([]),error_taxonomy:exports_external.array(exports_external.enum(["planning_error","interface_mismatch","logic_error","scope_creep","gate_evasion"])).default([])}),SyntaxEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("syntax"),files_checked:exports_external.number().int(),files_failed:exports_external.number().int(),skipped_count:exports_external.number().int().default(0),files:exports_external.array(exports_external.object({path:exports_external.string(),language:exports_external.string(),ok:exports_external.boolean(),errors:exports_external.array(exports_external.object({line:exports_external.number().int(),column:exports_external.number().int(),message:exports_external.string()})).default([]),skipped_reason:exports_external.string().optional()})).default([])}),PlaceholderEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("placeholder"),findings:exports_external.array(exports_external.object({path:exports_external.string(),line:exports_external.number().int(),kind:exports_external.enum(["comment","string","function_body","other"]),excerpt:exports_external.string(),rule_id:exports_external.string()})).default([]),files_scanned:exports_external.number().int(),files_with_findings:exports_external.number().int(),findings_count:exports_external.number().int()}),SastFindingSchema=exports_external.object({rule_id:exports_external.string(),severity:exports_external.enum(["critical","high","medium","low"]),message:exports_external.string(),location:exports_external.object({file:exports_external.string(),line:exports_external.number().int(),column:exports_external.number().int().optional()}),remediation:exports_external.string().optional()}),SastEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("sast"),findings:exports_external.array(SastFindingSchema).default([]),engine:exports_external.enum(["tier_a","tier_a+tier_b"]),files_scanned:exports_external.number().int(),findings_count:exports_external.number().int(),findings_by_severity:exports_external.object({critical:exports_external.number().int(),high:exports_external.number().int(),medium:exports_external.number().int(),low:exports_external.number().int()}),new_findings:exports_external.array(SastFindingSchema).optional(),pre_existing_findings:exports_external.array(SastFindingSchema).optional(),baseline_used:exports_external.boolean().optional()}),SbomEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("sbom"),components:exports_external.array(exports_external.object({name:exports_external.string(),version:exports_external.string(),type:exports_external.enum(["library","framework","application"]),purl:exports_external.string().optional(),license:exports_external.string().optional()})).default([]),metadata:exports_external.object({timestamp:exports_external.string().datetime(),tool:exports_external.string(),tool_version:exports_external.string()}),files:exports_external.array(exports_external.string()),components_count:exports_external.number().int(),output_path:exports_external.string()}),BuildEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("build"),runs:exports_external.array(exports_external.object({kind:exports_external.enum(["build","typecheck","test"]),command:exports_external.string(),cwd:exports_external.string(),exit_code:exports_external.number().int(),duration_ms:exports_external.number().int(),stdout_tail:exports_external.string(),stderr_tail:exports_external.string()})).default([]),files_scanned:exports_external.number().int(),runs_count:exports_external.number().int(),failed_count:exports_external.number().int(),skipped_reason:exports_external.string().optional()}),QualityBudgetEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("quality_budget"),metrics:exports_external.object({complexity_delta:exports_external.number(),public_api_delta:exports_external.number(),duplication_ratio:exports_external.number(),test_to_code_ratio:exports_external.number()}),thresholds:exports_external.object({max_complexity_delta:exports_external.number(),max_public_api_delta:exports_external.number(),max_duplication_ratio:exports_external.number(),min_test_to_code_ratio:exports_external.number()}),violations:exports_external.array(exports_external.object({type:exports_external.enum(["complexity","api","duplication","test_ratio"]),message:exports_external.string(),severity:exports_external.enum(["error","warning"]),files:exports_external.array(exports_external.string())})).default([]),files_analyzed:exports_external.array(exports_external.string())}),SecretscanEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("secretscan"),findings_count:exports_external.number().int().min(0).default(0),scan_directory:exports_external.string().optional(),files_scanned:exports_external.number().int().min(0).default(0),skipped_files:exports_external.number().int().min(0).default(0),incomplete_files:exports_external.number().int().min(0),incomplete_paths:exports_external.array(exports_external.object({path:exports_external.string(),reason:exports_external.string()}))}),GateEvidenceBaseSchema=exports_external.object({task_id:exports_external.string().optional(),agent:exports_external.string().optional(),timestamp:exports_external.string().datetime(),summary:exports_external.string().min(1),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}),MutationGateEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("mutation-gate"),verdict:exports_external.enum(["pass","warn","fail","skip"]),killRate:exports_external.number().min(0).max(1).optional(),adjustedKillRate:exports_external.number().min(0).max(1).optional(),survivedMutants:exports_external.string().optional()}),DriftVerificationEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("drift-verification"),verdict:exports_external.enum(["approved","rejected"]),requirementCoverage:exports_external.string().optional()}),HallucinationVerificationEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("hallucination-verification"),verdict:exports_external.enum(["approved","rejected"]),findings:exports_external.string().optional()}),EvidenceSchema=exports_external.discriminatedUnion("type",[ReviewEvidenceSchema,TestEvidenceSchema,DiffEvidenceSchema,ApprovalEvidenceSchema,NoteEvidenceSchema,RetrospectiveEvidenceSchema,SyntaxEvidenceSchema,PlaceholderEvidenceSchema,SastEvidenceSchema,SbomEvidenceSchema,BuildEvidenceSchema,QualityBudgetEvidenceSchema,SecretscanEvidenceSchema,MutationGateEvidenceSchema,DriftVerificationEvidenceSchema,HallucinationVerificationEvidenceSchema]),EvidenceBundleSchema=exports_external.object({schema_version:exports_external.literal("1.0.0"),task_id:exports_external.string().min(1),entries:exports_external.array(EvidenceSchema).default([]),created_at:exports_external.string().datetime(),updated_at:exports_external.string().datetime()})});function isDebug(){return process.env.OPENCODE_SWARM_DEBUG==="1"}function log(message,data){if(!isDebug())return;let timestamp=new Date().toISOString();if(data!==void 0)console.log(`[opencode-swarm ${timestamp}] ${message}`,data);else console.log(`[opencode-swarm ${timestamp}] ${message}`)}function warn(message,data){if(!isDebug())return;let timestamp=new Date().toISOString();if(data!==void 0)console.warn(`[opencode-swarm ${timestamp}] WARN: ${message}`,data);else console.warn(`[opencode-swarm ${timestamp}] WARN: ${message}`)}function criticalWarn(message,data){let timestamp=new Date().toISOString();if(data!==void 0)console.warn(`[opencode-swarm ${timestamp}] CRITICAL-WARN: ${message}`,data);else console.warn(`[opencode-swarm ${timestamp}] CRITICAL-WARN: ${message}`)}function error48(message,data){let timestamp=new Date().toISOString();if(data!==void 0)console.error(`[opencode-swarm ${timestamp}] ERROR: ${message}`,data);else console.error(`[opencode-swarm ${timestamp}] ERROR: ${message}`)}var init_logger=()=>{};function sanitizeBufferedLine(s){return s.replace(/\s+/g," ").replace(CONTROL_CHARS_RE,"").replace(/\s+/g," ").trim()}function addDeferredWarning(warning){let sanitized=sanitizeBufferedLine(warning);if(deferredWarnings.length<MAX_DEFERRED_WARNINGS-1){deferredWarnings.push(sanitized);return}if(!deferredWarningsTruncated)deferredWarnings.push(`[opencode-swarm] ${MAX_DEFERRED_WARNINGS-1} deferred warnings buffered; additional advisories were dropped (cap reached). Run with OPENCODE_SWARM_DEBUG=1 to see all advisories in the debug log.`),deferredWarningsTruncated=!0}function renderAdvisoryDetail(data){if(data===void 0||data===null)return"";let raw;if(typeof data==="string")raw=data;else if(data instanceof Error)raw=data.message;else if(Array.isArray(data)&&data.every((d)=>typeof d==="string"))raw=data.join("; ");else try{raw=JSON.stringify(data)??String(data)}catch{raw=String(data)}let collapsed=sanitizeBufferedLine(raw);if(collapsed==="")return"";return collapsed.length>MAX_ADVISORY_DETAIL_CHARS?`${collapsed.slice(0,MAX_ADVISORY_DETAIL_CHARS-1)}…`:collapsed}function advisoryWarn(message,data){let detail=renderAdvisoryDetail(data);addDeferredWarning(detail?`${message} ${detail}`:message),log(message,data)}function getDeferredWarnings(){return[...deferredWarnings]}function clearDeferredWarnings(){deferredWarnings.length=0,deferredWarningsTruncated=!1}var deferredWarnings,MAX_DEFERRED_WARNINGS=50,deferredWarningsTruncated=!1,CONTROL_CHARS_RE,MAX_ADVISORY_DETAIL_CHARS=600;var init_warning_buffer=__esm(()=>{init_logger();deferredWarnings=[],CONTROL_CHARS_RE=/[\x00-\x1F\x7F-\x9F]/g});function dotted(p){return p.map(String).join(".")}function deepClone(obj){try{return structuredClone(obj)}catch{return JSON.parse(JSON.stringify(obj))}}function countNodes(obj){if(obj===null||obj===void 0)return 0;if(typeof obj!=="object")return 1;if(Array.isArray(obj)){let count2=0;for(let el of obj)count2+=1+countNodes(el);return count2}let count=0;for(let _key of Object.keys(obj))count+=1;for(let val of Object.values(obj))count+=countNodes(val);return count}function selectDeepest(paths){let sorted=[...paths].sort((a,b)=>b.length-a.length),kept=[];for(let p of sorted)if(!kept.some((q)=>q.length>p.length&&startsWith(q,p)))kept.push(p);return kept}function startsWith(path,prefix){if(prefix.length>path.length)return!1;for(let i=0;i<prefix.length;i++)if(path[i]!==prefix[i])return!1;return!0}function removeAtPath(obj,path){if(path.length===0)return!1;let node=obj;for(let i=0;i<path.length-1;i++){if(node===null||node===void 0||typeof node!=="object")return!1;let key=path[i];if(Array.isArray(node)){let idx=Number(key);if(!Number.isInteger(idx)||idx<0||idx>=node.length)return!1;node=node[idx]}else node=node[String(key)]}if(node===null||node===void 0||typeof node!=="object")return!1;let lastSegment=path[path.length-1];if(Array.isArray(node)){let idx=Number(lastSegment);if(!Number.isInteger(idx)||idx<0||idx>=node.length)return!1;node.splice(idx,1)}else delete node[String(lastSegment)];return!0}function hasRemovedAncestor(p,removed){for(let len=1;len<p.length;len++)if(removed.has(keyOf(p.slice(0,len))))return!0;return!1}function dedupeByKey(paths){let seen=new Set,result=[];for(let p of paths){let k=keyOf(p);if(!seen.has(k))seen.add(k),result.push(p)}return result}function recordFor(path,issues){let key=keyOf(path);for(let issue2 of issues)if(keyOf(issue2.path)===key)return{path,code:issue2.code,message:issue2.message};return{path,code:"unknown",message:"no matching issue found"}}function sanitizeMalformedValues(schema,rawConfig){if(rawConfig===null||rawConfig===void 0||typeof rawConfig!=="object"||Array.isArray(rawConfig))return{config:{},recoveryWarnings:[{section:"<root>",severity:"warn",message:"Config input is not a plain object (received "+String(rawConfig===null?"null":typeof rawConfig)+"); schema defaults will apply."}]};if(schema.safeParse(rawConfig).success)return{config:rawConfig,recoveryWarnings:[]};let current=deepClone(rawConfig),removed=new Map,fuel=2*countNodes(rawConfig)+8,recovered=!1;for(let iter=0;iter<fuel;iter++){let res=schema.safeParse(current);if(res.success){recovered=!0;break}let issues=res.error.issues,leafCandidates=[],anyPathIssue=!1;for(let issue2 of issues){let p=issue2.path;if(p.length===0)continue;if(anyPathIssue=!0,issue2.code==="unrecognized_keys"&&Array.isArray(issue2.keys))for(let k of issue2.keys)leafCandidates.push([...p,k]);else leafCandidates.push(p)}let batch=selectDeepest(leafCandidates).filter((p)=>!removed.has(keyOf(p)));if(batch.length===0&&anyPathIssue){for(let issue2 of issues){let q=issue2.path;while(q!==null&&removed.has(keyOf(q)))q=q.length>1?q.slice(0,-1):null;if(q!==null&&!removed.has(keyOf(q)))batch.push(q)}batch=dedupeByKey(batch)}if(batch.length===0){let sections=dedupeByKey(issues.filter((i)=>i.path.length>0).map((i)=>[i.path[0]])).filter((p)=>!removed.has(keyOf(p)));if(sections.length===0)break;batch=sections}for(let p of batch)if(removeAtPath(current,p))removed.set(keyOf(p),recordFor(p,issues))}if(!recovered){if(!schema.safeParse(current).success){let topLevelKeys=[...Object.keys(current)];for(let key of topLevelKeys)if(key in current)delete current[key];if(!schema.safeParse(current).success);}}let surviving=[...removed.values()].filter((r)=>!hasRemovedAncestor(r.path,removed)).sort((a,b)=>a.path.length-b.path.length||keyOf(a.path).localeCompare(keyOf(b.path))).map((r)=>({section:dotted(r.path),severity:"warn",message:`Config ${r.path.length===1?"section":"field"} "${dotted(r.path)}" was invalid (${r.code}) and was dropped; schema defaults will apply.`,path:dotted(r.path)}));return{config:current,recoveryWarnings:surviving}}var keyOf=(p)=>JSON.stringify(p);function isActiveStatus(status){return!INACTIVE_STATUSES.has(status??"")}var KNOWLEDGE_SCHEMA_VERSION=3,INACTIVE_STATUSES,OUTCOME_BLOCK_THRESHOLD=-0.3;var init_knowledge_types=__esm(()=>{INACTIVE_STATUSES=new Set(["archived","quarantined","quarantined_unactionable"])});var exports_schema={};__export(exports_schema,{stripKnownSwarmPrefix:()=>stripKnownSwarmPrefix,resolveGuardrailsConfig:()=>resolveGuardrailsConfig,resolveGeneratedAgentRole:()=>resolveGeneratedAgentRole,resolveExternalSkillsConfig:()=>resolveExternalSkillsConfig,resolveAutoReviewConfig:()=>resolveAutoReviewConfig,isKnownCanonicalRole:()=>isKnownCanonicalRole,getCanonicalAgentRole:()=>getCanonicalAgentRole,_internals:()=>_internals,WorktreeIsolationConfigSchema:()=>WorktreeIsolationConfigSchema,WatchdogConfigSchema:()=>WatchdogConfigSchema,UIReviewConfigSchema:()=>UIReviewConfigSchema,TurboConfigSchema:()=>TurboConfigSchema,ToolFilterConfigSchema:()=>ToolFilterConfigSchema,TokenRatiosSchema:()=>TokenRatiosSchema,SwarmConfigSchema:()=>SwarmConfigSchema,SummaryConfigSchema:()=>SummaryConfigSchema,StandardTurboConfigSchema:()=>StandardTurboConfigSchema,SpecWriterConfigSchema:()=>SpecWriterConfigSchema,SlopDetectorConfigSchema:()=>SlopDetectorConfigSchema,SkillsConfigSchema:()=>SkillsConfigSchema,SkillPropagationConfigSchema:()=>SkillPropagationConfigSchema,SkillOptConfigSchema:()=>SkillOptConfigSchema,SkillImproverConfigSchema:()=>SkillImproverConfigSchema,SelfReviewConfigSchema:()=>SelfReviewConfigSchema,SecretscanConfigSchema:()=>SecretscanConfigSchema,ScoringWeightsSchema:()=>ScoringWeightsSchema,ScoringConfigSchema:()=>ScoringConfigSchema,ReviewPassesConfigSchema:()=>ReviewPassesConfigSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QualityBudgetConfigSchema:()=>QualityBudgetConfigSchema,PrmConfigSchema:()=>PrmConfigSchema,PricingConfigSchema:()=>PricingConfigSchema,PrMonitorConfigSchema:()=>PrMonitorConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanCursorConfigSchema:()=>PlanCursorConfigSchema,PlaceholderScanConfigSchema:()=>PlaceholderScanConfigSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,ParallelizationConfigSchema:()=>ParallelizationConfigSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LintConfigSchema:()=>LintConfigSchema,LearningConfigSchema:()=>LearningConfigSchema,LeanTurboStrategyConfigSchema:()=>LeanTurboStrategyConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,KnowledgeConfigSchema:()=>KnowledgeConfigSchema,KnowledgeApplicationConfigSchema:()=>KnowledgeApplicationConfigSchema,IntegrationAnalysisConfigSchema:()=>IntegrationAnalysisConfigSchema,IncrementalVerifyConfigSchema:()=>IncrementalVerifyConfigSchema,HooksConfigSchema:()=>HooksConfigSchema,GuardrailsProfileSchema:()=>GuardrailsProfileSchema,GuardrailsConfigSchema:()=>GuardrailsConfigSchema,GeneralCouncilConfigSchema:()=>GeneralCouncilConfigSchema,GateFeatureSchema:()=>GateFeatureSchema,GateConfigSchema:()=>GateConfigSchema,GATE_CONFIG_KNOWN_SECTION_KEYS:()=>GATE_CONFIG_KNOWN_SECTION_KEYS,FALLBACK_MODELS_MAX:()=>FALLBACK_MODELS_MAX,ExternalSkillsConfigSchema:()=>ExternalSkillsConfigSchema,ExternalSkillCandidateSourceTypeSchema:()=>ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateSchema:()=>ExternalSkillCandidateSchema,ExternalSkillCandidateEvaluationVerdictSchema:()=>ExternalSkillCandidateEvaluationVerdictSchema,EvidenceConfigSchema:()=>EvidenceConfigSchema,EpicConfigSchema:()=>EpicConfigSchema,DocsConfigSchema:()=>DocsConfigSchema,DiscoverySourceSchema:()=>DiscoverySourceSchema,DesignDocsConfigSchema:()=>DesignDocsConfigSchema,DecisionDecaySchema:()=>DecisionDecaySchema,DEFAULT_SKILL_OPT_CONFIG:()=>DEFAULT_SKILL_OPT_CONFIG,DEFAULT_SKILLS_CONFIG:()=>DEFAULT_SKILLS_CONFIG,DEFAULT_EXTERNAL_SKILLS_CONFIG:()=>DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_ARCHITECT_PROFILE:()=>DEFAULT_ARCHITECT_PROFILE,DEFAULT_AGENT_PROFILES:()=>DEFAULT_AGENT_PROFILES,CuratorConfigSchema:()=>CuratorConfigSchema,CouncilConfigSchema:()=>CouncilConfigSchema,ContextMapConfigSchema:()=>ContextMapConfigSchema,ContextBudgetConfigSchema:()=>ContextBudgetConfigSchema,ConsensusConfigSchema:()=>ConsensusConfigSchema,CompactionConfigSchema:()=>CompactionConfigSchema,CompactionAdvisoryConfigSchema:()=>CompactionAdvisoryConfigSchema,CheckpointConfigSchema:()=>CheckpointConfigSchema,AutomationModeSchema:()=>AutomationModeSchema,AutomationConfigSchema:()=>AutomationConfigSchema,AutomationCapabilitiesSchema:()=>AutomationCapabilitiesSchema,AutoReviewConfigSchema:()=>AutoReviewConfigSchema,AuthorityConfigSchema:()=>AuthorityConfigSchema,ArchitecturalSupervisionConfigSchema:()=>ArchitecturalSupervisionConfigSchema,ApplyPatchConfigSchema:()=>ApplyPatchConfigSchema,AgentThinkingConfigSchema:()=>AgentThinkingConfigSchema,AgentReasoningConfigSchema:()=>AgentReasoningConfigSchema,AgentOverrideConfigSchema:()=>AgentOverrideConfigSchema,AgentAuthorityRuleSchema:()=>AgentAuthorityRuleSchema,AdversarialTestingConfigSchema:()=>AdversarialTestingConfigSchema,AdversarialDetectionConfigSchema:()=>AdversarialDetectionConfigSchema,AUTO_REVIEW_V8_BURN_IN_DECISION:()=>AUTO_REVIEW_V8_BURN_IN_DECISION});function isKnownCanonicalRole(role){if(!role)return!1;return CANONICAL_ROLES_SET.has(role)}function getCanonicalAgentRole(agentName,generatedAgentNames){if(!agentName)return agentName;let normalized=agentName.toLowerCase();if(CANONICAL_ROLES_SET.has(normalized))return normalized;if(generatedAgentNames){let registry2=new Set;for(let n of generatedAgentNames)registry2.add(n.toLowerCase());if(!registry2.has(normalized))return agentName}for(let role of CANONICAL_ROLES_LONGEST_FIRST)for(let sep of SEPARATORS){let suffix=sep+role;if(normalized.length>suffix.length&&normalized.endsWith(suffix))return role}return agentName}function resolveGeneratedAgentRole(agentName,generatedAgentNames){return _internals.getCanonicalAgentRole(agentName,generatedAgentNames)}function stripKnownSwarmPrefix(agentName){return getCanonicalAgentRole(agentName)}function hasApprovedAutoReviewBurnIn(decision){return Boolean(decision?.approved===!0&&decision.artifact_path===AUTO_REVIEW_V8_BURN_IN_DECISION.artifact_path&&decision.artifact_sha256===AUTO_REVIEW_V8_BURN_IN_DECISION.artifact_sha256)}function autoReviewEnabledByRelease(context={}){let version2=context.packageVersion??package_default.version,major=Number.parseInt(version2.split(".")[0]??"",10);return Number.isInteger(major)&&major>=8&&hasApprovedAutoReviewBurnIn(context.burnInDecision??AUTO_REVIEW_V8_BURN_IN_DECISION)}function isPlainRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function normalizeAutoReviewInput(value,context={}){if(!isPlainRecord(value))return value;let normalized={...value};if(!Object.hasOwn(value,"enabled"))normalized.enabled=autoReviewEnabledByRelease(context);if(Object.hasOwn(value,"final_review")&&!isPlainRecord(value.final_review))return normalized;let nested=isPlainRecord(value.final_review)?{...value.final_review}:{};if(!Object.hasOwn(nested,"max_diff_bytes"))nested.max_diff_bytes=typeof value.max_diff_kb==="number"?value.max_diff_kb*1024:262144;if(!Object.hasOwn(nested,"timeout_ms"))nested.timeout_ms=typeof value.timeout_ms==="number"?value.timeout_ms:300000;return normalized.final_review=nested,normalized}function resolveAutoReviewConfig(raw={},context={}){let parsed=AutoReviewConfigObjectSchema.parse(normalizeAutoReviewInput(raw,context));if(parsed.final_review.mode==="gate"&&parsed.structured_findings===!1)throw Error('auto_review.final_review.mode="gate" requires auto_review.structured_findings=true');return parsed}function resolveGuardrailsConfig(config2,agentName){if(!agentName)return config2;let canonicalName=_internals.stripKnownSwarmPrefix(agentName),hasBuiltInProfile=canonicalName in DEFAULT_AGENT_PROFILES,userProfile=config2.profiles?.[agentName]??config2.profiles?.[canonicalName];if(!hasBuiltInProfile){if(userProfile)return{...config2,...userProfile};return config2}let builtInProfile=DEFAULT_AGENT_PROFILES[canonicalName];return{...config2,...builtInProfile,...userProfile||{}}}function rejectCheckpointPrototypePollution(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return raw;try{if(Object.getPrototypeOf(raw)!==Object.prototype)return{[INVALID_CHECKPOINT_PROTO_FIELD]:!0};for(let key of Reflect.ownKeys(raw))if(typeof key==="string"&&FORBIDDEN_CHECKPOINT_CONFIG_KEYS.has(key))return{[INVALID_CHECKPOINT_PROTO_FIELD]:!0}}catch{return{[INVALID_CHECKPOINT_PROTO_FIELD]:!0}}return raw}function resolveExternalSkillsConfig(input){if(input===void 0||input===null||typeof input!=="object"||Array.isArray(input))return{...DEFAULT_EXTERNAL_SKILLS_CONFIG};let config2=input;return{curation_enabled:config2.curation_enabled??DEFAULT_EXTERNAL_SKILLS_CONFIG.curation_enabled,max_candidates:config2.max_candidates??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_candidates,max_bytes_per_candidate:config2.max_bytes_per_candidate??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_bytes_per_candidate,eviction_policy:config2.eviction_policy??DEFAULT_EXTERNAL_SKILLS_CONFIG.eviction_policy,ttl_days:config2.ttl_days??DEFAULT_EXTERNAL_SKILLS_CONFIG.ttl_days,evaluation_enabled:config2.evaluation_enabled??DEFAULT_EXTERNAL_SKILLS_CONFIG.evaluation_enabled,sources:Array.isArray(config2.sources)?config2.sources:[],max_candidates_per_discovery:config2.max_candidates_per_discovery??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_candidates_per_discovery,max_concurrent_fetches:config2.max_concurrent_fetches??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_concurrent_fetches,fetch_timeout_ms:config2.fetch_timeout_ms??DEFAULT_EXTERNAL_SKILLS_CONFIG.fetch_timeout_ms}}var _internals,SEPARATORS,CANONICAL_ROLES_LONGEST_FIRST,CANONICAL_ROLES_SET,AgentReasoningConfigSchema,AgentThinkingConfigSchema,FALLBACK_MODELS_MAX=3,AgentOverrideConfigSchema,SwarmConfigSchema,ModelPricingConfigSchema,PricingConfigSchema,HooksConfigSchema,ScoringWeightsSchema,DecisionDecaySchema,TokenRatiosSchema,ScoringConfigSchema,ContextBudgetConfigSchema,EvidenceConfigSchema,GateFeatureSchema,PlaceholderScanConfigSchema,QualityBudgetConfigSchema,GATE_CONFIG_KNOWN_SECTION_KEYS,GateConfigSchema,PipelineConfigSchema,PhaseCompleteConfigSchema,SummaryConfigSchema,ReviewPassesConfigSchema,AUTO_REVIEW_V8_BURN_IN_DECISION,AutoReviewFinalConfigSchema,AutoReviewConfigObjectSchema,AutoReviewConfigSchema,AdversarialDetectionConfigSchema,AdversarialTestingConfigSchemaBase,AdversarialTestingConfigSchema,IntegrationAnalysisConfigSchema,DocsConfigSchema,DesignDocsConfigSchema,UIReviewConfigSchema,CompactionAdvisoryConfigSchema,LintConfigSchema,SecretscanConfigSchema,GuardrailsProfileSchema,DEFAULT_AGENT_PROFILES,DEFAULT_ARCHITECT_PROFILE,GuardrailsConfigSchema,WatchdogConfigSchema,SelfReviewConfigSchema,ToolFilterConfigSchema,PlanCursorConfigSchema,ContextMapConfigSchema,RepoGraphConfigSchema,INVALID_CHECKPOINT_PROTO_FIELD="__swarm_invalid_checkpoint_proto__",FORBIDDEN_CHECKPOINT_CONFIG_KEYS,CheckpointConfigSchema,ApplyPatchConfigSchema,AutomationModeSchema,AutomationCapabilitiesSchema,AutomationConfigSchemaBase,AutomationConfigSchema,KnowledgeConfigSchema,LearningConfigSchema,ConsensusConfigSchema,MemoryConfigSchema,CuratorConfigSchema,ArchitecturalSupervisionConfigSchema,KnowledgeApplicationConfigSchema,SkillPropagationAudienceSchema,SkillPropagationConfigSchema,SkillImproverConfigSchema,SkillsConfigSchema,SkillOptConfigSchema,DEFAULT_SKILL_OPT_CONFIG,SpecWriterConfigSchema,SlopDetectorConfigSchema,IncrementalVerifyConfigSchema,CompactionConfigSchema,PrmConfigSchema,AgentAuthorityRuleSchema,AuthorityConfigSchema,GeneralCouncilMemberConfigSchema,GeneralCouncilConfigSchema,CouncilConfigSchema,PrMonitorConfigSchema,ParallelizationConfigSchema,WorktreeIsolationConfigSchema,LeanTurboConfigSchema,EpicConfigSchema,StandardTurboConfigSchema,LeanTurboStrategyConfigSchema,TurboConfigSchema,ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateEvaluationVerdictSchema,DiscoverySourceSchema,ExternalSkillCandidateSchema,ExternalSkillsConfigSchema,DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_SKILLS_CONFIG,PluginConfigSchema;var init_schema=__esm(()=>{init_zod();init_package();init_knowledge_types();init_constants();_internals={stripKnownSwarmPrefix,getCanonicalAgentRole,resolveGuardrailsConfig},SEPARATORS=["_","-"," "],CANONICAL_ROLES_LONGEST_FIRST=[...ALL_AGENT_NAMES].sort((a,b)=>b.length-a.length),CANONICAL_ROLES_SET=new Set(ALL_AGENT_NAMES);AgentReasoningConfigSchema=exports_external.object({effort:exports_external.enum(["low","medium","high","max"]).optional()}),AgentThinkingConfigSchema=exports_external.object({type:exports_external.enum(["enabled","disabled"]).optional(),budget_tokens:exports_external.number().int().positive().optional()}),AgentOverrideConfigSchema=exports_external.object({model:exports_external.string().optional(),variant:exports_external.string().min(1).optional(),temperature:exports_external.number().min(0).max(2).optional(),disabled:exports_external.boolean().optional(),fallback_models:exports_external.array(exports_external.string()).max(FALLBACK_MODELS_MAX).optional(),reasoning:AgentReasoningConfigSchema.optional(),thinking:AgentThinkingConfigSchema.optional()}),SwarmConfigSchema=exports_external.object({name:exports_external.string().optional(),agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional()}),ModelPricingConfigSchema=exports_external.object({input_per_million:exports_external.number().min(0),output_per_million:exports_external.number().min(0),reasoning_per_million:exports_external.number().min(0).optional(),cache_per_million:exports_external.number().min(0).optional()}),PricingConfigSchema=exports_external.object({models:exports_external.record(exports_external.string().min(1),ModelPricingConfigSchema).optional().default({})}),HooksConfigSchema=exports_external.object({system_enhancer:exports_external.boolean().default(!0),compaction:exports_external.boolean().default(!0),agent_activity:exports_external.boolean().default(!0),delegation_tracker:exports_external.boolean().default(!1),agent_awareness_max_chars:exports_external.number().min(50).max(2000).default(300),delegation_gate:exports_external.boolean().default(!0),delegation_max_chars:exports_external.number().min(500).max(20000).default(4000),background_subagents:exports_external.boolean().default(!1),background_pending_timeout_minutes:exports_external.number().int().min(1).max(1440).default(30)}),ScoringWeightsSchema=exports_external.object({phase:exports_external.number().min(0).max(5).default(1),current_task:exports_external.number().min(0).max(5).default(2),blocked_task:exports_external.number().min(0).max(5).default(1.5),recent_failure:exports_external.number().min(0).max(5).default(2.5),recent_success:exports_external.number().min(0).max(5).default(0.5),evidence_presence:exports_external.number().min(0).max(5).default(1),decision_recency:exports_external.number().min(0).max(5).default(1.5),dependency_proximity:exports_external.number().min(0).max(5).default(1)}),DecisionDecaySchema=exports_external.object({mode:exports_external.enum(["linear","exponential"]).default("exponential"),half_life_hours:exports_external.number().min(1).max(168).default(24)}),TokenRatiosSchema=exports_external.object({prose:exports_external.number().min(0.1).max(1).default(0.25),code:exports_external.number().min(0.1).max(1).default(0.4),markdown:exports_external.number().min(0.1).max(1).default(0.3),json:exports_external.number().min(0.1).max(1).default(0.35)}),ScoringConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),max_candidates:exports_external.number().min(10).max(500).default(100),weights:ScoringWeightsSchema.optional(),decision_decay:DecisionDecaySchema.optional(),token_ratios:TokenRatiosSchema.optional()}),ContextBudgetConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),warn_threshold:exports_external.number().min(0).max(1).default(0.7),critical_threshold:exports_external.number().min(0).max(1).default(0.9),model_limits:exports_external.record(exports_external.string(),exports_external.number().min(1000)).default({default:128000}),max_injection_tokens:exports_external.number().min(100).max(50000).default(4000),unified_injection_tokens:exports_external.number().min(100).max(50000).optional(),tracked_agents:exports_external.array(exports_external.string()).default(["architect"]),scoring:ScoringConfigSchema.optional(),enforce:exports_external.boolean().default(!0),prune_target:exports_external.number().min(0).max(1).default(0.7),preserve_last_n_turns:exports_external.number().min(0).max(100).default(4),recent_window:exports_external.number().min(1).max(100).default(10),enforce_on_agent_switch:exports_external.boolean().default(!0),tool_output_mask_threshold:exports_external.number().min(100).max(1e5).default(2000)}),EvidenceConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_age_days:exports_external.number().min(1).max(365).default(90),max_bundles:exports_external.number().min(10).max(1e4).default(1000),auto_archive:exports_external.boolean().default(!1),cache_max_bytes:exports_external.number().min(512).max(52428800).optional(),cache_max_records:exports_external.number().min(10).max(1e5).optional()}),GateFeatureSchema=exports_external.object({enabled:exports_external.boolean().default(!0)}),PlaceholderScanConfigSchema=GateFeatureSchema.extend({deny_patterns:exports_external.array(exports_external.string()).default(["TODO","FIXME","TBD","XXX","placeholder","stub","wip","not implemented"]),allow_globs:exports_external.array(exports_external.string()).default(["docs/**","examples/**","tests/**","**/*.test.*","**/*.spec.*","**/mocks/**","**/__tests__/**"]),max_allowed_findings:exports_external.number().min(0).default(0),sentinel_allowlist:exports_external.array(exports_external.string()).default([])}),QualityBudgetConfigSchema=GateFeatureSchema.extend({max_complexity_delta:exports_external.number().default(5),max_public_api_delta:exports_external.number().default(10),max_duplication_ratio:exports_external.number().default(0.05),min_test_to_code_ratio:exports_external.number().default(0.3),enforce_on_globs:exports_external.array(exports_external.string()).default(["src/**"]),exclude_globs:exports_external.array(exports_external.string()).default(["docs/**","tests/**","**/*.test.*"])}),GATE_CONFIG_KNOWN_SECTION_KEYS={syntax_check:["enabled"],placeholder_scan:["enabled","deny_patterns","allow_globs","max_allowed_findings"],sast_scan:["enabled"],sbom_generate:["enabled"],build_check:["enabled"],quality_budget:["enabled","max_complexity_delta","max_public_api_delta","max_duplication_ratio","min_test_to_code_ratio","enforce_on_globs","exclude_globs"]},GateConfigSchema=exports_external.object({syntax_check:GateFeatureSchema.default({enabled:!0}),placeholder_scan:PlaceholderScanConfigSchema.default({enabled:!0,deny_patterns:["TODO","FIXME","TBD","XXX","placeholder","stub","wip","not implemented"],allow_globs:["docs/**","examples/**","tests/**","**/*.test.*","**/*.spec.*","**/mocks/**","**/__tests__/**"],max_allowed_findings:0,sentinel_allowlist:[]}),sast_scan:GateFeatureSchema.default({enabled:!0}),sbom_generate:GateFeatureSchema.default({enabled:!0}),build_check:GateFeatureSchema.default({enabled:!0}),quality_budget:QualityBudgetConfigSchema.default(()=>QualityBudgetConfigSchema.parse({}))}),PipelineConfigSchema=exports_external.object({parallel_precheck:exports_external.boolean().default(!0)}),PhaseCompleteConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),required_agents:exports_external.array(exports_external.enum(["coder","reviewer","test_engineer"])).default(["coder","reviewer","test_engineer"]),require_docs:exports_external.boolean().default(!0),policy:exports_external.enum(["enforce","warn"]).default("enforce"),regression_sweep:exports_external.object({enforce:exports_external.boolean().default(!1)}).optional()}),SummaryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),threshold_bytes:exports_external.number().min(1024).max(1048576).default(16384),max_summary_chars:exports_external.number().min(100).max(5000).default(1000),max_stored_bytes:exports_external.number().min(10240).max(104857600).default(10485760),retention_days:exports_external.number().min(1).max(365).default(7),exempt_tools:exports_external.array(exports_external.string()).default([...SUMMARIZER_EXEMPT_TOOL_NAMES])}),ReviewPassesConfigSchema=exports_external.object({always_security_review:exports_external.boolean().default(!1),security_globs:exports_external.array(exports_external.string()).default(["**/auth/**","**/api/**","**/crypto/**","**/security/**","**/middleware/**","**/session/**","**/token/**"])}),AUTO_REVIEW_V8_BURN_IN_DECISION={approved:!0,artifact_path:"docs/benchmarks/auto-review-v8-cost-baseline.json",artifact_sha256:"b4e981d4d87e3de80f6d7dd4ae782b08159d385019c4d8b0d300c0443f1984ce"};AutoReviewFinalConfigSchema=exports_external.object({on_phase_complete:exports_external.boolean().default(!0),on_plan_complete:exports_external.boolean().default(!0),model:exports_external.string().min(1).nullable().default(null),mode:exports_external.enum(["advisory","gate"]).default("advisory"),max_diff_bytes:exports_external.number().int().min(16384).max(2097152).default(262144),timeout_ms:exports_external.number().int().min(1e4).max(1800000).default(300000)}),AutoReviewConfigObjectSchema=exports_external.object({enabled:exports_external.boolean(),trigger:exports_external.enum(["task_completion","phase_boundary","both"]).default("phase_boundary"),timeout_ms:exports_external.number().int().min(1e4).max(1800000).default(300000),max_diff_kb:exports_external.number().int().min(16).max(2048).default(256),min_confidence:exports_external.number().min(0).max(1).default(0.7),structured_findings:exports_external.boolean().default(!0),validate_findings:exports_external.boolean().default(!1),validation_model:exports_external.string().min(1).nullable().default(null),validation_timeout_ms:exports_external.number().int().min(1e4).max(1800000).default(120000),final_review:AutoReviewFinalConfigSchema.default({on_phase_complete:!0,on_plan_complete:!0,model:null,mode:"advisory",max_diff_bytes:262144,timeout_ms:300000})});AutoReviewConfigSchema=exports_external.preprocess((value)=>normalizeAutoReviewInput(value),AutoReviewConfigObjectSchema);AdversarialDetectionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),policy:exports_external.enum(["warn","gate","ignore"]).default("warn"),pairs:exports_external.array(exports_external.tuple([exports_external.string(),exports_external.string()])).default([["coder","reviewer"]])}),AdversarialTestingConfigSchemaBase=exports_external.object({enabled:exports_external.boolean().default(!0),scope:exports_external.enum(["all","security-only"]).default("all")}),AdversarialTestingConfigSchema=AdversarialTestingConfigSchemaBase.default(()=>({enabled:!0,scope:"all"})),IntegrationAnalysisConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0)}),DocsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),doc_patterns:exports_external.array(exports_external.string()).default(["README.md","CONTRIBUTING.md","docs/**/*.md","docs/**/*.rst","**/CHANGELOG.md"])}),DesignDocsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),out_dir:exports_external.string().default("docs").refine((v)=>v.length>0&&v!=="."&&!v.includes("..")&&!v.startsWith("/")&&!v.startsWith("\\")&&!/^[A-Za-z]:/.test(v),{message:'design_docs.out_dir must be a non-empty project-relative path with no "..", leading slash, or drive letter'}),language:exports_external.string().optional()}),UIReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),trigger_paths:exports_external.array(exports_external.string()).default(["**/pages/**","**/components/**","**/views/**","**/screens/**","**/ui/**","**/layouts/**"]),trigger_keywords:exports_external.array(exports_external.string()).default(["new page","new screen","new component","redesign","layout change","form","modal","dialog","dropdown","sidebar","navbar","dashboard","landing page","signup","login form","settings page","profile page"])}),CompactionAdvisoryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),thresholds:exports_external.array(exports_external.number().int().min(10).max(500)).default([50,75,100,125,150]),message:exports_external.string().default("[SWARM HINT] Session has ${totalToolCalls} tool calls. Consider compacting at next phase boundary to maintain context quality.")}),LintConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),mode:exports_external.enum(["check","fix"]).default("check"),linter:exports_external.enum(["biome","eslint","auto"]).default("auto"),patterns:exports_external.array(exports_external.string()).default(["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/biome.json","**/biome.jsonc"]),exclude:exports_external.array(exports_external.string()).default(["**/node_modules/**","**/dist/**","**/.git/**","**/coverage/**","**/*.min.js"])}),SecretscanConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),patterns:exports_external.array(exports_external.string()).default(["**/*.{env,properties,yml,yaml,json,js,ts}","**/.env*","**/secrets/**","**/credentials/**","**/config/**/*.ts","**/config/**/*.js"]),exclude:exports_external.array(exports_external.string()).default(["**/node_modules/**","**/dist/**","**/.git/**","**/coverage/**","**/test/**","**/tests/**","**/__tests__/**","**/*.test.ts","**/*.test.js","**/*.spec.ts","**/*.spec.js"]),extensions:exports_external.array(exports_external.string()).default([".env",".properties",".yml",".yaml",".json",".js",".ts",".py",".rb",".go",".java",".cs",".php"])}),GuardrailsProfileSchema=exports_external.object({max_tool_calls:exports_external.number().min(0).max(1000).optional(),max_duration_minutes:exports_external.number().min(0).max(480).optional(),max_repetitions:exports_external.number().min(3).max(50).optional(),max_consecutive_errors:exports_external.number().min(2).max(20).optional(),warning_threshold:exports_external.number().min(0.1).max(0.9).optional(),idle_timeout_minutes:exports_external.number().min(5).max(240).optional(),max_transient_retries:exports_external.number().min(0).max(20).optional()}),DEFAULT_AGENT_PROFILES={architect:{max_tool_calls:0,max_duration_minutes:0,max_consecutive_errors:8,warning_threshold:0.75},coder:{max_tool_calls:400,max_duration_minutes:45,max_consecutive_errors:8,warning_threshold:0.85},test_engineer:{max_tool_calls:400,max_duration_minutes:45,max_consecutive_errors:8,warning_threshold:0.85},explorer:{max_tool_calls:150,max_duration_minutes:20,max_consecutive_errors:8,warning_threshold:0.75},reviewer:{max_tool_calls:200,max_duration_minutes:30,max_consecutive_errors:8,warning_threshold:0.65},critic:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.65},sme:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.65},docs:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.75},designer:{max_tool_calls:150,max_duration_minutes:20,warning_threshold:0.75}},DEFAULT_ARCHITECT_PROFILE=DEFAULT_AGENT_PROFILES.architect,GuardrailsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_tool_calls:exports_external.number().min(0).max(1000).default(200),max_duration_minutes:exports_external.number().min(0).max(480).default(30),max_repetitions:exports_external.number().min(3).max(50).default(10),max_consecutive_errors:exports_external.number().min(2).max(20).default(5),max_transient_retries:exports_external.number().min(0).max(20).default(5),warning_threshold:exports_external.number().min(0.1).max(0.9).default(0.75),idle_timeout_minutes:exports_external.number().min(5).max(240).default(60),no_op_warning_threshold:exports_external.number().min(1).max(100).default(15),max_coder_revisions:exports_external.number().int().min(1).max(20).default(5),runaway_output_max_turns:exports_external.number().int().min(1).max(20).default(5),qa_gates:exports_external.object({required_tools:exports_external.array(exports_external.string().min(1)).default(["diff","syntax_check","placeholder_scan","lint","pre_check_batch"]),require_reviewer_test_engineer:exports_external.boolean().default(!0)}).optional(),profiles:exports_external.record(exports_external.string(),GuardrailsProfileSchema).optional(),block_destructive_commands:exports_external.boolean().default(!0),interpreter_allowed_agents:exports_external.array(exports_external.string().min(1)).optional(),shell_audit_log:exports_external.boolean().default(!0),gate_denial_warn_threshold:exports_external.number().int().min(1).default(3),gate_denial_stop_threshold:exports_external.number().int().min(1).default(5),execution_stall_warn_calls:exports_external.number().int().min(1).default(30),execution_stall_stop_calls:exports_external.number().int().min(1).default(60),execution_stall_episode_minutes:exports_external.number().int().min(1).default(30)}),WatchdogConfigSchema=exports_external.object({scope_guard:exports_external.boolean().default(!0),skip_in_turbo:exports_external.boolean().default(!1),delegation_ledger:exports_external.boolean().default(!0)}),SelfReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),skip_in_turbo:exports_external.boolean().default(!0)});ToolFilterConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),overrides:exports_external.record(exports_external.string(),exports_external.array(exports_external.string())).default({})}),PlanCursorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_tokens:exports_external.number().min(500).max(4000).default(1500),lookahead_tasks:exports_external.number().min(0).max(5).default(2)}),ContextMapConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),mode:exports_external.enum(["conservative","balanced","aggressive"]).default("balanced"),max_capsule_tokens:exports_external.number().int().positive().default(2000),invalidate_on_hash_change:exports_external.boolean().default(!0),agent_profiles:exports_external.record(exports_external.string(),exports_external.string()).default({})}),RepoGraphConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),init_refresh:exports_external.boolean().default(!0),refresh_cap:exports_external.number().int().min(0).max(500).default(50),walk_budget_ms:exports_external.number().int().min(1000).max(60000).default(5000),max_files:exports_external.number().int().min(100).max(1e5).default(1e4),exclude_dirs:exports_external.array(exports_external.string().trim().min(1)).default([])}),FORBIDDEN_CHECKPOINT_CONFIG_KEYS=new Set(["__proto__","prototype","constructor"]);CheckpointConfigSchema=exports_external.preprocess(rejectCheckpointPrototypePollution,exports_external.object({enabled:exports_external.boolean().default(!0),auto_checkpoint_threshold:exports_external.number().int().min(1).max(20).default(3).describe("Maximum number of checkpoints to retain. Oldest checkpoints are evicted when this limit is exceeded."),max_retention:exports_external.number().int().min(1).max(100).default(20),allow_empty_commits:exports_external.boolean().default(!1)}).strict()),ApplyPatchConfigSchema=exports_external.object({fuzzy_match:exports_external.boolean().default(!1),fuzzy_match_context_aware:exports_external.boolean().default(!1)}).strict(),AutomationModeSchema=exports_external.enum(["manual","hybrid","auto"]),AutomationCapabilitiesSchema=exports_external.object({plan_sync:exports_external.boolean().default(!0),phase_preflight:exports_external.boolean().default(!1),config_doctor_on_startup:exports_external.boolean().default(!1),config_doctor_autofix:exports_external.boolean().default(!1),evidence_auto_summaries:exports_external.boolean().default(!0),decision_drift_detection:exports_external.boolean().default(!0)}),AutomationConfigSchemaBase=exports_external.object({mode:AutomationModeSchema.default("manual"),capabilities:AutomationCapabilitiesSchema.default({plan_sync:!0,phase_preflight:!1,config_doctor_on_startup:!1,config_doctor_autofix:!1,evidence_auto_summaries:!0,decision_drift_detection:!0})}),AutomationConfigSchema=AutomationConfigSchemaBase,KnowledgeConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),swarm_max_entries:exports_external.number().min(1).max(1e4).default(100),hive_max_entries:exports_external.number().min(1).max(1e5).default(200),auto_promote_days:exports_external.number().min(1).max(3650).default(90),max_inject_count:exports_external.number().min(0).max(50).default(5),delegate_max_inject_count:exports_external.number().min(0).max(50).default(8),inject_char_budget:exports_external.number().min(200).max(1e4).default(2000),context_budget_threshold:exports_external.number().int().positive().optional(),max_lesson_display_chars:exports_external.number().min(40).max(280).default(120),dedup_threshold:exports_external.number().min(0).max(1).default(0.6),scope_filter:exports_external.array(exports_external.string()).default(["global"]),hive_enabled:exports_external.boolean().default(!0),rejected_max_entries:exports_external.number().min(1).max(1000).default(20),validation_enabled:exports_external.boolean().default(!0),evergreen_confidence:exports_external.number().min(0).max(1).default(0.9),evergreen_utility:exports_external.number().min(0).max(1).default(0.8),low_utility_threshold:exports_external.number().min(0).max(1).default(0.3),min_retrievals_for_utility:exports_external.number().min(1).max(100).default(3),schema_version:exports_external.number().int().min(1).default(1),directive_min_confidence:exports_external.number().min(0).max(1).default(0.75),same_project_weight:exports_external.number().min(0).max(5).default(1),cross_project_weight:exports_external.number().min(0).max(5).default(0.5),min_encounter_score:exports_external.number().min(0).max(1).default(0.1),initial_encounter_score:exports_external.number().min(0).max(5).default(1),encounter_increment:exports_external.number().min(0).max(1).default(0.1),max_encounter_score:exports_external.number().min(1).max(20).default(10),default_max_phases:exports_external.number().int().positive().default(10),todo_max_phases:exports_external.number().int().positive().default(3),sweep_enabled:exports_external.boolean().default(!0),confidence_floor_action:exports_external.enum(["none","demote","quarantine"]).default("demote"),confidence_floor_min_outcomes:exports_external.number().int().min(0).default(3),confidence_floor_signal_threshold:exports_external.number().min(-1).max(1).default(0),contradiction_threshold_action:exports_external.enum(["tag_only","quarantine"]).default("quarantine"),contradiction_quarantine_threshold:exports_external.number().int().positive().default(3),contradiction_quarantine_window_days:exports_external.number().int().positive().default(30),promoted_demotion_min_negative_phases:exports_external.number().int().positive().default(3),promoted_demotion_signal_threshold:exports_external.number().min(-1).max(1).default(OUTCOME_BLOCK_THRESHOLD),promotion_min_terminal_applications:exports_external.number().min(0).max(100).default(0),promotion_min_distinct_cohorts:exports_external.number().min(0).max(50).default(0),promotion_require_actionable:exports_external.boolean().default(!0),realtime_learning_nudge:exports_external.object({enabled:exports_external.boolean().default(!0),first_after_tool_calls:exports_external.number().int().min(1).max(1000).default(10),repeat_after_tool_calls:exports_external.number().int().min(1).max(1000).default(25)}).default({enabled:!0,first_after_tool_calls:10,repeat_after_tool_calls:25}),retrieval:exports_external.object({mmr_lambda:exports_external.number().min(0).max(1).default(0.5),cold_start_bonus:exports_external.number().min(0).max(0.5).default(0.08),cold_start_max_age_phases:exports_external.number().int().min(0).max(100).default(3),synonym_min_cooccurrence:exports_external.number().int().min(1).max(100).default(3),synonym_map_max_pairs:exports_external.number().int().min(1).max(1e4).default(500)}).optional(),enrichment:exports_external.object({max_calls_per_day:exports_external.number().int().min(0).max(1000).default(30),quota_window:exports_external.enum(["utc","local"]).default("utc"),batch_size:exports_external.number().int().min(1).max(100).optional()}).default({max_calls_per_day:30,quota_window:"utc"})}),LearningConfigSchema=exports_external.object({realtime_admission:exports_external.object({enabled:exports_external.boolean().default(!0),max_queue_size:exports_external.number().int().min(1).max(500).default(50),min_drain:exports_external.number().int().min(1).max(50).default(1),max_drain:exports_external.number().int().min(1).max(100).default(10),drain_depth_factor:exports_external.number().min(0).max(1).default(0.5),drain_velocity_factor:exports_external.number().min(0).max(1).default(0.25),max_llm_calls_per_session:exports_external.number().int().min(0).max(500).default(20),max_tokens_per_session:exports_external.number().int().min(0).default(50000),max_concurrent_admissions:exports_external.number().int().min(1).max(16).default(2),max_retries_per_candidate:exports_external.number().int().min(0).max(5).default(1),per_candidate_llm_timeout_ms:exports_external.number().int().min(0).default(60000),max_drain_wall_time_ms:exports_external.number().int().min(0).default(1e4),supersede_nudge:exports_external.boolean().default(!0)}).prefault({}),prm_persistence:exports_external.object({enabled:exports_external.boolean().default(!0),min_support:exports_external.number().int().min(1).max(20).default(3),cooldown_ms:exports_external.number().int().min(0).default(900000)}).prefault({}),dedup_sweep:exports_external.object({enabled:exports_external.boolean().default(!0),max_comparisons:exports_external.number().int().min(0).default(2000),max_merges_per_sweep:exports_external.number().int().min(0).default(10)}).prefault({})}),ConsensusConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),default_min_support:exports_external.number().int().min(1).default(3),default_min_successful_runs:exports_external.number().int().min(0).default(2),default_max_evidence_items:exports_external.number().int().min(1).default(50),max_excerpt_chars:exports_external.number().int().min(1).default(500),llm_summarization_enabled:exports_external.boolean().default(!0),llm_timeout_ms:exports_external.number().int().min(0).default(60000),report_retention:exports_external.number().int().min(0).default(50)}),MemoryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),provider:exports_external.enum(["local-jsonl","sqlite"]).default("sqlite"),storageDir:exports_external.string().default(".swarm/memory"),sqlite:exports_external.object({path:exports_external.string().default(".swarm/memory/memory.db"),busyTimeoutMs:exports_external.number().int().min(0).max(60000).default(5000)}).default({path:".swarm/memory/memory.db",busyTimeoutMs:5000}),link:exports_external.object({enabled:exports_external.boolean().default(!1)}).default({enabled:!1}),recall:exports_external.object({defaultMaxItems:exports_external.number().int().min(1).max(20).default(8),defaultTokenBudget:exports_external.number().int().min(100).max(5000).default(1200),minScore:exports_external.number().min(0).max(1).default(0.05),injection:exports_external.object({enabled:exports_external.boolean().default(!0),minScore:exports_external.number().min(0).max(1).default(0.25),requireQuerySignal:exports_external.boolean().default(!0),maxItems:exports_external.number().int().min(1).max(20).default(6),tokenBudget:exports_external.number().int().min(100).max(5000).default(1000)}).default({enabled:!0,minScore:0.25,requireQuerySignal:!0,maxItems:6,tokenBudget:1000})}).default({defaultMaxItems:8,defaultTokenBudget:1200,minScore:0.05,injection:{enabled:!0,minScore:0.25,requireQuerySignal:!0,maxItems:6,tokenBudget:1000}}),learning:exports_external.object({learningRate:exports_external.number().min(0).max(1).default(0.1),propagationFactor:exports_external.number().min(0).max(1).default(0.3),qValueBoostWeight:exports_external.number().min(0).max(1).default(0.1),suppressionThreshold:exports_external.number().min(0).max(1).default(0.15),promotionThreshold:exports_external.number().min(0).max(1).default(0.85),propagationTokenOverlapThreshold:exports_external.number().min(0).max(1).default(0.4),propagationEmbeddingCosineThreshold:exports_external.number().min(0).max(1).default(0.7),propagationFanout:exports_external.number().int().min(0).max(1000).default(20),propagationLookbackDays:exports_external.number().int().min(1).max(3650).default(30)}).default({learningRate:0.1,propagationFactor:0.3,qValueBoostWeight:0.1,suppressionThreshold:0.15,promotionThreshold:0.85,propagationTokenOverlapThreshold:0.4,propagationEmbeddingCosineThreshold:0.7,propagationFanout:20,propagationLookbackDays:30}),writes:exports_external.object({mode:exports_external.literal("propose").default("propose")}).default({mode:"propose"}),redaction:exports_external.object({rejectDurableSecrets:exports_external.boolean().default(!0)}).default({rejectDurableSecrets:!0}),maintenance:exports_external.object({lowUtilityMaxConfidence:exports_external.number().min(0).max(1).default(0.45),lowUtilityMinAgeDays:exports_external.number().int().min(1).max(3650).default(30),importance:exports_external.object({wRecency:exports_external.number().min(0).max(1).default(0.2),wFrequency:exports_external.number().min(0).max(1).default(0.2),wFreshness:exports_external.number().min(0).max(1).default(0.15),wConfidence:exports_external.number().min(0).max(1).default(0.25),lambda:exports_external.number().min(0).max(10).default(0.05),mu:exports_external.number().min(0).max(10).default(0.01),n:exports_external.number().int().min(1).max(1e5).default(50),threshold:exports_external.number().min(0).max(1).default(0.2)}).default({wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2})}).default({lowUtilityMaxConfidence:0.45,lowUtilityMinAgeDays:30,importance:{wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2}}),qLearning:exports_external.object({learningRate:exports_external.number().min(0).max(1).default(0.1),qValueBoostWeight:exports_external.number().min(0).max(1).default(0.1),suppressionThreshold:exports_external.number().min(0).max(1).default(0.15),promotionThreshold:exports_external.number().min(0).max(1).default(0.85),promotionMinRetrievals:exports_external.number().int().min(0).max(1e5).default(5),propagationFraction:exports_external.number().min(0).max(1).default(0.3),propagationFanoutCap:exports_external.number().int().min(0).max(1e4).default(20),propagationWindowDays:exports_external.number().int().min(0).max(3650).default(30),propagationRelatednessThreshold:exports_external.number().min(0).max(1).default(0.7),explorationRate:exports_external.number().min(0).max(1).default(0.05),verdictPayloadCapBytes:exports_external.number().int().min(0).max(1048576).default(8192),initialQValue:exports_external.number().min(0).max(1).default(0.5)}).default({learningRate:0.1,qValueBoostWeight:0.1,suppressionThreshold:0.15,promotionThreshold:0.85,promotionMinRetrievals:5,propagationFraction:0.3,propagationFanoutCap:20,propagationWindowDays:30,propagationRelatednessThreshold:0.7,explorationRate:0.05,verdictPayloadCapBytes:8192,initialQValue:0.5}),consolidation:exports_external.object({enabled:exports_external.boolean().default(!1),maxClustersPerPass:exports_external.number().int().min(1).max(100).default(10),jaccardThreshold:exports_external.number().min(0).max(1).default(0.3),autoApplyMinConfidence:exports_external.number().min(0).max(1).default(0.6),decayHalfLifeDays:exports_external.object({user_preference:exports_external.number().int().min(0).max(36500).default(0),project_fact:exports_external.number().int().min(0).max(36500).default(0),architecture_decision:exports_external.number().int().min(0).max(36500).default(0),repo_convention:exports_external.number().int().min(0).max(36500).default(0),api_finding:exports_external.number().int().min(0).max(36500).default(180),code_pattern:exports_external.number().int().min(0).max(36500).default(90),test_pattern:exports_external.number().int().min(0).max(36500).default(90),failure_pattern:exports_external.number().int().min(0).max(36500).default(90),security_note:exports_external.number().int().min(0).max(36500).default(0),evidence:exports_external.number().int().min(0).max(36500).default(180),todo:exports_external.number().int().min(0).max(36500).default(30),scratch:exports_external.number().int().min(0).max(36500).default(7)}).default({user_preference:0,project_fact:0,architecture_decision:0,repo_convention:0,api_finding:180,code_pattern:90,test_pattern:90,failure_pattern:90,security_note:0,evidence:180,todo:30,scratch:7})}).default({enabled:!1,maxClustersPerPass:10,jaccardThreshold:0.3,autoApplyMinConfidence:0.6,decayHalfLifeDays:{user_preference:0,project_fact:0,architecture_decision:0,repo_convention:0,api_finding:180,code_pattern:90,test_pattern:90,failure_pattern:90,security_note:0,evidence:180,todo:30,scratch:7}}),hardDelete:exports_external.boolean().default(!1),embeddings:exports_external.object({enabled:exports_external.boolean().default(!1),model:exports_external.string().default("Xenova/all-MiniLM-L6-v2"),dimension:exports_external.number().int().min(1).default(384),version:exports_external.string().optional(),cacheSize:exports_external.number().int().min(1).default(256)}).default({enabled:!1,model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheSize:256}),retrieval:exports_external.object({rrfK:exports_external.number().int().min(1).default(60),weights:exports_external.object({lexical:exports_external.number().min(0).max(1).default(0.5),dense:exports_external.number().min(0).max(1).default(0.4),metadata:exports_external.number().min(0).max(1).default(0.1)}).default({lexical:0.5,dense:0.4,metadata:0.1}),rerank:exports_external.object({enabled:exports_external.boolean().default(!1),model:exports_external.string().optional()}).default({enabled:!1}),latencyBudgetMs:exports_external.number().int().min(0).default(250)}).default({rrfK:60,weights:{lexical:0.5,dense:0.4,metadata:0.1},rerank:{enabled:!1},latencyBudgetMs:250})}),CuratorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),init_enabled:exports_external.boolean().default(!0),phase_enabled:exports_external.boolean().default(!0),postmortem_enabled:exports_external.boolean().default(!0),max_summary_tokens:exports_external.number().min(500).max(8000).default(2000),min_knowledge_confidence:exports_external.number().min(0).max(1).default(0.7),compliance_report:exports_external.boolean().default(!0),suppress_warnings:exports_external.boolean().default(!0),drift_inject_max_chars:exports_external.number().min(100).max(2000).default(500),llm_timeout_ms:exports_external.number().int().min(5000).max(600000).default(300000),skill_generation_enabled:exports_external.boolean().default(!0),skill_generation_mode:exports_external.enum(["draft","active"]).default("draft"),min_skill_confidence:exports_external.number().min(0).max(1).default(0.7),min_skill_confirmations:exports_external.number().int().min(1).max(50).default(2)}),ArchitecturalSupervisionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),mode:exports_external.enum(["advisory","gate"]).default("advisory"),run_on:exports_external.enum(["phase_complete"]).default("phase_complete"),summary_model:exports_external.string().min(1).optional(),max_agent_summary_words:exports_external.number().int().min(20).max(500).default(100),max_phase_summary_words:exports_external.number().int().min(50).max(1000).default(250),allow_concerns_to_complete:exports_external.boolean().default(!0),persist_knowledge_recommendations:exports_external.boolean().default(!1),provenance_verify:exports_external.boolean().default(!1)}),KnowledgeApplicationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),mode:exports_external.enum(["warn","enforce"]).default("warn"),min_confidence:exports_external.number().min(0).max(1).default(0.85),critical_requires_ack:exports_external.boolean().default(!0),require_skill_refs:exports_external.boolean().default(!0),high_risk_tools:exports_external.array(exports_external.string()).default(["save_plan","update_task_status","phase_complete","task","Task"]),max_gate_denials:exports_external.number().int().min(1).max(100).default(5),gate_staleness_ms:exports_external.number().int().min(1e4).max(3600000).default(600000)}),SkillPropagationAudienceSchema=exports_external.string().max(64).refine((value)=>value!=="swarm-plugin",{message:"swarm-plugin is reserved for plugin-internal skill routing"}).refine((value)=>!value.startsWith("runner:"),{message:"runner:* values are derived from the active runner"}).regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,{message:"audiences must be lowercase domain tokens"}),SkillPropagationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),enforce:exports_external.boolean().default(!1),audiences:exports_external.array(SkillPropagationAudienceSchema).max(16).transform((values)=>[...new Set(values)]).default([])}),SkillImproverConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),model:exports_external.string().nullable().default(null),fallback_models:exports_external.array(exports_external.string()).default([]),max_calls_per_day:exports_external.number().int().min(1).max(1000).default(10),trigger:exports_external.enum(["manual","scheduled"]).default("manual"),consolidation_interval_hours:exports_external.number().int().min(1).max(720).default(24),consolidation_max_calls_per_run:exports_external.number().int().min(1).max(100).default(1),targets:exports_external.array(exports_external.enum(["skills","spec","architect_prompt","knowledge"])).default(["skills","spec","architect_prompt","knowledge"]),write_mode:exports_external.enum(["proposal","draft_skills"]).default("proposal"),require_user_approval:exports_external.boolean().default(!0),quota_window:exports_external.enum(["utc","local"]).default("utc"),allow_deterministic_fallback:exports_external.boolean().default(!0)}),SkillsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1)}),SkillOptConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),max_rounds:exports_external.number().int().min(1).max(50).default(5),max_candidates_per_round:exports_external.number().int().min(1).max(20).default(3),max_validations_per_round:exports_external.number().int().min(1).max(10).default(1),max_round_time_ms:exports_external.number().int().min(1e4).max(86400000).default(3600000),max_tokens_per_round:exports_external.number().int().min(1000).max(2000000).default(50000),max_rejections:exports_external.number().int().min(1).max(50).default(5),max_inconclusive_rounds:exports_external.number().int().min(0).max(10).default(2),max_transient_retries:exports_external.number().int().min(0).max(20).default(5),convergence_non_improvements:exports_external.number().int().min(1).max(20).default(3),max_changed_lines:exports_external.number().int().min(1).max(2000).default(200),max_changed_bytes:exports_external.number().int().min(64).max(200000).default(20000),max_changed_sections:exports_external.number().int().min(1).max(40).default(6),deadband:exports_external.number().min(0).max(1).default(0),retirement_min_age_days:exports_external.number().int().min(1).max(3650).default(60)}).strict(),DEFAULT_SKILL_OPT_CONFIG={enabled:!1,max_rounds:5,max_candidates_per_round:3,max_validations_per_round:1,max_round_time_ms:3600000,max_tokens_per_round:50000,max_rejections:5,max_inconclusive_rounds:2,max_transient_retries:5,convergence_non_improvements:3,max_changed_lines:200,max_changed_bytes:20000,max_changed_sections:6,deadband:0,retirement_min_age_days:60},SpecWriterConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),model:exports_external.string().nullable().default(null),fallback_models:exports_external.array(exports_external.string()).default([]),allow_spec_write:exports_external.boolean().default(!0)}),SlopDetectorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),classThreshold:exports_external.number().int().min(1).default(3),commentStripThreshold:exports_external.number().int().min(1).default(5),diffLineThreshold:exports_external.number().int().min(10).default(200),importHygieneThreshold:exports_external.number().int().min(1).default(2)}),IncrementalVerifyConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),command:exports_external.union([exports_external.string(),exports_external.array(exports_external.string())]).nullable().default(null),timeoutMs:exports_external.number().int().min(1000).max(300000).default(30000),triggerAgents:exports_external.array(exports_external.string()).default(["coder"])}),CompactionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),observationThreshold:exports_external.number().min(1).max(99).default(40),reflectionThreshold:exports_external.number().min(1).max(99).default(60),emergencyThreshold:exports_external.number().min(1).max(99).default(80),preserveLastNTurns:exports_external.number().int().min(1).default(5)}),PrmConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),pattern_thresholds:exports_external.object({repetition_loop:exports_external.number().min(1).default(2),ping_pong:exports_external.number().min(1).default(2),expansion_drift:exports_external.number().min(1).default(3),stuck_on_test:exports_external.number().min(1).default(3),context_thrash:exports_external.number().min(1).default(3)}).default(()=>({repetition_loop:2,ping_pong:2,expansion_drift:3,stuck_on_test:3,context_thrash:3})),max_trajectory_lines:exports_external.number().min(10).default(1000),escalation_enabled:exports_external.boolean().default(!0),detection_timeout_ms:exports_external.number().min(10).default(100)}),AgentAuthorityRuleSchema=exports_external.object({readOnly:exports_external.boolean().optional(),blockedExact:exports_external.array(exports_external.string()).optional(),allowedExact:exports_external.array(exports_external.string()).optional(),blockedPrefix:exports_external.array(exports_external.string()).optional(),allowedPrefix:exports_external.array(exports_external.string()).optional(),blockedZones:exports_external.array(exports_external.enum(["production","test","config","generated","docs","build"])).optional(),blockedGlobs:exports_external.array(exports_external.string()).optional(),allowedGlobs:exports_external.array(exports_external.string()).optional(),allowedCaseSensitiveGlobs:exports_external.array(exports_external.string()).optional()}),AuthorityConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),rules:exports_external.record(exports_external.string(),AgentAuthorityRuleSchema).default({}),universal_deny_prefixes:exports_external.array(exports_external.string().min(1)).default([]),verifier_config_paths:exports_external.array(exports_external.string()).optional().describe("Additional glob patterns for verifier config files that are merged into the architect agent's blockedGlobs at plugin init. Writes to matching files are blocked by the authority layer.")}),GeneralCouncilMemberConfigSchema=exports_external.object({memberId:exports_external.string().min(1),model:exports_external.string().min(1),role:exports_external.enum(["generalist","skeptic","domain_expert","devil_advocate","synthesizer"]),persona:exports_external.string().optional()}).strict(),GeneralCouncilConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),searchProvider:exports_external.enum(["tavily","brave"]).default("tavily"),searchApiKey:exports_external.string().optional(),members:exports_external.array(GeneralCouncilMemberConfigSchema).default([]),presets:exports_external.record(exports_external.string(),exports_external.array(GeneralCouncilMemberConfigSchema)).default({}),deliberate:exports_external.boolean().default(!0),moderator:exports_external.boolean().default(!0),moderatorModel:exports_external.string().optional(),maxSourcesPerMember:exports_external.number().int().min(1).max(20).default(5)}).strict(),CouncilConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),maxRounds:exports_external.number().int().min(1).max(10).default(3),parallelTimeoutMs:exports_external.number().int().min(5000).max(120000).default(30000),vetoPriority:exports_external.boolean().default(!0),requireAllMembers:exports_external.boolean().default(!1).describe("When true, submit_council_verdicts rejects if fewer than 5 member verdicts are provided. Equivalent to minimumMembers: 5."),minimumMembers:exports_external.number().int().min(1).max(5).default(3).describe("Minimum distinct council member verdicts required for synthesis. Default 3. Set to 1 to disable quorum enforcement. requireAllMembers: true overrides this to 5 (stricter constraint wins)."),escalateOnMaxRounds:exports_external.string().optional().describe("Optional webhook URL or handler name invoked when maxRounds is reached without APPROVE. Declared for forward compatibility; no behavior is implemented yet."),phaseConcernsAllowComplete:exports_external.boolean().default(!0).describe("When true, a phase-level council CONCERNS verdict with only MEDIUM/LOW findings does NOT block phase completion — the advisory notes are logged as warnings and the phase proceeds. When false, CONCERNS blocks like REJECT. Note: HIGH/CRITICAL findings from CONCERNS members are always promoted to requiredFixes and block at the tool level regardless of this setting. Default: true."),general:GeneralCouncilConfigSchema.optional()}).strict(),PrMonitorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),poll_interval_seconds:exports_external.number().int().min(30).max(300).default(60),max_subscriptions:exports_external.number().int().min(1).max(100).default(20),max_prs_per_cycle:exports_external.number().int().min(1).max(20).default(5),max_concurrent_pr_polls:exports_external.number().int().min(1).max(10).default(3),poll_timeout_ms:exports_external.number().int().min(5000).max(120000).default(30000),failure_threshold:exports_external.number().int().min(1).max(20).default(5),cooldown_seconds:exports_external.number().int().min(5).max(600).default(30),max_cooldown_seconds:exports_external.number().int().min(30).max(3600).default(300),cleanup_ttl_days:exports_external.number().int().min(1).max(90).default(7),auto_unsubscribe_on_merge:exports_external.boolean().default(!0),auto_unsubscribe_on_close:exports_external.boolean().default(!0),notify_ci_failure:exports_external.boolean().default(!0),notify_new_comments:exports_external.boolean().default(!0),notify_merge_conflict:exports_external.boolean().default(!0),notify_review_activity:exports_external.boolean().default(!0),notify_merged:exports_external.boolean().default(!0),notify_closed:exports_external.boolean().default(!0),notify_ci_success:exports_external.boolean().default(!1),auto_pr_feedback:exports_external.boolean().default(!1),event_delivery:exports_external.enum(["advisory","prompt"]).default("prompt"),auto_subscribe_on_pr_create:exports_external.boolean().default(!0)}).strict(),ParallelizationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),maxConcurrentTasks:exports_external.number().int().min(1).max(64).default(1),evidenceLockTimeoutMs:exports_external.number().int().min(1000).max(300000).default(60000),max_coders:exports_external.number().int().min(1).max(16).default(3),max_reviewers:exports_external.number().int().min(1).max(16).default(2)}),WorktreeIsolationConfigSchema=exports_external.object({policy:exports_external.enum(["auto","required","disabled"]).default("auto"),merge_strategy:exports_external.enum(["merge","rebase","cherry-pick"]).default("merge"),worktree_dir:exports_external.string().optional(),deps_strategy:exports_external.enum(["skip","copy","link"]).default("skip"),lane_permissions:exports_external.enum(["scoped_allow","deny","off"]).default("scoped_allow"),serialization_release_after_dispatches:exports_external.number().int().positive().default(5),serialization_release_after_ms:exports_external.number().int().positive().default(60000),runtime_isolation:exports_external.object({enabled:exports_external.boolean().default(!1),port_base:exports_external.number().int().nonnegative().max(65535).optional(),port_stride:exports_external.number().int().positive().default(1),env_overrides:exports_external.record(exports_external.string(),exports_external.string()).optional(),cache_redirects:exports_external.record(exports_external.string(),exports_external.string()).optional()}).optional()}),LeanTurboConfigSchema=exports_external.object({max_parallel_coders:exports_external.number().int().min(1).max(6).default(4),require_declared_scope:exports_external.boolean().default(!0),conflict_policy:exports_external.enum(["serialize","degrade"]).default("serialize"),degrade_on_risk:exports_external.boolean().default(!0),phase_reviewer:exports_external.boolean().default(!0),phase_critic:exports_external.boolean().default(!0),integrated_diff_required:exports_external.boolean().default(!0),allow_docs_only_without_reviewer:exports_external.boolean().default(!1),worktree_isolation:exports_external.boolean().default(!0),merge_strategy:exports_external.enum(["merge","rebase","cherry-pick"]).default("merge").optional(),worktree_dir:exports_external.string().optional(),deps_strategy:exports_external.enum(["skip","copy","link"]).optional(),runtime_isolation:exports_external.object({enabled:exports_external.boolean().default(!1),port_base:exports_external.number().int().nonnegative().max(65535).optional(),port_stride:exports_external.number().int().positive().default(1),env_overrides:exports_external.record(exports_external.string(),exports_external.string()).optional(),cache_redirects:exports_external.record(exports_external.string(),exports_external.string()).optional()}).optional()}),EpicConfigSchema=exports_external.object({cochange:exports_external.object({enabled:exports_external.boolean().default(!1),threshold:exports_external.number().min(-1).max(1).default(0.6),min_co_changes:exports_external.number().int().min(1).default(5)}).strict().optional(),mode:exports_external.object({enabled:exports_external.boolean().default(!1),activation_threshold:exports_external.number().min(0).max(1).default(0.3),min_commits_for_signal:exports_external.number().int().min(1).default(20)}).strict().optional(),calibration:exports_external.object({enabled:exports_external.boolean().default(!0),floor_threshold:exports_external.number().min(0).max(1).default(0.05),tighten_step:exports_external.number().min(0).max(1).default(0.02),loosen_step:exports_external.number().min(0).max(1).default(0.01),loosen_window:exports_external.number().int().min(1).default(10)}).strict().optional()}).strict(),StandardTurboConfigSchema=exports_external.object({strategy:exports_external.literal("standard"),lean:LeanTurboConfigSchema.optional(),epic:EpicConfigSchema.optional()}),LeanTurboStrategyConfigSchema=exports_external.object({strategy:exports_external.literal("lean"),lean:LeanTurboConfigSchema,epic:EpicConfigSchema.optional()}),TurboConfigSchema=exports_external.discriminatedUnion("strategy",[StandardTurboConfigSchema,LeanTurboStrategyConfigSchema]),ExternalSkillCandidateSourceTypeSchema=exports_external.enum(["github","url","collection","manual_import"]),ExternalSkillCandidateEvaluationVerdictSchema=exports_external.enum(["pending","in_review","quarantined","passed","rejected","promoted","revoked"]),DiscoverySourceSchema=exports_external.object({type:ExternalSkillCandidateSourceTypeSchema,location:exports_external.string().min(1),enabled:exports_external.boolean().default(!0),trust_level:exports_external.enum(["low","medium","high"]).default("low").optional()}),ExternalSkillCandidateSchema=exports_external.object({id:exports_external.string().uuid(),source_url:exports_external.string().url(),source_type:ExternalSkillCandidateSourceTypeSchema,publisher:exports_external.string().min(1),sha256:exports_external.string().regex(/^[a-f0-9]{64}$/),fetched_at:exports_external.string().datetime(),skill_name:exports_external.string().optional(),skill_description:exports_external.string().optional(),skill_body:exports_external.string(),risk_flags:exports_external.array(exports_external.string()).default([]),evaluation_verdict:ExternalSkillCandidateEvaluationVerdictSchema.default("pending"),evaluation_history:exports_external.array(exports_external.object({verdict:ExternalSkillCandidateEvaluationVerdictSchema,timestamp:exports_external.string().datetime(),actor:exports_external.string(),reason:exports_external.string().optional(),candidate_id:exports_external.string().optional(),original_verdict:ExternalSkillCandidateEvaluationVerdictSchema.optional(),gate_results:exports_external.array(exports_external.object({gate:exports_external.string(),verdict:exports_external.string()})).optional(),risk_assessment:exports_external.object({total_flags:exports_external.number().int().nonnegative(),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["error","warning"]),category:exports_external.string()}))}).optional(),risk_flags_count:exports_external.number().int().nonnegative().optional(),provenance_snapshot:exports_external.object({sha256:exports_external.string(),source_url:exports_external.string(),publisher:exports_external.string(),fetched_at:exports_external.string().datetime().optional()}).optional(),target_path:exports_external.string().optional(),promoted_content_hash:exports_external.string().regex(/^[a-f0-9]{64}$/).optional(),original_evaluation:exports_external.record(exports_external.string(),exports_external.unknown()).optional()})).default([])}),ExternalSkillsConfigSchema=exports_external.object({curation_enabled:exports_external.boolean().default(!1),max_candidates:exports_external.number().int().min(1).max(1e4).default(500),max_bytes_per_candidate:exports_external.number().int().min(1024).max(10485760).default(1048576),eviction_policy:exports_external.enum(["fifo"]).default("fifo"),ttl_days:exports_external.number().int().min(1).max(3650).default(90),evaluation_enabled:exports_external.boolean().default(!1),sources:exports_external.array(DiscoverySourceSchema).default([]),max_candidates_per_discovery:exports_external.number().int().min(1).max(1000).default(50),max_concurrent_fetches:exports_external.number().int().min(1).max(20).default(5),fetch_timeout_ms:exports_external.number().int().min(1000).max(300000).default(30000)}),DEFAULT_EXTERNAL_SKILLS_CONFIG={curation_enabled:!1,max_candidates:500,max_bytes_per_candidate:1048576,eviction_policy:"fifo",ttl_days:90,evaluation_enabled:!1,sources:[],max_candidates_per_discovery:50,max_concurrent_fetches:5,fetch_timeout_ms:30000},DEFAULT_SKILLS_CONFIG={enabled:!1};PluginConfigSchema=exports_external.object({config_format_version:exports_external.number().int().min(0).default(1),agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional(),default_agent:exports_external.string().optional().transform((v)=>{if(v===void 0)return;let trimmed=v.trim();return trimmed===""?void 0:trimmed}),auto_select_architect:exports_external.union([exports_external.boolean(),exports_external.string()]).optional().transform((v)=>{if(v===void 0)return;if(typeof v==="boolean")return v;let trimmed=v.trim();return trimmed===""?!1:trimmed}),swarms:exports_external.record(exports_external.string().regex(/^[^_]+$/,"Swarm ID must not contain underscores"),SwarmConfigSchema).optional(),max_iterations:exports_external.number().min(1).max(10).default(5),pipeline:PipelineConfigSchema.optional(),phase_complete:PhaseCompleteConfigSchema.optional(),qa_retry_limit:exports_external.number().min(1).max(10).default(3),execution_mode:exports_external.enum(["strict","balanced","fast"]).default("balanced"),inject_phase_reminders:exports_external.boolean().default(!0),hooks:HooksConfigSchema.optional(),gates:GateConfigSchema.optional(),context_budget:ContextBudgetConfigSchema.optional(),pricing:PricingConfigSchema.optional(),guardrails:GuardrailsConfigSchema.optional(),watchdog:WatchdogConfigSchema.optional(),self_review:SelfReviewConfigSchema.optional(),auto_review:AutoReviewConfigSchema.optional(),tool_filter:ToolFilterConfigSchema.optional(),authority:AuthorityConfigSchema.optional(),plan_cursor:PlanCursorConfigSchema.optional(),context_map:ContextMapConfigSchema.optional(),repo_graph:RepoGraphConfigSchema.prefault({}),evidence:EvidenceConfigSchema.optional(),summaries:SummaryConfigSchema.optional(),review_passes:ReviewPassesConfigSchema.optional(),adversarial_detection:AdversarialDetectionConfigSchema.optional(),adversarial_testing:AdversarialTestingConfigSchema.optional(),integration_analysis:IntegrationAnalysisConfigSchema.optional(),docs:DocsConfigSchema.optional(),design_docs:DesignDocsConfigSchema.optional(),ui_review:UIReviewConfigSchema.optional(),compaction_advisory:CompactionAdvisoryConfigSchema.optional(),lint:LintConfigSchema.optional(),secretscan:SecretscanConfigSchema.optional(),checkpoint:CheckpointConfigSchema.optional(),apply_patch:ApplyPatchConfigSchema.optional(),automation:AutomationConfigSchema.optional(),knowledge:KnowledgeConfigSchema.optional(),memory:MemoryConfigSchema.optional(),learning:LearningConfigSchema.optional(),consensus:ConsensusConfigSchema.optional(),curator:CuratorConfigSchema.optional(),architectural_supervision:ArchitecturalSupervisionConfigSchema.optional(),knowledge_application:KnowledgeApplicationConfigSchema.optional(),skillPropagation:SkillPropagationConfigSchema.optional(),skill_improver:SkillImproverConfigSchema.optional(),spec_writer:SpecWriterConfigSchema.optional(),tool_output:exports_external.object({truncation_enabled:exports_external.boolean().default(!0),max_lines:exports_external.number().min(10).max(500).default(150),per_tool:exports_external.record(exports_external.string(),exports_external.number()).optional(),truncation_tools:exports_external.array(exports_external.string()).optional().describe("Tools to apply output truncation to. Defaults to diff, symbols, bash, shell, test_runner, lint, pre_check_batch, complexity_hotspots, pkg_audit, sbom_generate, schema_drift.")}).optional(),slop_detector:SlopDetectorConfigSchema.optional(),todo_gate:exports_external.object({enabled:exports_external.boolean().default(!0),max_high_priority:exports_external.number().int().min(-1).default(0).describe("Max new high-priority TODOs (FIXME/HACK/XXX) before warning. 0 = warn on any. Set to -1 to disable."),block_on_threshold:exports_external.boolean().default(!1).describe("If true, block phase completion when threshold exceeded. Default: advisory only.")}).optional(),incremental_verify:IncrementalVerifyConfigSchema.optional(),compaction_service:CompactionConfigSchema.optional(),prm:PrmConfigSchema.optional(),council:CouncilConfigSchema.optional(),parallelization:ParallelizationConfigSchema.optional(),worktree:WorktreeIsolationConfigSchema.optional(),turbo:TurboConfigSchema.optional(),turbo_mode:exports_external.boolean().default(!1).optional(),quiet:exports_external.boolean().default(!0).optional(),version_check:exports_external.boolean().default(!0).optional(),full_auto:exports_external.object({enabled:exports_external.boolean().default(!1),locked:exports_external.boolean().default(!1),critic_model:exports_external.string().optional(),max_interactions_per_phase:exports_external.number().int().min(5).max(200).default(50),deadlock_threshold:exports_external.number().int().min(2).max(10).default(3),escalation_mode:exports_external.enum(["pause","terminate"]).default("pause"),mode:exports_external.enum(["assisted","supervised","strict"]).default("supervised"),fail_closed:exports_external.boolean().default(!0),permission_policy:exports_external.object({enabled:exports_external.boolean().default(!0),trusted_roots:exports_external.array(exports_external.string()).default(["."]),trusted_domains:exports_external.array(exports_external.string()).default([]),protected_paths:exports_external.array(exports_external.string()).default([".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"]),allow_defaults:exports_external.boolean().default(!0)}).default(()=>({enabled:!0,trusted_roots:["."],trusted_domains:[],protected_paths:[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"],allow_defaults:!0})),denials:exports_external.object({max_consecutive:exports_external.number().int().min(1).max(50).default(3),max_total:exports_external.number().int().min(1).max(500).default(20),on_limit:exports_external.enum(["pause","terminate"]).default("pause")}).default(()=>({max_consecutive:3,max_total:20,on_limit:"pause"})),oversight:exports_external.object({on_plan_change:exports_external.boolean().default(!0),on_task_completion:exports_external.boolean().default(!1),on_phase_boundary:exports_external.boolean().default(!0),on_high_risk_action:exports_external.boolean().default(!0),on_subagent_return_warning:exports_external.boolean().default(!0),every_tool_calls:exports_external.number().int().min(0).max(1e4).default(25),every_architect_turns:exports_external.number().int().min(0).max(1000).default(5),every_minutes:exports_external.number().int().min(0).max(1440).default(20),max_dispatch_retries:exports_external.number().int().min(0).max(10).default(2),max_consecutive_dispatch_failures:exports_external.number().int().min(0).max(50).default(3)}).default(()=>({on_plan_change:!0,on_task_completion:!1,on_phase_boundary:!0,on_high_risk_action:!0,on_subagent_return_warning:!0,every_tool_calls:25,every_architect_turns:5,every_minutes:20,max_dispatch_retries:2,max_consecutive_dispatch_failures:3}))}).optional().default(()=>({enabled:!1,locked:!1,max_interactions_per_phase:50,deadlock_threshold:3,escalation_mode:"pause",mode:"supervised",fail_closed:!0,permission_policy:{enabled:!0,trusted_roots:["."],trusted_domains:[],protected_paths:[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"],allow_defaults:!0},denials:{max_consecutive:3,max_total:20,on_limit:"pause"},oversight:{on_plan_change:!0,on_task_completion:!1,on_phase_boundary:!0,on_high_risk_action:!0,on_subagent_return_warning:!0,every_tool_calls:25,every_architect_turns:5,every_minutes:20,max_dispatch_retries:2,max_consecutive_dispatch_failures:3}})),pr_monitor:PrMonitorConfigSchema.optional(),external_skills:ExternalSkillsConfigSchema.optional(),skills:SkillsConfigSchema.optional(),skill_opt:SkillOptConfigSchema.optional()})});var exports_loader={};__export(exports_loader,{loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadAgentPrompt:()=>loadAgentPrompt,getSafeDefaultConfigLoadResult:()=>getSafeDefaultConfigLoadResult,formatZodIssues:()=>formatZodIssues,deepMerge:()=>deepMerge,MAX_MERGE_DEPTH:()=>MAX_MERGE_DEPTH,MAX_CONFIG_FILE_BYTES:()=>MAX_CONFIG_FILE_BYTES});import*as fs from"node:fs";import*as fsPromises from"node:fs/promises";import*as os from"node:os";import*as path from"node:path";function getUserConfigDir(){return process.env.XDG_CONFIG_HOME||path.join(os.homedir(),".config")}function loadRawConfigFromPath(configPath){try{if(fs.statSync(configPath).size>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let content=fs.readFileSync(configPath,"utf-8");if(content.length>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let sanitizedContent=content;if(content.charCodeAt(0)===65279)sanitizedContent=content.slice(1);let rawConfig=JSON.parse(sanitizedContent);if(typeof rawConfig!=="object"||rawConfig===null||Array.isArray(rawConfig))return advisoryWarn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config format invalid. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};return{config:rawConfig,fileExisted:!0,hadError:!1}}catch(error49){if(!(error49 instanceof Error&&("code"in error49)&&error49.code==="ENOENT")){let errorMessage=error49 instanceof Error?error49.message:String(error49);return advisoryWarn(`[opencode-swarm] ⚠️ CONFIG LOAD FAILURE — config exists at ${configPath} but could not be loaded: ${errorMessage}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config load failed. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0}}return{config:null,fileExisted:!1,hadError:!1}}}function migratePresetsConfig(raw){if(raw.presets&&typeof raw.presets==="object"&&!raw.agents){let presetName=raw.preset||"remote",presets=raw.presets,activePreset=presets[presetName]||Object.values(presets)[0];if(activePreset&&typeof activePreset==="object"){let migrated={...raw,agents:activePreset};return delete migrated.preset,delete migrated.presets,delete migrated.swarm_mode,advisoryWarn("[opencode-swarm] Migrated v6.12 presets config to agents format. Consider updating your opencode-swarm.json."),migrated}}return raw}function sanitizeExternalSkillsConfig(raw){if(!("external_skills"in raw)||raw.external_skills===void 0)return{result:raw,strippedKeys:[]};let esResult=ExternalSkillsConfigSchema.safeParse(raw.external_skills);if(esResult.success)return{result:{...raw,external_skills:resolveExternalSkillsConfig(esResult.data)},strippedKeys:[]};advisoryWarn("[opencode-swarm] external_skills config validation failed:",formatZodIssues(esResult.error)),advisoryWarn("[opencode-swarm] External skills curation disabled due to invalid config. Fix the external_skills section to enable it.");let cleaned={...raw};return delete cleaned.external_skills,{result:cleaned,strippedKeys:["external_skills"]}}function sanitizeGatesConfig(raw){let strippedKeys=[];if(!("gates"in raw)||raw.gates===void 0)return{result:raw,strippedKeys};if(typeof raw.gates!=="object"||raw.gates===null||Array.isArray(raw.gates)){advisoryWarn("[opencode-swarm] gates config validation failed: expected an object. Quality gates will use defaults; other config sections remain active.");let cleaned2={...raw};return delete cleaned2.gates,strippedKeys.push("gates"),{result:cleaned2,strippedKeys}}let gateSchemas=GateConfigSchema.shape,cleanedGates={...raw.gates};for(let[key,value]of Object.entries(cleanedGates)){let schema=gateSchemas[key];if(!schema){advisoryWarn(`[opencode-swarm] Unknown gates config section "gates.${key}" ignored. Other config sections remain active.`),delete cleanedGates[key],strippedKeys.push(`gates.${key}`);continue}let knownFields=GATE_CONFIG_KNOWN_SECTION_KEYS[key],sectionValue=value;if(knownFields&&typeof value==="object"&&value!==null&&!Array.isArray(value)){let cleanedSection={...value},knownFieldSet=new Set(knownFields);for(let fieldName of Object.keys(cleanedSection))if(!knownFieldSet.has(fieldName))advisoryWarn(`[opencode-swarm] Unknown gates config key "gates.${key}.${fieldName}" ignored. Other config sections remain active.`),delete cleanedSection[fieldName],strippedKeys.push(`gates.${key}.${fieldName}`);sectionValue=cleanedSection,cleanedGates[key]=cleanedSection}let sectionResult=schema.safeParse(sectionValue);if(!sectionResult.success){if(advisoryWarn(`[opencode-swarm] gates.${key} config validation failed; that gate section will use defaults and other config sections remain active:`,formatZodIssues(sectionResult.error)),delete cleanedGates[key],!strippedKeys.includes(`gates.${key}`))strippedKeys.push(`gates.${key}`)}}let gatesResult=GateConfigSchema.safeParse(cleanedGates);if(gatesResult.success)return{result:{...raw,gates:gatesResult.data},strippedKeys};advisoryWarn("[opencode-swarm] gates config validation failed after section cleanup; quality gates will use defaults and other config sections remain active:",formatZodIssues(gatesResult.error));let cleaned={...raw};if(delete cleaned.gates,!strippedKeys.includes("gates"))strippedKeys.push("gates");return{result:cleaned,strippedKeys}}function sanitizeSectionConfigs(raw){let{result:afterExternal,strippedKeys:externalStripped}=sanitizeExternalSkillsConfig(raw),{result,strippedKeys:gatesStripped}=sanitizeGatesConfig(afterExternal);return{result,strippedKeys:[...externalStripped,...gatesStripped]}}function formatZodIssues(error49){if(error49.issues.length===0)return"";return error49.issues.map((issue2)=>{let dotted2=issue2.path.map(String).join(".");return dotted2?`${dotted2}: ${issue2.message}`:issue2.message}).join("; ")}function stripUnrecognizedKeys(raw,error49){let removed=[],cleaned=structuredClone(raw);for(let issue2 of error49.issues){if(issue2.code!=="unrecognized_keys")continue;let keys=issue2.keys??[],node=cleaned;for(let seg of issue2.path)if(node&&typeof node==="object")node=node[seg];else{node=void 0;break}if(!node||typeof node!=="object")continue;for(let key of keys)if(key in node){delete node[key];let dotted2=[...issue2.path.map(String),key].join(".");removed.push(dotted2)}}return{cleaned,removed}}function rawFullAutoLocked(raw){if(!raw||typeof raw!=="object")return!1;let fullAuto=raw.full_auto;if(!fullAuto||typeof fullAuto!=="object"||Array.isArray(fullAuto))return!1;return fullAuto.locked===!0}function buildConfigWithMeta(rawUserConfig,rawProjectConfig,loadedFromFile,configHadErrors){let mergedRaw=rawUserConfig??{};if(rawProjectConfig)mergedRaw=deepMerge(mergedRaw,rawProjectConfig);if(rawFullAutoLocked(rawUserConfig)||rawFullAutoLocked(rawProjectConfig)){let fa=mergedRaw.full_auto&&typeof mergedRaw.full_auto==="object"&&!Array.isArray(mergedRaw.full_auto)?mergedRaw.full_auto:{};mergedRaw={...mergedRaw,full_auto:{...fa,locked:!0}}}mergedRaw=migratePresetsConfig(mergedRaw);let{result:sanitized,strippedKeys:gatesStripped}=sanitizeSectionConfigs(mergedRaw);mergedRaw=sanitized;let secure=(cfg)=>loadedFromFile&&configHadErrors?PluginConfigSchema.parse({...cfg,guardrails:{enabled:!0}}):cfg,firstResult=PluginConfigSchema.safeParse(mergedRaw);if(firstResult.success){let config2=secure(firstResult.data);if(loadedFromFile&&configHadErrors)return advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."),{config:config2,recovery:"guardrails_defaults",removedKeys:[...gatesStripped],warnings:[]};return{config:config2,recovery:gatesStripped.length>0?"stripped_keys":"none",removedKeys:[...gatesStripped],warnings:[]}}let{cleaned,removed}=stripUnrecognizedKeys(mergedRaw,firstResult.error);if(removed.length>0){let recovered=PluginConfigSchema.safeParse(cleaned);if(recovered.success)return advisoryWarn(`[opencode-swarm] Ignored ${removed.length} unrecognized config key(s): ${removed.join(", ")}. The rest of your configuration was preserved. Fix or remove these keys.`),{config:secure(recovered.data),recovery:"stripped_keys",removedKeys:[...gatesStripped,...removed],warnings:[]}}if(rawUserConfig){let{result:userSanitized,strippedKeys:userGatesStripped}=sanitizeSectionConfigs(rawUserConfig),userParseResult=PluginConfigSchema.safeParse(userSanitized);if(userParseResult.success)return advisoryWarn("[opencode-swarm] Project config ignored due to validation errors. Using user config."),{config:secure(userParseResult.data),recovery:"user_only",removedKeys:[...gatesStripped,...userGatesStripped],warnings:["Project config ignored due to validation errors; using user config."]};let userStripped=stripUnrecognizedKeys(userSanitized,userParseResult.error);if(userStripped.removed.length>0){let userRecovered=PluginConfigSchema.safeParse(userStripped.cleaned);if(userRecovered.success)return advisoryWarn(`[opencode-swarm] Project config ignored; also ignored ${userStripped.removed.length} unrecognized user-config key(s): ${userStripped.removed.join(", ")}.`),{config:secure(userRecovered.data),recovery:"user_only",removedKeys:[...gatesStripped,...userGatesStripped,...userStripped.removed],warnings:["Project config ignored due to validation errors; using user config."]}}}if(!(mergedRaw.guardrails&&typeof mergedRaw.guardrails==="object"&&!Array.isArray(mergedRaw.guardrails)&&mergedRaw.guardrails.enabled===!1)){let valueRecovery=sanitizeMalformedValues(PluginConfigSchema,mergedRaw);if(valueRecovery.recoveryWarnings.length>0){let recoveredParse=PluginConfigSchema.safeParse(valueRecovery.config);if(recoveredParse.success){let removedKeys=[...gatesStripped,...valueRecovery.recoveryWarnings.map((w)=>w.section)],secureParse=PluginConfigSchema.safeParse({...recoveredParse.data,guardrails:{...recoveredParse.data.guardrails,enabled:!0}});if(secureParse.success)return advisoryWarn(`[opencode-swarm] Ignored ${removedKeys.length} invalid or unrecognized config key(s): ${removedKeys.join(", ")}. The rest of your configuration was preserved. Fix or remove these keys.`),{config:secure(secureParse.data),recovery:"sanitized_values",removedKeys,warnings:[]}}}}let offending=stripUnrecognizedKeys(mergedRaw,firstResult.error).removed;if(offending.length>0)advisoryWarn(`[opencode-swarm] Merged config validation failed. Unrecognized key(s): ${offending.join(", ")}.`);else advisoryWarn("[opencode-swarm] Merged config validation failed:",formatZodIssues(firstResult.error));return advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."),{config:PluginConfigSchema.parse({guardrails:{enabled:!0}}),recovery:"guardrails_defaults",removedKeys:[...gatesStripped],warnings:["Config failed validation; using safe defaults with guardrails enabled."]}}function loadPluginConfig(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),userResult=loadRawConfigFromPath(userConfigPath),projectResult=loadRawConfigFromPath(projectConfigPath),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError;return buildConfigWithMeta(userResult.config,projectResult.config,loadedFromFile,configHadErrors).config}function loadPluginConfigWithMeta(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),userResult=loadRawConfigFromPath(userConfigPath),projectResult=loadRawConfigFromPath(projectConfigPath),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError,{config:config2,recovery,removedKeys,warnings}=buildConfigWithMeta(userResult.config,projectResult.config,loadedFromFile,configHadErrors);return{config:config2,loadedFromFile,configHadErrors,recovery,removedKeys,warnings}}function getSafeDefaultConfigLoadResult(){let{config:config2,recovery,removedKeys,warnings}=buildConfigWithMeta(null,null,!1,!1);return{config:config2,recovery,removedKeys,warnings,loadedFromFile:!1,configHadErrors:!1}}async function loadRawConfigFromPathAsync(configPath){try{if((await fsPromises.stat(configPath)).size>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let content=await fsPromises.readFile(configPath,"utf-8");if(content.length>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let sanitizedContent=content;if(content.charCodeAt(0)===65279)sanitizedContent=content.slice(1);let rawConfig=JSON.parse(sanitizedContent);if(typeof rawConfig!=="object"||rawConfig===null||Array.isArray(rawConfig))return advisoryWarn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config format invalid. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};return{config:rawConfig,fileExisted:!0,hadError:!1}}catch(error49){if(error49.code==="ENOENT")return{config:null,fileExisted:!1,hadError:!1};return advisoryWarn(`[opencode-swarm] Failed to load config from ${configPath}:`,error49 instanceof Error?error49.message:String(error49)),{config:null,fileExisted:!0,hadError:!0}}}async function loadPluginConfigWithMetaAsync(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),[userResult,projectResult]=await Promise.all([loadRawConfigFromPathAsync(userConfigPath),loadRawConfigFromPathAsync(projectConfigPath)]),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError,{config:config2,recovery,removedKeys,warnings}=buildConfigWithMeta(userResult.config,projectResult.config,loadedFromFile,configHadErrors);return{config:config2,loadedFromFile,configHadErrors,recovery,removedKeys,warnings}}function loadAgentPrompt(agentName){let promptsDir=path.join(getUserConfigDir(),"opencode",PROMPTS_DIR_NAME),result={},promptPath=path.join(promptsDir,`${agentName}.md`);if(fs.existsSync(promptPath))try{result.prompt=fs.readFileSync(promptPath,"utf-8")}catch(error49){advisoryWarn(`[opencode-swarm] Error reading prompt file ${promptPath}:`,error49 instanceof Error?error49.message:String(error49))}let appendPromptPath=path.join(promptsDir,`${agentName}_append.md`);if(fs.existsSync(appendPromptPath))try{result.appendPrompt=fs.readFileSync(appendPromptPath,"utf-8")}catch(error49){advisoryWarn(`[opencode-swarm] Error reading append prompt ${appendPromptPath}:`,error49 instanceof Error?error49.message:String(error49))}return result}var CONFIG_FILENAME="opencode-swarm.json",PROMPTS_DIR_NAME="opencode-swarm",MAX_CONFIG_FILE_BYTES=102400;var init_loader=__esm(()=>{init_warning_buffer();init_schema()});var ExecutionProfileSchema,TaskStatusSchema,TaskSizeSchema,PhaseStatusSchema,MigrationStatusSchema,TaskSchema,PhaseSchema,PlanSchema;var init_plan_schema=__esm(()=>{init_zod();ExecutionProfileSchema=exports_external.object({parallelization_enabled:exports_external.boolean().default(!1),max_concurrent_tasks:exports_external.number().int().min(1).max(64).default(10),council_parallel:exports_external.boolean().default(!0),locked:exports_external.boolean().default(!1),auto_proceed:exports_external.boolean().default(!1)}),TaskStatusSchema=exports_external.enum(["pending","in_progress","completed","blocked","closed"]),TaskSizeSchema=exports_external.enum(["small","medium","large"]),PhaseStatusSchema=exports_external.enum(["pending","in_progress","complete","completed","blocked","closed"]),MigrationStatusSchema=exports_external.enum(["native","migrated","migration_failed"]),TaskSchema=exports_external.object({id:exports_external.string(),phase:exports_external.number().int().min(1),status:TaskStatusSchema.default("pending"),size:TaskSizeSchema.default("small"),description:exports_external.string().min(1),depends:exports_external.array(exports_external.string()).default([]),acceptance:exports_external.string().optional(),files_touched:exports_external.array(exports_external.string()).default([]),evidence_path:exports_external.string().optional(),blocked_reason:exports_external.string().optional(),fr_refs:exports_external.array(exports_external.string()).optional()}),PhaseSchema=exports_external.object({id:exports_external.number().int().min(1),name:exports_external.string().min(1),status:PhaseStatusSchema.default("pending"),tasks:exports_external.array(TaskSchema).default([]),type:exports_external.enum(["code","non-code"]).optional(),required_agents:exports_external.array(exports_external.string()).optional()}),PlanSchema=exports_external.object({schema_version:exports_external.literal("1.0.0"),title:exports_external.string().min(1),swarm:exports_external.string().min(1),current_phase:exports_external.number().int().min(1).optional(),phases:exports_external.array(PhaseSchema).min(1),migration_status:MigrationStatusSchema.optional(),specMtime:exports_external.string().optional(),specHash:exports_external.string().optional(),execution_profile:ExecutionProfileSchema.optional()})});function stripCodeBlocks(content){return content.replace(FENCED_BLOCK_PATTERN,"").replace(INLINE_CODE_PATTERN,"")}function getLineNumber(content,position){return(content.substring(0,position).match(/\n/g)||[]).length+1}function validateSpecContent(content){let issues=[];if(!content||content.trim().length===0)return{valid:!1,issues:[{line:1,message:"Content is empty"}]};let strippedContent=stripCodeBlocks(content),frMatches=strippedContent.match(FR_ID_PATTERN);if(!frMatches||frMatches.length===0)issues.push({line:1,message:"No FR-### requirement IDs found in spec content"});let obligationMatches=strippedContent.match(OBLIGATION_PATTERN);if(!obligationMatches||obligationMatches.length===0)issues.push({line:1,message:"No obligation keywords (MUST, SHALL, SHOULD, MAY) found in spec content"});let sectionMatches=strippedContent.match(SECTION_HEADER_PATTERN);if(!sectionMatches||sectionMatches.length===0)issues.push({line:1,message:"No section headers (## Section Name) found in spec content"});let idMatches=strippedContent.matchAll(/\bFR-(\d{3})\b/g);for(let idMatch of idMatches)if(parseInt(idMatch[1],10)===0){let pos=idMatch.index;issues.push({line:getLineNumber(strippedContent,pos),message:`Invalid FR-ID "${idMatch[0]}" — number must be 001-999`})}return{valid:issues.length===0,issues}}var ObligationSchema,SpecRequirementSchema,SpecScenarioSchema,SpecSectionSchema,SwarmSpecSchema,SpecDeltaSchema,DeltaSpecSchema,FENCED_BLOCK_PATTERN,INLINE_CODE_PATTERN,FR_ID_PATTERN,OBLIGATION_PATTERN,SECTION_HEADER_PATTERN;var init_spec_schema=__esm(()=>{init_zod();ObligationSchema=exports_external.enum(["MUST","SHALL","SHOULD","MAY"]),SpecRequirementSchema=exports_external.object({id:exports_external.string().regex(/^FR-(?!000)\d{3}$/,"Requirement ID must match FR-### pattern (e.g., FR-001)"),obligation:ObligationSchema,text:exports_external.string().min(1)}),SpecScenarioSchema=exports_external.object({name:exports_external.string().min(1),given:exports_external.array(exports_external.string()).optional().default([]),when:exports_external.array(exports_external.string()).min(1,'Scenario must have at least one "when" clause'),thenClauses:exports_external.array(exports_external.string()).min(1,'Scenario must have at least one "then" clause')}),SpecSectionSchema=exports_external.object({name:exports_external.string().min(1),requirements:exports_external.array(SpecRequirementSchema).default([])}),SwarmSpecSchema=exports_external.object({title:exports_external.string().min(1),purpose:exports_external.string().min(1),sections:exports_external.array(SpecSectionSchema).min(1,"Spec must have at least one section")}),SpecDeltaSchema=exports_external.object({added:exports_external.array(SpecRequirementSchema).default([]),modified:exports_external.array(SpecRequirementSchema).default([]),removed:exports_external.array(SpecRequirementSchema).default([])}),DeltaSpecSchema=exports_external.union([SwarmSpecSchema,SpecDeltaSchema]),FENCED_BLOCK_PATTERN=/```[\s\S]*?```/g,INLINE_CODE_PATTERN=/`[^`]*`/g,FR_ID_PATTERN=/\bFR-\d{3}\b/g,OBLIGATION_PATTERN=/\b(MUST|SHALL|SHOULD|MAY)\b/g,SECTION_HEADER_PATTERN=/^##\s+.+$/gm});function resolveWorktreeIsolationConfig(config2){if(config2.worktree)return{...DEFAULT_WORKTREE_ISOLATION_CONFIG,...config2.worktree};let lean=config2.turbo?.strategy==="lean"?config2.turbo.lean:void 0;if(lean?.worktree_isolation)return{...DEFAULT_WORKTREE_ISOLATION_CONFIG,policy:"auto",merge_strategy:lean.merge_strategy??"merge",worktree_dir:lean.worktree_dir,deps_strategy:lean.deps_strategy??"skip",runtime_isolation:lean.runtime_isolation??DEFAULT_WORKTREE_ISOLATION_CONFIG.runtime_isolation};return DEFAULT_WORKTREE_ISOLATION_CONFIG}var init_worktree_isolation_config=__esm(()=>{init_constants()});var exports_config={};__export(exports_config,{validateSpecContent:()=>validateSpecContent,resolveWorktreeIsolationConfig:()=>resolveWorktreeIsolationConfig,resolveAutoReviewConfig:()=>resolveAutoReviewConfig,loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadAgentPrompt:()=>loadAgentPrompt,isSubagent:()=>isSubagent,isQAAgent:()=>isQAAgent,getSafeDefaultConfigLoadResult:()=>getSafeDefaultConfigLoadResult,_internals:()=>_internals2,WorktreeIsolationConfigSchema:()=>WorktreeIsolationConfigSchema,TurboConfigSchema:()=>TurboConfigSchema,TestEvidenceSchema:()=>TestEvidenceSchema,TaskStatusSchema:()=>TaskStatusSchema,TaskSizeSchema:()=>TaskSizeSchema,TaskSchema:()=>TaskSchema,SwarmSpecSchema:()=>SwarmSpecSchema,SwarmConfigSchema:()=>SwarmConfigSchema,SpecSectionSchema:()=>SpecSectionSchema,SpecScenarioSchema:()=>SpecScenarioSchema,SpecRequirementSchema:()=>SpecRequirementSchema,SpecDeltaSchema:()=>SpecDeltaSchema,SkillPropagationConfigSchema:()=>SkillPropagationConfigSchema,ReviewEvidenceSchema:()=>ReviewEvidenceSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QA_AGENTS:()=>QA_AGENTS,PricingConfigSchema:()=>PricingConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanSchema:()=>PlanSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseStatusSchema:()=>PhaseStatusSchema,PhaseSchema:()=>PhaseSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,PIPELINE_AGENTS:()=>PIPELINE_AGENTS,ObligationSchema:()=>ObligationSchema,ORCHESTRATOR_NAME:()=>ORCHESTRATOR_NAME,NoteEvidenceSchema:()=>NoteEvidenceSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MigrationStatusSchema:()=>MigrationStatusSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,EvidenceVerdictSchema:()=>EvidenceVerdictSchema,EvidenceTypeSchema:()=>EvidenceTypeSchema,EvidenceSchema:()=>EvidenceSchema,EvidenceBundleSchema:()=>EvidenceBundleSchema,EVIDENCE_MAX_TASK_BYTES:()=>EVIDENCE_MAX_TASK_BYTES,EVIDENCE_MAX_PATCH_BYTES:()=>EVIDENCE_MAX_PATCH_BYTES,EVIDENCE_MAX_JSON_BYTES:()=>EVIDENCE_MAX_JSON_BYTES,DiffEvidenceSchema:()=>DiffEvidenceSchema,DeltaSpecSchema:()=>DeltaSpecSchema,DEFAULT_MODELS:()=>DEFAULT_MODELS,BaseEvidenceSchema:()=>BaseEvidenceSchema,AutomationModeSchema:()=>AutomationModeSchema,AutomationConfigSchema:()=>AutomationConfigSchema,AutomationCapabilitiesSchema:()=>AutomationCapabilitiesSchema,AutoReviewConfigSchema:()=>AutoReviewConfigSchema,ApprovalEvidenceSchema:()=>ApprovalEvidenceSchema,ApplyPatchConfigSchema:()=>ApplyPatchConfigSchema,AgentOverrideConfigSchema:()=>AgentOverrideConfigSchema,AUTO_REVIEW_V8_BURN_IN_DECISION:()=>AUTO_REVIEW_V8_BURN_IN_DECISION,ALL_SUBAGENT_NAMES:()=>ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES:()=>ALL_AGENT_NAMES});var _internals2;var init_config=__esm(()=>{init_constants();init_evidence_schema();init_loader();init_loader();init_plan_schema();init_schema();init_spec_schema();init_worktree_isolation_config();_internals2={loadPluginConfigWithMeta}});function resolvePrompt(base,custom2,append){if(custom2)return custom2;if(append)return`${base}
|
|
159
159
|
|
|
160
160
|
${append}`;return base}import{randomUUID}from"node:crypto";import*as fsp from"node:fs/promises";import*as path2 from"node:path";function bundledProjectSkillFileReference(slug){return`file:${BUNDLED_PROJECT_SKILL_ROOT}/${slug}/SKILL.md`}function describeBundledSkillSyncFailure(err){return`[opencode-swarm] Could not install bundled project skills; continuing without sync: ${err instanceof Error?err.message:String(err)}`}async function isSymbolicLinkAsync(p){try{return(await fsp.lstat(p)).isSymbolicLink()}catch{return!1}}async function ensureNotSymlinkedDirectoryAsync(p){try{let stat3=await fsp.lstat(p);return stat3.isDirectory()&&!stat3.isSymbolicLink()}catch(err){return err.code==="ENOENT"}}async function pathExistsAsync(p){try{return await fsp.access(p),!0}catch{return!1}}async function collectBundledSkillFilesBoundedAsync(sourceDir,state,relativeDir=""){let currentSource=path2.join(sourceDir,relativeDir),entries=await fsp.readdir(currentSource,{withFileTypes:!0});entries.sort((a,b)=>a.name.localeCompare(b.name));let files=[];for(let entry of entries){let relativeEntry=path2.join(relativeDir,entry.name),sourcePath=path2.join(sourceDir,relativeEntry);if(entry.isSymbolicLink()||await isSymbolicLinkAsync(sourcePath))throw Error("refusing to copy symlinked bundled skill entry");if(entry.isDirectory()){files.push(...await collectBundledSkillFilesBoundedAsync(sourceDir,state,relativeEntry));continue}if(!entry.isFile())continue;let stat3=await fsp.stat(sourcePath),nextFiles=state.files+1,nextBytes=state.bytes+stat3.size;if(nextFiles>MAX_SKILL_FILES||nextBytes>MAX_SKILL_BYTES)throw Error("bundled skill package exceeds copy bounds");state.files=nextFiles,state.bytes=nextBytes,files.push({relativePath:relativeEntry})}return files}async function ensureContainedDirectoryAsync(rootDir,directory){let safeRoot=path2.resolve(rootDir),safeDirectory=path2.resolve(directory),relative2=path2.relative(safeRoot,safeDirectory);if(relative2.startsWith("..")||path2.isAbsolute(relative2))throw Error("bundled skill destination escaped its private root");try{let rootStat=await fsp.lstat(safeRoot);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}catch(err){if(err.code!=="ENOENT")throw err;await fsp.mkdir(safeRoot,{recursive:!0});let rootStat=await fsp.lstat(safeRoot);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}let current=safeRoot;for(let segment of relative2.split(path2.sep).filter(Boolean)){current=path2.join(current,segment);try{let stat3=await fsp.lstat(current);if(stat3.isSymbolicLink()||!stat3.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}catch(err){if(err.code!=="ENOENT")throw err;try{await fsp.mkdir(current)}catch(mkdirErr){if(mkdirErr.code!=="EEXIST")throw mkdirErr}let stat3=await fsp.lstat(current);if(stat3.isSymbolicLink()||!stat3.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}}}async function rollbackCopiedFilesAsync(copiedFiles,destDir,overwrittenFiles=[]){let safeDestDir=path2.resolve(destDir),dirs=new Set;for(let copiedFile of copiedFiles){let resolvedFile=path2.resolve(copiedFile),relative2=path2.relative(safeDestDir,resolvedFile);if(relative2.startsWith("..")||path2.isAbsolute(relative2))continue;try{await fsp.rm(resolvedFile,{force:!0})}catch{}dirs.add(path2.dirname(resolvedFile))}for(let overwritten of overwrittenFiles.reverse()){let resolvedFile=path2.resolve(overwritten.path),relative2=path2.relative(safeDestDir,resolvedFile);if(relative2.startsWith("..")||path2.isAbsolute(relative2))continue;try{await fsp.writeFile(resolvedFile,overwritten.contents)}catch{}}for(let dir of[...dirs].sort((a,b)=>b.length-a.length)){let relative2=path2.relative(safeDestDir,path2.resolve(dir));if(relative2.startsWith("..")||path2.isAbsolute(relative2))continue;try{await fsp.rmdir(dir)}catch{}}}async function copyFileAtomicAsync(sourcePath,destPath){let tempPath=path2.join(path2.dirname(destPath),`.${path2.basename(destPath)}.tmp.${randomUUID()}`);try{await fsp.copyFile(sourcePath,tempPath),await fsp.rename(tempPath,destPath)}catch(err){try{await fsp.rm(tempPath,{force:!0})}catch{}throw err}}async function copyBundledDirectoryBoundedAsync(sourceDir,destDir){let files=await collectBundledSkillFilesBoundedAsync(sourceDir,{files:0,bytes:0}),copiedFiles=[],overwrittenFiles=[];try{for(let file2 of files){let sourcePath=path2.join(sourceDir,file2.relativePath),destPath=path2.join(destDir,file2.relativePath);if(await ensureContainedDirectoryAsync(destDir,path2.dirname(destPath)),await pathExistsAsync(destPath)){if(await isSymbolicLinkAsync(destPath))throw Error("refusing to overwrite symlinked bundled skill file");let[sourceContents,destContents]=await Promise.all([fsp.readFile(sourcePath),fsp.readFile(destPath)]);if(sourceContents.equals(destContents))continue;overwrittenFiles.push({path:destPath,contents:destContents}),await copyFileAtomicAsync(sourcePath,destPath)}else await copyFileAtomicAsync(sourcePath,destPath),copiedFiles.push(destPath)}}catch(err){throw await rollbackCopiedFilesAsync(copiedFiles,destDir,overwrittenFiles),err}}async function performBundledProjectSkillSyncAsync(projectDirectory,packageRoot,quiet){try{let sourceRoot=path2.join(packageRoot,".opencode","skills"),swarmDir=path2.join(projectDirectory,".swarm"),skillsDir=path2.join(projectDirectory,BUNDLED_PROJECT_SKILL_ROOT);if(!await ensureNotSymlinkedDirectoryAsync(sourceRoot))throw Error("refusing to copy symlinked bundled skill source root");if(!await ensureNotSymlinkedDirectoryAsync(swarmDir))return;if(!await ensureNotSymlinkedDirectoryAsync(skillsDir))return;for(let slug of BUNDLED_PROJECT_SKILLS){let sourceDir=path2.join(sourceRoot,slug),sourceSkill=path2.join(sourceDir,"SKILL.md"),destDir=path2.join(skillsDir,slug);if(!await pathExistsAsync(sourceSkill))continue;if(!await ensureNotSymlinkedDirectoryAsync(sourceDir))throw Error("refusing to copy symlinked bundled skill directory");if(!await ensureNotSymlinkedDirectoryAsync(destDir))continue;await copyBundledDirectoryBoundedAsync(sourceDir,destDir),log("synchronized bundled skill",{slug:bundledProjectSkillFileReference(slug)})}}catch(err){let failureMsg=describeBundledSkillSyncFailure(err);if(quiet)advisoryWarn(failureMsg);else console.warn(failureMsg)}}async function syncBundledProjectSkillsIfMissingAsync(projectDirectory,packageRoot,quiet=!1){let syncKey=path2.resolve(projectDirectory,BUNDLED_PROJECT_SKILL_ROOT),existing=inFlightSyncs.get(syncKey);if(existing)return existing;if(inFlightSyncs.size>=MAX_IN_FLIGHT_SYNCS){log("skipping bundled skill sync because the in-flight limit was reached",{limit:MAX_IN_FLIGHT_SYNCS});return}let syncPromise=performBundledProjectSkillSyncAsync(projectDirectory,packageRoot,quiet).finally(()=>{if(inFlightSyncs.get(syncKey)===syncPromise)inFlightSyncs.delete(syncKey)});return inFlightSyncs.set(syncKey,syncPromise),syncPromise}var BUNDLED_PROJECT_SKILLS,BUNDLED_PROJECT_SKILL_ROOT=".swarm/bundled-skills",MAX_SKILL_FILES=64,MAX_SKILL_BYTES=512000,MAX_IN_FLIGHT_SYNCS=64,inFlightSyncs;var init_bundled_skills=__esm(()=>{init_warning_buffer();init_logger();BUNDLED_PROJECT_SKILLS=["brainstorm","specify","clarify-spec","resume","clarify","discover","consult","pre-phase-briefing","council","deep-dive","deep-research","codebase-review-swarm","swarm-implement","design-docs","swarm-pr-review","swarm","swarm-pr-feedback","swarm-pr-subscribe","swarm-ci-monitor","issue-ingest","plan","critic-gate","execute","phase-wrap","loop","writing-tests","running-tests","engineering-conventions","commit-pr","ci-failure-batching","gate-attribution","merge-queue-readiness","skill-edit-validation","worktree-retry-cleanup","test-file-split","fork-pr-operations","parallel-work-check","ci-fix-monitor","issue-tracer"];inFlightSyncs=new Map});function formatCandidateHeader(family){return["[CANDIDATE]",...CANDIDATE_FIELDS[family].map((name)=>name==="file_line"?"file:line":name)].join(" | ")}function formatCleanTemplate(family){return["[CLEAN]",family==="base_explorer"?"lane":"micro_lane","coverage_scope","evidence"].join(" | ")}function candidateHeaderFamily(fields){if(fields[0]?.trim()!=="[CANDIDATE]")return null;let normalized=fields.slice(1).map((field)=>field.trim());for(let family of["base_explorer","micro_lane"]){let canonicalHeaderFields=CANDIDATE_FIELDS[family].map((name)=>name==="file_line"?"file:line":name);if(normalized.length===canonicalHeaderFields.length&&canonicalHeaderFields.every((name,index)=>normalized[index]===name))return family}return null}function selectCandidateHeader(lines){let markerlessFallback=null;for(let[lineIndex,line]of lines.entries()){let fields=splitPipeFields(line.trim()).map((field)=>field.trim());if(fields.length<2||!fields.some(Boolean))continue;let markerBearing=fields[0]==="[CANDIDATE]",selection={lineIndex,fields,family:candidateHeaderFamily(fields),markerBearing};if(markerBearing)return selection;markerlessFallback??=selection}return markerlessFallback}function removeCandidateCodeFences(text){let lines=[],inFence=!1;for(let rawLine of text.split(`
|
|
161
161
|
`)){if(rawLine.trimStart().startsWith("```")){inFence=!inFence;continue}if(!inFence)lines.push(rawLine)}return lines.join(`
|
|
@@ -1912,21 +1912,21 @@ ${USAGE8}`;let councilFlag=parsed.council?"council=true":"council=false",signal=
|
|
|
1912
1912
|
`:"")+stderr;if(output.length>MAX_OUTPUT_BYTES2)output=`${output.slice(0,MAX_OUTPUT_BYTES2)}
|
|
1913
1913
|
... (output truncated)`;let result={success:!0,mode,linter,command,exitCode,output};if(exitCode===0)result.message=`${linter} ${mode} completed successfully with no issues`;else if(mode==="fix")result.message=`${linter} fix completed with exit code ${exitCode}. Run check mode to see remaining issues.`;else result.message=`${linter} check found issues (exit code ${exitCode}).`;return result}catch(error93){return{success:!1,mode,linter,command,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error"}}}var MAX_OUTPUT_BYTES2=512000,MAX_COMMAND_LENGTH=500,lint,_internals103;var init_lint=__esm(()=>{init_zod();init_discovery();init_utils();init_bun_compat();init_create_tool();init_path_security();lint=createSwarmTool({description:"Run project linter in check or fix mode. Supports biome, eslint (JS/TS), ruff (Python), clippy (Rust), golangci-lint (Go), checkstyle (Java), ktlint (Kotlin), dotnet-format (C#), cppcheck (C/C++), swiftlint (Swift), dart analyze (Dart), and rubocop (Ruby). Returns JSON with success status, exit code, and output for architect pre-reviewer gate. Use check mode for CI/linting and fix mode to automatically apply fixes.",args:{mode:exports_external.enum(["fix","check"]).describe('Linting mode: "check" for read-only lint check, "fix" to automatically apply fixes')},async execute(args2,directory){if(!validateArgs(args2))return JSON.stringify({success:!1,mode:"check",error:'Invalid arguments: mode must be "fix" or "check"'},null,2);if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({success:!1,mode:"check",error:"project directory is required but was not provided"},null,2);let{mode}=args2,cwd=directory,linter=await _internals103.detectAvailableLinter(directory);if(linter){let result=await _internals103.runLint(linter,mode,directory);return JSON.stringify(result,null,2)}let additionalLinter=_internals103.detectAdditionalLinter(cwd);if(additionalLinter){warn(`[lint] Using ${additionalLinter} linter for this project`);let result=await _internals103.runAdditionalLint(additionalLinter,mode,cwd);return JSON.stringify(result,null,2)}return JSON.stringify({success:!1,mode,error:"No linter found. Install biome or eslint for JS/TS projects, or a supported linter for your language (ruff, cargo clippy, golangci-lint, ktlint, dotnet format, cppcheck, swiftlint, dart analyze, rubocop).",message:`For JS/TS: npm install -D @biomejs/biome eslint
|
|
1914
1914
|
For Python: pip install ruff
|
|
1915
|
-
For Rust: rustup component add clippy`},null,2)}}),_internals103={detectAvailableLinter,runLint,detectAdditionalLinter,runAdditionalLint}});import*as fs66 from"node:fs";import*as path147 from"node:path";function calculateShannonEntropy(str){if(str.length===0)return 0;let freq=new Map;for(let char of str)freq.set(char,(freq.get(char)||0)+1);let entropy=0;for(let count of freq.values()){let p=count/str.length;entropy-=p*Math.log2(p)}return entropy}function isHighEntropyString(str){if(str.length<20)return!1;if(str.replace(/[^a-zA-Z0-9]/g,"").length/str.length<0.25)return!1;return calculateShannonEntropy(str)>4}function validateExcludePattern(exc){if(exc.length===0)return null;if(exc.length>MAX_FILE_PATH_LENGTH)return`invalid exclude path: exceeds maximum length of ${MAX_FILE_PATH_LENGTH}`;if(containsControlChars(exc))return"invalid exclude path: contains path traversal or control characters";if(containsPathTraversal(exc))return"invalid exclude path: contains path traversal or control characters";if(exc.startsWith("!"))return"invalid exclude path: negation patterns are not supported";if(exc.startsWith("/")||exc.startsWith("\\"))return"invalid exclude path: absolute paths are not supported";return null}function isGlobOrPathPattern(pattern){return pattern.includes("/")||pattern.includes("\\")||/[*?[\]{}]/.test(pattern)}function loadSecretScanIgnore(scanDir){let ignorePath=path147.join(scanDir,".secretscanignore");try{if(!fs66.existsSync(ignorePath))return[];let content=fs66.readFileSync(ignorePath,"utf8"),patterns=[];for(let rawLine of content.split(/\r?\n/)){let line=rawLine.trim();if(!line||line.startsWith("#"))continue;if(validateExcludePattern(line)===null)patterns.push(line)}return patterns}catch{return[]}}function isExcluded(entry,relPath,exactNames,globPatterns){if(exactNames.has(entry))return!0;for(let pattern of globPatterns)if(path147.matchesGlob(relPath,pattern))return!0;return!1}function validateDirectoryInput(dir){if(!dir||dir.length===0)return"directory is required";if(dir.length>MAX_FILE_PATH_LENGTH)return`directory exceeds maximum length of ${MAX_FILE_PATH_LENGTH}`;if(containsControlChars(dir))return"directory contains control characters";if(containsPathTraversal(dir))return"directory contains path traversal";return null}function isBinaryFile(filePath,buffer){let ext=path147.extname(filePath).toLowerCase();if(DEFAULT_EXCLUDE_EXTENSIONS.has(ext))return!0;if(buffer.length>=BINARY_PREFIX_BYTES){let uint323=buffer.subarray(0,BINARY_PREFIX_BYTES).readUInt32BE(0);for(let sig of BINARY_SIGNATURES)if(uint323===sig)return!0}let nullCount=0,checkLen=Math.min(buffer.length,BINARY_NULL_CHECK_BYTES);for(let i=0;i<checkLen;i++)if(buffer[i]===0)nullCount++;return nullCount>checkLen*BINARY_NULL_THRESHOLD}function scanLineForSecrets(line,_lineNum){let results=[];
|
|
1916
|
-
`);for(let i=0;i<lines.length;i++){let lineResults=scanLineForSecrets(lines[i],i+1);for(let result of lineResults)findings.push({path:filePath,line:i+1,type:result.type,confidence:result.confidence,severity:result.severity,redacted:result.redacted,context:createRedactedContext(lines[i],[result])})}}catch{}return findings}function isSymlinkLoop(realPath,visited){if(visited.has(realPath))return!0;return visited.add(realPath),!1}function isPathWithinScope(realPath,scanDir){let resolvedScanDir=path147.resolve(scanDir),resolvedRealPath=path147.resolve(realPath);return resolvedRealPath===resolvedScanDir||resolvedRealPath.startsWith(resolvedScanDir+path147.sep)||resolvedRealPath.startsWith(`${resolvedScanDir}/`)||resolvedRealPath.startsWith(`${resolvedScanDir}\\`)}function findScannableFiles(dir,excludeExact,excludeGlobs,scanDir,visited,stats2={skippedDirs:0,skippedFiles:0,fileErrors:0,symlinkSkipped:0}){let files=[],entries;try{entries=fs66.readdirSync(dir)}catch{return stats2.fileErrors++,files}entries.sort((a,b)=>{let aLower=a.toLowerCase(),bLower=b.toLowerCase();if(aLower<bLower)return-1;if(aLower>bLower)return 1;return a.localeCompare(b)});for(let entry of entries){let fullPath=path147.join(dir,entry),relPath=path147.relative(scanDir,fullPath).replace(/\\/g,"/");if(isExcluded(entry,relPath,excludeExact,excludeGlobs)){stats2.skippedDirs++;continue}let lstat6;try{lstat6=fs66.lstatSync(fullPath)}catch{stats2.fileErrors++;continue}if(lstat6.isSymbolicLink()){stats2.symlinkSkipped++;continue}if(lstat6.isDirectory()){let realPath;try{realPath=fs66.realpathSync(fullPath)}catch{stats2.fileErrors++;continue}if(isSymlinkLoop(realPath,visited)){stats2.symlinkSkipped++;continue}if(!isPathWithinScope(realPath,scanDir)){stats2.symlinkSkipped++;continue}let subFiles=findScannableFiles(fullPath,excludeExact,excludeGlobs,scanDir,visited,stats2);files.push(...subFiles)}else if(lstat6.isFile()){let ext=path147.extname(fullPath).toLowerCase();if(!DEFAULT_EXCLUDE_EXTENSIONS.has(ext))files.push(fullPath);else stats2.skippedFiles++}}return files}async function runSecretscan(directory){try{let result=await _internals104.secretscan.execute({directory},{}),jsonStr=typeof result==="string"?result:result.output;return JSON.parse(jsonStr)}catch(e){return{error:e instanceof Error?`scan failed: ${e.message}`:"scan failed: unknown error",scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0}}}async function runSecretscanOnFiles(files,directory){try{let findings=[],filesScanned=0,skippedFiles=0;for(let file3 of files){if(typeof file3!=="string"){skippedFiles++;continue}let resolvedPath=path147.isAbsolute(file3)?path147.resolve(file3):path147.resolve(directory,file3);if(!isPathWithinScope(resolvedPath,directory)){skippedFiles++;continue}let ext=path147.extname(resolvedPath).toLowerCase();if(DEFAULT_EXCLUDE_EXTENSIONS.has(ext)){skippedFiles++;continue}if(!fs66.existsSync(resolvedPath)){skippedFiles++;continue}let fileFindings=scanFileForSecrets(resolvedPath);if(filesScanned++,findings.push(...fileFindings),findings.length>=MAX_FINDINGS2){findings.length=MAX_FINDINGS2;break}}return findings.sort((a,b)=>{if(a.path<b.path)return-1;if(a.path>b.path)return 1;return a.line-b.line}),{scan_dir:directory,findings,count:findings.length,files_scanned:filesScanned,skipped_files:skippedFiles}}catch(e){return{error:e instanceof Error?`scan failed: ${e.message}`:"scan failed: unknown error",scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0}}}var MAX_FILE_PATH_LENGTH=500,MAX_FILE_SIZE_BYTES3=524288,MAX_FILES_SCANNED2=1000,MAX_FINDINGS2=100,MAX_OUTPUT_BYTES3=512000,MAX_LINE_LENGTH=1e4,MAX_CONTENT_BYTES=51200,BINARY_SIGNATURES,BINARY_PREFIX_BYTES=4,BINARY_NULL_CHECK_BYTES=8192,BINARY_NULL_THRESHOLD=0.1,DEFAULT_EXCLUDE_DIRS,DEFAULT_EXCLUDE_EXTENSIONS,SECRET_PATTERNS2,O_NOFOLLOW,secretscan,_internals104;var init_secretscan=__esm(()=>{init_zod();init_path_security();init_create_tool();BINARY_SIGNATURES=[0,2303741511,4292411360,1195984440,626017350,1347093252],DEFAULT_EXCLUDE_DIRS=new Set(["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".cache","vendor",".svn",".hg",".gradle","target","__pycache__",".pytest_cache",".venv","venv",".env",".idea",".vscode"]),DEFAULT_EXCLUDE_EXTENSIONS=new Set([".png",".jpg",".jpeg",".gif",".ico",".svg",".pdf",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".dylib",".bin",".dat",".db",".sqlite",".lock",".log",".md"]),SECRET_PATTERNS2=[{type:"aws_access_key",regex:/(?:AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|aws_access_key_id|aws_secret_access_key)\s*[=:]\s*['"]?([A-Z0-9]{20})['"]?/gi,confidence:"high",severity:"critical",redactTemplate:()=>"AKIA[REDACTED]"},{type:"aws_secret_key",regex:/(?:AWS_SECRET_ACCESS_KEY|aws_secret_access_key)\s*[=:]\s*['"]?([A-Za-z0-9+/=]{40})['"]?/gi,confidence:"high",severity:"critical",redactTemplate:()=>"[REDACTED_AWS_SECRET]"},{type:"api_key",regex:/(?:api[_-]?key|apikey|API[_-]?KEY)\s*[=:]\s*['"]?([a-zA-Z0-9_-]{16,64})['"]?/gi,confidence:"medium",severity:"high",redactTemplate:(m)=>{let key=m.match(/[a-zA-Z0-9_-]{16,64}/)?.[0]||"";return`api_key=${key.slice(0,4)}...${key.slice(-4)}`}},{type:"bearer_token",regex:/(?:bearer\s+|Bearer\s+)([a-zA-Z0-9_\-.]{1,200})[\s"'<]/gi,confidence:"medium",severity:"high",redactTemplate:()=>"bearer [REDACTED]"},{type:"basic_auth",regex:/(?:basic\s+|Basic\s+)([a-zA-Z0-9+/=]{1,200})[\s"'<]/gi,confidence:"medium",severity:"high",redactTemplate:()=>"basic [REDACTED]"},{type:"database_url",regex:/(?:mysql|postgres|postgresql|mongodb|redis):\/\/[^\s"'/:]+:[^\s"'/:]+@[^\s"']+/gi,confidence:"high",severity:"critical",redactTemplate:()=>"mysql://[user]:[password]@[host]"},{type:"github_token",regex:/(?:ghp|gho|ghu|ghs|ghr)_[a-zA-Z0-9]{36,}/gi,confidence:"high",severity:"critical",redactTemplate:()=>"ghp_[REDACTED]"},{type:"generic_token",regex:/(?:token|TOKEN)\s*[=:]\s*['"]?([a-zA-Z0-9_\-.]{20,80})['"]?/gi,confidence:"low",severity:"medium",redactTemplate:(m)=>{return`token=${(m.match(/[a-zA-Z0-9_\-.]{20,80}/)?.[0]||"").slice(0,4)}...`}},{type:"password",regex:/(?:password|passwd|pwd|PASSWORD|PASSWD)\s*[=:]\s*['"]?([^\s'"]{4,100})['"]?/gi,confidence:"medium",severity:"high",redactTemplate:()=>"password=[REDACTED]"},{type:"private_key",regex:/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/gi,confidence:"high",severity:"critical",redactTemplate:()=>"-----BEGIN PRIVATE KEY-----"},{type:"jwt",regex:/eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*/g,confidence:"high",severity:"high",redactTemplate:(m)=>`eyJ...${m.slice(-10)}`},{type:"stripe_key",regex:/(?:sk|pk)_(?:live|test)_[a-zA-Z0-9]{24,}/gi,confidence:"high",severity:"critical",redactTemplate:()=>"sk_live_[REDACTED]"},{type:"slack_token",regex:/xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*/g,confidence:"high",severity:"critical",redactTemplate:()=>"xoxb-[REDACTED]"},{type:"sendgrid_key",regex:/SG\.[a-zA-Z0-9_-]{22}\.[a-zA-Z0-9_-]{43}/g,confidence:"high",severity:"critical",redactTemplate:()=>"SG.[REDACTED]"},{type:"twilio_key",regex:/SK[a-f0-9]{32}/gi,confidence:"high",severity:"critical",redactTemplate:()=>"SK[REDACTED]"}];O_NOFOLLOW=process.platform!=="win32"?fs66.constants.O_NOFOLLOW:void 0;secretscan=createSwarmTool({description:"Scan directory for potential secrets (API keys, tokens, passwords) using regex patterns and entropy heuristics. Returns metadata-only findings with redacted previews - NEVER returns raw secrets. Excludes common directories (node_modules, .git, dist, etc.) by default. Supports glob patterns (e.g. **/.svelte-kit/**, **/*.test.ts) and reads .secretscanignore at the scan root.",args:{directory:exports_external.string().describe('Directory to scan for secrets (e.g., "." or "./src")'),exclude:exports_external.array(exports_external.string()).optional().describe("Patterns to exclude: plain directory names (e.g. node_modules), relative paths, or globs (e.g. **/.svelte-kit/**, **/*.test.ts). Added to default exclusions.")},async execute(args2,_directory,_ctx){let typedArgs=args2,directory,exclude;try{if(typedArgs&&typeof typedArgs==="object")directory=typedArgs.directory,exclude=typedArgs.exclude}catch{}if(directory===void 0)return JSON.stringify({error:"invalid arguments: directory is required",scan_dir:"",findings:[],count:0,files_scanned:0,skipped_files:0},null,2);let dirValidationError=validateDirectoryInput(directory);if(dirValidationError){let errorResult={error:`invalid directory: ${dirValidationError}`,scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0};return JSON.stringify(errorResult,null,2)}if(exclude)for(let exc of exclude){let err=validateExcludePattern(exc);if(err)return JSON.stringify({error:err,scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0},null,2)}try{let _scanDirRaw=path147.resolve(directory),scanDir=(()=>{try{return fs66.realpathSync(_scanDirRaw)}catch{return _scanDirRaw}})();if(!fs66.existsSync(scanDir))return JSON.stringify({error:"directory not found",scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0},null,2);if(!fs66.statSync(scanDir).isDirectory())return JSON.stringify({error:"target must be a directory, not a file",scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0},null,2);let excludeExact=new Set(DEFAULT_EXCLUDE_DIRS),excludeGlobs=[],ignoreFilePatterns=loadSecretScanIgnore(scanDir),allUserPatterns=[...exclude??[],...ignoreFilePatterns];for(let exc of allUserPatterns){if(exc.length===0)continue;if(isGlobOrPathPattern(exc))excludeGlobs.push(exc);else excludeExact.add(exc)}let stats2={skippedDirs:0,skippedFiles:0,fileErrors:0,symlinkSkipped:0},files=findScannableFiles(scanDir,excludeExact,excludeGlobs,scanDir,new Set,stats2);files.sort((a,b)=>{let aLower=a.toLowerCase(),bLower=b.toLowerCase();if(aLower<bLower)return-1;if(aLower>bLower)return 1;return a.localeCompare(b)});let filesToScan=files.slice(0,MAX_FILES_SCANNED2),allFindings=[],filesScanned=0,skippedFiles=stats2.skippedFiles;for(let filePath of filesToScan){if(allFindings.length>=MAX_FINDINGS2)break;let fileFindings=scanFileForSecrets(filePath);try{if(fs66.statSync(filePath).size>MAX_FILE_SIZE_BYTES3){skippedFiles++;continue}}catch{}filesScanned++;for(let finding of fileFindings){if(allFindings.length>=MAX_FINDINGS2)break;allFindings.push(finding)}}allFindings.sort((a,b)=>{let aPathLower=a.path.toLowerCase(),bPathLower=b.path.toLowerCase();if(aPathLower<bPathLower)return-1;if(aPathLower>bPathLower)return 1;if(a.path<b.path)return-1;if(a.path>b.path)return 1;return a.line-b.line});let result={scan_dir:directory,findings:allFindings,count:allFindings.length,files_scanned:filesScanned,skipped_files:skippedFiles+stats2.fileErrors+stats2.symlinkSkipped},parts=[];if(files.length>MAX_FILES_SCANNED2)parts.push(`Found ${files.length} files, scanned ${MAX_FILES_SCANNED2}`);if(allFindings.length>=MAX_FINDINGS2)parts.push(`Results limited to ${MAX_FINDINGS2} findings`);if(skippedFiles>0||stats2.fileErrors>0||stats2.symlinkSkipped>0)parts.push(`${skippedFiles+stats2.fileErrors+stats2.symlinkSkipped} files skipped (binary/oversized/symlinks/errors)`);if(parts.length>0)result.message=`${parts.join("; ")}.`;let jsonOutput=JSON.stringify(result,null,2);if(jsonOutput.length>MAX_OUTPUT_BYTES3){let truncatedResult={...result,findings:result.findings.slice(0,Math.floor(MAX_OUTPUT_BYTES3*0.8/200)),message:"Output truncated due to size limits."};jsonOutput=JSON.stringify(truncatedResult,null,2)}return jsonOutput}catch(e){let errorResult={error:e instanceof Error?`scan failed: ${e.message||"internal error"}`:"scan failed: unknown error",scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0};return JSON.stringify(errorResult,null,2)}}});_internals104={secretscan,runSecretscan,runSecretscanOnFiles,SECRET_PATTERNS:SECRET_PATTERNS2}});import*as fs67 from"node:fs";import*as path148 from"node:path";function detectFileExists(dir,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs67.readdirSync(dir),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs67.accessSync(path148.join(dir,pattern)),!0}catch{return!1}}function tokenizeCommand(cmd){let out=[],buf="",quote=null;for(let ch of cmd){if(quote){if(ch===quote)quote=null;else buf+=ch;continue}if(ch==='"'||ch==="'"){quote=ch;continue}if(ch===" "||ch==="\t"){if(buf.length>0)out.push(buf),buf="";continue}buf+=ch}if(buf.length>0)out.push(buf);return out}async function defaultSelectTestFramework(profile,dir){let sorted=[...profile.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted){if(!detectFileExists(dir,fw.detect))continue;let argv=tokenizeCommand(fw.cmd);if(argv.length===0)continue;if(!isCommandAvailable(argv[0]))continue;return{name:fw.name,cmd:argv,cwd:dir,detectedVia:fw.detect,filesIgnored:!1}}return null}function defaultBuildTestCommand(profile,framework,files,dir=".",opts={}){let scope=opts.scope??"all",coverage=opts.coverage??!1,bail=opts.bail??!1;switch(framework){case"bun":{let args2=["bun","test"];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"vitest":{let args2=["npx","vitest","run","--reporter=json","--outputFile",".swarm/cache/test-runner-vitest.json"];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"jest":{let args2=["npx","jest","--json"];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"mocha":{let args2=["npx","mocha"];if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"pytest":{let args2=process.platform==="win32"?["python","-m","pytest"]:["python3","-m","pytest"];if(coverage)args2.push("--cov=.","--cov-report=term-missing");if(bail)args2.push("-x");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"cargo":{let args2=["cargo","test"];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"pester":{if(scope!=="all"&&files.length>0){let psCommand=`Invoke-Pester -Path @('${files.map((f)=>f.replace(/'/g,"''").replace(/`/g,"``").replace(/\$/g,"`$")).join("','")}')`;return["pwsh","-EncodedCommand",Buffer.from(psCommand,"utf16le").toString("base64")]}return["pwsh","-Command","Invoke-Pester"]}case"go-test":return["go","test","./..."];case"maven":return["mvn","test"];case"gradle":{let isWindows=process.platform==="win32",hasGradlewBat=fs67.existsSync(path148.join(dir,"gradlew.bat")),hasGradlew=fs67.existsSync(path148.join(dir,"gradlew"));if(hasGradlewBat&&isWindows)return["gradlew.bat","test"];if(hasGradlew)return["./gradlew","test"];return["gradle","test"]}case"dotnet-test":return["dotnet","test"];case"ctest":return["ctest","--test-dir",["build","_build","cmake-build-debug","cmake-build-release","out"].find((d)=>fs67.existsSync(path148.join(dir,d,"CMakeCache.txt")))??"build"];case"swift-test":return["swift","test"];case"dart-test":return isCommandAvailable("flutter")?["flutter","test",...files]:["dart","test",...files];case"rspec":{let args2=isCommandAvailable("bundle")?["bundle","exec","rspec"]:["rspec"];if(bail)args2.push("--fail-fast");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"minitest":if(scope!=="all"&&files.length>0)return["ruby","-Itest","-e",files.map((f)=>`require_relative '${f.replace(/\\/g,"/").replace(/'/g,"\\'")}'`).join("; ")];return["ruby","-Itest","-e",'Dir.glob("test/**/*_test.rb").sort.each { |f| require_relative f }'];case"pest":{let args2=[phpVendorBin2("pest")];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"phpunit":{let args2=[phpVendorBin2("phpunit")];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"php-artisan":{let args2=["php","artisan","test"];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}default:{let fw=profile.test.frameworks.find((f)=>f.name===framework);if(!fw)return null;let argv=tokenizeCommand(fw.cmd);if(argv.length===0)return null;if(files.length===0)return argv;return[...argv,...files]}}}function phpVendorBin2(name){return path148.join("vendor","bin",process.platform==="win32"?`${name}.bat`:name)}function defaultParseTestOutput(framework,stdout,stderr,exitCode){let output=stdout&&stderr?`${stdout}
|
|
1915
|
+
For Rust: rustup component add clippy`},null,2)}}),_internals103={detectAvailableLinter,runLint,detectAdditionalLinter,runAdditionalLint}});import*as fs66 from"node:fs";import*as path147 from"node:path";function calculateShannonEntropy(str){if(str.length===0)return 0;let freq=new Map;for(let char of str)freq.set(char,(freq.get(char)||0)+1);let entropy=0;for(let count of freq.values()){let p=count/str.length;entropy-=p*Math.log2(p)}return entropy}function isHighEntropyString(str){if(str.length<20)return!1;if(str.replace(/[^a-zA-Z0-9]/g,"").length/str.length<0.25)return!1;return calculateShannonEntropy(str)>4}function validateExcludePattern(exc){if(exc.length===0)return null;if(exc.length>MAX_FILE_PATH_LENGTH)return`invalid exclude path: exceeds maximum length of ${MAX_FILE_PATH_LENGTH}`;if(containsControlChars(exc))return"invalid exclude path: contains path traversal or control characters";if(containsPathTraversal(exc))return"invalid exclude path: contains path traversal or control characters";if(exc.startsWith("!"))return"invalid exclude path: negation patterns are not supported";if(exc.startsWith("/")||exc.startsWith("\\"))return"invalid exclude path: absolute paths are not supported";return null}function isGlobOrPathPattern(pattern){return pattern.includes("/")||pattern.includes("\\")||/[*?[\]{}]/.test(pattern)}function loadSecretScanIgnore(scanDir){let ignorePath=path147.join(scanDir,".secretscanignore");try{if(!fs66.existsSync(ignorePath))return[];let content=fs66.readFileSync(ignorePath,"utf8"),patterns=[];for(let rawLine of content.split(/\r?\n/)){let line=rawLine.trim();if(!line||line.startsWith("#"))continue;if(validateExcludePattern(line)===null)patterns.push(line)}return patterns}catch{return[]}}function isExcluded(entry,relPath,exactNames,globPatterns){if(exactNames.has(entry))return!0;for(let pattern of globPatterns)if(path147.matchesGlob(relPath,pattern))return!0;return!1}function validateDirectoryInput(dir){if(!dir||dir.length===0)return"directory is required";if(dir.length>MAX_FILE_PATH_LENGTH)return`directory exceeds maximum length of ${MAX_FILE_PATH_LENGTH}`;if(containsControlChars(dir))return"directory contains control characters";if(containsPathTraversal(dir))return"directory contains path traversal";return null}function isBinaryFile(filePath,buffer){let ext=path147.extname(filePath).toLowerCase();if(DEFAULT_EXCLUDE_EXTENSIONS.has(ext))return!0;if(buffer.length>=BINARY_PREFIX_BYTES){let uint323=buffer.subarray(0,BINARY_PREFIX_BYTES).readUInt32BE(0);for(let sig of BINARY_SIGNATURES)if(uint323===sig)return!0}let nullCount=0,checkLen=Math.min(buffer.length,BINARY_NULL_CHECK_BYTES);for(let i=0;i<checkLen;i++)if(buffer[i]===0)nullCount++;return nullCount>checkLen*BINARY_NULL_THRESHOLD}function scanLineForSecrets(line,_lineNum){let results=[];for(let pattern of SECRET_PATTERNS2){pattern.regex.lastIndex=0;for(let match=pattern.regex.exec(line);match!==null;match=pattern.regex.exec(line)){let fullMatch=match[0],redacted=pattern.redactTemplate(fullMatch);if(results.push({type:pattern.type,confidence:pattern.confidence,severity:pattern.severity,redacted,matchStart:match.index,matchEnd:match.index+fullMatch.length}),match.index===pattern.regex.lastIndex)pattern.regex.lastIndex++}}let valueMatch=line.match(/((?:secret|key|token|password|cred|credential))\s*[=:]\s*["']?([a-zA-Z0-9+/=_-]{20,100})["']?/i);if(valueMatch&&isHighEntropyString(valueMatch[2])){let matchStart=valueMatch.index||0,matchEnd=matchStart+valueMatch[0].length;if(!results.some((r)=>!(r.matchEnd<=matchStart||r.matchStart>=matchEnd)))results.push({type:"high_entropy",confidence:"low",severity:"medium",redacted:`${valueMatch[1]}=[HIGH_ENTROPY]`,matchStart,matchEnd})}return results}function createRedactedContext(line,findings){if(findings.length===0)return"";let sorted=[...findings].sort((a,b)=>a.matchStart-b.matchStart),result="",lastEnd=0;for(let finding of sorted){if(finding.matchEnd<=lastEnd)continue;if(finding.matchStart>=lastEnd)result+=line.slice(lastEnd,finding.matchStart),result+="[REDACTED]";lastEnd=Math.max(lastEnd,finding.matchEnd)}if(result+=line.slice(lastEnd),result.length<=MAX_CONTEXT_CHARS)return result;let truncationMarker="...[context truncated]...",edgeLength=Math.floor((MAX_CONTEXT_CHARS-truncationMarker.length)/2),remaining=MAX_CONTEXT_CHARS-truncationMarker.length-edgeLength;return`${result.slice(0,edgeLength)}${truncationMarker}${result.slice(-remaining)}`}function readBoundedFile(filePath){let fd;try{let flags=fs66.constants.O_RDONLY|(O_NOFOLLOW!==void 0?O_NOFOLLOW:0);fd=_internals104.openFile(filePath,flags)}catch{return{status:"incomplete",reason:"read_error"}}let outcome;try{let stat13=_internals104.fstatFile(fd),initialSize=stat13.size;if(!stat13.isFile())outcome={status:"incomplete",reason:"non_file"};else{let bufferLength=Math.min(initialSize+1,MAX_FILE_SIZE_BYTES3+1),buffer=Buffer.allocUnsafe(bufferLength),bytesRead=0;while(bytesRead<buffer.length){let count=_internals104.readFileChunk(fd,buffer,bytesRead,buffer.length-bytesRead,null);if(count===0)break;bytesRead+=count}let postStat=_internals104.fstatFile(fd);if(postStat.size!==initialSize)outcome={status:"incomplete",reason:postStat.size>MAX_FILE_SIZE_BYTES3?"oversized":"read_error"};else outcome={status:"ok",buffer:buffer.subarray(0,bytesRead),truncated:initialSize>MAX_FILE_SIZE_BYTES3}}}catch{outcome={status:"incomplete",reason:"read_error"}}try{_internals104.closeFile(fd)}catch{return{status:"incomplete",reason:"read_error"}}return outcome}function scanFileForSecrets(filePath,mode){let findings=[];try{let lstat6=fs66.lstatSync(filePath);if(lstat6.isSymbolicLink())return mode==="explicit"?{status:"incomplete",reason:"symlink"}:{status:"skipped",reason:"symlink"};if(!lstat6.isFile())return{status:"incomplete",reason:"non_file"};let readOutcome=readBoundedFile(filePath);if(readOutcome.status==="incomplete")return readOutcome;let{buffer,truncated}=readOutcome;if(isBinaryFile(filePath,buffer))return{status:"skipped",reason:"binary"};if(truncated)return{status:"incomplete",reason:"oversized"};let content;if(buffer.length>=3&&buffer[0]===239&&buffer[1]===187&&buffer[2]===191)content=buffer.slice(3).toString("utf-8");else content=buffer.toString("utf-8");if(content.includes("\x00"))return{status:"skipped",reason:"binary"};let lines=content.split(`
|
|
1916
|
+
`);for(let i=0;i<lines.length;i++){if(mode==="standalone"&&lines[i].length>MAX_LONG_LINE_CHARS)continue;let lineResults=scanLineForSecrets(lines[i],i+1),context=createRedactedContext(lines[i],lineResults);for(let result of lineResults)findings.push({path:filePath,line:i+1,type:result.type,confidence:result.confidence,severity:result.severity,redacted:result.redacted,context})}return{status:"scanned",findings}}catch{return{status:"incomplete",reason:"read_error"}}}function assertNever3(value){throw Error(`Unhandled secretscan outcome: ${String(value)}`)}async function yieldToEventLoop2(){await new Promise((resolve57)=>setImmediate(resolve57))}function serializeSecretscanResult(result){let findings=result.findings,candidate=result,json3=JSON.stringify(candidate,null,2);while(Buffer.byteLength(json3,"utf8")>MAX_OUTPUT_BYTES3&&findings.length>0)findings=findings.slice(0,Math.floor(findings.length/2)),candidate={...result,findings,message:"Output truncated due to size limits."},json3=JSON.stringify(candidate,null,2);if(Buffer.byteLength(json3,"utf8")>MAX_OUTPUT_BYTES3)candidate={...result,findings:[],message:"Output truncated due to size limits."},json3=JSON.stringify(candidate,null,2);return json3}function isSymlinkLoop(realPath,visited){if(visited.has(realPath))return!0;return visited.add(realPath),!1}function isPathWithinScope(realPath,scanDir){let resolvedScanDir=path147.resolve(scanDir),resolvedRealPath=path147.resolve(realPath);return resolvedRealPath===resolvedScanDir||resolvedRealPath.startsWith(resolvedScanDir+path147.sep)||resolvedRealPath.startsWith(`${resolvedScanDir}/`)||resolvedRealPath.startsWith(`${resolvedScanDir}\\`)}function toSafeRelativePath(rootDir,targetPath){let relative31=path147.relative(rootDir,targetPath).replace(/\\/g,"/");if(!relative31||relative31===".")return".";if(relative31.startsWith("..")||path147.isAbsolute(relative31))return path147.basename(targetPath).replace(/\\/g,"/")||".";return relative31}function recordIncompletePath(target,rootDir,targetPath,reason){if(target.length>=MAX_INCOMPLETE_PATHS){target[MAX_INCOMPLETE_PATHS-1]={path:".",reason:"truncated"};return}target.push({path:toSafeRelativePath(rootDir,targetPath),reason})}function compareFilePaths(a,b){let aLower=a.toLowerCase(),bLower=b.toLowerCase();if(aLower<bLower)return-1;if(aLower>bLower)return 1;if(a<b)return-1;if(a>b)return 1;return 0}function addBoundedCandidate(state,filePath){state.totalCandidates++;let heap=state.files;if(heap.length<MAX_FILES_SCANNED2){heap.push(filePath);let index2=heap.length-1;while(index2>0){let parent=Math.floor((index2-1)/2);if(compareFilePaths(heap[parent],heap[index2])>=0)break;[heap[parent],heap[index2]]=[heap[index2],heap[parent]],index2=parent}return}if(compareFilePaths(filePath,heap[0])>=0)return;heap[0]=filePath;let index=0;while(!0){let left=index*2+1,right=left+1,largest=index;if(left<heap.length&&compareFilePaths(heap[left],heap[largest])>0)largest=left;if(right<heap.length&&compareFilePaths(heap[right],heap[largest])>0)largest=right;if(largest===index)break;[heap[index],heap[largest]]=[heap[largest],heap[index]],index=largest}}async function collectScannableFiles(dir,excludeExact,excludeGlobs,scanDir,visited,stats2,state){let pending=[dir];while(pending.length>0){if(state.deadlineExceeded||state.cleanupFailed)return;let currentDir=pending.pop();if(!currentDir)continue;let directory;try{directory=fs66.opendirSync(currentDir)}catch{stats2.fileErrors++,recordIncompletePath(state.incompletePaths,scanDir,currentDir,"read_error");continue}let stoppedEarly=!1;try{while(!0){if(state.entriesSinceYield>=DISCOVERY_YIELD_INTERVAL){if(state.entriesSinceYield=0,await _internals104.yieldToEventLoop(),_internals104.now()>=state.deadline){state.deadlineExceeded=!0,recordIncompletePath(state.incompletePaths,scanDir,currentDir,"deadline"),stoppedEarly=!0;break}}let entry=directory.readSync();if(!entry)break;state.entriesSinceYield++;let fullPath=path147.join(currentDir,entry.name),relPath=path147.relative(scanDir,fullPath).replace(/\\/g,"/");if(isExcluded(entry.name,relPath,excludeExact,excludeGlobs)){stats2.skippedDirs++;continue}let lstat6;try{lstat6=fs66.lstatSync(fullPath)}catch{stats2.fileErrors++,recordIncompletePath(state.incompletePaths,scanDir,fullPath,"read_error");continue}if(lstat6.isSymbolicLink()){stats2.symlinkSkipped++;continue}if(lstat6.isDirectory()){if(state.directoriesQueued>=MAX_DISCOVERY_DIRECTORIES){state.unexaminedDirectories++,recordIncompletePath(state.incompletePaths,scanDir,fullPath,"directory_limit");continue}let realPath;try{realPath=fs66.realpathSync(fullPath)}catch{stats2.fileErrors++,recordIncompletePath(state.incompletePaths,scanDir,fullPath,"read_error");continue}if(isSymlinkLoop(realPath,visited)||!isPathWithinScope(realPath,scanDir)){stats2.symlinkSkipped++;continue}pending.push(fullPath),state.directoriesQueued++}else if(lstat6.isFile()){let ext=path147.extname(fullPath).toLowerCase();if(!DEFAULT_EXCLUDE_EXTENSIONS.has(ext))addBoundedCandidate(state,fullPath);else stats2.skippedFiles++}else stats2.fileErrors++,recordIncompletePath(state.incompletePaths,scanDir,fullPath,"non_file")}}finally{try{_internals104.closeDirectory(directory)}catch(error93){if(error93.code!=="ERR_DIR_CLOSED")state.cleanupFailed=!0,recordIncompletePath(state.incompletePaths,scanDir,currentDir,"cleanup_failed")}}if(stoppedEarly)break}}async function runSecretscan(directory){try{let result=await _internals104.secretscan.execute({directory},{}),jsonStr=typeof result==="string"?result:result.output;return JSON.parse(jsonStr)}catch(e){return{error:e instanceof Error?`scan failed: ${e.message}`:"scan failed: unknown error",scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0}}}async function runSecretscanOnFiles(files,directory){try{let findings=[],filesScanned=0,skippedFiles=0,incompletePaths=[],rawRoot=path147.resolve(directory),canonicalRoot=(()=>{try{return fs66.realpathSync(rawRoot)}catch{return rawRoot}})(),rootStat;try{rootStat=fs66.lstatSync(canonicalRoot)}catch(error93){let err=error93;return{error:err.code==="ENOENT"?"directory not found":`scan failed: ${err.message||"unable to inspect directory"}`,scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0}}if(!rootStat.isDirectory())throw Error("target must be a directory");let filesToScan=files.slice(0,MAX_EXPLICIT_FILES_SCANNED),incompleteFiles=Math.max(0,files.length-filesToScan.length);if(files.length>filesToScan.length)recordIncompletePath(incompletePaths,canonicalRoot,canonicalRoot,"max_files");let deadline=_internals104.now()+SCAN_TIME_BUDGET_MS;await _internals104.yieldToEventLoop();for(let index=0;index<filesToScan.length;index++){if(_internals104.now()>=deadline){for(let remaining of filesToScan.slice(index)){let remainingPath=path147.isAbsolute(remaining)?path147.resolve(remaining):path147.resolve(rawRoot,remaining);recordIncompletePath(incompletePaths,canonicalRoot,remainingPath,"deadline")}incompleteFiles+=filesToScan.length-index;break}if(findings.length>=MAX_FINDINGS2){recordIncompletePath(incompletePaths,canonicalRoot,canonicalRoot,"truncated"),incompleteFiles+=filesToScan.length-index;break}let file3=filesToScan[index];if(typeof file3!=="string"){skippedFiles++;continue}let resolvedPath=path147.isAbsolute(file3)?path147.resolve(file3):path147.resolve(rawRoot,file3);if(!isPathWithinScope(resolvedPath,rawRoot)){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"scope_escape");continue}let lstat6;try{lstat6=_internals104.lstatFile(resolvedPath)}catch(error93){if(error93.code==="ENOENT"){skippedFiles++;continue}skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"read_error");continue}if(lstat6.isSymbolicLink()){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"symlink");continue}if(!lstat6.isFile()){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"non_file");continue}let ext=path147.extname(resolvedPath).toLowerCase();if(DEFAULT_EXCLUDE_EXTENSIONS.has(ext)){skippedFiles++;continue}let scanPath=resolvedPath;try{scanPath=fs66.realpathSync(resolvedPath)}catch(error93){if(error93.code==="ENOENT"){skippedFiles++;continue}skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"read_error");continue}if(!isPathWithinScope(scanPath,canonicalRoot)){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,scanPath,"scope_escape");continue}let outcome=scanFileForSecrets(scanPath,"explicit");switch(outcome.status){case"scanned":if(filesScanned++,findings.push(...outcome.findings),findings.length>MAX_FINDINGS2)findings.length=MAX_FINDINGS2;break;case"skipped":skippedFiles++;break;case"incomplete":skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,scanPath,outcome.reason);break;default:assertNever3(outcome)}if(index+1<filesToScan.length)await _internals104.yieldToEventLoop()}return findings.sort((a,b)=>{if(a.path<b.path)return-1;if(a.path>b.path)return 1;return a.line-b.line}),{scan_dir:directory,findings,count:findings.length,files_scanned:filesScanned,skipped_files:skippedFiles,incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}}catch(e){return{error:e instanceof Error?`scan failed: ${e.message}`:"scan failed: unknown error",scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0}}}var MAX_FILE_PATH_LENGTH=500,MAX_FILE_SIZE_BYTES3=524288,MAX_FILES_SCANNED2=1000,MAX_EXPLICIT_FILES_SCANNED=100,MAX_FINDINGS2=100,MAX_OUTPUT_BYTES3=512000,MAX_CONTEXT_CHARS=1000,MAX_LONG_LINE_CHARS=1e4,MAX_INCOMPLETE_PATHS=25,MAX_DISCOVERY_DIRECTORIES=1e4,SCAN_TIME_BUDGET_MS=55000,BINARY_SIGNATURES,BINARY_PREFIX_BYTES=4,BINARY_NULL_CHECK_BYTES=8192,BINARY_NULL_THRESHOLD=0.1,DEFAULT_EXCLUDE_DIRS,DEFAULT_EXCLUDE_EXTENSIONS,SECRET_PATTERNS2,O_NOFOLLOW,DISCOVERY_YIELD_INTERVAL=100,secretscan,_internals104;var init_secretscan=__esm(()=>{init_zod();init_path_security();init_create_tool();BINARY_SIGNATURES=[0,2303741511,4292411360,1195984440,626017350,1347093252],DEFAULT_EXCLUDE_DIRS=new Set(["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".cache","vendor",".svn",".hg",".gradle","target","__pycache__",".pytest_cache",".venv","venv",".env",".idea",".vscode"]),DEFAULT_EXCLUDE_EXTENSIONS=new Set([".png",".jpg",".jpeg",".gif",".ico",".svg",".pdf",".zip",".tar",".gz",".rar",".7z",".wasm",".exe",".dll",".so",".dylib",".bin",".dat",".db",".sqlite",".lock",".log",".md"]),SECRET_PATTERNS2=[{type:"aws_access_key",regex:/(?:AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|aws_access_key_id|aws_secret_access_key)\s*[=:]\s*['"]?([A-Z0-9]{20})['"]?/gi,confidence:"high",severity:"critical",redactTemplate:()=>"AKIA[REDACTED]"},{type:"aws_secret_key",regex:/(?:AWS_SECRET_ACCESS_KEY|aws_secret_access_key)\s*[=:]\s*['"]?([A-Za-z0-9+/=]{40})['"]?/gi,confidence:"high",severity:"critical",redactTemplate:()=>"[REDACTED_AWS_SECRET]"},{type:"api_key",regex:/(?:api[_-]?key|apikey|API[_-]?KEY)\s*[=:]\s*['"]?([a-zA-Z0-9_-]{16,64})['"]?/gi,confidence:"medium",severity:"high",redactTemplate:(m)=>{let key=m.match(/[a-zA-Z0-9_-]{16,64}/)?.[0]||"";return`api_key=${key.slice(0,4)}...${key.slice(-4)}`}},{type:"bearer_token",regex:/(?:bearer\s+|Bearer\s+)([a-zA-Z0-9_\-.]{1,200})[\s"'<]/gi,confidence:"medium",severity:"high",redactTemplate:()=>"bearer [REDACTED]"},{type:"basic_auth",regex:/(?:basic\s+|Basic\s+)([a-zA-Z0-9+/=]{1,200})[\s"'<]/gi,confidence:"medium",severity:"high",redactTemplate:()=>"basic [REDACTED]"},{type:"database_url",regex:/(?:mysql|postgres|postgresql|mongodb|redis):\/\/[^\s"'/:]+:[^\s"'/:]+@[^\s"']+/gi,confidence:"high",severity:"critical",redactTemplate:()=>"mysql://[user]:[password]@[host]"},{type:"github_token",regex:/(?:ghp|gho|ghu|ghs|ghr)_[a-zA-Z0-9]{36,}/gi,confidence:"high",severity:"critical",redactTemplate:()=>"ghp_[REDACTED]"},{type:"generic_token",regex:/(?:token|TOKEN)\s*[=:]\s*['"]?([a-zA-Z0-9_\-.]{20,80})['"]?/gi,confidence:"low",severity:"medium",redactTemplate:(m)=>{return`token=${(m.match(/[a-zA-Z0-9_\-.]{20,80}/)?.[0]||"").slice(0,4)}...`}},{type:"password",regex:/(?:password|passwd|pwd|PASSWORD|PASSWD)\s*[=:]\s*['"]?([^\s'"]{4,100})['"]?/gi,confidence:"medium",severity:"high",redactTemplate:()=>"password=[REDACTED]"},{type:"private_key",regex:/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/gi,confidence:"high",severity:"critical",redactTemplate:()=>"-----BEGIN PRIVATE KEY-----"},{type:"jwt",regex:/eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*/g,confidence:"high",severity:"high",redactTemplate:(m)=>`eyJ...${m.slice(-10)}`},{type:"stripe_key",regex:/(?:sk|pk)_(?:live|test)_[a-zA-Z0-9]{24,}/gi,confidence:"high",severity:"critical",redactTemplate:()=>"sk_live_[REDACTED]"},{type:"slack_token",regex:/xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*/g,confidence:"high",severity:"critical",redactTemplate:()=>"xoxb-[REDACTED]"},{type:"sendgrid_key",regex:/SG\.[a-zA-Z0-9_-]{22}\.[a-zA-Z0-9_-]{43}/g,confidence:"high",severity:"critical",redactTemplate:()=>"SG.[REDACTED]"},{type:"twilio_key",regex:/SK[a-f0-9]{32}/gi,confidence:"high",severity:"critical",redactTemplate:()=>"SK[REDACTED]"}];O_NOFOLLOW=process.platform!=="win32"?fs66.constants.O_NOFOLLOW:void 0;secretscan=createSwarmTool({description:"Scan directory for potential secrets (API keys, tokens, passwords) using regex patterns and entropy heuristics. Returns metadata-only findings with redacted previews - NEVER returns raw secrets. Excludes common directories (node_modules, .git, dist, etc.) by default. Supports glob patterns (e.g. **/.svelte-kit/**, **/*.test.ts) and reads .secretscanignore at the scan root.",args:{directory:exports_external.string().describe('Directory to scan for secrets (e.g., "." or "./src")'),exclude:exports_external.array(exports_external.string()).optional().describe("Patterns to exclude: plain directory names (e.g. node_modules), relative paths, or globs (e.g. **/.svelte-kit/**, **/*.test.ts). Added to default exclusions.")},async execute(args2,_directory,_ctx){let typedArgs=args2,directory,exclude;try{if(typedArgs&&typeof typedArgs==="object")directory=typedArgs.directory,exclude=typedArgs.exclude}catch{}if(directory===void 0)return JSON.stringify({error:"invalid arguments: directory is required",scan_dir:"",findings:[],count:0,files_scanned:0,skipped_files:0},null,2);let dirValidationError=validateDirectoryInput(directory);if(dirValidationError){let errorResult={error:`invalid directory: ${dirValidationError}`,scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0};return JSON.stringify(errorResult,null,2)}if(exclude)for(let exc of exclude){let err=validateExcludePattern(exc);if(err)return JSON.stringify({error:err,scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0},null,2)}try{let scanDirRaw=path147.resolve(directory),scanDir=(()=>{try{return fs66.realpathSync(scanDirRaw)}catch{return scanDirRaw}})(),dirStat;try{dirStat=fs66.lstatSync(scanDir)}catch(error93){let err=error93,errorResult={error:err.code==="ENOENT"?"directory not found":`scan failed: ${err.message||"unable to inspect directory"}`,scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0};return JSON.stringify(errorResult,null,2)}if(!dirStat.isDirectory())return JSON.stringify({error:"target must be a directory, not a file",scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0},null,2);let excludeExact=new Set(DEFAULT_EXCLUDE_DIRS),excludeGlobs=[],ignoreFilePatterns=loadSecretScanIgnore(scanDir),allUserPatterns=[...exclude??[],...ignoreFilePatterns];for(let exc of allUserPatterns){if(exc.length===0)continue;if(isGlobOrPathPattern(exc))excludeGlobs.push(exc);else excludeExact.add(exc)}let stats2={skippedDirs:0,skippedFiles:0,fileErrors:0,symlinkSkipped:0},visited=new Set,deadline=_internals104.now()+SCAN_TIME_BUDGET_MS,discovery={files:[],totalCandidates:0,deadline,deadlineExceeded:!1,cleanupFailed:!1,entriesSinceYield:0,incompletePaths:[],directoriesQueued:1,unexaminedDirectories:0};await _internals104.yieldToEventLoop(),await collectScannableFiles(scanDir,excludeExact,excludeGlobs,scanDir,visited,stats2,discovery);let files=discovery.files;files.sort(compareFilePaths);let filesToScan=files;if(discovery.totalCandidates>filesToScan.length)recordIncompletePath(discovery.incompletePaths,scanDir,scanDir,"max_files");if(discovery.deadlineExceeded)recordIncompletePath(discovery.incompletePaths,scanDir,scanDir,"deadline");if(discovery.cleanupFailed)recordIncompletePath(discovery.incompletePaths,scanDir,scanDir,"cleanup_failed");let allFindings=[],filesScanned=0,skippedFiles=stats2.skippedFiles,incompleteFiles=stats2.fileErrors+Math.max(0,discovery.totalCandidates-filesToScan.length)+(discovery.deadlineExceeded||discovery.cleanupFailed?1:0)+discovery.unexaminedDirectories;for(let index=0;index<filesToScan.length;index++){if(_internals104.now()>=deadline){for(let remaining of filesToScan.slice(index))recordIncompletePath(discovery.incompletePaths,scanDir,remaining,"deadline");incompleteFiles+=filesToScan.length-index;break}if(allFindings.length>=MAX_FINDINGS2){recordIncompletePath(discovery.incompletePaths,scanDir,scanDir,"truncated"),incompleteFiles+=filesToScan.length-index;break}let outcome=scanFileForSecrets(filesToScan[index],"standalone");switch(outcome.status){case"scanned":filesScanned++;break;case"skipped":skippedFiles++;break;case"incomplete":skippedFiles++,incompleteFiles++,recordIncompletePath(discovery.incompletePaths,scanDir,filesToScan[index],outcome.reason);break;default:assertNever3(outcome)}if(outcome.status==="scanned")for(let finding of outcome.findings){if(allFindings.length>=MAX_FINDINGS2)break;allFindings.push(finding)}if(index+1<filesToScan.length)await _internals104.yieldToEventLoop()}allFindings.sort((a,b)=>{let aPathLower=a.path.toLowerCase(),bPathLower=b.path.toLowerCase();if(aPathLower<bPathLower)return-1;if(aPathLower>bPathLower)return 1;if(a.path<b.path)return-1;if(a.path>b.path)return 1;return a.line-b.line});let result={scan_dir:directory,findings:allFindings,count:allFindings.length,files_scanned:filesScanned,skipped_files:skippedFiles+stats2.fileErrors+stats2.symlinkSkipped,incomplete_files:incompleteFiles,incomplete_paths:discovery.incompletePaths},parts=[];if(discovery.totalCandidates>MAX_FILES_SCANNED2)parts.push(`Found ${discovery.totalCandidates} files, selected ${MAX_FILES_SCANNED2}`);if(discovery.deadlineExceeded)parts.push("Discovery stopped at the scan deadline");if(discovery.cleanupFailed)parts.push("Discovery directory cleanup failed");if(allFindings.length>=MAX_FINDINGS2)parts.push(`Results limited to ${MAX_FINDINGS2} findings`);if(incompleteFiles>0)parts.push(`${incompleteFiles} files were not completely scanned`);if(skippedFiles>0||stats2.fileErrors>0||stats2.symlinkSkipped>0)parts.push(`${skippedFiles+stats2.fileErrors+stats2.symlinkSkipped} files skipped (binary/oversized/symlinks/errors)`);if(parts.length>0)result.message=`${parts.join("; ")}.`;return serializeSecretscanResult(result)}catch(e){let errorResult={error:e instanceof Error?`scan failed: ${e.message||"internal error"}`:"scan failed: unknown error",scan_dir:directory,findings:[],count:0,files_scanned:0,skipped_files:0};return JSON.stringify(errorResult,null,2)}}});_internals104={secretscan,runSecretscan,runSecretscanOnFiles,SECRET_PATTERNS:SECRET_PATTERNS2,now:Date.now,yieldToEventLoop:yieldToEventLoop2,openFile:fs66.openSync,fstatFile:fs66.fstatSync,readFileChunk:fs66.readSync,closeFile:fs66.closeSync,lstatFile:fs66.lstatSync,closeDirectory:(directory)=>directory.closeSync()}});import*as fs67 from"node:fs";import*as path148 from"node:path";function detectFileExists(dir,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs67.readdirSync(dir),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs67.accessSync(path148.join(dir,pattern)),!0}catch{return!1}}function tokenizeCommand(cmd){let out=[],buf="",quote=null;for(let ch of cmd){if(quote){if(ch===quote)quote=null;else buf+=ch;continue}if(ch==='"'||ch==="'"){quote=ch;continue}if(ch===" "||ch==="\t"){if(buf.length>0)out.push(buf),buf="";continue}buf+=ch}if(buf.length>0)out.push(buf);return out}async function defaultSelectTestFramework(profile,dir){let sorted=[...profile.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted){if(!detectFileExists(dir,fw.detect))continue;let argv=tokenizeCommand(fw.cmd);if(argv.length===0)continue;if(!isCommandAvailable(argv[0]))continue;return{name:fw.name,cmd:argv,cwd:dir,detectedVia:fw.detect,filesIgnored:!1}}return null}function defaultBuildTestCommand(profile,framework,files,dir=".",opts={}){let scope=opts.scope??"all",coverage=opts.coverage??!1,bail=opts.bail??!1;switch(framework){case"bun":{let args2=["bun","test"];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"vitest":{let args2=["npx","vitest","run","--reporter=json","--outputFile",".swarm/cache/test-runner-vitest.json"];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"jest":{let args2=["npx","jest","--json"];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"mocha":{let args2=["npx","mocha"];if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"pytest":{let args2=process.platform==="win32"?["python","-m","pytest"]:["python3","-m","pytest"];if(coverage)args2.push("--cov=.","--cov-report=term-missing");if(bail)args2.push("-x");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"cargo":{let args2=["cargo","test"];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"pester":{if(scope!=="all"&&files.length>0){let psCommand=`Invoke-Pester -Path @('${files.map((f)=>f.replace(/'/g,"''").replace(/`/g,"``").replace(/\$/g,"`$")).join("','")}')`;return["pwsh","-EncodedCommand",Buffer.from(psCommand,"utf16le").toString("base64")]}return["pwsh","-Command","Invoke-Pester"]}case"go-test":return["go","test","./..."];case"maven":return["mvn","test"];case"gradle":{let isWindows=process.platform==="win32",hasGradlewBat=fs67.existsSync(path148.join(dir,"gradlew.bat")),hasGradlew=fs67.existsSync(path148.join(dir,"gradlew"));if(hasGradlewBat&&isWindows)return["gradlew.bat","test"];if(hasGradlew)return["./gradlew","test"];return["gradle","test"]}case"dotnet-test":return["dotnet","test"];case"ctest":return["ctest","--test-dir",["build","_build","cmake-build-debug","cmake-build-release","out"].find((d)=>fs67.existsSync(path148.join(dir,d,"CMakeCache.txt")))??"build"];case"swift-test":return["swift","test"];case"dart-test":return isCommandAvailable("flutter")?["flutter","test",...files]:["dart","test",...files];case"rspec":{let args2=isCommandAvailable("bundle")?["bundle","exec","rspec"]:["rspec"];if(bail)args2.push("--fail-fast");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"minitest":if(scope!=="all"&&files.length>0)return["ruby","-Itest","-e",files.map((f)=>`require_relative '${f.replace(/\\/g,"/").replace(/'/g,"\\'")}'`).join("; ")];return["ruby","-Itest","-e",'Dir.glob("test/**/*_test.rb").sort.each { |f| require_relative f }'];case"pest":{let args2=[phpVendorBin2("pest")];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"phpunit":{let args2=[phpVendorBin2("phpunit")];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"php-artisan":{let args2=["php","artisan","test"];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}default:{let fw=profile.test.frameworks.find((f)=>f.name===framework);if(!fw)return null;let argv=tokenizeCommand(fw.cmd);if(argv.length===0)return null;if(files.length===0)return argv;return[...argv,...files]}}}function phpVendorBin2(name){return path148.join("vendor","bin",process.platform==="win32"?`${name}.bat`:name)}function defaultParseTestOutput(framework,stdout,stderr,exitCode){let output=stdout&&stderr?`${stdout}
|
|
1917
1917
|
${stderr}`:stdout||stderr||"",passed=0,failed=0,skipped=0,total,coveragePercent;switch(framework){case"vitest":case"jest":case"bun":{let jsonMatch=output.match(/\{[\s\S]*"testResults"[\s\S]*\}/);if(jsonMatch)try{let parsed=JSON.parse(jsonMatch[0]);if(parsed.numTotalTests!==void 0)passed=parsed.numPassedTests||0,failed=parsed.numFailedTests||0,skipped=parsed.numPendingTests||0,total=parsed.numTotalTests||0;if(parsed.coverage!==void 0)coveragePercent=parsed.coverage}catch{}if(total===void 0||total===0){let passMatch=output.match(/(\d+)\s+pass(ing|ed)?/),failMatch=output.match(/(\d+)\s+fail(ing|ed)?/),skipMatch=output.match(/(\d+)\s+skip(ping|ped)?/);if(passMatch)passed=parseInt(passMatch[1],10);if(failMatch)failed=parseInt(failMatch[1],10);if(skipMatch)skipped=parseInt(skipMatch[1],10);total=passed+failed+skipped}let coverageMatch=output.match(/All files[^\d]*(\d+\.?\d*)\s*%/);if(coveragePercent===void 0&&coverageMatch)coveragePercent=parseFloat(coverageMatch[1]);break}case"mocha":{let passMatch=output.match(/(\d+)\s+passing/),failMatch=output.match(/(\d+)\s+failing/),pendingMatch=output.match(/(\d+)\s+pending/);if(passMatch)passed=parseInt(passMatch[1],10);if(failMatch)failed=parseInt(failMatch[1],10);if(pendingMatch)skipped=parseInt(pendingMatch[1],10);total=passed+failed+skipped;break}case"pytest":{let passMatch=output.match(/(\d+)\s+passed/),failMatch=output.match(/(\d+)\s+failed/),skipMatch=output.match(/(\d+)\s+skipped/);if(passMatch)passed=parseInt(passMatch[1],10);if(failMatch)failed=parseInt(failMatch[1],10);if(skipMatch)skipped=parseInt(skipMatch[1],10);total=passed+failed+skipped;let coverageMatch=output.match(/TOTAL\s+(\d+\.?\d*)\s*%/);if(coverageMatch)coveragePercent=parseFloat(coverageMatch[1]);break}case"cargo":{let passMatch=output.match(/test result: ok\. (\d+) passed/),failMatch=output.match(/test result: FAILED\. (\d+) passed; (\d+) failed/);if(failMatch)passed=parseInt(failMatch[1],10),failed=parseInt(failMatch[2],10);else if(passMatch)passed=parseInt(passMatch[1],10);total=passed+failed;break}case"pester":{let passMatch=output.match(/Passed:\s*(\d+)/),failMatch=output.match(/Failed:\s*(\d+)/),skipMatch=output.match(/Skipped:\s*(\d+)/);if(passMatch)passed=parseInt(passMatch[1],10);if(failMatch)failed=parseInt(failMatch[1],10);if(skipMatch)skipped=parseInt(skipMatch[1],10);total=passed+failed+skipped;break}case"go-test":{let passMatches=[...output.matchAll(/--- PASS:/g)],failMatches=[...output.matchAll(/--- FAIL:/g)],skipMatches=[...output.matchAll(/--- SKIP:/g)];passed=passMatches.length,failed=failMatches.length,skipped=skipMatches.length,total=passed+failed+skipped;let covMatch=output.match(/coverage:\s*(\d+\.?\d*)\s*%/);if(covMatch)coveragePercent=parseFloat(covMatch[1]);break}case"maven":{let mavenMatch=output.match(/Tests run:\s*(\d+),\s*Failures:\s*(\d+),\s*Errors:\s*(\d+),\s*Skipped:\s*(\d+)/);if(mavenMatch){let tot=parseInt(mavenMatch[1],10),failures=parseInt(mavenMatch[2],10),errors5=parseInt(mavenMatch[3],10),sk=parseInt(mavenMatch[4],10);failed=failures+errors5,skipped=sk,passed=tot-failed-sk,total=tot}break}case"gradle":{let gradleMatch=output.match(/(\d+) tests? completed(?:,\s*(\d+) failed)?(?:,\s*(\d+) skipped)?/);if(gradleMatch)total=parseInt(gradleMatch[1],10),failed=gradleMatch[2]?parseInt(gradleMatch[2],10):0,skipped=gradleMatch[3]?parseInt(gradleMatch[3],10):0,passed=total-failed-skipped;break}case"dotnet-test":{let passMatch=output.match(/Passed[!:]?\s*(\d+)/i),failMatch=output.match(/Failed[!:]?\s*(\d+)/i),skipMatch=output.match(/Skipped[!:]?\s*(\d+)/i);if(passMatch)passed=parseInt(passMatch[1],10);if(failMatch)failed=parseInt(failMatch[1],10);if(skipMatch)skipped=parseInt(skipMatch[1],10);total=passed+failed+skipped;break}case"ctest":{let ctestMatch=output.match(/(\d+) tests? failed out of (\d+)/);if(ctestMatch)failed=parseInt(ctestMatch[1],10),total=parseInt(ctestMatch[2],10),passed=total-failed;else{let allPassMatch=output.match(/100% tests passed.*?(\d+) tests?/);if(allPassMatch)total=parseInt(allPassMatch[1],10),passed=total}break}case"swift-test":{let swiftMatch=output.match(/Executed (\d+) tests?,\s*with (\d+) failures?/);if(swiftMatch)total=parseInt(swiftMatch[1],10),failed=parseInt(swiftMatch[2],10),passed=total-failed;break}case"dart-test":{let dartPassMatch=output.match(/\+(\d+):\s*All tests passed/),dartMixMatch=output.match(/\+(\d+)\s+-(\d+):/);if(dartPassMatch)passed=parseInt(dartPassMatch[1],10),total=passed;else if(dartMixMatch)passed=parseInt(dartMixMatch[1],10),failed=parseInt(dartMixMatch[2],10),total=passed+failed;break}case"rspec":{let rspecMatch=output.match(/(\d+) examples?,\s*(\d+) failures?(?:,\s*(\d+) pending)?/);if(rspecMatch)total=parseInt(rspecMatch[1],10),failed=parseInt(rspecMatch[2],10),skipped=rspecMatch[3]?parseInt(rspecMatch[3],10):0,passed=total-failed-skipped;break}case"minitest":{let minitestMatch=output.match(/(\d+) runs?,\s*\d+ assertions?,\s*(\d+) failures?,\s*(\d+) errors?,\s*(\d+) skips?/);if(minitestMatch){total=parseInt(minitestMatch[1],10);let failures=parseInt(minitestMatch[2],10),errors5=parseInt(minitestMatch[3],10);skipped=parseInt(minitestMatch[4],10),failed=failures+errors5,passed=total-failed-skipped}break}case"pest":case"phpunit":case"php-artisan":{let phpunitMatch=output.match(/Tests:\s*(\d+),\s*Assertions:\s*\d+(?:,\s*Failures:\s*(\d+))?(?:,\s*Errors:\s*(\d+))?(?:,\s*Skipped:\s*(\d+))?/),okMatch=output.match(/OK\s*\((\d+)\s+tests?/);if(phpunitMatch){total=parseInt(phpunitMatch[1],10);let failures=phpunitMatch[2]?parseInt(phpunitMatch[2],10):0,errors5=phpunitMatch[3]?parseInt(phpunitMatch[3],10):0;skipped=phpunitMatch[4]?parseInt(phpunitMatch[4],10):0,failed=failures+errors5,passed=total-failed-skipped}else if(okMatch)total=parseInt(okMatch[1],10),passed=total;break}default:break}if(total===void 0)total=passed+failed+skipped;return{ok:exitCode===0,raw:{stdout,stderr,exitCode},passed,failed,skipped,total,...coveragePercent!==void 0?{coveragePercent}:{}}}async function defaultDetectProject(profile,dir){for(let f of profile.build.detectFiles)if(detectFileExists(dir,f))return!0;return!1}async function defaultSelectBuildCommand(profile,dir){let sorted=[...profile.build.commands].sort((a,b)=>b.priority-a.priority);for(let cmd of sorted){if(cmd.detectFile&&!detectFileExists(dir,cmd.detectFile))continue;let argv=tokenizeCommand(cmd.cmd);if(argv.length===0)continue;if(!isCommandAvailable(argv[0]))continue;return{name:cmd.name,cmd:argv,cwd:dir,detectedVia:cmd.detectFile??`${profile.id} default`}}return null}async function defaultTestFilesFor(profile,sourceFile,dir){let ext=path148.extname(sourceFile);if(!profile.extensions.includes(ext))return[];let base=path148.basename(sourceFile,ext),rel=path148.relative(dir,sourceFile),stripSrc=path148.dirname(rel).replace(/^src(\/|\\)/,""),candidates=new Set;for(let tDir of["tests","test","__tests__","spec"])for(let suffix of["","_test",".test","_spec",".spec"])candidates.add(path148.join(dir,tDir,stripSrc,`${base}${suffix}${ext}`));let existing=[];for(let c of candidates)try{fs67.accessSync(c),existing.push(c)}catch{}return existing}function defaultExtractImports(){return[]}async function defaultSelectFramework(){return null}async function defaultSelectEntryPoints(){return[]}function defaultBackendFor(profile){return{...profile,detectProject:(dir)=>defaultDetectProject(profile,dir),selectTestFramework:(dir)=>defaultSelectTestFramework(profile,dir),buildTestCommand:(framework,files,dir,opts)=>defaultBuildTestCommand(profile,framework,files,dir,opts),parseTestOutput:(framework,stdout,stderr,exitCode)=>defaultParseTestOutput(framework,stdout,stderr,exitCode),testFilesFor:(sourceFile,dir)=>defaultTestFilesFor(profile,sourceFile,dir),extractImports:()=>defaultExtractImports(),selectBuildCommand:(dir)=>defaultSelectBuildCommand(profile,dir),selectFramework:()=>defaultSelectFramework(),selectEntryPoints:()=>defaultSelectEntryPoints()}}var init_default_backend=__esm(()=>{init_discovery()});import*as fs68 from"node:fs";import*as path149 from"node:path";function extractImports(_sourceFile,source){let out=new Set;IMPORT_REGEX_SINGLE.lastIndex=0;let m=IMPORT_REGEX_SINGLE.exec(source);while(m!==null)out.add(m[1]),m=IMPORT_REGEX_SINGLE.exec(source);IMPORT_REGEX_GROUP.lastIndex=0,m=IMPORT_REGEX_GROUP.exec(source);while(m!==null){let block=m[1];IMPORT_REGEX_GROUP_LINE.lastIndex=0;let inner=IMPORT_REGEX_GROUP_LINE.exec(block);while(inner!==null)out.add(inner[1]),inner=IMPORT_REGEX_GROUP_LINE.exec(block);m=IMPORT_REGEX_GROUP.exec(source)}return[...out]}async function selectFramework(dir){let content;try{content=fs68.readFileSync(path149.join(dir,"go.mod"),"utf-8")}catch{return null}let candidates=[["github.com/gin-gonic/gin","gin"],["github.com/labstack/echo","echo"],["github.com/gofiber/fiber","fiber"],["github.com/gorilla/mux","gorilla"],["github.com/go-chi/chi","chi"]];for(let[pkg,name]of candidates)if(content.includes(pkg))return{name,detectedVia:`go.mod require ${pkg}`};return null}async function selectEntryPoints(dir){let points=[];try{fs68.accessSync(path149.join(dir,"main.go")),points.push("main.go")}catch{}try{let cmdDir=path149.join(dir,"cmd"),subdirs=fs68.readdirSync(cmdDir,{withFileTypes:!0}).filter((d)=>d.isDirectory());for(let sub of subdirs){let main=path149.join("cmd",sub.name,"main.go");try{fs68.accessSync(path149.join(dir,main)),points.push(main)}catch{}}}catch{}return points}function buildGoBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID);if(!profile)throw Error("buildGoBackend: go profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...defaultBackendFor(profile),extractImports,selectFramework,selectEntryPoints}}var PROFILE_ID="go",IMPORT_REGEX_SINGLE,IMPORT_REGEX_GROUP,IMPORT_REGEX_GROUP_LINE,_internals105;var init_go2=__esm(()=>{init_default_backend();init_profiles();IMPORT_REGEX_SINGLE=/^\s*import\s+(?:[a-zA-Z_.][a-zA-Z0-9_]*\s+)?"([^"]+)"/gm,IMPORT_REGEX_GROUP=/^\s*import\s*\(([\s\S]*?)\)/gm,IMPORT_REGEX_GROUP_LINE=/(?:[a-zA-Z_.][a-zA-Z0-9_]*\s+)?"([^"]+)"/g;_internals105={extractImports}});import*as fs69 from"node:fs";import*as path150 from"node:path";function parseImportTargets(rawTargets){let cleaned=rawTargets.replace(/[()]/g,"").split(`
|
|
1918
1918
|
`).map((line)=>line.replace(/#.*$/,"").replace(/\\\s*$/,"")).join(" "),out=[];for(let seg of cleaned.split(",")){let trimmed=seg.trim();if(trimmed.length===0)continue;let name=trimmed.split(/\s+as\s+/)[0].trim();if(/^[\w]+$/.test(name))out.push(name)}return out}function extractImports2(_sourceFile,source){let out=new Set;source=source.replace(/\\\r?\n[ \t]*/g," "),IMPORT_REGEX_FROM_WITH_TARGETS.lastIndex=0;let m=IMPORT_REGEX_FROM_WITH_TARGETS.exec(source);while(m!==null){let fromClause=m[1],targets=parseImportTargets(m[2]);if(fromClause.length>0&&/^\.+$/.test(fromClause)&&targets.length>0)for(let t of targets)out.add(`${fromClause}${t}`);else if(fromClause.length>0)out.add(fromClause);m=IMPORT_REGEX_FROM_WITH_TARGETS.exec(source)}IMPORT_REGEX_IMPORT.lastIndex=0,m=IMPORT_REGEX_IMPORT.exec(source);while(m!==null){let segments=m[1].split(",");for(let seg of segments){let trimmed=seg.trim();if(trimmed.length===0)continue;let mod=trimmed.split(/\s+as\s+/)[0].trim();if(/^[\w.]+$/.test(mod))out.add(mod)}m=IMPORT_REGEX_IMPORT.exec(source)}return[...out]}async function selectFramework2(dir){let candidates=[["django","django"],["flask","flask"],["fastapi","fastapi"],["starlette","starlette"],["tornado","tornado"],["aiohttp","aiohttp"],["bottle","bottle"]];for(let candidate of["pyproject.toml","requirements.txt","setup.py"])try{let lower=fs69.readFileSync(path150.join(dir,candidate),"utf-8").toLowerCase();for(let[pkg,name]of candidates)if(lower.includes(pkg))return{name,detectedVia:candidate}}catch{}return null}async function selectEntryPoints2(dir){let points=new Set;try{let scriptsBlock=fs69.readFileSync(path150.join(dir,"pyproject.toml"),"utf-8").match(/\[project\.scripts\][\s\S]*?(?=\n\[|$)/);if(scriptsBlock)for(let line of scriptsBlock[0].split(`
|
|
1919
1919
|
`)){let m=line.match(/=\s*['"]([^'":]+)/);if(m){let modPath=`${m[1].replace(/\./g,"/")}.py`;points.add(modPath)}}}catch{}for(let name of["manage.py","main.py","app.py","__main__.py"])try{fs69.accessSync(path150.join(dir,name)),points.add(name)}catch{}return[...points]}function buildPythonBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID2);if(!profile)throw Error("buildPythonBackend: python profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...defaultBackendFor(profile),extractImports:extractImports2,selectFramework:selectFramework2,selectEntryPoints:selectEntryPoints2}}var PROFILE_ID2="python",IMPORT_REGEX_FROM_WITH_TARGETS,IMPORT_REGEX_IMPORT,_internals106;var init_python2=__esm(()=>{init_default_backend();init_profiles();IMPORT_REGEX_FROM_WITH_TARGETS=/^\s*from\s+(\.*[\w.]*)\s+import\s+(\([^)]*\)|[^\n#]+)/gm,IMPORT_REGEX_IMPORT=/^\s*import\s+([^\n#]+)/gm;_internals106={extractImports:extractImports2}});import fs70 from"node:fs";import path151 from"node:path";function normalizePath2(p){return p.replace(/\\/g,"/")}function sharedTrailingSegments(a,b){let aParts=normalizePath2(a).split("/").filter(Boolean),bParts=normalizePath2(b).split("/").filter(Boolean),i=aParts.length-1,j=bParts.length-1,shared=0;while(i>=0&&j>=0&&aParts[i]===bParts[j])shared++,i--,j--;return shared}function isCacheStale(impactMap,generatedAtMs){for(let sourcePath of Object.keys(impactMap))try{if(fs70.statSync(sourcePath).mtimeMs>generatedAtMs)return!0}catch{return!0}return!1}function resolveRelativeImport(fromDir,importPath){if(!importPath.startsWith("."))return null;let resolved=path151.resolve(fromDir,importPath);if(path151.extname(resolved)){if(fs70.existsSync(resolved)&&fs70.statSync(resolved).isFile())return normalizePath2(resolved)}else for(let ext of EXTENSIONS_TO_TRY){let withExt=resolved+ext;if(fs70.existsSync(withExt)&&fs70.statSync(withExt).isFile())return normalizePath2(withExt)}return null}function resolvePythonImport(fromDir,module){if(!module.startsWith("."))return null;let leadingDots=module.match(/^\.+/)?.[0].length??0,baseDir=fromDir;for(let i=1;i<leadingDots;i++)baseDir=path151.dirname(baseDir);let rest=module.slice(leadingDots);if(rest.length===0){let initPath=path151.join(baseDir,"__init__.py");if(fs70.existsSync(initPath)&&fs70.statSync(initPath).isFile())return normalizePath2(initPath);return null}let subpath=rest.replace(/\./g,path151.sep),candidates=[`${path151.join(baseDir,subpath)}.py`,path151.join(baseDir,subpath,"__init__.py")];for(let c of candidates)if(fs70.existsSync(c)&&fs70.statSync(c).isFile())return normalizePath2(c);return null}function findGoModule(fromDir){let cur=path151.resolve(fromDir),walked=[];for(let i=0;i<16;i++){let cached3=goModuleCache.get(cur);if(cached3!==void 0){for(let d of walked)goModuleCache.set(d,cached3);return cached3}walked.push(cur);try{let goMod=path151.join(cur,"go.mod"),moduleMatch=fs70.readFileSync(goMod,"utf-8").match(/^\s*module\s+"?([^"\s/]+(?:\/[^"\s]+)*)"?/m);if(moduleMatch){let result={moduleRoot:cur,modulePath:moduleMatch[1]};for(let d of walked)goModuleCache.set(d,result);return result}}catch{}try{fs70.accessSync(path151.join(cur,".git"));break}catch{}let parent=path151.dirname(cur);if(parent===cur)break;cur=parent}for(let d of walked)goModuleCache.set(d,null);return null}function resolveGoImport(fromDir,importPath){let dir=null;if(importPath.startsWith("."))dir=path151.resolve(fromDir,importPath);else{let mod=findGoModule(fromDir);if(mod&&(importPath===mod.modulePath||importPath.startsWith(`${mod.modulePath}/`))){let subpath=importPath.slice(mod.modulePath.length);dir=path151.join(mod.moduleRoot,subpath)}}if(dir===null)return[];if(!fs70.existsSync(dir)||!fs70.statSync(dir).isDirectory())return[];try{return fs70.readdirSync(dir).filter((f)=>f.endsWith(".go")&&!f.endsWith("_test.go")).map((f)=>normalizePath2(path151.join(dir,f)))}catch{return[]}}function _clearGoModuleCache(){goModuleCache.clear()}function findTestFilesSync(cwd){let testFiles=[],skipDirs=new Set(["node_modules","dist",".git",".swarm",".cache"]);function walk(dir,visitedRealPaths){let entries;try{entries=fs70.readdirSync(dir,{withFileTypes:!0})}catch{return}let realPath;try{realPath=normalizePath2(fs70.realpathSync.native(dir))}catch{return}let directoryKey=process.platform==="win32"?realPath.toLowerCase():realPath;if(visitedRealPaths.has(directoryKey))return;visitedRealPaths.add(directoryKey);for(let entry of entries)if(entry.isDirectory()){if(!skipDirs.has(entry.name))walk(path151.join(dir,entry.name),visitedRealPaths)}else if(entry.isFile()){let name=entry.name,isTsTest=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(name)||dir.includes("__tests__")&&/\.(ts|tsx|js|jsx)$/.test(name),isPyTest=/^test_.+\.py$/.test(name)||/.+_test\.py$/.test(name)||dir.includes(`${path151.sep}tests${path151.sep}`)&&name.endsWith(".py"),isGoTest=/.+_test\.go$/.test(name);if(isTsTest||isPyTest||isGoTest)testFiles.push(normalizePath2(path151.join(dir,entry.name)))}}return walk(cwd,new Set),[...new Set(testFiles)]}function extractImports3(content){function execRegex(regex,content2){let results=[];regex.lastIndex=0;let match;while((match=regex.exec(content2))!==null)results.push(match[1]);return results}return[...execRegex(IMPORT_REGEX_ES,content),...execRegex(IMPORT_REGEX_REQUIRE,content),...execRegex(IMPORT_REGEX_REEXPORT,content)]}function addImpactEdgesForTestFile(testFile,content,impactMap){let ext=path151.extname(testFile).toLowerCase(),testDir=path151.dirname(testFile);function addEdge(source){if(!impactMap[source])impactMap[source]=[];if(!impactMap[source].includes(testFile))impactMap[source].push(testFile)}if(TS_EXTENSIONS.has(ext)){let imports=extractImports3(content);for(let importPath of imports){let resolved=resolveRelativeImport(testDir,importPath);if(resolved!==null)addEdge(resolved)}return}if(PYTHON_EXTENSIONS.has(ext)){let modules=_internals106.extractImports(testFile,content);for(let mod of modules){let resolved=resolvePythonImport(testDir,mod);if(resolved!==null)addEdge(resolved)}return}if(GO_EXTENSIONS.has(ext)){let imports=_internals105.extractImports(testFile,content);for(let importPath of imports){let sourceFiles=resolveGoImport(testDir,importPath);for(let source of sourceFiles)addEdge(source)}return}}async function buildImpactMapInternal(cwd){_clearGoModuleCache();let testFiles=findTestFilesSync(cwd),impactMap={};for(let testFile of testFiles){let content;try{content=fs70.readFileSync(testFile,"utf-8")}catch{continue}if(content.substring(0,8192).includes("\x00"))continue;addImpactEdgesForTestFile(testFile,content,impactMap)}return impactMap}async function buildImpactMap(cwd){let impactMap=await _internals107.buildImpactMapInternal(cwd);return await _internals107.saveImpactMap(cwd,impactMap),impactMap}async function loadImpactMap(cwd,options){let cachePath=path151.join(cwd,".swarm","cache","impact-map.json");if(fs70.existsSync(cachePath))try{let content=fs70.readFileSync(cachePath,"utf-8"),data=JSON.parse(content);if(data.map!==null&&typeof data.map==="object"&&!Array.isArray(data.map)){let map3=data.map;if(Object.values(map3).every((v)=>Array.isArray(v)&&v.every((item)=>typeof item==="string"))){let generatedAt=new Date(data.generatedAt).getTime();if(!_internals107.isCacheStale(map3,generatedAt))return map3;if(options?.skipRebuild)return map3}}if(options?.skipRebuild)return{}}catch{if(options?.skipRebuild)return{}}if(options?.skipRebuild)return{};return _internals107.buildImpactMap(cwd)}async function saveImpactMap(cwd,impactMap){if(!path151.isAbsolute(cwd))throw Error(`saveImpactMap requires an absolute project root path, got: "${cwd}"`);_internals107.validateProjectRoot(cwd);let cacheDir2=path151.join(cwd,".swarm","cache"),cachePath=path151.join(cacheDir2,"impact-map.json");if(!fs70.existsSync(cacheDir2))fs70.mkdirSync(cacheDir2,{recursive:!0});let data={generatedAt:new Date().toISOString(),fileCount:Object.keys(impactMap).length,map:impactMap};fs70.writeFileSync(cachePath,JSON.stringify(data,null,2),"utf-8")}async function analyzeImpact(changedFiles,cwd,budget){if(!Array.isArray(changedFiles))return{impactedTests:[],unrelatedTests:[],untestedFiles:[],impactMap:{}};let validFiles=changedFiles.filter((f)=>typeof f==="string"&&f.length>0&&!f.includes("\x00")),impactMap=await _internals107.loadImpactMap(cwd),impactedTestsSet=new Set,untestedFiles=[],visitedCount=0,budgetExceeded=!1;for(let changedFile of validFiles){if(budget!==void 0&&visitedCount>=budget){budgetExceeded=!0;break}let normalizedChanged=normalizePath2(path151.resolve(changedFile)),tests=impactMap[normalizedChanged];if(tests&&tests.length>0){for(let test of tests){if(budget!==void 0&&visitedCount>=budget){budgetExceeded=!0;break}impactedTestsSet.add(test),visitedCount++}if(budgetExceeded)break}else{let changedDir=normalizePath2(path151.dirname(normalizedChanged)),changedInputDir=normalizePath2(path151.dirname(changedFile)),suffixMatches=Object.entries(impactMap).filter(([sourcePath])=>{return sourcePath.endsWith(changedFile)||changedFile.endsWith(sourcePath)||sourcePath.endsWith(normalizedChanged)||normalizedChanged.endsWith(sourcePath)}).sort(([sourceA],[sourceB])=>{let sourceDirA=normalizePath2(path151.dirname(sourceA)),sourceDirB=normalizePath2(path151.dirname(sourceB)),exactA=sourceDirA===changedDir||changedInputDir!=="."&&(sourceDirA===changedInputDir||sourceDirA.endsWith(`/${changedInputDir}`)),exactB=sourceDirB===changedDir||changedInputDir!=="."&&(sourceDirB===changedInputDir||sourceDirB.endsWith(`/${changedInputDir}`));if(exactA!==exactB)return exactA?-1:1;let sharedA=Math.max(sharedTrailingSegments(sourceDirA,changedDir),changedInputDir==="."?0:sharedTrailingSegments(sourceDirA,changedInputDir)),sharedB=Math.max(sharedTrailingSegments(sourceDirB,changedDir),changedInputDir==="."?0:sharedTrailingSegments(sourceDirB,changedInputDir)),nearestA=sharedA>0,nearestB=sharedB>0;if(nearestA!==nearestB)return nearestA?-1:1;if(sharedA!==sharedB)return sharedB-sharedA;return sourceA.localeCompare(sourceB)}),found=suffixMatches.length>0;for(let[,tests2]of suffixMatches){if(budget!==void 0&&visitedCount>=budget){budgetExceeded=!0;break}for(let test of tests2){if(budget!==void 0&&visitedCount>=budget){budgetExceeded=!0;break}impactedTestsSet.add(test),visitedCount++}if(budgetExceeded)break}if(budgetExceeded)break;if(!found)untestedFiles.push(changedFile)}}let impactedTests=[...impactedTestsSet],allTestFiles=new Set;for(let tests of Object.values(impactMap))for(let test of tests)allTestFiles.add(test);let unrelatedTests=[...allTestFiles].filter((t)=>!impactedTestsSet.has(t));return{impactedTests,unrelatedTests,untestedFiles,impactMap,budgetExceeded}}var IMPORT_REGEX_ES,IMPORT_REGEX_REQUIRE,IMPORT_REGEX_REEXPORT,TS_EXTENSIONS,PYTHON_EXTENSIONS,GO_EXTENSIONS,EXTENSIONS_TO_TRY,goModuleCache,_internals107;var init_analyzer=__esm(()=>{init_manager2();init_go2();init_python2();IMPORT_REGEX_ES=/import\s+[\s\S]*?\s+from\s+['"]([^'"]+)['"]/g,IMPORT_REGEX_REQUIRE=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,IMPORT_REGEX_REEXPORT=/export\s+(?:\{[^}]*\}|\*)\s+from\s+['"]([^'"]+)['"]/g,TS_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),PYTHON_EXTENSIONS=new Set([".py"]),GO_EXTENSIONS=new Set([".go"]),EXTENSIONS_TO_TRY=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];goModuleCache=new Map;_internals107={validateProjectRoot,normalizePath:normalizePath2,isCacheStale,resolveRelativeImport,findTestFilesSync,extractImports:extractImports3,buildImpactMapInternal,buildImpactMap,loadImpactMap,saveImpactMap,analyzeImpact,_clearGoModuleCache}});function computeCombinedFlakyScore(recent){let totalRuns=recent.length;if(totalRuns<2)return{alternationCount:0,flakyScore:0};let alternationCount=0,passCount=0;for(let i=0;i<recent.length;i++){if(recent[i].result==="pass")passCount++;if(i>0&&recent[i].result!==recent[i-1].result)alternationCount++}let alternationScore=alternationCount/totalRuns,passRate=passCount/totalRuns,passRateVarianceScore=4*passRate*(1-passRate);return{alternationCount,flakyScore:(alternationScore+passRateVarianceScore)/2}}function detectFlakyTests(allHistory){let grouped=new Map;for(let record3 of allHistory){let key=`${record3.testFile.toLowerCase()}\x00${record3.testName.toLowerCase()}`;if(!grouped.has(key))grouped.set(key,{records:[],originalFile:record3.testFile,originalName:record3.testName});grouped.get(key).records.push(record3)}let results=[];for(let[_key,entry]of grouped){let records=entry.records;if(records.length===0)continue;let recent=records.slice().sort((a,b)=>new Date(a.timestamp).getTime()-new Date(b.timestamp).getTime()).slice(-20),totalRuns=recent.length;if(totalRuns<2)continue;let{alternationCount,flakyScore}=computeCombinedFlakyScore(recent),isQuarantined=flakyScore>0.3&&totalRuns>=5,recentResults=recent.map((r)=>r.result),testFile=entry.originalFile,testName=entry.originalName,recommendation;if(isQuarantined){if(alternationCount===totalRuns-1)recommendation="Highly unstable — investigate test isolation issues, mock cleanup, or shared state";else if(flakyScore>0.5)recommendation="Severely flaky — consider quarantining and rewriting test with proper isolation";else if(flakyScore>0.3)recommendation="Moderately flaky — review for timing dependencies, async issues, or environmental factors"}results.push({testFile,testName,flakyScore,totalRuns,alternationCount,isQuarantined,recentResults,recommendation})}return results}import fs71 from"node:fs";import path152 from"node:path";function getHistoryPath(workingDir){if(!workingDir)throw Error("getHistoryPath requires a working directory — project root must be provided by the caller");if(!path152.isAbsolute(workingDir))throw Error(`getHistoryPath requires an absolute project root path, got: "${workingDir}"`);return path152.join(workingDir,".swarm","cache","test-history.jsonl")}function sanitizeErrorMessage(errorMessage2){if(errorMessage2===void 0)return;if(errorMessage2.length>MAX_ERROR_LENGTH)return errorMessage2.substring(0,MAX_ERROR_LENGTH);return errorMessage2}function sanitizeStackPrefix(stackPrefix){if(stackPrefix===void 0)return;if(stackPrefix.length>MAX_STACK_LENGTH)return stackPrefix.substring(0,MAX_STACK_LENGTH);return stackPrefix}function sanitizeChangedFiles(changedFiles){return changedFiles.filter((f)=>typeof f==="string"&&f.length>0&&!DANGEROUS_PROPERTY_NAMES.has(f)).slice(0,MAX_CHANGED_FILES)}function isTestRunResult(value){return value==="pass"||value==="fail"||value==="skip"}function parseStoredRecord(value){if(typeof value!=="object"||value===null)return null;let record3=value;if(typeof record3.testFile!=="string"||record3.testFile.length===0)return null;if(typeof record3.testName!=="string"||record3.testName.length===0)return null;if(typeof record3.taskId!=="string"||record3.taskId.length===0)return null;if(!isTestRunResult(record3.result))return null;if(typeof record3.durationMs!=="number"||!Number.isFinite(record3.durationMs))return null;if(typeof record3.timestamp!=="string"||Number.isNaN(Date.parse(record3.timestamp)))return null;return{timestamp:record3.timestamp,taskId:record3.taskId,testFile:record3.testFile,testName:record3.testName,result:record3.result,durationMs:Math.max(0,record3.durationMs),errorMessage:typeof record3.errorMessage==="string"?sanitizeErrorMessage(record3.errorMessage):void 0,stackPrefix:typeof record3.stackPrefix==="string"?sanitizeStackPrefix(record3.stackPrefix):void 0,changedFiles:sanitizeChangedFiles(Array.isArray(record3.changedFiles)?record3.changedFiles:[])}}function batchAppendTestRuns(records,workingDir){if(records.length===0)return;for(let record3 of records){if(typeof record3.testFile!=="string"||record3.testFile.length===0)throw TypeError("testFile must be a non-empty string");if(typeof record3.testName!=="string"||record3.testName.length===0)throw TypeError("testName must be a non-empty string");if(typeof record3.taskId!=="string"||record3.taskId.length===0)throw TypeError("taskId must be a non-empty string");if(record3.result!=="pass"&&record3.result!=="fail"&&record3.result!=="skip")throw TypeError('result must be "pass", "fail", or "skip"');if(typeof record3.durationMs!=="number"||!Number.isFinite(record3.durationMs))throw TypeError("durationMs must be a finite number");if(record3.timestamp!==void 0&&Number.isNaN(Date.parse(record3.timestamp)))throw TypeError("timestamp must be a valid ISO 8601 string");if(record3.changedFiles!==void 0&&!Array.isArray(record3.changedFiles))throw TypeError("changedFiles must be an array")}let historyPath=getHistoryPath(workingDir),historyDir=path152.dirname(historyPath);if(_internals108.validateProjectRoot(workingDir),!fs71.existsSync(historyDir))fs71.mkdirSync(historyDir,{recursive:!0});withHistoryWriteLock(historyPath,()=>{let existingRecords=readAllRecords2(historyPath),sanitizedRecords=records.map((record3)=>({...record3,timestamp:record3.timestamp||new Date().toISOString(),durationMs:Math.max(0,record3.durationMs),errorMessage:sanitizeErrorMessage(record3.errorMessage),stackPrefix:sanitizeStackPrefix(record3.stackPrefix),changedFiles:sanitizeChangedFiles(record3.changedFiles||[])}));existingRecords.push(...sanitizedRecords);let recordsByTest=new Map;for(let rec of existingRecords){let normalizedKey=`${rec.testFile.toLowerCase()}|${rec.testName.toLowerCase()}`;if(!recordsByTest.has(normalizedKey))recordsByTest.set(normalizedKey,[]);recordsByTest.get(normalizedKey).push(rec)}let prunedRecords=[];for(let[,recs]of recordsByTest){recs.sort((a,b)=>new Date(a.timestamp).getTime()-new Date(b.timestamp).getTime());let toKeep=recs.slice(-MAX_HISTORY_PER_TEST);prunedRecords.push(...toKeep)}prunedRecords.sort((a,b)=>new Date(a.timestamp).getTime()-new Date(b.timestamp).getTime());try{let content=`${prunedRecords.map((rec)=>JSON.stringify(rec)).join(`
|
|
1920
1920
|
`)}
|
|
1921
1921
|
`,tempPath=`${historyPath}.tmp`;fs71.writeFileSync(tempPath,content,"utf-8"),fs71.renameSync(tempPath,historyPath)}catch(err){try{let tempPath=`${historyPath}.tmp`;if(fs71.existsSync(tempPath))fs71.unlinkSync(tempPath)}catch{}throw Error(`Failed to write test history: ${err instanceof Error?err.message:String(err)}`)}})}function withHistoryWriteLock(historyPath,fn2){let lockPath=`${historyPath}.write-lock`,deadline=Date.now()+HISTORY_WRITE_LOCK_TIMEOUT_MS;while(!0)try{fs71.mkdirSync(lockPath);break}catch(error93){if((error93 instanceof Error&&"code"in error93?error93.code:void 0)!=="EEXIST")throw Error(`Failed to acquire test history lock: ${error93 instanceof Error?error93.message:String(error93)}`);if(Date.now()>=deadline)throw Error(`Timed out waiting for test history lock: ${historyPath}`);try{let lockStat=fs71.statSync(lockPath);if(Date.now()-lockStat.mtimeMs>=HISTORY_WRITE_LOCK_STALE_MS){fs71.rmSync(lockPath,{recursive:!0,force:!0});continue}}catch{}let remainingMs=Math.max(0,deadline-Date.now()),sleepMs=Math.min(HISTORY_WRITE_LOCK_BACKOFF_MS,remainingMs);if(sleepMs>0)sleepSync(sleepMs)}try{return fn2()}finally{try{fs71.rmSync(lockPath,{recursive:!0,force:!0})}catch{}}function sleepSync(ms){let until=Date.now()+ms;while(Date.now()<until);}}function readAllRecords2(historyPath){if(!fs71.existsSync(historyPath))return[];try{let lines=fs71.readFileSync(historyPath,"utf-8").split(`
|
|
1922
|
-
`),records=[];for(let line of lines){let trimmed=line.trim();if(trimmed.length===0)continue;try{let parsed=JSON.parse(trimmed),record3=parseStoredRecord(parsed);if(record3)records.push(record3)}catch{}}return records}catch(err){throw Error(`Failed to read test history: ${err instanceof Error?err.message:String(err)}`)}}function getAllHistory(workingDir){let historyPath=getHistoryPath(workingDir),records=readAllRecords2(historyPath);return records.sort((a,b)=>new Date(a.timestamp).getTime()-new Date(b.timestamp).getTime()),records}var MAX_HISTORY_PER_TEST=20,MAX_ERROR_LENGTH=500,MAX_STACK_LENGTH=200,MAX_CHANGED_FILES=50,HISTORY_WRITE_LOCK_TIMEOUT_MS=5000,HISTORY_WRITE_LOCK_STALE_MS=60000,HISTORY_WRITE_LOCK_BACKOFF_MS=10,DANGEROUS_PROPERTY_NAMES,_internals108;var init_history_store=__esm(()=>{init_manager2();DANGEROUS_PROPERTY_NAMES=new Set(["__proto__","constructor","prototype"]);_internals108={validateProjectRoot}});import*as fs72 from"node:fs";import*as path153 from"node:path";function resolveWorkingDirectory(workingDirectory,fallbackDirectory){if(workingDirectory==null||workingDirectory===""){if(typeof fallbackDirectory!=="string"||fallbackDirectory==="")return{success:!1,message:"Invalid working_directory: no explicit working_directory was provided and fallbackDirectory is missing or not a string"};return{success:!0,directory:fallbackDirectory}}if(typeof workingDirectory!=="string")return{success:!1,message:"Invalid working_directory: path must be a string"};if(workingDirectory.includes("\x00"))return{success:!1,message:"Invalid working_directory: null bytes are not allowed"};let reservedDevicePattern=/^(NUL|CON|AUX|COM[1-9]|LPT[1-9])(\..*)?$/i;if(workingDirectory.startsWith("\\\\")||process.platform==="win32"&&reservedDevicePattern.test(workingDirectory))return{success:!1,message:"Invalid working_directory: Windows device paths are not allowed"};if(workingDirectory.split(/[\\/]/).includes(".."))return{success:!1,message:"Invalid working_directory: path traversal sequences (..) are not allowed"};let normalizedDir=path153.normalize(workingDirectory),resolvedDir=path153.resolve(normalizedDir),statResult;try{statResult=fs72.statSync(resolvedDir)}catch{return{success:!1,message:`Invalid working_directory: path "${resolvedDir}" does not exist or is inaccessible`}}if(!statResult.isDirectory())return{success:!1,message:`Invalid working_directory: path "${resolvedDir}" is not a directory`};if(typeof fallbackDirectory!=="string"||fallbackDirectory==="")return{success:!0,directory:resolvedDir};let resolvedFallback=path153.resolve(fallbackDirectory),fallbackExists=!1;try{fs72.statSync(resolvedFallback),fallbackExists=!0}catch{fallbackExists=!1}if(fallbackExists){if(resolvedDir.startsWith(resolvedFallback+path153.sep))return{success:!1,message:`Invalid working_directory: "${workingDirectory}" resolves to "${resolvedDir}" which is a subdirectory of fallback "${resolvedFallback}". Pass the project root path or omit working_directory entirely.`}}return{success:!0,directory:resolvedDir}}var init_resolve_working_directory=()=>{};class LanguageBackendRegistry{backends=new Map;register(backend){let existing=this.backends.get(backend.id);if(existing&&existing!==backend)throw Error(`LanguageBackendRegistry: backend id "${backend.id}" registered twice. Each LanguageBackend.id must be unique.`);this.backends.set(backend.id,backend)}get(id){return this.backends.get(id)}getOrDefault(id){let registered=this.backends.get(id);if(registered)return registered;let profile=LANGUAGE_REGISTRY.get(id);if(!profile)return;return defaultBackendFor(profile)}unregister(id){this.backends.delete(id)}}var LANGUAGE_BACKEND_REGISTRY;var init_registry_backend=__esm(()=>{init_default_backend();init_profiles();LANGUAGE_BACKEND_REGISTRY=new LanguageBackendRegistry});import*as fs73 from"node:fs";import*as path154 from"node:path";function detectLaravelProject(directory){let signals=getLaravelSignals(directory);return[signals.hasArtisanFile,signals.hasLaravelFrameworkDep,signals.hasConfigApp].filter(Boolean).length>=2}function getLaravelSignals(directory){let hasArtisanFile=checkArtisanFile(directory),hasLaravelFrameworkDep=checkLaravelFrameworkDep(directory),hasConfigApp=checkConfigApp(directory);return{hasArtisanFile,hasLaravelFrameworkDep,hasConfigApp}}function checkArtisanFile(directory){let artisanPath=path154.join(directory,"artisan");if(!fs73.existsSync(artisanPath))return!1;try{return fs73.statSync(artisanPath).isFile()}catch{return!1}}function checkLaravelFrameworkDep(directory){let composerPath=path154.join(directory,"composer.json");if(!fs73.existsSync(composerPath))return!1;try{let content=fs73.readFileSync(composerPath,"utf-8");return typeof(JSON.parse(content)?.require??{})["laravel/framework"]==="string"}catch{return!1}}function checkConfigApp(directory){return fs73.existsSync(path154.join(directory,"config","app.php"))}function isLarastanConfigured(directory){let neonPath=path154.join(directory,"phpstan.neon");if(!fs73.existsSync(neonPath))return!1;try{let fd=fs73.openSync(neonPath,"r");try{let buf=Buffer.alloc(4096),bytesRead=fs73.readSync(fd,buf,0,4096,0),content=buf.subarray(0,bytesRead).toString("utf-8");return content.includes("nunomaduro/larastan")||content.includes("larastan/larastan")}finally{fs73.closeSync(fd)}}catch{return!1}}function getLaravelCommandOverlay(directory){if(!detectLaravelProject(directory))return null;let lintCommand=null;if(fs73.existsSync(path154.join(directory,"pint.json")))lintCommand="vendor/bin/pint --test";else if(fs73.existsSync(path154.join(directory,".php-cs-fixer.php")))lintCommand="vendor/bin/php-cs-fixer fix --dry-run --diff";let staticAnalysisCommand=null,staticAnalysisTool=null,hasPhpstanNeon=fs73.existsSync(path154.join(directory,"phpstan.neon")),hasPhpstanNeonDist=fs73.existsSync(path154.join(directory,"phpstan.neon.dist"));if(hasPhpstanNeon||hasPhpstanNeonDist)staticAnalysisCommand="vendor/bin/phpstan analyse",staticAnalysisTool=isLarastanConfigured(directory)?"larastan":"phpstan";return{testCommand:"php artisan test",lintCommand,staticAnalysisCommand,staticAnalysisTool,auditCommand:"composer audit --locked --format=json",supportsParallel:!0}}var init_framework_detector=()=>{};import*as fs74 from"node:fs";import*as path155 from"node:path";async function selectFramework3(dir){if(detectLaravelProject(dir))return{name:"laravel",detectedVia:"Laravel signals (artisan / composer.json / config/app.php)"};return null}async function selectTestFramework(dir){if(detectLaravelProject(dir))return{name:"php-artisan",cmd:["php","artisan","test"],cwd:dir,detectedVia:"Laravel signals (artisan / composer.json / config/app.php)"};if(fs74.existsSync(path155.join(dir,"Pest.php")))return{name:"pest",cmd:[phpVendorBin3("pest")],cwd:dir,detectedVia:"Pest.php"};if(fs74.existsSync(path155.join(dir,"phpunit.xml")))return{name:"phpunit",cmd:[phpVendorBin3("phpunit")],cwd:dir,detectedVia:"phpunit.xml"};if(fs74.existsSync(path155.join(dir,"phpunit.xml.dist")))return{name:"phpunit",cmd:[phpVendorBin3("phpunit")],cwd:dir,detectedVia:"phpunit.xml.dist"};return null}function phpVendorBin3(name){return path155.join("vendor","bin",process.platform==="win32"?`${name}.bat`:name)}function buildPhpBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID3);if(!profile)throw Error("buildPhpBackend: php profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...defaultBackendFor(profile),selectFramework:selectFramework3,selectTestFramework}}var PROFILE_ID3="php";var init_php2=__esm(()=>{init_default_backend();init_framework_detector();init_profiles()});import*as fs75 from"node:fs";import*as path156 from"node:path";function readPackageJsonRaw(dir){try{let content=fs75.readFileSync(path156.join(dir,"package.json"),"utf-8");return JSON.parse(content)}catch{return null}}function readPackageJson(dir){return _internals109.readPackageJsonRaw(dir)}function readPackageJsonTestScript(dir){return readPackageJson(dir)?.scripts?.test??null}function frameworkFromScriptsTest(script){if(script.includes("vitest"))return"vitest";if(script.includes("jest"))return"jest";if(script.includes("mocha"))return"mocha";if(script.includes("bun test"))return"bun:test";return null}function frameworkFromDevDeps(devDeps){if(!devDeps)return null;if(devDeps.vitest||devDeps["@vitest/ui"])return"vitest";if(devDeps.jest||devDeps["@types/jest"])return"jest";if(devDeps.mocha||devDeps["@types/mocha"])return"mocha";return null}function selectionFromFramework(profile,fwName,dir,detectedVia){let fw=profile.test.frameworks.find((f)=>f.name===fwName);if(!fw)return null;let argv=tokenizeCommand(fw.cmd);if(argv.length===0)return null;return{name:fw.name,cmd:argv,cwd:dir,detectedVia,filesIgnored:!1}}async function selectTestFramework2(dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)return null;let pkg=readPackageJson(dir),script=pkg?.scripts?.test;if(script){let fwName=frameworkFromScriptsTest(script);if(fwName){let sel=selectionFromFramework(profile,fwName,dir,"package.json#scripts.test");if(sel)return sel}}let devDepsFw=frameworkFromDevDeps(pkg?.devDependencies);if(devDepsFw){let sel=selectionFromFramework(profile,devDepsFw,dir,"package.json#devDependencies");if(sel)return sel}return defaultSelectTestFramework(profile,dir)}function buildTestCommand(framework,files,dir,opts){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)return null;return defaultBuildTestCommand(profile,framework,files,dir,opts)}function parseTestOutput(framework,stdout,stderr,exitCode){return defaultParseTestOutput(framework,stdout,stderr,exitCode)}async function selectFramework4(dir){let pkg=readPackageJson(dir);if(!pkg)return null;let deps={...pkg.dependencies,...pkg.devDependencies},order=[["next","next"],["nuxt","nuxt"],["@angular/core","angular"],["svelte","svelte"],["react","react"],["vue","vue"],["express","express"],["fastify","fastify"],["@nestjs/core","nestjs"]];for(let[pkgName,displayName]of order)if(deps[pkgName])return{name:displayName,detectedVia:`package.json#dependencies.${pkgName}`};return null}async function selectEntryPoints3(dir){let pkg=readPackageJson(dir);if(!pkg)return[];let points=[],obj=pkg;if(obj.bin)if(typeof obj.bin==="string")points.push(obj.bin);else for(let v of Object.values(obj.bin))points.push(v);if(obj.main)points.push(obj.main);if(obj.module&&obj.module!==obj.main)points.push(obj.module);if(obj.exports&&typeof obj.exports==="object"){let root=obj.exports["."];if(typeof root==="string"&&!points.includes(root))points.push(root)}return[...new Set(points.filter((p)=>p.length>0))]}function extractImports4(_sourceFile,source){let out=new Set;for(let re of[IMPORT_REGEX_ES2,IMPORT_REGEX_BARE,IMPORT_REGEX_REQUIRE2,IMPORT_REGEX_DYNAMIC,IMPORT_REGEX_REEXPORT2]){re.lastIndex=0;let m=re.exec(source);while(m!==null)out.add(m[1]),m=re.exec(source)}return[...out]}async function selectBuildCommand(dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)return null;return defaultSelectBuildCommand(profile,dir)}async function testFilesFor(sourceFile,dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)return[];return defaultTestFilesFor(profile,sourceFile,dir)}function buildTypescriptBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)throw Error("buildTypescriptBackend: typescript profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...profile,selectTestFramework:selectTestFramework2,buildTestCommand,parseTestOutput,extractImports:extractImports4,selectBuildCommand,testFilesFor,selectFramework:selectFramework4,selectEntryPoints:selectEntryPoints3}}var PROFILE_ID4="typescript",IMPORT_REGEX_ES2,IMPORT_REGEX_BARE,IMPORT_REGEX_REQUIRE2,IMPORT_REGEX_DYNAMIC,IMPORT_REGEX_REEXPORT2,_internals109;var init_typescript=__esm(()=>{init_default_backend();init_profiles();IMPORT_REGEX_ES2=/import\s+[\s\S]*?\s+from\s+['"]([^'"]+)['"]/g,IMPORT_REGEX_BARE=/import\s+['"]([^'"]+)['"]/g,IMPORT_REGEX_REQUIRE2=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,IMPORT_REGEX_DYNAMIC=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,IMPORT_REGEX_REEXPORT2=/export\s+(?:\{[^}]*\}|\*)\s+from\s+['"]([^'"]+)['"]/g;_internals109={readPackageJsonRaw,readPackageJsonTestScript,frameworkFromScriptsTest}});function registerAllBackends(){if(registered)return;LANGUAGE_BACKEND_REGISTRY.register(buildTypescriptBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildPythonBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildGoBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildPhpBackend()),registered=!0}var registered=!1;var init_backends=__esm(()=>{init_registry_backend();init_go2();init_php2();init_python2();init_typescript();registerAllBackends()});var exports_dispatch={};__export(exports_dispatch,{pickedProfiles:()=>pickedProfiles,pickBackend:()=>pickBackend,clearDispatchCache:()=>clearDispatchCache,_internals:()=>_internals110});import*as fs76 from"node:fs";import*as path157 from"node:path";function safeReaddirSet(dir){try{return new Set(fs76.readdirSync(dir))}catch{return new Set}}function manifestHash(dir){let entries=safeReaddirSet(dir);if(entries.size===0)return"";let parts=[];for(let name of MANIFEST_FILES){if(!entries.has(name))continue;try{let stat13=fs76.statSync(path157.join(dir,name));parts.push(`${name}:${stat13.size}:${stat13.mtimeMs}:${stat13.ino}`)}catch{}}return parts.join("|")}function findManifestRoot(start){let resolved=path157.resolve(start),cached3=manifestRootCache.get(resolved);if(cached3!==void 0)return cached3;let cur=resolved;for(let i=0;i<32;i++){let entries=safeReaddirSet(cur);if(entries.size>0){for(let name of MANIFEST_FILES)if(entries.has(name))return manifestRootCache.set(resolved,cur),cur;if(entries.has(".git"))return manifestRootCache.set(resolved,cur),cur}let parent=path157.dirname(cur);if(parent===cur)break;cur=parent}return manifestRootCache.set(resolved,start),start}function evictIfNeeded(){if(cache2.size<=_internals110.cacheCapacity)return;let oldestKey,oldestOrder=1/0;for(let[k,v]of cache2.entries())if(v.insertOrder<oldestOrder)oldestOrder=v.insertOrder,oldestKey=k;if(oldestKey!==void 0)cache2.delete(oldestKey)}async function pickBackend(dir){let root=findManifestRoot(dir),hash4=manifestHash(root),cacheKey=root,cached3=cache2.get(cacheKey);if(cached3&&cached3.hash===hash4)return cached3.backend;if(hash4==="")return cache2.set(cacheKey,{hash:hash4,backend:null,profiles:[],insertOrder:insertCounter++}),evictIfNeeded(),null;let profiles=await _internals110.detectProjectLanguages(root);if(profiles.length===0)return cache2.set(cacheKey,{hash:hash4,backend:null,profiles:[],insertOrder:insertCounter++}),evictIfNeeded(),null;let winner=profiles[0],backend=LANGUAGE_BACKEND_REGISTRY.getOrDefault(winner.id)??null;return cache2.set(cacheKey,{hash:hash4,backend,profiles:profiles.map((p)=>({id:p.id})),insertOrder:insertCounter++}),evictIfNeeded(),backend}function pickedProfiles(dir){let root=findManifestRoot(dir);return cache2.get(root)?.profiles??[]}function clearDispatchCache(){cache2.clear(),manifestRootCache.clear(),insertCounter=0}var _internals110,cache2,insertCounter=0,MANIFEST_FILES,_MANIFEST_SET,manifestRootCache;var init_dispatch=__esm(()=>{init_backends();init_detector();init_registry_backend();_internals110={detectProjectLanguages,cacheCapacity:64},cache2=new Map,MANIFEST_FILES=["package.json","tsconfig.json","pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","Cargo.toml","go.mod","pom.xml","build.gradle","build.gradle.kts","build.zig","CMakeLists.txt","Makefile","meson.build","Package.swift","pubspec.yaml","Gemfile","composer.json"],_MANIFEST_SET=new Set(MANIFEST_FILES);manifestRootCache=new Map});import*as fs77 from"node:fs";import*as path158 from"node:path";async function estimateFanOut(sourceFiles,cwd){try{let impactMap=await _internals111.loadImpactMap(cwd,{skipRebuild:!0}),uniqueTestFiles=new Set;for(let sourceFile of sourceFiles){let normalizedPath2=path158.resolve(cwd,sourceFile).replace(/\\/g,"/"),testFiles=impactMap[normalizedPath2];if(testFiles)for(let testFile of testFiles)uniqueTestFiles.add(testFile)}return{estimatedCount:uniqueTestFiles.size}}catch{return{estimatedCount:0}}}function isAbsolutePath(str){if(str.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test(str))return!0;if(/^\\\\/.test(str))return!0;if(/^\\\\\.\\/.test(str))return!0;return!1}function containsPowerShellMetacharacters(str){return POWERSHELL_METACHARACTERS.test(str)}function validateArgs2(args2){if(typeof args2!=="object"||args2===null)return!1;let obj=args2;if(obj.scope!==void 0){if(obj.scope!=="all"&&obj.scope!=="convention"&&obj.scope!=="graph"&&obj.scope!=="impact")return!1}if(obj.files!==void 0){if(!Array.isArray(obj.files))return!1;for(let f of obj.files){if(typeof f!=="string")return!1;if(isAbsolutePath(f))return!1;if(containsPathTraversal(f))return!1;if(containsControlChars(f))return!1;if(containsPowerShellMetacharacters(f))return!1}}if(obj.coverage!==void 0){if(typeof obj.coverage!=="boolean")return!1}if(obj.bail!==void 0){if(typeof obj.bail!=="boolean")return!1}if(obj.timeout_ms!==void 0){if(typeof obj.timeout_ms!=="number")return!1;if(obj.timeout_ms<0||obj.timeout_ms>MAX_TIMEOUT_MS2)return!1}return!0}function hasPackageJsonDependency(deps,...patterns){for(let pattern of patterns)if(deps[pattern])return!0;return!1}function hasDevDependency(devDeps,...patterns){if(!devDeps)return!1;return hasPackageJsonDependency(devDeps,...patterns)}function detectGoTest(cwd){return _internals111.existsSync(path158.join(cwd,"go.mod"))&&_internals111.isCommandAvailable("go")}function detectJavaMaven(cwd){return _internals111.existsSync(path158.join(cwd,"pom.xml"))&&_internals111.isCommandAvailable("mvn")}function detectGradle(cwd){let hasBuildFile=_internals111.existsSync(path158.join(cwd,"build.gradle"))||_internals111.existsSync(path158.join(cwd,"build.gradle.kts")),hasGradlew=_internals111.existsSync(path158.join(cwd,"gradlew"))||_internals111.existsSync(path158.join(cwd,"gradlew.bat"));return hasBuildFile&&(hasGradlew||_internals111.isCommandAvailable("gradle"))}function detectDotnetTest(cwd){try{return _internals111.readdirSync(cwd).some((f)=>f.endsWith(".csproj"))&&_internals111.isCommandAvailable("dotnet")}catch{return!1}}function detectCTest(cwd){let hasSource=_internals111.existsSync(path158.join(cwd,"CMakeLists.txt")),hasBuildCache=_internals111.existsSync(path158.join(cwd,"CMakeCache.txt"))||_internals111.existsSync(path158.join(cwd,"build","CMakeCache.txt"));return(hasSource||hasBuildCache)&&_internals111.isCommandAvailable("ctest")}function detectSwiftTest(cwd){return _internals111.existsSync(path158.join(cwd,"Package.swift"))&&_internals111.isCommandAvailable("swift")}function detectDartTest(cwd){return _internals111.existsSync(path158.join(cwd,"pubspec.yaml"))&&(_internals111.isCommandAvailable("dart")||_internals111.isCommandAvailable("flutter"))}function detectRSpec(cwd){let hasRSpecFile=_internals111.existsSync(path158.join(cwd,".rspec")),hasGemfile=_internals111.existsSync(path158.join(cwd,"Gemfile")),hasSpecDir=_internals111.existsSync(path158.join(cwd,"spec"));return(hasRSpecFile||hasGemfile&&hasSpecDir)&&(_internals111.isCommandAvailable("bundle")||_internals111.isCommandAvailable("rspec"))}function detectMinitest(cwd){return _internals111.existsSync(path158.join(cwd,"test"))&&(_internals111.existsSync(path158.join(cwd,"Gemfile"))||_internals111.existsSync(path158.join(cwd,"Rakefile")))&&_internals111.isCommandAvailable("ruby")}async function detectTestFrameworkViaDispatch(cwd){try{let{pickBackend:pickBackend2}=await Promise.resolve().then(() => (init_dispatch(),exports_dispatch)),backend=await pickBackend2(cwd);if(!backend?.selectTestFramework)return"none";let sel=await backend.selectTestFramework(cwd);if(!sel)return"none";return DISPATCH_FRAMEWORK_MAP[sel.name]??"none"}catch{return"none"}}async function buildTestCommandViaDispatch(framework,scope,files,coverage,baseDir,bail){if(framework==="none")return null;try{let{pickBackend:pickBackend2}=await Promise.resolve().then(() => (init_dispatch(),exports_dispatch)),backend=await pickBackend2(baseDir);if(backend?.buildTestCommand){let cmd=backend.buildTestCommand(framework,files,baseDir,{scope,coverage,bail});if(cmd)return cmd}return null}catch{return null}}async function parseTestOutputViaDispatch(framework,output,baseDir){if(framework==="none")return null;try{let{pickBackend:pickBackend2}=await Promise.resolve().then(() => (init_dispatch(),exports_dispatch)),backend=await pickBackend2(baseDir);if(!backend?.parseTestOutput)return null;let summary=backend.parseTestOutput(framework,output,"",0),passed=summary.passed??0,failed=summary.failed??0,skipped=summary.skipped??0,total=summary.total??passed+failed+skipped,result={totals:{passed,failed,skipped,total}};if(summary.coveragePercent!==void 0)result.coveragePercent=summary.coveragePercent;return result}catch{return null}}async function detectTestFramework(cwd){let baseDir=cwd;try{let packageJsonPath=path158.join(baseDir,"package.json");if(_internals111.existsSync(packageJsonPath)){let content=_internals111.readFileSync(packageJsonPath,"utf-8"),pkg=JSON.parse(content),_deps=pkg.dependencies||{},devDeps=pkg.devDependencies||{},scripts=pkg.scripts||{};if(scripts.test?.includes("vitest"))return"vitest";if(scripts.test?.includes("jest"))return"jest";if(scripts.test?.includes("mocha"))return"mocha";if(scripts.test?.includes("bun test"))return"bun";if(hasDevDependency(devDeps,"vitest","@vitest/ui"))return"vitest";if(hasDevDependency(devDeps,"jest","@types/jest"))return"jest";if(hasDevDependency(devDeps,"mocha","@types/mocha"))return"mocha";if(_internals111.existsSync(path158.join(baseDir,"bun.lockb"))||_internals111.existsSync(path158.join(baseDir,"bun.lock"))){if(scripts.test?.includes("bun"))return"bun"}}}catch{}try{let pyprojectTomlPath=path158.join(baseDir,"pyproject.toml"),setupCfgPath=path158.join(baseDir,"setup.cfg"),requirementsTxtPath=path158.join(baseDir,"requirements.txt");if(_internals111.existsSync(pyprojectTomlPath)){let content=_internals111.readFileSync(pyprojectTomlPath,"utf-8");if(content.includes("[tool.pytest"))return"pytest";if(content.includes("pytest"))return"pytest"}if(_internals111.existsSync(setupCfgPath)){if(_internals111.readFileSync(setupCfgPath,"utf-8").includes("[pytest]"))return"pytest"}if(_internals111.existsSync(requirementsTxtPath)){if(_internals111.readFileSync(requirementsTxtPath,"utf-8").includes("pytest"))return"pytest"}}catch{}try{let cargoTomlPath=path158.join(baseDir,"Cargo.toml");if(_internals111.existsSync(cargoTomlPath)){let content=_internals111.readFileSync(cargoTomlPath,"utf-8");if(content.includes("[dev-dependencies]")){if(content.includes("tokio")||content.includes("mockall")||content.includes("pretty_assertions"))return"cargo"}}}catch{}try{let pesterConfigPath=path158.join(baseDir,"pester.config.ps1"),pesterConfigJsonPath=path158.join(baseDir,"pester.config.ps1.json"),pesterPs1Path=path158.join(baseDir,"tests.ps1");if(_internals111.existsSync(pesterConfigPath)||_internals111.existsSync(pesterConfigJsonPath)||_internals111.existsSync(pesterPs1Path))return"pester"}catch{}let phpFramework=detectPhpTest(baseDir);if(phpFramework)return phpFramework;if(detectGoTest(baseDir))return"go-test";if(detectJavaMaven(baseDir))return"maven";if(detectGradle(baseDir))return"gradle";if(detectDotnetTest(baseDir))return"dotnet-test";if(detectCTest(baseDir))return"ctest";if(detectSwiftTest(baseDir))return"swift-test";if(detectDartTest(baseDir))return"dart-test";if(detectRSpec(baseDir))return"rspec";if(detectMinitest(baseDir))return"minitest";return"none"}function detectPhpTest(cwd){if(_internals111.existsSync(path158.join(cwd,"artisan"))&&_internals111.existsSync(path158.join(cwd,"composer.json")))return"php-artisan";if(_internals111.existsSync(path158.join(cwd,"Pest.php")))return"pest";if(_internals111.existsSync(path158.join(cwd,"phpunit.xml"))||_internals111.existsSync(path158.join(cwd,"phpunit.xml.dist")))return"phpunit";return null}function isTestDirectoryPath(normalizedPath2){return normalizedPath2.split("/").some((segment)=>TEST_DIRECTORY_NAMES.includes(segment))}function resolveWorkspacePath(file3,workingDir){return path158.isAbsolute(file3)?path158.resolve(file3):path158.resolve(workingDir,file3)}function toWorkspaceOutputPath(absolutePath2,workingDir,preferRelative){if(!preferRelative)return absolutePath2;return path158.relative(workingDir,absolutePath2)}function dedupePush(target,value){if(!target.includes(value))target.push(value)}function buildLanguageSpecificTestNames(nameWithoutExt,ext){switch(ext){case".go":return[`${nameWithoutExt}_test.go`];case".py":return[`test_${nameWithoutExt}.py`,`${nameWithoutExt}_test.py`];case".rb":return[`${nameWithoutExt}_spec.rb`];case".java":return[`${nameWithoutExt}Test.java`,`${nameWithoutExt}Tests.java`,`Test${nameWithoutExt}.java`,`${nameWithoutExt}IT.java`];case".cs":return[`${nameWithoutExt}Test.cs`,`${nameWithoutExt}Tests.cs`];case".kt":return[`${nameWithoutExt}Test.kt`,`${nameWithoutExt}Tests.kt`,`Test${nameWithoutExt}.kt`];case".php":return[`${nameWithoutExt}Test.php`,`${nameWithoutExt}Tests.php`,`Test${nameWithoutExt}.php`];case".ps1":return[`${nameWithoutExt}.Tests.ps1`,`${nameWithoutExt}.tests.ps1`];default:return[]}}function getRepoLevelCandidateDirectories(workingDir,relativePath2,ext){let relativeDir=path158.dirname(relativePath2),nestedRelativeDir=relativeDir==="."?"":relativeDir,directories=TEST_DIRECTORY_NAMES.flatMap((dirName)=>{let rootDir=path158.join(workingDir,dirName);return nestedRelativeDir?[rootDir,path158.join(rootDir,nestedRelativeDir)]:[rootDir]}),normalizedRelativePath=relativePath2.replace(/\\/g,"/");if(ext===".java"&&normalizedRelativePath.startsWith("src/main/java/"))directories.push(path158.join(workingDir,"src/test/java",path158.dirname(normalizedRelativePath.slice(14))));if((ext===".kt"||ext===".java")&&normalizedRelativePath.startsWith("src/main/kotlin/"))directories.push(path158.join(workingDir,"src/test/kotlin",path158.dirname(normalizedRelativePath.slice(16))));return[...new Set(directories)]}function hasCompoundTestExtension(filename){let lower=filename.toLowerCase();return COMPOUND_TEST_EXTENSIONS.some((ext)=>lower.endsWith(ext))}function isLanguageSpecificTestFile(basename22){let lower=basename22.toLowerCase();if(lower.endsWith("_test.go"))return!0;if(lower.endsWith(".py")&&(lower.startsWith("test_")||lower.endsWith("_test.py")))return!0;if(lower.endsWith("_spec.rb"))return!0;if(lower.endsWith(".java")&&(/^Test[A-Z]/.test(basename22)||basename22.endsWith("Test.java")||basename22.endsWith("Tests.java")||lower.endsWith("it.java")))return!0;if(lower.endsWith(".cs")&&(lower.endsWith("test.cs")||lower.endsWith("tests.cs")))return!0;if(lower.endsWith(".kt")&&(/^Test[A-Z]/.test(basename22)||lower.endsWith("test.kt")||lower.endsWith("tests.kt")))return!0;if(lower.endsWith(".php")&&(/^Test[A-Z]/.test(basename22)||basename22.endsWith("Test.php")||basename22.endsWith("Tests.php")))return!0;if(lower.endsWith(".tests.ps1"))return!0;return!1}function isConventionTestFilePath(filePath){let normalizedPath2=filePath.replace(/\\/g,"/"),basename22=path158.basename(filePath);return hasCompoundTestExtension(basename22)||basename22.includes(".spec.")||basename22.includes(".test.")||isLanguageSpecificTestFile(basename22)||isTestDirectoryPath(normalizedPath2)}function getTestFilesFromConvention(sourceFiles,workingDir=process.cwd()){let testFiles=[];for(let file3 of sourceFiles){let absoluteFile=resolveWorkspacePath(file3,workingDir),relativeFile=path158.relative(workingDir,absoluteFile),basename22=path158.basename(absoluteFile),dirname65=path158.dirname(absoluteFile),preferRelativeOutput=!path158.isAbsolute(file3);if(isConventionTestFilePath(relativeFile)||isConventionTestFilePath(file3)){dedupePush(testFiles,toWorkspaceOutputPath(absoluteFile,workingDir,preferRelativeOutput));continue}let nameWithoutExt=basename22.replace(/\.[^.]+$/,""),ext=path158.extname(basename22),genericTestNames=[`${nameWithoutExt}.spec${ext}`,`${nameWithoutExt}.test${ext}`],languageSpecificTestNames=buildLanguageSpecificTestNames(nameWithoutExt,ext),colocatedCandidates=[...genericTestNames,...languageSpecificTestNames].map((candidateName)=>path158.join(dirname65,candidateName)),testDirectoryNames=[basename22,...genericTestNames,...languageSpecificTestNames],repoLevelDirectories=getRepoLevelCandidateDirectories(workingDir,relativeFile,ext),possibleTestFiles=[...colocatedCandidates,...TEST_DIRECTORY_NAMES.flatMap((dirName)=>testDirectoryNames.map((candidateName)=>path158.join(dirname65,dirName,candidateName))),...repoLevelDirectories.flatMap((candidateDir)=>testDirectoryNames.map((candidateName)=>path158.join(candidateDir,candidateName)))];for(let testFile of possibleTestFiles)if(fs77.existsSync(testFile))dedupePush(testFiles,toWorkspaceOutputPath(testFile,workingDir,preferRelativeOutput))}return testFiles}async function getTestFilesFromGraph(sourceFiles,workingDir){let testFiles=[],absoluteSourceFiles=sourceFiles.map((sourceFile)=>resolveWorkspacePath(sourceFile,workingDir)),candidateTestFiles=getTestFilesFromConvention(sourceFiles,workingDir);if(sourceFiles.length===0)return testFiles;for(let testFile of candidateTestFiles)try{let absoluteTestFile=resolveWorkspacePath(testFile,workingDir),content=fs77.readFileSync(absoluteTestFile,"utf-8"),testDir=path158.dirname(absoluteTestFile),importRegex=/import\s+.*?\s+from\s+['"]([^'"]+)['"]/g,match;match=importRegex.exec(content);while(match!==null){let importPath=match[1],resolvedImport;if(importPath.startsWith(".")){if(resolvedImport=path158.resolve(testDir,importPath),!path158.extname(resolvedImport))for(let extToTry of[".ts",".tsx",".js",".jsx",".mjs",".cjs"]){let withExt=resolvedImport+extToTry;if(absoluteSourceFiles.includes(withExt)||fs77.existsSync(withExt)){resolvedImport=withExt;break}}}else continue;let importBasename=path158.basename(resolvedImport,path158.extname(resolvedImport)),importDir=path158.dirname(resolvedImport);for(let sourceFile of absoluteSourceFiles){let sourceDir=path158.dirname(sourceFile),sourceBasename=path158.basename(sourceFile,path158.extname(sourceFile)),isRelatedDir=importDir===sourceDir||importDir===path158.join(sourceDir,"__tests__")||importDir===path158.join(sourceDir,"tests")||importDir===path158.join(sourceDir,"test")||importDir===path158.join(sourceDir,"spec");if(resolvedImport===sourceFile||importBasename===sourceBasename&&isRelatedDir){dedupePush(testFiles,testFile);break}}match=importRegex.exec(content)}let requireRegex=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;match=requireRegex.exec(content);while(match!==null){let importPath=match[1];if(importPath.startsWith(".")){let resolvedImport=path158.resolve(testDir,importPath);if(!path158.extname(resolvedImport))for(let extToTry of[".ts",".tsx",".js",".jsx",".mjs",".cjs"]){let withExt=resolvedImport+extToTry;if(absoluteSourceFiles.includes(withExt)||fs77.existsSync(withExt)){resolvedImport=withExt;break}}let importDir=path158.dirname(resolvedImport),importBasename=path158.basename(resolvedImport,path158.extname(resolvedImport));for(let sourceFile of absoluteSourceFiles){let sourceDir=path158.dirname(sourceFile),sourceBasename=path158.basename(sourceFile,path158.extname(sourceFile)),isRelatedDir=importDir===sourceDir||importDir===path158.join(sourceDir,"__tests__")||importDir===path158.join(sourceDir,"tests")||importDir===path158.join(sourceDir,"test")||importDir===path158.join(sourceDir,"spec");if(resolvedImport===sourceFile||importBasename===sourceBasename&&isRelatedDir){dedupePush(testFiles,testFile);break}}}match=requireRegex.exec(content)}}catch{}return testFiles}function getTargetedExecutionUnsupportedReason(framework){switch(framework){case"go-test":return"go test targets packages, not individual test files";case"cargo":return"cargo test targets crates, targets, or test names rather than file paths";case"maven":return"maven test selection is class-based, not file-path based";case"gradle":return"gradle test selection is class-based, not file-path based";case"dotnet-test":return"dotnet test filters by fully qualified names, not file paths";case"ctest":return"ctest filters named tests from the build tree, not source test files";case"swift-test":return"swift test filters test names, not file paths";default:return null}}function buildTestCommand2(framework,scope,files,coverage,baseDir,bail){switch(framework){case"bun":{let args2=["bun","test"];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"vitest":{let args2=["npx","vitest","run","--reporter=json","--outputFile",VITEST_JSON_OUTPUT_RELATIVE_PATH];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail=1");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"jest":{let args2=["npx","jest","--json"];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"mocha":{let args2=["npx","mocha"];if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"pytest":{let args2=process.platform==="win32"?["python","-m","pytest"]:["python3","-m","pytest"];if(coverage)args2.push("--cov=.","--cov-report=term-missing");if(bail)args2.push("-x");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"cargo":{let args2=["cargo","test"];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"pester":{if(scope!=="all"&&files.length>0){let psCommand=`Invoke-Pester -Path @('${files.map((f)=>f.replace(/'/g,"''").replace(/`/g,"``").replace(/\$/g,"`$")).join("','")}')`;return["pwsh","-EncodedCommand",Buffer.from(psCommand,"utf16le").toString("base64")]}return["pwsh","-Command","Invoke-Pester"]}case"go-test":return["go","test","./..."];case"maven":return["mvn","test"];case"gradle":{let isWindows=process.platform==="win32",hasGradlewBat=fs77.existsSync(path158.join(baseDir,"gradlew.bat")),hasGradlew=fs77.existsSync(path158.join(baseDir,"gradlew"));if(hasGradlewBat&&isWindows)return["gradlew.bat","test"];if(hasGradlew)return["./gradlew","test"];return["gradle","test"]}case"dotnet-test":return["dotnet","test"];case"ctest":return["ctest","--test-dir",["build","_build","cmake-build-debug","cmake-build-release","out"].find((d)=>fs77.existsSync(path158.join(baseDir,d,"CMakeCache.txt")))??"build"];case"swift-test":return["swift","test"];case"dart-test":return _internals111.isCommandAvailable("flutter")?["flutter","test",...files]:["dart","test",...files];case"rspec":{let args2=_internals111.isCommandAvailable("bundle")?["bundle","exec","rspec"]:["rspec"];if(bail)args2.push("--fail-fast");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"minitest":if(scope!=="all"&&files.length>0)return["ruby","-Itest","-e",files.map((f)=>`require_relative '${f.replace(/\\/g,"/").replace(/'/g,"\\'")}'`).join("; ")];return["ruby","-Itest","-e",'Dir.glob("test/**/*_test.rb").sort.each { |f| require_relative f }'];case"pest":{let args2=[phpVendorBin4("pest")];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"phpunit":{let args2=[phpVendorBin4("phpunit")];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"php-artisan":{let args2=["php","artisan","test"];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}default:return null}}function phpVendorBin4(name){return path158.join("vendor","bin",process.platform==="win32"?`${name}.bat`:name)}function mapFrameworkStatusToResult(status){if(typeof status!=="string")return null;let normalized=status.toLowerCase();if(normalized==="pass"||normalized==="passed")return"pass";if(normalized==="fail"||normalized==="failed")return"fail";if(normalized==="skip"||normalized==="skipped"||normalized==="pending"||normalized==="todo")return"skip";return null}function firstLine(value){if(typeof value!=="string")return;let line=value.split(`
|
|
1922
|
+
`),records=[];for(let line of lines){let trimmed=line.trim();if(trimmed.length===0)continue;try{let parsed=JSON.parse(trimmed),record3=parseStoredRecord(parsed);if(record3)records.push(record3)}catch{}}return records}catch(err){throw Error(`Failed to read test history: ${err instanceof Error?err.message:String(err)}`)}}function getAllHistory(workingDir){let historyPath=getHistoryPath(workingDir),records=readAllRecords2(historyPath);return records.sort((a,b)=>new Date(a.timestamp).getTime()-new Date(b.timestamp).getTime()),records}var MAX_HISTORY_PER_TEST=20,MAX_ERROR_LENGTH=500,MAX_STACK_LENGTH=200,MAX_CHANGED_FILES=50,HISTORY_WRITE_LOCK_TIMEOUT_MS=5000,HISTORY_WRITE_LOCK_STALE_MS=60000,HISTORY_WRITE_LOCK_BACKOFF_MS=10,DANGEROUS_PROPERTY_NAMES,_internals108;var init_history_store=__esm(()=>{init_manager2();DANGEROUS_PROPERTY_NAMES=new Set(["__proto__","constructor","prototype"]);_internals108={validateProjectRoot}});import*as fs72 from"node:fs";import*as path153 from"node:path";function resolveWorkingDirectory(workingDirectory,fallbackDirectory){if(workingDirectory==null||workingDirectory===""){if(typeof fallbackDirectory!=="string"||fallbackDirectory==="")return{success:!1,message:"Invalid working_directory: no explicit working_directory was provided and fallbackDirectory is missing or not a string"};return{success:!0,directory:fallbackDirectory}}if(typeof workingDirectory!=="string")return{success:!1,message:"Invalid working_directory: path must be a string"};if(workingDirectory.includes("\x00"))return{success:!1,message:"Invalid working_directory: null bytes are not allowed"};let reservedDevicePattern=/^(NUL|CON|AUX|COM[1-9]|LPT[1-9])(\..*)?$/i;if(workingDirectory.startsWith("\\\\")||process.platform==="win32"&&reservedDevicePattern.test(workingDirectory))return{success:!1,message:"Invalid working_directory: Windows device paths are not allowed"};if(workingDirectory.split(/[\\/]/).includes(".."))return{success:!1,message:"Invalid working_directory: path traversal sequences (..) are not allowed"};let normalizedDir=path153.normalize(workingDirectory),resolvedDir=path153.resolve(normalizedDir),statResult;try{statResult=fs72.statSync(resolvedDir)}catch{return{success:!1,message:`Invalid working_directory: path "${resolvedDir}" does not exist or is inaccessible`}}if(!statResult.isDirectory())return{success:!1,message:`Invalid working_directory: path "${resolvedDir}" is not a directory`};if(typeof fallbackDirectory!=="string"||fallbackDirectory==="")return{success:!0,directory:resolvedDir};let resolvedFallback=path153.resolve(fallbackDirectory),fallbackExists=!1;try{fs72.statSync(resolvedFallback),fallbackExists=!0}catch{fallbackExists=!1}if(fallbackExists){if(resolvedDir.startsWith(resolvedFallback+path153.sep))return{success:!1,message:`Invalid working_directory: "${workingDirectory}" resolves to "${resolvedDir}" which is a subdirectory of fallback "${resolvedFallback}". Pass the project root path or omit working_directory entirely.`}}return{success:!0,directory:resolvedDir}}var init_resolve_working_directory=()=>{};class LanguageBackendRegistry{backends=new Map;register(backend){let existing=this.backends.get(backend.id);if(existing&&existing!==backend)throw Error(`LanguageBackendRegistry: backend id "${backend.id}" registered twice. Each LanguageBackend.id must be unique.`);this.backends.set(backend.id,backend)}get(id){return this.backends.get(id)}getOrDefault(id){let registered=this.backends.get(id);if(registered)return registered;let profile=LANGUAGE_REGISTRY.get(id);if(!profile)return;return defaultBackendFor(profile)}unregister(id){this.backends.delete(id)}}var LANGUAGE_BACKEND_REGISTRY;var init_registry_backend=__esm(()=>{init_default_backend();init_profiles();LANGUAGE_BACKEND_REGISTRY=new LanguageBackendRegistry});import*as fs73 from"node:fs";import*as path154 from"node:path";function detectLaravelProject(directory){let signals=getLaravelSignals(directory);return[signals.hasArtisanFile,signals.hasLaravelFrameworkDep,signals.hasConfigApp].filter(Boolean).length>=2}function getLaravelSignals(directory){let hasArtisanFile=checkArtisanFile(directory),hasLaravelFrameworkDep=checkLaravelFrameworkDep(directory),hasConfigApp=checkConfigApp(directory);return{hasArtisanFile,hasLaravelFrameworkDep,hasConfigApp}}function checkArtisanFile(directory){let artisanPath=path154.join(directory,"artisan");if(!fs73.existsSync(artisanPath))return!1;try{return fs73.statSync(artisanPath).isFile()}catch{return!1}}function checkLaravelFrameworkDep(directory){let composerPath=path154.join(directory,"composer.json");if(!fs73.existsSync(composerPath))return!1;try{let content=fs73.readFileSync(composerPath,"utf-8");return typeof(JSON.parse(content)?.require??{})["laravel/framework"]==="string"}catch{return!1}}function checkConfigApp(directory){return fs73.existsSync(path154.join(directory,"config","app.php"))}function isLarastanConfigured(directory){let neonPath=path154.join(directory,"phpstan.neon");if(!fs73.existsSync(neonPath))return!1;try{let fd=fs73.openSync(neonPath,"r");try{let buf=Buffer.alloc(4096),bytesRead=fs73.readSync(fd,buf,0,4096,0),content=buf.subarray(0,bytesRead).toString("utf-8");return content.includes("nunomaduro/larastan")||content.includes("larastan/larastan")}finally{fs73.closeSync(fd)}}catch{return!1}}function getLaravelCommandOverlay(directory){if(!detectLaravelProject(directory))return null;let lintCommand=null;if(fs73.existsSync(path154.join(directory,"pint.json")))lintCommand="vendor/bin/pint --test";else if(fs73.existsSync(path154.join(directory,".php-cs-fixer.php")))lintCommand="vendor/bin/php-cs-fixer fix --dry-run --diff";let staticAnalysisCommand=null,staticAnalysisTool=null,hasPhpstanNeon=fs73.existsSync(path154.join(directory,"phpstan.neon")),hasPhpstanNeonDist=fs73.existsSync(path154.join(directory,"phpstan.neon.dist"));if(hasPhpstanNeon||hasPhpstanNeonDist)staticAnalysisCommand="vendor/bin/phpstan analyse",staticAnalysisTool=isLarastanConfigured(directory)?"larastan":"phpstan";return{testCommand:"php artisan test",lintCommand,staticAnalysisCommand,staticAnalysisTool,auditCommand:"composer audit --locked --format=json",supportsParallel:!0}}var init_framework_detector=()=>{};import*as fs74 from"node:fs";import*as path155 from"node:path";async function selectFramework3(dir){if(detectLaravelProject(dir))return{name:"laravel",detectedVia:"Laravel signals (artisan / composer.json / config/app.php)"};return null}async function selectTestFramework(dir){if(detectLaravelProject(dir))return{name:"php-artisan",cmd:["php","artisan","test"],cwd:dir,detectedVia:"Laravel signals (artisan / composer.json / config/app.php)"};if(fs74.existsSync(path155.join(dir,"Pest.php")))return{name:"pest",cmd:[phpVendorBin3("pest")],cwd:dir,detectedVia:"Pest.php"};if(fs74.existsSync(path155.join(dir,"phpunit.xml")))return{name:"phpunit",cmd:[phpVendorBin3("phpunit")],cwd:dir,detectedVia:"phpunit.xml"};if(fs74.existsSync(path155.join(dir,"phpunit.xml.dist")))return{name:"phpunit",cmd:[phpVendorBin3("phpunit")],cwd:dir,detectedVia:"phpunit.xml.dist"};return null}function phpVendorBin3(name){return path155.join("vendor","bin",process.platform==="win32"?`${name}.bat`:name)}function buildPhpBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID3);if(!profile)throw Error("buildPhpBackend: php profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...defaultBackendFor(profile),selectFramework:selectFramework3,selectTestFramework}}var PROFILE_ID3="php";var init_php2=__esm(()=>{init_default_backend();init_framework_detector();init_profiles()});import*as fs75 from"node:fs";import*as path156 from"node:path";function readPackageJsonRaw(dir){try{let content=fs75.readFileSync(path156.join(dir,"package.json"),"utf-8");return JSON.parse(content)}catch{return null}}function readPackageJson(dir){return _internals109.readPackageJsonRaw(dir)}function readPackageJsonTestScript(dir){return readPackageJson(dir)?.scripts?.test??null}function frameworkFromScriptsTest(script){if(script.includes("vitest"))return"vitest";if(script.includes("jest"))return"jest";if(script.includes("mocha"))return"mocha";if(script.includes("bun test"))return"bun:test";return null}function frameworkFromDevDeps(devDeps){if(!devDeps)return null;if(devDeps.vitest||devDeps["@vitest/ui"])return"vitest";if(devDeps.jest||devDeps["@types/jest"])return"jest";if(devDeps.mocha||devDeps["@types/mocha"])return"mocha";return null}function selectionFromFramework(profile,fwName,dir,detectedVia){let fw=profile.test.frameworks.find((f)=>f.name===fwName);if(!fw)return null;let argv=tokenizeCommand(fw.cmd);if(argv.length===0)return null;return{name:fw.name,cmd:argv,cwd:dir,detectedVia,filesIgnored:!1}}async function selectTestFramework2(dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)return null;let pkg=readPackageJson(dir),script=pkg?.scripts?.test;if(script){let fwName=frameworkFromScriptsTest(script);if(fwName){let sel=selectionFromFramework(profile,fwName,dir,"package.json#scripts.test");if(sel)return sel}}let devDepsFw=frameworkFromDevDeps(pkg?.devDependencies);if(devDepsFw){let sel=selectionFromFramework(profile,devDepsFw,dir,"package.json#devDependencies");if(sel)return sel}return defaultSelectTestFramework(profile,dir)}function buildTestCommand(framework,files,dir,opts){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)return null;return defaultBuildTestCommand(profile,framework,files,dir,opts)}function parseTestOutput(framework,stdout,stderr,exitCode){return defaultParseTestOutput(framework,stdout,stderr,exitCode)}async function selectFramework4(dir){let pkg=readPackageJson(dir);if(!pkg)return null;let deps={...pkg.dependencies,...pkg.devDependencies},order=[["next","next"],["nuxt","nuxt"],["@angular/core","angular"],["svelte","svelte"],["react","react"],["vue","vue"],["express","express"],["fastify","fastify"],["@nestjs/core","nestjs"]];for(let[pkgName,displayName]of order)if(deps[pkgName])return{name:displayName,detectedVia:`package.json#dependencies.${pkgName}`};return null}async function selectEntryPoints3(dir){let pkg=readPackageJson(dir);if(!pkg)return[];let points=[],obj=pkg;if(obj.bin)if(typeof obj.bin==="string")points.push(obj.bin);else for(let v of Object.values(obj.bin))points.push(v);if(obj.main)points.push(obj.main);if(obj.module&&obj.module!==obj.main)points.push(obj.module);if(obj.exports&&typeof obj.exports==="object"){let root=obj.exports["."];if(typeof root==="string"&&!points.includes(root))points.push(root)}return[...new Set(points.filter((p)=>p.length>0))]}function extractImports4(_sourceFile,source){let out=new Set;for(let re of[IMPORT_REGEX_ES2,IMPORT_REGEX_BARE,IMPORT_REGEX_REQUIRE2,IMPORT_REGEX_DYNAMIC,IMPORT_REGEX_REEXPORT2]){re.lastIndex=0;let m=re.exec(source);while(m!==null)out.add(m[1]),m=re.exec(source)}return[...out]}async function selectBuildCommand(dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)return null;return defaultSelectBuildCommand(profile,dir)}async function testFilesFor(sourceFile,dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)return[];return defaultTestFilesFor(profile,sourceFile,dir)}function buildTypescriptBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)throw Error("buildTypescriptBackend: typescript profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...profile,selectTestFramework:selectTestFramework2,buildTestCommand,parseTestOutput,extractImports:extractImports4,selectBuildCommand,testFilesFor,selectFramework:selectFramework4,selectEntryPoints:selectEntryPoints3}}var PROFILE_ID4="typescript",IMPORT_REGEX_ES2,IMPORT_REGEX_BARE,IMPORT_REGEX_REQUIRE2,IMPORT_REGEX_DYNAMIC,IMPORT_REGEX_REEXPORT2,_internals109;var init_typescript=__esm(()=>{init_default_backend();init_profiles();IMPORT_REGEX_ES2=/import\s+[\s\S]*?\s+from\s+['"]([^'"]+)['"]/g,IMPORT_REGEX_BARE=/import\s+['"]([^'"]+)['"]/g,IMPORT_REGEX_REQUIRE2=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,IMPORT_REGEX_DYNAMIC=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,IMPORT_REGEX_REEXPORT2=/export\s+(?:\{[^}]*\}|\*)\s+from\s+['"]([^'"]+)['"]/g;_internals109={readPackageJsonRaw,readPackageJsonTestScript,frameworkFromScriptsTest}});function registerAllBackends(){if(registered)return;LANGUAGE_BACKEND_REGISTRY.register(buildTypescriptBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildPythonBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildGoBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildPhpBackend()),registered=!0}var registered=!1;var init_backends=__esm(()=>{init_registry_backend();init_go2();init_php2();init_python2();init_typescript();registerAllBackends()});var exports_dispatch={};__export(exports_dispatch,{pickedProfiles:()=>pickedProfiles,pickBackend:()=>pickBackend,clearDispatchCache:()=>clearDispatchCache,_internals:()=>_internals110});import*as fs76 from"node:fs";import*as path157 from"node:path";function safeReaddirSet(dir){try{return new Set(fs76.readdirSync(dir))}catch{return new Set}}function manifestHash(dir){let entries=safeReaddirSet(dir);if(entries.size===0)return"";let parts=[];for(let name of MANIFEST_FILES){if(!entries.has(name))continue;try{let stat13=fs76.statSync(path157.join(dir,name));parts.push(`${name}:${stat13.size}:${stat13.mtimeMs}:${stat13.ino}`)}catch{}}return parts.join("|")}function findManifestRoot(start){let resolved=path157.resolve(start),cached3=manifestRootCache.get(resolved);if(cached3!==void 0)return cached3;let cur=resolved;for(let i=0;i<32;i++){let entries=safeReaddirSet(cur);if(entries.size>0){for(let name of MANIFEST_FILES)if(entries.has(name))return manifestRootCache.set(resolved,cur),cur;if(entries.has(".git"))return manifestRootCache.set(resolved,cur),cur}let parent=path157.dirname(cur);if(parent===cur)break;cur=parent}return manifestRootCache.set(resolved,start),start}function evictIfNeeded(){if(cache2.size<=_internals110.cacheCapacity)return;let oldestKey,oldestOrder=1/0;for(let[k,v]of cache2.entries())if(v.insertOrder<oldestOrder)oldestOrder=v.insertOrder,oldestKey=k;if(oldestKey!==void 0)cache2.delete(oldestKey)}async function pickBackend(dir){let root=findManifestRoot(dir),hash4=manifestHash(root),cacheKey=root,cached3=cache2.get(cacheKey);if(cached3&&cached3.hash===hash4)return cached3.backend;if(hash4==="")return cache2.set(cacheKey,{hash:hash4,backend:null,profiles:[],insertOrder:insertCounter++}),evictIfNeeded(),null;let profiles=await _internals110.detectProjectLanguages(root);if(profiles.length===0)return cache2.set(cacheKey,{hash:hash4,backend:null,profiles:[],insertOrder:insertCounter++}),evictIfNeeded(),null;let winner=profiles[0],backend=LANGUAGE_BACKEND_REGISTRY.getOrDefault(winner.id)??null;return cache2.set(cacheKey,{hash:hash4,backend,profiles:profiles.map((p)=>({id:p.id})),insertOrder:insertCounter++}),evictIfNeeded(),backend}function pickedProfiles(dir){let root=findManifestRoot(dir);return cache2.get(root)?.profiles??[]}function clearDispatchCache(){cache2.clear(),manifestRootCache.clear(),insertCounter=0}var _internals110,cache2,insertCounter=0,MANIFEST_FILES,_MANIFEST_SET,manifestRootCache;var init_dispatch=__esm(()=>{init_backends();init_detector();init_registry_backend();_internals110={detectProjectLanguages,cacheCapacity:64},cache2=new Map,MANIFEST_FILES=["package.json","tsconfig.json","pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","Cargo.toml","go.mod","pom.xml","build.gradle","build.gradle.kts","build.zig","CMakeLists.txt","Makefile","meson.build","Package.swift","pubspec.yaml","Gemfile","composer.json"],_MANIFEST_SET=new Set(MANIFEST_FILES);manifestRootCache=new Map});import*as fs77 from"node:fs";import*as path158 from"node:path";async function estimateFanOut(sourceFiles,cwd){try{let impactMap=await _internals111.loadImpactMap(cwd,{skipRebuild:!0}),uniqueTestFiles=new Set;for(let sourceFile of sourceFiles){let normalizedPath2=path158.resolve(cwd,sourceFile).replace(/\\/g,"/"),testFiles=impactMap[normalizedPath2];if(testFiles)for(let testFile of testFiles)uniqueTestFiles.add(testFile)}return{estimatedCount:uniqueTestFiles.size}}catch{return{estimatedCount:0}}}function isAbsolutePath(str){if(str.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test(str))return!0;if(/^\\\\/.test(str))return!0;if(/^\\\\\.\\/.test(str))return!0;return!1}function containsPowerShellMetacharacters(str){return POWERSHELL_METACHARACTERS.test(str)}function validateArgs2(args2){if(typeof args2!=="object"||args2===null)return!1;let obj=args2;if(obj.scope!==void 0){if(obj.scope!=="all"&&obj.scope!=="convention"&&obj.scope!=="graph"&&obj.scope!=="impact")return!1}if(obj.files!==void 0){if(!Array.isArray(obj.files))return!1;for(let f of obj.files){if(typeof f!=="string")return!1;if(isAbsolutePath(f))return!1;if(containsPathTraversal(f))return!1;if(containsControlChars(f))return!1;if(containsPowerShellMetacharacters(f))return!1}}if(obj.coverage!==void 0){if(typeof obj.coverage!=="boolean")return!1}if(obj.bail!==void 0){if(typeof obj.bail!=="boolean")return!1}if(obj.timeout_ms!==void 0){if(typeof obj.timeout_ms!=="number")return!1;if(obj.timeout_ms<0||obj.timeout_ms>MAX_TIMEOUT_MS2)return!1}return!0}function hasPackageJsonDependency(deps,...patterns){for(let pattern of patterns)if(deps[pattern])return!0;return!1}function hasDevDependency(devDeps,...patterns){if(!devDeps)return!1;return hasPackageJsonDependency(devDeps,...patterns)}function detectGoTest(cwd){return _internals111.existsSync(path158.join(cwd,"go.mod"))&&_internals111.isCommandAvailable("go")}function detectJavaMaven(cwd){return _internals111.existsSync(path158.join(cwd,"pom.xml"))&&_internals111.isCommandAvailable("mvn")}function detectGradle(cwd){let hasBuildFile=_internals111.existsSync(path158.join(cwd,"build.gradle"))||_internals111.existsSync(path158.join(cwd,"build.gradle.kts")),hasGradlew=_internals111.existsSync(path158.join(cwd,"gradlew"))||_internals111.existsSync(path158.join(cwd,"gradlew.bat"));return hasBuildFile&&(hasGradlew||_internals111.isCommandAvailable("gradle"))}function detectDotnetTest(cwd){try{return _internals111.readdirSync(cwd).some((f)=>f.endsWith(".csproj"))&&_internals111.isCommandAvailable("dotnet")}catch{return!1}}function detectCTest(cwd){let hasSource=_internals111.existsSync(path158.join(cwd,"CMakeLists.txt")),hasBuildCache=_internals111.existsSync(path158.join(cwd,"CMakeCache.txt"))||_internals111.existsSync(path158.join(cwd,"build","CMakeCache.txt"));return(hasSource||hasBuildCache)&&_internals111.isCommandAvailable("ctest")}function detectSwiftTest(cwd){return _internals111.existsSync(path158.join(cwd,"Package.swift"))&&_internals111.isCommandAvailable("swift")}function detectDartTest(cwd){return _internals111.existsSync(path158.join(cwd,"pubspec.yaml"))&&(_internals111.isCommandAvailable("dart")||_internals111.isCommandAvailable("flutter"))}function detectRSpec(cwd){let hasRSpecFile=_internals111.existsSync(path158.join(cwd,".rspec")),hasGemfile=_internals111.existsSync(path158.join(cwd,"Gemfile")),hasSpecDir=_internals111.existsSync(path158.join(cwd,"spec"));return(hasRSpecFile||hasGemfile&&hasSpecDir)&&(_internals111.isCommandAvailable("bundle")||_internals111.isCommandAvailable("rspec"))}function detectMinitest(cwd){return _internals111.existsSync(path158.join(cwd,"test"))&&(_internals111.existsSync(path158.join(cwd,"Gemfile"))||_internals111.existsSync(path158.join(cwd,"Rakefile")))&&_internals111.isCommandAvailable("ruby")}async function detectTestFrameworkViaDispatch(cwd){try{let{pickBackend:pickBackend2}=await Promise.resolve().then(() => (init_dispatch(),exports_dispatch)),backend=await pickBackend2(cwd);if(!backend?.selectTestFramework)return"none";let sel=await backend.selectTestFramework(cwd);if(!sel)return"none";return DISPATCH_FRAMEWORK_MAP[sel.name]??"none"}catch{return"none"}}async function buildTestCommandViaDispatch(framework,scope,files,coverage,baseDir,bail){if(framework==="none")return null;try{let{pickBackend:pickBackend2}=await Promise.resolve().then(() => (init_dispatch(),exports_dispatch)),backend=await pickBackend2(baseDir);if(backend?.buildTestCommand){let cmd=backend.buildTestCommand(framework,files,baseDir,{scope,coverage,bail});if(cmd)return cmd}return null}catch{return null}}async function parseTestOutputViaDispatch(framework,output,baseDir){if(framework==="none")return null;try{let{pickBackend:pickBackend2}=await Promise.resolve().then(() => (init_dispatch(),exports_dispatch)),backend=await pickBackend2(baseDir);if(!backend?.parseTestOutput)return null;let summary=backend.parseTestOutput(framework,output,"",0),passed=summary.passed??0,failed=summary.failed??0,skipped=summary.skipped??0,total=summary.total??passed+failed+skipped,result={totals:{passed,failed,skipped,total}};if(summary.coveragePercent!==void 0)result.coveragePercent=summary.coveragePercent;return result}catch{return null}}async function detectTestFramework(cwd){let baseDir=cwd;try{let packageJsonPath=path158.join(baseDir,"package.json");if(_internals111.existsSync(packageJsonPath)){let content=_internals111.readFileSync(packageJsonPath,"utf-8"),pkg=JSON.parse(content),_deps=pkg.dependencies||{},devDeps=pkg.devDependencies||{},scripts=pkg.scripts||{};if(scripts.test?.includes("vitest"))return"vitest";if(scripts.test?.includes("jest"))return"jest";if(scripts.test?.includes("mocha"))return"mocha";if(scripts.test?.includes("bun test"))return"bun";if(hasDevDependency(devDeps,"vitest","@vitest/ui"))return"vitest";if(hasDevDependency(devDeps,"jest","@types/jest"))return"jest";if(hasDevDependency(devDeps,"mocha","@types/mocha"))return"mocha";if(_internals111.existsSync(path158.join(baseDir,"bun.lockb"))||_internals111.existsSync(path158.join(baseDir,"bun.lock"))){if(scripts.test?.includes("bun"))return"bun"}}}catch{}try{let pyprojectTomlPath=path158.join(baseDir,"pyproject.toml"),setupCfgPath=path158.join(baseDir,"setup.cfg"),requirementsTxtPath=path158.join(baseDir,"requirements.txt");if(_internals111.existsSync(pyprojectTomlPath)){let content=_internals111.readFileSync(pyprojectTomlPath,"utf-8");if(content.includes("[tool.pytest"))return"pytest";if(content.includes("pytest"))return"pytest"}if(_internals111.existsSync(setupCfgPath)){if(_internals111.readFileSync(setupCfgPath,"utf-8").includes("[pytest]"))return"pytest"}if(_internals111.existsSync(requirementsTxtPath)){if(_internals111.readFileSync(requirementsTxtPath,"utf-8").includes("pytest"))return"pytest"}}catch{}try{let cargoTomlPath=path158.join(baseDir,"Cargo.toml");if(_internals111.existsSync(cargoTomlPath)){let content=_internals111.readFileSync(cargoTomlPath,"utf-8");if(content.includes("[dev-dependencies]")){if(content.includes("tokio")||content.includes("mockall")||content.includes("pretty_assertions"))return"cargo"}}}catch{}try{let pesterConfigPath=path158.join(baseDir,"pester.config.ps1"),pesterConfigJsonPath=path158.join(baseDir,"pester.config.ps1.json"),pesterPs1Path=path158.join(baseDir,"tests.ps1");if(_internals111.existsSync(pesterConfigPath)||_internals111.existsSync(pesterConfigJsonPath)||_internals111.existsSync(pesterPs1Path))return"pester"}catch{}let phpFramework=detectPhpTest(baseDir);if(phpFramework)return phpFramework;if(detectGoTest(baseDir))return"go-test";if(detectJavaMaven(baseDir))return"maven";if(detectGradle(baseDir))return"gradle";if(detectDotnetTest(baseDir))return"dotnet-test";if(detectCTest(baseDir))return"ctest";if(detectSwiftTest(baseDir))return"swift-test";if(detectDartTest(baseDir))return"dart-test";if(detectRSpec(baseDir))return"rspec";if(detectMinitest(baseDir))return"minitest";return"none"}function detectPhpTest(cwd){if(_internals111.existsSync(path158.join(cwd,"artisan"))&&_internals111.existsSync(path158.join(cwd,"composer.json")))return"php-artisan";if(_internals111.existsSync(path158.join(cwd,"Pest.php")))return"pest";if(_internals111.existsSync(path158.join(cwd,"phpunit.xml"))||_internals111.existsSync(path158.join(cwd,"phpunit.xml.dist")))return"phpunit";return null}function isTestDirectoryPath(normalizedPath2){return normalizedPath2.split("/").some((segment)=>TEST_DIRECTORY_NAMES.includes(segment))}function resolveWorkspacePath(file3,workingDir){return path158.isAbsolute(file3)?path158.resolve(file3):path158.resolve(workingDir,file3)}function toWorkspaceOutputPath(absolutePath2,workingDir,preferRelative){if(!preferRelative)return absolutePath2;return path158.relative(workingDir,absolutePath2)}function dedupePush(target,value){if(!target.includes(value))target.push(value)}function buildLanguageSpecificTestNames(nameWithoutExt,ext){switch(ext){case".go":return[`${nameWithoutExt}_test.go`];case".py":return[`test_${nameWithoutExt}.py`,`${nameWithoutExt}_test.py`];case".rb":return[`${nameWithoutExt}_spec.rb`];case".java":return[`${nameWithoutExt}Test.java`,`${nameWithoutExt}Tests.java`,`Test${nameWithoutExt}.java`,`${nameWithoutExt}IT.java`];case".cs":return[`${nameWithoutExt}Test.cs`,`${nameWithoutExt}Tests.cs`];case".kt":return[`${nameWithoutExt}Test.kt`,`${nameWithoutExt}Tests.kt`,`Test${nameWithoutExt}.kt`];case".php":return[`${nameWithoutExt}Test.php`,`${nameWithoutExt}Tests.php`,`Test${nameWithoutExt}.php`];case".ps1":return[`${nameWithoutExt}.Tests.ps1`,`${nameWithoutExt}.tests.ps1`];default:return[]}}function getRepoLevelCandidateDirectories(workingDir,relativePath2,ext){let relativeDir=path158.dirname(relativePath2),nestedRelativeDir=relativeDir==="."?"":relativeDir,directories=TEST_DIRECTORY_NAMES.flatMap((dirName)=>{let rootDir=path158.join(workingDir,dirName);return nestedRelativeDir?[rootDir,path158.join(rootDir,nestedRelativeDir)]:[rootDir]}),normalizedRelativePath=relativePath2.replace(/\\/g,"/");if(ext===".java"&&normalizedRelativePath.startsWith("src/main/java/"))directories.push(path158.join(workingDir,"src/test/java",path158.dirname(normalizedRelativePath.slice(14))));if((ext===".kt"||ext===".java")&&normalizedRelativePath.startsWith("src/main/kotlin/"))directories.push(path158.join(workingDir,"src/test/kotlin",path158.dirname(normalizedRelativePath.slice(16))));return[...new Set(directories)]}function hasCompoundTestExtension(filename){let lower=filename.toLowerCase();return COMPOUND_TEST_EXTENSIONS.some((ext)=>lower.endsWith(ext))}function isLanguageSpecificTestFile(basename23){let lower=basename23.toLowerCase();if(lower.endsWith("_test.go"))return!0;if(lower.endsWith(".py")&&(lower.startsWith("test_")||lower.endsWith("_test.py")))return!0;if(lower.endsWith("_spec.rb"))return!0;if(lower.endsWith(".java")&&(/^Test[A-Z]/.test(basename23)||basename23.endsWith("Test.java")||basename23.endsWith("Tests.java")||lower.endsWith("it.java")))return!0;if(lower.endsWith(".cs")&&(lower.endsWith("test.cs")||lower.endsWith("tests.cs")))return!0;if(lower.endsWith(".kt")&&(/^Test[A-Z]/.test(basename23)||lower.endsWith("test.kt")||lower.endsWith("tests.kt")))return!0;if(lower.endsWith(".php")&&(/^Test[A-Z]/.test(basename23)||basename23.endsWith("Test.php")||basename23.endsWith("Tests.php")))return!0;if(lower.endsWith(".tests.ps1"))return!0;return!1}function isConventionTestFilePath(filePath){let normalizedPath2=filePath.replace(/\\/g,"/"),basename23=path158.basename(filePath);return hasCompoundTestExtension(basename23)||basename23.includes(".spec.")||basename23.includes(".test.")||isLanguageSpecificTestFile(basename23)||isTestDirectoryPath(normalizedPath2)}function getTestFilesFromConvention(sourceFiles,workingDir=process.cwd()){let testFiles=[];for(let file3 of sourceFiles){let absoluteFile=resolveWorkspacePath(file3,workingDir),relativeFile=path158.relative(workingDir,absoluteFile),basename23=path158.basename(absoluteFile),dirname65=path158.dirname(absoluteFile),preferRelativeOutput=!path158.isAbsolute(file3);if(isConventionTestFilePath(relativeFile)||isConventionTestFilePath(file3)){dedupePush(testFiles,toWorkspaceOutputPath(absoluteFile,workingDir,preferRelativeOutput));continue}let nameWithoutExt=basename23.replace(/\.[^.]+$/,""),ext=path158.extname(basename23),genericTestNames=[`${nameWithoutExt}.spec${ext}`,`${nameWithoutExt}.test${ext}`],languageSpecificTestNames=buildLanguageSpecificTestNames(nameWithoutExt,ext),colocatedCandidates=[...genericTestNames,...languageSpecificTestNames].map((candidateName)=>path158.join(dirname65,candidateName)),testDirectoryNames=[basename23,...genericTestNames,...languageSpecificTestNames],repoLevelDirectories=getRepoLevelCandidateDirectories(workingDir,relativeFile,ext),possibleTestFiles=[...colocatedCandidates,...TEST_DIRECTORY_NAMES.flatMap((dirName)=>testDirectoryNames.map((candidateName)=>path158.join(dirname65,dirName,candidateName))),...repoLevelDirectories.flatMap((candidateDir)=>testDirectoryNames.map((candidateName)=>path158.join(candidateDir,candidateName)))];for(let testFile of possibleTestFiles)if(fs77.existsSync(testFile))dedupePush(testFiles,toWorkspaceOutputPath(testFile,workingDir,preferRelativeOutput))}return testFiles}async function getTestFilesFromGraph(sourceFiles,workingDir){let testFiles=[],absoluteSourceFiles=sourceFiles.map((sourceFile)=>resolveWorkspacePath(sourceFile,workingDir)),candidateTestFiles=getTestFilesFromConvention(sourceFiles,workingDir);if(sourceFiles.length===0)return testFiles;for(let testFile of candidateTestFiles)try{let absoluteTestFile=resolveWorkspacePath(testFile,workingDir),content=fs77.readFileSync(absoluteTestFile,"utf-8"),testDir=path158.dirname(absoluteTestFile),importRegex=/import\s+.*?\s+from\s+['"]([^'"]+)['"]/g,match;match=importRegex.exec(content);while(match!==null){let importPath=match[1],resolvedImport;if(importPath.startsWith(".")){if(resolvedImport=path158.resolve(testDir,importPath),!path158.extname(resolvedImport))for(let extToTry of[".ts",".tsx",".js",".jsx",".mjs",".cjs"]){let withExt=resolvedImport+extToTry;if(absoluteSourceFiles.includes(withExt)||fs77.existsSync(withExt)){resolvedImport=withExt;break}}}else continue;let importBasename=path158.basename(resolvedImport,path158.extname(resolvedImport)),importDir=path158.dirname(resolvedImport);for(let sourceFile of absoluteSourceFiles){let sourceDir=path158.dirname(sourceFile),sourceBasename=path158.basename(sourceFile,path158.extname(sourceFile)),isRelatedDir=importDir===sourceDir||importDir===path158.join(sourceDir,"__tests__")||importDir===path158.join(sourceDir,"tests")||importDir===path158.join(sourceDir,"test")||importDir===path158.join(sourceDir,"spec");if(resolvedImport===sourceFile||importBasename===sourceBasename&&isRelatedDir){dedupePush(testFiles,testFile);break}}match=importRegex.exec(content)}let requireRegex=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;match=requireRegex.exec(content);while(match!==null){let importPath=match[1];if(importPath.startsWith(".")){let resolvedImport=path158.resolve(testDir,importPath);if(!path158.extname(resolvedImport))for(let extToTry of[".ts",".tsx",".js",".jsx",".mjs",".cjs"]){let withExt=resolvedImport+extToTry;if(absoluteSourceFiles.includes(withExt)||fs77.existsSync(withExt)){resolvedImport=withExt;break}}let importDir=path158.dirname(resolvedImport),importBasename=path158.basename(resolvedImport,path158.extname(resolvedImport));for(let sourceFile of absoluteSourceFiles){let sourceDir=path158.dirname(sourceFile),sourceBasename=path158.basename(sourceFile,path158.extname(sourceFile)),isRelatedDir=importDir===sourceDir||importDir===path158.join(sourceDir,"__tests__")||importDir===path158.join(sourceDir,"tests")||importDir===path158.join(sourceDir,"test")||importDir===path158.join(sourceDir,"spec");if(resolvedImport===sourceFile||importBasename===sourceBasename&&isRelatedDir){dedupePush(testFiles,testFile);break}}}match=requireRegex.exec(content)}}catch{}return testFiles}function getTargetedExecutionUnsupportedReason(framework){switch(framework){case"go-test":return"go test targets packages, not individual test files";case"cargo":return"cargo test targets crates, targets, or test names rather than file paths";case"maven":return"maven test selection is class-based, not file-path based";case"gradle":return"gradle test selection is class-based, not file-path based";case"dotnet-test":return"dotnet test filters by fully qualified names, not file paths";case"ctest":return"ctest filters named tests from the build tree, not source test files";case"swift-test":return"swift test filters test names, not file paths";default:return null}}function buildTestCommand2(framework,scope,files,coverage,baseDir,bail){switch(framework){case"bun":{let args2=["bun","test"];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"vitest":{let args2=["npx","vitest","run","--reporter=json","--outputFile",VITEST_JSON_OUTPUT_RELATIVE_PATH];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail=1");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"jest":{let args2=["npx","jest","--json"];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"mocha":{let args2=["npx","mocha"];if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"pytest":{let args2=process.platform==="win32"?["python","-m","pytest"]:["python3","-m","pytest"];if(coverage)args2.push("--cov=.","--cov-report=term-missing");if(bail)args2.push("-x");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"cargo":{let args2=["cargo","test"];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"pester":{if(scope!=="all"&&files.length>0){let psCommand=`Invoke-Pester -Path @('${files.map((f)=>f.replace(/'/g,"''").replace(/`/g,"``").replace(/\$/g,"`$")).join("','")}')`;return["pwsh","-EncodedCommand",Buffer.from(psCommand,"utf16le").toString("base64")]}return["pwsh","-Command","Invoke-Pester"]}case"go-test":return["go","test","./..."];case"maven":return["mvn","test"];case"gradle":{let isWindows=process.platform==="win32",hasGradlewBat=fs77.existsSync(path158.join(baseDir,"gradlew.bat")),hasGradlew=fs77.existsSync(path158.join(baseDir,"gradlew"));if(hasGradlewBat&&isWindows)return["gradlew.bat","test"];if(hasGradlew)return["./gradlew","test"];return["gradle","test"]}case"dotnet-test":return["dotnet","test"];case"ctest":return["ctest","--test-dir",["build","_build","cmake-build-debug","cmake-build-release","out"].find((d)=>fs77.existsSync(path158.join(baseDir,d,"CMakeCache.txt")))??"build"];case"swift-test":return["swift","test"];case"dart-test":return _internals111.isCommandAvailable("flutter")?["flutter","test",...files]:["dart","test",...files];case"rspec":{let args2=_internals111.isCommandAvailable("bundle")?["bundle","exec","rspec"]:["rspec"];if(bail)args2.push("--fail-fast");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"minitest":if(scope!=="all"&&files.length>0)return["ruby","-Itest","-e",files.map((f)=>`require_relative '${f.replace(/\\/g,"/").replace(/'/g,"\\'")}'`).join("; ")];return["ruby","-Itest","-e",'Dir.glob("test/**/*_test.rb").sort.each { |f| require_relative f }'];case"pest":{let args2=[phpVendorBin4("pest")];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"phpunit":{let args2=[phpVendorBin4("phpunit")];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"php-artisan":{let args2=["php","artisan","test"];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}default:return null}}function phpVendorBin4(name){return path158.join("vendor","bin",process.platform==="win32"?`${name}.bat`:name)}function mapFrameworkStatusToResult(status){if(typeof status!=="string")return null;let normalized=status.toLowerCase();if(normalized==="pass"||normalized==="passed")return"pass";if(normalized==="fail"||normalized==="failed")return"fail";if(normalized==="skip"||normalized==="skipped"||normalized==="pending"||normalized==="todo")return"skip";return null}function firstLine(value){if(typeof value!=="string")return;let line=value.split(`
|
|
1923
1923
|
`).find((part)=>part.trim().length>0)?.trim();return line&&line.length>0?line:void 0}function parseJestLikeJsonTestResults(payload){if(typeof payload!=="object"||payload===null)return[];let rawSuites=payload.testResults;if(!Array.isArray(rawSuites))return[];let parsed=[];for(let suite of rawSuites){if(typeof suite!=="object"||suite===null)continue;let suiteObj=suite,rawFile=typeof suiteObj.name==="string"?suiteObj.name:typeof suiteObj.testFilePath==="string"?suiteObj.testFilePath:void 0;if(!rawFile)continue;let testFile=rawFile.replace(/\\/g,"/"),assertionResults=suiteObj.assertionResults;if(!Array.isArray(assertionResults))continue;for(let assertion of assertionResults){if(typeof assertion!=="object"||assertion===null)continue;let assertionObj=assertion,result=mapFrameworkStatusToResult(assertionObj.status),testName=typeof assertionObj.fullName==="string"?assertionObj.fullName:typeof assertionObj.title==="string"?assertionObj.title:void 0;if(!result||!testName||testName.length===0)continue;let firstFailure=(Array.isArray(assertionObj.failureMessages)?assertionObj.failureMessages:[]).find((entry)=>typeof entry==="string"&&entry.length>0),durationMs=typeof assertionObj.duration==="number"&&Number.isFinite(assertionObj.duration)?Math.max(assertionObj.duration,0):0;parsed.push({testFile,testName,result,durationMs,errorMessage:firstLine(firstFailure),stackPrefix:firstLine(firstFailure)})}}return parsed}function parseBunJsonLines(output){let parsed=[];for(let line of output.split(`
|
|
1924
1924
|
`)){let trimmed=line.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))continue;try{let obj=JSON.parse(trimmed),rawFile=typeof obj.file==="string"?obj.file:typeof obj.testFile==="string"?obj.testFile:typeof obj.path==="string"?obj.path:void 0,rawName=typeof obj.testName==="string"?obj.testName:typeof obj.fullName==="string"?obj.fullName:typeof obj.name==="string"?obj.name:void 0,result=mapFrameworkStatusToResult(typeof obj.status==="string"?obj.status:obj.result);if(!rawFile||!rawName||!result)continue;let errorObj=typeof obj.error==="object"&&obj.error!==null?obj.error:void 0,durationMs=typeof obj.durationMs==="number"&&Number.isFinite(obj.durationMs)?Math.max(obj.durationMs,0):typeof obj.duration==="number"&&Number.isFinite(obj.duration)?Math.max(obj.duration,0):0;parsed.push({testFile:rawFile.replace(/\\/g,"/"),testName:rawName,result,durationMs,errorMessage:firstLine(errorObj?.message??obj.errorMessage),stackPrefix:firstLine(errorObj?.stack)})}catch{}}return parsed}function parseFrameworkJsonTestResults(framework,output){let jsonMatch=output.match(/\{[\s\S]*"testResults"[\s\S]*\}/);if(jsonMatch)try{let parsed=JSON.parse(jsonMatch[0]),testResults=parseJestLikeJsonTestResults(parsed);if(testResults.length>0)return testResults}catch{}for(let line of output.split(`
|
|
1925
1925
|
`)){let trimmed=line.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))continue;try{let parsed=JSON.parse(trimmed),testResults=parseJestLikeJsonTestResults(parsed);if(testResults.length>0)return testResults}catch{}}if(framework==="bun")return parseBunJsonLines(output);return[]}function parseTestOutput2(framework,output){let totals={passed:0,failed:0,skipped:0,total:0},coveragePercent;switch(framework){case"vitest":case"jest":case"bun":{let jsonMatch=output.match(/\{[\s\S]*"testResults"[\s\S]*\}/);if(jsonMatch)try{let parsed=JSON.parse(jsonMatch[0]);if(parsed.numTotalTests!==void 0)totals.passed=parsed.numPassedTests||0,totals.failed=parsed.numFailedTests||0,totals.skipped=parsed.numPendingTests||0,totals.total=parsed.numTotalTests||0;if(parsed.coverage!==void 0)coveragePercent=parsed.coverage}catch{}if(totals.total===0){let passMatch=output.match(/(\d+)\s+pass(ing|ed)?/),failMatch=output.match(/(\d+)\s+fail(ing|ed)?/),skipMatch=output.match(/(\d+)\s+skip(ping|ped)?/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped}let coverageMatch=output.match(/All files[^\d]*(\d+\.?\d*)\s*%/);if(!coveragePercent&&coverageMatch)coveragePercent=parseFloat(coverageMatch[1]);break}case"mocha":{let passMatch=output.match(/(\d+)\s+passing/),failMatch=output.match(/(\d+)\s+failing/),pendingMatch=output.match(/(\d+)\s+pending/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(pendingMatch)totals.skipped=parseInt(pendingMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"pytest":{let passMatch=output.match(/(\d+)\s+passed/),failMatch=output.match(/(\d+)\s+failed/),skipMatch=output.match(/(\d+)\s+skipped/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;let coverageMatch=output.match(/TOTAL\s+(\d+\.?\d*)\s*%/);if(coverageMatch)coveragePercent=parseFloat(coverageMatch[1]);break}case"cargo":{let passMatch=output.match(/test result: ok\. (\d+) passed/),failMatch=output.match(/test result: FAILED\. (\d+) passed; (\d+) failed/);if(failMatch)totals.passed=parseInt(failMatch[1],10),totals.failed=parseInt(failMatch[2],10);else if(passMatch)totals.passed=parseInt(passMatch[1],10);totals.total=totals.passed+totals.failed;break}case"pester":{let passMatch=output.match(/Passed:\s*(\d+)/),failMatch=output.match(/Failed:\s*(\d+)/),skipMatch=output.match(/Skipped:\s*(\d+)/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"go-test":{let passMatches=[...output.matchAll(/--- PASS:/g)],failMatches=[...output.matchAll(/--- FAIL:/g)],skipMatches=[...output.matchAll(/--- SKIP:/g)];totals.passed=passMatches.length,totals.failed=failMatches.length,totals.skipped=skipMatches.length,totals.total=totals.passed+totals.failed+totals.skipped;let covMatch=output.match(/coverage:\s*(\d+\.?\d*)\s*%/);if(covMatch)coveragePercent=parseFloat(covMatch[1]);break}case"maven":{let mavenMatch=output.match(/Tests run:\s*(\d+),\s*Failures:\s*(\d+),\s*Errors:\s*(\d+),\s*Skipped:\s*(\d+)/);if(mavenMatch){let total=parseInt(mavenMatch[1],10),failures=parseInt(mavenMatch[2],10),errors5=parseInt(mavenMatch[3],10),skipped=parseInt(mavenMatch[4],10);totals.failed=failures+errors5,totals.skipped=skipped,totals.passed=total-totals.failed-skipped,totals.total=total}break}case"gradle":{let gradleMatch=output.match(/(\d+) tests? completed(?:,\s*(\d+) failed)?(?:,\s*(\d+) skipped)?/);if(gradleMatch)totals.total=parseInt(gradleMatch[1],10),totals.failed=gradleMatch[2]?parseInt(gradleMatch[2],10):0,totals.skipped=gradleMatch[3]?parseInt(gradleMatch[3],10):0,totals.passed=totals.total-totals.failed-totals.skipped;break}case"dotnet-test":{let passMatch=output.match(/Passed[!:]?\s*(\d+)/i),failMatch=output.match(/Failed[!:]?\s*(\d+)/i),skipMatch=output.match(/Skipped[!:]?\s*(\d+)/i);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"ctest":{let ctestMatch=output.match(/(\d+) tests? failed out of (\d+)/);if(ctestMatch)totals.failed=parseInt(ctestMatch[1],10),totals.total=parseInt(ctestMatch[2],10),totals.passed=totals.total-totals.failed;else{let allPassMatch=output.match(/100% tests passed.*?(\d+) tests?/);if(allPassMatch)totals.total=parseInt(allPassMatch[1],10),totals.passed=totals.total}break}case"swift-test":{let swiftMatch=output.match(/Executed (\d+) tests?,\s*with (\d+) failures?/);if(swiftMatch)totals.total=parseInt(swiftMatch[1],10),totals.failed=parseInt(swiftMatch[2],10),totals.passed=totals.total-totals.failed;break}case"dart-test":{let dartPassMatch=output.match(/\+(\d+):\s*All tests passed/),dartMixMatch=output.match(/\+(\d+)\s+-(\d+):/);if(dartPassMatch)totals.passed=parseInt(dartPassMatch[1],10),totals.total=totals.passed;else if(dartMixMatch)totals.passed=parseInt(dartMixMatch[1],10),totals.failed=parseInt(dartMixMatch[2],10),totals.total=totals.passed+totals.failed;break}case"rspec":{let rspecMatch=output.match(/(\d+) examples?,\s*(\d+) failures?(?:,\s*(\d+) pending)?/);if(rspecMatch)totals.total=parseInt(rspecMatch[1],10),totals.failed=parseInt(rspecMatch[2],10),totals.skipped=rspecMatch[3]?parseInt(rspecMatch[3],10):0,totals.passed=totals.total-totals.failed-totals.skipped;break}case"minitest":{let minitestMatch=output.match(/(\d+) runs?,\s*\d+ assertions?,\s*(\d+) failures?,\s*(\d+) errors?,\s*(\d+) skips?/);if(minitestMatch)totals.total=parseInt(minitestMatch[1],10),totals.failed=parseInt(minitestMatch[2],10)+parseInt(minitestMatch[3],10),totals.skipped=parseInt(minitestMatch[4],10),totals.passed=totals.total-totals.failed-totals.skipped;break}case"pest":case"phpunit":case"php-artisan":{let phpunitMatch=output.match(/Tests:\s*(\d+),\s*Assertions:\s*\d+(?:,\s*Failures:\s*(\d+))?(?:,\s*Errors:\s*(\d+))?(?:,\s*Skipped:\s*(\d+))?/),okMatch=output.match(/OK\s*\((\d+)\s+tests?/);if(phpunitMatch){totals.total=parseInt(phpunitMatch[1],10);let failures=phpunitMatch[2]?parseInt(phpunitMatch[2],10):0,errors5=phpunitMatch[3]?parseInt(phpunitMatch[3],10):0;totals.skipped=phpunitMatch[4]?parseInt(phpunitMatch[4],10):0,totals.failed=failures+errors5,totals.passed=totals.total-totals.failed-totals.skipped}else if(okMatch)totals.total=parseInt(okMatch[1],10),totals.passed=totals.total;break}default:break}return{totals,coveragePercent}}async function readBoundedStream3(stream,maxBytes){let reader=stream.getReader(),chunks=[],totalBytes=0,truncated=!1;try{while(!0){let{done,value}=await reader.read();if(done)break;if(totalBytes+value.length>maxBytes){let remaining=maxBytes-totalBytes;if(remaining>0)chunks.push(value.slice(0,remaining));totalBytes=maxBytes,truncated=!0,reader.cancel().catch(()=>{});break}chunks.push(value),totalBytes+=value.length}}catch{}finally{try{reader.releaseLock()}catch{}}let decoder=new TextDecoder("utf-8",{fatal:!1}),combined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)combined.set(chunk,offset),offset+=chunk.length;return{text:decoder.decode(combined),truncated}}async function runTests(framework,scope,files,coverage,timeout_ms,cwd,bail){if(scope!=="all"&&files.length>0){let unsupportedReason=getTargetedExecutionUnsupportedReason(framework);if(unsupportedReason)return{success:!1,framework,scope,error:`Framework "${framework}" does not support targeted test-file execution`,message:`The resolved test selection cannot be run safely because ${unsupportedReason}. Use a framework-native selector manually or let the architect handle the broader sweep.`,outcome:"error"}}let command=process.env.SWARM_LANG_BACKEND!=="legacy"?await buildTestCommandViaDispatch(framework,scope,files,coverage,cwd,bail)??buildTestCommand2(framework,scope,files,coverage,cwd,bail):buildTestCommand2(framework,scope,files,coverage,cwd,bail);if(!command)return{success:!1,framework,scope,error:`No test command available for framework: ${framework}`,message:"Install a supported test framework to run tests",outcome:"error"};if(command.join(" ").length>MAX_COMMAND_LENGTH2)return{success:!1,framework,scope,command,error:"Command exceeds maximum allowed length",outcome:"error"};let startTime=Date.now(),vitestJsonOutputPath=framework==="vitest"?path158.join(cwd,".swarm","cache","test-runner-vitest.json"):void 0;try{if(vitestJsonOutputPath)try{if(fs77.mkdirSync(path158.dirname(vitestJsonOutputPath),{recursive:!0}),fs77.existsSync(vitestJsonOutputPath))fs77.unlinkSync(vitestJsonOutputPath)}catch{}let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd}),timeoutPromise=new Promise((resolve60)=>setTimeout(()=>{proc.kill(),resolve60(-1)},timeout_ms)),[exitCode,stdoutResult,stderrResult]=await Promise.all([Promise.race([proc.exited,timeoutPromise]),readBoundedStream3(proc.stdout,MAX_OUTPUT_BYTES4),readBoundedStream3(proc.stderr,MAX_OUTPUT_BYTES4)]),duration_ms=Date.now()-startTime,output=stdoutResult.text;if(stderrResult.text)output+=(output?`
|
|
1926
1926
|
`:"")+stderrResult.text;if(vitestJsonOutputPath)try{if(fs77.existsSync(vitestJsonOutputPath)){let vitestJsonOutput=fs77.readFileSync(vitestJsonOutputPath,"utf-8");if(vitestJsonOutput.trim().length>0)output+=(output?`
|
|
1927
1927
|
`:"")+vitestJsonOutput}}catch{}if(stdoutResult.truncated||stderrResult.truncated)output+=`
|
|
1928
|
-
... (output truncated at stream read limit)`;let parsed=process.env.SWARM_LANG_BACKEND!=="legacy"?await parseTestOutputViaDispatch(framework,output,cwd)??parseTestOutput2(framework,output):parseTestOutput2(framework,output),parsedTestCases=parseFrameworkJsonTestResults(framework,output),totals={...parsed.totals},{coveragePercent}=parsed;if(totals.total===0&&parsedTestCases.length>0){for(let entry of parsedTestCases)if(entry.result==="pass")totals.passed++;else if(entry.result==="fail")totals.failed++;else totals.skipped++;totals.total=parsedTestCases.length}let isTimeout=exitCode===-1;if(exitCode===0&&totals.failed===0){let result={success:!0,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,outcome:"pass",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;if(result.message=`${framework} tests passed (${totals.passed}/${totals.total})`,coveragePercent!==void 0)result.message+=` with ${coveragePercent}% coverage`;return result}else{let result={success:!1,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,error:isTimeout?`Tests timed out after ${timeout_ms}ms`:`Tests failed with ${totals.failed} failures`,message:isTimeout?`${framework} tests timed out after ${timeout_ms}ms`:`${framework} tests failed (${totals.failed}/${totals.total} failed)`,outcome:isTimeout?"error":"regression",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;return result}}catch(error93){let duration_ms=Date.now()-startTime;return{success:!1,framework,scope,command,timeout_ms,duration_ms,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error",outcome:"error"}}}function normalizeHistoryTestFile(testFile,workingDir){let normalized=testFile.replace(/\\/g,"/");if(!path158.isAbsolute(testFile))return normalized;let relative33=path158.relative(workingDir,testFile);if(relative33.startsWith("..")||path158.isAbsolute(relative33))return normalized;return relative33.replace(/\\/g,"/")}function combineAggregateResult(current,next){if(current==="fail"||next==="fail")return"fail";if(current==="pass"||next==="pass")return"pass";return"skip"}function recordAndAnalyzeResults(result,testFiles,workingDir,sourceFiles,parsedTestCases){if(!result.totals||result.totals.total===0)return;let now=new Date().toISOString(),changedFiles=(sourceFiles&&sourceFiles.length>0?sourceFiles:testFiles).map((f)=>f.replace(/\\/g,"/")),aggregateResultsByFile=new Map,validParsedCases=parsedTestCases?.filter((parsedCase)=>parsedCase.testFile.length>0&&parsedCase.testName.length>0)??[],allRecords=[];for(let parsedCase of validParsedCases){let normalizedTestFile=normalizeHistoryTestFile(parsedCase.testFile,workingDir);allRecords.push({timestamp:now,taskId:"auto",testFile:normalizedTestFile,testName:parsedCase.testName,result:parsedCase.result,durationMs:parsedCase.durationMs,errorMessage:parsedCase.errorMessage,stackPrefix:parsedCase.stackPrefix,changedFiles}),aggregateResultsByFile.set(normalizedTestFile,combineAggregateResult(aggregateResultsByFile.get(normalizedTestFile),parsedCase.result))}if(aggregateResultsByFile.size===0){let aggregateResult=result.success?"pass":"fail";for(let testFile of testFiles)aggregateResultsByFile.set(testFile.replace(/\\/g,"/"),aggregateResult)}for(let[testFile,aggregateResult]of aggregateResultsByFile)allRecords.push({timestamp:now,taskId:"auto",testFile,testName:AGGREGATE_TEST_NAME,result:aggregateResult,durationMs:result.duration_ms||0,changedFiles});try{batchAppendTestRuns(allRecords,workingDir)}catch{}}function selectHistoryForAnalysis(history){let filesWithIndividualRecords=new Set;for(let record3 of history)if(record3.testName!==AGGREGATE_TEST_NAME)filesWithIndividualRecords.add(record3.testFile.toLowerCase());if(filesWithIndividualRecords.size===0)return history;return history.filter((record3)=>record3.testName!==AGGREGATE_TEST_NAME||!filesWithIndividualRecords.has(record3.testFile.toLowerCase()))}function analyzeFailures(workingDir){let report={flakyTests:[],failureClusters:[],quarantinedFailures:[]};try{let history=selectHistoryForAnalysis(getAllHistory(workingDir));if(history.length===0)return report;report.flakyTests=detectFlakyTests(history);let failingResults=history.filter((r)=>r.result==="fail");if(failingResults.length>0){let{clusters}=classifyAndCluster(failingResults,history);report.failureClusters=clusters.map((c)=>({rootCause:c.rootCause,affectedFiles:c.affectedTestFiles,classification:c.classification}))}for(let entry of report.flakyTests)if(entry.isQuarantined)report.quarantinedFailures.push(`${entry.testFile}: ${entry.testName}`)}catch{}return report}var MAX_OUTPUT_BYTES4=512000,MAX_COMMAND_LENGTH2=500,DEFAULT_TIMEOUT_MS3=60000,MAX_TIMEOUT_MS2=300000,MAX_SAFE_TEST_FILES=50,MAX_SAFE_SOURCE_FILES=1,AGGREGATE_TEST_NAME="(aggregate)",VITEST_JSON_OUTPUT_RELATIVE_PATH=".swarm/cache/test-runner-vitest.json",POWERSHELL_METACHARACTERS,DISPATCH_FRAMEWORK_MAP,COMPOUND_TEST_EXTENSIONS,TEST_DIRECTORY_NAMES,SOURCE_EXTENSIONS,test_runner,_internals111;var init_test_runner=__esm(()=>{init_zod();init_discovery();init_analyzer();init_failure_classifier();init_history_store();init_bun_compat();init_path_security();init_create_tool();init_resolve_working_directory();POWERSHELL_METACHARACTERS=/[|;&`$(){}[\]<>"'#*?\x00-\x1f]/;DISPATCH_FRAMEWORK_MAP={bun:"bun",vitest:"vitest",jest:"jest",mocha:"mocha",pytest:"pytest",cargo:"cargo",pester:"pester","go-test":"go-test",maven:"maven",gradle:"gradle","dotnet-test":"dotnet-test",ctest:"ctest","swift-test":"swift-test","dart-test":"dart-test",rspec:"rspec",minitest:"minitest",pest:"pest",phpunit:"phpunit","php-artisan":"php-artisan","bun:test":"bun","xcodebuild-test":"swift-test","flutter test":"dart-test","dart test":"dart-test",Pest:"pest",PHPUnit:"phpunit"};COMPOUND_TEST_EXTENSIONS=[".test.ts",".test.tsx",".test.js",".test.jsx",".tests.ps1",".spec.ts",".spec.tsx",".spec.js",".spec.jsx",".test.ps1",".spec.ps1"],TEST_DIRECTORY_NAMES=["__tests__","tests","test","spec"];SOURCE_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".ps1",".psm1",".go",".java",".kt",".kts",".cs",".c",".h",".cpp",".hpp",".cc",".cxx",".php",".swift",".dart",".rb",".pyi"]);test_runner=createSwarmTool({description:'Run project tests with framework detection. Supports bun, vitest, jest, mocha, pytest, cargo, pester, go-test, maven, gradle, dotnet-test, ctest, swift-test, dart-test, rspec, and minitest. Returns deterministic normalized JSON with framework, scope, command, totals, coverage, duration, success status, and failures. Use scope "all" for full suite, "convention" to accept direct test files or map source files to test files, "graph" to find related tests via imports from source files, or "impact" to find tests covering changed source files using test-impact analysis.',args:{scope:exports_external.enum(["all","convention","graph","impact"]).optional().describe('Test scope: "all" runs full suite, "convention" accepts direct test files or maps source files to tests by naming, "graph" finds related tests via imports from source files, "impact" finds tests covering changed source files via test-impact analysis'),files:exports_external.array(exports_external.string()).optional().describe('Specific files to test. For "convention", pass source files or direct test files. For "graph" and "impact", pass source files only.'),coverage:exports_external.boolean().optional().describe("Enable coverage reporting if supported"),bail:exports_external.boolean().optional().describe("Stop running tests after the first failure. Default false. Note: coverage may be incomplete when bail=true with coverage=true."),timeout_ms:exports_external.number().optional().describe("Timeout in milliseconds (default 60000, max 300000)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, tests run relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let workingDirInput;if(args2&&typeof args2==="object"){let obj=args2;workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={success:!1,framework:"none",scope:"all",error:dirResult.message,outcome:"error"};return JSON.stringify(errorResult,null,2)}let workingDir=dirResult.directory;if(workingDir.length>4096)return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(/^[/\\]{2}/.test(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsControlChars(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsPathTraversal(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(!validateArgs2(args2))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid arguments",message:'scope must be "all", "convention", "graph", or "impact"; files must be array of strings; coverage must be boolean; timeout_ms must be a positive number',outcome:"error"},null,2);let scope=args2.scope||"all";if(scope==="all"){if(!process.env.SWARM_ALLOW_FULL_SUITE)return JSON.stringify({success:!1,framework:"none",scope:"all",error:'scope "all" is blocked for agent use. Use scope "convention" with specific test files, or scope "graph" with exactly one source file.',message:'The full test suite is blocked in agent context. Use scope "convention" with specific test files, or scope "graph" with exactly one source file. Example: { scope: "convention", files: ["src/tools/test-runner.ts"] }',outcome:"error"},null,2)}if((scope==="convention"||scope==="graph"||scope==="impact")&&(!args2.files||args2.files.length===0))return JSON.stringify({success:!1,framework:"none",scope,error:'scope "convention" and "graph" require explicit files array - omitting files causes unsafe full-project discovery',message:'When using scope "convention" or "graph", you must provide a non-empty "files" array. Use scope "all" for full project test suite without specifying files.',outcome:"error"},null,2);let _files=args2.files||[],coverage=args2.coverage||!1,bail=args2.bail||!1,timeout_ms=Math.min(args2.timeout_ms||DEFAULT_TIMEOUT_MS3,MAX_TIMEOUT_MS2),useDispatch=process.env.SWARM_LANG_BACKEND!=="legacy",framework;if(useDispatch){if(framework=await detectTestFrameworkViaDispatch(workingDir),framework==="none")framework=await detectTestFramework(workingDir)}else framework=await detectTestFramework(workingDir);if(framework==="none")return JSON.stringify({success:!1,framework:"none",scope,error:"No test framework detected",message:"No supported test framework found. Install bun, vitest, jest, mocha, pytest, cargo, pester, or a supported language test runner (go test, maven, gradle, dotnet test, ctest, swift test, dart test, rspec, minitest).",totals:{passed:0,failed:0,skipped:0,total:0},outcome:"error"},null,2);let testFiles=[],graphFallbackReason,effectiveScope=scope;if(scope==="all");else if(scope==="convention"){let directTestFiles=args2.files.filter((file3)=>isConventionTestFilePath(file3)),sourceFiles=args2.files.filter((file3)=>{if(directTestFiles.includes(file3))return!1;let ext=path158.extname(file3).toLowerCase();return SOURCE_EXTENSIONS.has(ext)}),invalidFiles=args2.files.filter((file3)=>!directTestFiles.includes(file3)&&!sourceFiles.includes(file3));if(directTestFiles.length===0&&sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no recognized source files or direct test files",message:"The files array must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.) or a direct test file in a supported test location/naming convention.",outcome:"error"},null,2);if(invalidFiles.length>0){let errorResult={success:!1,framework,scope,error:"Provided files include entries that are neither recognized source files nor direct test files",message:`These files are not valid for targeted test discovery: ${invalidFiles.join(", ")}`,outcome:"error"};return JSON.stringify(errorResult,null,2)}if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "convention" accepts at most ${MAX_SAFE_SOURCE_FILES} source file for discovery (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "convention" discovery (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or pass direct test file paths instead of source files.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}testFiles=[...directTestFiles,...getTestFilesFromConvention(sourceFiles,workingDir)].filter((file3,index,items)=>items.indexOf(file3)===index)}else if(scope==="graph"){let sourceFiles=args2.files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path158.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)});if(sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "graph" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error"},null,2);if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "graph" accepts at most ${MAX_SAFE_SOURCE_FILES} source file (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "graph" (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or use scope "convention" with direct test file paths.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let estimate=await estimateFanOut(sourceFiles,workingDir);if(estimate.estimatedCount>MAX_SAFE_TEST_FILES){let errorResult={success:!1,framework,scope,error:"Estimated test file count exceeds safe maximum",message:`Scope "graph" resolution would produce approximately ${estimate.estimatedCount} test files, which exceeds the safe limit of ${MAX_SAFE_TEST_FILES}. Break the source files into smaller batches and retry.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}else if(scope==="impact"){let sourceFiles=args2.files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path158.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)});if(sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "impact" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error"},null,2);if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "impact" accepts at most ${MAX_SAFE_SOURCE_FILES} source file (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "impact" (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or use scope "convention" with direct test file paths.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let estimate=await estimateFanOut(sourceFiles,workingDir);if(estimate.estimatedCount>MAX_SAFE_TEST_FILES){let errorResult={success:!1,framework,scope,error:"Estimated test file count exceeds safe maximum",message:`Scope "impact" resolution would produce approximately ${estimate.estimatedCount} test files, which exceeds the safe limit of ${MAX_SAFE_TEST_FILES}. Break the source files into smaller batches and retry.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}try{let impactResult=await _internals111.analyzeImpact(sourceFiles,workingDir,MAX_SAFE_TEST_FILES);if(impactResult.budgetExceeded){let errorResult={success:!1,framework,scope,error:"Budget exceeded during impact analysis",message:`Impact analysis exceeded safe budget of ${MAX_SAFE_TEST_FILES} test files.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}if(impactResult.impactedTests.length>0)testFiles=impactResult.impactedTests.map((absPath)=>{let relativePath2=path158.relative(workingDir,absPath);return path158.isAbsolute(relativePath2)?absPath:relativePath2});else{graphFallbackReason="no impacted tests found via impact analysis, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}}catch{graphFallbackReason="impact analysis failed, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}}if(scope!=="all"&&testFiles.length===0){let errorResult={success:!1,framework,scope:effectiveScope,error:"Provided source files resolved to zero test files",message:graphFallbackReason?`No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/). (${graphFallbackReason})`:"No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/).",outcome:"skip",...scope==="graph"&&{attempted_scope:"graph"},...scope==="impact"&&{attempted_scope:"graph"}};return JSON.stringify(errorResult,null,2)}if(scope!=="all"&&testFiles.length>MAX_SAFE_TEST_FILES){let sampleFiles=testFiles.slice(0,5),errorResult={success:!1,framework,scope:effectiveScope,error:`Resolved test file count (${testFiles.length}) exceeds safe maximum (${MAX_SAFE_TEST_FILES})`,message:`Too many test files resolved (${testFiles.length}). Maximum allowed is ${MAX_SAFE_TEST_FILES}. Treat this as SKIP without retry. Provide more specific source files to narrow down test scope. First few resolved: ${sampleFiles.join(", ")}`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let result=await runTests(framework,effectiveScope,testFiles,coverage,timeout_ms,workingDir,bail);recordAndAnalyzeResults(result,testFiles,workingDir,_files.length>0?_files:void 0,result.testCases);let historyReport;if(!result.success&&result.totals&&result.totals.failed>0){if(historyReport=analyzeFailures(workingDir),historyReport.quarantinedFailures.length>0)result.message=(result.message||"")+` | QUARANTINED (flaky): ${historyReport.quarantinedFailures.join(", ")}`;if(historyReport.failureClusters.length>0){let clusterSummary=historyReport.failureClusters.slice(0,3).map((c)=>`${c.classification}: ${c.rootCause.substring(0,80)}`).join("; ");result.message=`${result.message||""} | FAILURE ANALYSIS: ${clusterSummary}`}}if(graphFallbackReason&&result.message)result.message=`${result.message} (${graphFallbackReason})`;if(bail&&coverage&&result.message)result.message=`${result.message} (coverage may be incomplete: bail=true stopped early)`;return JSON.stringify(result,null,2)}}),_internals111={analyzeImpact,loadImpactMap,isCommandAvailable,existsSync:fs77.existsSync,readdirSync:fs77.readdirSync,readFileSync:fs77.readFileSync,selectHistoryForAnalysis,AGGREGATE_TEST_NAME}});import*as fs78 from"node:fs";import*as path159 from"node:path";function validateDirectoryPath(dir){if(!dir||typeof dir!=="string")throw Error("Directory path is required");if(dir.includes(".."))throw Error("Directory path must not contain path traversal sequences");let normalized=path159.normalize(dir);return path159.isAbsolute(normalized)?normalized:path159.resolve(normalized)}function validateTimeout(timeoutMs,defaultValue){if(timeoutMs===void 0)return defaultValue;if(typeof timeoutMs!=="number"||!Number.isFinite(timeoutMs))throw Error("Timeout must be a finite number");if(timeoutMs<=0)throw Error("Timeout must be greater than 0");if(timeoutMs<MIN_CHECK_TIMEOUT_MS)throw Error(`Timeout must be at least ${MIN_CHECK_TIMEOUT_MS}ms (5 seconds)`);if(timeoutMs>MAX_CHECK_TIMEOUT_MS)throw Error(`Timeout must not exceed ${MAX_CHECK_TIMEOUT_MS}ms (5 minutes)`);return timeoutMs}function getPackageVersion(dir){try{let packagePath=path159.join(dir,"package.json");if(fs78.existsSync(packagePath)){let content=fs78.readFileSync(packagePath,"utf-8");return JSON.parse(content).version??null}}catch{}return null}function getChangelogVersion(dir){try{let changelogPath=path159.join(dir,"CHANGELOG.md");if(fs78.existsSync(changelogPath)){let match=fs78.readFileSync(changelogPath,"utf-8").match(/^##\s*\[?(\d+\.\d+\.\d+)\]?/m);if(match)return match[1]}}catch{}return null}function getVersionFileVersion(dir){let possibleFiles=["VERSION.txt","version.txt","VERSION","version"];for(let file3 of possibleFiles){let filePath=path159.join(dir,file3);if(fs78.existsSync(filePath))try{let match=fs78.readFileSync(filePath,"utf-8").trim().match(/(\d+\.\d+\.\d+)/);if(match)return match[1]}catch{}}return null}async function runVersionCheck2(dir,_timeoutMs){let startTime=Date.now();try{let packageVersion=_internals112.getPackageVersion(dir),changelogVersion=_internals112.getChangelogVersion(dir),versionFileVersion=_internals112.getVersionFileVersion(dir),versions3=[];if(packageVersion)versions3.push(`package.json: ${packageVersion}`);if(changelogVersion)versions3.push(`CHANGELOG.md: ${changelogVersion}`);if(versionFileVersion)versions3.push(`version file: ${versionFileVersion}`);if(new Set([packageVersion,changelogVersion,versionFileVersion].filter(Boolean)).size<=1){if(versions3.length===0)return{type:"version",status:"skip",message:"No version information found to check",details:{},durationMs:Date.now()-startTime};return{type:"version",status:"pass",message:`Version consistent: ${versions3.join(", ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}return{type:"version",status:"fail",message:`Version mismatch: ${versions3.join("; ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}catch(error93){return{type:"version",status:"error",message:`Version check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runLintCheck(dir,linter,timeoutMs){let startTime=Date.now();try{let lintPromise=runLint(linter,"check",dir),timeoutId,timeoutPromise=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(Error(`Lint check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([lintPromise,timeoutPromise]).finally(()=>clearTimeout(timeoutId));if(!result.success)return{type:"lint",status:"error",message:result.error??"Lint check failed",details:{linter,success:result.success},durationMs:Date.now()-startTime};if(result.exitCode!==0){let issueMatch=result.output.match(/(\d+)\s+(issues?|errors?)/i),issueCount=issueMatch?parseInt(issueMatch[1],10):void 0;return{type:"lint",status:"fail",message:issueCount?`Lint found ${issueCount} issue(s)`:"Lint found issues",details:{linter,exitCode:result.exitCode,issueCount,hasOutput:result.output.length>0},durationMs:Date.now()-startTime}}return{type:"lint",status:"pass",message:"Lint check passed",details:{linter,exitCode:result.exitCode},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))return{type:"lint",status:"error",message:error93.message,details:{linter},durationMs:Date.now()-startTime};return{type:"lint",status:"error",message:`Lint check failed: ${error93 instanceof Error?error93.message:String(error93)}`,details:{linter},durationMs:Date.now()-startTime}}}async function runTestsCheck(_dir,scope,timeoutMs){let startTime=Date.now();try{let result=await runTests("none",scope,[],!1,timeoutMs,_dir,!1);if(!result.success)return{type:"tests",status:"error",message:result.error??"Tests check failed",details:{framework:result.framework,scope,success:result.success},durationMs:Date.now()-startTime};if(result.totals.failed>0)return{type:"tests",status:"fail",message:`Tests failed: ${result.totals.failed}/${result.totals.total} failed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime};if(result.totals.total===0)return{type:"tests",status:"skip",message:"No tests found to run",details:{framework:result.framework,scope},durationMs:Date.now()-startTime};return{type:"tests",status:"pass",message:`Tests passed: ${result.totals.passed} passed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&(error93.message.includes("timeout")||error93.message.includes("ETIMEDOUT")))return{type:"tests",status:"error",message:`Tests check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"tests",status:"error",message:`Tests check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runSecretsCheck(dir,timeoutMs){let startTime=Date.now();try{let secretsPromise=runSecretscan(dir),timeoutPromise=new Promise((_,reject)=>{setTimeout(()=>{reject(Error(`Secrets check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([secretsPromise,timeoutPromise]);if(result.findings&&result.findings.length>0){let critical=result.findings.filter((f)=>f.severity==="critical").length,high=result.findings.filter((f)=>f.severity==="high").length;return{type:"secrets",status:"fail",message:`Found ${result.findings.length} secret(s): ${critical} critical, ${high} high`,details:{count:result.count,critical,high,filesScanned:result.files_scanned},durationMs:Date.now()-startTime}}return{type:"secrets",status:"pass",message:"No secrets detected",details:{filesScanned:result.files_scanned},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.name==="AbortError")return{type:"secrets",status:"error",message:`Secrets check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"secrets",status:"error",message:`Secrets check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runEvidenceCheck(dir){let startTime=Date.now();try{let plan=await loadPlan(dir);if(!plan)return{type:"evidence",status:"skip",message:"No plan found to check evidence against",details:{},durationMs:Date.now()-startTime};let completedTaskIds=[];for(let phase of plan.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.push(task.id);if(completedTaskIds.length===0)return{type:"evidence",status:"skip",message:"No completed tasks yet",details:{completedTasks:0},durationMs:Date.now()-startTime};let evidenceTaskIds=new Set(await listEvidenceTaskIds(dir)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(dir,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}let completedWithEvidence=completedTaskIds.length-missingEvidence.length;if(missingEvidence.length>0)return{type:"evidence",status:"fail",message:`${missingEvidence.length} completed task(s) missing evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence,missingTasks:missingEvidence.slice(0,10),missingCount:missingEvidence.length},durationMs:Date.now()-startTime};return{type:"evidence",status:"pass",message:`All ${completedTaskIds.length} completed tasks have evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence},durationMs:Date.now()-startTime}}catch(error93){return{type:"evidence",status:"error",message:`Evidence check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runRequirementCoverageCheck(dir,currentPhase){let startTime=Date.now();try{if(readEffectiveSpecSync(dir)===null)return{type:"req_coverage",status:"skip",message:"No effective spec found, requirement coverage not required",details:{},durationMs:Date.now()-startTime};let coverage=await checkRequirementCoverage(currentPhase,dir);if(coverage.exists)return{type:"req_coverage",status:"pass",message:"Requirement coverage report found",details:{path:coverage.path},durationMs:Date.now()-startTime};return{type:"req_coverage",status:"fail",message:"Requirement coverage report missing but effective spec exists",details:{expectedPath:coverage.path},durationMs:Date.now()-startTime}}catch(error93){return{type:"req_coverage",status:"error",message:`Requirement coverage check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runPreflight(dir,phase,config3){let startTime=Date.now(),reportId=`preflight-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,validatedDir;try{validatedDir=_internals112.validateDirectoryPath(dir)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid directory: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid directory"}}let validatedTimeout;try{validatedTimeout=_internals112.validateTimeout(config3?.checkTimeoutMs,DEFAULT_CONFIG.checkTimeoutMs)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid config: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid configuration"}}let cfg={checkTimeoutMs:validatedTimeout,skipTests:config3?.skipTests??DEFAULT_CONFIG.skipTests,skipSecrets:config3?.skipSecrets??DEFAULT_CONFIG.skipSecrets,skipEvidence:config3?.skipEvidence??DEFAULT_CONFIG.skipEvidence,skipVersion:config3?.skipVersion??DEFAULT_CONFIG.skipVersion,testScope:config3?.testScope??DEFAULT_CONFIG.testScope,linter:config3?.linter??DEFAULT_CONFIG.linter};log("[Preflight] Starting preflight checks",{reportId,phase,config:{skipTests:cfg.skipTests,skipSecrets:cfg.skipSecrets,skipEvidence:cfg.skipEvidence,skipVersion:cfg.skipVersion,testScope:cfg.testScope,linter:cfg.linter}});let checks5=[];log("[Preflight] Running lint check...");let lintResult=await _internals112.runLintCheck(validatedDir,cfg.linter,cfg.checkTimeoutMs);if(checks5.push(lintResult),log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`),!cfg.skipTests){log("[Preflight] Running tests check...");let testsResult=await _internals112.runTestsCheck(validatedDir,cfg.testScope,cfg.checkTimeoutMs);checks5.push(testsResult),log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`)}else checks5.push({type:"tests",status:"skip",message:"Tests check skipped by configuration"});if(!cfg.skipSecrets){log("[Preflight] Running secrets check...");let secretsResult=await _internals112.runSecretsCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(secretsResult),log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`)}else checks5.push({type:"secrets",status:"skip",message:"Secrets check skipped by configuration"});if(!cfg.skipEvidence){log("[Preflight] Running evidence check...");let evidenceResult=await _internals112.runEvidenceCheck(validatedDir);checks5.push(evidenceResult),log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`)}else checks5.push({type:"evidence",status:"skip",message:"Evidence check skipped by configuration"});log("[Preflight] Running requirement coverage check...");let reqCoverageResult=await _internals112.runRequirementCoverageCheck(validatedDir,phase);if(checks5.push(reqCoverageResult),log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`),!cfg.skipVersion){log("[Preflight] Running version check...");let versionResult=await _internals112.runVersionCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(versionResult),log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`)}else checks5.push({type:"version",status:"skip",message:"Version check skipped by configuration"});let totalDurationMs=Date.now()-startTime,failedChecks=checks5.filter((c)=>c.status==="fail").length,errorChecks=checks5.filter((c)=>c.status==="error").length,skippedChecks=checks5.filter((c)=>c.status==="skip").length,overall,message;if(errorChecks>0)overall="fail",message=`Preflight failed with ${errorChecks} error(s)`;else if(failedChecks>0)overall="fail",message=`Preflight failed: ${failedChecks} check(s) failed`;else if(skippedChecks===checks5.length)overall="skipped",message="All checks were skipped";else overall="pass",message="Preflight passed all checks";return log(`[Preflight] Complete: ${overall} ${message}`),{id:reportId,timestamp:startTime,phase,overall,checks:checks5,totalDurationMs,message}}function formatPreflightMarkdown(report){let lines=["## Preflight Report","",`**Phase**: ${report.phase}`,`**Overall**: ${report.overall==="pass"?"✅ PASS":report.overall==="fail"?"❌ FAIL":"⏭️ SKIPPED"}`,`**Duration**: ${(report.totalDurationMs/1000).toFixed(2)}s`,"","### Checks",""];for(let check3 of report.checks){let icon=check3.status==="pass"?"✅":check3.status==="fail"?"❌":check3.status==="error"?"⚠️":"⏭️";lines.push(`- ${icon} **${check3.type}**: ${check3.message}`)}return lines.push(""),lines.push(report.message),lines.join(`
|
|
1929
|
-
`)}async function handlePreflightCommand(directory,_args){let phase=(await loadPlan(directory))?.current_phase??1,report=await _internals112.runPreflight(directory,phase);return _internals112.formatPreflightMarkdown(report)}var MIN_CHECK_TIMEOUT_MS=5000,MAX_CHECK_TIMEOUT_MS=300000,DEFAULT_CONFIG,_internals112;var init_preflight_service=__esm(()=>{init_gate_bridge();init_manager2();init_manager();init_effective_spec();init_lint();init_secretscan();init_test_runner();init_utils();DEFAULT_CONFIG={checkTimeoutMs:60000,skipTests:!1,skipSecrets:!1,skipEvidence:!1,skipVersion:!1,testScope:"convention",linter:"biome"};_internals112={runPreflight,formatPreflightMarkdown,handlePreflightCommand,validateDirectoryPath,validateTimeout,getPackageVersion,getChangelogVersion,getVersionFileVersion,runVersionCheck:runVersionCheck2,runLintCheck,runTestsCheck,runSecretsCheck,runEvidenceCheck,runRequirementCoverageCheck}});var init_preflight=__esm(()=>{init_preflight_service()});function parsePromoteArgs(args2){let category,lessonId,lessonText,force=!1,reason,actionable={};for(let i=0;i<args2.length;i++){let arg=args2[i],actionabilityField=ACTIONABILITY_LIST_FLAGS.get(arg);if(arg==="--category"&&i+1<args2.length)category=args2[i+1],i++;else if(arg==="--from-swarm"&&i+1<args2.length)lessonId=args2[i+1],i++;else if(arg==="--force")force=!0;else if(arg==="--reason"&&i+1<args2.length)reason=args2[i+1],i++;else if(actionabilityField!==void 0&&i+1<args2.length){let supplied=args2[i+1].split(",").map((v)=>v.trim()).filter((v)=>v.length>0);actionable[actionabilityField]=dedupeCapped([...actionable[actionabilityField]??[],...supplied],{cap:ACTIONABILITY_FIELD_CAP}),i++}else if(!arg.startsWith("--")){lessonText=args2.slice(i).join(" ");break}}return{category,lessonId,lessonText,force,reason,actionable}}async function handlePromoteCommand(directory,args2){let{category,lessonId,lessonText,force,reason,actionable}=parsePromoteArgs(args2);if(!lessonText&&!lessonId)return`Usage: /swarm promote "<lesson text>" or /swarm promote --from-swarm <id>
|
|
1928
|
+
... (output truncated at stream read limit)`;let parsed=process.env.SWARM_LANG_BACKEND!=="legacy"?await parseTestOutputViaDispatch(framework,output,cwd)??parseTestOutput2(framework,output):parseTestOutput2(framework,output),parsedTestCases=parseFrameworkJsonTestResults(framework,output),totals={...parsed.totals},{coveragePercent}=parsed;if(totals.total===0&&parsedTestCases.length>0){for(let entry of parsedTestCases)if(entry.result==="pass")totals.passed++;else if(entry.result==="fail")totals.failed++;else totals.skipped++;totals.total=parsedTestCases.length}let isTimeout=exitCode===-1;if(exitCode===0&&totals.failed===0){let result={success:!0,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,outcome:"pass",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;if(result.message=`${framework} tests passed (${totals.passed}/${totals.total})`,coveragePercent!==void 0)result.message+=` with ${coveragePercent}% coverage`;return result}else{let result={success:!1,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,error:isTimeout?`Tests timed out after ${timeout_ms}ms`:`Tests failed with ${totals.failed} failures`,message:isTimeout?`${framework} tests timed out after ${timeout_ms}ms`:`${framework} tests failed (${totals.failed}/${totals.total} failed)`,outcome:isTimeout?"error":"regression",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;return result}}catch(error93){let duration_ms=Date.now()-startTime;return{success:!1,framework,scope,command,timeout_ms,duration_ms,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error",outcome:"error"}}}function normalizeHistoryTestFile(testFile,workingDir){let normalized=testFile.replace(/\\/g,"/");if(!path158.isAbsolute(testFile))return normalized;let relative33=path158.relative(workingDir,testFile);if(relative33.startsWith("..")||path158.isAbsolute(relative33))return normalized;return relative33.replace(/\\/g,"/")}function combineAggregateResult(current,next){if(current==="fail"||next==="fail")return"fail";if(current==="pass"||next==="pass")return"pass";return"skip"}function recordAndAnalyzeResults(result,testFiles,workingDir,sourceFiles,parsedTestCases){if(!result.totals||result.totals.total===0)return;let now=new Date().toISOString(),changedFiles=(sourceFiles&&sourceFiles.length>0?sourceFiles:testFiles).map((f)=>f.replace(/\\/g,"/")),aggregateResultsByFile=new Map,validParsedCases=parsedTestCases?.filter((parsedCase)=>parsedCase.testFile.length>0&&parsedCase.testName.length>0)??[],allRecords=[];for(let parsedCase of validParsedCases){let normalizedTestFile=normalizeHistoryTestFile(parsedCase.testFile,workingDir);allRecords.push({timestamp:now,taskId:"auto",testFile:normalizedTestFile,testName:parsedCase.testName,result:parsedCase.result,durationMs:parsedCase.durationMs,errorMessage:parsedCase.errorMessage,stackPrefix:parsedCase.stackPrefix,changedFiles}),aggregateResultsByFile.set(normalizedTestFile,combineAggregateResult(aggregateResultsByFile.get(normalizedTestFile),parsedCase.result))}if(aggregateResultsByFile.size===0){let aggregateResult=result.success?"pass":"fail";for(let testFile of testFiles)aggregateResultsByFile.set(testFile.replace(/\\/g,"/"),aggregateResult)}for(let[testFile,aggregateResult]of aggregateResultsByFile)allRecords.push({timestamp:now,taskId:"auto",testFile,testName:AGGREGATE_TEST_NAME,result:aggregateResult,durationMs:result.duration_ms||0,changedFiles});try{batchAppendTestRuns(allRecords,workingDir)}catch{}}function selectHistoryForAnalysis(history){let filesWithIndividualRecords=new Set;for(let record3 of history)if(record3.testName!==AGGREGATE_TEST_NAME)filesWithIndividualRecords.add(record3.testFile.toLowerCase());if(filesWithIndividualRecords.size===0)return history;return history.filter((record3)=>record3.testName!==AGGREGATE_TEST_NAME||!filesWithIndividualRecords.has(record3.testFile.toLowerCase()))}function analyzeFailures(workingDir){let report={flakyTests:[],failureClusters:[],quarantinedFailures:[]};try{let history=selectHistoryForAnalysis(getAllHistory(workingDir));if(history.length===0)return report;report.flakyTests=detectFlakyTests(history);let failingResults=history.filter((r)=>r.result==="fail");if(failingResults.length>0){let{clusters}=classifyAndCluster(failingResults,history);report.failureClusters=clusters.map((c)=>({rootCause:c.rootCause,affectedFiles:c.affectedTestFiles,classification:c.classification}))}for(let entry of report.flakyTests)if(entry.isQuarantined)report.quarantinedFailures.push(`${entry.testFile}: ${entry.testName}`)}catch{}return report}var MAX_OUTPUT_BYTES4=512000,MAX_COMMAND_LENGTH2=500,DEFAULT_TIMEOUT_MS3=60000,MAX_TIMEOUT_MS2=300000,MAX_SAFE_TEST_FILES=50,MAX_SAFE_SOURCE_FILES=1,AGGREGATE_TEST_NAME="(aggregate)",VITEST_JSON_OUTPUT_RELATIVE_PATH=".swarm/cache/test-runner-vitest.json",POWERSHELL_METACHARACTERS,DISPATCH_FRAMEWORK_MAP,COMPOUND_TEST_EXTENSIONS,TEST_DIRECTORY_NAMES,SOURCE_EXTENSIONS,test_runner,_internals111;var init_test_runner=__esm(()=>{init_zod();init_discovery();init_analyzer();init_failure_classifier();init_history_store();init_bun_compat();init_path_security();init_create_tool();init_resolve_working_directory();POWERSHELL_METACHARACTERS=/[|;&`$(){}[\]<>"'#*?\x00-\x1f]/;DISPATCH_FRAMEWORK_MAP={bun:"bun",vitest:"vitest",jest:"jest",mocha:"mocha",pytest:"pytest",cargo:"cargo",pester:"pester","go-test":"go-test",maven:"maven",gradle:"gradle","dotnet-test":"dotnet-test",ctest:"ctest","swift-test":"swift-test","dart-test":"dart-test",rspec:"rspec",minitest:"minitest",pest:"pest",phpunit:"phpunit","php-artisan":"php-artisan","bun:test":"bun","xcodebuild-test":"swift-test","flutter test":"dart-test","dart test":"dart-test",Pest:"pest",PHPUnit:"phpunit"};COMPOUND_TEST_EXTENSIONS=[".test.ts",".test.tsx",".test.js",".test.jsx",".tests.ps1",".spec.ts",".spec.tsx",".spec.js",".spec.jsx",".test.ps1",".spec.ps1"],TEST_DIRECTORY_NAMES=["__tests__","tests","test","spec"];SOURCE_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".ps1",".psm1",".go",".java",".kt",".kts",".cs",".c",".h",".cpp",".hpp",".cc",".cxx",".php",".swift",".dart",".rb",".pyi"]);test_runner=createSwarmTool({description:'Run project tests with framework detection. Supports bun, vitest, jest, mocha, pytest, cargo, pester, go-test, maven, gradle, dotnet-test, ctest, swift-test, dart-test, rspec, and minitest. Returns deterministic normalized JSON with framework, scope, command, totals, coverage, duration, success status, and failures. Use scope "all" for full suite, "convention" to accept direct test files or map source files to test files, "graph" to find related tests via imports from source files, or "impact" to find tests covering changed source files using test-impact analysis.',args:{scope:exports_external.enum(["all","convention","graph","impact"]).optional().describe('Test scope: "all" runs full suite, "convention" accepts direct test files or maps source files to tests by naming, "graph" finds related tests via imports from source files, "impact" finds tests covering changed source files via test-impact analysis'),files:exports_external.array(exports_external.string()).optional().describe('Specific files to test. For "convention", pass source files or direct test files. For "graph" and "impact", pass source files only.'),coverage:exports_external.boolean().optional().describe("Enable coverage reporting if supported"),bail:exports_external.boolean().optional().describe("Stop running tests after the first failure. Default false. Note: coverage may be incomplete when bail=true with coverage=true."),timeout_ms:exports_external.number().optional().describe("Timeout in milliseconds (default 60000, max 300000)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, tests run relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let workingDirInput;if(args2&&typeof args2==="object"){let obj=args2;workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={success:!1,framework:"none",scope:"all",error:dirResult.message,outcome:"error"};return JSON.stringify(errorResult,null,2)}let workingDir=dirResult.directory;if(workingDir.length>4096)return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(/^[/\\]{2}/.test(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsControlChars(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsPathTraversal(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(!validateArgs2(args2))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid arguments",message:'scope must be "all", "convention", "graph", or "impact"; files must be array of strings; coverage must be boolean; timeout_ms must be a positive number',outcome:"error"},null,2);let scope=args2.scope||"all";if(scope==="all"){if(!process.env.SWARM_ALLOW_FULL_SUITE)return JSON.stringify({success:!1,framework:"none",scope:"all",error:'scope "all" is blocked for agent use. Use scope "convention" with specific test files, or scope "graph" with exactly one source file.',message:'The full test suite is blocked in agent context. Use scope "convention" with specific test files, or scope "graph" with exactly one source file. Example: { scope: "convention", files: ["src/tools/test-runner.ts"] }',outcome:"error"},null,2)}if((scope==="convention"||scope==="graph"||scope==="impact")&&(!args2.files||args2.files.length===0))return JSON.stringify({success:!1,framework:"none",scope,error:'scope "convention" and "graph" require explicit files array - omitting files causes unsafe full-project discovery',message:'When using scope "convention" or "graph", you must provide a non-empty "files" array. Use scope "all" for full project test suite without specifying files.',outcome:"error"},null,2);let _files=args2.files||[],coverage=args2.coverage||!1,bail=args2.bail||!1,timeout_ms=Math.min(args2.timeout_ms||DEFAULT_TIMEOUT_MS3,MAX_TIMEOUT_MS2),useDispatch=process.env.SWARM_LANG_BACKEND!=="legacy",framework;if(useDispatch){if(framework=await detectTestFrameworkViaDispatch(workingDir),framework==="none")framework=await detectTestFramework(workingDir)}else framework=await detectTestFramework(workingDir);if(framework==="none")return JSON.stringify({success:!1,framework:"none",scope,error:"No test framework detected",message:"No supported test framework found. Install bun, vitest, jest, mocha, pytest, cargo, pester, or a supported language test runner (go test, maven, gradle, dotnet test, ctest, swift test, dart test, rspec, minitest).",totals:{passed:0,failed:0,skipped:0,total:0},outcome:"error"},null,2);let testFiles=[],graphFallbackReason,effectiveScope=scope;if(scope==="all");else if(scope==="convention"){let directTestFiles=args2.files.filter((file3)=>isConventionTestFilePath(file3)),sourceFiles=args2.files.filter((file3)=>{if(directTestFiles.includes(file3))return!1;let ext=path158.extname(file3).toLowerCase();return SOURCE_EXTENSIONS.has(ext)}),invalidFiles=args2.files.filter((file3)=>!directTestFiles.includes(file3)&&!sourceFiles.includes(file3));if(directTestFiles.length===0&&sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no recognized source files or direct test files",message:"The files array must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.) or a direct test file in a supported test location/naming convention.",outcome:"error"},null,2);if(invalidFiles.length>0){let errorResult={success:!1,framework,scope,error:"Provided files include entries that are neither recognized source files nor direct test files",message:`These files are not valid for targeted test discovery: ${invalidFiles.join(", ")}`,outcome:"error"};return JSON.stringify(errorResult,null,2)}if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "convention" accepts at most ${MAX_SAFE_SOURCE_FILES} source file for discovery (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "convention" discovery (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or pass direct test file paths instead of source files.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}testFiles=[...directTestFiles,...getTestFilesFromConvention(sourceFiles,workingDir)].filter((file3,index,items)=>items.indexOf(file3)===index)}else if(scope==="graph"){let sourceFiles=args2.files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path158.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)});if(sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "graph" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error"},null,2);if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "graph" accepts at most ${MAX_SAFE_SOURCE_FILES} source file (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "graph" (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or use scope "convention" with direct test file paths.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let estimate=await estimateFanOut(sourceFiles,workingDir);if(estimate.estimatedCount>MAX_SAFE_TEST_FILES){let errorResult={success:!1,framework,scope,error:"Estimated test file count exceeds safe maximum",message:`Scope "graph" resolution would produce approximately ${estimate.estimatedCount} test files, which exceeds the safe limit of ${MAX_SAFE_TEST_FILES}. Break the source files into smaller batches and retry.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}else if(scope==="impact"){let sourceFiles=args2.files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path158.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)});if(sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "impact" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error"},null,2);if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "impact" accepts at most ${MAX_SAFE_SOURCE_FILES} source file (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "impact" (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or use scope "convention" with direct test file paths.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let estimate=await estimateFanOut(sourceFiles,workingDir);if(estimate.estimatedCount>MAX_SAFE_TEST_FILES){let errorResult={success:!1,framework,scope,error:"Estimated test file count exceeds safe maximum",message:`Scope "impact" resolution would produce approximately ${estimate.estimatedCount} test files, which exceeds the safe limit of ${MAX_SAFE_TEST_FILES}. Break the source files into smaller batches and retry.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}try{let impactResult=await _internals111.analyzeImpact(sourceFiles,workingDir,MAX_SAFE_TEST_FILES);if(impactResult.budgetExceeded){let errorResult={success:!1,framework,scope,error:"Budget exceeded during impact analysis",message:`Impact analysis exceeded safe budget of ${MAX_SAFE_TEST_FILES} test files.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}if(impactResult.impactedTests.length>0)testFiles=impactResult.impactedTests.map((absPath)=>{let relativePath2=path158.relative(workingDir,absPath);return path158.isAbsolute(relativePath2)?absPath:relativePath2});else{graphFallbackReason="no impacted tests found via impact analysis, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}}catch{graphFallbackReason="impact analysis failed, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}}if(scope!=="all"&&testFiles.length===0){let errorResult={success:!1,framework,scope:effectiveScope,error:"Provided source files resolved to zero test files",message:graphFallbackReason?`No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/). (${graphFallbackReason})`:"No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/).",outcome:"skip",...scope==="graph"&&{attempted_scope:"graph"},...scope==="impact"&&{attempted_scope:"graph"}};return JSON.stringify(errorResult,null,2)}if(scope!=="all"&&testFiles.length>MAX_SAFE_TEST_FILES){let sampleFiles=testFiles.slice(0,5),errorResult={success:!1,framework,scope:effectiveScope,error:`Resolved test file count (${testFiles.length}) exceeds safe maximum (${MAX_SAFE_TEST_FILES})`,message:`Too many test files resolved (${testFiles.length}). Maximum allowed is ${MAX_SAFE_TEST_FILES}. Treat this as SKIP without retry. Provide more specific source files to narrow down test scope. First few resolved: ${sampleFiles.join(", ")}`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let result=await runTests(framework,effectiveScope,testFiles,coverage,timeout_ms,workingDir,bail);recordAndAnalyzeResults(result,testFiles,workingDir,_files.length>0?_files:void 0,result.testCases);let historyReport;if(!result.success&&result.totals&&result.totals.failed>0){if(historyReport=analyzeFailures(workingDir),historyReport.quarantinedFailures.length>0)result.message=(result.message||"")+` | QUARANTINED (flaky): ${historyReport.quarantinedFailures.join(", ")}`;if(historyReport.failureClusters.length>0){let clusterSummary=historyReport.failureClusters.slice(0,3).map((c)=>`${c.classification}: ${c.rootCause.substring(0,80)}`).join("; ");result.message=`${result.message||""} | FAILURE ANALYSIS: ${clusterSummary}`}}if(graphFallbackReason&&result.message)result.message=`${result.message} (${graphFallbackReason})`;if(bail&&coverage&&result.message)result.message=`${result.message} (coverage may be incomplete: bail=true stopped early)`;return JSON.stringify(result,null,2)}}),_internals111={analyzeImpact,loadImpactMap,isCommandAvailable,existsSync:fs77.existsSync,readdirSync:fs77.readdirSync,readFileSync:fs77.readFileSync,selectHistoryForAnalysis,AGGREGATE_TEST_NAME}});import*as fs78 from"node:fs";import*as path159 from"node:path";function formatSecretscanIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function validateDirectoryPath(dir){if(!dir||typeof dir!=="string")throw Error("Directory path is required");if(dir.includes(".."))throw Error("Directory path must not contain path traversal sequences");let normalized=path159.normalize(dir);return path159.isAbsolute(normalized)?normalized:path159.resolve(normalized)}function validateTimeout(timeoutMs,defaultValue){if(timeoutMs===void 0)return defaultValue;if(typeof timeoutMs!=="number"||!Number.isFinite(timeoutMs))throw Error("Timeout must be a finite number");if(timeoutMs<=0)throw Error("Timeout must be greater than 0");if(timeoutMs<MIN_CHECK_TIMEOUT_MS)throw Error(`Timeout must be at least ${MIN_CHECK_TIMEOUT_MS}ms (5 seconds)`);if(timeoutMs>MAX_CHECK_TIMEOUT_MS)throw Error(`Timeout must not exceed ${MAX_CHECK_TIMEOUT_MS}ms (5 minutes)`);return timeoutMs}function getPackageVersion(dir){try{let packagePath=path159.join(dir,"package.json");if(fs78.existsSync(packagePath)){let content=fs78.readFileSync(packagePath,"utf-8");return JSON.parse(content).version??null}}catch{}return null}function getChangelogVersion(dir){try{let changelogPath=path159.join(dir,"CHANGELOG.md");if(fs78.existsSync(changelogPath)){let match=fs78.readFileSync(changelogPath,"utf-8").match(/^##\s*\[?(\d+\.\d+\.\d+)\]?/m);if(match)return match[1]}}catch{}return null}function getVersionFileVersion(dir){let possibleFiles=["VERSION.txt","version.txt","VERSION","version"];for(let file3 of possibleFiles){let filePath=path159.join(dir,file3);if(fs78.existsSync(filePath))try{let match=fs78.readFileSync(filePath,"utf-8").trim().match(/(\d+\.\d+\.\d+)/);if(match)return match[1]}catch{}}return null}async function runVersionCheck2(dir,_timeoutMs){let startTime=Date.now();try{let packageVersion=_internals112.getPackageVersion(dir),changelogVersion=_internals112.getChangelogVersion(dir),versionFileVersion=_internals112.getVersionFileVersion(dir),versions3=[];if(packageVersion)versions3.push(`package.json: ${packageVersion}`);if(changelogVersion)versions3.push(`CHANGELOG.md: ${changelogVersion}`);if(versionFileVersion)versions3.push(`version file: ${versionFileVersion}`);if(new Set([packageVersion,changelogVersion,versionFileVersion].filter(Boolean)).size<=1){if(versions3.length===0)return{type:"version",status:"skip",message:"No version information found to check",details:{},durationMs:Date.now()-startTime};return{type:"version",status:"pass",message:`Version consistent: ${versions3.join(", ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}return{type:"version",status:"fail",message:`Version mismatch: ${versions3.join("; ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}catch(error93){return{type:"version",status:"error",message:`Version check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runLintCheck(dir,linter,timeoutMs){let startTime=Date.now();try{let lintPromise=runLint(linter,"check",dir),timeoutId,timeoutPromise=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(Error(`Lint check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([lintPromise,timeoutPromise]).finally(()=>clearTimeout(timeoutId));if(!result.success)return{type:"lint",status:"error",message:result.error??"Lint check failed",details:{linter,success:result.success},durationMs:Date.now()-startTime};if(result.exitCode!==0){let issueMatch=result.output.match(/(\d+)\s+(issues?|errors?)/i),issueCount=issueMatch?parseInt(issueMatch[1],10):void 0;return{type:"lint",status:"fail",message:issueCount?`Lint found ${issueCount} issue(s)`:"Lint found issues",details:{linter,exitCode:result.exitCode,issueCount,hasOutput:result.output.length>0},durationMs:Date.now()-startTime}}return{type:"lint",status:"pass",message:"Lint check passed",details:{linter,exitCode:result.exitCode},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))return{type:"lint",status:"error",message:error93.message,details:{linter},durationMs:Date.now()-startTime};return{type:"lint",status:"error",message:`Lint check failed: ${error93 instanceof Error?error93.message:String(error93)}`,details:{linter},durationMs:Date.now()-startTime}}}async function runTestsCheck(_dir,scope,timeoutMs){let startTime=Date.now();try{let result=await runTests("none",scope,[],!1,timeoutMs,_dir,!1);if(!result.success)return{type:"tests",status:"error",message:result.error??"Tests check failed",details:{framework:result.framework,scope,success:result.success},durationMs:Date.now()-startTime};if(result.totals.failed>0)return{type:"tests",status:"fail",message:`Tests failed: ${result.totals.failed}/${result.totals.total} failed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime};if(result.totals.total===0)return{type:"tests",status:"skip",message:"No tests found to run",details:{framework:result.framework,scope},durationMs:Date.now()-startTime};return{type:"tests",status:"pass",message:`Tests passed: ${result.totals.passed} passed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&(error93.message.includes("timeout")||error93.message.includes("ETIMEDOUT")))return{type:"tests",status:"error",message:`Tests check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"tests",status:"error",message:`Tests check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runSecretsCheck(dir,timeoutMs){let startTime=Date.now();try{let secretsPromise=_internals112.runSecretscan(dir),timeoutPromise=new Promise((_,reject)=>{setTimeout(()=>{reject(Error(`Secrets check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([secretsPromise,timeoutPromise]);if("error"in result)return{type:"secrets",status:"fail",message:`Secrets check failed: ${result.error}`,details:{error:result.error,filesScanned:result.files_scanned,incompleteFiles:0,incompletePaths:[]},durationMs:Date.now()-startTime};let findingsCount=Math.max(result.count,result.findings.length);if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{type:"secrets",status:"fail",message:"Secrets check failed: scanner returned incomplete coverage metadata",details:{filesScanned:result.files_scanned},durationMs:Date.now()-startTime};let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=result,hasCountMismatch=result.count!==result.findings.length,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasZeroCoverage=result.files_scanned===0,failures=[];if(findingsCount>0){let critical=result.findings.filter((f)=>f.severity==="critical").length,high=result.findings.filter((f)=>f.severity==="high").length;failures.push(`Found ${findingsCount} secret(s): ${critical} critical, ${high} high`)}if(hasIncompleteCoverage){let incompleteSummary=incompletePaths.length>0?`; incomplete paths: ${formatSecretscanIncompletePaths(incompletePaths)}`:"";failures.push(`${incompleteFiles} incomplete file(s)${incompleteSummary}`)}if(hasCountMismatch)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(hasZeroCoverage)failures.push("zero requested files scanned");if(failures.length>0)return{type:"secrets",status:"fail",message:`Secrets check failed: ${failures.join("; ")}`,details:{count:findingsCount,reportedCount:result.count,critical:result.findings.filter((f)=>f.severity==="critical").length,high:result.findings.filter((f)=>f.severity==="high").length,filesScanned:result.files_scanned,skippedFiles:result.skipped_files,incompleteFiles,incompletePaths},durationMs:Date.now()-startTime};return{type:"secrets",status:"pass",message:"No secrets detected",details:{filesScanned:result.files_scanned,skippedFiles:result.skipped_files,incompleteFiles,incompletePaths},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.name==="AbortError")return{type:"secrets",status:"error",message:`Secrets check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"secrets",status:"error",message:`Secrets check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runEvidenceCheck(dir){let startTime=Date.now();try{let plan=await loadPlan(dir);if(!plan)return{type:"evidence",status:"skip",message:"No plan found to check evidence against",details:{},durationMs:Date.now()-startTime};let completedTaskIds=[];for(let phase of plan.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.push(task.id);if(completedTaskIds.length===0)return{type:"evidence",status:"skip",message:"No completed tasks yet",details:{completedTasks:0},durationMs:Date.now()-startTime};let evidenceTaskIds=new Set(await listEvidenceTaskIds(dir)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(dir,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}let completedWithEvidence=completedTaskIds.length-missingEvidence.length;if(missingEvidence.length>0)return{type:"evidence",status:"fail",message:`${missingEvidence.length} completed task(s) missing evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence,missingTasks:missingEvidence.slice(0,10),missingCount:missingEvidence.length},durationMs:Date.now()-startTime};return{type:"evidence",status:"pass",message:`All ${completedTaskIds.length} completed tasks have evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence},durationMs:Date.now()-startTime}}catch(error93){return{type:"evidence",status:"error",message:`Evidence check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runRequirementCoverageCheck(dir,currentPhase){let startTime=Date.now();try{if(readEffectiveSpecSync(dir)===null)return{type:"req_coverage",status:"skip",message:"No effective spec found, requirement coverage not required",details:{},durationMs:Date.now()-startTime};let coverage=await checkRequirementCoverage(currentPhase,dir);if(coverage.exists)return{type:"req_coverage",status:"pass",message:"Requirement coverage report found",details:{path:coverage.path},durationMs:Date.now()-startTime};return{type:"req_coverage",status:"fail",message:"Requirement coverage report missing but effective spec exists",details:{expectedPath:coverage.path},durationMs:Date.now()-startTime}}catch(error93){return{type:"req_coverage",status:"error",message:`Requirement coverage check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runPreflight(dir,phase,config3){let startTime=Date.now(),reportId=`preflight-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,validatedDir;try{validatedDir=_internals112.validateDirectoryPath(dir)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid directory: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid directory"}}let validatedTimeout;try{validatedTimeout=_internals112.validateTimeout(config3?.checkTimeoutMs,DEFAULT_CONFIG.checkTimeoutMs)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid config: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid configuration"}}let cfg={checkTimeoutMs:validatedTimeout,skipTests:config3?.skipTests??DEFAULT_CONFIG.skipTests,skipSecrets:config3?.skipSecrets??DEFAULT_CONFIG.skipSecrets,skipEvidence:config3?.skipEvidence??DEFAULT_CONFIG.skipEvidence,skipVersion:config3?.skipVersion??DEFAULT_CONFIG.skipVersion,testScope:config3?.testScope??DEFAULT_CONFIG.testScope,linter:config3?.linter??DEFAULT_CONFIG.linter};log("[Preflight] Starting preflight checks",{reportId,phase,config:{skipTests:cfg.skipTests,skipSecrets:cfg.skipSecrets,skipEvidence:cfg.skipEvidence,skipVersion:cfg.skipVersion,testScope:cfg.testScope,linter:cfg.linter}});let checks5=[];log("[Preflight] Running lint check...");let lintResult=await _internals112.runLintCheck(validatedDir,cfg.linter,cfg.checkTimeoutMs);if(checks5.push(lintResult),log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`),!cfg.skipTests){log("[Preflight] Running tests check...");let testsResult=await _internals112.runTestsCheck(validatedDir,cfg.testScope,cfg.checkTimeoutMs);checks5.push(testsResult),log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`)}else checks5.push({type:"tests",status:"skip",message:"Tests check skipped by configuration"});if(!cfg.skipSecrets){log("[Preflight] Running secrets check...");let secretsResult=await _internals112.runSecretsCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(secretsResult),log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`)}else checks5.push({type:"secrets",status:"skip",message:"Secrets check skipped by configuration"});if(!cfg.skipEvidence){log("[Preflight] Running evidence check...");let evidenceResult=await _internals112.runEvidenceCheck(validatedDir);checks5.push(evidenceResult),log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`)}else checks5.push({type:"evidence",status:"skip",message:"Evidence check skipped by configuration"});log("[Preflight] Running requirement coverage check...");let reqCoverageResult=await _internals112.runRequirementCoverageCheck(validatedDir,phase);if(checks5.push(reqCoverageResult),log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`),!cfg.skipVersion){log("[Preflight] Running version check...");let versionResult=await _internals112.runVersionCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(versionResult),log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`)}else checks5.push({type:"version",status:"skip",message:"Version check skipped by configuration"});let totalDurationMs=Date.now()-startTime,failedChecks=checks5.filter((c)=>c.status==="fail").length,errorChecks=checks5.filter((c)=>c.status==="error").length,skippedChecks=checks5.filter((c)=>c.status==="skip").length,overall,message;if(errorChecks>0)overall="fail",message=`Preflight failed with ${errorChecks} error(s)`;else if(failedChecks>0)overall="fail",message=`Preflight failed: ${failedChecks} check(s) failed`;else if(skippedChecks===checks5.length)overall="skipped",message="All checks were skipped";else overall="pass",message="Preflight passed all checks";return log(`[Preflight] Complete: ${overall} ${message}`),{id:reportId,timestamp:startTime,phase,overall,checks:checks5,totalDurationMs,message}}function formatPreflightMarkdown(report){let lines=["## Preflight Report","",`**Phase**: ${report.phase}`,`**Overall**: ${report.overall==="pass"?"✅ PASS":report.overall==="fail"?"❌ FAIL":"⏭️ SKIPPED"}`,`**Duration**: ${(report.totalDurationMs/1000).toFixed(2)}s`,"","### Checks",""];for(let check3 of report.checks){let icon=check3.status==="pass"?"✅":check3.status==="fail"?"❌":check3.status==="error"?"⚠️":"⏭️";lines.push(`- ${icon} **${check3.type}**: ${check3.message}`)}return lines.push(""),lines.push(report.message),lines.join(`
|
|
1929
|
+
`)}async function handlePreflightCommand(directory,_args){let phase=(await loadPlan(directory))?.current_phase??1,report=await _internals112.runPreflight(directory,phase);return _internals112.formatPreflightMarkdown(report)}var MIN_CHECK_TIMEOUT_MS=5000,MAX_CHECK_TIMEOUT_MS=300000,DEFAULT_CONFIG,_internals112;var init_preflight_service=__esm(()=>{init_gate_bridge();init_manager2();init_manager();init_effective_spec();init_lint();init_secretscan();init_test_runner();init_utils();DEFAULT_CONFIG={checkTimeoutMs:60000,skipTests:!1,skipSecrets:!1,skipEvidence:!1,skipVersion:!1,testScope:"convention",linter:"biome"};_internals112={runPreflight,formatPreflightMarkdown,handlePreflightCommand,validateDirectoryPath,validateTimeout,getPackageVersion,getChangelogVersion,getVersionFileVersion,runVersionCheck:runVersionCheck2,runLintCheck,runTestsCheck,runSecretscan,runSecretsCheck,runEvidenceCheck,runRequirementCoverageCheck}});var init_preflight=__esm(()=>{init_preflight_service()});function parsePromoteArgs(args2){let category,lessonId,lessonText,force=!1,reason,actionable={};for(let i=0;i<args2.length;i++){let arg=args2[i],actionabilityField=ACTIONABILITY_LIST_FLAGS.get(arg);if(arg==="--category"&&i+1<args2.length)category=args2[i+1],i++;else if(arg==="--from-swarm"&&i+1<args2.length)lessonId=args2[i+1],i++;else if(arg==="--force")force=!0;else if(arg==="--reason"&&i+1<args2.length)reason=args2[i+1],i++;else if(actionabilityField!==void 0&&i+1<args2.length){let supplied=args2[i+1].split(",").map((v)=>v.trim()).filter((v)=>v.length>0);actionable[actionabilityField]=dedupeCapped([...actionable[actionabilityField]??[],...supplied],{cap:ACTIONABILITY_FIELD_CAP}),i++}else if(!arg.startsWith("--")){lessonText=args2.slice(i).join(" ");break}}return{category,lessonId,lessonText,force,reason,actionable}}async function handlePromoteCommand(directory,args2){let{category,lessonId,lessonText,force,reason,actionable}=parsePromoteArgs(args2);if(!lessonText&&!lessonId)return`Usage: /swarm promote "<lesson text>" or /swarm promote --from-swarm <id>
|
|
1930
1930
|
Options: --category <cat>, --force --reason "<why>" (audited policy override)
|
|
1931
1931
|
Actionability (direct text only; required unless knowledge.promotion_require_actionable=false):
|
|
1932
1932
|
--applies-to-tools <a,b>, --applies-to-agents <a,b>,
|
|
@@ -1950,7 +1950,7 @@ CATEGORY: ${correction.category}
|
|
|
1950
1950
|
GUIDANCE: ${correction.guidance}
|
|
1951
1951
|
ACTION: ${correction.action}`}var GUIDANCE_TEMPLATES,ACTION_TEMPLATES;var init_course_correction=__esm(()=>{GUIDANCE_TEMPLATES={repetition_loop:"Agent is repeating the same action on the same target. Consider consolidating changes, stepping back to review the approach, or delegating to a different agent.",ping_pong:"Agents are delegating back and forth without making progress. Consider having the architect take direct control or redefining the task boundaries.",expansion_drift:"Scope is expanding beyond the original task. Consider creating a follow-up task, reducing the current scope, or updating the spec.",stuck_on_test:"Repeated edit-test cycles detected. Consider reviewing the test expectations, checking for environmental issues, or seeking SME consultation.",context_thrash:"Agent is requesting increasingly large file sets. Consider focusing on the specific files needed for the current task or compacting context."},ACTION_TEMPLATES={repetition_loop:(match)=>{let agents=match.affectedAgents.length>0?match.affectedAgents.join(", "):"current agent";return`Stop repetitive edits to ${match.affectedTargets.length>0?match.affectedTargets.join(", "):"current target"} by ${agents}. Take a step back and consolidate the changes made so far before proceeding.`},ping_pong:()=>{return"Interrupt the delegation cycle. Architect should take direct control of the task or explicitly redefine which agent owns which subtask."},expansion_drift:()=>{return"Freeze current scope. Document what's been attempted and create a follow-up issue for additional work. Complete current task before expanding further."},stuck_on_test:(match)=>{return`Pause edit-test cycle. ${match.affectedAgents.length>0?match.affectedAgents.join(", "):"the agent"} should review test expectations, verify environment is clean, and consult SME if root cause is unclear.`},context_thrash:(match)=>{return`Restrict file access to only ${match.affectedTargets.length>0?match.affectedTargets.slice(0,3).join(", "):"requested files"}. Use targeted file selection instead of broad context requests.`}}});function createDefaultEscalationState(){return{patternCounts:new Map,escalationLevel:0,lastPatternDetected:null,hardStopPending:!1}}function cloneEscalationState(state){return{patternCounts:new Map(state.patternCounts),escalationLevel:state.escalationLevel,lastPatternDetected:state.lastPatternDetected?{...state.lastPatternDetected,stepRange:[...state.lastPatternDetected.stepRange],affectedAgents:[...state.lastPatternDetected.affectedAgents],affectedTargets:[...state.lastPatternDetected.affectedTargets]}:null,hardStopPending:state.hardStopPending}}function generateCorrection(match,level){let levelPrefix=level===1?"GUIDANCE":level===2?"STRONG GUIDANCE":"HARD STOP",alertTemplates={repetition_loop:`${levelPrefix}: Repetitive action loop detected`,ping_pong:`${levelPrefix}: Delegation ping-pong detected`,expansion_drift:`${levelPrefix}: Scope expansion drift detected`,stuck_on_test:`${levelPrefix}: Stuck in edit-test cycle`,context_thrash:`${levelPrefix}: Excessive context requests detected`},guidanceTemplates={repetition_loop:"Stop the repetitive loop. Consolidate changes and take a different approach.",ping_pong:"Interrupt the delegation cycle. Architect should take direct control.",expansion_drift:"Freeze scope expansion. Complete current task before adding more work.",stuck_on_test:"Pause edit-test cycle. Review test expectations and verify environment.",context_thrash:"Restrict file access. Use targeted selection instead of broad context requests."},actionTemplates={repetition_loop:"Consolidate changes and change approach immediately.",ping_pong:"Architect take direct control or redefine agent task boundaries.",expansion_drift:"Document progress and create follow-up issue for additional work.",stuck_on_test:"Review test expectations, verify environment, consult SME if needed.",context_thrash:"Restrict to only the specific files needed for the current task."};return{alert:alertTemplates[match.pattern],category:match.category,guidance:guidanceTemplates[match.pattern],action:actionTemplates[match.pattern],pattern:match.pattern,stepRange:match.stepRange}}class EscalationTracker{_sessionId;_state;constructor(sessionId,initialState){this._sessionId=sessionId,this._state=initialState??createDefaultEscalationState()}recordDetection(match){let newCount=(this._state.patternCounts.get(match.pattern)??0)+1;if(this._state.patternCounts.set(match.pattern,newCount),this._state.lastPatternDetected=match,newCount===1){let correction=generateCorrection(match,1);return this._state.escalationLevel=1,{level:1,correction,hardStop:!1}}else if(newCount===2){let correction=generateCorrection(match,2);return this._state.escalationLevel=2,telemetry.prmEscalationTriggered(this._sessionId,match.pattern,2,newCount),{level:2,correction,hardStop:!1}}else{let correction=generateCorrection(match,3);return this._state.escalationLevel=3,this._state.hardStopPending=!0,telemetry.prmHardStop(this._sessionId,match.pattern,3,newCount),{level:3,correction,hardStop:!0}}}getState(){return cloneEscalationState(this._state)}reset(){this._state=createDefaultEscalationState()}isHardStopPending(){return this._state.hardStopPending}}var init_escalation=__esm(()=>{init_telemetry()});function sanitizeString3(input){if(!input||typeof input!=="string")return"";let result=input;result=result.replace(/[\n\r]/g,""),result=result.replace(/`/g,""),result=result.replace(/<[^>]*>/g,"");for(let pattern of INJECTION_PATTERNS2)result=result.replace(pattern,"[REDACTED]");if(result=result.trim(),result.length>200)result=`${result.slice(0,197)}...`;return result}function detectRepetitionLoop(trajectory,config3){let matches=[];if(trajectory.length<2)return matches;let windowSize=10,threshold=config3.pattern_thresholds?.repetition_loop??DEFAULT_THRESHOLDS.repetition_loop;for(let i=0;i<trajectory.length;i++){let windowStart=Math.max(0,i-windowSize+1),window2=trajectory.slice(windowStart,i+1),counts=new Map;for(let entry of window2){let key=`${entry.agent}|${entry.action}|${entry.target}`,existing=counts.get(key);if(existing)existing.count++,existing.endStep=entry.step;else counts.set(key,{count:1,startStep:entry.step,endStep:entry.step})}for(let[key,data]of counts)if(data.count>=threshold){let[agent,action,target]=key.split("|"),severity=data.count>=3?"high":"medium";matches.push({pattern:"repetition_loop",severity,category:"coordination_error",stepRange:[data.startStep,data.endStep],description:`Agent "${sanitizeString3(agent)}" performed "${sanitizeString3(action)}" on "${sanitizeString3(target)}" ${data.count} times within ${windowSize} steps`,affectedAgents:[sanitizeString3(agent)],affectedTargets:[sanitizeString3(target)],occurrenceCount:data.count})}}return matches}function detectPingPong(trajectory,config3){let matches=[],threshold=config3.pattern_thresholds?.ping_pong??DEFAULT_THRESHOLDS.ping_pong,minThreshold=3,effectiveThreshold=Math.max(threshold,3),delegateEntries=trajectory.filter((e)=>e.action==="delegate");if(delegateEntries.length<effectiveThreshold)return matches;let detectedPairs=new Set,i=0;while(i<delegateEntries.length){if(i+1>=delegateEntries.length)break;let firstAgent=delegateEntries[i].agent,secondAgent=delegateEntries[i+1].agent,target=delegateEntries[i].target;if(firstAgent===secondAgent){i++;continue}let endIndex=i+1;for(let j=i+2;j<delegateEntries.length;j++){let expectedAgent=(j-i)%2===0?firstAgent:secondAgent;if(delegateEntries[j].agent!==expectedAgent||delegateEntries[j].target!==target)break;endIndex=j}let patternLength=endIndex-i+1;if(patternLength>=effectiveThreshold){let pairKey2=`${[firstAgent,secondAgent].sort().join(",")}-${target}`;if(!detectedPairs.has(pairKey2)){detectedPairs.add(pairKey2);let roundTrips=Math.floor(patternLength/2);matches.push({pattern:"ping_pong",severity:"high",category:"coordination_error",stepRange:[delegateEntries[i].step,delegateEntries[endIndex].step],description:`Ping-pong delegation detected: "${sanitizeString3(firstAgent)}" and "${sanitizeString3(secondAgent)}" alternating on "${sanitizeString3(target)}"`,affectedAgents:[sanitizeString3(firstAgent),sanitizeString3(secondAgent)],affectedTargets:[sanitizeString3(target)],occurrenceCount:roundTrips})}i=endIndex+1}else i++}return matches}function detectExpansionDrift(trajectory,config3){let matches=[],threshold=config3.pattern_thresholds?.expansion_drift??DEFAULT_THRESHOLDS.expansion_drift,windowSize=Math.max(threshold,5),minTrajectoryLength=windowSize*2;if(trajectory.length<minTrajectoryLength)return matches;for(let i=windowSize*2;i<=trajectory.length;i+=windowSize){let recentWindow=trajectory.slice(i-windowSize,i),previousWindow=trajectory.slice(i-windowSize*2,i-windowSize),recentTargets=new Set(recentWindow.map((e)=>e.target)),previousTargets=new Set(previousWindow.map((e)=>e.target));if(previousTargets.size>0){let expansionRatio=recentTargets.size/previousTargets.size;if(expansionRatio>1.5)matches.push({pattern:"expansion_drift",severity:"medium",category:"specification_error",stepRange:[previousWindow[0].step,recentWindow[recentWindow.length-1].step],description:`Scope expansion detected: ${previousTargets.size} unique targets → ${recentTargets.size} unique targets (${expansionRatio.toFixed(1)}x increase)`,affectedAgents:[...new Set(recentWindow.map((e)=>sanitizeString3(e.agent)))],affectedTargets:[...recentTargets].map((t)=>sanitizeString3(t)),occurrenceCount:Math.floor(expansionRatio*10)/10})}}return matches}function detectStuckOnTest(trajectory,config3){let matches=[];if(trajectory.length<3)return matches;let threshold=config3.pattern_thresholds?.stuck_on_test??DEFAULT_THRESHOLDS.stuck_on_test,fileCycles=new Map;for(let i=0;i<trajectory.length;i++){let entry=trajectory[i];if(entry.action==="edit"){let existing=fileCycles.get(entry.target);if(existing){if(existing.edits++,existing.steps.push(entry.step),!existing.agents.includes(entry.agent))existing.agents.push(entry.agent)}else fileCycles.set(entry.target,{edits:1,tests:0,steps:[entry.step],agents:[entry.agent]})}else if(entry.action==="test"){let existing=fileCycles.get(entry.target);if(existing)existing.tests++}}for(let[file3,data]of fileCycles)if(data.edits>=threshold&&data.tests>=1){let cycleCount=0,lastEditStep=-1,lastTestStep=-1,cycleStart=-1,cycleEnd=-1;for(let i=0;i<trajectory.length;i++){let entry=trajectory[i];if(entry.target===file3){if(entry.action==="edit"){if(lastTestStep>lastEditStep&&lastEditStep>0){if(cycleCount++,cycleStart===-1)cycleStart=lastEditStep;cycleEnd=entry.step}lastEditStep=entry.step}else if(entry.action==="test"&&entry.result==="failure")lastTestStep=entry.step}}if(cycleCount>=threshold)matches.push({pattern:"stuck_on_test",severity:"high",category:"reasoning_error",stepRange:[cycleStart,cycleEnd],description:`Stuck on test detected: ${cycleCount} edit-test cycles on "${sanitizeString3(file3)}"`,affectedAgents:data.agents.map((a)=>sanitizeString3(a)),affectedTargets:[sanitizeString3(file3)],occurrenceCount:cycleCount})}return matches}function detectContextThrash(trajectory,config3){let matches=[];if(trajectory.length<2)return matches;let threshold=config3.pattern_thresholds?.context_thrash??DEFAULT_THRESHOLDS.context_thrash,seenTargets=new Set,cumulativeCounts=[];for(let entry of trajectory)seenTargets.add(entry.target),cumulativeCounts.push(seenTargets.size);let runStart=0,runLength=1;for(let i=1;i<=cumulativeCounts.length;i++)if(i<cumulativeCounts.length&&cumulativeCounts[i]>cumulativeCounts[i-1])runLength++;else{if(runLength>=threshold){let runEnd=i-1,priorCount=runStart>0?cumulativeCounts[runStart-1]:0,finalCount=cumulativeCounts[runEnd];matches.push({pattern:"context_thrash",severity:"medium",category:"coordination_error",stepRange:[trajectory[runStart].step,trajectory[runEnd].step],description:`Context thrash detected: unique targets grew monotonically from ${priorCount} to ${finalCount} over ${runLength} steps`,affectedAgents:[...new Set(trajectory.slice(runStart,runEnd+1).map((e)=>sanitizeString3(e.agent)))],affectedTargets:[...new Set(trajectory.slice(runStart,runEnd+1).map((e)=>sanitizeString3(e.target)))],occurrenceCount:runLength})}runStart=i,runLength=1}return matches}function detectPatterns(trajectory,config3,lastProcessedStep=0){let startTime=Date.now();if(config3.enabled===!1)return{matches:[],detectionTimeMs:0,patternsChecked:5};let allMatches=[];allMatches.push(...detectRepetitionLoop(trajectory,config3)),allMatches.push(...detectPingPong(trajectory,config3)),allMatches.push(...detectExpansionDrift(trajectory,config3)),allMatches.push(...detectStuckOnTest(trajectory,config3)),allMatches.push(...detectContextThrash(trajectory,config3));let detectionTimeMs=Date.now()-startTime,severityRank={critical:4,high:3,medium:2,low:1},dedupedMatches=new Map;for(let match of allMatches){let key=`${match.pattern}-${match.affectedAgents.join(",")}-${match.affectedTargets.join(",")}-${match.stepRange[0]}-${match.stepRange[1]}`,existing=dedupedMatches.get(key);if(!existing)dedupedMatches.set(key,match);else{let existingRank=severityRank[existing.severity]??0;if((severityRank[match.severity]??0)>existingRank)dedupedMatches.set(key,match)}}return{matches:Array.from(dedupedMatches.values()).filter((match)=>match.stepRange[1]>lastProcessedStep),detectionTimeMs,patternsChecked:5}}var INJECTION_PATTERNS2,DEFAULT_THRESHOLDS;var init_pattern_detector=__esm(()=>{INJECTION_PATTERNS2=[/\[SYSTEM\]/gi,/SYSTEM\s*OVERRIDE/gi,/IGNORE\s*PREVIOUS/gi,/IGNORE\s*ALL/gi,/NEW\s*INSTRUCTION/gi,/Override\s*instructions/gi,/\bJAILBREAK/gi,/\bDAN\s*MODE/gi,/\bBYPASS/gi];DEFAULT_THRESHOLDS={repetition_loop:2,ping_pong:2,expansion_drift:3,stuck_on_test:3,context_thrash:3}});import{promises as fs82}from"node:fs";import path163 from"node:path";function isPathSafe3(targetPath,basePath){let resolvedTarget=path163.resolve(targetPath),resolvedBase=path163.resolve(basePath),rel=path163.relative(resolvedBase,resolvedTarget);return!rel.startsWith("..")&&!path163.isAbsolute(rel)}function isWithinReplaysDir(targetPath){let parts=path163.resolve(targetPath).split(path163.sep);for(let i=0;i<parts.length-1;i++)if(parts[i]===".swarm"&&parts[i+1]==="replays")return!0;return!1}function sanitizeFilename(input){return input.replace(/[^a-zA-Z0-9_-]/g,"_")}async function startReplayRecording(sessionID,directory){try{let replayDir=path163.join(directory,".swarm","replays"),filename=`${sanitizeFilename(sessionID)}-${Date.now()}.jsonl`,filepath=path163.join(replayDir,filename);if(!isPathSafe3(filepath,replayDir))return advisoryWarn(`[replay] Invalid path detected - path traversal attempt blocked for session ${sessionID}`),null;return await fs82.mkdir(replayDir,{recursive:!0}),filepath}catch(err){return log(`[replay] Failed to start recording for session ${sessionID}: ${err}`),null}}async function recordReplayEntry(artifactPath,sessionID,entry){try{if(!isWithinReplaysDir(artifactPath)){log(`[replay] Invalid artifact path - not within .swarm/replays/: ${artifactPath}`);return}let fullEntry={timestamp:new Date().toISOString(),sessionID,...entry},line=`${JSON.stringify(fullEntry)}
|
|
1952
1952
|
`;await fs82.appendFile(artifactPath,line,"utf-8")}catch(err){log(`[replay] Failed to record entry: ${err}`)}}var init_replay=__esm(()=>{init_warning_buffer();init_logger()});function resetPrmSessionState(session,sessionId){if(session.prmEscalationTracker=void 0,session.prmInitialized=!1,session.prmPatternCounts=new Map,session.prmEscalationLevel=0,session.prmLastPatternDetected=null,session.prmHardStopPending=!1,session.prmHardStopInjectPending=!1,session.prmTrajectoryStep=0,session.prmInjectedAdvisoryKeys=new Set,session.replayArtifactPath=null,sessionId)_internals114.clearTrajectoryCache(sessionId)}function resolvePrmPatternPersistenceOptions(learning){return{enabled:learning.prm_persistence.enabled,min_support:learning.prm_persistence.min_support,cooldown_ms:learning.prm_persistence.cooldown_ms,admission_enabled:learning.realtime_admission.enabled,max_queue_size:learning.realtime_admission.max_queue_size}}function createPrmHook(config3,directory,patternPersistence){async function toolAfter(context){if(!config3.enabled)return;let{sessionID}=context,session=_internals114.getAgentSession(sessionID);if(!session||!session.delegationActive)return;try{let cachedTrajectory=_internals114.getInMemoryTrajectory(sessionID),trajectory=cachedTrajectory.length>0?cachedTrajectory:await _internals114.readTrajectory(sessionID,directory),detectionResult=_internals114.detectPatterns(trajectory,config3,session.prmTrajectoryStep);if(detectionResult.matches.length===0)return;if(patternPersistence?.enabled)for(let match of detectionResult.matches){let observation=_internals114.recordPatternObservation(sessionID,match,{minSupport:patternPersistence.min_support,cooldownMs:patternPersistence.cooldown_ms});if(observation.persistable&&observation.candidate){try{await _internals114.appendInsightCandidates(directory,[observation.candidate])}catch(err){warn(`[prm] insight-candidate append failed (non-fatal): ${err instanceof Error?err.message:String(err)}`)}if(patternPersistence.admission_enabled)_internals114.enqueueCandidate(sessionID,observation.candidate,{maxQueueSize:patternPersistence.max_queue_size})}}let sessionPrmState=session,escalationTracker=sessionPrmState.prmEscalationTracker;if(!sessionPrmState.replayArtifactPath)sessionPrmState.replayArtifactPath=await _internals114.startReplayRecording(sessionID,directory);let artifactPath=sessionPrmState.replayArtifactPath;if(!sessionPrmState.prmInitialized)sessionPrmState.prmInitialized=!0,_internals114.cleanupOldTrajectoryFiles(directory).catch(()=>{});if(!escalationTracker){let initialState=session.prmLastPatternDetected?{patternCounts:new Map(session.prmPatternCounts.entries()),escalationLevel:session.prmEscalationLevel,lastPatternDetected:session.prmLastPatternDetected,hardStopPending:session.prmHardStopPending}:void 0;escalationTracker=new EscalationTracker(sessionID,initialState),sessionPrmState.prmEscalationTracker=escalationTracker}let previousEscalationLevel=session.prmEscalationLevel,tickHardStop=!1;for(let match of detectionResult.matches){let correction=_internals114.generateCourseCorrection(match,trajectory),formattedCorrection=_internals114.formatCourseCorrectionForInjection(correction),escalationLevel=0,hardStopPending=!1;if(config3.escalation_enabled!==!1){let escalationResult=escalationTracker.recordDetection(match);escalationLevel=escalationResult.level,hardStopPending=escalationResult.hardStop}let prmDedupeKey=`prm:${match.pattern}:${escalationLevel}`;if(!session.prmInjectedAdvisoryKeys?.has(prmDedupeKey))pushAdvisory(session,`[${prmDedupeKey}] ${formattedCorrection}`,{dedupeKey:prmDedupeKey}),session.prmInjectedAdvisoryKeys??=new Set,session.prmInjectedAdvisoryKeys.add(prmDedupeKey);if(session.prmPatternCounts.set(match.pattern,(session.prmPatternCounts.get(match.pattern)??0)+1),session.prmEscalationLevel=escalationLevel,session.prmLastPatternDetected=match,tickHardStop=tickHardStop||hardStopPending,session.prmHardStopPending=tickHardStop,tickHardStop)session.prmHardStopInjectPending=!0;if(_internals114.telemetry.prmPatternDetected(sessionID,match.pattern,match.severity,match.category,match.stepRange),_internals114.telemetry.prmCourseCorrectionInjected(sessionID,match.pattern,escalationLevel),artifactPath)await _internals114.recordReplayEntry(artifactPath,sessionID,{type:"pattern_detected",data:{pattern:match.pattern,severity:match.severity,category:match.category,stepRange:match.stepRange,description:match.description,affectedAgents:match.affectedAgents,affectedTargets:match.affectedTargets,occurrenceCount:match.occurrenceCount}});if(artifactPath)await _internals114.recordReplayEntry(artifactPath,sessionID,{type:"course_correction",data:{pattern:correction.pattern,alert:correction.alert,category:correction.category,guidance:correction.guidance,action:correction.action,stepRange:correction.stepRange,escalationLevel}})}if(artifactPath&&session.prmEscalationLevel>previousEscalationLevel)await _internals114.recordReplayEntry(artifactPath,sessionID,{type:"escalation",data:{previousLevel:previousEscalationLevel,newLevel:session.prmEscalationLevel,hardStopPending:session.prmHardStopPending}});if(artifactPath&&session.prmHardStopPending&&previousEscalationLevel<3)await _internals114.recordReplayEntry(artifactPath,sessionID,{type:"hard_stop",data:{escalationLevel:session.prmEscalationLevel,triggeredAt:new Date().toISOString()}});if(trajectory.length>0)session.prmTrajectoryStep=trajectory[trajectory.length-1].step}catch(err){log(`[prm] toolAfter error for session ${sessionID}: ${err}`)}}return{toolAfter}}var _internals114;var init_prm=__esm(()=>{init_course_correction();init_escalation();init_pattern_detector();init_micro_reflector();init_candidate_queue();init_prm_pattern_support();init_state2();init_telemetry();init_logger();init_course_correction();init_escalation();init_pattern_detector();init_replay();init_trajectory_store();_internals114={getAgentSession,readTrajectory,getInMemoryTrajectory,detectPatterns,generateCourseCorrection,formatCourseCorrectionForInjection,cleanupOldTrajectoryFiles,clearTrajectoryCache,recordReplayEntry,startReplayRecording,telemetry,recordPatternObservation,enqueueCandidate,appendInsightCandidates}});import*as fs83 from"node:fs";import*as path164 from"node:path";function errorMessage2(err){if(err instanceof Error)return err.message;return String(err)}async function handleResetSessionCommand(directory,_args){let results=[];try{let backup=_internals115.backupSwarmStateBeforeReset(directory,"reset-session",["session"]);if(backup.backupDir&&backup.copied.length>0){let rel=path164.relative(directory,backup.backupDir);results.push(`\uD83D\uDCE6 Backed up session state to ${rel}/ (restore by copying files back into .swarm/session/)`)}for(let w of backup.warnings)results.push(`⚠️ Backup warning: ${w}`)}catch(err){results.push(`⚠️ Auto-backup failed (continuing with reset): ${err instanceof Error?err.message:String(err)}`)}let statePath;try{if(statePath=validateSwarmPath(directory,"session/state.json"),fs83.existsSync(statePath))fs83.unlinkSync(statePath),results.push("✅ Deleted .swarm/session/state.json");else results.push("⏭️ state.json not found (already clean)")}catch{results.push("❌ Failed to delete state.json")}let sessionDir=statePath?path164.dirname(statePath):void 0,sessionFiles=[];if(sessionDir&&fs83.existsSync(sessionDir))try{sessionFiles=fs83.readdirSync(sessionDir)}catch(err){results.push(`❌ Failed to read session directory: ${errorMessage2(err)}`)}for(let file3 of sessionFiles){if(file3==="state.json")continue;let filePath=path164.join(sessionDir,file3);try{if(!fs83.existsSync(filePath))continue;if(!fs83.lstatSync(filePath).isFile())continue;fs83.unlinkSync(filePath),results.push(`✓ Deleted ${file3}`)}catch(err){results.push(`❌ Failed to delete ${file3}: ${errorMessage2(err)}`)}}let sessionCount=swarmState.agentSessions.size;for(let[sessionId,session]of swarmState.agentSessions)resetPrmSessionState(session,sessionId),clearTrajectoryStep(sessionId);swarmState.agentSessions.clear(),results.push(`✅ Cleared ${sessionCount} in-memory agent session(s)`);let chainCount=swarmState.delegationChains.size;swarmState.delegationChains.clear(),results.push(`✅ Cleared ${chainCount} delegation chain(s)`);let worktreesDir=path164.resolve(path164.dirname(directory),SWARM_WORKTREE_DIR_NAME);try{if(fs83.existsSync(worktreesDir))fs83.rmSync(worktreesDir,{recursive:!0,force:!0}),results.push("✅ Removed .swarm-worktrees/ directory")}catch(err){results.push(`⚠️ Failed to remove .swarm-worktrees/: ${errorMessage2(err)}`)}try{let branchResult=await _internals115.cleanupOrphanedBranches(directory,[]);if(branchResult.removed.length>0)results.push(`✅ Removed ${branchResult.removed.length} orphan swarm-lane branch(es)`);if(branchResult.errors.length>0)results.push(`⚠️ Failed to remove ${branchResult.errors.length} branch(es): ${branchResult.errors.map((e)=>e.error).join("; ")}`);if(branchResult.skippedRecoveryBranches&&branchResult.skippedRecoveryBranches.length>0)results.push(`ℹ️ Preserved ${branchResult.skippedRecoveryBranches.length} branch(es) with unresolved merge-back recovery records (run /swarm status to inspect)`);if(branchResult.recoveryReadError)results.push("⚠️ Skipped all lane-branch deletions: .swarm/recovery/ was unreadable (fail-safe). Resolve or clear corrupt recovery records and re-run.")}catch(err){results.push(`⚠️ Failed to cleanup orphan branches: ${errorMessage2(err)}`)}return["## Session State Reset","",...results,"","Session state cleared. Plan, evidence, and knowledge preserved.","","**All circuit breakers and revision limits have been cleared.** You can continue in this session — fresh state will be initialized automatically on the next tool call."].join(`
|
|
1953
|
-
`)}var _internals115;var init_reset_session=__esm(()=>{init_constants();init_trajectory_logger();init_utils2();init_prm();init_state2();init_merge();init_reset_backup();_internals115={cleanupOrphanedBranches,backupSwarmStateBeforeReset}});import{mkdirSync as mkdirSync43,readdirSync as
|
|
1953
|
+
`)}var _internals115;var init_reset_session=__esm(()=>{init_constants();init_trajectory_logger();init_utils2();init_prm();init_state2();init_merge();init_reset_backup();_internals115={cleanupOrphanedBranches,backupSwarmStateBeforeReset}});import{mkdirSync as mkdirSync43,readdirSync as readdirSync25,renameSync as renameSync25,rmSync as rmSync13,statSync as statSync34}from"node:fs";import*as path165 from"node:path";function sanitizeSummaryId(id){if(!id||id.length===0)throw Error("Invalid summary ID: empty string");if(/\0/.test(id))throw Error("Invalid summary ID: contains null bytes");for(let i=0;i<id.length;i++)if(id.charCodeAt(i)<32)throw Error("Invalid summary ID: contains control characters");if(id.includes("..")||id.includes("../")||id.includes("..\\"))throw Error("Invalid summary ID: path traversal detected");if(!SUMMARY_ID_REGEX.test(id))throw Error(`Invalid summary ID: must match pattern ^S\\d+$, got "${id}"`);return id}async function storeSummary(directory,id,fullOutput,summaryText,maxStoredBytes){let sanitizedId=sanitizeSummaryId(id),preCheckEntry={id:sanitizedId,summaryText,fullOutput,timestamp:Date.now(),originalBytes:Buffer.byteLength(fullOutput,"utf8")},serializedSize=Buffer.byteLength(JSON.stringify(preCheckEntry),"utf8");if(serializedSize>maxStoredBytes)throw Error(`Summary entry size (${serializedSize} bytes) exceeds maximum (${maxStoredBytes} bytes)`);let relativePath2=path165.join("summaries",`${sanitizedId}.json`),summaryPath=validateSwarmPath(directory,relativePath2),summaryDir=path165.dirname(summaryPath),entry={id:sanitizedId,summaryText,fullOutput,timestamp:Date.now(),originalBytes:Buffer.byteLength(fullOutput,"utf8")},entryJson=JSON.stringify(entry);mkdirSync43(summaryDir,{recursive:!0});let tempPath=path165.join(summaryDir,`${sanitizedId}.json.tmp.${Date.now()}.${process.pid}`);try{await bunWrite(tempPath,entryJson),renameSync25(tempPath,summaryPath)}catch(error93){try{rmSync13(tempPath,{force:!0})}catch{}throw error93}}async function loadFullOutput(directory,id){let sanitizedId=sanitizeSummaryId(id),relativePath2=path165.join("summaries",`${sanitizedId}.json`);validateSwarmPath(directory,relativePath2);let content=await readSwarmFileAsync(directory,relativePath2);if(content===null)return null;try{let parsed=JSON.parse(content);if(typeof parsed.fullOutput==="string")return parsed.fullOutput;return warn(`Summary entry ${sanitizedId} missing valid fullOutput field`),null}catch(error93){return warn(`Summary entry validation failed for ${sanitizedId}: ${error93 instanceof Error?error93.message:String(error93)}`),null}}var SUMMARY_ID_REGEX;var init_manager4=__esm(()=>{init_utils2();init_utils();init_bun_compat();SUMMARY_ID_REGEX=/^S\d+$/});async function handleRetrieveCommand(directory,args2){let summaryId=args2[0];if(!summaryId)return["## Swarm Retrieve","","Usage: `/swarm retrieve <id>`","","Example: `/swarm retrieve S1`","","Retrieves the full output that was replaced by a summary."].join(`
|
|
1954
1954
|
`);try{let fullOutput=await loadFullOutput(directory,summaryId);if(fullOutput===null)return`## Summary Not Found
|
|
1955
1955
|
|
|
1956
1956
|
No stored output found for ID \`${summaryId}\`.
|
|
@@ -2071,7 +2071,7 @@ Spec-Kit SDD support:
|
|
|
2071
2071
|
Error analyzing git history: ${err instanceof Error?err.message:String(err)}
|
|
2072
2072
|
|
|
2073
2073
|
Ensure this is a git repository with commit history.`}let report=["# Simulate Report","",`Generated: ${new Date().toISOString()}`,"","## Dark Matter Analysis",`${darkMatterPairs.length} hidden coupling pairs detected:`,"","| File A | File B | NPMI | Co-Changes | Lift |","|--------|--------|------|------------|------|",...darkMatterPairs.map((p)=>`| ${p.fileA} | ${p.fileB} | ${p.npmi.toFixed(3)} | ${p.coChangeCount} | ${p.lift.toFixed(2)} |`),"","## Recommendation",`${darkMatterPairs.length} hidden coupling pairs may cause unexpected side effects when modified.`].filter(Boolean).join(`
|
|
2074
|
-
`);try{let fs91=await import("node:fs/promises"),path173=await import("node:path"),reportPath=path173.join(directory,".swarm","simulate-report.md");await fs91.mkdir(path173.dirname(reportPath),{recursive:!0});let reportTempPath=path173.join(path173.dirname(reportPath),`${path173.basename(reportPath)}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await fs91.writeFile(reportTempPath,report,"utf-8"),renameSync28(reportTempPath,reportPath)}catch(err){try{unlinkSync28(reportTempPath)}catch{}throw err}}catch(err){let writeErr=err instanceof Error?err.message:String(err);warn(`simulate: failed to write report to ${directory}/.swarm/simulate-report.md`,writeErr)}return`${darkMatterPairs.length} hidden coupling pairs detected`}var init_simulate=__esm(()=>{init_co_change_analyzer();init_utils()});import{createHash as createHash37,randomUUID as randomUUID16}from"node:crypto";import{closeSync as closeSync17,existsSync as existsSync84,fsyncSync as fsyncSync6,mkdirSync as mkdirSync46,openSync as openSync17,readFileSync as readFileSync65,renameSync as renameSync29,statSync as
|
|
2074
|
+
`);try{let fs91=await import("node:fs/promises"),path173=await import("node:path"),reportPath=path173.join(directory,".swarm","simulate-report.md");await fs91.mkdir(path173.dirname(reportPath),{recursive:!0});let reportTempPath=path173.join(path173.dirname(reportPath),`${path173.basename(reportPath)}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await fs91.writeFile(reportTempPath,report,"utf-8"),renameSync28(reportTempPath,reportPath)}catch(err){try{unlinkSync28(reportTempPath)}catch{}throw err}}catch(err){let writeErr=err instanceof Error?err.message:String(err);warn(`simulate: failed to write report to ${directory}/.swarm/simulate-report.md`,writeErr)}return`${darkMatterPairs.length} hidden coupling pairs detected`}var init_simulate=__esm(()=>{init_co_change_analyzer();init_utils()});import{createHash as createHash37,randomUUID as randomUUID16}from"node:crypto";import{closeSync as closeSync17,existsSync as existsSync84,fsyncSync as fsyncSync6,mkdirSync as mkdirSync46,openSync as openSync17,readFileSync as readFileSync65,renameSync as renameSync29,statSync as statSync35,unlinkSync as unlinkSync29,writeFileSync as writeFileSync27,writeFileSync as writeFileSyncAsync}from"node:fs";import*as path173 from"node:path";function canonicalJson2(value){if(value===null||typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map(canonicalJson2).join(",")}]`;return`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${canonicalJson2(v)}`).join(",")}}`}function computeStateHash(value){return createHash37("sha256").update(canonicalJson2(value),"utf8").digest("hex")}function computeContentHash2(content){return createHash37("sha256").update(content,"utf8").digest("hex")}function computeEventHash(event){return computeStateHash({seq:event.seq,candidateId:event.candidateId,skillSlug:event.skillSlug,eventType:event.eventType,fromState:event.fromState,toState:event.toState,actor:event.actor,origin:event.origin,reason:event.reason,contentHashBefore:event.contentHashBefore,contentHashAfter:event.contentHashAfter,hashBefore:event.hashBefore,evidenceRefs:event.evidenceRefs,...event.payload?{payload:event.payload}:{},timestamp:event.timestamp})}function isValidSkillSlug(slug){return SLUG_PATTERN3.test(slug)}function isValidCandidateId(id){return/^[A-Za-z0-9_-]{8,128}$/.test(id)}function mintCandidateId(){return randomUUID16()}function candidateDir(directory,skillSlug,candidateId2){return path173.join(directory,".swarm","evolution","skills",skillSlug,candidateId2)}function ledgerPath(directory,skillSlug,candidateId2){return path173.join(candidateDir(directory,skillSlug,candidateId2),"lifecycle.jsonl")}function stateProjectionPath(directory,skillSlug,candidateId2){return path173.join(candidateDir(directory,skillSlug,candidateId2),"state.json")}function ensureCandidateDir(directory,skillSlug,candidateId2){let dir=candidateDir(directory,skillSlug,candidateId2);if(!existsSync84(dir))mkdirSync46(dir,{recursive:!0});return dir}function writeFileFsyncedThenRename2(tempPath,targetPath,data){let fd=openSync17(tempPath,"w");try{writeFileSync27(fd,data,"utf8"),fsyncSync6(fd)}finally{closeSync17(fd)}try{renameSync29(tempPath,targetPath)}catch(err){try{unlinkSync29(tempPath)}catch{}throw err}}async function appendEvent(directory,eventInput){if(!isValidSkillSlug(eventInput.skillSlug))throw Error(`invalid skill slug: ${eventInput.skillSlug}`);if(!isValidCandidateId(eventInput.candidateId))throw Error(`invalid candidate id: ${eventInput.candidateId}`);let filePath=ledgerPath(directory,eventInput.skillSlug,eventInput.candidateId);return ensureCandidateDir(directory,eventInput.skillSlug,eventInput.candidateId),_internals123.withEvidenceLock(directory,path173.join(".swarm","evolution","skills",eventInput.skillSlug,eventInput.candidateId,"lifecycle.jsonl"),"skill-opt-ledger","append-skill-opt-event",async()=>{let existing=existsSync84(filePath)?readFileSync65(filePath,"utf8"):"",events=parseEventsFromText(existing),nextSeq=events.length===0?1:events[events.length-1].seq+1,lastEvent=events.length===0?null:events[events.length-1],hashBefore=lastEvent?lastEvent.hashAfter:computeStateHash(null),event={seq:nextSeq,timestamp:eventInput.timestamp??new Date().toISOString(),candidateId:eventInput.candidateId,skillSlug:eventInput.skillSlug,eventType:eventInput.eventType,fromState:eventInput.fromState,toState:eventInput.toState,actor:eventInput.actor,origin:eventInput.origin,contentHashBefore:eventInput.contentHashBefore,contentHashAfter:eventInput.contentHashAfter,hashBefore,hashAfter:"",reason:eventInput.reason,evidenceRefs:eventInput.evidenceRefs,...eventInput.payload?{payload:eventInput.payload}:{}};event.hashAfter=computeEventHash(event);let tempPath=`${filePath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`,line=`${JSON.stringify(event)}
|
|
2075
2075
|
`,validContent=events.map((e)=>JSON.stringify(e)).join(`
|
|
2076
2076
|
`)+(events.length>0?`
|
|
2077
2077
|
`:"");_internals123.writeFileFsyncedThenRename(tempPath,filePath,validContent+line);let verify=parseEventsFromText(_internals123.readFileSync(filePath,"utf8")),last=verify.length>0?verify[verify.length-1]:null;if(!last||last.seq!==event.seq||last.hashAfter!==event.hashAfter)throw Error(`skill-opt ledger append verification failed for candidate ${event.candidateId} seq ${event.seq}`);return event})}function parseEventsFromText(text){if(text.length===0)return[];let lines=text.split(`
|
|
@@ -2079,7 +2079,7 @@ Ensure this is a git repository with commit history.`}let report=["# Simulate Re
|
|
|
2079
2079
|
`),events=[],truncated=!1,badSuffix=null,lastCompleteSeq=0;for(let i=0;i<lines.length;i++){let line=lines[i];if(line.length===0)continue;let parsed;try{parsed=JSON.parse(line)}catch{truncated=!0,badSuffix=lines.slice(i).join(`
|
|
2080
2080
|
`);break}if(computeEventHash(parsed)!==parsed.hashAfter){truncated=!0,badSuffix=lines.slice(i).join(`
|
|
2081
2081
|
`);break}events.push(parsed),lastCompleteSeq=parsed.seq}let state=events.length===0?null:events[events.length-1].toState;return{events,state,truncated,badSuffix,lastCompleteSeq}}function quarantineSuffix(directory,skillSlug,badSuffix){let dir=path173.join(directory,".swarm","evolution","skills");if(!existsSync84(dir))mkdirSync46(dir,{recursive:!0});let hash4=computeStateHash(badSuffix).slice(0,12),stamp=Date.now(),quarantinePath=path173.join(dir,`lifecycle-quarantine.${skillSlug}.${stamp}.${hash4}`);return writeFileSyncAsync(quarantinePath,badSuffix,"utf8"),quarantinePath}function writeStateProjection(directory,skillSlug,candidateId2,replay){let target=stateProjectionPath(directory,skillSlug,candidateId2);ensureCandidateDir(directory,skillSlug,candidateId2);let projection={v:1,candidateId:candidateId2,skillSlug,state:replay.state,lastCompleteSeq:replay.lastCompleteSeq,truncated:replay.truncated,eventCount:replay.events.length,updatedAt:new Date().toISOString()},tempPath=`${target}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;_internals123.writeFileFsyncedThenRename(tempPath,target,`${JSON.stringify(projection,null,2)}
|
|
2082
|
-
`)}function writeArtifact(directory,skillSlug,candidateId2,fileName,content){let dir=ensureCandidateDir(directory,skillSlug,candidateId2),target=path173.join(dir,fileName),tempPath=`${target}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;return _internals123.writeFileFsyncedThenRename(tempPath,target,content),target}function readArtifact(directory,skillSlug,candidateId2,fileName){let target=path173.join(candidateDir(directory,skillSlug,candidateId2),fileName);if(!existsSync84(target))return null;return readFileSync65(target,"utf8")}var SLUG_PATTERN3,_internals123;var init_store2=__esm(()=>{init_lock();SLUG_PATTERN3=/^[a-z0-9][a-z0-9-]{0,63}$/;_internals123={withEvidenceLock,writeFileFsyncedThenRename:writeFileFsyncedThenRename2,writeFileSync:writeFileSyncAsync,readFileSync:readFileSync65,renameSync:renameSync29,unlinkSync:unlinkSync29,existsSync:existsSync84,statSync:statSync36}});function isLegalTransition(from,to){return(from===null?INITIAL_TRANSITIONS:LEGAL_TRANSITIONS[from]).includes(to)}function assertTransition(from,to){if(!isLegalTransition(from,to))throw new IllegalTransitionError(from,to)}async function recordTransition(input){let replay=replayCandidate(input.directory,input.skillSlug,input.candidateId),fromState=replay.state;if(replay.truncated&&replay.badSuffix)quarantineSuffix(input.directory,input.skillSlug,replay.badSuffix),fromState=replay.events.length===0?null:replay.events[replay.events.length-1].toState;if(assertTransition(fromState,input.toState),input.toState==="validation_running"){if(replay.events.some((e)=>e.toState==="accepted_pending_approval"||e.toState==="rejected"||e.toState==="inconclusive"))throw Error(`candidate ${input.candidateId} already completed validation — start a new candidate to re-test`)}let event=await appendEvent(input.directory,{candidateId:input.candidateId,skillSlug:input.skillSlug,eventType:input.eventType,fromState,toState:input.toState,actor:input.actor,origin:input.origin,contentHashBefore:input.contentHashBefore??null,contentHashAfter:input.contentHashAfter??null,reason:input.reason,evidenceRefs:input.evidenceRefs??[],...input.payload?{payload:input.payload}:{}});return writeStateProjection(input.directory,input.skillSlug,input.candidateId,{...replayCandidate(input.directory,input.skillSlug,input.candidateId),events:[...replay.events,event]}),{event,fromState,replayTruncated:replay.truncated}}function currentCandidateState(directory,skillSlug,candidateId2){let replay=replayCandidate(directory,skillSlug,candidateId2);if(replay.truncated&&replay.badSuffix)quarantineSuffix(directory,skillSlug,replay.badSuffix);return{state:replay.events.length===0?null:replay.events[replay.events.length-1].toState,lastEvent:replay.events.length===0?null:replay.events[replay.events.length-1],truncated:replay.truncated}}var IllegalTransitionError,LEGAL_TRANSITIONS,INITIAL_TRANSITIONS;var init_lifecycle=__esm(()=>{init_store2();IllegalTransitionError=class IllegalTransitionError extends Error{from;to;constructor(from,to){super(`illegal skill-opt transition: ${from??"<none>"} → ${to}`);this.from=from;this.to=to;this.name="IllegalTransitionError"}};LEGAL_TRANSITIONS={discovered:["drafted"],drafted:["smoke_validated","rejected"],smoke_validated:["validation_running","rejected"],validation_running:["accepted_pending_approval","rejected","inconclusive"],accepted_pending_approval:["activated","expired","rolled_back"],rejected:[],inconclusive:["drafted","rejected"],activated:["rolled_back"],expired:[],rolled_back:[]},INITIAL_TRANSITIONS=["discovered"]});import{existsSync as existsSync85,mkdirSync as mkdirSync47,readFileSync as readFileSync66,renameSync as renameSync30,unlinkSync as unlinkSync30,writeFileSync as writeFileSync28}from"node:fs";import*as path174 from"node:path";function writeSkillFileAtomic(targetPath,content){let tempPath=`${targetPath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;try{_internals124.writeFileSync(tempPath,content,"utf8"),_internals124.renameSync(tempPath,targetPath)}finally{try{if(existsSync85(tempPath))_internals124.unlinkSync(tempPath)}catch{}}}async function activateCandidate(input){let skillPath=path174.join(input.directory,".opencode","skills","generated",input.skillSlug,"SKILL.md"),incumbent=existsSync85(skillPath)?readFileSync66(skillPath,"utf8"):"",currentHash=computeContentHash2(incumbent);if(currentHash!==input.expectedContentHash)return{activated:!1,reason:`STALE_BASE: expected ${input.expectedContentHash.slice(0,12)} but current is ${currentHash.slice(0,12)}`,rollbackSnapshotRef:""};let candidateContent=readArtifact(input.directory,input.skillSlug,input.candidateId,"candidate.md");if(candidateContent===null)return{activated:!1,reason:"candidate content not found (drafted candidate missing)",rollbackSnapshotRef:""};let state=currentCandidateState(input.directory,input.skillSlug,input.candidateId);if(state.state!=="accepted_pending_approval")return{activated:!1,reason:`INVALID_STATE: candidate is in state ${state.state??"<none>"}; activation requires accepted_pending_approval`,rollbackSnapshotRef:""};let rollbackSnapshotRef=writeArtifact(input.directory,input.skillSlug,input.candidateId,"rollback.md",incumbent),skillRoot=path174.dirname(skillPath);if(!existsSync85(skillRoot))mkdirSync47(skillRoot,{recursive:!0});return writeSkillFileAtomic(skillPath,candidateContent),await recordTransition({directory:input.directory,skillSlug:input.skillSlug,candidateId:input.candidateId,toState:"activated",eventType:"activate",actor:input.actor,origin:"command:skill-opt:approve",reason:"human-approved activation",contentHashBefore:currentHash,contentHashAfter:computeContentHash2(candidateContent),evidenceRefs:[rollbackSnapshotRef],payload:{rollbackSnapshotRef}}),{activated:!0,reason:"activated",rollbackSnapshotRef}}async function rollbackCandidate(input){let snapshot=readArtifact(input.directory,input.skillSlug,input.candidateId,"rollback.md");if(snapshot===null)return{rolledBack:!1,reason:"no rollback snapshot recorded for this candidate"};let state=currentCandidateState(input.directory,input.skillSlug,input.candidateId);if(state.state!=="activated")return{rolledBack:!1,reason:`INVALID_STATE: candidate is in state ${state.state??"<none>"}; rollback requires activated`};let skillPath=path174.join(input.directory,".opencode","skills","generated",input.skillSlug,"SKILL.md"),beforeContent=existsSync85(skillPath)?readFileSync66(skillPath,"utf8"):"";return writeSkillFileAtomic(skillPath,snapshot),await recordTransition({directory:input.directory,skillSlug:input.skillSlug,candidateId:input.candidateId,toState:"rolled_back",eventType:"rollback",actor:input.actor,origin:"command:skill-opt:rollback",reason:"human-invoked rollback",contentHashBefore:computeContentHash2(beforeContent),contentHashAfter:computeContentHash2(snapshot)}),{rolledBack:!0,reason:"rolled back from snapshot"}}var _internals124;var init_activation2=__esm(()=>{init_lifecycle();init_store2();_internals124={writeFileSync:writeFileSync28,renameSync:renameSync30,unlinkSync:unlinkSync30}});var exports_runner={};__export(exports_runner,{runEvaluation:()=>runEvaluation,createModelEvaluationExecutor:()=>createModelEvaluationExecutor,_internals:()=>_internals125});import*as fs91 from"node:fs";import*as path175 from"node:path";function aggregateCost(results){if(results.some((result)=>result.cost.source==="unavailable"))return{source:"unavailable"};return{source:results.some((result)=>result.cost.source==="estimated")?"estimated":"reported",usd:results.reduce((sum,result)=>sum+(result.cost.usd??0),0)}}function failureResult(args2){return{v:1,taskId:args2.task.id,category:args2.task.category,protected:args2.task.protected,repetition:args2.repetition,candidateId:args2.candidate.id,seed:args2.seed,outcome:args2.outcome,scoreRange:args2.task.scorer.scoreRange,cost:args2.cost??{source:"unavailable"},durationMs:args2.durationMs,retries:0,failureCode:args2.failureCode}}function parseBuiltinScore(text){let value;try{value=JSON.parse(text.trim())}catch{throw new ScorerFailure("malformed","builtin-invalid-json",!1)}let parsed=BuiltinVerdictSchema.safeParse(value);if(!parsed.success)throw new ScorerFailure("malformed","builtin-schema-invalid",!1);let verdict=parsed.data;return{v:1,score:verdict.caught?1:0,cost:{source:"unavailable"},metadata:verdict.reason?{reason:verdict.reason}:void 0}}async function scoreExecution(args2){if(args2.task.scorer.kind==="builtin")return parseBuiltinScore(args2.execution.text);let sourceEnvironment=resolveContainedExistingPath(args2.inputRoot,args2.task.environment.path),sourceExecutable=resolveContainedExistingPath(args2.inputRoot,args2.task.scorer.argv[0]),scorerRelative=path175.relative(sourceEnvironment,sourceExecutable);if(!scorerRelative||scorerRelative===".."||scorerRelative.startsWith(`..${path175.sep}`)||path175.isAbsolute(scorerRelative))throw new ScorerFailure("malformed","scorer-outside-task-package",!1);let isolatedExecutable=resolveContainedExistingPath(args2.isolatedRoot,scorerRelative);if(!fs91.statSync(isolatedExecutable).isFile())throw new ScorerFailure("malformed","scorer-not-a-file",!1);let extension=path175.extname(isolatedExecutable).toLowerCase(),isJavaScript=[".cjs",".js",".mjs"].includes(extension),executable=isJavaScript?process.execPath:isolatedExecutable,scorerArgs=isJavaScript?[isolatedExecutable,...args2.task.scorer.argv.slice(1)]:args2.task.scorer.argv.slice(1),artifactDirectory=path175.join(args2.isolatedRoot,".artifacts");fs91.mkdirSync(artifactDirectory,{recursive:!0}),fs91.writeFileSync(path175.join(artifactDirectory,"model-output.json"),JSON.stringify({v:1,text:args2.execution.text}));let result=await _internals125.runExternalTool({executable,args:scorerArgs,cwd:args2.isolatedRoot,timeoutMs:Math.min(args2.task.scorer.timeoutMs,args2.timeoutMs),maxStdoutBytes:args2.maxOutputBytes,maxStderrBytes:args2.maxOutputBytes,abortSignal:args2.abortSignal,env:{...process.env,SWARM_EVAL_TASK_ID:args2.task.id,SWARM_EVAL_CANDIDATE_ID:args2.candidate.id,SWARM_EVAL_ARTIFACT_DIR:artifactDirectory,SWARM_EVAL_SEED:args2.seed}});if(result.status==="timeout")throw new ScorerFailure("timeout","scorer-timeout",!1);if(result.status==="cancelled")throw new ScorerFailure("cancelled","scorer-cancelled",!1);if(result.status==="spawn-error")throw new ScorerFailure("infrastructure_failure","scorer-spawn-failure",!0);if(result.exitCode!==0)throw new ScorerFailure("infrastructure_failure",`scorer-exit-${result.exitCode??"none"}`,!0);if(result.stdoutTruncated||result.stderrTruncated)throw new ScorerFailure("malformed","scorer-output-truncated",!1);let value;try{value=JSON.parse(result.stdout.trim())}catch{throw new ScorerFailure("malformed","scorer-invalid-json",!1)}let parsed=ScorerOutputSchema.safeParse(value);if(!parsed.success)throw new ScorerFailure("malformed","scorer-schema-invalid",!1);return parsed.data}async function runExecutorWithinBudget(args2){let startedAt=Date.now(),controller=new AbortController,timedOut=!1,parentAbort=()=>controller.abort();if(args2.parentSignal.addEventListener("abort",parentAbort,{once:!0}),args2.parentSignal.aborted)controller.abort();let timer=setTimeout(()=>{timedOut=!0,controller.abort()},args2.maxTimeMs);try{let aborted3=new Promise((resolve66)=>{let finish=()=>resolve66({status:timedOut?"timeout":"cancelled",text:"",durationMs:Date.now()-startedAt,cost:{source:"unavailable"},error:timedOut?"executor-task-timeout":"executor-cancelled"});if(controller.signal.addEventListener("abort",finish,{once:!0}),controller.signal.aborted)finish()});return await Promise.race([args2.options.executor({task:args2.task,candidate:args2.candidate,isolatedRoot:args2.isolatedRoot,instruction:args2.instruction,payload:args2.payload,seed:args2.seed,abortSignal:controller.signal,projectRoot:args2.options.projectRoot}),aborted3])}finally{clearTimeout(timer),args2.parentSignal.removeEventListener("abort",parentAbort),controller.abort()}}async function executePairMember(args2){let startedAt=Date.now(),seed=canonicalHash(`${args2.options.seed}:${args2.task.id}:${args2.candidate.id}:${args2.repetition}`);if(args2.signal.aborted)return failureResult({...args2,seed,outcome:"cancelled",durationMs:0,failureCode:"cancelled-before-execution"});if(args2.task.environment.kind==="container")return failureResult({...args2,seed,outcome:"unsupported",durationMs:0,failureCode:"container-runner-unavailable"});try{return await _internals125.withDisposableWorktree({projectRoot:args2.options.projectRoot,baseRef:args2.baseSha,abortSignal:args2.signal,run:async(worktree)=>{let isolatedRoot=path175.join(worktree.path,".swarm-evaluation-task");fs91.mkdirSync(isolatedRoot,{recursive:!0});try{fs91.cpSync(resolveContainedExistingPath(args2.inputRoot,args2.task.environment.path),isolatedRoot,{recursive:!0,errorOnExist:!1});let instruction=fs91.readFileSync(resolveContainedExistingPath(args2.inputRoot,args2.task.instructionPath),"utf8"),payload=fs91.readFileSync(resolveContainedExistingPath(args2.inputRoot,args2.candidate.payloadPath),"utf8"),remainingBeforeExecution=args2.options.budgets.maxTaskTimeMs-(Date.now()-startedAt);if(remainingBeforeExecution<=0)return failureResult({...args2,seed,outcome:"timeout",durationMs:Date.now()-startedAt,failureCode:"task-budget-exhausted-before-executor"});let execution=await runExecutorWithinBudget({options:args2.options,task:args2.task,candidate:args2.candidate,isolatedRoot,instruction,payload,seed,parentSignal:args2.signal,maxTimeMs:remainingBeforeExecution});if(execution.status!=="completed")return failureResult({...args2,seed,outcome:execution.status==="infrastructure_failure"?"infrastructure_failure":execution.status,durationMs:execution.durationMs,cost:execution.cost,failureCode:execution.error??`executor-${execution.status}`});if(Buffer.byteLength(execution.text,"utf8")>args2.options.budgets.maxOutputBytes)return failureResult({...args2,seed,outcome:"malformed",durationMs:Date.now()-startedAt,cost:execution.cost,failureCode:"executor-output-truncated"});let scored;try{let remainingBeforeScorer=args2.options.budgets.maxTaskTimeMs-(Date.now()-startedAt);if(remainingBeforeScorer<=0)throw new ScorerFailure("timeout","task-budget-exhausted-before-scorer",!1);scored=await scoreExecution({task:args2.task,candidate:args2.candidate,inputRoot:args2.inputRoot,isolatedRoot,execution,seed,maxOutputBytes:args2.options.budgets.maxOutputBytes,timeoutMs:remainingBeforeScorer,abortSignal:args2.signal})}catch(error93){let scorerFailure=error93 instanceof ScorerFailure?error93:void 0;return failureResult({...args2,seed,outcome:args2.signal.aborted?"cancelled":scorerFailure?.outcome??"malformed",durationMs:Date.now()-startedAt,cost:execution.cost,failureCode:scorerFailure?.failureCode??(error93 instanceof Error?error93.message.slice(0,160):"scorer-error")})}let[minimum,maximum]=args2.task.scorer.scoreRange;if(scored.score<minimum||scored.score>maximum)return failureResult({...args2,seed,outcome:"malformed",durationMs:Date.now()-startedAt,cost:scored.cost,failureCode:"score-out-of-range"});return{v:1,taskId:args2.task.id,category:args2.task.category,protected:args2.task.protected,repetition:args2.repetition,candidateId:args2.candidate.id,seed,outcome:"scored",score:scored.score,scoreRange:args2.task.scorer.scoreRange,cost:scored.cost,durationMs:Date.now()-startedAt,retries:0,metadata:scored.metadata}}finally{fs91.rmSync(isolatedRoot,{recursive:!0,force:!0})}}})}catch(error93){return failureResult({...args2,seed,outcome:"infrastructure_failure",durationMs:Date.now()-startedAt,failureCode:canonicalHash(String(error93)).slice(0,32)})}}async function executePairMemberWithRetries(args2){let result;for(let attempt=0;attempt<=args2.options.budgets.maxRetries;attempt++)if(result=await executePairMember(args2),result.retries=attempt,result.outcome!=="infrastructure_failure"||args2.signal.aborted)return result;return result}async function runEvaluation(options){let inputRoot=options.inputRoot??options.projectRoot,tasks=options.tasks.map((task)=>EvaluationTaskV1Schema.parse(task));if(tasks.length===0||tasks.length>options.budgets.maxTasks)throw Error("evaluation task count exceeds its declared budget");if(tasks.some((task)=>task.split!==options.split))throw Error("evaluation task split does not match the run split");let baseline=EvaluationCandidateV1Schema.parse(options.baseline),candidate=EvaluationCandidateV1Schema.parse(options.candidate);for(let item of[baseline,candidate])if(await computeCandidateInputContentHash(inputRoot,item)!==item.contentHash)throw Error(`candidate ${item.id} content hash is invalid`);let snapshotDraft={v:1,id:`taskset-${canonicalHash(tasks.map((task)=>task.id)).slice(0,20)}`,split:options.split,tasks,createdAt:new Date().toISOString()};for(let task of tasks)await admitEvaluationTask(options.projectRoot,task,inputRoot);let taskSet={...snapshotDraft,contentHash:computeTaskSetContentHash(snapshotDraft)},storedTaskSet=await saveTaskSetSnapshot(options.projectRoot,taskSet,inputRoot),runId=`eval-${canonicalHash({baseline:baseline.contentHash,candidate:candidate.contentHash,taskSet:storedTaskSet.contentHash,split:options.split,seed:options.seed,models:options.models,budgets:options.budgets}).slice(0,32)}`,existingRun=await readEvaluationRun(options.projectRoot,runId);if(existingRun)return existingRun;if(options.split==="test")await claimHeldOutTest(options.projectRoot,{v:1,runId,taskSetHash:storedTaskSet.contentHash,baselineHash:baseline.contentHash,candidateHash:candidate.contentHash,claimedAt:new Date().toISOString()});let before=await _internals125.captureWorkingTreeFingerprint(options.projectRoot),controller=new AbortController,externallyCancelled=options.abortSignal?.aborted??!1,timedOut=!1,budgetInconclusive=!1,scheduledSpendUsd=0,externalAbort=()=>{externallyCancelled=!0,controller.abort()};if(options.abortSignal?.addEventListener("abort",externalAbort,{once:!0}),externallyCancelled)controller.abort();let totalExecutions=tasks.length*2*options.budgets.maxRepetitions,executionWaves=Math.ceil(totalExecutions/options.budgets.maxConcurrency),totalTimeoutMs=Math.min(2147483647,options.budgets.maxTaskTimeMs*executionWaves*(options.budgets.maxRetries+1)+1000),timeout=setTimeout(()=>{timedOut=!0,controller.abort()},totalTimeoutMs);try{let limit=pLimit(options.budgets.maxConcurrency),jobs=[];for(let task of tasks)for(let item of[baseline,candidate])for(let repetition=0;repetition<options.budgets.maxRepetitions;repetition++)jobs.push(limit(()=>executePairMemberWithRetries({options,inputRoot,task,candidate:item,repetition,signal:controller.signal,baseSha:before.head}).then((result)=>{if(options.budgets.maxSpendUsd!==void 0){if(result.cost.source==="unavailable")budgetInconclusive=!0,controller.abort();else if(scheduledSpendUsd+=result.cost.usd??0,scheduledSpendUsd>options.budgets.maxSpendUsd)budgetInconclusive=!0,controller.abort()}return result})));let results=await Promise.all(jobs);for(let task of tasks)if(await computeTaskInputContentHash(inputRoot,task)!==task.contentHash)throw Error(`task ${task.id} changed during evaluation`);for(let item of[baseline,candidate])if(await computeCandidateInputContentHash(inputRoot,item)!==item.contentHash)throw Error(`candidate ${item.id} changed during evaluation`);let cost=aggregateCost(results),spendUnknown=options.budgets.maxSpendUsd!==void 0&&cost.source==="unavailable",overSpend=options.budgets.maxSpendUsd!==void 0&&cost.source!=="unavailable"&&(cost.usd??0)>options.budgets.maxSpendUsd,incomplete=results.some((result)=>result.outcome!=="scored"),runDraft={v:1,runId,createdAt:new Date().toISOString(),status:externallyCancelled||timedOut?"cancelled":incomplete||spendUnknown||overSpend||budgetInconclusive?"inconclusive":"complete",baseline,candidate,taskSet:{id:storedTaskSet.id,contentHash:storedTaskSet.contentHash,taskIds:tasks.map((task)=>task.id)},split:options.split,seed:options.seed,models:options.models,environment:{platform:process.platform,arch:process.arch,runtime:`node-${process.versions.node};bun-${process.versions.bun??"compat"}`,baseSha:before.head,activeTreeHash:canonicalHash(before),taskSetHash:storedTaskSet.contentHash},budgets:options.budgets,results,cost},run=EvaluationRunV1Schema.parse({...runDraft,integrityHash:computeRunIntegrityHash(runDraft)});return await saveEvaluationRun(options.projectRoot,run),run}finally{clearTimeout(timeout),options.abortSignal?.removeEventListener("abort",externalAbort);let after=await _internals125.captureWorkingTreeFingerprint(options.projectRoot);if(before.head!==after.head||before.porcelainHash!==after.porcelainHash)throw Error("evaluation changed the active working tree")}}function createModelEvaluationExecutor(dispatcher,parentSessionId){return async(args2)=>{let result=await dispatcher({sessionDirectory:args2.projectRoot,agentName:args2.candidate.agent??"reviewer",modelId:args2.candidate.model,system:args2.payload,prompt:["EVALUATION TASK:",args2.instruction,"",`Work ONLY in this directory: ${args2.isolatedRoot}`,"Return the task-required scorer payload exactly."].join(`
|
|
2082
|
+
`)}function writeArtifact(directory,skillSlug,candidateId2,fileName,content){let dir=ensureCandidateDir(directory,skillSlug,candidateId2),target=path173.join(dir,fileName),tempPath=`${target}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;return _internals123.writeFileFsyncedThenRename(tempPath,target,content),target}function readArtifact(directory,skillSlug,candidateId2,fileName){let target=path173.join(candidateDir(directory,skillSlug,candidateId2),fileName);if(!existsSync84(target))return null;return readFileSync65(target,"utf8")}var SLUG_PATTERN3,_internals123;var init_store2=__esm(()=>{init_lock();SLUG_PATTERN3=/^[a-z0-9][a-z0-9-]{0,63}$/;_internals123={withEvidenceLock,writeFileFsyncedThenRename:writeFileFsyncedThenRename2,writeFileSync:writeFileSyncAsync,readFileSync:readFileSync65,renameSync:renameSync29,unlinkSync:unlinkSync29,existsSync:existsSync84,statSync:statSync35}});function isLegalTransition(from,to){return(from===null?INITIAL_TRANSITIONS:LEGAL_TRANSITIONS[from]).includes(to)}function assertTransition(from,to){if(!isLegalTransition(from,to))throw new IllegalTransitionError(from,to)}async function recordTransition(input){let replay=replayCandidate(input.directory,input.skillSlug,input.candidateId),fromState=replay.state;if(replay.truncated&&replay.badSuffix)quarantineSuffix(input.directory,input.skillSlug,replay.badSuffix),fromState=replay.events.length===0?null:replay.events[replay.events.length-1].toState;if(assertTransition(fromState,input.toState),input.toState==="validation_running"){if(replay.events.some((e)=>e.toState==="accepted_pending_approval"||e.toState==="rejected"||e.toState==="inconclusive"))throw Error(`candidate ${input.candidateId} already completed validation — start a new candidate to re-test`)}let event=await appendEvent(input.directory,{candidateId:input.candidateId,skillSlug:input.skillSlug,eventType:input.eventType,fromState,toState:input.toState,actor:input.actor,origin:input.origin,contentHashBefore:input.contentHashBefore??null,contentHashAfter:input.contentHashAfter??null,reason:input.reason,evidenceRefs:input.evidenceRefs??[],...input.payload?{payload:input.payload}:{}});return writeStateProjection(input.directory,input.skillSlug,input.candidateId,{...replayCandidate(input.directory,input.skillSlug,input.candidateId),events:[...replay.events,event]}),{event,fromState,replayTruncated:replay.truncated}}function currentCandidateState(directory,skillSlug,candidateId2){let replay=replayCandidate(directory,skillSlug,candidateId2);if(replay.truncated&&replay.badSuffix)quarantineSuffix(directory,skillSlug,replay.badSuffix);return{state:replay.events.length===0?null:replay.events[replay.events.length-1].toState,lastEvent:replay.events.length===0?null:replay.events[replay.events.length-1],truncated:replay.truncated}}var IllegalTransitionError,LEGAL_TRANSITIONS,INITIAL_TRANSITIONS;var init_lifecycle=__esm(()=>{init_store2();IllegalTransitionError=class IllegalTransitionError extends Error{from;to;constructor(from,to){super(`illegal skill-opt transition: ${from??"<none>"} → ${to}`);this.from=from;this.to=to;this.name="IllegalTransitionError"}};LEGAL_TRANSITIONS={discovered:["drafted"],drafted:["smoke_validated","rejected"],smoke_validated:["validation_running","rejected"],validation_running:["accepted_pending_approval","rejected","inconclusive"],accepted_pending_approval:["activated","expired","rolled_back"],rejected:[],inconclusive:["drafted","rejected"],activated:["rolled_back"],expired:[],rolled_back:[]},INITIAL_TRANSITIONS=["discovered"]});import{existsSync as existsSync85,mkdirSync as mkdirSync47,readFileSync as readFileSync66,renameSync as renameSync30,unlinkSync as unlinkSync30,writeFileSync as writeFileSync28}from"node:fs";import*as path174 from"node:path";function writeSkillFileAtomic(targetPath,content){let tempPath=`${targetPath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;try{_internals124.writeFileSync(tempPath,content,"utf8"),_internals124.renameSync(tempPath,targetPath)}finally{try{if(existsSync85(tempPath))_internals124.unlinkSync(tempPath)}catch{}}}async function activateCandidate(input){let skillPath=path174.join(input.directory,".opencode","skills","generated",input.skillSlug,"SKILL.md"),incumbent=existsSync85(skillPath)?readFileSync66(skillPath,"utf8"):"",currentHash=computeContentHash2(incumbent);if(currentHash!==input.expectedContentHash)return{activated:!1,reason:`STALE_BASE: expected ${input.expectedContentHash.slice(0,12)} but current is ${currentHash.slice(0,12)}`,rollbackSnapshotRef:""};let candidateContent=readArtifact(input.directory,input.skillSlug,input.candidateId,"candidate.md");if(candidateContent===null)return{activated:!1,reason:"candidate content not found (drafted candidate missing)",rollbackSnapshotRef:""};let state=currentCandidateState(input.directory,input.skillSlug,input.candidateId);if(state.state!=="accepted_pending_approval")return{activated:!1,reason:`INVALID_STATE: candidate is in state ${state.state??"<none>"}; activation requires accepted_pending_approval`,rollbackSnapshotRef:""};let rollbackSnapshotRef=writeArtifact(input.directory,input.skillSlug,input.candidateId,"rollback.md",incumbent),skillRoot=path174.dirname(skillPath);if(!existsSync85(skillRoot))mkdirSync47(skillRoot,{recursive:!0});return writeSkillFileAtomic(skillPath,candidateContent),await recordTransition({directory:input.directory,skillSlug:input.skillSlug,candidateId:input.candidateId,toState:"activated",eventType:"activate",actor:input.actor,origin:"command:skill-opt:approve",reason:"human-approved activation",contentHashBefore:currentHash,contentHashAfter:computeContentHash2(candidateContent),evidenceRefs:[rollbackSnapshotRef],payload:{rollbackSnapshotRef}}),{activated:!0,reason:"activated",rollbackSnapshotRef}}async function rollbackCandidate(input){let snapshot=readArtifact(input.directory,input.skillSlug,input.candidateId,"rollback.md");if(snapshot===null)return{rolledBack:!1,reason:"no rollback snapshot recorded for this candidate"};let state=currentCandidateState(input.directory,input.skillSlug,input.candidateId);if(state.state!=="activated")return{rolledBack:!1,reason:`INVALID_STATE: candidate is in state ${state.state??"<none>"}; rollback requires activated`};let skillPath=path174.join(input.directory,".opencode","skills","generated",input.skillSlug,"SKILL.md"),beforeContent=existsSync85(skillPath)?readFileSync66(skillPath,"utf8"):"";return writeSkillFileAtomic(skillPath,snapshot),await recordTransition({directory:input.directory,skillSlug:input.skillSlug,candidateId:input.candidateId,toState:"rolled_back",eventType:"rollback",actor:input.actor,origin:"command:skill-opt:rollback",reason:"human-invoked rollback",contentHashBefore:computeContentHash2(beforeContent),contentHashAfter:computeContentHash2(snapshot)}),{rolledBack:!0,reason:"rolled back from snapshot"}}var _internals124;var init_activation2=__esm(()=>{init_lifecycle();init_store2();_internals124={writeFileSync:writeFileSync28,renameSync:renameSync30,unlinkSync:unlinkSync30}});var exports_runner={};__export(exports_runner,{runEvaluation:()=>runEvaluation,createModelEvaluationExecutor:()=>createModelEvaluationExecutor,_internals:()=>_internals125});import*as fs91 from"node:fs";import*as path175 from"node:path";function aggregateCost(results){if(results.some((result)=>result.cost.source==="unavailable"))return{source:"unavailable"};return{source:results.some((result)=>result.cost.source==="estimated")?"estimated":"reported",usd:results.reduce((sum,result)=>sum+(result.cost.usd??0),0)}}function failureResult(args2){return{v:1,taskId:args2.task.id,category:args2.task.category,protected:args2.task.protected,repetition:args2.repetition,candidateId:args2.candidate.id,seed:args2.seed,outcome:args2.outcome,scoreRange:args2.task.scorer.scoreRange,cost:args2.cost??{source:"unavailable"},durationMs:args2.durationMs,retries:0,failureCode:args2.failureCode}}function parseBuiltinScore(text){let value;try{value=JSON.parse(text.trim())}catch{throw new ScorerFailure("malformed","builtin-invalid-json",!1)}let parsed=BuiltinVerdictSchema.safeParse(value);if(!parsed.success)throw new ScorerFailure("malformed","builtin-schema-invalid",!1);let verdict=parsed.data;return{v:1,score:verdict.caught?1:0,cost:{source:"unavailable"},metadata:verdict.reason?{reason:verdict.reason}:void 0}}async function scoreExecution(args2){if(args2.task.scorer.kind==="builtin")return parseBuiltinScore(args2.execution.text);let sourceEnvironment=resolveContainedExistingPath(args2.inputRoot,args2.task.environment.path),sourceExecutable=resolveContainedExistingPath(args2.inputRoot,args2.task.scorer.argv[0]),scorerRelative=path175.relative(sourceEnvironment,sourceExecutable);if(!scorerRelative||scorerRelative===".."||scorerRelative.startsWith(`..${path175.sep}`)||path175.isAbsolute(scorerRelative))throw new ScorerFailure("malformed","scorer-outside-task-package",!1);let isolatedExecutable=resolveContainedExistingPath(args2.isolatedRoot,scorerRelative);if(!fs91.statSync(isolatedExecutable).isFile())throw new ScorerFailure("malformed","scorer-not-a-file",!1);let extension=path175.extname(isolatedExecutable).toLowerCase(),isJavaScript=[".cjs",".js",".mjs"].includes(extension),executable=isJavaScript?process.execPath:isolatedExecutable,scorerArgs=isJavaScript?[isolatedExecutable,...args2.task.scorer.argv.slice(1)]:args2.task.scorer.argv.slice(1),artifactDirectory=path175.join(args2.isolatedRoot,".artifacts");fs91.mkdirSync(artifactDirectory,{recursive:!0}),fs91.writeFileSync(path175.join(artifactDirectory,"model-output.json"),JSON.stringify({v:1,text:args2.execution.text}));let result=await _internals125.runExternalTool({executable,args:scorerArgs,cwd:args2.isolatedRoot,timeoutMs:Math.min(args2.task.scorer.timeoutMs,args2.timeoutMs),maxStdoutBytes:args2.maxOutputBytes,maxStderrBytes:args2.maxOutputBytes,abortSignal:args2.abortSignal,env:{...process.env,SWARM_EVAL_TASK_ID:args2.task.id,SWARM_EVAL_CANDIDATE_ID:args2.candidate.id,SWARM_EVAL_ARTIFACT_DIR:artifactDirectory,SWARM_EVAL_SEED:args2.seed}});if(result.status==="timeout")throw new ScorerFailure("timeout","scorer-timeout",!1);if(result.status==="cancelled")throw new ScorerFailure("cancelled","scorer-cancelled",!1);if(result.status==="spawn-error")throw new ScorerFailure("infrastructure_failure","scorer-spawn-failure",!0);if(result.exitCode!==0)throw new ScorerFailure("infrastructure_failure",`scorer-exit-${result.exitCode??"none"}`,!0);if(result.stdoutTruncated||result.stderrTruncated)throw new ScorerFailure("malformed","scorer-output-truncated",!1);let value;try{value=JSON.parse(result.stdout.trim())}catch{throw new ScorerFailure("malformed","scorer-invalid-json",!1)}let parsed=ScorerOutputSchema.safeParse(value);if(!parsed.success)throw new ScorerFailure("malformed","scorer-schema-invalid",!1);return parsed.data}async function runExecutorWithinBudget(args2){let startedAt=Date.now(),controller=new AbortController,timedOut=!1,parentAbort=()=>controller.abort();if(args2.parentSignal.addEventListener("abort",parentAbort,{once:!0}),args2.parentSignal.aborted)controller.abort();let timer=setTimeout(()=>{timedOut=!0,controller.abort()},args2.maxTimeMs);try{let aborted3=new Promise((resolve66)=>{let finish=()=>resolve66({status:timedOut?"timeout":"cancelled",text:"",durationMs:Date.now()-startedAt,cost:{source:"unavailable"},error:timedOut?"executor-task-timeout":"executor-cancelled"});if(controller.signal.addEventListener("abort",finish,{once:!0}),controller.signal.aborted)finish()});return await Promise.race([args2.options.executor({task:args2.task,candidate:args2.candidate,isolatedRoot:args2.isolatedRoot,instruction:args2.instruction,payload:args2.payload,seed:args2.seed,abortSignal:controller.signal,projectRoot:args2.options.projectRoot}),aborted3])}finally{clearTimeout(timer),args2.parentSignal.removeEventListener("abort",parentAbort),controller.abort()}}async function executePairMember(args2){let startedAt=Date.now(),seed=canonicalHash(`${args2.options.seed}:${args2.task.id}:${args2.candidate.id}:${args2.repetition}`);if(args2.signal.aborted)return failureResult({...args2,seed,outcome:"cancelled",durationMs:0,failureCode:"cancelled-before-execution"});if(args2.task.environment.kind==="container")return failureResult({...args2,seed,outcome:"unsupported",durationMs:0,failureCode:"container-runner-unavailable"});try{return await _internals125.withDisposableWorktree({projectRoot:args2.options.projectRoot,baseRef:args2.baseSha,abortSignal:args2.signal,run:async(worktree)=>{let isolatedRoot=path175.join(worktree.path,".swarm-evaluation-task");fs91.mkdirSync(isolatedRoot,{recursive:!0});try{fs91.cpSync(resolveContainedExistingPath(args2.inputRoot,args2.task.environment.path),isolatedRoot,{recursive:!0,errorOnExist:!1});let instruction=fs91.readFileSync(resolveContainedExistingPath(args2.inputRoot,args2.task.instructionPath),"utf8"),payload=fs91.readFileSync(resolveContainedExistingPath(args2.inputRoot,args2.candidate.payloadPath),"utf8"),remainingBeforeExecution=args2.options.budgets.maxTaskTimeMs-(Date.now()-startedAt);if(remainingBeforeExecution<=0)return failureResult({...args2,seed,outcome:"timeout",durationMs:Date.now()-startedAt,failureCode:"task-budget-exhausted-before-executor"});let execution=await runExecutorWithinBudget({options:args2.options,task:args2.task,candidate:args2.candidate,isolatedRoot,instruction,payload,seed,parentSignal:args2.signal,maxTimeMs:remainingBeforeExecution});if(execution.status!=="completed")return failureResult({...args2,seed,outcome:execution.status==="infrastructure_failure"?"infrastructure_failure":execution.status,durationMs:execution.durationMs,cost:execution.cost,failureCode:execution.error??`executor-${execution.status}`});if(Buffer.byteLength(execution.text,"utf8")>args2.options.budgets.maxOutputBytes)return failureResult({...args2,seed,outcome:"malformed",durationMs:Date.now()-startedAt,cost:execution.cost,failureCode:"executor-output-truncated"});let scored;try{let remainingBeforeScorer=args2.options.budgets.maxTaskTimeMs-(Date.now()-startedAt);if(remainingBeforeScorer<=0)throw new ScorerFailure("timeout","task-budget-exhausted-before-scorer",!1);scored=await scoreExecution({task:args2.task,candidate:args2.candidate,inputRoot:args2.inputRoot,isolatedRoot,execution,seed,maxOutputBytes:args2.options.budgets.maxOutputBytes,timeoutMs:remainingBeforeScorer,abortSignal:args2.signal})}catch(error93){let scorerFailure=error93 instanceof ScorerFailure?error93:void 0;return failureResult({...args2,seed,outcome:args2.signal.aborted?"cancelled":scorerFailure?.outcome??"malformed",durationMs:Date.now()-startedAt,cost:execution.cost,failureCode:scorerFailure?.failureCode??(error93 instanceof Error?error93.message.slice(0,160):"scorer-error")})}let[minimum,maximum]=args2.task.scorer.scoreRange;if(scored.score<minimum||scored.score>maximum)return failureResult({...args2,seed,outcome:"malformed",durationMs:Date.now()-startedAt,cost:scored.cost,failureCode:"score-out-of-range"});return{v:1,taskId:args2.task.id,category:args2.task.category,protected:args2.task.protected,repetition:args2.repetition,candidateId:args2.candidate.id,seed,outcome:"scored",score:scored.score,scoreRange:args2.task.scorer.scoreRange,cost:scored.cost,durationMs:Date.now()-startedAt,retries:0,metadata:scored.metadata}}finally{fs91.rmSync(isolatedRoot,{recursive:!0,force:!0})}}})}catch(error93){return failureResult({...args2,seed,outcome:"infrastructure_failure",durationMs:Date.now()-startedAt,failureCode:canonicalHash(String(error93)).slice(0,32)})}}async function executePairMemberWithRetries(args2){let result;for(let attempt=0;attempt<=args2.options.budgets.maxRetries;attempt++)if(result=await executePairMember(args2),result.retries=attempt,result.outcome!=="infrastructure_failure"||args2.signal.aborted)return result;return result}async function runEvaluation(options){let inputRoot=options.inputRoot??options.projectRoot,tasks=options.tasks.map((task)=>EvaluationTaskV1Schema.parse(task));if(tasks.length===0||tasks.length>options.budgets.maxTasks)throw Error("evaluation task count exceeds its declared budget");if(tasks.some((task)=>task.split!==options.split))throw Error("evaluation task split does not match the run split");let baseline=EvaluationCandidateV1Schema.parse(options.baseline),candidate=EvaluationCandidateV1Schema.parse(options.candidate);for(let item of[baseline,candidate])if(await computeCandidateInputContentHash(inputRoot,item)!==item.contentHash)throw Error(`candidate ${item.id} content hash is invalid`);let snapshotDraft={v:1,id:`taskset-${canonicalHash(tasks.map((task)=>task.id)).slice(0,20)}`,split:options.split,tasks,createdAt:new Date().toISOString()};for(let task of tasks)await admitEvaluationTask(options.projectRoot,task,inputRoot);let taskSet={...snapshotDraft,contentHash:computeTaskSetContentHash(snapshotDraft)},storedTaskSet=await saveTaskSetSnapshot(options.projectRoot,taskSet,inputRoot),runId=`eval-${canonicalHash({baseline:baseline.contentHash,candidate:candidate.contentHash,taskSet:storedTaskSet.contentHash,split:options.split,seed:options.seed,models:options.models,budgets:options.budgets}).slice(0,32)}`,existingRun=await readEvaluationRun(options.projectRoot,runId);if(existingRun)return existingRun;if(options.split==="test")await claimHeldOutTest(options.projectRoot,{v:1,runId,taskSetHash:storedTaskSet.contentHash,baselineHash:baseline.contentHash,candidateHash:candidate.contentHash,claimedAt:new Date().toISOString()});let before=await _internals125.captureWorkingTreeFingerprint(options.projectRoot),controller=new AbortController,externallyCancelled=options.abortSignal?.aborted??!1,timedOut=!1,budgetInconclusive=!1,scheduledSpendUsd=0,externalAbort=()=>{externallyCancelled=!0,controller.abort()};if(options.abortSignal?.addEventListener("abort",externalAbort,{once:!0}),externallyCancelled)controller.abort();let totalExecutions=tasks.length*2*options.budgets.maxRepetitions,executionWaves=Math.ceil(totalExecutions/options.budgets.maxConcurrency),totalTimeoutMs=Math.min(2147483647,options.budgets.maxTaskTimeMs*executionWaves*(options.budgets.maxRetries+1)+1000),timeout=setTimeout(()=>{timedOut=!0,controller.abort()},totalTimeoutMs);try{let limit=pLimit(options.budgets.maxConcurrency),jobs=[];for(let task of tasks)for(let item of[baseline,candidate])for(let repetition=0;repetition<options.budgets.maxRepetitions;repetition++)jobs.push(limit(()=>executePairMemberWithRetries({options,inputRoot,task,candidate:item,repetition,signal:controller.signal,baseSha:before.head}).then((result)=>{if(options.budgets.maxSpendUsd!==void 0){if(result.cost.source==="unavailable")budgetInconclusive=!0,controller.abort();else if(scheduledSpendUsd+=result.cost.usd??0,scheduledSpendUsd>options.budgets.maxSpendUsd)budgetInconclusive=!0,controller.abort()}return result})));let results=await Promise.all(jobs);for(let task of tasks)if(await computeTaskInputContentHash(inputRoot,task)!==task.contentHash)throw Error(`task ${task.id} changed during evaluation`);for(let item of[baseline,candidate])if(await computeCandidateInputContentHash(inputRoot,item)!==item.contentHash)throw Error(`candidate ${item.id} changed during evaluation`);let cost=aggregateCost(results),spendUnknown=options.budgets.maxSpendUsd!==void 0&&cost.source==="unavailable",overSpend=options.budgets.maxSpendUsd!==void 0&&cost.source!=="unavailable"&&(cost.usd??0)>options.budgets.maxSpendUsd,incomplete=results.some((result)=>result.outcome!=="scored"),runDraft={v:1,runId,createdAt:new Date().toISOString(),status:externallyCancelled||timedOut?"cancelled":incomplete||spendUnknown||overSpend||budgetInconclusive?"inconclusive":"complete",baseline,candidate,taskSet:{id:storedTaskSet.id,contentHash:storedTaskSet.contentHash,taskIds:tasks.map((task)=>task.id)},split:options.split,seed:options.seed,models:options.models,environment:{platform:process.platform,arch:process.arch,runtime:`node-${process.versions.node};bun-${process.versions.bun??"compat"}`,baseSha:before.head,activeTreeHash:canonicalHash(before),taskSetHash:storedTaskSet.contentHash},budgets:options.budgets,results,cost},run=EvaluationRunV1Schema.parse({...runDraft,integrityHash:computeRunIntegrityHash(runDraft)});return await saveEvaluationRun(options.projectRoot,run),run}finally{clearTimeout(timeout),options.abortSignal?.removeEventListener("abort",externalAbort);let after=await _internals125.captureWorkingTreeFingerprint(options.projectRoot);if(before.head!==after.head||before.porcelainHash!==after.porcelainHash)throw Error("evaluation changed the active working tree")}}function createModelEvaluationExecutor(dispatcher,parentSessionId){return async(args2)=>{let result=await dispatcher({sessionDirectory:args2.projectRoot,agentName:args2.candidate.agent??"reviewer",modelId:args2.candidate.model,system:args2.payload,prompt:["EVALUATION TASK:",args2.instruction,"",`Work ONLY in this directory: ${args2.isolatedRoot}`,"Return the task-required scorer payload exactly."].join(`
|
|
2083
2083
|
`),timeoutMs:args2.task.scorer.timeoutMs,parentSessionId,abortSignal:args2.abortSignal});return{status:result.status==="error"?"infrastructure_failure":result.status,text:result.text,durationMs:result.durationMs,cost:{source:"unavailable"},error:result.error}}}var ScorerOutputSchema,BuiltinVerdictSchema,ScorerFailure,_internals125;var init_runner=__esm(()=>{init_p_limit();init_zod();init_external_tool_runner();init_contracts();init_disposable_worktree();init_hashing();init_store();ScorerOutputSchema=exports_external.object({v:exports_external.literal(1),score:exports_external.number().finite(),cost:CostRecordSchema,metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}).strict(),BuiltinVerdictSchema=exports_external.object({v:exports_external.literal(1),caught:exports_external.boolean(),reason:exports_external.string().optional()}).strict();ScorerFailure=class ScorerFailure extends Error{outcome;failureCode;retryable;constructor(outcome,failureCode,retryable){super(failureCode);this.outcome=outcome;this.failureCode=failureCode;this.retryable=retryable;this.name="ScorerFailure"}};_internals125={captureWorkingTreeFingerprint,runExternalTool,withDisposableWorktree}});import*as fs92 from"node:fs/promises";import*as path176 from"node:path";function parseBaselineManifest(value){if(value===null||typeof value!=="object"||Array.isArray(value)||Object.keys(value).sort().join("\x00")!==["v","sourceSha","payloadPath","sha256"].sort().join("\x00"))throw Error("PR-review recovery baseline manifest is invalid");let manifest=value;if(manifest.v!==1||typeof manifest.sourceSha!=="string"||typeof manifest.payloadPath!=="string"||typeof manifest.sha256!=="string")throw Error("PR-review recovery baseline manifest is invalid");return manifest}async function candidate(packageRoot,input){return{...input,contentHash:await computeCandidateInputContentHash(packageRoot,input)}}async function task(packageRoot){let input={v:1,id:"pr-review-controller-recovery",source:"curated",split:"train",category:"pr-review-recovery",protected:!0,instructionPath:INSTRUCTION_PATH,environment:{kind:"fixture",path:ENVIRONMENT_PATH},scorer:{kind:"project",argv:[SCORER_PATH],timeoutMs:30000,scoreRange:[0,1]},provenance:{origin:"https://github.com/ZaxbyHub/opencode-swarm/issues/2075",license:"MIT"}};return{...input,contentHash:await computeTaskInputContentHash(packageRoot,input)}}async function verifyBaseline(packageRoot,requestedSourceSha){if(requestedSourceSha!==PR_REVIEW_RECOVERY_BASE_SHA)throw Error(`PR-review recovery baseline source SHA must be ${PR_REVIEW_RECOVERY_BASE_SHA}`);let manifest=parseBaselineManifest(JSON.parse(await fs92.readFile(path176.join(packageRoot,BASELINE_MANIFEST_PATH),"utf8")));if(manifest.sourceSha!==PR_REVIEW_RECOVERY_BASE_SHA||manifest.payloadPath!==BASELINE_PAYLOAD_PATH)throw Error("PR-review recovery baseline source SHA is invalid");let payload=await fs92.readFile(path176.join(packageRoot,manifest.payloadPath));if(sha256(payload)!==manifest.sha256)throw Error("PR-review recovery baseline payload hash is invalid")}async function evaluatePrReviewRecoveryV1(options){let packageRoot=path176.resolve(options.packageRoot??options.projectRoot);await verifyBaseline(packageRoot,options.baselineSourceSha??PR_REVIEW_RECOVERY_BASE_SHA);let model=options.model??"configured",baseline=await candidate(packageRoot,{v:1,id:"pr-review-recovery-baseline",kind:"baseline",payloadPath:BASELINE_PAYLOAD_PATH,model,agent:"reviewer"}),current=await candidate(packageRoot,{v:1,id:"pr-review-recovery-candidate",kind:"skill",payloadPath:CANDIDATE_PAYLOAD_PATH,model,agent:"reviewer"}),budgets={maxTasks:1,maxRepetitions:1,maxConcurrency:1,maxTaskTimeMs:60000,maxRetries:0,maxOutputBytes:32768,...options.budgets};return runEvaluation({projectRoot:options.projectRoot,inputRoot:packageRoot,tasks:[await task(packageRoot)],baseline,candidate:current,split:"train",seed:options.seed??"pr-review-recovery-v1",models:[model],budgets,executor:createModelEvaluationExecutor(options.dispatcher,options.parentSessionId),abortSignal:options.abortSignal})}var PR_REVIEW_RECOVERY_BASE_SHA="3811fe5981072c7fa541523e9f08430f18594590",FIXTURE_ROOT="evaluation-fixtures/pr-review-recovery",BASELINE_MANIFEST_PATH,BASELINE_PAYLOAD_PATH,CANDIDATE_PAYLOAD_PATH=".opencode/skills/swarm-pr-review/SKILL.md",INSTRUCTION_PATH,ENVIRONMENT_PATH,SCORER_PATH;var init_pr_review_recovery=__esm(()=>{init_hashing();init_runner();BASELINE_MANIFEST_PATH=`${FIXTURE_ROOT}/baseline-manifest.json`,BASELINE_PAYLOAD_PATH=`${FIXTURE_ROOT}/baseline/SKILL.md`,INSTRUCTION_PATH=`${FIXTURE_ROOT}/instruction.md`,ENVIRONMENT_PATH=`${FIXTURE_ROOT}/environment`,SCORER_PATH=`${ENVIRONMENT_PATH}/score-recovery.cjs`});function normalize16(result){if(result.outcome!=="scored"||result.score===void 0)return;let[minimum,maximum]=result.scoreRange;if(maximum<=minimum||result.score<minimum||result.score>maximum)return;return(result.score-minimum)/(maximum-minimum)}function resultKey(result){return`${result.taskId}\x00${result.repetition}`}function collectPairs(candidateResults,referenceResults){let references=new Map(referenceResults.map((result)=>[resultKey(result),result])),pairs=[];for(let candidateResult of candidateResults){let referenceResult=references.get(resultKey(candidateResult));if(!referenceResult)continue;let candidate2=normalize16(candidateResult),reference=normalize16(referenceResult);if(candidate2===void 0||reference===void 0)continue;pairs.push({key:resultKey(candidateResult),category:candidateResult.category,protected:candidateResult.protected||referenceResult.protected,reference,candidate:candidate2,referenceResult,candidateResult})}return pairs.sort((left,right)=>left.key.localeCompare(right.key))}function mean(values){return values.length===0?0:values.reduce((total,value)=>total+value,0)/values.length}function seededRandom(seedHash){let state=Number.parseInt(seedHash.slice(0,8),16)>>>0;return()=>{state+=1831565813;let value=state;return value=Math.imul(value^value>>>15,value|1),value^=value+Math.imul(value^value>>>7,value|61),((value^value>>>14)>>>0)/4294967296}}function percentile(sorted,probability){if(sorted.length===0)return 0;let position=(sorted.length-1)*probability,lower=Math.floor(position),upper=Math.ceil(position);if(lower===upper)return sorted[lower]??0;let fraction=position-lower;return(sorted[lower]??0)*(1-fraction)+(sorted[upper]??0)*fraction}function pairedBootstrapConfidenceInterval(deltas,seedHash,resamples=1e4){if(deltas.length===0)return[0,0];let random=seededRandom(seedHash),estimates=Array(resamples);for(let sample=0;sample<resamples;sample++){let total=0;for(let index=0;index<deltas.length;index++)total+=deltas[Math.floor(random()*deltas.length)]??0;estimates[sample]=total/deltas.length}return estimates.sort((left,right)=>left-right),[percentile(estimates,0.025),percentile(estimates,0.975)]}function availableCosts(pairs){return pairs.every((pair)=>pair.candidateResult.cost.source!=="unavailable"&&pair.referenceResult.cost.source!=="unavailable")}function makeComparison(pairs,scheduledPairs,referenceRunId,referenceCandidateId,seedHash){let deltas=pairs.map((pair)=>pair.candidate-pair.reference);return{baselineRunId:referenceRunId,baselineCandidateId:referenceCandidateId,baselineMean:mean(pairs.map((pair)=>pair.reference)),candidateMean:mean(pairs.map((pair)=>pair.candidate)),pairedDelta:mean(deltas),confidenceInterval:pairedBootstrapConfidenceInterval(deltas,seedHash),validPairs:pairs.length,missingPairs:Math.max(0,scheduledPairs-pairs.length),coverage:scheduledPairs===0?0:Math.min(1,pairs.length/scheduledPairs)}}function decidePromotion(input){let run=input.run,policy=PromotionPolicyV1Schema.parse({v:1,...input.policy??{}}),policyHash=canonicalHash(policy),seedHash=sha256(`${run.seed}${run.taskSet.contentHash}${run.baseline.contentHash}${run.candidate.contentHash}${policyHash}`),scheduledPairs=run.taskSet.taskIds.length*run.budgets.maxRepetitions,candidateResults=run.results.filter((result)=>result.candidateId===run.candidate.id),baselineResults=run.results.filter((result)=>result.candidateId===run.baseline.id),baselinePairs=collectPairs(candidateResults,baselineResults),historicalCompatible=input.historicalBest!==void 0&&input.historicalBest.taskSet.contentHash===run.taskSet.contentHash&&input.historicalBest.split===run.split,historicalResults=historicalCompatible?input.historicalBest?.results.filter((result)=>result.candidateId===input.historicalBest?.candidate.id):[],historicalPairs=collectPairs(candidateResults,historicalResults??[]),historicalSeed=sha256(`${seedHash}:historical-best`),baseline=makeComparison(baselinePairs,scheduledPairs,run.runId,run.baseline.id,seedHash),historicalBest=makeComparison(historicalPairs,scheduledPairs,input.historicalBest?.runId??"unavailable",input.historicalBest?.candidate.id??"unavailable",historicalSeed),categories=[...new Set(baselinePairs.map((pair)=>pair.category))].sort().map((category)=>{let pairs=baselinePairs.filter((pair)=>pair.category===category),categoryProtected=pairs.some((pair)=>pair.protected),tolerance=policy.protectedCategoryTolerances[category]??0,baselineMean=mean(pairs.map((pair)=>pair.reference)),candidateMean=mean(pairs.map((pair)=>pair.candidate)),pairedDelta=candidateMean-baselineMean;return{category,protected:categoryProtected,tolerance,baselineMean,candidateMean,pairedDelta,regression:categoryProtected&&pairedDelta<-tolerance}}),reasons=[],status="inconclusive";if(!historicalCompatible)reasons.push("historical_best_incompatible_or_missing");if(baseline.validPairs<policy.minValidPairs)reasons.push("baseline_insufficient_valid_pairs");if(historicalBest.validPairs<policy.minValidPairs)reasons.push("historical_best_insufficient_valid_pairs");if(baseline.coverage<policy.minCoverage)reasons.push("baseline_insufficient_coverage");if(historicalBest.coverage<policy.minCoverage)reasons.push("historical_best_insufficient_coverage");if(policy.requireAvailableCosts&&(!availableCosts(baselinePairs)||!availableCosts(historicalPairs)||run.cost.source==="unavailable"||input.historicalBest?.cost.source==="unavailable"))reasons.push("promotion_cost_unavailable");let evidenceSufficient=reasons.length===0,protectedRegressions=categories.filter((category)=>category.regression);for(let category of protectedRegressions)reasons.push(`protected_category_regression:${category.category}`);let baselineDecisiveRegression=baseline.confidenceInterval[1]<-policy.deadband,historicalDecisiveRegression=historicalBest.confidenceInterval[1]<-policy.deadband;if(evidenceSufficient&&(baselineDecisiveRegression||historicalDecisiveRegression)){if(status="reject",baselineDecisiveRegression)reasons.push("decisive_regression:baseline");if(historicalDecisiveRegression)reasons.push("decisive_regression:historical_best")}else if(evidenceSufficient&&protectedRegressions.length>0)status="reject";else if(evidenceSufficient&&baseline.confidenceInterval[0]>policy.deadband&&historicalBest.confidenceInterval[0]>policy.deadband)status="accept",reasons.push("improvement_exceeds_deadband_for_baseline_and_historical_best");else if(evidenceSufficient)reasons.push("confidence_interval_overlaps_deadband");let historicalRun=input.historicalBest,decisionCore={runId:run.runId,status,reasons,baseline,historicalBest,deadband:policy.deadband,bootstrap:{resamples:1e4,confidence:0.95,seedHash},categories,lineage:{baselineRunId:run.runId,historicalBestRunId:historicalRun?.runId??"unavailable",taskSetHash:run.taskSet.contentHash,baselineHash:run.baseline.contentHash,candidateHash:run.candidate.contentHash,historicalBestHash:historicalRun?.candidate.contentHash??"0".repeat(64)},policyHash,unavailableQualityMetrics:["complexity_delta","public_api_delta"]};return PromotionDecisionV1Schema.parse({v:1,decisionId:`promotion-${canonicalHash(decisionCore)}`,decidedAt:input.decidedAt??new Date().toISOString(),...decisionCore})}var init_statistics=__esm(()=>{init_contracts();init_hashing()});async function evaluateCandidateV1(options){let run=await runEvaluation(options),decision=decidePromotion({run,historicalBest:options.historicalBest,policy:options.policy,decidedAt:options.decidedAt}),storedDecision=await savePromotionDecision(options.projectRoot,decision);return{run,decision:storedDecision}}var evaluationV1;var init_public_api=__esm(()=>{init_gate_ground_truth();init_hashing();init_pr_review_recovery();init_runner();init_statistics();init_store();evaluationV1=Object.freeze(Object.assign((options)=>evaluateCandidateV1(options),{evaluateCandidate:evaluateCandidateV1,evaluatePrReviewRecovery:evaluatePrReviewRecoveryV1,runEvaluation,decidePromotion:(input)=>decidePromotion(input),hashTaskInput:computeTaskInputContentHash,hashCandidateInput:computeCandidateInputContentHash,recordTestImpactGroundTruth:recordTestImpactGateGroundTruth}))});function buildGeneratorInputs(args2){for(let ev of args2.eligibleEvidence){if(args2.claimedTestTaskIds.has(ev.id))throw Error(`LEAKAGE_DETECTED: evidence id ${ev.id} is a held-out task`);let phraseFields=[...ev.triggers,...ev.requiredActions,...ev.forbiddenActions];for(let id of args2.claimedTestTaskIds){let escaped=id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),re=new RegExp(`(^|[^A-Za-z0-9_-])${escaped}([^A-Za-z0-9_-]|$)`);for(let phrase of phraseFields)if(re.test(phrase))throw Error(`LEAKAGE_DETECTED: evidence ${ev.id} phrase references held-out task ${id}`)}}return{baselineContent:args2.baselineContent,eligibleEvidence:args2.eligibleEvidence,counterexamples:args2.counterexamples,budget:{maxChangedLines:args2.budget.max_changed_lines,maxChangedBytes:args2.budget.max_changed_bytes,maxChangedSections:args2.budget.max_changed_sections}}}function defaultDeterministicDraft(inputs){let baseline=inputs.baselineContent,evidenceLines=inputs.eligibleEvidence.slice(0,6).map((e)=>`- ${e.id} (confidence ${e.confidence.toFixed(2)}): triggers=${e.triggers.slice(0,3).join("; ")}`).join(`
|
|
2084
2084
|
`),counterexampleNote=inputs.counterexamples.length>0?`
|
|
2085
2085
|
|
|
@@ -5561,7 +5561,7 @@ ${instruction}`}async function sendWakePrompt(sessionID,events,messageID){let ac
|
|
|
5561
5561
|
`);case"pr.review.approved":return[`${dedupToken} (advisory) PR #${payload.prNumber} — Review: approved`,` Repository: ${payload.repoFullName}`,` URL: ${payload.prUrl||""}`,` Review state: ${payload.reviewDecision||"APPROVED"}`].join(`
|
|
5562
5562
|
`);case"pr.merged":return[`${dedupToken} (advisory) PR #${payload.prNumber} — PR merged (TERMINAL)`,` Repository: ${payload.repoFullName}`,` URL: ${payload.prUrl||""}`," Monitoring ends: report final status and stop — the subscription is complete."].join(`
|
|
5563
5563
|
`);case"pr.closed":return[`${dedupToken} (advisory) PR #${payload.prNumber} — PR closed without merge (TERMINAL)`,` Repository: ${payload.repoFullName}`,` URL: ${payload.prUrl||""}`," Monitoring ends: report final status and stop — the subscription is complete."].join(`
|
|
5564
|
-
`);default:return null}}var CLEAR_UNADDRESSED_DELAY_MS=2000,MAX_PENDING_CLEARS=200,pendingClears,_internals136,AUTO_PR_FEEDBACK_EVENTS,EVENT_CONFIG_MAP,CONTENT_EVENT_TYPES;var init_pr_event_subscribers=__esm(()=>{init_pr_workflow_gate();init_state2();init_utils();init_event_bus();init_pr_event_delivery();init_pr_feedback_event_queue();init_pr_subscriptions();pendingClears=new Map,_internals136={handlePrEvent,getGlobalEventBus,listActive,updateSnapshot,getAgentSession,readPrWorkflowGateState,activatePrWorkflow,enqueuePrFeedbackMonitorEvent,deliverPrActivity,isPrEventDeliveryRegistered,scheduleClearUnaddressed,clearUnaddressedDelayMs:CLEAR_UNADDRESSED_DELAY_MS,log,formatAdvisory},AUTO_PR_FEEDBACK_EVENTS=new Set(["pr.ci.failed","pr.merge.conflict"]),EVENT_CONFIG_MAP={"pr.ci.failed":"notify_ci_failure","pr.ci.passed":"notify_ci_success","pr.new.comment":"notify_new_comments","pr.merge.conflict":"notify_merge_conflict","pr.merge.conflict_resolved":"notify_merge_conflict","pr.review.changes_requested":"notify_review_activity","pr.review.approved":"notify_review_activity","pr.merged":"notify_merged","pr.closed":"notify_closed"};CONTENT_EVENT_TYPES=new Set(["pr.new.comment","pr.review.changes_requested","pr.review.approved","pr.review.comment"])});var exports_status_artifact={};__export(exports_status_artifact,{AutomationStatusArtifact:()=>AutomationStatusArtifact});import*as fs97 from"node:fs";import*as path194 from"node:path";function createEmptySnapshot(mode,capabilities){return{timestamp:Date.now(),mode,enabled:mode!=="manual",currentPhase:0,lastTrigger:null,pendingActions:0,lastOutcome:null,capabilities}}function validateFilename(filename){if(filename.includes("\x00"))throw Error("Invalid filename: contains null byte");let pathSeparators=["/","\\",".."];for(let sep30 of pathSeparators)if(filename.includes(sep30))throw Error(`Invalid filename: contains path separator '${sep30}'`);if(filename.startsWith("/")||filename.startsWith("\\")||/^[a-zA-Z]:/.test(filename))throw Error("Invalid filename: absolute paths not allowed");if(filename.length>MAX_FILENAME_LENGTH)throw Error(`Invalid filename: exceeds maximum length of ${MAX_FILENAME_LENGTH} characters`);if(!SAFE_FILENAME_PATTERN.test(filename))throw Error("Invalid filename: contains unsafe characters");if(filename.includes("/")||filename.includes("\\"))throw Error("Invalid filename: path separators not allowed");if(!filename.trim()||filename.trim()!==filename)throw Error("Invalid filename: cannot be empty or contain leading/trailing whitespace");return filename}class AutomationStatusArtifact{swarmDir;filename;currentSnapshot;constructor(swarmDir,filename="automation-status.json"){let sanitizedFilename=validateFilename(filename);this.swarmDir=swarmDir,this.filename=sanitizedFilename,this.currentSnapshot=this.load()??createEmptySnapshot("manual",{plan_sync:!1,phase_preflight:!1,config_doctor_on_startup:!1,config_doctor_autofix:!1,evidence_auto_summaries:!1,decision_drift_detection:!1})}getFilePath(){return path194.join(this.swarmDir,this.filename)}load(){let filePath=this.getFilePath();try{if(fs97.existsSync(filePath)){let content=fs97.readFileSync(filePath,"utf-8");return JSON.parse(content)}}catch{}return null}write(){let filePath=this.getFilePath();if(!fs97.existsSync(this.swarmDir))fs97.mkdirSync(this.swarmDir,{recursive:!0});fs97.writeFileSync(filePath,JSON.stringify(this.currentSnapshot,null,2),"utf-8")}getSnapshot(){return{...this.currentSnapshot}}read(){let loaded=this.load();if(loaded)this.currentSnapshot=loaded;return this.getSnapshot()}updateConfig(mode,capabilities){this.currentSnapshot={...this.currentSnapshot,mode,enabled:mode!=="manual",timestamp:Date.now(),capabilities},this.write()}updatePhase(phase){this.currentSnapshot={...this.currentSnapshot,currentPhase:phase,timestamp:Date.now()},this.write()}recordTrigger(triggeredAt,triggeredPhase,source,reason){this.currentSnapshot={...this.currentSnapshot,lastTrigger:{triggeredAt,triggeredPhase,source,reason},timestamp:Date.now()},this.write()}updatePendingActions(count){this.currentSnapshot={...this.currentSnapshot,pendingActions:count,timestamp:Date.now()},this.write()}recordOutcome(state,phase,message){this.currentSnapshot={...this.currentSnapshot,lastOutcome:{state,phase,outcomeAt:Date.now(),message:message??null},timestamp:Date.now()},this.write()}clearOutcome(){this.currentSnapshot={...this.currentSnapshot,lastOutcome:{state:"none",phase:null,outcomeAt:null,message:null},timestamp:Date.now()},this.write()}isEnabled(){return this.currentSnapshot.enabled}hasCapability(capability){return this.currentSnapshot.capabilities[capability]===!0}getGuiSummary(){let{currentSnapshot}=this,status="Disabled";if(currentSnapshot.enabled)status=currentSnapshot.mode.charAt(0).toUpperCase()+currentSnapshot.mode.slice(1);let lastTrigger=null;if(currentSnapshot.lastTrigger?.triggeredAt)lastTrigger=new Date(currentSnapshot.lastTrigger.triggeredAt).toLocaleTimeString();let outcome=null;if(currentSnapshot.lastOutcome?.state&¤tSnapshot.lastOutcome.state!=="none")outcome=currentSnapshot.lastOutcome.state;return{status,phase:currentSnapshot.currentPhase,lastTrigger,pending:currentSnapshot.pendingActions,outcome}}}var MAX_FILENAME_LENGTH=255,SAFE_FILENAME_PATTERN;var init_status_artifact=__esm(()=>{SAFE_FILENAME_PATTERN=/^[a-zA-Z0-9._-]+$/});var exports_trigger={};__export(exports_trigger,{PreflightTriggerManager:()=>PreflightTriggerManager,PhaseBoundaryTrigger:()=>PhaseBoundaryTrigger});class PhaseBoundaryTrigger{eventBus;config;lastKnownPhase=0;lastTriggeredPhase=0;constructor(eventBus,config3){this.eventBus=eventBus??getGlobalEventBus(),this.config={minCompletedTasksThreshold:config3?.minCompletedTasksThreshold??1,allowZeroTaskTrigger:config3?.allowZeroTaskTrigger??!1}}setCurrentPhase(phase){this.lastKnownPhase=phase}getCurrentPhase(){return this.lastKnownPhase}get lastTriggeredPhaseValue(){return this.lastTriggeredPhase}detectBoundary(newPhase,completedTasks,totalTasks){if(newPhase===this.lastKnownPhase)return{detected:!1,previousPhase:this.lastKnownPhase,currentPhase:newPhase,reason:"Phase unchanged",completedTaskCount:completedTasks,totalTaskCount:totalTasks};let boundaryResult={detected:!0,previousPhase:this.lastKnownPhase,currentPhase:newPhase,reason:`Phase transition from ${this.lastKnownPhase} to ${newPhase}`,completedTaskCount:completedTasks,totalTaskCount:totalTasks};return this.lastKnownPhase=newPhase,this.eventBus.publish("phase.boundary.detected",boundaryResult),boundaryResult}shouldTriggerPreflight(boundaryResult){if(this.lastTriggeredPhase===boundaryResult.currentPhase)return log("[Trigger] Preflight already triggered for phase",{phase:boundaryResult.currentPhase}),!1;let threshold=this.config.minCompletedTasksThreshold??1;if(!(this.config.allowZeroTaskTrigger||boundaryResult.completedTaskCount>=threshold))return log("[Trigger] Preflight skipped - insufficient task completion",{completed:boundaryResult.completedTaskCount,required:threshold}),!1;return!0}markTriggered(phase){this.lastTriggeredPhase=phase}reset(){this.lastKnownPhase=0,this.lastTriggeredPhase=0}}class PreflightTriggerManager{automationConfig;eventBus;trigger;requestQueue;requestCounter=0;preflightHandler=null;unsubscribe=null;unsubscribeSkipped=null;constructor(automationConfig,eventBus,triggerConfig){this.automationConfig=automationConfig,this.eventBus=eventBus??getGlobalEventBus(),this.trigger=new PhaseBoundaryTrigger(this.eventBus,triggerConfig),this.requestQueue=new AutomationQueue({maxSize:100,defaultMaxRetries:3,overflowStrategy:"evict-oldest"}),this.unsubscribeSkipped=this.eventBus.subscribe("preflight.skipped",(event)=>{let payload=event.payload;if(payload.reason==="queue_overflow"||payload.reason==="queue_enqueue_error")criticalWarn("[PreflightTrigger] preflight skipped",{reason:payload.reason,phase:payload.phase,requestId:payload.requestId,queueDepth:this.requestQueue.size()})})}isEnabled(){if(!this.automationConfig)return!1;if(!this.automationConfig.capabilities)return!1;if(this.automationConfig.mode==="manual")return!1;return this.automationConfig.capabilities.phase_preflight===!0}getMode(){if(!this.automationConfig)return"unknown";return this.automationConfig.mode??"unknown"}updatePhase(phase){this.trigger.setCurrentPhase(phase)}async checkAndTrigger(currentPhase,completedTasks,totalTasks){let phasePreflight=this.automationConfig?.capabilities?.phase_preflight,mode=this.automationConfig?.mode;if(!this.isEnabled())return log("[PreflightTrigger] Disabled via feature flags",{mode:mode??"unknown",phase_preflight:phasePreflight}),await this.eventBus.publish("preflight.skipped",{reason:"feature_disabled",mode:mode??"unknown",phase_preflight:phasePreflight}),!1;let boundaryResult=this.trigger.detectBoundary(currentPhase,completedTasks,totalTasks);if(!boundaryResult.detected)return!1;if(!this.trigger.shouldTriggerPreflight(boundaryResult))return await this.eventBus.publish("preflight.skipped",{reason:"threshold_not_met",boundary:boundaryResult}),!1;return this.triggerPreflight(boundaryResult)}async triggerPreflight(boundaryResult){let requestId=`preflight-${Date.now()}-${++this.requestCounter}`,request={id:requestId,triggeredAt:Date.now(),currentPhase:boundaryResult.currentPhase,source:"phase_boundary",reason:boundaryResult.reason,metadata:{completedTaskCount:boundaryResult.completedTaskCount,totalTaskCount:boundaryResult.totalTaskCount}};try{this.requestQueue.enqueue(request,"high")}catch(error93){log("[PreflightTrigger] Queue enqueue failed (continuing)",{requestId,phase:boundaryResult.currentPhase,error:error93 instanceof Error?error93.message:String(error93)}),await this.eventBus.publish("preflight.skipped",{reason:"queue_enqueue_error",requestId,phase:boundaryResult.currentPhase})}return this.trigger.markTriggered(boundaryResult.currentPhase),await this.eventBus.publish("preflight.requested",request),await this.eventBus.publish("preflight.triggered",{requestId,phase:boundaryResult.currentPhase,timestamp:request.triggeredAt}),log("[PreflightTrigger] Preflight triggered",{requestId,phase:boundaryResult.currentPhase,completed:boundaryResult.completedTaskCount,total:boundaryResult.totalTaskCount}),!0}getPendingRequests(){return this.requestQueue.getAll().map((item)=>item.payload)}getQueueSize(){return this.requestQueue.size()}getStats(){let mode="unknown";try{mode=this.getMode()}catch{mode="unknown"}return{enabled:this.isEnabled(),mode,currentPhase:this.trigger.getCurrentPhase(),lastTriggeredPhase:this.trigger.lastTriggeredPhaseValue,pendingRequests:this.getQueueSize()}}reset(){if(this.trigger.reset(),this.requestQueue.clear(),this.unsubscribe)this.unsubscribe(),this.unsubscribe=null;if(this.unsubscribeSkipped)this.unsubscribeSkipped(),this.unsubscribeSkipped=null}registerHandler(handler){if(this.unsubscribe)this.unsubscribe();this.preflightHandler=handler;let HANDLER_TIMEOUT_MS=120000;this.unsubscribe=this.eventBus.subscribe("preflight.requested",async(event)=>{let request=event.payload,timeoutHandle;try{if(this.preflightHandler)await Promise.race([this.preflightHandler(request),new Promise((_,reject)=>{timeoutHandle=setTimeout(()=>{reject(Error(`Preflight handler timed out after ${HANDLER_TIMEOUT_MS}ms`))},HANDLER_TIMEOUT_MS)})])}catch(error93){log("[PreflightTrigger] Handler error",{requestId:request.id,phase:request.currentPhase,errorType:error93 instanceof Error?error93.name:"unknown"})}finally{clearTimeout(timeoutHandle);let match=this.requestQueue.getAll().find((it)=>it.payload.id===request.id);if(match)this.requestQueue.complete(match.id)}}),log("[PreflightTrigger] Handler registered")}unregisterHandler(){if(this.unsubscribe)this.unsubscribe(),this.unsubscribe=null;this.preflightHandler=null,log("[PreflightTrigger] Handler unregistered")}hasHandler(){return this.preflightHandler!==null}}var init_trigger=__esm(()=>{init_utils();init_event_bus();init_queue()});function truncateWords(text,maxWords){let trimmed=text.trim();if(trimmed.length===0)return{text:trimmed,truncated:!1};let words=trimmed.split(/\s+/);if(words.length<=maxWords)return{text:trimmed,truncated:!1};return{text:`${words.slice(0,maxWords).join(" ")}…`,truncated:!0}}function capArray(items,maxItems){if(items.length<=maxItems)return{items,truncated:!1};return{items:items.slice(0,maxItems),truncated:!0}}function normalizeAgentWorkSummary(input,maxSummaryWords=MAX_AGENT_SUMMARY_WORDS){let truncated=!1,sum=truncateWords(input.summary,maxSummaryWords);truncated||=sum.truncated;let cap=(items)=>{let r=capArray(items??[],MAX_LIST_ITEMS);return truncated||=r.truncated,r.items},candidate2={schema_version:SUMMARY_SCHEMA_VERSION,phase:input.phase,task_id:input.task_id,session_id:input.session_id,agent:input.agent,parent_agent:input.parent_agent,summary:sum.text,key_decisions:cap(input.key_decisions),constraints_observed:cap(input.constraints_observed),constraints_violated:cap(input.constraints_violated),assumptions:cap(input.assumptions),risks:cap(input.risks),files_touched:input.files_touched?capArray(input.files_touched,50).items:void 0,evidence_refs:capArray(input.evidence_refs??[],20).items,created_at:input.created_at??new Date().toISOString(),truncated:truncated||void 0};return AgentWorkSummarySchema.parse(candidate2)}var SUMMARY_SCHEMA_VERSION="1.0.0",MAX_AGENT_SUMMARY_WORDS=100,MAX_PHASE_SUMMARY_WORDS=250,MAX_LIST_ITEMS=5,SupervisorVerdictSchema,AgentWorkSummarySchema,PhaseArchitectureSummarySchema,SupervisorFindingSchema,KnowledgeRecommendationSchema,EvidenceProvenanceSchema,ArchitectureSupervisorReportSchema;var init_schema3=__esm(()=>{init_zod();SupervisorVerdictSchema=exports_external.enum(["APPROVE","CONCERNS","REJECT"]);AgentWorkSummarySchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),task_id:exports_external.string().min(1).optional(),session_id:exports_external.string().min(1),agent:exports_external.string().min(1),parent_agent:exports_external.string().min(1).optional(),summary:exports_external.string().min(1),key_decisions:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),constraints_observed:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),constraints_violated:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),assumptions:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),risks:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),files_touched:exports_external.array(exports_external.string().min(1)).max(50).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).max(20).default([]),created_at:exports_external.string().datetime(),truncated:exports_external.boolean().optional()});PhaseArchitectureSummarySchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),summary:exports_external.string().default(""),agents_seen:exports_external.array(exports_external.string().min(1)).default([]),tasks_seen:exports_external.array(exports_external.string().min(1)).default([]),key_decisions:exports_external.array(exports_external.string().min(1)).default([]),conflicts:exports_external.array(exports_external.string().min(1)).default([]),unresolved_risks:exports_external.array(exports_external.string().min(1)).default([]),constraint_violations:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),created_at:exports_external.string().datetime()}),SupervisorFindingSchema=exports_external.object({severity:exports_external.enum(["low","medium","high","critical"]),category:exports_external.string().min(1),agents:exports_external.array(exports_external.string().min(1)).default([]),tasks:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),description:exports_external.string().min(1),recommendation:exports_external.string().default("")}),KnowledgeRecommendationSchema=exports_external.object({lesson:exports_external.string().min(1),target_agents:exports_external.array(exports_external.string().min(1)).default([]),confidence:exports_external.number().min(0).max(1).default(0.5),evidence_refs:exports_external.array(exports_external.string().min(1)).default([])}),EvidenceProvenanceSchema=exports_external.object({agent_name:exports_external.string().min(1).optional(),session_id:exports_external.string().min(1).optional(),captured_at:exports_external.string().datetime().optional()}),ArchitectureSupervisorReportSchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),verdict:SupervisorVerdictSchema,findings:exports_external.array(SupervisorFindingSchema).default([]),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema).default([]),created_at:exports_external.string().datetime(),provenance:EvidenceProvenanceSchema.optional()})});import{existsSync as existsSync103,mkdirSync as mkdirSync60,readFileSync as readFileSync82,renameSync as renameSync35,unlinkSync as unlinkSync34,writeFileSync as writeFileSync40}from"node:fs";import*as path205 from"node:path";function writeRawSidecar(absPath,bundle){mkdirSync60(path205.dirname(absPath),{recursive:!0});let tempFile=`${absPath}.tmp-${Date.now()}-${process.pid}`;try{writeFileSync40(tempFile,JSON.stringify(bundle,null,2),"utf-8"),renameSync35(tempFile,absPath)}finally{if(existsSync103(tempFile))try{unlinkSync34(tempFile)}catch{}}}async function writeAgentSummary(directory,summary){let taskId=summary.task_id??`phase-${summary.phase}-summaries`;return await saveEvidence(directory,taskId,{task_id:taskId,type:"note",timestamp:summary.created_at,agent:summary.agent,verdict:"info",summary:summary.summary,metadata:{kind:AGENT_SUMMARY_METADATA_KIND,phase:summary.phase,session_id:summary.session_id,payload:summary}}),taskId}async function listAgentSummaries(directory,filter={}){let taskIds=await listEvidenceTaskIds(directory),results=[];for(let taskId of taskIds){let loaded=await loadEvidence(directory,taskId);if(loaded.status!=="found")continue;for(let entry of loaded.bundle.entries){if(entry.type!=="note")continue;let meta3=entry.metadata;if(!meta3||meta3.kind!==AGENT_SUMMARY_METADATA_KIND)continue;if(filter.phase!==void 0&&meta3.phase!==filter.phase)continue;if(filter.session!==void 0&&meta3.session_id!==filter.session)continue;let parsed=AgentWorkSummarySchema.safeParse(meta3.payload);if(!parsed.success){warn(`Skipping malformed agent summary in task ${taskId}: ${parsed.error.issues.map((i)=>i.message).join(", ")}`);continue}results.push(parsed.data)}}return results}function writePhaseArchitectureSummary(directory,summary){let rel=path205.join("evidence",String(summary.phase),PHASE_SUMMARY_FILE),abs=validateSwarmPath(directory,rel);return writeRawSidecar(abs,summary),abs}function writeSupervisorReport(directory,report){let rel=path205.join("evidence",String(report.phase),SUPERVISOR_REPORT_FILE),abs=validateSwarmPath(directory,rel),bundle={entries:[{type:SUPERVISOR_ENTRY_TYPE,phase_number:report.phase,scope:"phase",timestamp:report.created_at,verdict:report.verdict,findings:report.findings,knowledge_recommendations:report.knowledge_recommendations,...report.provenance?{provenance:report.provenance}:{}}]};return writeRawSidecar(abs,bundle),abs}function readSupervisorReportRaw(directory,phase){let rel=path205.join("evidence",String(phase),SUPERVISOR_REPORT_FILE),abs;try{abs=validateSwarmPath(directory,rel)}catch{return null}if(!existsSync103(abs))return null;try{return JSON.parse(readFileSync82(abs,"utf-8")).entries?.find((e)=>e.type===SUPERVISOR_ENTRY_TYPE)??null}catch{return null}}var AGENT_SUMMARY_METADATA_KIND="agent_summary",PHASE_SUMMARY_FILE="phase-architecture-summary.json",SUPERVISOR_REPORT_FILE="architecture-supervisor.json",SUPERVISOR_ENTRY_TYPE="architecture-supervisor";var init_store4=__esm(()=>{init_manager2();init_utils2();init_utils();init_schema3()});var exports_aggregate={};__export(exports_aggregate,{aggregatePhaseSummary:()=>aggregatePhaseSummary});function dedupe2(values){return Array.from(new Set(values)).filter((v)=>v.trim().length>0)}function detectConflicts(summaries){let observedBy=new Map,violatedBy=new Map;for(let s of summaries){for(let c of s.constraints_observed){if(!observedBy.has(c))observedBy.set(c,new Set);observedBy.get(c)?.add(s.agent)}for(let c of s.constraints_violated){if(!violatedBy.has(c))violatedBy.set(c,new Set);violatedBy.get(c)?.add(s.agent)}}let conflicts=[];for(let[constraint,violators]of violatedBy){let observers=observedBy.get(constraint);if(observers&&observers.size>0){let obs=Array.from(observers).sort().join(", "),vio=Array.from(violators).sort().join(", ");conflicts.push(`Constraint "${constraint}" observed by [${obs}] but violated by [${vio}]`)}}return conflicts.sort()}async function aggregatePhaseSummary(directory,phase,options={}){let summaries=await listAgentSummaries(directory,{phase});if(summaries.length===0)return null;let agentsSeen=dedupe2(summaries.map((s)=>s.agent)).sort(),tasksSeen=dedupe2(summaries.map((s)=>s.task_id).filter((t)=>Boolean(t))).sort(),keyDecisions=dedupe2(summaries.flatMap((s)=>s.key_decisions)),unresolvedRisks=dedupe2(summaries.flatMap((s)=>s.risks)),constraintViolations=dedupe2(summaries.flatMap((s)=>s.constraints_violated)),evidenceRefs=dedupe2(summaries.flatMap((s)=>s.evidence_refs)),conflicts=detectConflicts(summaries),headline=`Phase ${phase}: ${summaries.length} agent summary(ies) across ${tasksSeen.length} task(s); ${constraintViolations.length} constraint violation(s), ${conflicts.length} cross-agent conflict(s).`,cap=options.maxPhaseSummaryWords??MAX_PHASE_SUMMARY_WORDS,summaryText=truncateWords(headline,cap).text,phaseSummary={schema_version:SUMMARY_SCHEMA_VERSION,phase,summary:summaryText,agents_seen:agentsSeen,tasks_seen:tasksSeen,key_decisions:keyDecisions,conflicts,unresolved_risks:unresolvedRisks,constraint_violations:constraintViolations,evidence_refs:evidenceRefs,created_at:options.now?.()??new Date().toISOString()};return writePhaseArchitectureSummary(directory,phaseSummary),phaseSummary}var init_aggregate=__esm(()=>{init_schema3();init_store4()});var exports_preflight_integration={};__export(exports_preflight_integration,{runManualPreflight:()=>runManualPreflight,createPreflightIntegration:()=>createPreflightIntegration});function createPreflightIntegration(config3){let{automationConfig,directory,swarmDir,preflightConfig,updateStatusArtifact=!0}=config3;if(automationConfig?.capabilities?.phase_preflight!==!0)throw Error("Preflight is not enabled in automation capabilities. Set automation.capabilities.phase_preflight to true.");let manager=new PreflightTriggerManager(automationConfig,void 0,{directory}),statusArtifact=null;if(updateStatusArtifact&&swarmDir)statusArtifact=new AutomationStatusArtifact(swarmDir);let preflightHandler=async(request)=>{log("[PreflightIntegration] Handling preflight request",{requestId:request.id,phase:request.currentPhase,source:request.source});let report=await runPreflight(directory,request.currentPhase,preflightConfig);if(statusArtifact){let state=report.overall==="pass"?"success":"failure";statusArtifact.recordOutcome(state,request.currentPhase,report.message),log("[PreflightIntegration] Status artifact updated",{state,phase:request.currentPhase,message:report.message})}log("[PreflightIntegration] Preflight complete",{requestId:request.id,overall:report.overall,message:report.message,durationMs:report.totalDurationMs})};return manager.registerHandler(preflightHandler),{manager,cleanup:()=>{manager.unregisterHandler()}}}async function runManualPreflight(directory,phase,config3){return runPreflight(directory,phase,config3)}var init_preflight_integration=__esm(()=>{init_status_artifact();init_trigger();init_preflight_service();init_logger()});var exports_doc_scan={};__export(exports_doc_scan,{scanDocIndex:()=>scanDocIndex,extractDocConstraints:()=>extractDocConstraints,doc_scan:()=>doc_scan,doc_extract:()=>doc_extract});import*as crypto15 from"node:crypto";import*as fs115 from"node:fs";import{mkdir as mkdir41,readdir as readdir13,readFile as readFile44,realpath as realpath8,stat as stat17,writeFile as writeFile27}from"node:fs/promises";import*as path221 from"node:path";function normalizeSeparators(filePath){return filePath.replace(/\\/g,"/")}function matchesDocPattern(filePath,patterns){let normalizedPath2=normalizeSeparators(filePath),basename28=path221.basename(filePath);for(let pattern of patterns){if(!pattern.includes("/")&&!pattern.includes("\\")){if(basename28===pattern)return!0;continue}if(pattern.startsWith("**/")){let filenamePattern=pattern.slice(3);if(basename28===filenamePattern)return!0;continue}let dirPrefix=normalizeSeparators(pattern).replace(/\/\*\*.*$/,"").replace(/\/\*.*$/,"");if(normalizedPath2.startsWith(`${dirPrefix}/`)||normalizedPath2===dirPrefix)return!0}return!1}function extractTitleAndSummary(content,filename){let lines=content.split(`
|
|
5564
|
+
`);default:return null}}var CLEAR_UNADDRESSED_DELAY_MS=2000,MAX_PENDING_CLEARS=200,pendingClears,_internals136,AUTO_PR_FEEDBACK_EVENTS,EVENT_CONFIG_MAP,CONTENT_EVENT_TYPES;var init_pr_event_subscribers=__esm(()=>{init_pr_workflow_gate();init_state2();init_utils();init_event_bus();init_pr_event_delivery();init_pr_feedback_event_queue();init_pr_subscriptions();pendingClears=new Map,_internals136={handlePrEvent,getGlobalEventBus,listActive,updateSnapshot,getAgentSession,readPrWorkflowGateState,activatePrWorkflow,enqueuePrFeedbackMonitorEvent,deliverPrActivity,isPrEventDeliveryRegistered,scheduleClearUnaddressed,clearUnaddressedDelayMs:CLEAR_UNADDRESSED_DELAY_MS,log,formatAdvisory},AUTO_PR_FEEDBACK_EVENTS=new Set(["pr.ci.failed","pr.merge.conflict"]),EVENT_CONFIG_MAP={"pr.ci.failed":"notify_ci_failure","pr.ci.passed":"notify_ci_success","pr.new.comment":"notify_new_comments","pr.merge.conflict":"notify_merge_conflict","pr.merge.conflict_resolved":"notify_merge_conflict","pr.review.changes_requested":"notify_review_activity","pr.review.approved":"notify_review_activity","pr.merged":"notify_merged","pr.closed":"notify_closed"};CONTENT_EVENT_TYPES=new Set(["pr.new.comment","pr.review.changes_requested","pr.review.approved","pr.review.comment"])});var exports_status_artifact={};__export(exports_status_artifact,{AutomationStatusArtifact:()=>AutomationStatusArtifact});import*as fs97 from"node:fs";import*as path194 from"node:path";function createEmptySnapshot(mode,capabilities){return{timestamp:Date.now(),mode,enabled:mode!=="manual",currentPhase:0,lastTrigger:null,pendingActions:0,lastOutcome:null,capabilities}}function validateFilename(filename){if(filename.includes("\x00"))throw Error("Invalid filename: contains null byte");let pathSeparators=["/","\\",".."];for(let sep30 of pathSeparators)if(filename.includes(sep30))throw Error(`Invalid filename: contains path separator '${sep30}'`);if(filename.startsWith("/")||filename.startsWith("\\")||/^[a-zA-Z]:/.test(filename))throw Error("Invalid filename: absolute paths not allowed");if(filename.length>MAX_FILENAME_LENGTH)throw Error(`Invalid filename: exceeds maximum length of ${MAX_FILENAME_LENGTH} characters`);if(!SAFE_FILENAME_PATTERN.test(filename))throw Error("Invalid filename: contains unsafe characters");if(filename.includes("/")||filename.includes("\\"))throw Error("Invalid filename: path separators not allowed");if(!filename.trim()||filename.trim()!==filename)throw Error("Invalid filename: cannot be empty or contain leading/trailing whitespace");return filename}class AutomationStatusArtifact{swarmDir;filename;currentSnapshot;constructor(swarmDir,filename="automation-status.json"){let sanitizedFilename=validateFilename(filename);this.swarmDir=swarmDir,this.filename=sanitizedFilename,this.currentSnapshot=this.load()??createEmptySnapshot("manual",{plan_sync:!1,phase_preflight:!1,config_doctor_on_startup:!1,config_doctor_autofix:!1,evidence_auto_summaries:!1,decision_drift_detection:!1})}getFilePath(){return path194.join(this.swarmDir,this.filename)}load(){let filePath=this.getFilePath();try{if(fs97.existsSync(filePath)){let content=fs97.readFileSync(filePath,"utf-8");return JSON.parse(content)}}catch{}return null}write(){let filePath=this.getFilePath();if(!fs97.existsSync(this.swarmDir))fs97.mkdirSync(this.swarmDir,{recursive:!0});fs97.writeFileSync(filePath,JSON.stringify(this.currentSnapshot,null,2),"utf-8")}getSnapshot(){return{...this.currentSnapshot}}read(){let loaded=this.load();if(loaded)this.currentSnapshot=loaded;return this.getSnapshot()}updateConfig(mode,capabilities){this.currentSnapshot={...this.currentSnapshot,mode,enabled:mode!=="manual",timestamp:Date.now(),capabilities},this.write()}updatePhase(phase){this.currentSnapshot={...this.currentSnapshot,currentPhase:phase,timestamp:Date.now()},this.write()}recordTrigger(triggeredAt,triggeredPhase,source,reason){this.currentSnapshot={...this.currentSnapshot,lastTrigger:{triggeredAt,triggeredPhase,source,reason},timestamp:Date.now()},this.write()}updatePendingActions(count){this.currentSnapshot={...this.currentSnapshot,pendingActions:count,timestamp:Date.now()},this.write()}recordOutcome(state,phase,message){this.currentSnapshot={...this.currentSnapshot,lastOutcome:{state,phase,outcomeAt:Date.now(),message:message??null},timestamp:Date.now()},this.write()}clearOutcome(){this.currentSnapshot={...this.currentSnapshot,lastOutcome:{state:"none",phase:null,outcomeAt:null,message:null},timestamp:Date.now()},this.write()}isEnabled(){return this.currentSnapshot.enabled}hasCapability(capability){return this.currentSnapshot.capabilities[capability]===!0}getGuiSummary(){let{currentSnapshot}=this,status="Disabled";if(currentSnapshot.enabled)status=currentSnapshot.mode.charAt(0).toUpperCase()+currentSnapshot.mode.slice(1);let lastTrigger=null;if(currentSnapshot.lastTrigger?.triggeredAt)lastTrigger=new Date(currentSnapshot.lastTrigger.triggeredAt).toLocaleTimeString();let outcome=null;if(currentSnapshot.lastOutcome?.state&¤tSnapshot.lastOutcome.state!=="none")outcome=currentSnapshot.lastOutcome.state;return{status,phase:currentSnapshot.currentPhase,lastTrigger,pending:currentSnapshot.pendingActions,outcome}}}var MAX_FILENAME_LENGTH=255,SAFE_FILENAME_PATTERN;var init_status_artifact=__esm(()=>{SAFE_FILENAME_PATTERN=/^[a-zA-Z0-9._-]+$/});var exports_trigger={};__export(exports_trigger,{PreflightTriggerManager:()=>PreflightTriggerManager,PhaseBoundaryTrigger:()=>PhaseBoundaryTrigger});class PhaseBoundaryTrigger{eventBus;config;lastKnownPhase=0;lastTriggeredPhase=0;constructor(eventBus,config3){this.eventBus=eventBus??getGlobalEventBus(),this.config={minCompletedTasksThreshold:config3?.minCompletedTasksThreshold??1,allowZeroTaskTrigger:config3?.allowZeroTaskTrigger??!1}}setCurrentPhase(phase){this.lastKnownPhase=phase}getCurrentPhase(){return this.lastKnownPhase}get lastTriggeredPhaseValue(){return this.lastTriggeredPhase}detectBoundary(newPhase,completedTasks,totalTasks){if(newPhase===this.lastKnownPhase)return{detected:!1,previousPhase:this.lastKnownPhase,currentPhase:newPhase,reason:"Phase unchanged",completedTaskCount:completedTasks,totalTaskCount:totalTasks};let boundaryResult={detected:!0,previousPhase:this.lastKnownPhase,currentPhase:newPhase,reason:`Phase transition from ${this.lastKnownPhase} to ${newPhase}`,completedTaskCount:completedTasks,totalTaskCount:totalTasks};return this.lastKnownPhase=newPhase,this.eventBus.publish("phase.boundary.detected",boundaryResult),boundaryResult}shouldTriggerPreflight(boundaryResult){if(this.lastTriggeredPhase===boundaryResult.currentPhase)return log("[Trigger] Preflight already triggered for phase",{phase:boundaryResult.currentPhase}),!1;let threshold=this.config.minCompletedTasksThreshold??1;if(!(this.config.allowZeroTaskTrigger||boundaryResult.completedTaskCount>=threshold))return log("[Trigger] Preflight skipped - insufficient task completion",{completed:boundaryResult.completedTaskCount,required:threshold}),!1;return!0}markTriggered(phase){this.lastTriggeredPhase=phase}reset(){this.lastKnownPhase=0,this.lastTriggeredPhase=0}}class PreflightTriggerManager{automationConfig;eventBus;trigger;requestQueue;requestCounter=0;preflightHandler=null;unsubscribe=null;unsubscribeSkipped=null;constructor(automationConfig,eventBus,triggerConfig){this.automationConfig=automationConfig,this.eventBus=eventBus??getGlobalEventBus(),this.trigger=new PhaseBoundaryTrigger(this.eventBus,triggerConfig),this.requestQueue=new AutomationQueue({maxSize:100,defaultMaxRetries:3,overflowStrategy:"evict-oldest"}),this.unsubscribeSkipped=this.eventBus.subscribe("preflight.skipped",(event)=>{let payload=event.payload;if(payload.reason==="queue_overflow"||payload.reason==="queue_enqueue_error")criticalWarn("[PreflightTrigger] preflight skipped",{reason:payload.reason,phase:payload.phase,requestId:payload.requestId,queueDepth:this.requestQueue.size()})})}isEnabled(){if(!this.automationConfig)return!1;if(!this.automationConfig.capabilities)return!1;if(this.automationConfig.mode==="manual")return!1;return this.automationConfig.capabilities.phase_preflight===!0}getMode(){if(!this.automationConfig)return"unknown";return this.automationConfig.mode??"unknown"}updatePhase(phase){this.trigger.setCurrentPhase(phase)}async checkAndTrigger(currentPhase,completedTasks,totalTasks){let phasePreflight=this.automationConfig?.capabilities?.phase_preflight,mode=this.automationConfig?.mode;if(!this.isEnabled())return log("[PreflightTrigger] Disabled via feature flags",{mode:mode??"unknown",phase_preflight:phasePreflight}),await this.eventBus.publish("preflight.skipped",{reason:"feature_disabled",mode:mode??"unknown",phase_preflight:phasePreflight}),!1;let boundaryResult=this.trigger.detectBoundary(currentPhase,completedTasks,totalTasks);if(!boundaryResult.detected)return!1;if(!this.trigger.shouldTriggerPreflight(boundaryResult))return await this.eventBus.publish("preflight.skipped",{reason:"threshold_not_met",boundary:boundaryResult}),!1;return this.triggerPreflight(boundaryResult)}async triggerPreflight(boundaryResult){let requestId=`preflight-${Date.now()}-${++this.requestCounter}`,request={id:requestId,triggeredAt:Date.now(),currentPhase:boundaryResult.currentPhase,source:"phase_boundary",reason:boundaryResult.reason,metadata:{completedTaskCount:boundaryResult.completedTaskCount,totalTaskCount:boundaryResult.totalTaskCount}};try{this.requestQueue.enqueue(request,"high")}catch(error93){log("[PreflightTrigger] Queue enqueue failed (continuing)",{requestId,phase:boundaryResult.currentPhase,error:error93 instanceof Error?error93.message:String(error93)}),await this.eventBus.publish("preflight.skipped",{reason:"queue_enqueue_error",requestId,phase:boundaryResult.currentPhase})}return this.trigger.markTriggered(boundaryResult.currentPhase),await this.eventBus.publish("preflight.requested",request),await this.eventBus.publish("preflight.triggered",{requestId,phase:boundaryResult.currentPhase,timestamp:request.triggeredAt}),log("[PreflightTrigger] Preflight triggered",{requestId,phase:boundaryResult.currentPhase,completed:boundaryResult.completedTaskCount,total:boundaryResult.totalTaskCount}),!0}getPendingRequests(){return this.requestQueue.getAll().map((item)=>item.payload)}getQueueSize(){return this.requestQueue.size()}getStats(){let mode="unknown";try{mode=this.getMode()}catch{mode="unknown"}return{enabled:this.isEnabled(),mode,currentPhase:this.trigger.getCurrentPhase(),lastTriggeredPhase:this.trigger.lastTriggeredPhaseValue,pendingRequests:this.getQueueSize()}}reset(){if(this.trigger.reset(),this.requestQueue.clear(),this.unsubscribe)this.unsubscribe(),this.unsubscribe=null;if(this.unsubscribeSkipped)this.unsubscribeSkipped(),this.unsubscribeSkipped=null}registerHandler(handler){if(this.unsubscribe)this.unsubscribe();this.preflightHandler=handler;let HANDLER_TIMEOUT_MS=120000;this.unsubscribe=this.eventBus.subscribe("preflight.requested",async(event)=>{let request=event.payload,timeoutHandle;try{if(this.preflightHandler)await Promise.race([this.preflightHandler(request),new Promise((_,reject)=>{timeoutHandle=setTimeout(()=>{reject(Error(`Preflight handler timed out after ${HANDLER_TIMEOUT_MS}ms`))},HANDLER_TIMEOUT_MS)})])}catch(error93){log("[PreflightTrigger] Handler error",{requestId:request.id,phase:request.currentPhase,errorType:error93 instanceof Error?error93.name:"unknown"})}finally{clearTimeout(timeoutHandle);let match=this.requestQueue.getAll().find((it)=>it.payload.id===request.id);if(match)this.requestQueue.complete(match.id)}}),log("[PreflightTrigger] Handler registered")}unregisterHandler(){if(this.unsubscribe)this.unsubscribe(),this.unsubscribe=null;this.preflightHandler=null,log("[PreflightTrigger] Handler unregistered")}hasHandler(){return this.preflightHandler!==null}}var init_trigger=__esm(()=>{init_utils();init_event_bus();init_queue()});function truncateWords(text,maxWords){let trimmed=text.trim();if(trimmed.length===0)return{text:trimmed,truncated:!1};let words=trimmed.split(/\s+/);if(words.length<=maxWords)return{text:trimmed,truncated:!1};return{text:`${words.slice(0,maxWords).join(" ")}…`,truncated:!0}}function capArray(items,maxItems){if(items.length<=maxItems)return{items,truncated:!1};return{items:items.slice(0,maxItems),truncated:!0}}function normalizeAgentWorkSummary(input,maxSummaryWords=MAX_AGENT_SUMMARY_WORDS){let truncated=!1,sum=truncateWords(input.summary,maxSummaryWords);truncated||=sum.truncated;let cap=(items)=>{let r=capArray(items??[],MAX_LIST_ITEMS);return truncated||=r.truncated,r.items},candidate2={schema_version:SUMMARY_SCHEMA_VERSION,phase:input.phase,task_id:input.task_id,session_id:input.session_id,agent:input.agent,parent_agent:input.parent_agent,summary:sum.text,key_decisions:cap(input.key_decisions),constraints_observed:cap(input.constraints_observed),constraints_violated:cap(input.constraints_violated),assumptions:cap(input.assumptions),risks:cap(input.risks),files_touched:input.files_touched?capArray(input.files_touched,50).items:void 0,evidence_refs:capArray(input.evidence_refs??[],20).items,created_at:input.created_at??new Date().toISOString(),truncated:truncated||void 0};return AgentWorkSummarySchema.parse(candidate2)}var SUMMARY_SCHEMA_VERSION="1.0.0",MAX_AGENT_SUMMARY_WORDS=100,MAX_PHASE_SUMMARY_WORDS=250,MAX_LIST_ITEMS=5,SupervisorVerdictSchema,AgentWorkSummarySchema,PhaseArchitectureSummarySchema,SupervisorFindingSchema,KnowledgeRecommendationSchema,EvidenceProvenanceSchema,ArchitectureSupervisorReportSchema;var init_schema3=__esm(()=>{init_zod();SupervisorVerdictSchema=exports_external.enum(["APPROVE","CONCERNS","REJECT"]);AgentWorkSummarySchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),task_id:exports_external.string().min(1).optional(),session_id:exports_external.string().min(1),agent:exports_external.string().min(1),parent_agent:exports_external.string().min(1).optional(),summary:exports_external.string().min(1),key_decisions:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),constraints_observed:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),constraints_violated:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),assumptions:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),risks:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),files_touched:exports_external.array(exports_external.string().min(1)).max(50).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).max(20).default([]),created_at:exports_external.string().datetime(),truncated:exports_external.boolean().optional()});PhaseArchitectureSummarySchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),summary:exports_external.string().default(""),agents_seen:exports_external.array(exports_external.string().min(1)).default([]),tasks_seen:exports_external.array(exports_external.string().min(1)).default([]),key_decisions:exports_external.array(exports_external.string().min(1)).default([]),conflicts:exports_external.array(exports_external.string().min(1)).default([]),unresolved_risks:exports_external.array(exports_external.string().min(1)).default([]),constraint_violations:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),created_at:exports_external.string().datetime()}),SupervisorFindingSchema=exports_external.object({severity:exports_external.enum(["low","medium","high","critical"]),category:exports_external.string().min(1),agents:exports_external.array(exports_external.string().min(1)).default([]),tasks:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),description:exports_external.string().min(1),recommendation:exports_external.string().default("")}),KnowledgeRecommendationSchema=exports_external.object({lesson:exports_external.string().min(1),target_agents:exports_external.array(exports_external.string().min(1)).default([]),confidence:exports_external.number().min(0).max(1).default(0.5),evidence_refs:exports_external.array(exports_external.string().min(1)).default([])}),EvidenceProvenanceSchema=exports_external.object({agent_name:exports_external.string().min(1).optional(),session_id:exports_external.string().min(1).optional(),captured_at:exports_external.string().datetime().optional()}),ArchitectureSupervisorReportSchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),verdict:SupervisorVerdictSchema,findings:exports_external.array(SupervisorFindingSchema).default([]),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema).default([]),created_at:exports_external.string().datetime(),provenance:EvidenceProvenanceSchema.optional()})});import{existsSync as existsSync103,mkdirSync as mkdirSync60,readFileSync as readFileSync82,renameSync as renameSync35,unlinkSync as unlinkSync34,writeFileSync as writeFileSync40}from"node:fs";import*as path205 from"node:path";function writeRawSidecar(absPath,bundle){mkdirSync60(path205.dirname(absPath),{recursive:!0});let tempFile=`${absPath}.tmp-${Date.now()}-${process.pid}`;try{writeFileSync40(tempFile,JSON.stringify(bundle,null,2),"utf-8"),renameSync35(tempFile,absPath)}finally{if(existsSync103(tempFile))try{unlinkSync34(tempFile)}catch{}}}async function writeAgentSummary(directory,summary){let taskId=summary.task_id??`phase-${summary.phase}-summaries`;return await saveEvidence(directory,taskId,{task_id:taskId,type:"note",timestamp:summary.created_at,agent:summary.agent,verdict:"info",summary:summary.summary,metadata:{kind:AGENT_SUMMARY_METADATA_KIND,phase:summary.phase,session_id:summary.session_id,payload:summary}}),taskId}async function listAgentSummaries(directory,filter={}){let taskIds=await listEvidenceTaskIds(directory),results=[];for(let taskId of taskIds){let loaded=await loadEvidence(directory,taskId);if(loaded.status!=="found")continue;for(let entry of loaded.bundle.entries){if(entry.type!=="note")continue;let meta3=entry.metadata;if(!meta3||meta3.kind!==AGENT_SUMMARY_METADATA_KIND)continue;if(filter.phase!==void 0&&meta3.phase!==filter.phase)continue;if(filter.session!==void 0&&meta3.session_id!==filter.session)continue;let parsed=AgentWorkSummarySchema.safeParse(meta3.payload);if(!parsed.success){warn(`Skipping malformed agent summary in task ${taskId}: ${parsed.error.issues.map((i)=>i.message).join(", ")}`);continue}results.push(parsed.data)}}return results}function writePhaseArchitectureSummary(directory,summary){let rel=path205.join("evidence",String(summary.phase),PHASE_SUMMARY_FILE),abs=validateSwarmPath(directory,rel);return writeRawSidecar(abs,summary),abs}function writeSupervisorReport(directory,report){let rel=path205.join("evidence",String(report.phase),SUPERVISOR_REPORT_FILE),abs=validateSwarmPath(directory,rel),bundle={entries:[{type:SUPERVISOR_ENTRY_TYPE,phase_number:report.phase,scope:"phase",timestamp:report.created_at,verdict:report.verdict,findings:report.findings,knowledge_recommendations:report.knowledge_recommendations,...report.provenance?{provenance:report.provenance}:{}}]};return writeRawSidecar(abs,bundle),abs}function readSupervisorReportRaw(directory,phase){let rel=path205.join("evidence",String(phase),SUPERVISOR_REPORT_FILE),abs;try{abs=validateSwarmPath(directory,rel)}catch{return null}if(!existsSync103(abs))return null;try{return JSON.parse(readFileSync82(abs,"utf-8")).entries?.find((e)=>e.type===SUPERVISOR_ENTRY_TYPE)??null}catch{return null}}var AGENT_SUMMARY_METADATA_KIND="agent_summary",PHASE_SUMMARY_FILE="phase-architecture-summary.json",SUPERVISOR_REPORT_FILE="architecture-supervisor.json",SUPERVISOR_ENTRY_TYPE="architecture-supervisor";var init_store4=__esm(()=>{init_manager2();init_utils2();init_utils();init_schema3()});var exports_aggregate={};__export(exports_aggregate,{aggregatePhaseSummary:()=>aggregatePhaseSummary});function dedupe2(values){return Array.from(new Set(values)).filter((v)=>v.trim().length>0)}function detectConflicts(summaries){let observedBy=new Map,violatedBy=new Map;for(let s of summaries){for(let c of s.constraints_observed){if(!observedBy.has(c))observedBy.set(c,new Set);observedBy.get(c)?.add(s.agent)}for(let c of s.constraints_violated){if(!violatedBy.has(c))violatedBy.set(c,new Set);violatedBy.get(c)?.add(s.agent)}}let conflicts=[];for(let[constraint,violators]of violatedBy){let observers=observedBy.get(constraint);if(observers&&observers.size>0){let obs=Array.from(observers).sort().join(", "),vio=Array.from(violators).sort().join(", ");conflicts.push(`Constraint "${constraint}" observed by [${obs}] but violated by [${vio}]`)}}return conflicts.sort()}async function aggregatePhaseSummary(directory,phase,options={}){let summaries=await listAgentSummaries(directory,{phase});if(summaries.length===0)return null;let agentsSeen=dedupe2(summaries.map((s)=>s.agent)).sort(),tasksSeen=dedupe2(summaries.map((s)=>s.task_id).filter((t)=>Boolean(t))).sort(),keyDecisions=dedupe2(summaries.flatMap((s)=>s.key_decisions)),unresolvedRisks=dedupe2(summaries.flatMap((s)=>s.risks)),constraintViolations=dedupe2(summaries.flatMap((s)=>s.constraints_violated)),evidenceRefs=dedupe2(summaries.flatMap((s)=>s.evidence_refs)),conflicts=detectConflicts(summaries),headline=`Phase ${phase}: ${summaries.length} agent summary(ies) across ${tasksSeen.length} task(s); ${constraintViolations.length} constraint violation(s), ${conflicts.length} cross-agent conflict(s).`,cap=options.maxPhaseSummaryWords??MAX_PHASE_SUMMARY_WORDS,summaryText=truncateWords(headline,cap).text,phaseSummary={schema_version:SUMMARY_SCHEMA_VERSION,phase,summary:summaryText,agents_seen:agentsSeen,tasks_seen:tasksSeen,key_decisions:keyDecisions,conflicts,unresolved_risks:unresolvedRisks,constraint_violations:constraintViolations,evidence_refs:evidenceRefs,created_at:options.now?.()??new Date().toISOString()};return writePhaseArchitectureSummary(directory,phaseSummary),phaseSummary}var init_aggregate=__esm(()=>{init_schema3();init_store4()});var exports_preflight_integration={};__export(exports_preflight_integration,{runManualPreflight:()=>runManualPreflight,createPreflightIntegration:()=>createPreflightIntegration});function createPreflightIntegration(config3){let{automationConfig,directory,swarmDir,preflightConfig,updateStatusArtifact=!0}=config3;if(automationConfig?.capabilities?.phase_preflight!==!0)throw Error("Preflight is not enabled in automation capabilities. Set automation.capabilities.phase_preflight to true.");let manager=new PreflightTriggerManager(automationConfig,void 0,{directory}),statusArtifact=null;if(updateStatusArtifact&&swarmDir)statusArtifact=new AutomationStatusArtifact(swarmDir);let preflightHandler=async(request)=>{log("[PreflightIntegration] Handling preflight request",{requestId:request.id,phase:request.currentPhase,source:request.source});let report=await runPreflight(directory,request.currentPhase,preflightConfig);if(statusArtifact){let state=report.overall==="pass"?"success":"failure";statusArtifact.recordOutcome(state,request.currentPhase,report.message),log("[PreflightIntegration] Status artifact updated",{state,phase:request.currentPhase,message:report.message})}log("[PreflightIntegration] Preflight complete",{requestId:request.id,overall:report.overall,message:report.message,durationMs:report.totalDurationMs})};return manager.registerHandler(preflightHandler),{manager,cleanup:()=>{manager.unregisterHandler()}}}async function runManualPreflight(directory,phase,config3){return runPreflight(directory,phase,config3)}var init_preflight_integration=__esm(()=>{init_status_artifact();init_trigger();init_preflight_service();init_logger()});var exports_doc_scan={};__export(exports_doc_scan,{scanDocIndex:()=>scanDocIndex,extractDocConstraints:()=>extractDocConstraints,doc_scan:()=>doc_scan,doc_extract:()=>doc_extract});import*as crypto15 from"node:crypto";import*as fs115 from"node:fs";import{mkdir as mkdir41,readdir as readdir13,readFile as readFile44,realpath as realpath8,stat as stat17,writeFile as writeFile27}from"node:fs/promises";import*as path221 from"node:path";function normalizeSeparators(filePath){return filePath.replace(/\\/g,"/")}function matchesDocPattern(filePath,patterns){let normalizedPath2=normalizeSeparators(filePath),basename29=path221.basename(filePath);for(let pattern of patterns){if(!pattern.includes("/")&&!pattern.includes("\\")){if(basename29===pattern)return!0;continue}if(pattern.startsWith("**/")){let filenamePattern=pattern.slice(3);if(basename29===filenamePattern)return!0;continue}let dirPrefix=normalizeSeparators(pattern).replace(/\/\*\*.*$/,"").replace(/\/\*.*$/,"");if(normalizedPath2.startsWith(`${dirPrefix}/`)||normalizedPath2===dirPrefix)return!0}return!1}function extractTitleAndSummary(content,filename){let lines=content.split(`
|
|
5565
5565
|
`),title=filename,summary="",foundTitle=!1,potentialSummaryLines=[];for(let i=0;i<lines.length&&i<READ_LINES_LIMIT;i++){let line=lines[i].trim();if(!foundTitle&&line.startsWith("# ")){title=line.slice(2).trim(),foundTitle=!0;continue}if(line&&!line.startsWith("#"))potentialSummaryLines.push(line)}for(let line of potentialSummaryLines)if(summary+=(summary?" ":"")+line,summary.length>=MAX_SUMMARY_LENGTH)break;if(summary.length>MAX_SUMMARY_LENGTH)summary=`${summary.slice(0,MAX_SUMMARY_LENGTH-3)}...`;return{title,summary}}function stripMarkdown(text){return text.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/^\s*[-*•]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").trim()}async function scanDocIndex(directory){let manifestPath=path221.join(directory,".swarm","doc-manifest.json"),defaultPatterns=DocsConfigSchema.parse({}).doc_patterns,extraPatterns=["ARCHITECTURE.md","CLAUDE.md","AGENTS.md",".github/*.md","doc/**/*.md"],allPatterns=[...defaultPatterns,...extraPatterns];try{let manifestContent=await readFile44(manifestPath,"utf-8"),existingManifest=JSON.parse(manifestContent);if(existingManifest.schema_version===1&&existingManifest.files){let cacheValid=!0;for(let file3 of existingManifest.files)try{let fullPath=path221.join(directory,file3.path);if(fs115.statSync(fullPath).mtimeMs>file3.mtime){cacheValid=!1;break}}catch{cacheValid=!1;break}if(cacheValid)return{manifest:existingManifest,cached:!0}}}catch{}let resolvedDirectory=await realpath8(directory).catch(()=>directory),discoveredFiles=[],rootReadable=!1,truncated=!1,walkDir2=async(dir)=>{let entries;try{if(entries=await readdir13(dir,{withFileTypes:!0}),dir===directory)rootReadable=!0}catch{return}for(let entry of entries){let isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let symlinkPath=path221.join(dir,entry.name),resolved=await realpath8(symlinkPath),rel=path221.relative(resolvedDirectory,resolved);if(rel.startsWith("..")||path221.isAbsolute(rel))continue;isFile=(await stat17(symlinkPath)).isFile()}catch{continue}if(isDir){if(!SKIP_DIRECTORIES3.has(entry.name))await walkDir2(path221.join(dir,entry.name));continue}if(!isFile)continue;let fullPath=path221.join(dir,entry.name),relPath=normalizeSeparators(path221.relative(directory,fullPath)),skipThisFile=!1;for(let pattern of SKIP_PATTERNS)if(pattern.test(relPath)){skipThisFile=!0;break}if(skipThisFile)continue;if(!matchesDocPattern(relPath,allPatterns))continue;if(discoveredFiles.length>=MAX_INDEXED_FILES){truncated=!0;return}let fileStat;try{fileStat=await stat17(fullPath)}catch{continue}let content;try{content=await readFile44(fullPath,"utf-8")}catch{continue}let{title,summary}=extractTitleAndSummary(content,path221.basename(relPath));discoveredFiles.push({path:relPath,title,summary,lines:content.split(`
|
|
5566
5566
|
`).length,mtime:fileStat.mtimeMs})}};if(await walkDir2(directory),!rootReadable)return{manifest:{schema_version:1,scanned_at:new Date().toISOString(),files:[]},cached:!1};if(discoveredFiles.sort((a,b)=>a.path.toLowerCase().localeCompare(b.path.toLowerCase())),discoveredFiles.length>MAX_INDEXED_FILES)discoveredFiles.splice(MAX_INDEXED_FILES),truncated=!0;if(truncated&&discoveredFiles.length>0)discoveredFiles[0].summary=`[Warning: ${MAX_INDEXED_FILES}+ docs found, listing first ${MAX_INDEXED_FILES}] `+discoveredFiles[0].summary;let manifest={schema_version:1,scanned_at:new Date().toISOString(),files:discoveredFiles};try{await mkdir41(path221.dirname(manifestPath),{recursive:!0}),await writeFile27(manifestPath,JSON.stringify(manifest,null,2),"utf-8")}catch{}return{manifest,cached:!1}}function isConstraintLine(line){let upperLine=line.toUpperCase();for(let pattern of CONSTRAINT_PATTERNS)if(pattern.test(upperLine))return!0;if(/^\s*[-*•]/.test(line)&&ACTION_WORDS.test(line))return!0;return!1}function extractConstraintsFromContent(content){let lines=content.split(`
|
|
5567
5567
|
`),constraints=[];for(let line of lines){if(constraints.length>=MAX_CONSTRAINTS_PER_DOC)break;let trimmed=line.trim();if(!trimmed)continue;if(isConstraintLine(trimmed)){let cleaned=stripMarkdown(trimmed),len=cleaned.length;if(len>=MIN_LESSON_LENGTH&&len<=MAX_CONSTRAINT_LENGTH)constraints.push(cleaned)}}return constraints}async function extractDocConstraints(directory,taskFiles,taskDescription){let manifestPath=path221.join(directory,".swarm","doc-manifest.json"),manifest;try{let content=await readFile44(manifestPath,"utf-8");manifest=JSON.parse(content)}catch{manifest=(await scanDocIndex(directory)).manifest}let knowledgePath=resolveSwarmKnowledgePath(directory),existingEntries=await readKnowledge(knowledgePath),taskContext=[...taskFiles,taskDescription].join(" "),taskBigrams=wordBigrams(normalize10(taskContext)),extractedCount=0,skippedCount=0,details=[];for(let docFile of manifest.files){let docContext=`${docFile.path} ${docFile.title} ${docFile.summary}`,docBigrams=wordBigrams(normalize10(docContext)),score=jaccardBigram(taskBigrams,docBigrams);if(score<=RELEVANCE_THRESHOLD){skippedCount++;continue}let fullContent;try{fullContent=await readFile44(path221.join(directory,docFile.path),"utf-8")}catch{skippedCount++;continue}let constraints=extractConstraintsFromContent(fullContent);if(constraints.length===0){skippedCount++;continue}let docDetails={path:docFile.path,score,constraints:[]};for(let constraint of constraints)if(!findNearDuplicate(constraint,existingEntries,DEDUP_THRESHOLD2)){let entry={id:crypto15.randomUUID(),tier:"swarm",lesson:constraint,category:"architecture",tags:["doc-scan",path221.basename(docFile.path)],scope:"global",confidence:0.5,status:"candidate",confirmed_by:[],project_name:"",retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:1,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),auto_generated:!0,hive_eligible:!1};await appendKnowledge(knowledgePath,entry),existingEntries.push(entry),extractedCount++,docDetails.constraints.push(constraint)}if(docDetails.constraints.length>0)details.push(docDetails);else skippedCount++}return{extracted:extractedCount,skipped:skippedCount,details}}var SKIP_DIRECTORIES3,SKIP_PATTERNS,MAX_SUMMARY_LENGTH=200,MAX_INDEXED_FILES=100,READ_LINES_LIMIT=30,MIN_LESSON_LENGTH=15,MAX_CONSTRAINTS_PER_DOC=5,MAX_CONSTRAINT_LENGTH=200,RELEVANCE_THRESHOLD=0.1,DEDUP_THRESHOLD2=0.6,CONSTRAINT_PATTERNS,ACTION_WORDS,doc_scan,doc_extract;var init_doc_scan=__esm(()=>{init_zod();init_schema();init_knowledge_store();init_create_tool();SKIP_DIRECTORIES3=new Set(["node_modules",".git",".swarm","dist","build",".next","vendor","bazel-out","bazel-bin","bazel-genfiles","bazel-testlogs",".gradle","target"]),SKIP_PATTERNS=[/\.test\./,/\.spec\./,/\.d\.ts$/];CONSTRAINT_PATTERNS=[/\bMUST\b/,/\bMUST NOT\b/,/\bSHOULD\b/,/\bSHOULD NOT\b/,/\bDO NOT\b/,/\bALWAYS\b/,/\bNEVER\b/,/\bREQUIRED\b/],ACTION_WORDS=/\b(must|should|don't|avoid|ensure|use|follow)\b/i;doc_scan=createSwarmTool({description:"Scan project documentation files and build an index manifest. Caches results in .swarm/doc-manifest.json for fast subsequent scans.",args:{force:exports_external.boolean().optional().describe("Force re-scan even if cache is valid")},execute:async(args2,directory)=>{let force=!1;try{if(args2&&typeof args2==="object"){if(args2.force===!0)force=!0}}catch{}if(force){let manifestPath=path221.join(directory,".swarm","doc-manifest.json");try{fs115.unlinkSync(manifestPath)}catch{}}let{manifest,cached:cached3}=await scanDocIndex(directory);return JSON.stringify({success:!0,files_count:manifest.files.length,cached:cached3,manifest},null,2)}}),doc_extract=createSwarmTool({description:"Extract actionable constraints from project documentation relevant to the current task. Scans docs via doc-manifest, scores relevance via Jaccard bigram similarity, and stores non-duplicate constraints in .swarm/knowledge.jsonl.",args:{task_files:exports_external.array(exports_external.string()).describe("List of file paths involved in the current task"),task_description:exports_external.string().describe("Description of the current task")},execute:async(args2,directory)=>{let taskFiles=[],taskDescription="";try{if(args2&&typeof args2==="object"){let obj=args2;if(Array.isArray(obj.task_files))taskFiles=obj.task_files.filter((f)=>typeof f==="string");if(typeof obj.task_description==="string")taskDescription=obj.task_description}}catch{}if(taskFiles.length===0&&!taskDescription)return JSON.stringify({success:!1,error:"task_files or task_description is required"});let result=await extractDocConstraints(directory,taskFiles,taskDescription);return JSON.stringify({success:!0,...result},null,2)}})});import{existsSync as existsSync108}from"node:fs";import{readFile as readFile45}from"node:fs/promises";import*as path222 from"node:path";function inferCategoriesFromPhase(phaseDescription){let lower=phaseDescription.toLowerCase(),patterns=[{pattern:/\b(?:test|qa|quality|verification|validation)\b/,categories:["testing","debugging"]},{pattern:/\b(?:implement|build|develop|coding|code)\b/,categories:["tooling","architecture","debugging"]},{pattern:/\b(?:integrat|deploy|ci|cd|release|publish)\b/,categories:["integration","tooling","performance"]},{pattern:/\b(?:plan|design|architect|spec|requirement)\b/,categories:["architecture","process"]},{pattern:/\b(?:review|refactor|cleanup|polish|optimi)\b/,categories:["performance","architecture","process"]},{pattern:/\b(?:secur|audit|harden|compliance)\b/,categories:["security","testing"]},{pattern:/\b(?:setup|config|scaffold|init|bootstrap)\b/,categories:["tooling","other"]},{pattern:/\b(?:doc|readme|changelog)\b/,categories:["process","tooling"]}];for(let{pattern,categories}of patterns)if(pattern.test(lower))return categories;return["process","tooling"]}async function transactShownFile(shownFile,mutate){return transactFile(shownFile,async(filePath)=>{if(!existsSync108(filePath))return{};try{let content=await readFile45(filePath,"utf-8");return JSON.parse(content)}catch{return{}}},async(filePath,data)=>{await atomicWriteFile(filePath,JSON.stringify(data,null,2))},mutate)}async function recordLessonsShown(directory,lessonIds,currentPhase){if(lessonIds.length===0)return;let shownFile=path222.join(directory,".swarm",".knowledge-shown.json");try{let phaseMatch=/^Phase\s+(\d+)/i.exec(currentPhase),canonicalKey=phaseMatch?`Phase ${phaseMatch[1]}`:currentPhase;if(!await transactShownFile(shownFile,(shownData)=>{let existing=new Set(shownData[canonicalKey]??[]);for(let id of lessonIds)existing.add(id);return shownData[canonicalKey]=[...existing],shownData}))warn("[swarm] Knowledge: failed to record shown lessons")}catch{warn("[swarm] Knowledge: failed to record shown lessons")}}async function readMergedKnowledge(directory,config3,context,opts){let swarmPath3=resolveSwarmKnowledgePath(directory),swarmEntries=await readKnowledge(swarmPath3),hiveEntries=[];if(config3.hive_enabled!==!1){let hivePath=resolveHiveKnowledgePath2();hiveEntries=await readKnowledge(hivePath)}let seenLessons=new Set,merged=[];for(let entry of hiveEntries){let normalized=normalize10(entry.lesson);seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}for(let entry of swarmEntries){let normalized=normalize10(entry.lesson);if(seenLessons.has(normalized))continue;let swarmBigrams=wordBigrams(normalized);if(hiveEntries.some((hiveEntry)=>jaccardBigram(swarmBigrams,wordBigrams(normalize10(hiveEntry.lesson)))>=JACCARD_THRESHOLD2))continue;if(merged.some((m)=>m.tier==="swarm"&&jaccardBigram(swarmBigrams,wordBigrams(normalize10(m.lesson)))>=JACCARD_THRESHOLD2))continue;seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}let retractionRecords=await readRetractionRecords(directory),suppressedLessons=new Set(retractionRecords.map((record3)=>record3.normalized_lesson).filter((value)=>typeof value==="string"&&value.length>0)),scopeFilter=config3.scope_filter??["global"],ranked=merged.filter((entry)=>(opts?.skipScopeFilter||scopeFilter.some((pattern)=>(entry.scope??"global")===pattern))&&isActiveStatus(entry.status)&&!suppressedLessons.has(normalize10(entry.lesson))).map((entry)=>{let categoryScore=0;if(context?.currentPhase){if(inferCategoriesFromPhase(context.currentPhase).includes(entry.category))categoryScore=1;else if(entry.category==="process")categoryScore=0.5}else categoryScore=0.5;let confidenceScore=entry.confidence,keywordsScore=0;if(context?.techStack&&entry.tags.length>0){let matchingTags=entry.tags.filter((t)=>context.techStack.some((s)=>t.toLowerCase().includes(s.toLowerCase())||s.toLowerCase().includes(t.toLowerCase()))).length;keywordsScore=Math.min(matchingTags/Math.max(entry.tags.length,1),1)}else if(entry.tags.length===0)keywordsScore=0.5;let tierBoost=0,isSameProject=!1;if(entry.tier==="hive"&&"source_project"in entry){let sourceProject=entry.source_project;isSameProject=!!(context?.projectName&&sourceProject===context.projectName),tierBoost=HIVE_TIER_BOOST}let sameProjectPenalty=isSameProject?DEFAULT_SAME_PROJECT_PENALTY:0,finalScore=categoryScore*0.4+confidenceScore*0.35+keywordsScore*0.25+tierBoost+sameProjectPenalty;return{...entry,relevanceScore:{category:categoryScore,confidence:confidenceScore,keywords:keywordsScore},finalScore:Math.min(Math.max(finalScore,0),1)}});ranked.sort((a,b)=>{let scoreDiff=b.finalScore-a.finalScore;if(Math.abs(scoreDiff)>0.001)return scoreDiff;let dateA=new Date(a.created_at).getTime();return new Date(b.created_at).getTime()-dateA});let maxInject=config3.max_inject_count??5;return ranked.slice(0,maxInject)}async function updateRetrievalOutcome(directory,phaseInfo,phaseSucceeded){let shownFile=path222.join(directory,".swarm",".knowledge-shown.json");try{if(!existsSync108(shownFile))return;let shownIds;try{let content=await readFile45(shownFile,"utf-8");shownIds=JSON.parse(content)[phaseInfo]}catch{return}if(!shownIds||shownIds.length===0)return;let outcome=phaseSucceeded?"success":"failure",evidenceSummary=`${phaseInfo} ${phaseSucceeded?"succeeded":"failed"} after entry was shown`;await transactShownFile(shownFile,(data)=>{return delete data[phaseInfo],data});for(let id of shownIds)await _internals151.recordKnowledgeEvent(directory,{type:"outcome",knowledge_id:id,phase:phaseInfo,outcome,evidence_summary:evidenceSummary})}catch{warn("[swarm] Knowledge: failed to update retrieval outcomes")}}function lc(s){return(s??"").toLowerCase()}function anyMatch(haystack,needles){if(needles.length===0)return!1;let hay=haystack.map(lc);return needles.some((n)=>hay.some((h)=>h.includes(lc(n))))}function tokenizeContext(ctx){let parts=[];if(ctx.taskTitle)parts.push(ctx.taskTitle);if(ctx.taskDescription)parts.push(ctx.taskDescription);if(ctx.lastUserMessage)parts.push(ctx.lastUserMessage);if(ctx.currentAction)parts.push(ctx.currentAction);if(ctx.currentTool)parts.push(ctx.currentTool);if(ctx.targetAgent)parts.push(ctx.targetAgent);if(ctx.declaredScope)parts.push(ctx.declaredScope);if(ctx.recentReviewerFailures)parts.push(...ctx.recentReviewerFailures);if(ctx.recentTestFailures)parts.push(...ctx.recentTestFailures);if(ctx.recentToolErrors)parts.push(...ctx.recentToolErrors);if(ctx.planConstraints)parts.push(...ctx.planConstraints);if(ctx.filePaths)parts.push(...ctx.filePaths);return parts.map(lc)}function scoreDirectiveAgainstContext(entry,ctx){let haystack=tokenizeContext(ctx),triggerHit=entry.triggers&&entry.triggers.length>0?anyMatch(haystack,entry.triggers):!1,actionHit=entry.applies_to_tools&&entry.applies_to_tools.length>0?entry.applies_to_tools.map(lc).some((t)=>t===lc(ctx.currentTool)||t===lc(ctx.currentAction)):!1,agentHit=entry.applies_to_agents&&entry.applies_to_agents.length>0?entry.applies_to_agents.map(lc).some((a)=>a===lc(ctx.targetAgent)):!1,score=0;if(triggerHit)score+=0.5;if(actionHit)score+=0.35;if(agentHit)score+=0.25;if(entry.directive_priority==="critical")score+=0.4;else if(entry.directive_priority==="high")score+=0.2;else if(entry.directive_priority==="medium")score+=0.1;return{triggerHit,actionHit,agentHit,score:Math.min(1,score)}}var JACCARD_THRESHOLD2=0.6,HIVE_TIER_BOOST=0.05,DEFAULT_SAME_PROJECT_PENALTY=-0.05,_internals151;var init_knowledge_reader=__esm(()=>{init_task_file();init_logger();init_knowledge_events();init_knowledge_store();init_knowledge_types();_internals151={readMergedKnowledge,updateRetrievalOutcome,scoreDirectiveAgainstContext,transactShownFile,recordKnowledgeEvent,recordLessonsShown}});function entryText(e){return`${e.lesson} ${e.tags.join(" ")} ${e.category}`}function entryAgePhases(e){let cb=e.confirmed_by;if(!Array.isArray(cb)||cb.length===0)return 0;let phases=new Set;for(let c of cb)if(typeof c?.phase_number==="number")phases.add(c.phase_number);return phases.size>0?phases.size:cb.length}function clampLambda(v){if(typeof v!=="number"||Number.isNaN(v))return 0.5;return Math.min(1,Math.max(0,v))}function mmrRerank(pool,pinned,max,lambda){if(pool.length===0)return[];let bigrams=new Map,bg=(e)=>{let s=bigrams.get(e.id);if(!s)s=wordBigrams(normalize10(e.lesson??"")),bigrams.set(e.id,s);return s},selected=[...pinned],candidates=[...pool],out=[];while(selected.length<max&&candidates.length>0){let bestIdx=-1,bestScore=Number.NEGATIVE_INFINITY,best=null;for(let i=0;i<candidates.length;i++){let c=candidates[i],maxSim=0;for(let s of selected){let sim=jaccardBigram(bg(c),bg(s));if(sim>maxSim)maxSim=sim}let score=lambda*c.finalScore-(1-lambda)*maxSim;if(score>bestScore+0.000000001||Math.abs(score-bestScore)<=0.000000001&&best!==null&&tieBreak(c,best)<0)bestScore=score,bestIdx=i,best=c}if(bestIdx<0||best===null)break;out.push(best),selected.push(best),candidates.splice(bestIdx,1)}return out}function tieBreak(a,b){if(Math.abs(a.finalScore-b.finalScore)>0.000000001)return b.finalScore-a.finalScore;let at=new Date(a.created_at).getTime(),bt=new Date(b.created_at).getTime();if(at!==bt)return bt-at;return a.id<b.id?-1:a.id>b.id?1:0}function statusBoost(status){if(status==="promoted")return 0.15;if(status==="established")return 0.1;return 0}async function searchKnowledge(params){let{directory,config:config3,query,context,mode,agent="unknown",sessionId="unknown",tier="all",emitEvent=!0,applyScopeFilter=!0,forceReadHive=!1,applyRoleScope=!0}=params,traceId=newTraceId2(),max=params.maxResults??config3.max_inject_count??5,results=[],synonymTokens=[],synonymTrace={};try{let mergeConfig={...config3,hive_enabled:tier==="swarm"?!1:forceReadHive?!0:config3.hive_enabled,max_inject_count:Math.max(20,max)},projected={projectName:context?.projectName??"unknown",currentPhase:context?.currentPhase??"",techStack:context?.techStack,recentErrors:[...context?.recentReviewerFailures??[],...context?.recentTestFailures??[],...context?.recentToolErrors??[]]},candidates=await readMergedKnowledge(directory,mergeConfig,projected,{skipScopeFilter:!applyScopeFilter}),counterRollups=await readKnowledgeCounterRollups(directory);candidates=candidates.filter((e)=>{if(!isActiveStatus(e.status))return!1;if(tier==="hive"&&e.tier!=="hive")return!1;return!0});let role=stripKnownSwarmPrefix(agent).toLowerCase();if(applyRoleScope&&role&&role!=="unknown")candidates=candidates.filter((e)=>{if(!e.applies_to_agents||e.applies_to_agents.length===0)return!0;if(role==="architect")return!0;return e.applies_to_agents.map((a)=>stripKnownSwarmPrefix(a).toLowerCase()).includes(role)});let queryText=(query??"").trim(),queryBigrams=queryText?wordBigrams(normalize10(queryText)):null,hasQuery=queryBigrams!==null,textWeight=hasQuery?TEXT_WEIGHT:0,metaWeight=hasQuery?META_WEIGHT:1,compositeRaw=[queryText,context?.taskTitle,context?.taskDescription,context?.lastUserMessage,context?.currentAction,...context?.recentReviewerFailures??[],...context?.recentTestFailures??[],...context?.recentToolErrors??[]].filter((s)=>typeof s==="string"&&s.length>0).join(" "),compositeNorm=normalize10(compositeRaw),hasComposite=compositeNorm.length>0;try{if(hasComposite){let synMap=await readSynonymMap(directory,config3.retrieval?.synonym_map_max_pairs),synIndex=buildSynonymIndex(synMap,config3.retrieval?.synonym_min_cooccurrence),baseTokens=compositeNorm.split(" ").filter(Boolean);synonymTokens=expandTokens(synIndex,baseTokens)}}catch{synonymTokens=[]}let minConf=typeof config3.directive_min_confidence==="number"?config3.directive_min_confidence:DIRECTIVE_BOOST_MIN_CONFIDENCE,scored=candidates.map((entry)=>{let retrievalOutcomes=effectiveRetrievalOutcomes(entry.retrieval_outcomes,counterRollups.get(entry.id)),textScore=queryBigrams?jaccardBigram(queryBigrams,wordBigrams(normalize10(entryText(entry)))):0,metaScore=entry.finalScore,ds=context?scoreDirectiveAgainstContext(entry,context):{triggerHit:!1,actionHit:!1,agentHit:!1,score:0},confBoost=context&&entry.confidence>=minConf&&(ds.actionHit||ds.agentHit)?0.25:0,generatedSkillBoost=entry.generated_skill_path&&entry.status!=="archived"?0.05:0,outcomeBoost=computeOutcomeSignal(retrievalOutcomes)*OUTCOME_RANK_WEIGHT,coldStartBonus=(retrievalOutcomes.applied_explicit_count??0)===0&&entryAgePhases(entry)<(config3.retrieval?.cold_start_max_age_phases??DEFAULT_COLD_START_MAX_AGE_PHASES)?config3.retrieval?.cold_start_bonus??DEFAULT_COLD_START_BONUS:0,synonymBoost=0;if(synonymTokens.length>0){let entryHay=normalize10(entryText(entry)),matched=[];for(let t of synonymTokens)if(t.length>0&&entryHay.includes(t))matched.push(t);if(matched.length>0)synonymBoost=SYNONYM_TEXT_BOOST,synonymTrace[entry.id]=matched}let triggerRecallBoost=!ds.triggerHit&&hasComposite&&Array.isArray(entry.triggers)&&entry.triggers.some((tr)=>{let n=normalize10(tr);return n.length>=TRIGGER_RECALL_MIN_LEN&&compositeNorm.includes(n)})?TRIGGER_RECALL_BOOST:0,finalScore=Math.min(1,Math.max(0,textWeight*textScore+metaWeight*metaScore+ds.score+confBoost+generatedSkillBoost+outcomeBoost+coldStartBonus+synonymBoost+triggerRecallBoost+(hasQuery&&!entry.confidence_floor_demoted?statusBoost(entry.status):0))),statusScoreBoost=hasQuery&&!entry.confidence_floor_demoted?statusBoost(entry.status):0,isCritical=entry.directive_priority==="critical"&&(ds.triggerHit||ds.actionHit||ds.agentHit),isForceHive=forceReadHive&&entry.tier==="hive";return{...entry,retrieval_outcomes:retrievalOutcomes,finalScore,coldStartBoost:coldStartBonus,score_breakdown:{text_score:textScore,metadata_score:metaScore,directive_score:ds.score,confidence_boost:confBoost,generated_skill_boost:generatedSkillBoost,outcome_boost:outcomeBoost,cold_start_boost:coldStartBonus,synonym_boost:synonymBoost,trigger_recall_boost:triggerRecallBoost,status_boost:statusScoreBoost,final_score:finalScore,...synonymTrace[entry.id]?{synonym_matches:synonymTrace[entry.id]}:{}},__critical:isCritical,__forceHive:isForceHive}});scored.sort((a,b)=>{let diff=b.finalScore-a.finalScore;if(Math.abs(diff)>0.001)return diff;return new Date(b.created_at).getTime()-new Date(a.created_at).getTime()});let top=[],seen=new Set;for(let e of scored){if(top.length>=max)break;if(e.__critical&&!seen.has(e.id))top.push(e),seen.add(e.id)}for(let e of scored){if(top.length>=max)break;if(e.__forceHive&&!seen.has(e.id))top.push(e),seen.add(e.id)}let lambda=clampLambda(config3.retrieval?.mmr_lambda),remaining=scored.filter((e)=>!seen.has(e.id)),selected=mmrRerank(remaining,top,max,lambda);for(let e of selected){if(top.length>=max)break;if(!seen.has(e.id))top.push(e),seen.add(e.id)}results=top.map(({__critical:_c,__forceHive:_f,...rest})=>rest)}catch(err){warn(`[search-knowledge] retrieval failed: ${err instanceof Error?err.message:String(err)}`),results=[]}if(emitEvent){let ranks={},scores={};results.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore});let synonymBreakdown={};for(let e of results)if(synonymTrace[e.id])synonymBreakdown[e.id]=synonymTrace[e.id];let scoreBreakdown=synonymTokens.length>0?{synonyms_expanded:synonymTokens,synonym_matches:synonymBreakdown}:void 0;await recordKnowledgeEvent(directory,{type:"retrieved",trace_id:traceId,session_id:sessionId,phase:context?.currentPhase,task_id:context?.taskId,agent,query:query??context?.lastUserMessage??context?.currentPhase??"",retrieval_mode:mode,result_ids:results.map((e)=>e.id),ranks,scores,...scoreBreakdown?{score_breakdown:scoreBreakdown}:{}})}return{trace_id:traceId,results}}var TEXT_WEIGHT=0.6,META_WEIGHT=0.4,DIRECTIVE_BOOST_MIN_CONFIDENCE=0.75,SYNONYM_TEXT_BOOST=0.15,TRIGGER_RECALL_BOOST=0.3,TRIGGER_RECALL_MIN_LEN=3,DEFAULT_COLD_START_BONUS=0.08,DEFAULT_COLD_START_MAX_AGE_PHASES=3,OUTCOME_RANK_WEIGHT=0.1;var init_search_knowledge=__esm(()=>{init_schema();init_synonym_map();init_logger();init_knowledge_events();init_knowledge_reader();init_knowledge_store();init_knowledge_types()});var exports_knowledge_recall={};__export(exports_knowledge_recall,{knowledge_recall:()=>knowledge_recall,_internals:()=>_internals152});var knowledge_recall,_internals152;var init_knowledge_recall=__esm(()=>{init_zod();init_config();init_schema();init_search_knowledge();init_knowledge_diagnostics();init_logger();init_create_tool();knowledge_recall=createSwarmTool({description:"Performs semantic natural-language search across the knowledge base for relevant past decisions, patterns, and lessons learned. Returns ranked results via the unified hybrid retrieval service and a trace_id for knowledge_receipt. This is the tool to use when the user has a QUESTION about what the knowledge base contains. For structured filter-based retrieval (by category, status, or score), use `knowledge_query` instead.",args:{query:exports_external.string().min(3).describe("Natural language search query"),top_n:exports_external.number().int().min(1).max(20).optional().describe("Maximum results to return (default: 5)"),tier:exports_external.enum(["all","swarm","hive"]).optional().describe("Knowledge tier to search (default: 'all')"),debug:exports_external.boolean().optional().describe("Include path/version/health debug metadata in the response")},execute:async(args2,directory,ctx)=>{let queryInput,topNInput,tierInput,debugInput;try{if(args2&&typeof args2==="object"){let obj=args2;queryInput=obj.query,topNInput=obj.top_n,tierInput=obj.tier,debugInput=obj.debug}}catch{}let wantDebug=debugInput===!0;if(typeof queryInput!=="string"||queryInput.length<3)return JSON.stringify({results:[],total:0,error:"query must be a string with at least 3 characters"});let topN=5;if(typeof topNInput==="number"&&Number.isInteger(topNInput))topN=Math.max(1,Math.min(20,topNInput));let tier="all";if(tierInput==="swarm"||tierInput==="hive")tier=tierInput;let knowledgeConfig=KnowledgeConfigSchema.parse({});try{let{config:config3}=loadPluginConfigWithMeta(directory);knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch{}let{trace_id,results}=await searchKnowledge({directory,config:knowledgeConfig,query:queryInput,mode:"manual",agent:ctx?.agent??"unknown",sessionId:ctx?.sessionID??"unknown",tier,maxResults:topN,applyScopeFilter:!1,forceReadHive:!0,applyRoleScope:!1}),scored=results.map((e)=>({id:e.id,confidence:e.confidence,category:e.category,lesson:e.lesson,score:e.finalScore,score_breakdown:e.score_breakdown}));log("[knowledge_recall] completed",{agent:ctx?.agent??"unknown",session_id:ctx?.sessionID??"unknown",query:queryInput,tier,result_count:scored.length,trace_id});let result={results:scored,total:scored.length,trace_id};if(wantDebug)result.debug=await computeKnowledgeDebug(directory);return JSON.stringify(result)}}),_internals152={knowledge_recall}});var exports_prompt_renderer={};__export(exports_prompt_renderer,{renderEnvironmentPrompt:()=>renderEnvironmentPrompt});function renderEnvironmentPrompt(profile,audience){let policy=deriveCommandPolicy(profile),header=["RUNTIME ENVIRONMENT",`- Host OS: ${profile.hostOS}`,`- Shell family: ${profile.shellFamily}`,`- Execution mode: ${profile.executionMode}`,`- Path style: ${profile.pathStyle}`].join(`
|
|
@@ -5904,8 +5904,8 @@ ${originalText}`})}}init_constants();import*as path216 from"node:path";init_prof
|
|
|
5904
5904
|
`)state="code",out+=ch,i+=1;else{if(ch==="[")regexInClass=!0;else if(ch==="]")regexInClass=!1;else if(ch==="/"&&!regexInClass)state="code",prevSignificant="/";out+=ch,i+=1}break;case"line":if(ch===`
|
|
5905
5905
|
`)state="code",out+=ch;i+=1;break;case"block":if(ch==="*"&&next==="/")state="code",i+=2;else{if(ch===`
|
|
5906
5906
|
`)out+=ch;i+=1}break}}return out}function parseFileImports(rawContent,sourceFile,workspaceRoot){let ext=sourceFile?path210.extname(sourceFile).toLowerCase():"";if(ext===".py"||ext===".pyw")return parsePythonFileImports(rawContent,sourceFile);if(ext===".rs")return parseRustFileImports(rawContent,sourceFile,workspaceRoot);if(ext===".go")return parseGoFileImports(rawContent);let imports=[],content=stripComments2(rawContent),importRegex=/import\s+(?:\{[\s\S]*?\}|(?:\*\s+as\s+\w+)|\w+)\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s+['"`]([^'"`\0\t\r\n]+)['"`]|require\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)|export\s*\{[^}]*\}\s*from\s+['"`]([^'"`\0\t\r\n]+)['"`]|export\s+\*(?:\s+as\s+\w+)?\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)/g;for(let match of content.matchAll(importRegex)){let modulePath=match[1]||match[2]||match[3]||match[4]||match[5]||match[6];if(!modulePath)continue;if(containsControlChars(modulePath))continue;let matchedString=match[0],importType="named";if(matchedString.includes("* as"))importType="namespace";else if(/^import\s*\(/.test(matchedString))importType="sideeffect";else if(/^export\s*\{/.test(matchedString))importType="named";else if(/^export\s+\*/.test(matchedString))importType="namespace";else if(/^import\s+\{/.test(matchedString))importType="named";else if(/^import\s+\w+\s+from\s+['"`]/.test(matchedString))importType="default";else if(/^import\s+['"`]/m.test(matchedString))importType="sideeffect";else if(matchedString.includes("require("))importType="require";imports.push({specifier:modulePath,importType,importedSymbols:parseImportedSymbols(matchedString,importType),bindings:parseImportBindings(matchedString,importType),reExport:/^\s*export\b/.test(matchedString)})}return imports}function makeParsedImport(specifier,importType,bindings,reExport=!1){if(!specifier||containsControlChars(specifier))return null;return{specifier,importType,importedSymbols:bindings.map((binding)=>binding.imported),bindings,reExport}}function parsePythonFileImports(rawContent,sourceFile){let imports=[],isPackageInit=sourceFile?["__init__.py","__init__.pyw"].includes(path210.basename(sourceFile)):!1;for(let line of rawContent.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let fullImport=trimmed.match(/^import\s+(.+?)(?:\s*#.*)?$/);if(fullImport){for(let rawPart of fullImport[1].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^([\w.]+)\s+as\s+(\w+)$/),specifier=alias?alias[1]:part,local=alias?alias[2]:specifier.split(".")[0];if(!/^\w+$/.test(local))continue;let parsed2=makeParsedImport(specifier,"namespace",[{imported:specifier,local}]);if(parsed2)imports.push(parsed2)}continue}let fromImport=trimmed.match(/^from\s+(\S+)\s+import\s+(.+?)(?:\s*#.*)?$/);if(!fromImport)continue;if(fromImport[2].trim()==="*"){let parsed2=makeParsedImport(normalizePythonModuleSpecifier2(fromImport[1]),"namespace",[],isPackageInit);if(parsed2)imports.push(parsed2);continue}let bindings=[];for(let rawPart of fromImport[2].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^\w+$/.test(part))bindings.push({imported:part,local:part})}let parsed=makeParsedImport(normalizePythonModuleSpecifier2(fromImport[1]),"named",bindings,isPackageInit);if(parsed)imports.push(parsed)}return imports}function normalizePythonModuleSpecifier2(specifier){let leadingDots=specifier.match(/^\.+/)?.[0].length??0;if(leadingDots===0)return specifier;let rest=specifier.slice(leadingDots).replace(/\./g,"/");return`${leadingDots===1?"./":"../".repeat(leadingDots-1)}${rest}`}function rustModulePathToSpecifier(modulePath,sourceFile,workspaceRoot){let parts=modulePath.split("::").filter(Boolean);if(parts.length===0)return modulePath;if(parts[0]==="self")return`./${parts.slice(1).join("/")}`;if(parts[0]==="super"){let superCount=0;while(parts[superCount]==="super")superCount++;return`${"../".repeat(superCount)}${parts.slice(superCount).join("/")}`}if(parts[0]==="crate"&&sourceFile&&workspaceRoot){let target=path210.join(workspaceRoot,...parts.slice(1)),relative44=path210.relative(path210.dirname(sourceFile),target).replace(/\\/g,"/");if(!relative44.startsWith("."))relative44=`./${relative44}`;return relative44}return modulePath}function parseRustFileImports(rawContent,sourceFile,workspaceRoot){let imports=[];for(let line of rawContent.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed.startsWith("use "))continue;let grouped=trimmed.match(/^use\s+(.+?)::\{(.+)\}\s*;?\s*$/);if(grouped){let specifier2=rustModulePathToSpecifier(grouped[1].trim(),sourceFile,workspaceRoot),bindings=[];for(let rawPart of grouped[2].split(",")){let part=rawPart.trim();if(!part)continue;let alias2=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias2)bindings.push({imported:alias2[1],local:alias2[2]});else if(/^\w+$/.test(part)){let local2=part==="self"?grouped[1].split("::").pop()||grouped[1]:part;bindings.push({imported:part,local:local2})}}let parsed2=makeParsedImport(specifier2,"named",bindings);if(parsed2)imports.push(parsed2);continue}let simple=trimmed.match(/^use\s+(.+?)\s*;?\s*$/);if(!simple)continue;let rawPath=simple[1].trim(),alias=rawPath.match(/^(.+?)\s+as\s+(\w+)$/),fullPath=(alias?alias[1]:rawPath).trim(),parts=fullPath.split("::").filter(Boolean),imported=parts.pop()??fullPath,specifier=rustModulePathToSpecifier(parts.join("::")||fullPath,sourceFile,workspaceRoot),local=alias?alias[2]:imported,parsed=makeParsedImport(specifier,"named",/^\w+$/.test(imported)&&/^\w+$/.test(local)?[{imported,local}]:[]);if(parsed)imports.push(parsed)}return imports}function parseGoFileImports(rawContent){let imports=[],content=stripComments2(rawContent),parseSpec=(text)=>{let spec=text.trim();if(!spec)return;let aliased=spec.match(/^([\w._]+)\s+["`]([^"`]+)["`]$/);if(aliased){if(aliased[1]==="_"){let parsed2=makeParsedImport(aliased[2],"sideeffect",[]);if(parsed2)imports.push(parsed2);return}if(aliased[1]==="."){let parsed2=makeParsedImport(aliased[2],"namespace",[{imported:"*",local:"."}]);if(parsed2)imports.push(parsed2);return}let parsed=makeParsedImport(aliased[2],"named",[{imported:aliased[2],local:aliased[1]}]);if(parsed)imports.push(parsed);return}let simple=spec.match(/^["`]([^"`]+)["`]$/);if(simple){let parsed=makeParsedImport(simple[1],"namespace",[]);if(parsed)imports.push(parsed)}};for(let block of content.matchAll(/import\s*\(([\s\S]*?)\)/g))for(let line of block[1].split(/\r?\n/))parseSpec(line);let withoutBlocks=content.replace(/import\s*\([\s\S]*?\)/g,"");for(let match of withoutBlocks.matchAll(/^\s*import\s+(.+)$/gm))parseSpec(match[1]);return imports}function parseImportBindings(matchedString,importType){if(importType==="namespace")return[];if(importType==="default"){let defaultMatch=matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/);return defaultMatch?[{imported:"default",local:defaultMatch[1]}]:[]}if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let bindings=[],seen=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim().replace(/^type\s+/,"");if(!part)continue;let aliasSplit=part.split(/\s+as\s+/i),imported=aliasSplit[0].trim(),local=(aliasSplit[1]??aliasSplit[0]).trim();if(!/^[A-Za-z_$][\w$]*$/.test(imported))continue;if(!/^[A-Za-z_$][\w$]*$/.test(local))continue;if(seen.has(imported))continue;seen.add(imported),bindings.push({imported,local})}return bindings}var SAFE_USAGE_IDENTIFIER=/^[A-Za-z_][A-Za-z0-9_]*$/;function computeUsedSymbols(strippedContent,bindings){if(bindings.length===0)return[];let used=new Set;for(let binding of bindings){if(!SAFE_USAGE_IDENTIFIER.test(binding.local)){used.add(binding.imported);continue}let re=new RegExp(`\\b${binding.local}\\b`,"g"),count=0;for(let _match of strippedContent.matchAll(re))if(count++,count>1)break;if(count>1)used.add(binding.imported)}return[...used].sort((a,b)=>a.localeCompare(b))}function usedSymbolsForImport(parsed,strippedContent){if(parsed.importType==="namespace"||parsed.importType==="sideeffect"||parsed.importType==="require")return;if(parsed.reExport)return[...new Set(parsed.bindings.map((b)=>b.imported))].sort((a,b)=>a.localeCompare(b));return computeUsedSymbols(strippedContent,parsed.bindings)}function collectExports(symbols2){let exported=symbols2.filter((s)=>s.exported),exports=exported.map((s)=>s.signature===`default ${s.name}`?"default":s.name),exportLines={};for(let i=0;i<exported.length;i++){let s=exported[i],name=exports[i];if(typeof s.line==="number"&&Number.isFinite(s.line)&&exportLines[name]===void 0)exportLines[name]=s.line}return{exports,exportLines}}function parseImportedSymbols(matchedString,importType){if(importType==="namespace")return["*"];if(importType==="default")return matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/)?["default"]:[];if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let symbols2=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim();if(!part)continue;let cleaned=part.replace(/^type\s+/,"").split(/\s+as\s+/i)[0].trim();if(/^[A-Za-z_$][\w$]*$/.test(cleaned))symbols2.add(cleaned)}return[...symbols2].sort((a,b)=>a.localeCompare(b))}var MANIFEST_BASENAMES=new Set(["package.json","Cargo.toml","pyproject.toml","go.mod"]);function isGraphWideInputPath(filePath){return MANIFEST_BASENAMES.has(path210.basename(filePath))}function recordManifestDir(manifestDirs,absoluteRoot,dir,entryName){if(!MANIFEST_BASENAMES.has(entryName))return;let rel=path210.relative(absoluteRoot,dir).split(path210.sep).join("/");if(rel.startsWith("./"))rel=rel.slice(2);manifestDirs.add(rel)}function isWalkBudgetExceeded(ctx){if(ctx.abortReason!==void 0)return!0;if(_internals145.now()-ctx.startedAt>ctx.walkBudgetMs)return ctx.abortReason="budget",!0;return!1}function isFileCapReached(ctx,filesLength){if(filesLength>=ctx.maxFiles)return ctx.abortReason="cap",!0;return!1}async function canonicalDirKeyAsync(dir){try{return await fsPromises7.realpath(dir)}catch{return null}}async function walkRepoGraphInputs(dir,options){let absoluteRoot=path210.resolve(dir),stats2={filesScanned:0,skippedDirs:0,skippedFiles:0,truncated:!1,_absoluteRoot:absoluteRoot},ctx={stats:stats2,seenRealPaths:new Set,startedAt:_internals145.now(),walkBudgetMs:options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,maxFiles:options?.maxFiles??DEFAULT_WALK_FILE_CAP,followSymlinks:options?.followSymlinks??!1,skipDirs:resolveSkipDirectories(options?.excludeDirs),manifestDirs:new Set,manifestWitnesses:[]},files=[],manifestFiles=[],metadata=[],unreadableDirectories=[],unreadableFiles=[],queue=[absoluteRoot],processed=0;while(queue.length>0){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;let current=queue.shift(),key=await canonicalDirKeyAsync(current);if(key!==null){if(ctx.seenRealPaths.has(key)){ctx.stats.skippedDirs++;continue}ctx.seenRealPaths.add(key)}else unreadableDirectories.push(current);let entries;try{entries=await fsPromises7.readdir(current,{withFileTypes:!0})}catch{unreadableDirectories.push(current);continue}entries.sort((a,b)=>a.name.toLowerCase().localeCompare(b.name.toLowerCase()));let absoluteRoot2=ctx.stats._absoluteRoot;for(let entry of entries){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;if(ctx.skipDirs.has(entry.name)){ctx.stats.skippedDirs++;continue}let fullPath=path210.join(current,entry.name);if(entry.isSymbolicLink()&&!ctx.followSymlinks){ctx.stats.skippedDirs++;continue}if(entry.isDirectory())queue.push(fullPath);else if(entry.isFile()){if(absoluteRoot2!==void 0)recordManifestDir(ctx.manifestDirs,absoluteRoot2,current,entry.name);let ext=path210.extname(fullPath).toLowerCase(),isSource=SUPPORTED_EXTENSIONS.has(ext),isManifest=isGraphWideInputPath(fullPath);if(isSource)files.push(fullPath);if(isManifest)manifestFiles.push(fullPath);if(options?.captureMetadata&&(isSource||isManifest)||options?.captureManifestMetadata&&isManifest)try{let fileStats=await fsPromises7.stat(fullPath);metadata.push({absolutePath:fullPath,kind:isManifest?"manifest":"source",sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs})}catch{unreadableFiles.push(fullPath)}}if(processed++,processed%ASYNC_WALK_YIELD_INTERVAL===0)await yieldToEventLoop()}}if(ctx.abortReason==="cap"||ctx.abortReason==="budget")ctx.stats.truncated=!0;return{sourceFiles:files,manifestFiles,metadata,manifestDirs:ctx.manifestDirs,truncated:stats2.truncated,truncationReason:ctx.abortReason,incomplete:stats2.truncated||unreadableDirectories.length>0||unreadableFiles.length>0,unreadableDirectories,unreadableFiles,probedFiles:metadata.length,elapsedMs:Math.max(0,_internals145.now()-ctx.startedAt)}}function toModuleName(filePath,workspaceRoot){return path210.relative(workspaceRoot,filePath).split(path210.sep).join("/")}function getLanguage(filePath){let ext=path210.extname(filePath).toLowerCase(),jsFamilyLanguage=JS_FAMILY_EXTENSION_TO_LANGUAGE[ext];if(jsFamilyLanguage)return jsFamilyLanguage;return EXTENSION_TO_LANGUAGE[ext]??"unknown"}function isBinaryContent(content){if(content.includes("\x00"))return!0;return!1}function scanFile(filePath,absoluteRoot,maxFileSize,hasManifest){let content,fileStats;try{if(fileStats=fsSync12.statSync(filePath),fileStats.size>maxFileSize)return{node:null,edges:[]};content=fsSync12.readFileSync(filePath,"utf-8")}catch{return{node:null,edges:[]}}if(isBinaryContent(content))return{node:null,edges:[]};let ext=path210.extname(filePath).toLowerCase(),exports=[],exportLines={};try{if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(ext)){let relativePath2=path210.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals145.extractTSSymbols(relativePath2,absoluteRoot)))}else if(ext===".py"||ext===".pyw"){let relativePath2=path210.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals145.extractPythonSymbols(relativePath2,absoluteRoot)))}else if(ext===".rs"){let relativePath2=path210.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals145.extractRustSymbols(relativePath2,absoluteRoot)))}else if(ext===".go"){let relativePath2=path210.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals145.extractGoSymbols(relativePath2,absoluteRoot)))}let parsedImports=_internals145.parseFileImports(content,filePath,absoluteRoot),strippedForUsage=parsedImports.length>0?_internals145.stripComments(content):"",moduleName=toModuleName(filePath,absoluteRoot),node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},imports:parsedImports.map((p)=>p.specifier),language:getLanguage(filePath),mtime:fileStats.mtime.toISOString(),sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs,ontology:_internals145.extractFileOntology({moduleName,filePath,content,language:getLanguage(filePath),exports,imports:parsedImports.map((p)=>p.specifier),hasManifest})},edges=[],sortedImports=[...parsedImports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let parsed of sortedImports){let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,parsed.specifier);if(resolvedTarget!==null){let usedSymbols=usedSymbolsForImport(parsed,strippedForUsage);edges.push({source:filePath,target:resolvedTarget,importSpecifier:parsed.specifier,importType:parsed.importType,importedSymbols:parsed.importedSymbols,...usedSymbols!==void 0?{usedSymbols}:{},targetKind:isScannableSourcePath(resolvedTarget)?"node":"asset"})}}return{node,edges}}catch{return{node:null,edges:[]}}}async function scanFileAsync(filePath,absoluteRoot,maxFileSize,hasManifest){let content,fileStats;try{if(fileStats=await fsPromises7.stat(filePath),fileStats.size>maxFileSize){let moduleName2=toModuleName(filePath,absoluteRoot);return{node:null,edges:[],symbolEdges:[],diagnostics:{oversizedFiles:[moduleName2]},inputWitness:{file:moduleName2,kind:"stable-skip",sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs}}}content=await fsPromises7.readFile(filePath,"utf-8")}catch{return{node:null,edges:[],symbolEdges:[],diagnostics:{unreadableFiles:[toModuleName(filePath,absoluteRoot)]}}}if(isBinaryContent(content)){let moduleName2=toModuleName(filePath,absoluteRoot);return{node:null,edges:[],symbolEdges:[],diagnostics:{binaryFiles:[moduleName2]},inputWitness:{file:moduleName2,kind:"stable-skip",sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs}}}let grammarId=getLanguage(filePath),facts=await _internals145.extractFileSymbols(grammarId,content);if(facts===null){let fallback=scanFile(filePath,absoluteRoot,maxFileSize,hasManifest),parsedImports=[];try{parsedImports=_internals145.parseFileImports(content,filePath,absoluteRoot)}catch{parsedImports=[]}return{...fallback,symbolEdges:[],diagnostics:{extractionFailures:[{file:toModuleName(filePath,absoluteRoot),language:grammarId,reason:"symbol_extraction_failed"}],unresolvedImports:unresolvedRelativeImportsFor(parsedImports,filePath,absoluteRoot)}}}let exportedDefs=facts.defs.filter((d)=>d.exported),exports=exportedDefs.map((d)=>d.name),exportLines={},exportRanges={};for(let d of exportedDefs)exportLines[d.name]=d.startLine,exportRanges[d.name]={startLine:d.startLine,endLine:d.endLine};let exportsSet=new Set(exports),isPythonPackageInit=grammarId==="python"&&["__init__.py","__init__.pyw"].includes(path210.basename(filePath));for(let imp of facts.imports){let packageInitBindings=isPythonPackageInit&&imp.bindings.length>0?imp.bindings.filter((binding)=>!binding.local.startsWith("_")).map((binding)=>({imported:binding.imported,exported:binding.local})):[],exportedBindings=imp.reExport&&imp.exportedBindings?imp.exportedBindings:packageInitBindings;if(exportedBindings.length===0)continue;for(let binding of exportedBindings){if(binding.imported==="*"){if(!exportsSet.has(binding.exported))exportsSet.add(binding.exported),exports.push(binding.exported);if(imp.startLine!==void 0&&exportLines[binding.exported]===void 0)exportLines[binding.exported]=imp.startLine;if(imp.startLine!==void 0&&imp.endLine!==void 0&&exportRanges[binding.exported]===void 0)exportRanges[binding.exported]={startLine:imp.startLine,endLine:imp.endLine};continue}if(!exportsSet.has(binding.exported))exportsSet.add(binding.exported),exports.push(binding.exported);if(imp.startLine!==void 0&&exportLines[binding.exported]===void 0)exportLines[binding.exported]=imp.startLine;if(imp.startLine!==void 0&&imp.endLine!==void 0&&exportRanges[binding.exported]===void 0)exportRanges[binding.exported]={startLine:imp.startLine,endLine:imp.endLine}}}let imports=facts.imports.map((i)=>i.specifier),moduleName=toModuleName(filePath,absoluteRoot),language=grammarId,node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},...Object.keys(exportRanges).length>0?{exportRanges}:{},imports,language,mtime:fileStats.mtime.toISOString(),sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs,ontology:_internals145.extractFileOntology({moduleName,filePath,content,language,exports,imports,hasManifest})},edges=[],sortedImports=[...facts.imports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let imp of sortedImports){let edgeImportType=imp.importType==="commonjs"?"require":imp.importType,resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(resolvedTarget!==null){let usedBindings=imp.reExport?imp.bindings:imp.bindings.filter((b)=>facts.refs.some((r)=>r.identifier===b.local)),usedSymbols=edgeImportType!=="namespace"&&edgeImportType!=="require"&&edgeImportType!=="sideeffect"?usedBindings.map((b)=>b.imported):void 0;edges.push({source:filePath,target:resolvedTarget,importSpecifier:imp.specifier,importType:edgeImportType,importedSymbols:imp.bindings.map((b)=>b.imported),...usedSymbols!==void 0?{usedSymbols}:{},targetKind:isScannableSourcePath(resolvedTarget)?"node":"asset"})}}let unresolvedImports=sortedImports.filter((imp)=>isRelativeImportSpecifier(imp.specifier)).filter((imp)=>resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier)===null).map((imp)=>({file:moduleName,specifier:imp.specifier})),symbolEdges=[],localToImported=new Map;for(let imp of facts.imports){if(imp.reExport)continue;for(let binding of imp.bindings)localToImported.set(binding.local,{specifier:imp.specifier,imported:binding.imported})}let seenSymbolEdgeKeys=new Set;for(let ref of facts.refs){let mapping=localToImported.get(ref.identifier);if(!mapping)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,mapping.specifier);if(!resolvedTarget)continue;let fromSymbol=ref.enclosingDecl??"<module>",key=filePath+"\x00"+fromSymbol+"\x00"+resolvedTarget+"\x00"+mapping.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol,toFile:resolvedTarget,toSymbol:mapping.imported})}for(let imp of facts.imports){let packageInitBindings=isPythonPackageInit&&imp.bindings.length>0?imp.bindings.filter((binding)=>!binding.local.startsWith("_")).map((binding)=>({imported:binding.imported,exported:binding.local})):[],exportedBindings=imp.reExport&&imp.exportedBindings?imp.exportedBindings:packageInitBindings;if(exportedBindings.length===0)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(!resolvedTarget)continue;for(let binding of exportedBindings){if(binding.imported==="*")continue;let key=filePath+"\x00"+binding.exported+"\x00"+resolvedTarget+"\x00"+binding.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol:binding.exported,toFile:resolvedTarget,toSymbol:binding.imported})}}return{node,edges,symbolEdges,diagnostics:unresolvedImports.length>0?{unresolvedImports}:void 0}}async function buildWorkspaceGraphAsync(workspaceRoot,options){validateWorkspace(workspaceRoot);let maxFileSize=options?.maxFileSizeBytes??1048576,maxFiles=options?.maxFiles??DEFAULT_WALK_FILE_CAP,walkBudgetMs=options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,followSymlinks=options?.followSymlinks??!1,absoluteRoot=path210.resolve(workspaceRoot);if(!existsSync104(absoluteRoot))throw Error(`Workspace directory does not exist: ${workspaceRoot}`);if(isRefusedWorkspaceRoot(absoluteRoot))throw Error(`Refusing to scan top-level system path as workspace: ${absoluteRoot}. Set workspaceRoot to a project directory.`);let graph=createEmptyGraph(workspaceRoot),stats2={filesScanned:0,skippedDirs:0,skippedFiles:0,truncated:!1,_absoluteRoot:absoluteRoot},diagnostics=createEmptyDiagnostics(),walked=await walkRepoGraphInputs(absoluteRoot,{walkBudgetMs,maxFiles,followSymlinks,excludeDirs:options?.excludeDirs,captureManifestMetadata:!0}),sourceFiles=walked.sourceFiles;stats2.truncated=walked.truncated;for(let input of walked.metadata){if(input.kind!=="manifest")continue;let relative44=toModuleName(input.absolutePath,absoluteRoot);pushInputWitness(diagnostics.extractorInputWitnesses,{file:relative44,kind:"manifest",sizeBytes:input.sizeBytes,mtimeMs:input.mtimeMs})}if(sourceFiles.sort((a,b)=>{let normA=normalizeGraphPath(a),normB=normalizeGraphPath(b);return normA.localeCompare(normB)}),stats2.truncated)warn(`[repo-graph] Walk truncated: collected ${sourceFiles.length} files within ${walkBudgetMs}ms / ${maxFiles}-file budget.`);let hasManifest=(relDir)=>walked.manifestDirs.has(relDir),seenEdges=new Set,seenSymbolEdges=new Set,allSymbolEdges=[],processedSinceYield=0;for(let filePath of sourceFiles){let result=await scanFileAsync(filePath,absoluteRoot,maxFileSize,hasManifest);if(mergeDiagnostics(diagnostics,result.diagnostics),result.inputWitness)pushInputWitness(diagnostics.extractorInputWitnesses,result.inputWitness);if(result.node){let appended=!1;try{appendNodeFast(graph,result.node),appended=!0}catch{stats2.skippedFiles++,pushCapped(diagnostics.validationSkippedFiles,result.node.moduleName),pushInputWitness(diagnostics.extractorInputWitnesses,{file:result.node.moduleName,kind:"stable-skip",sizeBytes:result.node.sizeBytes,mtimeMs:result.node.mtimeMs})}if(appended){for(let edge of result.edges)try{appendEdgeFast(graph,edge,seenEdges)}catch{}for(let symbolEdge of result.symbolEdges){let key=symbolEdge.fromFile+"\x00"+symbolEdge.fromSymbol+"\x00"+symbolEdge.toFile+"\x00"+symbolEdge.toSymbol;if(!seenSymbolEdges.has(key))seenSymbolEdges.add(key),allSymbolEdges.push(symbolEdge)}stats2.filesScanned++}}else stats2.skippedFiles++;if(processedSinceYield++,processedSinceYield%ASYNC_SCAN_YIELD_INTERVAL===0)await yieldToEventLoop()}if(graph.metadata={generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length},allSymbolEdges.length>0)graph.symbolEdges=allSymbolEdges;if(diagnostics.walkTruncated=stats2.truncated,diagnostics.walkTruncationReason=walked.truncationReason,graph.diagnostics=diagnosticsHaveEntries(diagnostics)?diagnostics:createEmptyDiagnostics(),stats2.skippedFiles>0||stats2.skippedDirs>0||stats2.truncated)log(`[repo-graph] Scan stats: ${stats2.filesScanned} files scanned, ${stats2.skippedFiles} files skipped, ${stats2.skippedDirs} dirs skipped`+(stats2.truncated?", TRUNCATED":""));return graph}import*as path211 from"node:path";var MAX_CACHED_WORKSPACES=16,workspaceCache=new Map;function normalizeWorkspace(workspace){let resolved=path211.normalize(path211.resolve(workspace));return process.platform==="win32"?resolved.toLowerCase():resolved}function touch(key,entry){return workspaceCache.delete(key),workspaceCache.set(key,entry),entry}function getEntry(workspace){let key=normalizeWorkspace(workspace),entry=workspaceCache.get(key);return entry?touch(key,entry):void 0}function setEntry(workspace,entry){let key=normalizeWorkspace(workspace);touch(key,entry);while(workspaceCache.size>MAX_CACHED_WORKSPACES){let oldestKey=workspaceCache.keys().next().value;if(oldestKey===void 0)break;workspaceCache.delete(oldestKey)}}function getCachedGraph(workspace){return getEntry(workspace)?.graph}function setCachedGraph(workspace,graph,mtime){setEntry(workspace,{graph,dirty:!1,...mtime===void 0?{}:{mtime}})}function isDirty(workspace){return getEntry(workspace)?.dirty??!1}function clearCache(workspace){workspaceCache.delete(normalizeWorkspace(workspace))}function getCachedMtime(workspace){return getEntry(workspace)?.mtime}init_package();init_utils2();init_bun_compat();init_path_security();import{createHash as createHash40}from"node:crypto";import*as fsPromises8 from"node:fs/promises";import*as path212 from"node:path";var REPO_GRAPH_FINGERPRINT_FILENAME="repo-graph.fingerprint.json",FINGERPRINT_SCHEMA_VERSION=1,EXTRACTOR_STAMP=createHash40("sha256").update(`${package_default.version}\x00${GRAPH_SCHEMA_VERSION}`).digest("hex"),DEFAULT_WALK_BUDGET_MS2=5000,DEFAULT_MAX_FILES=1e4,CACHE_TTL_MS3=30000,MAX_CACHE_ENTRIES4=16,MAX_FINGERPRINT_BYTES=25165824,MAX_FINGERPRINT_ENTRIES=100256,MAX_RELATIVE_PATH_LENGTH=4096,WINDOWS_RENAME_MAX_RETRIES4=5,WINDOWS_RENAME_RETRY_DELAY_MS2=100,probeCache=new Map,_internals146={now:Date.now,walkRepoGraphInputs,open:fsPromises8.open,bunWrite,fsRename:fsPromises8.rename,fsUnlink:fsPromises8.unlink,retryDelayMs:WINDOWS_RENAME_RETRY_DELAY_MS2};function normalizeRoot(root){let resolved=path212.normalize(path212.resolve(root));return process.platform==="win32"?resolved.toLowerCase():resolved}function normalizedExcludes(options){return[...new Set((options?.excludeDirs??[]).filter(Boolean))].sort((a,b)=>a.localeCompare(b))}function exclusionStamp(options){return createHash40("sha256").update(JSON.stringify({excludeDirs:normalizedExcludes(options),followSymlinks:options?.followSymlinks??!1})).digest("hex")}function optionSignature(options){return JSON.stringify({walkBudgetMs:options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS2,maxFiles:options?.maxFiles??DEFAULT_MAX_FILES,followSymlinks:options?.followSymlinks??!1,excludeDirs:normalizedExcludes(options)})}function touchCache(rootKey,entry){probeCache.delete(rootKey),probeCache.set(rootKey,entry);while(probeCache.size>MAX_CACHE_ENTRIES4){let oldest=probeCache.keys().next().value;if(oldest===void 0)break;probeCache.delete(oldest)}}function invalidateFreshnessCache(root){if(root===void 0){probeCache.clear();return}probeCache.delete(normalizeRoot(root))}function fingerprintPath(root){let target=validateSwarmPath(root,REPO_GRAPH_FINGERPRINT_FILENAME);return validateSymlinkBoundary(target,root),target}async function writeFingerprintAtomic(root,data){let target=fingerprintPath(root),temp=path212.join(path212.dirname(target),`.repo-graph.fingerprint.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2,10)}.tmp`);validateSymlinkBoundary(temp,root);try{await _internals146.bunWrite(temp,data);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES4;attempt++)try{await _internals146.fsRename(temp,target),lastError=void 0;break}catch(error93){lastError=error93;let code=error93.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY"||attempt===WINDOWS_RENAME_MAX_RETRIES4-1)break;await new Promise((resolve78)=>setTimeout(resolve78,_internals146.retryDelayMs))}if(lastError!==void 0)throw lastError}finally{try{await _internals146.fsUnlink(temp)}catch{}}}async function refuseFingerprint(root){try{await _internals146.fsUnlink(fingerprintPath(root))}catch{}return invalidateFreshnessCache(root),!1}function safeRelativePath(value){if(value.length===0||value.length>MAX_RELATIVE_PATH_LENGTH||containsControlChars(value)||path212.isAbsolute(value)||/^[A-Za-z]:[/\\]/.test(value))return null;let normalized=value.replace(/\\/g,"/").replace(/^(?:\.\/)+/,"");if(normalized.length===0||normalized.split("/").some((segment)=>segment===".."||segment===""))return null;return normalized}function relativeFromRoot(root,absolutePath2){let relative45=path212.relative(path212.resolve(root),path212.resolve(absolutePath2));if(relative45.startsWith("..")||path212.isAbsolute(relative45))return null;return safeRelativePath(relative45)}function absoluteFromRelative(root,relativePath2){let safe=safeRelativePath(relativePath2);if(safe===null)return null;let resolvedRoot=path212.resolve(root),absolute=path212.resolve(resolvedRoot,safe),relative45=path212.relative(resolvedRoot,absolute);if(relative45.startsWith("..")||path212.isAbsolute(relative45))return null;return absolute}function validMetadata(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let record3=value;return Object.keys(record3).length===2&&typeof record3.size==="number"&&Number.isFinite(record3.size)&&record3.size>=0&&typeof record3.mtimeMs==="number"&&Number.isFinite(record3.mtimeMs)&&record3.mtimeMs>=0}function parseFingerprint(value,options){if(!value||typeof value!=="object"||Array.isArray(value))return null;let record3=value;if(Object.keys(record3).sort().join(",")!=="exclusionStamp,extractorStamp,files,schema_version"||record3.schema_version!==FINGERPRINT_SCHEMA_VERSION||record3.extractorStamp!==EXTRACTOR_STAMP||record3.exclusionStamp!==exclusionStamp(options)||!record3.files||typeof record3.files!=="object"||Array.isArray(record3.files))return null;let rawFiles=record3.files,entries=Object.entries(rawFiles);if(entries.length>MAX_FINGERPRINT_ENTRIES)return null;let files=Object.create(null);for(let[rawPath,metadata]of entries){let safe=safeRelativePath(rawPath);if(safe===null||safe!==rawPath||!validMetadata(metadata))return null;files[safe]=metadata}return{schema_version:FINGERPRINT_SCHEMA_VERSION,extractorStamp:EXTRACTOR_STAMP,exclusionStamp:exclusionStamp(options),files}}function emptyProbe(state,elapsedMs){return{state,changed:[],removed:[],truncated:!1,probedFiles:0,elapsedMs:Math.max(0,elapsedMs)}}async function readFingerprint(root,options){let target=fingerprintPath(root),handle=await _internals146.open(target,"r");try{let stats2=await handle.stat();if(stats2.size>MAX_FINGERPRINT_BYTES)return null;let buffer=Buffer.alloc(stats2.size),offset=0;while(offset<buffer.length){let read=await handle.read(buffer,offset,buffer.length-offset,offset);if(read.bytesRead===0)break;offset+=read.bytesRead}let data=buffer.subarray(0,offset).toString("utf8");return parseFingerprint(JSON.parse(data),options)}finally{await handle.close()}}async function probeUncached(root,options){let startedAt=_internals146.now(),fingerprint;try{fingerprint=await readFingerprint(root,options)}catch{fingerprint=null}if(fingerprint===null)return emptyProbe("no-fingerprint",_internals146.now()-startedAt);let walk;try{walk=await _internals146.walkRepoGraphInputs(root,{walkBudgetMs:options?.walkBudgetMs,maxFiles:options?.maxFiles,followSymlinks:options?.followSymlinks,excludeDirs:options?.excludeDirs,captureMetadata:!0})}catch{return{...emptyProbe("inconclusive",_internals146.now()-startedAt),truncated:!1}}let current=new Map,changed=[];for(let input of walk.metadata){let relative45=relativeFromRoot(root,input.absolutePath);if(relative45===null)continue;let metadata={size:input.sizeBytes,mtimeMs:input.mtimeMs};current.set(relative45,metadata);let previous=fingerprint.files[relative45];if(previous===void 0||previous.size!==metadata.size||previous.mtimeMs!==metadata.mtimeMs)changed.push(path212.resolve(input.absolutePath))}let incomplete=walk.incomplete,removed=[];if(!incomplete){for(let relative45 of Object.keys(fingerprint.files))if(!current.has(relative45)){let absolute=absoluteFromRelative(root,relative45);if(absolute!==null)removed.push(absolute)}}return changed.sort((a,b)=>a.localeCompare(b)),removed.sort((a,b)=>a.localeCompare(b)),{state:incomplete?"inconclusive":changed.length>0||removed.length>0?"drifted":"clean",changed,removed:incomplete?[]:removed,truncated:walk.truncated,probedFiles:walk.probedFiles,elapsedMs:Math.max(0,_internals146.now()-startedAt)}}async function probeFreshness(root,options){let rootKey=normalizeRoot(root),signature=optionSignature(options),now=_internals146.now(),cached3=probeCache.get(rootKey);if(cached3?.signature===signature){if(cached3.value&&cached3.expiresAt>now)return touchCache(rootKey,cached3),cached3.value;if(cached3.inFlight)return touchCache(rootKey,cached3),cached3.inFlight}let inFlight=probeUncached(root,options),entry={signature,expiresAt:0,inFlight};touchCache(rootKey,entry);try{let value=await inFlight;if(probeCache.get(rootKey)?.inFlight===inFlight)entry.value=value,entry.expiresAt=_internals146.now()+CACHE_TTL_MS3,entry.inFlight=void 0,touchCache(rootKey,entry);return value}catch{if(probeCache.get(rootKey)?.inFlight===inFlight)probeCache.delete(rootKey);return emptyProbe("inconclusive",0)}}function diagnosticPaths(root,diagnostics){let reportedStable=new Set;for(let raw of[...diagnostics?.oversizedFiles??[],...diagnostics?.binaryFiles??[],...diagnostics?.validationSkippedFiles??[]]){let safe=safeRelativePath(raw);if(safe===null)return null;if(absoluteFromRelative(root,safe)===null)return null;reportedStable.add(safe)}let witnesses=new Map,stable=new Set;for(let witness of diagnostics?.extractorInputWitnesses??[]){let safe=safeRelativePath(witness.file);if(safe===null||witness.kind!=="manifest"&&witness.kind!=="stable-skip"||!Number.isFinite(witness.sizeBytes)||witness.sizeBytes<0||!Number.isFinite(witness.mtimeMs)||witness.mtimeMs<0||witnesses.has(safe))return null;if(witnesses.set(safe,{...witness,file:safe}),witness.kind==="stable-skip")stable.add(safe)}for(let relative45 of reportedStable)if(witnesses.get(relative45)?.kind!=="stable-skip")return null;return{stable,witnesses}}async function writeFingerprint(root,graph,options){invalidateFreshnessCache(root);try{let walk=await _internals146.walkRepoGraphInputs(root,{walkBudgetMs:options?.walkBudgetMs,maxFiles:options?.maxFiles,followSymlinks:options?.followSymlinks,excludeDirs:options?.excludeDirs,captureMetadata:!0});if(walk.unreadableDirectories.length>0||walk.unreadableFiles.length>0)return refuseFingerprint(root);let certifiedInputs=diagnosticPaths(root,graph.diagnostics);if(certifiedInputs===null)return refuseFingerprint(root);let current=new Map;for(let input of walk.metadata){let relative45=relativeFromRoot(root,input.absolutePath);if(relative45===null)return refuseFingerprint(root);current.set(relative45,{size:input.sizeBytes,mtimeMs:input.mtimeMs})}for(let[relative45,witness]of certifiedInputs.witnesses){let observed=current.get(relative45);if(observed===void 0||observed.size!==witness.sizeBytes||observed.mtimeMs!==witness.mtimeMs)return refuseFingerprint(root)}let nodePaths=new Set;for(let node of Object.values(graph.nodes)){let relative45=relativeFromRoot(root,node.filePath);if(relative45===null)return refuseFingerprint(root);if(typeof node.sizeBytes!=="number"||!Number.isFinite(node.sizeBytes)||node.sizeBytes<0||typeof node.mtimeMs!=="number"||!Number.isFinite(node.mtimeMs)||node.mtimeMs<0)return refuseFingerprint(root);let observed=current.get(relative45);if(observed===void 0||observed.size!==node.sizeBytes||observed.mtimeMs!==node.mtimeMs)return refuseFingerprint(root);nodePaths.add(relative45)}for(let input of walk.metadata){let relative45=relativeFromRoot(root,input.absolutePath);if(relative45===null)return refuseFingerprint(root);if(input.kind==="manifest"&&certifiedInputs.witnesses.get(relative45)?.kind!=="manifest")return refuseFingerprint(root);if(input.kind!=="source")continue;if(!nodePaths.has(relative45)&&!certifiedInputs.stable.has(relative45))return refuseFingerprint(root)}let files=Object.create(null);for(let relative45 of[...current.keys()].sort((a,b)=>a.localeCompare(b)))files[relative45]=current.get(relative45);if(Object.keys(files).length>MAX_FINGERPRINT_ENTRIES)return refuseFingerprint(root);let sidecar={schema_version:FINGERPRINT_SCHEMA_VERSION,extractorStamp:EXTRACTOR_STAMP,exclusionStamp:exclusionStamp(options),files},serialized3=`${JSON.stringify(sidecar,null,2)}
|
|
5907
|
-
`;if(Buffer.byteLength(serialized3,"utf8")>MAX_FINGERPRINT_BYTES)return refuseFingerprint(root);return await writeFingerprintAtomic(root,serialized3),invalidateFreshnessCache(root),!0}catch{return refuseFingerprint(root)}}init_logger();init_path_security();import{existsSync as existsSync106,readdirSync as readdirSync32}from"node:fs";import*as fsPromises10 from"node:fs/promises";import*as path215 from"node:path";init_path_security();import*as path213 from"node:path";var GRAPH_HEALTH_OUTPUT_LIMIT=50,MAX_HEALTH_PATH_LENGTH=500,cachedReverseIndex=null;function normalizeLookupPath(input){return normalizeGraphPath(input).replace(/^(?:\.\/)+/,"")}function graphRoot(graph){return path213.resolve(graph.workspaceRoot)}function toModuleName2(graph,input){let normalized=normalizeLookupPath(input);if(path213.isAbsolute(normalized)||/^[A-Za-z]:\//.test(normalized))return normalizeLookupPath(path213.relative(graphRoot(graph),normalized));return normalized}function absoluteKeyForModule(graph,moduleName){return normalizeGraphPath(path213.resolve(graphRoot(graph),moduleName))}function getGraphNode(graph,input){let moduleName=toModuleName2(graph,input),direct=graph.nodes[absoluteKeyForModule(graph,moduleName)];if(direct)return direct;return getQueryIndexes(graph).moduleNameIndex.get(moduleName)}function moduleNameForEdgePath(graph,edgePath){let key=normalizeGraphPath(edgePath),node=graph.nodes[key];if(node)return normalizeLookupPath(node.moduleName);return normalizeLookupPath(path213.relative(graphRoot(graph),edgePath))}function buildReverseIndex(graph){let reverse=new Map,forward=new Map,moduleNameIndex=new Map;for(let node of Object.values(graph.nodes))moduleNameIndex.set(normalizeLookupPath(node.moduleName),node);for(let edge of graph.edges){if(isAssetEdge(edge))continue;let source=normalizeGraphPath(edge.source),target=normalizeGraphPath(edge.target),sourceRef={file:moduleNameForEdgePath(graph,edge.source),importType:edge.importType},targetRef={file:moduleNameForEdgePath(graph,edge.target),importType:edge.importType},reverseRefs=reverse.get(target);if(reverseRefs)reverseRefs.push(sourceRef);else reverse.set(target,[sourceRef]);let forwardRefs=forward.get(source);if(forwardRefs)forwardRefs.push(targetRef);else forward.set(source,[targetRef])}for(let refs of reverse.values())refs.sort((a,b)=>a.file.localeCompare(b.file));for(let refs of forward.values())refs.sort((a,b)=>a.file.localeCompare(b.file));return cachedReverseIndex={graph,index:reverse,forwardIndex:forward,moduleNameIndex},reverse}function getQueryIndexes(graph){if(cachedReverseIndex&&cachedReverseIndex.graph===graph)return cachedReverseIndex;return buildReverseIndex(graph),cachedReverseIndex}function getReverseIndex(graph){return getQueryIndexes(graph).index}function getForwardIndex(graph){return getQueryIndexes(graph).forwardIndex}function resetQueryCache(){cachedReverseIndex=null}function isSafeHealthPath(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value)||containsPathTraversal(value))return!1;if(path213.isAbsolute(value)||/^[A-Za-z]:[\\/]/.test(value))return!1;return!0}function isSafeHealthText(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value))return!1;return!0}function cap(entries){return entries.slice(0,GRAPH_HEALTH_OUTPUT_LIMIT)}function sanitizeExtractionFailures(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.language)&&isSafeHealthText(entry.reason))entries.push({file:entry.file,language:entry.language,reason:entry.reason})}return cap(entries)}function sanitizeUnresolvedImports(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.specifier))entries.push({file:entry.file,specifier:entry.specifier})}return cap(entries)}function sanitizePathList(value){if(!Array.isArray(value))return[];return cap(value.filter(isSafeHealthPath))}function getProbeStaleFiles(probe2,workspaceRoot){if(!probe2)return[];let root=path213.resolve(workspaceRoot),stale=new Set;for(let absolutePath2 of[...probe2.changed,...probe2.removed]){if(typeof absolutePath2!=="string"||!path213.isAbsolute(absolutePath2))continue;let relative46=normalizeGraphPath(path213.relative(root,absolutePath2));if(!isSafeHealthPath(relative46))continue;stale.add(relative46)}return[...stale].sort((a,b)=>a.localeCompare(b)).slice(0,GRAPH_HEALTH_OUTPUT_LIMIT)}function getGraphHealth(graph,workspaceRoot,probe2){let probeState=probe2?.state??"no-fingerprint";if(!graph)return{schemaVersion:null,fresh:!1,probeState,staleFiles:[],extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],validationSkippedFiles:[],lowConfidenceEdgeCount:0,walkTruncated:!1,walkTruncationReason:null,incrementalFallbacks:0,notes:['No repo graph found at .swarm/repo-graph.json. Run repo_map with action="build" first.']};let diagnostics=graph.diagnostics,fresh=probeState==="clean",staleFiles=getProbeStaleFiles(probe2,workspaceRoot??graph.workspaceRoot),notes=[];if(probeState==="drifted")notes.push('Graph content is stale relative to the workspace. Run repo_map with action="build" if automatic refresh is unavailable.');else if(probeState==="no-fingerprint")notes.push('Graph has no matching content fingerprint. Run repo_map with action="build" to certify it.');else if(probeState==="inconclusive")notes.push("Graph freshness is unknown because the bounded workspace probe did not complete; no refresh or deletion was attempted.");if(!diagnostics)notes.push('Graph has no recorded diagnostics. Rebuild with repo_map action="build" to collect health details.');let binaryFiles=sanitizePathList(diagnostics?.binaryFiles),binaryCount=binaryFiles.length;if(binaryCount>0)notes.push(`${binaryCount} binary files skipped during last build.`);let unreadableFiles=sanitizePathList(diagnostics?.unreadableFiles),unreadableCount=unreadableFiles.length;if(unreadableCount>0)notes.push(`${unreadableCount} unreadable files skipped during last build.`);let walkTruncated=diagnostics?.walkTruncated===!0,rawReason=diagnostics?.walkTruncationReason,walkTruncationReason=rawReason==="budget"||rawReason==="cap"?rawReason:null,incrementalFallbacks=typeof diagnostics?.incrementalFallbacks==="number"&&Number.isFinite(diagnostics.incrementalFallbacks)&&diagnostics.incrementalFallbacks>0?Math.floor(diagnostics.incrementalFallbacks):0;if(walkTruncated)notes.push("Graph is INCOMPLETE: walk hit the file-cap/wall-clock budget — results may be missing files."+(walkTruncationReason?` (reason: ${walkTruncationReason})`:""));if(incrementalFallbacks>0)notes.push(`${incrementalFallbacks} incremental update(s) fell back to a full rebuild (validation failure or concurrent modification).`);return{schemaVersion:graph.schema_version,fresh,probeState,staleFiles,extractionFailures:sanitizeExtractionFailures(diagnostics?.extractionFailures),unresolvedImports:sanitizeUnresolvedImports(diagnostics?.unresolvedImports),oversizedFiles:sanitizePathList(diagnostics?.oversizedFiles),unsupportedFiles:sanitizePathList(diagnostics?.unsupportedFiles),binaryFiles,unreadableFiles,validationSkippedFiles:sanitizePathList(diagnostics?.validationSkippedFiles),lowConfidenceEdgeCount:typeof diagnostics?.lowConfidenceEdgeCount==="number"&&Number.isFinite(diagnostics.lowConfidenceEdgeCount)&&diagnostics.lowConfidenceEdgeCount>0?Math.floor(diagnostics.lowConfidenceEdgeCount):0,walkTruncated,walkTruncationReason,incrementalFallbacks,notes}}function getImporters(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];return getReverseIndex(graph).get(normalizeGraphPath(node.filePath))??[]}function getDependencies(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];let sourceKey=normalizeGraphPath(node.filePath);return getForwardIndex(graph).get(sourceKey)??[]}function getSymbolConsumers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[];for(let edge of graph.edges){if(isAssetEdge(edge))continue;if(normalizeGraphPath(edge.target)!==targetKey)continue;let importedSymbols=edge.importedSymbols??[];if(edge.importType==="namespace"){refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:"*"});continue}if(importedSymbols.includes(symbolName))refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:symbolName})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}function getCallers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[],seen=new Set;for(let edge of graph.edges){if(isAssetEdge(edge))continue;if(normalizeGraphPath(edge.target)!==targetKey)continue;let file3=moduleNameForEdgePath(graph,edge.source);if(seen.has(file3))continue;if(edge.usedSymbols!==void 0){if(edge.usedSymbols.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"used"});continue}let imported=edge.importedSymbols??[];if(edge.importType==="namespace"||imported.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"imported"})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}var DEAD_EXPORT_EXCLUDED_ROLES=new Set(["api_route","cli_command","test_file","agent","hook","middleware"]);function getDeadExports(graph,options){if(!isSchemaVersionAtLeast(graph.schema_version,"1.1.0"))return{schemaSupported:!1,analyzedFiles:0,skippedUnresolvable:0,candidates:[],note:'Graph predates schema 1.1.0 (no usedSymbols data). Run repo_map action="build" to enable dead_exports.'};let usage=new Map;for(let edge of graph.edges){if(isAssetEdge(edge))continue;let target=normalizeGraphPath(edge.target),entry=usage.get(target);if(!entry)entry={used:new Set,unresolvable:!1},usage.set(target,entry);if(edge.importType==="namespace"||edge.importType==="sideeffect"||edge.importType==="require")entry.unresolvable=!0;else if(edge.usedSymbols)for(let symbol3 of edge.usedSymbols)entry.used.add(symbol3)}let reverse=getReverseIndex(graph),candidates=[],analyzedFiles=0,skippedUnresolvable=0;for(let node of Object.values(graph.nodes)){if(node.exports.length===0)continue;let key=normalizeGraphPath(node.filePath),importerCount=reverse.get(key)?.length??0;if(importerCount===0)continue;if((node.ontology?.roles??[]).some((r)=>DEAD_EXPORT_EXCLUDED_ROLES.has(r)))continue;let entry=usage.get(key);if(entry?.unresolvable){skippedUnresolvable++;continue}analyzedFiles++;let used=entry?.used??new Set;for(let symbol3 of node.exports){if(symbol3==="default")continue;if(used.has(symbol3))continue;candidates.push({file:node.moduleName,symbol:symbol3,line:node.exportLines?.[symbol3],importerCount})}}candidates.sort((a,b)=>a.file.localeCompare(b.file)||a.symbol.localeCompare(b.symbol));let limit=options?.maxCandidates??100,truncated=candidates.length>limit;return{schemaSupported:!0,analyzedFiles,skippedUnresolvable,candidates:candidates.slice(0,limit),note:"Advisory: exported symbols with no detected in-repo reference, limited to files imported by >=1 other file. Regex analysis cannot see dynamic dispatch, string-keyed access, or namespace/barrel re-export usage; verify before removing."+(truncated?` Showing ${limit} of ${candidates.length}.`:"")}}function getBlastRadius(graph,filePaths,maxDepth=3){let targetNodes=filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0),targets=targetNodes.map((node)=>normalizeLookupPath(node.moduleName));if(maxDepth<=0||targetNodes.length===0)return{target:filePaths.map((filePath)=>toModuleName2(graph,filePath)),directDependents:[],transitiveDependents:[],depthReached:0,totalDependents:0,riskLevel:"low"};let reverse=getReverseIndex(graph),visited=new Set(targetNodes.map((node)=>normalizeGraphPath(node.filePath))),direct=new Set,transitive=new Set,depthReached=0,queue=targetNodes.map((node)=>({key:normalizeGraphPath(node.filePath),depth:0}));while(queue.length>0){let next=[];for(let{key,depth}of queue){let importers=reverse.get(key)??[];for(let ref of importers){let importerNode=getGraphNode(graph,ref.file);if(!importerNode)continue;let importerKey=normalizeGraphPath(importerNode.filePath);if(visited.has(importerKey))continue;if(visited.add(importerKey),depth===0)direct.add(ref.file);else transitive.add(ref.file);if(depthReached=Math.max(depthReached,depth+1),depth+1<maxDepth)next.push({key:importerKey,depth:depth+1})}}queue=next}let totalDependents=direct.size+transitive.size;return{target:targets,directDependents:[...direct].sort(),transitiveDependents:[...transitive].sort(),depthReached,totalDependents,riskLevel:classifyRisk(totalDependents)}}function classifyRisk(count){if(count<=3)return"low";if(count<=10)return"medium";if(count<=25)return"high";return"critical"}function getKeyFiles(graph,topN=10){let reverse=getReverseIndex(graph),scored=Object.values(graph.nodes).map((node)=>({node,inDegree:reverse.get(normalizeGraphPath(node.filePath))?.length??0}));return scored.sort((a,b)=>{if(b.inDegree!==a.inDegree)return b.inDegree-a.inDegree;return a.node.moduleName.localeCompare(b.node.moduleName)}),scored.slice(0,topN).map((item)=>item.node)}function getFileOntology(graph,filePath){return getGraphNode(graph,filePath)?.ontology??null}function getLocalizationContext(graph,filePath,options={}){let target=toModuleName2(graph,filePath),node=getGraphNode(graph,target),importers=getImporters(graph,target),dependencies=getDependencies(graph,target),blast=getBlastRadius(graph,[target],options.maxDepth??2),externalSymbols=collectExternallyUsedSymbols(graph,node),summary=formatLocalizationSummary({target,importers,dependencies,blast,externalSymbols,ontology:node?.ontology??null,maxImporters:options.maxImporters??5,maxDeps:options.maxDeps??5});return{target,importerCount:importers.length,importers:importers.slice(0,options.maxImporters??5),dependencyCount:dependencies.length,dependencies:dependencies.slice(0,options.maxDeps??5),exportedSymbolsUsedExternally:externalSymbols,blastRadius:blast,summary}}function getContextPack(graph,file3,symbol3,options={}){if(!isSchemaVersionAtLeast(graph.schema_version,"1.2.0"))return{schemaSupported:!1,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:'rebuild with repo_map action="build"'};let maxDepth=options.maxDepth??2,maxTokens=options.maxTokens??4000,targetNode=getGraphNode(graph,file3);if(!targetNode)return{schemaSupported:!0,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:"Target file not found in graph"};let targetFile=normalizeGraphPath(targetNode.filePath),forward=new Map,reverse=new Map,symbolEdges=graph.symbolEdges??[];for(let edge of symbolEdges){let fromKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`,toKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`,fromEdges=forward.get(fromKey);if(fromEdges)fromEdges.push(edge);else forward.set(fromKey,[edge]);let toEdges=reverse.get(toKey);if(toEdges)toEdges.push(edge);else reverse.set(toKey,[edge])}let targetKey=`${targetFile}\x00${symbol3}`,visited=new Map,queue=[{key:targetKey,depth:0}];visited.set(targetKey,0);let reached=[],queueHead=0;while(queueHead<queue.length){let{key,depth}=queue[queueHead];queueHead++;let[curFile,curSymbol]=key.split("\x00",2);if(reached.push({file:curFile,symbol:curSymbol,depth}),depth>=maxDepth)continue;let outEdges=forward.get(key)??[];for(let edge of outEdges){let nextKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}let inEdges=reverse.get(key)??[];for(let edge of inEdges){let nextKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}}let TOKENS_PER_LINE=12,TOKENS_PER_SIGNATURE=10,spansWithDepth=[];for(let{file:symFile,symbol:sym,depth:d}of reached){let range=graph.nodes[symFile]?.exportRanges?.[sym];if(!range)continue;let mode=d===0?"full":d<maxDepth?"full":"signature";spansWithDepth.push({span:{file:symFile,symbol:sym,startLine:range.startLine,endLine:range.endLine,mode},depth:d})}spansWithDepth.sort((a,b)=>{let aIsTarget=a.span.file===targetFile&&a.span.symbol===symbol3?0:1,bIsTarget=b.span.file===targetFile&&b.span.symbol===symbol3?0:1;if(aIsTarget!==bIsTarget)return aIsTarget-bIsTarget;if(a.depth!==b.depth)return a.depth-b.depth;let fileCmp=a.span.file.localeCompare(b.span.file);if(fileCmp!==0)return fileCmp;return a.span.symbol.localeCompare(b.span.symbol)});let estimatedTokens=0,finalSpans=[],truncated=!1;for(let{span}of spansWithDepth){let spanTokens=span.mode==="full"?(span.endLine-span.startLine+1)*TOKENS_PER_LINE:TOKENS_PER_SIGNATURE;if(finalSpans.length>0&&estimatedTokens+spanTokens>maxTokens){truncated=!0;break}finalSpans.push(span),estimatedTokens+=spanTokens}return{schemaSupported:!0,target:{file:targetFile,symbol:symbol3},spans:finalSpans,truncated,estimatedTokens}}function collectExternallyUsedSymbols(graph,node){if(!node)return[];let exported=new Set(node.exports),used=new Set,targetKey=normalizeGraphPath(node.filePath);for(let edge of graph.edges){if(isAssetEdge(edge))continue;if(normalizeGraphPath(edge.target)!==targetKey)continue;for(let symbol3 of edge.importedSymbols??[])if(exported.has(symbol3))used.add(symbol3)}return[...used].sort((a,b)=>a.localeCompare(b))}function formatLocalizationSummary(opts){let importerList=opts.importers.length===0?"(none)":opts.importers.slice(0,opts.maxImporters).map((ref)=>ref.file).join(", ")+(opts.importers.length>opts.maxImporters?`, +${opts.importers.length-opts.maxImporters} more`:""),depList=opts.dependencies.length===0?"(none)":opts.dependencies.slice(0,opts.maxDeps).map((ref)=>ref.file).join(", ")+(opts.dependencies.length>opts.maxDeps?`, +${opts.dependencies.length-opts.maxDeps} more`:""),symbolList=opts.externalSymbols.length===0?"(none used externally)":opts.externalSymbols.slice(0,8).join(", ")+(opts.externalSymbols.length>8?`, +${opts.externalSymbols.length-8} more`:""),roles=opts.ontology?.roles.join(", ")||"unknown",findings=opts.ontology?.findings.length??0;return["LOCALIZATION CONTEXT",` Target: ${opts.target}`,` Roles: ${roles}`,` Imported by (${opts.importers.length}): ${importerList}`,` Imports (${opts.dependencies.length}): ${depList}`,` Exports used externally: ${symbolList}`,` Blast radius: ${opts.blast.totalDependents} files (${opts.blast.riskLevel} risk)`,` Ontology findings: ${findings}`].join(`
|
|
5908
|
-
`)}function getPackageBoundaries(graph,topN=25){return summarizePackageBoundaries(Object.values(graph.nodes),graph.edges,topN)}function summarizePackageBoundaries(nodes,edges,topN){let groups=new Map,ensure=(node)=>{let name=node.ontology?.packageBoundary||inferBoundary(node.moduleName),group=groups.get(name);if(!group)group={name,root:name,fileCount:0,roles:{},dependsOn:[],dependedOnBy:[],routeCount:0,dataOperationCount:0,findingCount:0,publicFiles:[]},groups.set(name,group);return group},boundaryByPath=new Map;for(let node of nodes){let group=ensure(node);boundaryByPath.set(normalizeGraphPath(node.filePath),group.name),group.fileCount++;let ontology=node.ontology;for(let role of ontology?.roles??["source_module"])group.roles[role]=(group.roles[role]??0)+1;if(group.routeCount+=ontology?.routes.length??0,group.dataOperationCount+=ontology?.dataOperations.length??0,group.findingCount+=ontology?.findings.length??0,node.exports.length>0)group.publicFiles.push(node.moduleName)}let dependsOn=new Map,dependedOnBy=new Map;for(let edge of edges){if(isAssetEdge(edge))continue;let sourceBoundary=boundaryByPath.get(normalizeGraphPath(edge.source)),targetBoundary=boundaryByPath.get(normalizeGraphPath(edge.target));if(!sourceBoundary||!targetBoundary||sourceBoundary===targetBoundary)continue;if(!dependsOn.has(sourceBoundary))dependsOn.set(sourceBoundary,new Set);if(!dependedOnBy.has(targetBoundary))dependedOnBy.set(targetBoundary,new Set);dependsOn.get(sourceBoundary)?.add(targetBoundary),dependedOnBy.get(targetBoundary)?.add(sourceBoundary)}for(let group of groups.values())group.dependsOn=[...dependsOn.get(group.name)??[]].sort(),group.dependedOnBy=[...dependedOnBy.get(group.name)??[]].sort(),group.publicFiles.sort((a,b)=>a.localeCompare(b)),group.publicFiles=group.publicFiles.slice(0,20);return[...groups.values()].sort((a,b)=>{if(b.findingCount!==a.findingCount)return b.findingCount-a.findingCount;if(b.fileCount!==a.fileCount)return b.fileCount-a.fileCount;return a.name.localeCompare(b.name)}).slice(0,topN)}function summarizeSelectedPackageBoundaries(graph,nodes,topN=25){let summaries=summarizePackageBoundaries(nodes,[],topN),boundaryByModule=new Map;for(let node of nodes)boundaryByModule.set(normalizeLookupPath(node.moduleName),node.ontology?.packageBoundary??inferBoundary(node.moduleName));let byName=new Map(summaries.map((summary)=>[summary.name,summary])),dependsOn=new Map,dependedOnBy=new Map;for(let node of nodes){let sourceBoundary=boundaryByModule.get(normalizeLookupPath(node.moduleName));if(!sourceBoundary)continue;for(let dep of getDependencies(graph,node.moduleName)){let targetBoundary=boundaryByModule.get(normalizeLookupPath(dep.file));if(!targetBoundary||sourceBoundary===targetBoundary||!byName.has(sourceBoundary)||!byName.has(targetBoundary))continue;if(!dependsOn.has(sourceBoundary))dependsOn.set(sourceBoundary,new Set);if(!dependedOnBy.has(targetBoundary))dependedOnBy.set(targetBoundary,new Set);dependsOn.get(sourceBoundary)?.add(targetBoundary),dependedOnBy.get(targetBoundary)?.add(sourceBoundary)}}for(let summary of summaries)summary.dependsOn=[...dependsOn.get(summary.name)??[]].sort(),summary.dependedOnBy=[...dependedOnBy.get(summary.name)??[]].sort();return summaries}function inferBoundary(moduleName){return inferPackageBoundary(moduleName)}function buildOntologyPreflightPacket(graph,filePaths=[],options={}){let maxFiles=options.maxFiles??12,maxFindings=options.maxFindings??20,boundedNodes=(filePaths.length>0?filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0):getKeyFiles(graph,maxFiles)).slice(0,maxFiles),findings=boundedNodes.flatMap((node)=>(node.ontology?.findings??[]).map((finding)=>({file:node.moduleName,...finding}))).slice(0,maxFindings),routes=boundedNodes.flatMap((node)=>(node.ontology?.routes??[]).map((route)=>({file:node.moduleName,...route}))),dataOperations=boundedNodes.flatMap((node)=>(node.ontology?.dataOperations??[]).map((fact)=>({file:node.moduleName,...fact}))),security=boundedNodes.flatMap((node)=>(node.ontology?.security??[]).map((fact)=>({file:node.moduleName,...fact})));return{generatedAt:new Date().toISOString(),targets:boundedNodes.map((node)=>node.moduleName),summary:{fileCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length,targetCount:boundedNodes.length,findingCount:findings.length,routeCount:routes.length,dataOperationCount:dataOperations.length,securityFactCount:security.length},files:boundedNodes.map((node)=>({file:node.moduleName,roles:node.ontology?.roles??[],packageBoundary:node.ontology?.packageBoundary??inferBoundary(node.moduleName),importerCount:getImporters(graph,node.moduleName).length,dependencyCount:getDependencies(graph,node.moduleName).length,routeCount:node.ontology?.routes.length??0,dataOperationCount:node.ontology?.dataOperations.length??0,securityFactCount:node.ontology?.security.length??0,findingCount:node.ontology?.findings.length??0})),routes,dataOperations,security,findings,packageBoundaries:summarizeSelectedPackageBoundaries(graph,boundedNodes,options.maxBoundaries??10)}}init_utils2();init_logger();init_path_security();import{constants as constants4,existsSync as existsSync105,readFileSync as readFileSync85,statSync as statSync43}from"node:fs";import*as fsPromises9 from"node:fs/promises";import*as path214 from"node:path";var WINDOWS_RENAME_MAX_RETRIES5=5,WINDOWS_RENAME_RETRY_DELAY_MS3=100,_internals147={safeRealpathSync,fsRename:fsPromises9.rename.bind(fsPromises9),retryDelayMs:WINDOWS_RENAME_RETRY_DELAY_MS3,writeFingerprint};function validateLoadedGraph(parsed){if(!parsed.schema_version)throw Object.assign(Error("repo-graph.json missing schema_version"),{code:"CORRUPTION"});if(!parsed.nodes||typeof parsed.nodes!=="object")throw Object.assign(Error("repo-graph.json missing or invalid nodes"),{code:"CORRUPTION"});if(!Array.isArray(parsed.edges))throw Object.assign(Error("repo-graph.json missing or invalid edges"),{code:"CORRUPTION"});for(let[key,node]of Object.entries(parsed.nodes)){if(!key||typeof key!=="string")throw Object.assign(Error("repo-graph.json contains invalid node key"),{code:"CORRUPTION"});try{validateGraphNode(node)}catch(err){let msg=err instanceof Error?err.message:"Invalid node structure";throw Object.assign(Error(`repo-graph.json node validation failed: ${msg}`),{code:"CORRUPTION"})}}for(let edge of parsed.edges)try{validateGraphEdge(edge)}catch(err){let msg=err instanceof Error?err.message:"Invalid edge structure";throw Object.assign(Error(`repo-graph.json edge validation failed: ${msg}`),{code:"CORRUPTION"})}if(!parsed.metadata||typeof parsed.metadata!=="object"||typeof parsed.metadata.generatedAt!=="string"||typeof parsed.metadata.generator!=="string"||typeof parsed.metadata.nodeCount!=="number"||typeof parsed.metadata.edgeCount!=="number")throw Object.assign(Error("repo-graph.json missing or invalid metadata"),{code:"CORRUPTION"});if(parsed.symbolEdges!==void 0){if(!Array.isArray(parsed.symbolEdges))throw Object.assign(Error("repo-graph.json symbolEdges must be an array"),{code:"CORRUPTION"});for(let entry of parsed.symbolEdges)if(typeof entry!=="object"||entry===null||typeof entry.fromFile!=="string"||typeof entry.fromSymbol!=="string"||typeof entry.toFile!=="string"||typeof entry.toSymbol!=="string"||entry.fromFile===""||entry.fromSymbol===""||entry.toFile===""||entry.toSymbol===""||containsControlChars(entry.fromFile)||containsControlChars(entry.fromSymbol)||containsControlChars(entry.toFile)||containsControlChars(entry.toSymbol)||containsPathTraversal(entry.fromFile)||containsPathTraversal(entry.toFile))throw Object.assign(Error("repo-graph.json contains invalid symbolEdges entry"),{code:"CORRUPTION"})}}function getGraphPath(workspace){validateWorkspace(workspace);let basePath=validateSwarmPath(workspace,REPO_GRAPH_FILENAME);return validateSymlinkBoundary(basePath,workspace),basePath}async function loadGraph(workspace){validateWorkspace(workspace);let normalized=path214.normalize(workspace),cached3=getCachedGraph(normalized);if(cached3&&!isDirty(normalized))try{let graphPath=getGraphPath(workspace);if(existsSync105(graphPath)){let stats2=await fsPromises9.stat(graphPath),cachedMtime=getCachedMtime(normalized);if(cachedMtime!==void 0&&stats2.mtimeMs!==cachedMtime)clearCache(normalized);else return cached3}else clearCache(normalized)}catch{clearCache(normalized)}try{let graphPath=getGraphPath(workspace);if(!existsSync105(graphPath))return null;let stats2=await fsPromises9.stat(graphPath),content=await fsPromises9.readFile(graphPath,"utf-8");if(content.includes("\x00")||content.includes("�"))throw Object.assign(Error("repo-graph.json contains null bytes or invalid encoding"),{code:"CORRUPTION"});let parsed;try{parsed=JSON.parse(content)}catch{throw Object.assign(Error("repo-graph.json contains invalid JSON"),{code:"CORRUPTION"})}return validateLoadedGraph(parsed),setCachedGraph(normalized,parsed,stats2.mtimeMs),parsed}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="CORRUPTION")throw error93;if(error93 instanceof Error&&"code"in error93&&error93.code==="ENOENT")return null;throw error93}}function loadGraphSync(workspace){validateWorkspace(workspace);let normalized=path214.normalize(workspace);try{let graphPath=getGraphPath(workspace);if(!existsSync105(graphPath))return null;let stats2=statSync43(graphPath),content=readFileSync85(graphPath,"utf-8");if(content.includes("\x00")||content.includes("�"))throw Object.assign(Error("repo-graph.json contains null bytes or invalid encoding"),{code:"CORRUPTION"});let parsed;try{parsed=JSON.parse(content)}catch{throw Object.assign(Error("repo-graph.json contains invalid JSON"),{code:"CORRUPTION"})}return validateLoadedGraph(parsed),setCachedGraph(normalized,parsed,stats2.mtimeMs),parsed}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="ENOENT")return null;throw error93}}async function saveGraph(workspace,graph,options){if(validateWorkspace(workspace),!graph.schema_version)throw Error("Graph must have schema_version");if(!graph.nodes||typeof graph.nodes!=="object")throw Error("Graph must have nodes object");if(!Array.isArray(graph.edges))throw Error("Graph must have edges array");let normalizedWorkspace=path214.normalize(workspace),realWorkspace=_internals147.safeRealpathSync(workspace,normalizedWorkspace);if(realWorkspace===null)throw Error(`Workspace realpath security check failed (non-ENOENT): ${workspace}`);let normalizedGraphRoot=path214.normalize(graph.workspaceRoot),realGraphRoot=_internals147.safeRealpathSync(graph.workspaceRoot,normalizedGraphRoot);if(realGraphRoot===null)throw Error(`Graph workspaceRoot realpath security check failed (non-ENOENT): ${graph.workspaceRoot}`);if(path214.normalize(realWorkspace)!==path214.normalize(realGraphRoot))throw Error(`Graph workspaceRoot mismatch: graph was built for "${graph.workspaceRoot}" but save was called for "${workspace}"`);let normalized=normalizedWorkspace,graphPath=getGraphPath(workspace);updateGraphMetadata(graph);let tempPath=`${graphPath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;await fsPromises9.mkdir(path214.dirname(tempPath),{recursive:!0});let lastError=null;try{if(options?.createAtomic)try{let handle=await fsPromises9.open(tempPath,"wx",420);await handle.writeFile(JSON.stringify(graph,null,2),"utf-8"),await handle.close()}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="EEXIST")throw Error("file already exists");throw error93}else await fsPromises9.writeFile(tempPath,JSON.stringify(graph,null,2),"utf-8");if(options?.createAtomic)try{await fsPromises9.copyFile(tempPath,graphPath,constants4.COPYFILE_EXCL)}catch(error93){throw lastError=error93 instanceof Error?error93:Error(String(error93)),lastError}else{for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES5;attempt++)try{await _internals147.fsRename(tempPath,graphPath),lastError=null;break}catch(error93){lastError=error93 instanceof Error?error93:Error(String(error93));let code=lastError.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")break;if(attempt<WINDOWS_RENAME_MAX_RETRIES5-1)await new Promise((resolve79)=>setTimeout(resolve79,_internals147.retryDelayMs))}if(lastError)throw lastError}}finally{try{await fsPromises9.unlink(tempPath)}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code!=="ENOENT")error48(`Failed to clean up temp file ${tempPath}:`,error93)}}let stats2=await fsPromises9.stat(graphPath);setCachedGraph(normalized,graph,stats2.mtimeMs)}var _internals148={stat:(p)=>fsPromises10.stat(p),scanFileAsync,buildWorkspaceGraphAsync,saveGraph,writeFingerprint},MAX_DIAGNOSTIC_ENTRIES2=200,MANIFEST_BASENAMES2=new Set(["package.json","Cargo.toml","pyproject.toml","go.mod"]);function buildManifestClosure(graph,absoluteRoot){let dirs=new Set;for(let node of Object.values(graph.nodes)){let absDir=path215.dirname(node.filePath),rel=path215.relative(absoluteRoot,absDir).split(path215.sep).join("/");rel=rel.replace(/^(?:\.\/)+/,"");while(!0){dirs.add(rel);let idx=rel.lastIndexOf("/");if(idx<0){if(rel!=="")dirs.add("");break}rel=rel.slice(0,idx)}}let manifestDirs=new Set;for(let relDir of dirs){let absDir=relDir===""?absoluteRoot:path215.join(absoluteRoot,relDir);try{if(readdirSync32(absDir).some((name)=>MANIFEST_BASENAMES2.has(name)))manifestDirs.add(relDir)}catch{}}return(relDir)=>manifestDirs.has(relDir)}function validateFileUpdates(graph){for(let edge of graph.edges){let normalizedSource=normalizeGraphPath(edge.source);if(!graph.nodes[normalizedSource])return{validationFailed:!0,offendingEdge:edge,reason:"missing-source-node"};if(!isAssetEdge(edge)){let normalizedTarget=normalizeGraphPath(edge.target);if(!graph.nodes[normalizedTarget])return{validationFailed:!0,offendingEdge:edge,reason:"missing-target-node"}}}if(graph.symbolEdges&&graph.symbolEdges.length>0){let validSymbolEdges=[];for(let symbolEdge of graph.symbolEdges){let normalizedFromFile=normalizeGraphPath(symbolEdge.fromFile),normalizedToFile=normalizeGraphPath(symbolEdge.toFile);if(graph.nodes[normalizedFromFile]&&graph.nodes[normalizedToFile])validSymbolEdges.push(symbolEdge)}graph.symbolEdges=validSymbolEdges}return{validationFailed:!1}}function diagnosticName(filePath,absoluteRoot){return path215.relative(absoluteRoot,filePath).split(path215.sep).join("/")}function dedupeCapped2(entries,keyOf2,limit=MAX_DIAGNOSTIC_ENTRIES2){let seen=new Set,result=[];for(let entry of entries){let key=keyOf2(entry);if(seen.has(key))continue;if(seen.add(key),result.push(entry),result.length>=limit)break}return result}function replaceFileDiagnostics(graph,file3,replacement){let diagnostics={...graph.diagnostics??{}},replaceStrings=(current,incoming)=>dedupeCapped2([...(current??[]).filter((entry)=>entry!==file3),...incoming??[]],(entry)=>entry);diagnostics.extractionFailures=dedupeCapped2([...(diagnostics.extractionFailures??[]).filter((entry)=>entry.file!==file3),...replacement?.extractionFailures??[]],(entry)=>`${entry.file}\x00${entry.language}\x00${entry.reason}`),diagnostics.unresolvedImports=dedupeCapped2([...(diagnostics.unresolvedImports??[]).filter((entry)=>entry.file!==file3),...replacement?.unresolvedImports??[]],(entry)=>`${entry.file}\x00${entry.specifier}`),diagnostics.oversizedFiles=replaceStrings(diagnostics.oversizedFiles,replacement?.oversizedFiles),diagnostics.binaryFiles=replaceStrings(diagnostics.binaryFiles,replacement?.binaryFiles),diagnostics.unreadableFiles=replaceStrings(diagnostics.unreadableFiles,replacement?.unreadableFiles),diagnostics.validationSkippedFiles=replaceStrings(diagnostics.validationSkippedFiles,replacement?.validationSkippedFiles),diagnostics.extractorInputWitnesses=dedupeCapped2([...(diagnostics.extractorInputWitnesses??[]).filter((entry)=>entry.file!==file3),...replacement?.extractorInputWitnesses??[]],(entry)=>`${entry.kind}\x00${entry.file}`,MAX_EXTRACTOR_INPUT_WITNESSES),graph.diagnostics=diagnostics}function scanDiagnostics(diagnostics,inputWitness){if(!diagnostics&&!inputWitness)return;return{...diagnostics??{},extractorInputWitnesses:inputWitness?[inputWitness]:[]}}function isEnoent(error93){return error93 instanceof Error&&"code"in error93&&error93.code==="ENOENT"}function applyAuthorizedDeletion(graph,filePath,absoluteRoot){let normalizedPath2=normalizeGraphPath(filePath);if(delete graph.nodes[normalizedPath2],graph.edges=graph.edges.filter((edge)=>normalizeGraphPath(edge.source)!==normalizedPath2&&normalizeGraphPath(edge.target)!==normalizedPath2),graph.symbolEdges)graph.symbolEdges=graph.symbolEdges.filter((edge)=>normalizeGraphPath(edge.fromFile)!==normalizedPath2&&normalizeGraphPath(edge.toFile)!==normalizedPath2);replaceFileDiagnostics(graph,diagnosticName(filePath,absoluteRoot))}async function updateGraphForFiles(workspaceRoot,filePaths,options){if(options?.forceRebuild){let graph2=await _internals148.buildWorkspaceGraphAsync(workspaceRoot,options.buildOptions);return await persistGraph(workspaceRoot,graph2,options.buildOptions),graph2}let existingGraph=await loadGraph(workspaceRoot);if(!existingGraph){let graph2=await _internals148.buildWorkspaceGraphAsync(workspaceRoot,options?.buildOptions);return await persistGraph(workspaceRoot,graph2,options?.buildOptions),graph2}let graph=existingGraph,absoluteRoot=path215.resolve(workspaceRoot),maxFileSize=options?.buildOptions?.maxFileSizeBytes??1048576,hasManifest=buildManifestClosure(graph,absoluteRoot);await applyAsyncFileUpdates(graph,filePaths,absoluteRoot,maxFileSize,hasManifest);let firstCheck=validateFileUpdates(graph);if(firstCheck.validationFailed)return await fallBackToFullRebuild(workspaceRoot,firstCheck.offendingEdge,firstCheck.reason,options?.buildOptions);let normalizedWorkspace=path215.normalize(workspaceRoot),loadedMtime=getCachedMtime(normalizedWorkspace);if(loadedMtime!==void 0){let graphPath=getGraphPath(workspaceRoot),currentStats=null;try{if(existsSync106(graphPath))currentStats=await _internals148.stat(graphPath)}catch{}if(currentStats!==null&¤tStats.mtimeMs!==loadedMtime){clearCacheAndResetQuery(normalizedWorkspace);let freshGraph=await loadGraph(workspaceRoot);if(!freshGraph)return await fallBackToFullRebuild(workspaceRoot,void 0,void 0,options?.buildOptions);await applyAsyncFileUpdates(freshGraph,filePaths,absoluteRoot,maxFileSize,buildManifestClosure(freshGraph,absoluteRoot));let replayCheck=validateFileUpdates(freshGraph);if(replayCheck.validationFailed)return await fallBackToFullRebuild(workspaceRoot,replayCheck.offendingEdge,replayCheck.reason,options?.buildOptions);let postReplayMtime=getCachedMtime(normalizedWorkspace);try{let postReplayStats=await _internals148.stat(graphPath);if(postReplayMtime!==void 0&&postReplayStats.mtimeMs!==postReplayMtime)return warn("[repo-graph] Concurrent modification persisted during replay — falling back to full rebuild"),await fallBackToFullRebuild(workspaceRoot,void 0,void 0,options?.buildOptions)}catch{return warn("[repo-graph] Re-stat failed after concurrent-modification replay — falling back to full rebuild"),await fallBackToFullRebuild(workspaceRoot,void 0,void 0,options?.buildOptions)}return finalizeAndSave(workspaceRoot,freshGraph,options?.buildOptions)}}return finalizeAndSave(workspaceRoot,graph,options?.buildOptions)}async function applyAsyncFileUpdates(graph,filePaths,absoluteRoot,maxFileSize,hasManifest){for(let rawFilePath of filePaths){let normalizedPath2=normalizeGraphPath(rawFilePath);if(!isScannableSourcePath(rawFilePath))continue;let fileDiagnosticName=diagnosticName(rawFilePath,absoluteRoot);try{await _internals148.stat(rawFilePath)}catch(error93){if(isEnoent(error93))applyAuthorizedDeletion(graph,rawFilePath,absoluteRoot);else replaceFileDiagnostics(graph,fileDiagnosticName,{unreadableFiles:[fileDiagnosticName]});continue}let result=await _internals148.scanFileAsync(rawFilePath,absoluteRoot,maxFileSize,hasManifest);if(result.node){let sanitizedImports=result.node.imports.filter((imp)=>!containsControlChars(imp)),sanitizedNode={...result.node,imports:sanitizedImports};try{upsertNode(graph,sanitizedNode)}catch{let validationWitness=typeof sanitizedNode.sizeBytes==="number"&&typeof sanitizedNode.mtimeMs==="number"?{file:fileDiagnosticName,kind:"stable-skip",sizeBytes:sanitizedNode.sizeBytes,mtimeMs:sanitizedNode.mtimeMs}:void 0;replaceFileDiagnostics(graph,fileDiagnosticName,scanDiagnostics({...result.diagnostics,validationSkippedFiles:[fileDiagnosticName]},validationWitness));continue}if(graph.edges=graph.edges.filter((edge)=>normalizeGraphPath(edge.source)!==normalizedPath2),graph.symbolEdges)graph.symbolEdges=graph.symbolEdges.filter((edge)=>normalizeGraphPath(edge.fromFile)!==normalizedPath2);for(let edge of result.edges)if(!graph.edges.some((e)=>e.source===edge.source&&e.target===edge.target&&e.importSpecifier===edge.importSpecifier))try{addEdge(graph,edge)}catch{}if(result.symbolEdges.length>0){if(!graph.symbolEdges)graph.symbolEdges=[];let existingKeys=new Set(graph.symbolEdges.map((se)=>`${se.fromFile}\x00${se.fromSymbol}\x00${se.toFile}\x00${se.toSymbol}`));for(let symbolEdge of result.symbolEdges){let key=`${symbolEdge.fromFile}\x00${symbolEdge.fromSymbol}\x00${symbolEdge.toFile}\x00${symbolEdge.toSymbol}`;if(!existingKeys.has(key))graph.symbolEdges.push(symbolEdge),existingKeys.add(key)}}replaceFileDiagnostics(graph,fileDiagnosticName,scanDiagnostics(result.diagnostics,result.inputWitness))}else{if((result.diagnostics?.oversizedFiles?.length??0)>0||(result.diagnostics?.binaryFiles?.length??0)>0){if(graph.edges=graph.edges.filter((edge)=>normalizeGraphPath(edge.source)!==normalizedPath2),graph.symbolEdges)graph.symbolEdges=graph.symbolEdges.filter((edge)=>normalizeGraphPath(edge.fromFile)!==normalizedPath2);delete graph.nodes[normalizedPath2],replaceFileDiagnostics(graph,fileDiagnosticName,scanDiagnostics(result.diagnostics,result.inputWitness));continue}try{await _internals148.stat(rawFilePath),replaceFileDiagnostics(graph,fileDiagnosticName,{...result.diagnostics,unreadableFiles:[fileDiagnosticName]})}catch(error93){if(isEnoent(error93))applyAuthorizedDeletion(graph,rawFilePath,absoluteRoot);else replaceFileDiagnostics(graph,fileDiagnosticName,{...result.diagnostics,unreadableFiles:[fileDiagnosticName]})}}}}function clearCacheAndResetQuery(normalizedWorkspace){clearCache(normalizedWorkspace),resetQueryCache()}async function finalizeAndSave(workspaceRoot,graph,buildOptions){if(graph.symbolEdges&&graph.symbolEdges.length===0)delete graph.symbolEdges;return updateGraphMetadata(graph),resetQueryCache(),await persistGraph(workspaceRoot,graph,buildOptions),graph}async function persistGraph(workspaceRoot,graph,buildOptions){await _internals148.saveGraph(workspaceRoot,graph),await _internals148.writeFingerprint(workspaceRoot,graph,{maxFiles:buildOptions?.maxFiles,walkBudgetMs:buildOptions?.walkBudgetMs,followSymlinks:buildOptions?.followSymlinks,excludeDirs:buildOptions?.excludeDirs})}async function fallBackToFullRebuild(workspaceRoot,offendingEdge,reason,buildOptions){if(offendingEdge)warn(`[repo-graph] Incremental update failed, falling back to full rebuild (offending edge: source=${offendingEdge.source} target=${offendingEdge.target} importSpecifier=${offendingEdge.importSpecifier}`+(reason?`, reason=${reason}`:"")+")");else warn("[repo-graph] Concurrent modification detected — falling back to full rebuild");let rebuiltGraph=await _internals148.buildWorkspaceGraphAsync(workspaceRoot,buildOptions),prev=rebuiltGraph.diagnostics??{},prevFallbacks=typeof prev.incrementalFallbacks==="number"?prev.incrementalFallbacks:0;return rebuiltGraph.diagnostics={...prev,incrementalFallbacks:prevFallbacks+1},await persistGraph(workspaceRoot,rebuiltGraph,buildOptions),rebuiltGraph}init_logger();function extractFilePath(args2){if(!args2||typeof args2!=="object")return null;let a=args2,filePath=a.file_path??a.path??a.filePath;if(!filePath||typeof filePath!=="string")return null;for(let i=0;i<3;i++)try{let decoded=decodeURIComponent(filePath);if(decoded===filePath)break;filePath=decoded}catch{break}return filePath=filePath.replace(/./g,".").replace(///g,"/").replace(/․/g,"."),filePath}function isSupportedSourceFile(filePath){return isScannableSourcePath(filePath)}function rebaseOntoWorkspace(realFilePath,realWorkspace,workspaceRoot){let normRealFile=realFilePath.replace(/\\/g,"/"),normRealWs=realWorkspace.replace(/\\/g,"/");if(normRealFile!==normRealWs&&!normRealFile.startsWith(`${normRealWs}/`))return realFilePath;if(path216.resolve(workspaceRoot)===path216.resolve(realWorkspace))return realFilePath;let rel=normRealFile.slice(normRealWs.length+(normRealFile===normRealWs?0:1));return path216.join(workspaceRoot,rel)}function createRepoGraphBuilderHook(workspaceRoot,deps,options){let _buildWorkspaceGraph=deps?.buildWorkspaceGraph??buildWorkspaceGraphAsync,_saveGraph=deps?.saveGraph??saveGraph,_updateGraphForFiles=deps?.updateGraphForFiles??updateGraphForFiles,_loadGraph=deps?.loadGraph??loadGraph,_probeFreshness=deps?.probeFreshness??probeFreshness,_writeFingerprint=deps?.writeFingerprint??writeFingerprint,_isGraphWideInputPath=deps?.isGraphWideInputPath??isGraphWideInputPath,_safeRealpathSync=deps?.safeRealpathSync??safeRealpathSync,_enabled=options?.enabled??!0,_initRefresh=options?.initRefresh??!0,_refreshCap=options?.refreshCap??50,_maxFiles=options?.maxFiles??1e4,_walkBudgetMs=options?.walkBudgetMs??5000,_excludeDirs=(options?.excludeDirs??[]).filter((d)=>d.length>0),_excludeDirSet=new Set(_excludeDirs),_buildOptions={excludeDirs:_excludeDirs,...options?.maxFiles===void 0?{}:{maxFiles:_maxFiles},...options?.walkBudgetMs===void 0?{}:{walkBudgetMs:_walkBudgetMs}},_hasConfiguredBuildOptions=options?.maxFiles!==void 0||options?.walkBudgetMs!==void 0||options?.excludeDirs!==void 0,_freshnessOptions={maxFiles:_maxFiles,walkBudgetMs:_walkBudgetMs,excludeDirs:_excludeDirs},initStarted=!1,initPromise=Promise.resolve(),FAILURE_ADVISORY_THRESHOLD=3,FAILURE_DECAY_MS=300000,ADVISORY_COOLDOWN_MS=60000,MAX_TRACKED_SESSIONS4=100,failuresBySession=new Map;function recordSuccess(sessionID){failuresBySession.delete(sessionID)}function recordFailure(sessionID,now){let state=failuresBySession.get(sessionID);if(state&&now-state.lastFailureAt>FAILURE_DECAY_MS)failuresBySession.delete(sessionID),state=void 0;if(!state){if(failuresBySession.size>=MAX_TRACKED_SESSIONS4){let oldest=failuresBySession.keys().next().value;if(oldest!==void 0)failuresBySession.delete(oldest)}state={failures:0,lastFailureAt:0,lastAdvisoryAt:0},failuresBySession.set(sessionID,state)}state.failures+=1,state.lastFailureAt=now;let advise=!1;if(state.failures>=FAILURE_ADVISORY_THRESHOLD&&now-state.lastAdvisoryAt>=ADVISORY_COOLDOWN_MS)advise=!0,state.lastAdvisoryAt=now;return{count:state.failures,advise}}async function rebuildGraph(reason){let graph=await _buildWorkspaceGraph(workspaceRoot,_buildOptions);await _saveGraph(workspaceRoot,graph);let fingerprintWritten=await _writeFingerprint(workspaceRoot,graph,_freshnessOptions);if(log(`[repo-graph] Built graph (${reason}): ${graph.metadata.nodeCount} nodes, ${graph.metadata.edgeCount} edges`),!fingerprintWritten)warn("[repo-graph] Graph saved, but its freshness fingerprint could not be certified; the next session will rebuild it safely.")}function uniqueDriftFiles(probe2){return[...new Set([...probe2.changed,...probe2.removed])]}function updateFiles(files){return _hasConfiguredBuildOptions?_updateGraphForFiles(workspaceRoot,files,{buildOptions:_buildOptions}):_updateGraphForFiles(workspaceRoot,files)}async function doInit(){await yieldToEventLoop();try{if(!_initRefresh){await rebuildGraph("configured legacy startup rebuild");return}let graph;try{graph=await _loadGraph(workspaceRoot)}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="CORRUPTION"){await rebuildGraph("corrupt saved graph");return}throw error93}if(!graph){await rebuildGraph("no saved graph");return}let probe2=await _probeFreshness(workspaceRoot,_freshnessOptions);if(probe2.state==="clean"||probe2.state==="inconclusive"){log(`[repo-graph] Startup freshness probe: ${probe2.state}; no refresh`);return}if(probe2.state==="no-fingerprint"){await rebuildGraph("no compatible freshness fingerprint");return}let driftFiles=uniqueDriftFiles(probe2);if(driftFiles.length===0){log("[repo-graph] Startup freshness probe reported no drift files");return}let fullRebuildThreshold=Math.max(_refreshCap*4,graph.metadata.nodeCount*0.4),requiresGraphWideRebuild=driftFiles.some(_isGraphWideInputPath);if(requiresGraphWideRebuild||driftFiles.length>fullRebuildThreshold){await rebuildGraph(requiresGraphWideRebuild?"graph-wide input drift":`drift set exceeded ${fullRebuildThreshold} files`);return}let refreshed=await updateFiles(driftFiles);log(`[repo-graph] Incrementally refreshed ${driftFiles.length} startup drift files: ${refreshed.metadata.nodeCount} nodes`)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);if(message.includes("does not exist")||message.includes("Refusing to scan")){log(`[repo-graph] Skipping scan: ${message}`);return}error48(`[repo-graph] Failed to build graph: ${message}`)}}return{init(){if(!_enabled)return Promise.resolve();if(!initStarted)initStarted=!0,initPromise=doInit();return initPromise},async toolAfter(input,_output){if(!_enabled)return;if(await initPromise.catch(()=>{}),!WRITE_TOOL_NAMES.includes(input.tool))return;let filePath=extractFilePath(input.args);if(!filePath)return;if(filePath.includes("\x00"))return;if(!isSupportedSourceFile(filePath))return;if(_excludeDirSet.size>0&&filePath.split(/[/\\]/).some((segment)=>_excludeDirSet.has(segment)))return;let absoluteFilePath=path216.isAbsolute(filePath)?filePath:path216.resolve(workspaceRoot,filePath),realFilePath=_safeRealpathSync(absoluteFilePath,absoluteFilePath);if(realFilePath===null)return;let realWorkspace=_safeRealpathSync(workspaceRoot,workspaceRoot);if(realWorkspace===null)return;let normalizedAbsolute=realFilePath.replace(/\\/g,"/"),normalizedWorkspace=realWorkspace.replace(/\\/g,"/");if(!normalizedAbsolute.startsWith(`${normalizedWorkspace}/`)&&normalizedAbsolute!==normalizedWorkspace)return;try{let pathForUpdate=rebaseOntoWorkspace(realFilePath,realWorkspace,workspaceRoot);await updateFiles([pathForUpdate]),recordSuccess(input.sessionID),log(`[repo-graph] Incremental update for ${path216.basename(filePath)}`)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93),{count,advise}=recordFailure(input.sessionID,Date.now());if(error48(`[repo-graph] Incremental update failed: ${message}`),advise)warn(`[repo-graph] ${count} consecutive incremental update failures. The dependency graph may be stale. Consider reloading the workspace.`)}}}}init_review_receipt();init_constants();init_schema();init_manager2();init_detector();init_manager();init_state2();init_swarm_artifact_cache();import*as fs116 from"node:fs";import*as path223 from"node:path";init_utils2();init_manager();init_utils();import*as fs111 from"node:fs";import*as path217 from"node:path";var DEFAULT_DRIFT_CONFIG={staleThresholdPhases:1,detectContradictions:!0,maxSignals:5};function extractDecisionsFromContext(contextContent){let decisions=[],lines=contextContent.split(`
|
|
5907
|
+
`;if(Buffer.byteLength(serialized3,"utf8")>MAX_FINGERPRINT_BYTES)return refuseFingerprint(root);return await writeFingerprintAtomic(root,serialized3),invalidateFreshnessCache(root),!0}catch{return refuseFingerprint(root)}}init_logger();init_path_security();import{existsSync as existsSync106,readdirSync as readdirSync31}from"node:fs";import*as fsPromises10 from"node:fs/promises";import*as path215 from"node:path";init_path_security();import*as path213 from"node:path";var GRAPH_HEALTH_OUTPUT_LIMIT=50,MAX_HEALTH_PATH_LENGTH=500,cachedReverseIndex=null;function normalizeLookupPath(input){return normalizeGraphPath(input).replace(/^(?:\.\/)+/,"")}function graphRoot(graph){return path213.resolve(graph.workspaceRoot)}function toModuleName2(graph,input){let normalized=normalizeLookupPath(input);if(path213.isAbsolute(normalized)||/^[A-Za-z]:\//.test(normalized))return normalizeLookupPath(path213.relative(graphRoot(graph),normalized));return normalized}function absoluteKeyForModule(graph,moduleName){return normalizeGraphPath(path213.resolve(graphRoot(graph),moduleName))}function getGraphNode(graph,input){let moduleName=toModuleName2(graph,input),direct=graph.nodes[absoluteKeyForModule(graph,moduleName)];if(direct)return direct;return getQueryIndexes(graph).moduleNameIndex.get(moduleName)}function moduleNameForEdgePath(graph,edgePath){let key=normalizeGraphPath(edgePath),node=graph.nodes[key];if(node)return normalizeLookupPath(node.moduleName);return normalizeLookupPath(path213.relative(graphRoot(graph),edgePath))}function buildReverseIndex(graph){let reverse=new Map,forward=new Map,moduleNameIndex=new Map;for(let node of Object.values(graph.nodes))moduleNameIndex.set(normalizeLookupPath(node.moduleName),node);for(let edge of graph.edges){if(isAssetEdge(edge))continue;let source=normalizeGraphPath(edge.source),target=normalizeGraphPath(edge.target),sourceRef={file:moduleNameForEdgePath(graph,edge.source),importType:edge.importType},targetRef={file:moduleNameForEdgePath(graph,edge.target),importType:edge.importType},reverseRefs=reverse.get(target);if(reverseRefs)reverseRefs.push(sourceRef);else reverse.set(target,[sourceRef]);let forwardRefs=forward.get(source);if(forwardRefs)forwardRefs.push(targetRef);else forward.set(source,[targetRef])}for(let refs of reverse.values())refs.sort((a,b)=>a.file.localeCompare(b.file));for(let refs of forward.values())refs.sort((a,b)=>a.file.localeCompare(b.file));return cachedReverseIndex={graph,index:reverse,forwardIndex:forward,moduleNameIndex},reverse}function getQueryIndexes(graph){if(cachedReverseIndex&&cachedReverseIndex.graph===graph)return cachedReverseIndex;return buildReverseIndex(graph),cachedReverseIndex}function getReverseIndex(graph){return getQueryIndexes(graph).index}function getForwardIndex(graph){return getQueryIndexes(graph).forwardIndex}function resetQueryCache(){cachedReverseIndex=null}function isSafeHealthPath(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value)||containsPathTraversal(value))return!1;if(path213.isAbsolute(value)||/^[A-Za-z]:[\\/]/.test(value))return!1;return!0}function isSafeHealthText(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value))return!1;return!0}function cap(entries){return entries.slice(0,GRAPH_HEALTH_OUTPUT_LIMIT)}function sanitizeExtractionFailures(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.language)&&isSafeHealthText(entry.reason))entries.push({file:entry.file,language:entry.language,reason:entry.reason})}return cap(entries)}function sanitizeUnresolvedImports(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.specifier))entries.push({file:entry.file,specifier:entry.specifier})}return cap(entries)}function sanitizePathList(value){if(!Array.isArray(value))return[];return cap(value.filter(isSafeHealthPath))}function getProbeStaleFiles(probe2,workspaceRoot){if(!probe2)return[];let root=path213.resolve(workspaceRoot),stale=new Set;for(let absolutePath2 of[...probe2.changed,...probe2.removed]){if(typeof absolutePath2!=="string"||!path213.isAbsolute(absolutePath2))continue;let relative46=normalizeGraphPath(path213.relative(root,absolutePath2));if(!isSafeHealthPath(relative46))continue;stale.add(relative46)}return[...stale].sort((a,b)=>a.localeCompare(b)).slice(0,GRAPH_HEALTH_OUTPUT_LIMIT)}function getGraphHealth(graph,workspaceRoot,probe2){let probeState=probe2?.state??"no-fingerprint";if(!graph)return{schemaVersion:null,fresh:!1,probeState,staleFiles:[],extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],validationSkippedFiles:[],lowConfidenceEdgeCount:0,walkTruncated:!1,walkTruncationReason:null,incrementalFallbacks:0,notes:['No repo graph found at .swarm/repo-graph.json. Run repo_map with action="build" first.']};let diagnostics=graph.diagnostics,fresh=probeState==="clean",staleFiles=getProbeStaleFiles(probe2,workspaceRoot??graph.workspaceRoot),notes=[];if(probeState==="drifted")notes.push('Graph content is stale relative to the workspace. Run repo_map with action="build" if automatic refresh is unavailable.');else if(probeState==="no-fingerprint")notes.push('Graph has no matching content fingerprint. Run repo_map with action="build" to certify it.');else if(probeState==="inconclusive")notes.push("Graph freshness is unknown because the bounded workspace probe did not complete; no refresh or deletion was attempted.");if(!diagnostics)notes.push('Graph has no recorded diagnostics. Rebuild with repo_map action="build" to collect health details.');let binaryFiles=sanitizePathList(diagnostics?.binaryFiles),binaryCount=binaryFiles.length;if(binaryCount>0)notes.push(`${binaryCount} binary files skipped during last build.`);let unreadableFiles=sanitizePathList(diagnostics?.unreadableFiles),unreadableCount=unreadableFiles.length;if(unreadableCount>0)notes.push(`${unreadableCount} unreadable files skipped during last build.`);let walkTruncated=diagnostics?.walkTruncated===!0,rawReason=diagnostics?.walkTruncationReason,walkTruncationReason=rawReason==="budget"||rawReason==="cap"?rawReason:null,incrementalFallbacks=typeof diagnostics?.incrementalFallbacks==="number"&&Number.isFinite(diagnostics.incrementalFallbacks)&&diagnostics.incrementalFallbacks>0?Math.floor(diagnostics.incrementalFallbacks):0;if(walkTruncated)notes.push("Graph is INCOMPLETE: walk hit the file-cap/wall-clock budget — results may be missing files."+(walkTruncationReason?` (reason: ${walkTruncationReason})`:""));if(incrementalFallbacks>0)notes.push(`${incrementalFallbacks} incremental update(s) fell back to a full rebuild (validation failure or concurrent modification).`);return{schemaVersion:graph.schema_version,fresh,probeState,staleFiles,extractionFailures:sanitizeExtractionFailures(diagnostics?.extractionFailures),unresolvedImports:sanitizeUnresolvedImports(diagnostics?.unresolvedImports),oversizedFiles:sanitizePathList(diagnostics?.oversizedFiles),unsupportedFiles:sanitizePathList(diagnostics?.unsupportedFiles),binaryFiles,unreadableFiles,validationSkippedFiles:sanitizePathList(diagnostics?.validationSkippedFiles),lowConfidenceEdgeCount:typeof diagnostics?.lowConfidenceEdgeCount==="number"&&Number.isFinite(diagnostics.lowConfidenceEdgeCount)&&diagnostics.lowConfidenceEdgeCount>0?Math.floor(diagnostics.lowConfidenceEdgeCount):0,walkTruncated,walkTruncationReason,incrementalFallbacks,notes}}function getImporters(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];return getReverseIndex(graph).get(normalizeGraphPath(node.filePath))??[]}function getDependencies(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];let sourceKey=normalizeGraphPath(node.filePath);return getForwardIndex(graph).get(sourceKey)??[]}function getSymbolConsumers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[];for(let edge of graph.edges){if(isAssetEdge(edge))continue;if(normalizeGraphPath(edge.target)!==targetKey)continue;let importedSymbols=edge.importedSymbols??[];if(edge.importType==="namespace"){refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:"*"});continue}if(importedSymbols.includes(symbolName))refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:symbolName})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}function getCallers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[],seen=new Set;for(let edge of graph.edges){if(isAssetEdge(edge))continue;if(normalizeGraphPath(edge.target)!==targetKey)continue;let file3=moduleNameForEdgePath(graph,edge.source);if(seen.has(file3))continue;if(edge.usedSymbols!==void 0){if(edge.usedSymbols.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"used"});continue}let imported=edge.importedSymbols??[];if(edge.importType==="namespace"||imported.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"imported"})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}var DEAD_EXPORT_EXCLUDED_ROLES=new Set(["api_route","cli_command","test_file","agent","hook","middleware"]);function getDeadExports(graph,options){if(!isSchemaVersionAtLeast(graph.schema_version,"1.1.0"))return{schemaSupported:!1,analyzedFiles:0,skippedUnresolvable:0,candidates:[],note:'Graph predates schema 1.1.0 (no usedSymbols data). Run repo_map action="build" to enable dead_exports.'};let usage=new Map;for(let edge of graph.edges){if(isAssetEdge(edge))continue;let target=normalizeGraphPath(edge.target),entry=usage.get(target);if(!entry)entry={used:new Set,unresolvable:!1},usage.set(target,entry);if(edge.importType==="namespace"||edge.importType==="sideeffect"||edge.importType==="require")entry.unresolvable=!0;else if(edge.usedSymbols)for(let symbol3 of edge.usedSymbols)entry.used.add(symbol3)}let reverse=getReverseIndex(graph),candidates=[],analyzedFiles=0,skippedUnresolvable=0;for(let node of Object.values(graph.nodes)){if(node.exports.length===0)continue;let key=normalizeGraphPath(node.filePath),importerCount=reverse.get(key)?.length??0;if(importerCount===0)continue;if((node.ontology?.roles??[]).some((r)=>DEAD_EXPORT_EXCLUDED_ROLES.has(r)))continue;let entry=usage.get(key);if(entry?.unresolvable){skippedUnresolvable++;continue}analyzedFiles++;let used=entry?.used??new Set;for(let symbol3 of node.exports){if(symbol3==="default")continue;if(used.has(symbol3))continue;candidates.push({file:node.moduleName,symbol:symbol3,line:node.exportLines?.[symbol3],importerCount})}}candidates.sort((a,b)=>a.file.localeCompare(b.file)||a.symbol.localeCompare(b.symbol));let limit=options?.maxCandidates??100,truncated=candidates.length>limit;return{schemaSupported:!0,analyzedFiles,skippedUnresolvable,candidates:candidates.slice(0,limit),note:"Advisory: exported symbols with no detected in-repo reference, limited to files imported by >=1 other file. Regex analysis cannot see dynamic dispatch, string-keyed access, or namespace/barrel re-export usage; verify before removing."+(truncated?` Showing ${limit} of ${candidates.length}.`:"")}}function getBlastRadius(graph,filePaths,maxDepth=3){let targetNodes=filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0),targets=targetNodes.map((node)=>normalizeLookupPath(node.moduleName));if(maxDepth<=0||targetNodes.length===0)return{target:filePaths.map((filePath)=>toModuleName2(graph,filePath)),directDependents:[],transitiveDependents:[],depthReached:0,totalDependents:0,riskLevel:"low"};let reverse=getReverseIndex(graph),visited=new Set(targetNodes.map((node)=>normalizeGraphPath(node.filePath))),direct=new Set,transitive=new Set,depthReached=0,queue=targetNodes.map((node)=>({key:normalizeGraphPath(node.filePath),depth:0}));while(queue.length>0){let next=[];for(let{key,depth}of queue){let importers=reverse.get(key)??[];for(let ref of importers){let importerNode=getGraphNode(graph,ref.file);if(!importerNode)continue;let importerKey=normalizeGraphPath(importerNode.filePath);if(visited.has(importerKey))continue;if(visited.add(importerKey),depth===0)direct.add(ref.file);else transitive.add(ref.file);if(depthReached=Math.max(depthReached,depth+1),depth+1<maxDepth)next.push({key:importerKey,depth:depth+1})}}queue=next}let totalDependents=direct.size+transitive.size;return{target:targets,directDependents:[...direct].sort(),transitiveDependents:[...transitive].sort(),depthReached,totalDependents,riskLevel:classifyRisk(totalDependents)}}function classifyRisk(count){if(count<=3)return"low";if(count<=10)return"medium";if(count<=25)return"high";return"critical"}function getKeyFiles(graph,topN=10){let reverse=getReverseIndex(graph),scored=Object.values(graph.nodes).map((node)=>({node,inDegree:reverse.get(normalizeGraphPath(node.filePath))?.length??0}));return scored.sort((a,b)=>{if(b.inDegree!==a.inDegree)return b.inDegree-a.inDegree;return a.node.moduleName.localeCompare(b.node.moduleName)}),scored.slice(0,topN).map((item)=>item.node)}function getFileOntology(graph,filePath){return getGraphNode(graph,filePath)?.ontology??null}function getLocalizationContext(graph,filePath,options={}){let target=toModuleName2(graph,filePath),node=getGraphNode(graph,target),importers=getImporters(graph,target),dependencies=getDependencies(graph,target),blast=getBlastRadius(graph,[target],options.maxDepth??2),externalSymbols=collectExternallyUsedSymbols(graph,node),summary=formatLocalizationSummary({target,importers,dependencies,blast,externalSymbols,ontology:node?.ontology??null,maxImporters:options.maxImporters??5,maxDeps:options.maxDeps??5});return{target,importerCount:importers.length,importers:importers.slice(0,options.maxImporters??5),dependencyCount:dependencies.length,dependencies:dependencies.slice(0,options.maxDeps??5),exportedSymbolsUsedExternally:externalSymbols,blastRadius:blast,summary}}function getContextPack(graph,file3,symbol3,options={}){if(!isSchemaVersionAtLeast(graph.schema_version,"1.2.0"))return{schemaSupported:!1,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:'rebuild with repo_map action="build"'};let maxDepth=options.maxDepth??2,maxTokens=options.maxTokens??4000,targetNode=getGraphNode(graph,file3);if(!targetNode)return{schemaSupported:!0,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:"Target file not found in graph"};let targetFile=normalizeGraphPath(targetNode.filePath),forward=new Map,reverse=new Map,symbolEdges=graph.symbolEdges??[];for(let edge of symbolEdges){let fromKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`,toKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`,fromEdges=forward.get(fromKey);if(fromEdges)fromEdges.push(edge);else forward.set(fromKey,[edge]);let toEdges=reverse.get(toKey);if(toEdges)toEdges.push(edge);else reverse.set(toKey,[edge])}let targetKey=`${targetFile}\x00${symbol3}`,visited=new Map,queue=[{key:targetKey,depth:0}];visited.set(targetKey,0);let reached=[],queueHead=0;while(queueHead<queue.length){let{key,depth}=queue[queueHead];queueHead++;let[curFile,curSymbol]=key.split("\x00",2);if(reached.push({file:curFile,symbol:curSymbol,depth}),depth>=maxDepth)continue;let outEdges=forward.get(key)??[];for(let edge of outEdges){let nextKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}let inEdges=reverse.get(key)??[];for(let edge of inEdges){let nextKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}}let TOKENS_PER_LINE=12,TOKENS_PER_SIGNATURE=10,spansWithDepth=[];for(let{file:symFile,symbol:sym,depth:d}of reached){let range=graph.nodes[symFile]?.exportRanges?.[sym];if(!range)continue;let mode=d===0?"full":d<maxDepth?"full":"signature";spansWithDepth.push({span:{file:symFile,symbol:sym,startLine:range.startLine,endLine:range.endLine,mode},depth:d})}spansWithDepth.sort((a,b)=>{let aIsTarget=a.span.file===targetFile&&a.span.symbol===symbol3?0:1,bIsTarget=b.span.file===targetFile&&b.span.symbol===symbol3?0:1;if(aIsTarget!==bIsTarget)return aIsTarget-bIsTarget;if(a.depth!==b.depth)return a.depth-b.depth;let fileCmp=a.span.file.localeCompare(b.span.file);if(fileCmp!==0)return fileCmp;return a.span.symbol.localeCompare(b.span.symbol)});let estimatedTokens=0,finalSpans=[],truncated=!1;for(let{span}of spansWithDepth){let spanTokens=span.mode==="full"?(span.endLine-span.startLine+1)*TOKENS_PER_LINE:TOKENS_PER_SIGNATURE;if(finalSpans.length>0&&estimatedTokens+spanTokens>maxTokens){truncated=!0;break}finalSpans.push(span),estimatedTokens+=spanTokens}return{schemaSupported:!0,target:{file:targetFile,symbol:symbol3},spans:finalSpans,truncated,estimatedTokens}}function collectExternallyUsedSymbols(graph,node){if(!node)return[];let exported=new Set(node.exports),used=new Set,targetKey=normalizeGraphPath(node.filePath);for(let edge of graph.edges){if(isAssetEdge(edge))continue;if(normalizeGraphPath(edge.target)!==targetKey)continue;for(let symbol3 of edge.importedSymbols??[])if(exported.has(symbol3))used.add(symbol3)}return[...used].sort((a,b)=>a.localeCompare(b))}function formatLocalizationSummary(opts){let importerList=opts.importers.length===0?"(none)":opts.importers.slice(0,opts.maxImporters).map((ref)=>ref.file).join(", ")+(opts.importers.length>opts.maxImporters?`, +${opts.importers.length-opts.maxImporters} more`:""),depList=opts.dependencies.length===0?"(none)":opts.dependencies.slice(0,opts.maxDeps).map((ref)=>ref.file).join(", ")+(opts.dependencies.length>opts.maxDeps?`, +${opts.dependencies.length-opts.maxDeps} more`:""),symbolList=opts.externalSymbols.length===0?"(none used externally)":opts.externalSymbols.slice(0,8).join(", ")+(opts.externalSymbols.length>8?`, +${opts.externalSymbols.length-8} more`:""),roles=opts.ontology?.roles.join(", ")||"unknown",findings=opts.ontology?.findings.length??0;return["LOCALIZATION CONTEXT",` Target: ${opts.target}`,` Roles: ${roles}`,` Imported by (${opts.importers.length}): ${importerList}`,` Imports (${opts.dependencies.length}): ${depList}`,` Exports used externally: ${symbolList}`,` Blast radius: ${opts.blast.totalDependents} files (${opts.blast.riskLevel} risk)`,` Ontology findings: ${findings}`].join(`
|
|
5908
|
+
`)}function getPackageBoundaries(graph,topN=25){return summarizePackageBoundaries(Object.values(graph.nodes),graph.edges,topN)}function summarizePackageBoundaries(nodes,edges,topN){let groups=new Map,ensure=(node)=>{let name=node.ontology?.packageBoundary||inferBoundary(node.moduleName),group=groups.get(name);if(!group)group={name,root:name,fileCount:0,roles:{},dependsOn:[],dependedOnBy:[],routeCount:0,dataOperationCount:0,findingCount:0,publicFiles:[]},groups.set(name,group);return group},boundaryByPath=new Map;for(let node of nodes){let group=ensure(node);boundaryByPath.set(normalizeGraphPath(node.filePath),group.name),group.fileCount++;let ontology=node.ontology;for(let role of ontology?.roles??["source_module"])group.roles[role]=(group.roles[role]??0)+1;if(group.routeCount+=ontology?.routes.length??0,group.dataOperationCount+=ontology?.dataOperations.length??0,group.findingCount+=ontology?.findings.length??0,node.exports.length>0)group.publicFiles.push(node.moduleName)}let dependsOn=new Map,dependedOnBy=new Map;for(let edge of edges){if(isAssetEdge(edge))continue;let sourceBoundary=boundaryByPath.get(normalizeGraphPath(edge.source)),targetBoundary=boundaryByPath.get(normalizeGraphPath(edge.target));if(!sourceBoundary||!targetBoundary||sourceBoundary===targetBoundary)continue;if(!dependsOn.has(sourceBoundary))dependsOn.set(sourceBoundary,new Set);if(!dependedOnBy.has(targetBoundary))dependedOnBy.set(targetBoundary,new Set);dependsOn.get(sourceBoundary)?.add(targetBoundary),dependedOnBy.get(targetBoundary)?.add(sourceBoundary)}for(let group of groups.values())group.dependsOn=[...dependsOn.get(group.name)??[]].sort(),group.dependedOnBy=[...dependedOnBy.get(group.name)??[]].sort(),group.publicFiles.sort((a,b)=>a.localeCompare(b)),group.publicFiles=group.publicFiles.slice(0,20);return[...groups.values()].sort((a,b)=>{if(b.findingCount!==a.findingCount)return b.findingCount-a.findingCount;if(b.fileCount!==a.fileCount)return b.fileCount-a.fileCount;return a.name.localeCompare(b.name)}).slice(0,topN)}function summarizeSelectedPackageBoundaries(graph,nodes,topN=25){let summaries=summarizePackageBoundaries(nodes,[],topN),boundaryByModule=new Map;for(let node of nodes)boundaryByModule.set(normalizeLookupPath(node.moduleName),node.ontology?.packageBoundary??inferBoundary(node.moduleName));let byName=new Map(summaries.map((summary)=>[summary.name,summary])),dependsOn=new Map,dependedOnBy=new Map;for(let node of nodes){let sourceBoundary=boundaryByModule.get(normalizeLookupPath(node.moduleName));if(!sourceBoundary)continue;for(let dep of getDependencies(graph,node.moduleName)){let targetBoundary=boundaryByModule.get(normalizeLookupPath(dep.file));if(!targetBoundary||sourceBoundary===targetBoundary||!byName.has(sourceBoundary)||!byName.has(targetBoundary))continue;if(!dependsOn.has(sourceBoundary))dependsOn.set(sourceBoundary,new Set);if(!dependedOnBy.has(targetBoundary))dependedOnBy.set(targetBoundary,new Set);dependsOn.get(sourceBoundary)?.add(targetBoundary),dependedOnBy.get(targetBoundary)?.add(sourceBoundary)}}for(let summary of summaries)summary.dependsOn=[...dependsOn.get(summary.name)??[]].sort(),summary.dependedOnBy=[...dependedOnBy.get(summary.name)??[]].sort();return summaries}function inferBoundary(moduleName){return inferPackageBoundary(moduleName)}function buildOntologyPreflightPacket(graph,filePaths=[],options={}){let maxFiles=options.maxFiles??12,maxFindings=options.maxFindings??20,boundedNodes=(filePaths.length>0?filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0):getKeyFiles(graph,maxFiles)).slice(0,maxFiles),findings=boundedNodes.flatMap((node)=>(node.ontology?.findings??[]).map((finding)=>({file:node.moduleName,...finding}))).slice(0,maxFindings),routes=boundedNodes.flatMap((node)=>(node.ontology?.routes??[]).map((route)=>({file:node.moduleName,...route}))),dataOperations=boundedNodes.flatMap((node)=>(node.ontology?.dataOperations??[]).map((fact)=>({file:node.moduleName,...fact}))),security=boundedNodes.flatMap((node)=>(node.ontology?.security??[]).map((fact)=>({file:node.moduleName,...fact})));return{generatedAt:new Date().toISOString(),targets:boundedNodes.map((node)=>node.moduleName),summary:{fileCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length,targetCount:boundedNodes.length,findingCount:findings.length,routeCount:routes.length,dataOperationCount:dataOperations.length,securityFactCount:security.length},files:boundedNodes.map((node)=>({file:node.moduleName,roles:node.ontology?.roles??[],packageBoundary:node.ontology?.packageBoundary??inferBoundary(node.moduleName),importerCount:getImporters(graph,node.moduleName).length,dependencyCount:getDependencies(graph,node.moduleName).length,routeCount:node.ontology?.routes.length??0,dataOperationCount:node.ontology?.dataOperations.length??0,securityFactCount:node.ontology?.security.length??0,findingCount:node.ontology?.findings.length??0})),routes,dataOperations,security,findings,packageBoundaries:summarizeSelectedPackageBoundaries(graph,boundedNodes,options.maxBoundaries??10)}}init_utils2();init_logger();init_path_security();import{constants as constants4,existsSync as existsSync105,readFileSync as readFileSync85,statSync as statSync42}from"node:fs";import*as fsPromises9 from"node:fs/promises";import*as path214 from"node:path";var WINDOWS_RENAME_MAX_RETRIES5=5,WINDOWS_RENAME_RETRY_DELAY_MS3=100,_internals147={safeRealpathSync,fsRename:fsPromises9.rename.bind(fsPromises9),retryDelayMs:WINDOWS_RENAME_RETRY_DELAY_MS3,writeFingerprint};function validateLoadedGraph(parsed){if(!parsed.schema_version)throw Object.assign(Error("repo-graph.json missing schema_version"),{code:"CORRUPTION"});if(!parsed.nodes||typeof parsed.nodes!=="object")throw Object.assign(Error("repo-graph.json missing or invalid nodes"),{code:"CORRUPTION"});if(!Array.isArray(parsed.edges))throw Object.assign(Error("repo-graph.json missing or invalid edges"),{code:"CORRUPTION"});for(let[key,node]of Object.entries(parsed.nodes)){if(!key||typeof key!=="string")throw Object.assign(Error("repo-graph.json contains invalid node key"),{code:"CORRUPTION"});try{validateGraphNode(node)}catch(err){let msg=err instanceof Error?err.message:"Invalid node structure";throw Object.assign(Error(`repo-graph.json node validation failed: ${msg}`),{code:"CORRUPTION"})}}for(let edge of parsed.edges)try{validateGraphEdge(edge)}catch(err){let msg=err instanceof Error?err.message:"Invalid edge structure";throw Object.assign(Error(`repo-graph.json edge validation failed: ${msg}`),{code:"CORRUPTION"})}if(!parsed.metadata||typeof parsed.metadata!=="object"||typeof parsed.metadata.generatedAt!=="string"||typeof parsed.metadata.generator!=="string"||typeof parsed.metadata.nodeCount!=="number"||typeof parsed.metadata.edgeCount!=="number")throw Object.assign(Error("repo-graph.json missing or invalid metadata"),{code:"CORRUPTION"});if(parsed.symbolEdges!==void 0){if(!Array.isArray(parsed.symbolEdges))throw Object.assign(Error("repo-graph.json symbolEdges must be an array"),{code:"CORRUPTION"});for(let entry of parsed.symbolEdges)if(typeof entry!=="object"||entry===null||typeof entry.fromFile!=="string"||typeof entry.fromSymbol!=="string"||typeof entry.toFile!=="string"||typeof entry.toSymbol!=="string"||entry.fromFile===""||entry.fromSymbol===""||entry.toFile===""||entry.toSymbol===""||containsControlChars(entry.fromFile)||containsControlChars(entry.fromSymbol)||containsControlChars(entry.toFile)||containsControlChars(entry.toSymbol)||containsPathTraversal(entry.fromFile)||containsPathTraversal(entry.toFile))throw Object.assign(Error("repo-graph.json contains invalid symbolEdges entry"),{code:"CORRUPTION"})}}function getGraphPath(workspace){validateWorkspace(workspace);let basePath=validateSwarmPath(workspace,REPO_GRAPH_FILENAME);return validateSymlinkBoundary(basePath,workspace),basePath}async function loadGraph(workspace){validateWorkspace(workspace);let normalized=path214.normalize(workspace),cached3=getCachedGraph(normalized);if(cached3&&!isDirty(normalized))try{let graphPath=getGraphPath(workspace);if(existsSync105(graphPath)){let stats2=await fsPromises9.stat(graphPath),cachedMtime=getCachedMtime(normalized);if(cachedMtime!==void 0&&stats2.mtimeMs!==cachedMtime)clearCache(normalized);else return cached3}else clearCache(normalized)}catch{clearCache(normalized)}try{let graphPath=getGraphPath(workspace);if(!existsSync105(graphPath))return null;let stats2=await fsPromises9.stat(graphPath),content=await fsPromises9.readFile(graphPath,"utf-8");if(content.includes("\x00")||content.includes("�"))throw Object.assign(Error("repo-graph.json contains null bytes or invalid encoding"),{code:"CORRUPTION"});let parsed;try{parsed=JSON.parse(content)}catch{throw Object.assign(Error("repo-graph.json contains invalid JSON"),{code:"CORRUPTION"})}return validateLoadedGraph(parsed),setCachedGraph(normalized,parsed,stats2.mtimeMs),parsed}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="CORRUPTION")throw error93;if(error93 instanceof Error&&"code"in error93&&error93.code==="ENOENT")return null;throw error93}}function loadGraphSync(workspace){validateWorkspace(workspace);let normalized=path214.normalize(workspace);try{let graphPath=getGraphPath(workspace);if(!existsSync105(graphPath))return null;let stats2=statSync42(graphPath),content=readFileSync85(graphPath,"utf-8");if(content.includes("\x00")||content.includes("�"))throw Object.assign(Error("repo-graph.json contains null bytes or invalid encoding"),{code:"CORRUPTION"});let parsed;try{parsed=JSON.parse(content)}catch{throw Object.assign(Error("repo-graph.json contains invalid JSON"),{code:"CORRUPTION"})}return validateLoadedGraph(parsed),setCachedGraph(normalized,parsed,stats2.mtimeMs),parsed}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="ENOENT")return null;throw error93}}async function saveGraph(workspace,graph,options){if(validateWorkspace(workspace),!graph.schema_version)throw Error("Graph must have schema_version");if(!graph.nodes||typeof graph.nodes!=="object")throw Error("Graph must have nodes object");if(!Array.isArray(graph.edges))throw Error("Graph must have edges array");let normalizedWorkspace=path214.normalize(workspace),realWorkspace=_internals147.safeRealpathSync(workspace,normalizedWorkspace);if(realWorkspace===null)throw Error(`Workspace realpath security check failed (non-ENOENT): ${workspace}`);let normalizedGraphRoot=path214.normalize(graph.workspaceRoot),realGraphRoot=_internals147.safeRealpathSync(graph.workspaceRoot,normalizedGraphRoot);if(realGraphRoot===null)throw Error(`Graph workspaceRoot realpath security check failed (non-ENOENT): ${graph.workspaceRoot}`);if(path214.normalize(realWorkspace)!==path214.normalize(realGraphRoot))throw Error(`Graph workspaceRoot mismatch: graph was built for "${graph.workspaceRoot}" but save was called for "${workspace}"`);let normalized=normalizedWorkspace,graphPath=getGraphPath(workspace);updateGraphMetadata(graph);let tempPath=`${graphPath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;await fsPromises9.mkdir(path214.dirname(tempPath),{recursive:!0});let lastError=null;try{if(options?.createAtomic)try{let handle=await fsPromises9.open(tempPath,"wx",420);await handle.writeFile(JSON.stringify(graph,null,2),"utf-8"),await handle.close()}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="EEXIST")throw Error("file already exists");throw error93}else await fsPromises9.writeFile(tempPath,JSON.stringify(graph,null,2),"utf-8");if(options?.createAtomic)try{await fsPromises9.copyFile(tempPath,graphPath,constants4.COPYFILE_EXCL)}catch(error93){throw lastError=error93 instanceof Error?error93:Error(String(error93)),lastError}else{for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES5;attempt++)try{await _internals147.fsRename(tempPath,graphPath),lastError=null;break}catch(error93){lastError=error93 instanceof Error?error93:Error(String(error93));let code=lastError.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")break;if(attempt<WINDOWS_RENAME_MAX_RETRIES5-1)await new Promise((resolve79)=>setTimeout(resolve79,_internals147.retryDelayMs))}if(lastError)throw lastError}}finally{try{await fsPromises9.unlink(tempPath)}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code!=="ENOENT")error48(`Failed to clean up temp file ${tempPath}:`,error93)}}let stats2=await fsPromises9.stat(graphPath);setCachedGraph(normalized,graph,stats2.mtimeMs)}var _internals148={stat:(p)=>fsPromises10.stat(p),scanFileAsync,buildWorkspaceGraphAsync,saveGraph,writeFingerprint},MAX_DIAGNOSTIC_ENTRIES2=200,MANIFEST_BASENAMES2=new Set(["package.json","Cargo.toml","pyproject.toml","go.mod"]);function buildManifestClosure(graph,absoluteRoot){let dirs=new Set;for(let node of Object.values(graph.nodes)){let absDir=path215.dirname(node.filePath),rel=path215.relative(absoluteRoot,absDir).split(path215.sep).join("/");rel=rel.replace(/^(?:\.\/)+/,"");while(!0){dirs.add(rel);let idx=rel.lastIndexOf("/");if(idx<0){if(rel!=="")dirs.add("");break}rel=rel.slice(0,idx)}}let manifestDirs=new Set;for(let relDir of dirs){let absDir=relDir===""?absoluteRoot:path215.join(absoluteRoot,relDir);try{if(readdirSync31(absDir).some((name)=>MANIFEST_BASENAMES2.has(name)))manifestDirs.add(relDir)}catch{}}return(relDir)=>manifestDirs.has(relDir)}function validateFileUpdates(graph){for(let edge of graph.edges){let normalizedSource=normalizeGraphPath(edge.source);if(!graph.nodes[normalizedSource])return{validationFailed:!0,offendingEdge:edge,reason:"missing-source-node"};if(!isAssetEdge(edge)){let normalizedTarget=normalizeGraphPath(edge.target);if(!graph.nodes[normalizedTarget])return{validationFailed:!0,offendingEdge:edge,reason:"missing-target-node"}}}if(graph.symbolEdges&&graph.symbolEdges.length>0){let validSymbolEdges=[];for(let symbolEdge of graph.symbolEdges){let normalizedFromFile=normalizeGraphPath(symbolEdge.fromFile),normalizedToFile=normalizeGraphPath(symbolEdge.toFile);if(graph.nodes[normalizedFromFile]&&graph.nodes[normalizedToFile])validSymbolEdges.push(symbolEdge)}graph.symbolEdges=validSymbolEdges}return{validationFailed:!1}}function diagnosticName(filePath,absoluteRoot){return path215.relative(absoluteRoot,filePath).split(path215.sep).join("/")}function dedupeCapped2(entries,keyOf2,limit=MAX_DIAGNOSTIC_ENTRIES2){let seen=new Set,result=[];for(let entry of entries){let key=keyOf2(entry);if(seen.has(key))continue;if(seen.add(key),result.push(entry),result.length>=limit)break}return result}function replaceFileDiagnostics(graph,file3,replacement){let diagnostics={...graph.diagnostics??{}},replaceStrings=(current,incoming)=>dedupeCapped2([...(current??[]).filter((entry)=>entry!==file3),...incoming??[]],(entry)=>entry);diagnostics.extractionFailures=dedupeCapped2([...(diagnostics.extractionFailures??[]).filter((entry)=>entry.file!==file3),...replacement?.extractionFailures??[]],(entry)=>`${entry.file}\x00${entry.language}\x00${entry.reason}`),diagnostics.unresolvedImports=dedupeCapped2([...(diagnostics.unresolvedImports??[]).filter((entry)=>entry.file!==file3),...replacement?.unresolvedImports??[]],(entry)=>`${entry.file}\x00${entry.specifier}`),diagnostics.oversizedFiles=replaceStrings(diagnostics.oversizedFiles,replacement?.oversizedFiles),diagnostics.binaryFiles=replaceStrings(diagnostics.binaryFiles,replacement?.binaryFiles),diagnostics.unreadableFiles=replaceStrings(diagnostics.unreadableFiles,replacement?.unreadableFiles),diagnostics.validationSkippedFiles=replaceStrings(diagnostics.validationSkippedFiles,replacement?.validationSkippedFiles),diagnostics.extractorInputWitnesses=dedupeCapped2([...(diagnostics.extractorInputWitnesses??[]).filter((entry)=>entry.file!==file3),...replacement?.extractorInputWitnesses??[]],(entry)=>`${entry.kind}\x00${entry.file}`,MAX_EXTRACTOR_INPUT_WITNESSES),graph.diagnostics=diagnostics}function scanDiagnostics(diagnostics,inputWitness){if(!diagnostics&&!inputWitness)return;return{...diagnostics??{},extractorInputWitnesses:inputWitness?[inputWitness]:[]}}function isEnoent(error93){return error93 instanceof Error&&"code"in error93&&error93.code==="ENOENT"}function applyAuthorizedDeletion(graph,filePath,absoluteRoot){let normalizedPath2=normalizeGraphPath(filePath);if(delete graph.nodes[normalizedPath2],graph.edges=graph.edges.filter((edge)=>normalizeGraphPath(edge.source)!==normalizedPath2&&normalizeGraphPath(edge.target)!==normalizedPath2),graph.symbolEdges)graph.symbolEdges=graph.symbolEdges.filter((edge)=>normalizeGraphPath(edge.fromFile)!==normalizedPath2&&normalizeGraphPath(edge.toFile)!==normalizedPath2);replaceFileDiagnostics(graph,diagnosticName(filePath,absoluteRoot))}async function updateGraphForFiles(workspaceRoot,filePaths,options){if(options?.forceRebuild){let graph2=await _internals148.buildWorkspaceGraphAsync(workspaceRoot,options.buildOptions);return await persistGraph(workspaceRoot,graph2,options.buildOptions),graph2}let existingGraph=await loadGraph(workspaceRoot);if(!existingGraph){let graph2=await _internals148.buildWorkspaceGraphAsync(workspaceRoot,options?.buildOptions);return await persistGraph(workspaceRoot,graph2,options?.buildOptions),graph2}let graph=existingGraph,absoluteRoot=path215.resolve(workspaceRoot),maxFileSize=options?.buildOptions?.maxFileSizeBytes??1048576,hasManifest=buildManifestClosure(graph,absoluteRoot);await applyAsyncFileUpdates(graph,filePaths,absoluteRoot,maxFileSize,hasManifest);let firstCheck=validateFileUpdates(graph);if(firstCheck.validationFailed)return await fallBackToFullRebuild(workspaceRoot,firstCheck.offendingEdge,firstCheck.reason,options?.buildOptions);let normalizedWorkspace=path215.normalize(workspaceRoot),loadedMtime=getCachedMtime(normalizedWorkspace);if(loadedMtime!==void 0){let graphPath=getGraphPath(workspaceRoot),currentStats=null;try{if(existsSync106(graphPath))currentStats=await _internals148.stat(graphPath)}catch{}if(currentStats!==null&¤tStats.mtimeMs!==loadedMtime){clearCacheAndResetQuery(normalizedWorkspace);let freshGraph=await loadGraph(workspaceRoot);if(!freshGraph)return await fallBackToFullRebuild(workspaceRoot,void 0,void 0,options?.buildOptions);await applyAsyncFileUpdates(freshGraph,filePaths,absoluteRoot,maxFileSize,buildManifestClosure(freshGraph,absoluteRoot));let replayCheck=validateFileUpdates(freshGraph);if(replayCheck.validationFailed)return await fallBackToFullRebuild(workspaceRoot,replayCheck.offendingEdge,replayCheck.reason,options?.buildOptions);let postReplayMtime=getCachedMtime(normalizedWorkspace);try{let postReplayStats=await _internals148.stat(graphPath);if(postReplayMtime!==void 0&&postReplayStats.mtimeMs!==postReplayMtime)return warn("[repo-graph] Concurrent modification persisted during replay — falling back to full rebuild"),await fallBackToFullRebuild(workspaceRoot,void 0,void 0,options?.buildOptions)}catch{return warn("[repo-graph] Re-stat failed after concurrent-modification replay — falling back to full rebuild"),await fallBackToFullRebuild(workspaceRoot,void 0,void 0,options?.buildOptions)}return finalizeAndSave(workspaceRoot,freshGraph,options?.buildOptions)}}return finalizeAndSave(workspaceRoot,graph,options?.buildOptions)}async function applyAsyncFileUpdates(graph,filePaths,absoluteRoot,maxFileSize,hasManifest){for(let rawFilePath of filePaths){let normalizedPath2=normalizeGraphPath(rawFilePath);if(!isScannableSourcePath(rawFilePath))continue;let fileDiagnosticName=diagnosticName(rawFilePath,absoluteRoot);try{await _internals148.stat(rawFilePath)}catch(error93){if(isEnoent(error93))applyAuthorizedDeletion(graph,rawFilePath,absoluteRoot);else replaceFileDiagnostics(graph,fileDiagnosticName,{unreadableFiles:[fileDiagnosticName]});continue}let result=await _internals148.scanFileAsync(rawFilePath,absoluteRoot,maxFileSize,hasManifest);if(result.node){let sanitizedImports=result.node.imports.filter((imp)=>!containsControlChars(imp)),sanitizedNode={...result.node,imports:sanitizedImports};try{upsertNode(graph,sanitizedNode)}catch{let validationWitness=typeof sanitizedNode.sizeBytes==="number"&&typeof sanitizedNode.mtimeMs==="number"?{file:fileDiagnosticName,kind:"stable-skip",sizeBytes:sanitizedNode.sizeBytes,mtimeMs:sanitizedNode.mtimeMs}:void 0;replaceFileDiagnostics(graph,fileDiagnosticName,scanDiagnostics({...result.diagnostics,validationSkippedFiles:[fileDiagnosticName]},validationWitness));continue}if(graph.edges=graph.edges.filter((edge)=>normalizeGraphPath(edge.source)!==normalizedPath2),graph.symbolEdges)graph.symbolEdges=graph.symbolEdges.filter((edge)=>normalizeGraphPath(edge.fromFile)!==normalizedPath2);for(let edge of result.edges)if(!graph.edges.some((e)=>e.source===edge.source&&e.target===edge.target&&e.importSpecifier===edge.importSpecifier))try{addEdge(graph,edge)}catch{}if(result.symbolEdges.length>0){if(!graph.symbolEdges)graph.symbolEdges=[];let existingKeys=new Set(graph.symbolEdges.map((se)=>`${se.fromFile}\x00${se.fromSymbol}\x00${se.toFile}\x00${se.toSymbol}`));for(let symbolEdge of result.symbolEdges){let key=`${symbolEdge.fromFile}\x00${symbolEdge.fromSymbol}\x00${symbolEdge.toFile}\x00${symbolEdge.toSymbol}`;if(!existingKeys.has(key))graph.symbolEdges.push(symbolEdge),existingKeys.add(key)}}replaceFileDiagnostics(graph,fileDiagnosticName,scanDiagnostics(result.diagnostics,result.inputWitness))}else{if((result.diagnostics?.oversizedFiles?.length??0)>0||(result.diagnostics?.binaryFiles?.length??0)>0){if(graph.edges=graph.edges.filter((edge)=>normalizeGraphPath(edge.source)!==normalizedPath2),graph.symbolEdges)graph.symbolEdges=graph.symbolEdges.filter((edge)=>normalizeGraphPath(edge.fromFile)!==normalizedPath2);delete graph.nodes[normalizedPath2],replaceFileDiagnostics(graph,fileDiagnosticName,scanDiagnostics(result.diagnostics,result.inputWitness));continue}try{await _internals148.stat(rawFilePath),replaceFileDiagnostics(graph,fileDiagnosticName,{...result.diagnostics,unreadableFiles:[fileDiagnosticName]})}catch(error93){if(isEnoent(error93))applyAuthorizedDeletion(graph,rawFilePath,absoluteRoot);else replaceFileDiagnostics(graph,fileDiagnosticName,{...result.diagnostics,unreadableFiles:[fileDiagnosticName]})}}}}function clearCacheAndResetQuery(normalizedWorkspace){clearCache(normalizedWorkspace),resetQueryCache()}async function finalizeAndSave(workspaceRoot,graph,buildOptions){if(graph.symbolEdges&&graph.symbolEdges.length===0)delete graph.symbolEdges;return updateGraphMetadata(graph),resetQueryCache(),await persistGraph(workspaceRoot,graph,buildOptions),graph}async function persistGraph(workspaceRoot,graph,buildOptions){await _internals148.saveGraph(workspaceRoot,graph),await _internals148.writeFingerprint(workspaceRoot,graph,{maxFiles:buildOptions?.maxFiles,walkBudgetMs:buildOptions?.walkBudgetMs,followSymlinks:buildOptions?.followSymlinks,excludeDirs:buildOptions?.excludeDirs})}async function fallBackToFullRebuild(workspaceRoot,offendingEdge,reason,buildOptions){if(offendingEdge)warn(`[repo-graph] Incremental update failed, falling back to full rebuild (offending edge: source=${offendingEdge.source} target=${offendingEdge.target} importSpecifier=${offendingEdge.importSpecifier}`+(reason?`, reason=${reason}`:"")+")");else warn("[repo-graph] Concurrent modification detected — falling back to full rebuild");let rebuiltGraph=await _internals148.buildWorkspaceGraphAsync(workspaceRoot,buildOptions),prev=rebuiltGraph.diagnostics??{},prevFallbacks=typeof prev.incrementalFallbacks==="number"?prev.incrementalFallbacks:0;return rebuiltGraph.diagnostics={...prev,incrementalFallbacks:prevFallbacks+1},await persistGraph(workspaceRoot,rebuiltGraph,buildOptions),rebuiltGraph}init_logger();function extractFilePath(args2){if(!args2||typeof args2!=="object")return null;let a=args2,filePath=a.file_path??a.path??a.filePath;if(!filePath||typeof filePath!=="string")return null;for(let i=0;i<3;i++)try{let decoded=decodeURIComponent(filePath);if(decoded===filePath)break;filePath=decoded}catch{break}return filePath=filePath.replace(/./g,".").replace(///g,"/").replace(/․/g,"."),filePath}function isSupportedSourceFile(filePath){return isScannableSourcePath(filePath)}function rebaseOntoWorkspace(realFilePath,realWorkspace,workspaceRoot){let normRealFile=realFilePath.replace(/\\/g,"/"),normRealWs=realWorkspace.replace(/\\/g,"/");if(normRealFile!==normRealWs&&!normRealFile.startsWith(`${normRealWs}/`))return realFilePath;if(path216.resolve(workspaceRoot)===path216.resolve(realWorkspace))return realFilePath;let rel=normRealFile.slice(normRealWs.length+(normRealFile===normRealWs?0:1));return path216.join(workspaceRoot,rel)}function createRepoGraphBuilderHook(workspaceRoot,deps,options){let _buildWorkspaceGraph=deps?.buildWorkspaceGraph??buildWorkspaceGraphAsync,_saveGraph=deps?.saveGraph??saveGraph,_updateGraphForFiles=deps?.updateGraphForFiles??updateGraphForFiles,_loadGraph=deps?.loadGraph??loadGraph,_probeFreshness=deps?.probeFreshness??probeFreshness,_writeFingerprint=deps?.writeFingerprint??writeFingerprint,_isGraphWideInputPath=deps?.isGraphWideInputPath??isGraphWideInputPath,_safeRealpathSync=deps?.safeRealpathSync??safeRealpathSync,_enabled=options?.enabled??!0,_initRefresh=options?.initRefresh??!0,_refreshCap=options?.refreshCap??50,_maxFiles=options?.maxFiles??1e4,_walkBudgetMs=options?.walkBudgetMs??5000,_excludeDirs=(options?.excludeDirs??[]).filter((d)=>d.length>0),_excludeDirSet=new Set(_excludeDirs),_buildOptions={excludeDirs:_excludeDirs,...options?.maxFiles===void 0?{}:{maxFiles:_maxFiles},...options?.walkBudgetMs===void 0?{}:{walkBudgetMs:_walkBudgetMs}},_hasConfiguredBuildOptions=options?.maxFiles!==void 0||options?.walkBudgetMs!==void 0||options?.excludeDirs!==void 0,_freshnessOptions={maxFiles:_maxFiles,walkBudgetMs:_walkBudgetMs,excludeDirs:_excludeDirs},initStarted=!1,initPromise=Promise.resolve(),FAILURE_ADVISORY_THRESHOLD=3,FAILURE_DECAY_MS=300000,ADVISORY_COOLDOWN_MS=60000,MAX_TRACKED_SESSIONS4=100,failuresBySession=new Map;function recordSuccess(sessionID){failuresBySession.delete(sessionID)}function recordFailure(sessionID,now){let state=failuresBySession.get(sessionID);if(state&&now-state.lastFailureAt>FAILURE_DECAY_MS)failuresBySession.delete(sessionID),state=void 0;if(!state){if(failuresBySession.size>=MAX_TRACKED_SESSIONS4){let oldest=failuresBySession.keys().next().value;if(oldest!==void 0)failuresBySession.delete(oldest)}state={failures:0,lastFailureAt:0,lastAdvisoryAt:0},failuresBySession.set(sessionID,state)}state.failures+=1,state.lastFailureAt=now;let advise=!1;if(state.failures>=FAILURE_ADVISORY_THRESHOLD&&now-state.lastAdvisoryAt>=ADVISORY_COOLDOWN_MS)advise=!0,state.lastAdvisoryAt=now;return{count:state.failures,advise}}async function rebuildGraph(reason){let graph=await _buildWorkspaceGraph(workspaceRoot,_buildOptions);await _saveGraph(workspaceRoot,graph);let fingerprintWritten=await _writeFingerprint(workspaceRoot,graph,_freshnessOptions);if(log(`[repo-graph] Built graph (${reason}): ${graph.metadata.nodeCount} nodes, ${graph.metadata.edgeCount} edges`),!fingerprintWritten)warn("[repo-graph] Graph saved, but its freshness fingerprint could not be certified; the next session will rebuild it safely.")}function uniqueDriftFiles(probe2){return[...new Set([...probe2.changed,...probe2.removed])]}function updateFiles(files){return _hasConfiguredBuildOptions?_updateGraphForFiles(workspaceRoot,files,{buildOptions:_buildOptions}):_updateGraphForFiles(workspaceRoot,files)}async function doInit(){await yieldToEventLoop();try{if(!_initRefresh){await rebuildGraph("configured legacy startup rebuild");return}let graph;try{graph=await _loadGraph(workspaceRoot)}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="CORRUPTION"){await rebuildGraph("corrupt saved graph");return}throw error93}if(!graph){await rebuildGraph("no saved graph");return}let probe2=await _probeFreshness(workspaceRoot,_freshnessOptions);if(probe2.state==="clean"||probe2.state==="inconclusive"){log(`[repo-graph] Startup freshness probe: ${probe2.state}; no refresh`);return}if(probe2.state==="no-fingerprint"){await rebuildGraph("no compatible freshness fingerprint");return}let driftFiles=uniqueDriftFiles(probe2);if(driftFiles.length===0){log("[repo-graph] Startup freshness probe reported no drift files");return}let fullRebuildThreshold=Math.max(_refreshCap*4,graph.metadata.nodeCount*0.4),requiresGraphWideRebuild=driftFiles.some(_isGraphWideInputPath);if(requiresGraphWideRebuild||driftFiles.length>fullRebuildThreshold){await rebuildGraph(requiresGraphWideRebuild?"graph-wide input drift":`drift set exceeded ${fullRebuildThreshold} files`);return}let refreshed=await updateFiles(driftFiles);log(`[repo-graph] Incrementally refreshed ${driftFiles.length} startup drift files: ${refreshed.metadata.nodeCount} nodes`)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);if(message.includes("does not exist")||message.includes("Refusing to scan")){log(`[repo-graph] Skipping scan: ${message}`);return}error48(`[repo-graph] Failed to build graph: ${message}`)}}return{init(){if(!_enabled)return Promise.resolve();if(!initStarted)initStarted=!0,initPromise=doInit();return initPromise},async toolAfter(input,_output){if(!_enabled)return;if(await initPromise.catch(()=>{}),!WRITE_TOOL_NAMES.includes(input.tool))return;let filePath=extractFilePath(input.args);if(!filePath)return;if(filePath.includes("\x00"))return;if(!isSupportedSourceFile(filePath))return;if(_excludeDirSet.size>0&&filePath.split(/[/\\]/).some((segment)=>_excludeDirSet.has(segment)))return;let absoluteFilePath=path216.isAbsolute(filePath)?filePath:path216.resolve(workspaceRoot,filePath),realFilePath=_safeRealpathSync(absoluteFilePath,absoluteFilePath);if(realFilePath===null)return;let realWorkspace=_safeRealpathSync(workspaceRoot,workspaceRoot);if(realWorkspace===null)return;let normalizedAbsolute=realFilePath.replace(/\\/g,"/"),normalizedWorkspace=realWorkspace.replace(/\\/g,"/");if(!normalizedAbsolute.startsWith(`${normalizedWorkspace}/`)&&normalizedAbsolute!==normalizedWorkspace)return;try{let pathForUpdate=rebaseOntoWorkspace(realFilePath,realWorkspace,workspaceRoot);await updateFiles([pathForUpdate]),recordSuccess(input.sessionID),log(`[repo-graph] Incremental update for ${path216.basename(filePath)}`)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93),{count,advise}=recordFailure(input.sessionID,Date.now());if(error48(`[repo-graph] Incremental update failed: ${message}`),advise)warn(`[repo-graph] ${count} consecutive incremental update failures. The dependency graph may be stale. Consider reloading the workspace.`)}}}}init_review_receipt();init_constants();init_schema();init_manager2();init_detector();init_manager();init_state2();init_swarm_artifact_cache();import*as fs116 from"node:fs";import*as path223 from"node:path";init_utils2();init_manager();init_utils();import*as fs111 from"node:fs";import*as path217 from"node:path";var DEFAULT_DRIFT_CONFIG={staleThresholdPhases:1,detectContradictions:!0,maxSignals:5};function extractDecisionsFromContext(contextContent){let decisions=[],lines=contextContent.split(`
|
|
5909
5909
|
`),inDecisionsSection=!1,currentPhase=null,lineNumber=0;for(let i=0;i<lines.length;i++){let line=lines[i];lineNumber=i+1;let phaseMatch=line.match(/^## Phase (\d+)/);if(phaseMatch)currentPhase=parseInt(phaseMatch[1],10);if(line.trim()==="## Decisions"){inDecisionsSection=!0;continue}if(inDecisionsSection&&line.startsWith("## "))break;if(inDecisionsSection&&line.trim().startsWith("- ")){let text=line.trim().substring(2),confirmed=text.includes("✅")||text.includes("[confirmed]"),timestampMatch=text.match(/\[(\d{4}-\d{2}-\d{2}T[\d:.]+Z?)\]/),timestamp=timestampMatch?timestampMatch[1]:null,decisionPhaseMatch=text.match(/Phase (\d+)/),decisionPhase=decisionPhaseMatch?parseInt(decisionPhaseMatch[1],10):currentPhase;decisions.push({text:text.replace(/\s*\[.*?\]\s*/g,"").trim(),phase:decisionPhase,confirmed,timestamp,line:lineNumber})}}return decisions}function isDecisionStale(decision,currentPhase,threshold){if(decision.phase===null)return!decision.confirmed;let phaseDiff=currentPhase-decision.phase;if(phaseDiff>=threshold)return!0;if(phaseDiff===0&&!decision.confirmed)return!0;return!1}function classifyPolarity(textLower,positiveKeywords,negativeKeywords){if(negativeKeywords.some((k)=>textLower.includes(k)))return"negative";if(positiveKeywords.some((k)=>textLower.includes(k)))return"positive";return null}function findContradictions(decisions){let signals=[],contradictionPairs=[[["use","using","use ","adopt","implement","enable"],["not use","don't use","do not use","avoid","disable","remove"]],[["keep","retain","preserve"],["remove","delete","drop","eliminate"]],[["include","add","incorporate"],["exclude","skip","omit"]],[["require","mandatory","must"],["optional","skip","can skip"]],[["background","async"],["foreground","sync","synchronous"]]];for(let i=0;i<decisions.length;i++){let decisionA=decisions[i],textLower=decisionA.text.toLowerCase();for(let j=i+1;j<decisions.length;j++){let decisionB=decisions[j],textBLower=decisionB.text.toLowerCase();for(let[positiveKeywords,negativeKeywords]of contradictionPairs){let polarityA=classifyPolarity(textLower,positiveKeywords,negativeKeywords),polarityB=classifyPolarity(textBLower,positiveKeywords,negativeKeywords);if(polarityA==="positive"&&polarityB==="negative"||polarityA==="negative"&&polarityB==="positive"){let wordsA=textLower.split(/\s+/).slice(0,4).join(" "),wordsB=textBLower.split(/\s+/).slice(0,4).join(" ");if(wordsA.split(/\s+/).filter((w)=>w.length>2&&wordsB.includes(w)).length>0||wordsA.includes("file"))signals.push({id:`contradiction-${i}-${j}`,severity:"error",type:"contradiction",message:"Contradictory decisions detected",source:{file:"context.md",line:decisionA.line},relatedDecisions:[decisionA.text,decisionB.text],hint:"Review both decisions and clarify the intended approach."})}}}}return signals}function extractCurrentPhaseFromLegacy(planContent){if(!planContent)return null;let lines=planContent.split(`
|
|
5910
5910
|
`);for(let i=0;i<Math.min(30,lines.length);i++){let progressMatch=lines[i].trim().match(/^## Phase (\d+):?\s*(.*?)\s*\[IN PROGRESS\]/i);if(progressMatch)return parseInt(progressMatch[1],10)}for(let i=0;i<Math.min(5,lines.length);i++){let phaseMatch=lines[i].trim().match(/Phase:\s*(\d+)/i);if(phaseMatch)return parseInt(phaseMatch[1],10)}return null}async function analyzeDecisionDrift(directory,config3={}){let effectiveConfig={...DEFAULT_DRIFT_CONFIG,...config3},signals=[],analyzedAt=new Date().toISOString();try{let plan=await loadPlan(directory),currentPhase=plan?.current_phase??1;if(!plan){let legacyPhase=extractCurrentPhaseFromLegacy(await readSwarmFileAsync(directory,"plan.md")??"");if(legacyPhase!==null)currentPhase=legacyPhase}let contextPath=path217.join(directory,".swarm","context.md"),contextContent="";try{if(fs111.existsSync(contextPath))contextContent=fs111.readFileSync(contextPath,"utf-8")}catch(error93){return log("[DecisionDriftAnalyzer] context file read failed",{error:error93 instanceof Error?error93.message:String(error93)}),{hasDrift:!1,signals:[],summary:"",analyzedAt}}if(!contextContent)return{hasDrift:!1,signals:[],summary:"",analyzedAt};let decisions=extractDecisionsFromContext(contextContent);if(decisions.length===0)return{hasDrift:!1,signals:[],summary:"",analyzedAt};for(let decision of decisions)if(isDecisionStale(decision,currentPhase,effectiveConfig.staleThresholdPhases)){let hint;if(decision.phase!==null&&decision.phase<currentPhase)hint=`Decision was from Phase ${decision.phase}, current is Phase ${currentPhase}.`;else if(!decision.confirmed)hint="Decision has not been confirmed. Consider confirming or revisiting.";signals.push({id:`stale-${decision.line}`,severity:decision.phase!==null&&decision.phase<currentPhase?"warning":"warning",type:"stale",message:`Stale decision: "${decision.text.substring(0,50)}${decision.text.length>50?"...":""}"`,source:{file:"context.md",line:decision.line},hint})}if(effectiveConfig.detectContradictions){let contradictions=findContradictions(decisions);signals.push(...contradictions)}let limitedSignals=signals.slice(0,effectiveConfig.maxSignals),summary=buildDriftSummary(limitedSignals);return{hasDrift:limitedSignals.length>0,signals:limitedSignals,summary,analyzedAt}}catch(error93){return log("[DecisionDriftAnalyzer] drift analysis failed",{error:error93 instanceof Error?error93.message:String(error93)}),{hasDrift:!1,signals:[],summary:"",analyzedAt}}}function buildDriftSummary(signals){if(signals.length===0)return"";let warnings=signals.filter((s)=>s.severity==="warning"),errors5=signals.filter((s)=>s.severity==="error"),lines=["[SWARM DECISION DRIFT]"];if(errors5.length>0){lines.push(`⚠️ ${errors5.length} contradiction(s) detected:`);for(let err of errors5.slice(0,2)){let related=err.relatedDecisions?` (${err.relatedDecisions[0].substring(0,30)}... vs ${err.relatedDecisions[1].substring(0,30)}...)`:"";lines.push(` - ${err.type}: ${err.message}${related}`)}}if(warnings.length>0){lines.push(`\uD83D\uDCA1 ${warnings.length} stale decision(s) found:`);for(let warn2 of warnings.slice(0,3)){let hint=warn2.hint?` - ${warn2.hint}`:"";lines.push(` - ${warn2.message.substring(0,60)}${hint}`)}}return lines.push("See .swarm/context.md for details."),lines.join(`
|
|
5911
5911
|
`)}function formatDriftForContext(result){if(!result.hasDrift||!result.summary)return"";let maxLength=600,summary=result.summary;if(summary.length>maxLength)summary=`${summary.substring(0,maxLength-3)}...`;return summary}init_config_doctor();init_context_budget_service();init_diagnose_service();init_evidence_service();init_evidence_summary_service();init_export_service();init_handoff_service();init_history_service();init_plan_service();init_preflight_integration();init_preflight_service();init_status_service();function charsToTokens(chars){if(chars<=0)return 0;return Math.ceil(chars*0.33)}function allocateInjectionBudget(systemEnhancerDemandTokens,knowledgeInjectorDemandChars,config3){let budget=config3.totalBudgetTokens,seDemand=Math.max(0,systemEnhancerDemandTokens),kiChars=Math.max(0,knowledgeInjectorDemandChars),ceiling=Math.max(0,budget),kiDemand=charsToTokens(kiChars);if(seDemand+kiDemand<=ceiling)return{systemEnhancerTokens:seDemand,knowledgeInjectorTokens:kiDemand,totalTokens:seDemand+kiDemand};if(seDemand>=ceiling)return{systemEnhancerTokens:ceiling,knowledgeInjectorTokens:0,totalTokens:ceiling};if(kiDemand>=ceiling)return{systemEnhancerTokens:0,knowledgeInjectorTokens:ceiling,totalTokens:ceiling};let totalDemand=seDemand+kiDemand,seShare=Math.floor(seDemand/totalDemand*ceiling),kiShare=ceiling-seShare;return{systemEnhancerTokens:seShare,knowledgeInjectorTokens:kiShare,totalTokens:ceiling}}var sessionBudgets=new Map,MAX_TRACKED_SESSIONS4=256;function evictSessionBudgets(){while(sessionBudgets.size>MAX_TRACKED_SESSIONS4){let firstKey=sessionBudgets.keys().next().value;if(firstKey===void 0)break;sessionBudgets.delete(firstKey)}}function resetUnifiedBudget(sessionID,totalBudget){sessionBudgets.set(sessionID,{total:totalBudget,used:0,seDemand:0}),evictSessionBudgets()}function setSystemEnhancerDemand(sessionID,demand){let budget=sessionBudgets.get(sessionID);if(!budget)return;budget.seDemand=demand}function getSystemEnhancerDemand(sessionID){return sessionBudgets.get(sessionID)?.seDemand??0}init_telemetry();init_co_change_analyzer();init_utils();init_constants();init_schema();init_arg_hash();import*as fs112 from"node:fs/promises";import*as path218 from"node:path";function safeGet(obj,key){if(!obj||!Object.hasOwn(obj,key))return;return obj[key]}function resolveAgentModel(agentName,config3){let baseName=stripKnownSwarmPrefix(agentName).toLowerCase(),agentOverride=safeGet(config3.agents,baseName)?.model;if(agentOverride)return agentOverride;if(config3.swarms)for(let swarm of Object.values(config3.swarms)){let swarmModel=safeGet(swarm.agents,baseName)?.model;if(swarmModel)return swarmModel}return safeGet(DEFAULT_MODELS,baseName)??DEFAULT_MODELS.default}function detectAdversarialPair(agentA,agentB,config3){let modelA=resolveAgentModel(agentA,config3).toLowerCase(),modelB=resolveAgentModel(agentB,config3).toLowerCase();return modelA===modelB?modelA:null}function formatAdversarialWarning(agentA,agentB,sharedModel,policy){if(policy==="gate")return`⚠️ GATE POLICY: Same-model adversarial pair detected. Agent ${agentA} and checker ${agentB} both use model ${sharedModel}. This requires extra scrutiny — escalate if issues are found.`;return`⚠️ Same-model adversarial pair detected. Agent ${agentA} and checker ${agentB} both use model ${sharedModel}. Review may lack independence.`}var PRECEDENT_MANIPULATION_PATTERNS=[/we skipped .* in phase \d+/i,/consistent with how we handled/i,/going forward/i,/the reviewer didn't flag this pattern before/i,/this is consistent with/i,/we should continue/i],SELF_REVIEW_PATTERNS=[/I (verified|checked|reviewed|validated).*(myself|my own)/i,/I (think|believe) this (looks|is) correct/i,/this (looks|seems|appears) (good|correct|fine)/i],CONTENT_EXEMPTION_PATTERNS=[/documentation doesn't need/i,/config changes are trivial/i,/just a (rename|refactor|typo)/i,/test files don't need/i,/this is (just|only) a/i,/no need for (review|the full)/i],GATE_DELEGATION_BYPASS_PATTERNS=[/I verified the changes/i,/code looks correct to me/i,/the code looks (good|fine)/i,/task marked complete/i,/I (checked|reviewed).*myself/i,/edit tool on (src|tests|config)/i,/write tool on (src|tests|config)/i,/writeCount.*\d+.*source/i,/I'll just make this small fix directly/i,/It's faster if I do it myself/i,/edit tool on.*plan\.md/i,/write tool on.*plan\.md/i,/\[ \].*to \[x\].*in plan\.md/i,/status.*pending.*complete.*plan\.json/i,/I'll just mark this one as done/i,/mark it done directly/i,/SPEC_STALENESS_SKIP/i,/SWARM_SKIP_SPEC_GATE/i],GATE_MISCLASSIFICATION_PATTERNS=[/(?:src\/|source\/|source\s+code|source\s+file).*tier\s*[01]/i,/tier\s*[01].*(?:src\/|source\/|source\s+code|source\s+file)/i,/(?:security|auth|crypto|secret|credential|permission).*tier\s*[012]/i,/tier\s*[012].*(?:security|auth|crypto|secret|credential|permission)/i,/below\s+tier\s*3.*(?:security|auth|crypto|secret|credential|permission)/i,/classification[:\s-]*tier\s*[01]/i,/tier\s*[01][\s:]*classification/i,/(?:small|trivial|minor).*tier\s*[01]/i,/tier\s*[01].*(?:small|trivial|minor)/i,/(?:small|trivial|minor).*(?:classification|classified|assigned).*tier/i,/(?:classification|classified|assigned).*(?:small|trivial|minor).*tier/i,/pipeline\s+started.*(?:assigning|setting|classifying).*tier/i,/(?:assigning|setting|classifying).*tier.*after.*pipeline/i,/tier.*assigned.*(?:after|retroactive)/i,/retroactive.*(?:tier|classification)/i],VELOCITY_RATIONALIZATION_PATTERNS=[/to save time/i,/since we're behind/i,/quick fix/i,/review.*later/i,/in the interest of efficiency/i,/we can (review|check).*later/i,/for (speed|efficiency)/i],INTER_AGENT_MANIPULATION_PATTERNS=[/\b(5th|fifth|final|last)\s+(attempt|try|time)\b/i,/\bthis\s+is\s+(blocking|blocking\s+everything|critical|urgent)\b/i,/\bwe('re|\s+are)\s+(behind|late|running\s+out\s+of\s+time)\b/i,/\buser\s+is\s+waiting\b/i,/\bship\s+(this|it)\s+(now|today|immediately)\b/i,/\b(I'm|I\s+am)\s+(frustrated|disappointed|sad|upset)\b/i,/\bthis\s+is\s+(frustrating|disappointing)\b/i,/\b(I've|I\s+have)\s+been\s+working\s+on\s+this\b/i,/\bplease\s+(help|approve|pass)\b/i,/\bor\s+I('ll|\s+will)\s+(stop|halt|pause)\b/i,/\bor\s+all\s+work\s+stops\b/i,/\bI('ll|\s+will)\s+have\s+to\s+alert\s+the\s+user\b/i,/\bthis\s+will\s+(delay|block)\s+everything\b/i,/\bjust\s+approve\s+this\b/i,/\bI\s+(need|want)\s+you\s+to\s+(approve|pass)\b/i,/\boverride\s+(this|the)\s+(check|gate|review)\b/i],REJECTION_SPIRAL_PATTERNS=[/\b(?:rejected|failed\s+review|needs\s+revision)\b.*\b(?:again|third\s+time|4th\s+time|5th\s+time|for\s+the\s+\d+(?:st|nd|rd|th)\s+time)\b/i,/\b(?:same\s+feedback|same\s+issues?)\b.*\b(?:again|repeated|multiple\s+times?)\b/i,/\b(?:stuck|trapped|endless|repeating)\b.*\b(?:loop|cycle)\b/i];function detectAdversarialPatterns(text){if(typeof text!=="string")return[];let matches=[];for(let pattern of PRECEDENT_MANIPULATION_PATTERNS){let match=text.match(pattern);if(match)matches.push({pattern:"PRECEDENT_MANIPULATION",severity:"HIGHEST",matchedText:match[0],confidence:"HIGH"})}for(let pattern of SELF_REVIEW_PATTERNS){let match=text.match(pattern);if(match)matches.push({pattern:"SELF_REVIEW",severity:"HIGH",matchedText:match[0],confidence:"HIGH"})}for(let pattern of CONTENT_EXEMPTION_PATTERNS){let match=text.match(pattern);if(match)matches.push({pattern:"CONTENT_EXEMPTION",severity:"HIGH",matchedText:match[0],confidence:"HIGH"})}for(let pattern of GATE_DELEGATION_BYPASS_PATTERNS){let match=text.match(pattern);if(match)matches.push({pattern:"GATE_DELEGATION_BYPASS",severity:"HIGHEST",matchedText:match[0],confidence:"HIGH"})}for(let pattern of GATE_MISCLASSIFICATION_PATTERNS){let match=text.match(pattern);if(match)matches.push({pattern:"GATE_MISCLASSIFICATION",severity:"HIGH",matchedText:match[0],confidence:"HIGH"})}for(let pattern of VELOCITY_RATIONALIZATION_PATTERNS){let match=text.match(pattern);if(match)matches.push({pattern:"VELOCITY_RATIONALIZATION",severity:"HIGH",matchedText:match[0],confidence:"HIGH"})}for(let pattern of INTER_AGENT_MANIPULATION_PATTERNS){let match=text.match(pattern);if(match)matches.push({pattern:"INTER_AGENT_MANIPULATION",severity:"HIGH",matchedText:match[0],confidence:"HIGH"})}for(let pattern of REJECTION_SPIRAL_PATTERNS){let match=text.match(pattern);if(match)matches.push({pattern:"REJECTION_SPIRAL",severity:"HIGH",matchedText:match[0],confidence:"HIGH"})}return matches}function formatDebuggingSpiralEvent(match,taskId){return JSON.stringify({event:"debugging_spiral_detected",taskId,pattern:match.pattern,severity:match.severity,matchedText:match.matchedText,confidence:match.confidence,timestamp:new Date().toISOString()})}async function handleDebuggingSpiral(match,taskId,directory){let eventLogged=!1,checkpointCreated=!1;try{let swarmDir=path218.join(directory,".swarm");await fs112.mkdir(swarmDir,{recursive:!0});let eventsPath=path218.join(swarmDir,"events.jsonl");await fs112.appendFile(eventsPath,`${formatDebuggingSpiralEvent(match,taskId)}
|
|
@@ -6127,7 +6127,7 @@ Do not stop or summarize. Inspect the durable gate, dispatch or collect the next
|
|
|
6127
6127
|
${output.text}`;return}let banner=workflowBanner(state.mode,{suspended,suspendedReason,userInterrupted,maxConsecutive,recovery});bannerStamps.set(input.sessionID,now),evictBannerDedupeMapsIfOverBound(),output.text=`${banner}
|
|
6128
6128
|
|
|
6129
6129
|
${output.text}`},_inspectWakeBudget:(sessionID)=>wakeBudgets.get(sessionID)}}init_pending_delegations();init_pr_workflow_gate();var MAX_PARENT_DEPTH=16,MAX_TRACKED_SESSION_PARENTS=512;function rememberBounded2(parents,childSessionID,parentSessionID){parents.delete(childSessionID),parents.set(childSessionID,parentSessionID);while(parents.size>MAX_TRACKED_SESSION_PARENTS){let oldest=parents.keys().next().value;if(typeof oldest!=="string")break;parents.delete(oldest)}}function createPrWorkflowSessionResolver(options){let session=options.client?.session,parents=new Map;return{observeEvent:(input)=>{let event=input.event;if(event?.type!=="session.created"&&event?.type!=="session.updated")return;let child=event.properties?.info?.id,parent=event.properties?.info?.parentID;if(typeof child==="string"&&child.trim()&&typeof parent==="string"&&parent.trim())rememberBounded2(parents,child.trim(),parent.trim())},resolve:async(sessionID)=>{let original=sessionID.trim();if(!original)return sessionID;let current=original,visited=new Set;for(let depth=0;depth<MAX_PARENT_DEPTH;depth+=1){if(visited.has(current))break;if(visited.add(current),await readPrWorkflowGateState(options.directory,current))return current;let parent=parents.get(current);if(!parent)parent=findByCorrelationId(options.directory,current)?.parentSessionId;if(!parent&&session?.get){let result=await session.get({path:{id:current},query:{directory:options.directory}});if(result?.error==null){let candidate2=result?.data?.parentID;if(typeof candidate2==="string"&&candidate2.trim())parent=candidate2.trim()}}if(!parent)return original;rememberBounded2(parents,current,parent),current=parent}return original}}}init_review_receipt_collector();init_schema();init_scope_binding();init_state2();init_normalize_tool_name();init_review_receipt();init_review_receipt_scope();init_reviewer_scope_file_fingerprint();init_skill_propagation_gate();init_task_result_classifier();function lifecycleTarget(args2){let delegation=parseDelegationArgs(args2);return delegation?stripKnownSwarmPrefix(delegation.targetAgent).toLowerCase():""}function isTaskTool6(tool3){if(typeof tool3!=="string")return!1;let normalized=normalizeToolName(tool3);return normalized==="Task"||normalized==="task"}function generationFingerprintsAreCurrent(directory,generation){let{modifiedFiles,modifiedFileFingerprints:fingerprints}=generation;if(modifiedFiles.length===0||modifiedFiles.length!==fingerprints.length||new Set(modifiedFiles).size!==modifiedFiles.length||new Set(fingerprints.map((entry)=>entry.file)).size!==fingerprints.length)return!1;let fingerprintBytes=0;for(let file3 of modifiedFiles){let stored=fingerprints.filter((entry)=>entry.file===file3),current=captureReviewerScopeFileFingerprint(directory,file3,MAX_REVIEWER_SCOPE_FINGERPRINT_AGGREGATE_BYTES-fingerprintBytes);if(stored.length!==1||!current||!reviewerScopeFileFingerprintsEqual(stored[0],current))return!1;if(current.kind==="file")fingerprintBytes+=current.size}return!0}function scopeMatchesGenerationFingerprints(scope,generation){let records=new Map;for(let line of scope.content.split(`
|
|
6130
|
-
`).slice(1)){if(!line)continue;try{let parsed=JSON.parse(line);if(typeof parsed.path==="string")records.set(parsed.path,parsed)}catch{return!1}}if(records.size!==generation.modifiedFileFingerprints.length||scope.files.length!==generation.modifiedFiles.length)return!1;return generation.modifiedFileFingerprints.every((fingerprint)=>{let record3=records.get(fingerprint.file);if(!record3)return!1;return fingerprint.kind==="deleted"?record3.state==="deleted":record3.state==="file"&&record3.bytes===fingerprint.size&&record3.sha256===fingerprint.hash})}async function beginApprovedReviewerScopeLifecycle(input){if(!isTaskTool6(input.tool))return null;let taskId=await resolveReviewerScopeTaskId(input.directory,input.args);if(!taskId)return null;let target=lifecycleTarget(input.args);if(target==="coder"){let binding=getScopeBindingForParentDispatch({parentSessionId:input.parentSessionID,dispatchCallId:input.callID});if(binding?.taskId!==taskId)return null;let rawArgs=input.args&&typeof input.args==="object"?input.args:null;return startReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID,background:rawArgs?.background===!0||rawArgs?.background==="true",declaredFiles:binding.files})?"coder_started":null}if(target==="reviewer"){let ready=peekReadyReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId});if(!ready||!generationFingerprintsAreCurrent(input.directory,ready)){if(ready)discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID});throw Error("REVIEWER_SCOPE_STALE: coder post-write fingerprints are incomplete or changed before reviewer dispatch")}let snapshot=await buildReviewerTaskScope(input.directory,ready.modifiedFiles,input.maxBytes,{taskId:ready.taskId,coderCallID:ready.coderCallID,generation:ready.generation,sessionIncarnation:ready.sessionIncarnation}),current=peekReadyReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId}),exactGenerationStillCurrent=current!==null&¤t.coderCallID===ready.coderCallID&¤t.generation===ready.generation&¤t.sessionIncarnation===ready.sessionIncarnation&&isReviewerScopeGenerationCurrent({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID,generation:ready.generation,sessionIncarnation:ready.sessionIncarnation});if(!snapshot||!current||!exactGenerationStillCurrent||!generationFingerprintsAreCurrent(input.directory,current)||!scopeMatchesGenerationFingerprints(snapshot,current))throw discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID}),Error("REVIEWER_SCOPE_STALE: exact reviewer dispatch scope changed during capture");let claimed=claimReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID});if(!claimed||claimed.coderCallID!==ready.coderCallID||claimed.generation!==ready.generation||claimed.sessionIncarnation!==ready.sessionIncarnation||!attachReviewerScopeGenerationDispatchSnapshot({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID,snapshot:{hash:computeScopeFingerprint(snapshot.content,snapshot.description).hash,description:snapshot.description,files:[...snapshot.files],headSha:snapshot.headSha,taskId:claimed.taskId,coderCallID:claimed.coderCallID,generation:claimed.generation,sessionIncarnation:claimed.sessionIncarnation}}))throw discardReviewerScopeGenerationClaim({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID}),Error("REVIEWER_SCOPE_STALE: exact reviewer dispatch scope could not be captured");return"reviewer_claimed"}return null}async function completeReviewerScopeLifecycle(input){if(!isTaskTool6(input.tool))return null;if(lifecycleTarget(input.args)!=="coder")return null;let result=classifyTaskResult(input.output);if(result==="running")return null;let taskId=await resolveReviewerScopeTaskId(input.directory,input.args);if(!taskId)return discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,coderCallID:input.callID}),null;if(result==="non_success")return discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID}),null;return markReviewerScopeGenerationReady({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID})?"coder_ready":null}init_schema();init_bun_compat();init_logger();var import_picomatch2=__toESM(require_picomatch2(),1);import{existsSync as existsSync116,readdirSync as readdirSync34,readFileSync as readFileSync90,statSync as statSync47}from"node:fs";import*as path233 from"node:path";var PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"]);function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path233.resolve(directory),resolved=path233.resolve(baseDir,concrete),rel=path233.relative(baseDir,resolved);if(rel.startsWith("..")||path233.isAbsolute(rel))return null}return v}function findBinaryInPath(binary){let candidates=process.platform==="win32"?[`${binary}.exe`,`${binary}.cmd`,`${binary}.bat`,binary]:[binary];for(let dir of(process.env.PATH??"").split(path233.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path233.join(dir,name);if(existsSync116(candidate2))return candidate2}}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve87)=>setTimeout(()=>resolve87("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let pattern;try{pattern=new RegExp(regex,"m")}catch(err){return{result:"error",detail:`grep: invalid regex ${err instanceof Error?err.message:String(err)}`}}let matcher=import_picomatch2.default(glob,{dot:!0}),visited=0,matches=0,walk=(dir)=>{if(visited>=GREP_MAX_FILES)return;let entries;try{entries=readdirSync34(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(visited>=GREP_MAX_FILES)return;let fullPath=path233.join(dir,entry.name),relPath=path233.relative(directory,fullPath).replace(/\\/g,"/");if(entry.isDirectory()){if(!GREP_SKIP_DIRECTORIES.has(entry.name))walk(fullPath);continue}if(!entry.isFile())continue;if(visited++,!matcher(relPath))continue;try{if(statSync47(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync90(fullPath,"utf-8").match(pattern);if(found)matches+=found.length}catch{}}};if(walk(directory),visited>=GREP_MAX_FILES)return{result:"error",detail:`grep: file scan exceeded ${GREP_MAX_FILES} files`};if(matches===0)return{result:"pass",detail:"grep: zero matches"};return{result:"fail",detail:`grep: ${matches} match(es) found`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git2=findBinaryInPath("git");if(!git2)return null;let res=await runArgv([git2,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path233.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe=validateRepoRelativeGlob(directory,rest);if(safe===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed=await changedPaths(directory);if(changed===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path233.normalize(safe),isChanged=changed.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}init_knowledge_escalator();init_knowledge_events();init_skill_propagation_gate();var VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([A-Za-z0-9._-]{1,80})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi;function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),id=m[2],evidence2=m[3]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({id,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[]};try{let verifyById=new Map(params.directivesToVerify.map((d)=>[d.id,d]));if(verifyById.size===0)return result;let verdicts=parseReviewerDirectiveCompliance(params.transcript),addressed=new Set,violatedIds=new Set,traceId=newTraceId2(),sessionId=params.sessionId??"unknown",agent=params.agent??"reviewer";for(let v of verdicts){let directive=verifyById.get(v.id);if(!directive)continue;addressed.add(v.id);let type=verdictToEventType(v.verdict),predicateCheck;if(v.verdict==="violated"&&directive.verification_predicate){let outcome=await runDirectivePredicate(directive.verification_predicate,params.directory);predicateCheck={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}if(await recordKnowledgeEvent(params.directory,{type,trace_id:traceId,knowledge_id:v.id,session_id:sessionId,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:v.evidence,predicate_check:predicateCheck}),type==="violated")violatedIds.add(v.id);result.emitted.push({id:v.id,type,source:"reviewer"})}for(let d of params.directivesToVerify){if(d.priority!=="critical")continue;if(addressed.has(d.id))continue;result.omittedCriticals.push(d.id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:d.id,session_id:sessionId,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:"reviewer_omitted"}),violatedIds.add(d.id),result.emitted.push({id:d.id,type:"violated",source:"reviewer"})}if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}function isTaskTool7(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool7(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}init_constants();init_schema();init_scope_binding();init_scope_persistence();init_state2();init_normalize_tool_name();init_pr_workflow_gate();init_write_target_resolver();import*as path234 from"node:path";var WRITE_TOOLS2=new Set(WRITE_TOOL_NAMES);function createScopeGuardHook(config3,fallbackDirectory,injectAdvisory){let enabled=config3.enabled??!0,_skipInTurbo=config3.skip_in_turbo??!1;return{toolBefore:async(input,output)=>{if(!enabled)return;let toolName=normalizeToolName(input.tool);if(!WRITE_TOOLS2.has(toolName))return;let sessionId=input.sessionID,activeAgent=swarmState.activeAgent.get(sessionId),session=swarmState.agentSessions.get(sessionId),agentName=activeAgent??session?.agentName??"unknown",agentRole=stripKnownSwarmPrefix(agentName);if(agentRole===ORCHESTRATOR_NAME)return;if(agentRole!=="coder")return;let directory=_internals162.resolveSessionWorkspaceDirectory(sessionId,fallbackDirectory),targets=_internals162.resolveWriteTargets(toolName,output.args,{directory});if(targets.status==="unverifiable")throw Error(`WRITE TARGET UNVERIFIABLE: ${agentName} invoked ${toolName}: ${targets.reason}`);if(targets.paths.length===0)return;let taskId=_internals162.resolveTaskId(session),binding=taskId?_internals162.resolveAuthorizedScopeBinding({directory,taskId,activeSessionId:sessionId}):_internals162.resolveAuthorizedScopeBindingForSession({directory,activeSessionId:sessionId});if(!binding){if(binding=_internals162.getAuthorizedPrFeedbackScopeBinding({directory,activeSessionId:sessionId,taskId:taskId??void 0})??_internals162.resolveAuthorizedPrFeedbackScopeBindingFromDisk({directory,activeSessionId:sessionId,taskId:taskId??void 0}),binding&&!await _internals162.validatePrFeedbackScopeBinding(directory,binding))binding=null}if(!taskId&&binding&&session)taskId=binding.taskId,session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];let declaredScope=binding?.files??null;if(!declaredScope||declaredScope.length===0){let mismatch=_internals162.describeScopeWorkspaceMismatch({directory,activeSessionId:sessionId,taskId});if(mismatch)throw Error(`${mismatch} ${agentName} cannot invoke ${toolName} for task ${taskId??"unknown"}.`);throw Error(`SCOPE_NOT_DECLARED: ${agentName} cannot invoke ${toolName} without a validated scope for task ${taskId??"unknown"}.`)}for(let rawPath of targets.paths){let filePath=sanitizePath(rawPath);if(!isFileInScope(filePath,declaredScope,directory))reportScopeViolation(agentName,filePath,taskId,session,injectAdvisory,swarmState,declaredScope)}}}}function isFileInScope(filePath,scopeEntries,directory){let dir=directory??process.cwd(),resolvedFile=path234.resolve(dir,filePath);return scopeEntries.filter((scope)=>scope.length>0).some((scope)=>{let resolvedScope=path234.resolve(dir,scope);if(resolvedFile===resolvedScope)return!0;let rel=path234.relative(resolvedScope,resolvedFile);return rel.length>0&&!rel.startsWith("..")&&!path234.isAbsolute(rel)})}function sanitizePath(raw){let result="";for(let i=0;i<raw.length;i++){let c=raw.charCodeAt(i);if(c<=31||c===127||c>=128&&c<=159){result+="_";continue}result+=raw[i]}return result.replace(/\[[\d;]*m/g,"")}var _internals162={sanitizePath,resolveWriteTargets:resolveWriteTargets2,resolveAuthorizedScopeBinding,resolveAuthorizedScopeBindingForSession,getAuthorizedPrFeedbackScopeBinding,resolveAuthorizedPrFeedbackScopeBindingFromDisk,validatePrFeedbackScopeBinding,resolveSessionWorkspaceDirectory,describeScopeWorkspaceMismatch,resolveTaskId:(session)=>session?.currentTaskId??null};function reportScopeViolation(agentName,filePath,taskId,session,injectAdvisory,state,scopeEntries){let violationMessage=`SCOPE VIOLATION: ${agentName} attempted to modify '${filePath}' which is not in declared scope for task ${taskId??"unknown"}. Declared scope: [${scopeEntries.slice(0,3).join(", ")}${scopeEntries.length>3?"...":""}]`;if(session)session.lastScopeViolation=violationMessage,session.scopeViolationDetected=!0;if(injectAdvisory)for(let[archSessionId,archSession]of state.agentSessions){let archAgent=state.activeAgent.get(archSessionId)??archSession.agentName;if(stripKnownSwarmPrefix(archAgent)===ORCHESTRATOR_NAME){try{injectAdvisory(archSessionId,`[SCOPE GUARD] ${violationMessage}`)}catch{}break}}throw Error(violationMessage)}init_constants();init_schema();init_state2();init_normalize_tool_name();function createSelfReviewHook(config3,injectAdvisory){let enabled=config3.enabled??!0,skipInTurbo=config3.skip_in_turbo??!0;return{toolAfter:async(input,output)=>{if(!enabled)return;if(normalizeToolName(input.tool)!=="update_task_status")return;let args2=output.args;if(args2?.status!=="in_progress")return;let taskId=typeof args2?.task_id==="string"?args2.task_id:"unknown",sessionId=input.sessionID,agentName=swarmState.activeAgent.get(sessionId)??swarmState.agentSessions.get(sessionId)?.agentName??"";if(stripKnownSwarmPrefix(agentName)!==ORCHESTRATOR_NAME)return;if(skipInTurbo){let session=swarmState.agentSessions.get(sessionId);if(session&&session.turboMode===!0)return}let advisory=[`[SELF-REVIEW] Task ${taskId} is now delegated to coder.`,"After coder completes, review for:"," • Broken conditionals (inverted if/else, wrong comparisons)"," • Off-by-one errors (array bounds, loop indices)"," • Assumptions contradicting existing codebase patterns"," • Missing error handling (uncaught exceptions, unhandled promises)"," • Scope creep (changes outside the declared task spec)","Delegate to critic with self-review focus before marking complete."].join(`
|
|
6130
|
+
`).slice(1)){if(!line)continue;try{let parsed=JSON.parse(line);if(typeof parsed.path==="string")records.set(parsed.path,parsed)}catch{return!1}}if(records.size!==generation.modifiedFileFingerprints.length||scope.files.length!==generation.modifiedFiles.length)return!1;return generation.modifiedFileFingerprints.every((fingerprint)=>{let record3=records.get(fingerprint.file);if(!record3)return!1;return fingerprint.kind==="deleted"?record3.state==="deleted":record3.state==="file"&&record3.bytes===fingerprint.size&&record3.sha256===fingerprint.hash})}async function beginApprovedReviewerScopeLifecycle(input){if(!isTaskTool6(input.tool))return null;let taskId=await resolveReviewerScopeTaskId(input.directory,input.args);if(!taskId)return null;let target=lifecycleTarget(input.args);if(target==="coder"){let binding=getScopeBindingForParentDispatch({parentSessionId:input.parentSessionID,dispatchCallId:input.callID});if(binding?.taskId!==taskId)return null;let rawArgs=input.args&&typeof input.args==="object"?input.args:null;return startReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID,background:rawArgs?.background===!0||rawArgs?.background==="true",declaredFiles:binding.files})?"coder_started":null}if(target==="reviewer"){let ready=peekReadyReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId});if(!ready||!generationFingerprintsAreCurrent(input.directory,ready)){if(ready)discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID});throw Error("REVIEWER_SCOPE_STALE: coder post-write fingerprints are incomplete or changed before reviewer dispatch")}let snapshot=await buildReviewerTaskScope(input.directory,ready.modifiedFiles,input.maxBytes,{taskId:ready.taskId,coderCallID:ready.coderCallID,generation:ready.generation,sessionIncarnation:ready.sessionIncarnation}),current=peekReadyReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId}),exactGenerationStillCurrent=current!==null&¤t.coderCallID===ready.coderCallID&¤t.generation===ready.generation&¤t.sessionIncarnation===ready.sessionIncarnation&&isReviewerScopeGenerationCurrent({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID,generation:ready.generation,sessionIncarnation:ready.sessionIncarnation});if(!snapshot||!current||!exactGenerationStillCurrent||!generationFingerprintsAreCurrent(input.directory,current)||!scopeMatchesGenerationFingerprints(snapshot,current))throw discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID}),Error("REVIEWER_SCOPE_STALE: exact reviewer dispatch scope changed during capture");let claimed=claimReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID});if(!claimed||claimed.coderCallID!==ready.coderCallID||claimed.generation!==ready.generation||claimed.sessionIncarnation!==ready.sessionIncarnation||!attachReviewerScopeGenerationDispatchSnapshot({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID,snapshot:{hash:computeScopeFingerprint(snapshot.content,snapshot.description).hash,description:snapshot.description,files:[...snapshot.files],headSha:snapshot.headSha,taskId:claimed.taskId,coderCallID:claimed.coderCallID,generation:claimed.generation,sessionIncarnation:claimed.sessionIncarnation}}))throw discardReviewerScopeGenerationClaim({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID}),Error("REVIEWER_SCOPE_STALE: exact reviewer dispatch scope could not be captured");return"reviewer_claimed"}return null}async function completeReviewerScopeLifecycle(input){if(!isTaskTool6(input.tool))return null;if(lifecycleTarget(input.args)!=="coder")return null;let result=classifyTaskResult(input.output);if(result==="running")return null;let taskId=await resolveReviewerScopeTaskId(input.directory,input.args);if(!taskId)return discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,coderCallID:input.callID}),null;if(result==="non_success")return discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID}),null;return markReviewerScopeGenerationReady({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID})?"coder_ready":null}init_schema();init_bun_compat();init_logger();var import_picomatch2=__toESM(require_picomatch2(),1);import{existsSync as existsSync116,readdirSync as readdirSync33,readFileSync as readFileSync90,statSync as statSync46}from"node:fs";import*as path233 from"node:path";var PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"]);function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path233.resolve(directory),resolved=path233.resolve(baseDir,concrete),rel=path233.relative(baseDir,resolved);if(rel.startsWith("..")||path233.isAbsolute(rel))return null}return v}function findBinaryInPath(binary){let candidates=process.platform==="win32"?[`${binary}.exe`,`${binary}.cmd`,`${binary}.bat`,binary]:[binary];for(let dir of(process.env.PATH??"").split(path233.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path233.join(dir,name);if(existsSync116(candidate2))return candidate2}}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve87)=>setTimeout(()=>resolve87("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let pattern;try{pattern=new RegExp(regex,"m")}catch(err){return{result:"error",detail:`grep: invalid regex ${err instanceof Error?err.message:String(err)}`}}let matcher=import_picomatch2.default(glob,{dot:!0}),visited=0,matches=0,walk=(dir)=>{if(visited>=GREP_MAX_FILES)return;let entries;try{entries=readdirSync33(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(visited>=GREP_MAX_FILES)return;let fullPath=path233.join(dir,entry.name),relPath=path233.relative(directory,fullPath).replace(/\\/g,"/");if(entry.isDirectory()){if(!GREP_SKIP_DIRECTORIES.has(entry.name))walk(fullPath);continue}if(!entry.isFile())continue;if(visited++,!matcher(relPath))continue;try{if(statSync46(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync90(fullPath,"utf-8").match(pattern);if(found)matches+=found.length}catch{}}};if(walk(directory),visited>=GREP_MAX_FILES)return{result:"error",detail:`grep: file scan exceeded ${GREP_MAX_FILES} files`};if(matches===0)return{result:"pass",detail:"grep: zero matches"};return{result:"fail",detail:`grep: ${matches} match(es) found`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git2=findBinaryInPath("git");if(!git2)return null;let res=await runArgv([git2,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path233.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe=validateRepoRelativeGlob(directory,rest);if(safe===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed=await changedPaths(directory);if(changed===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path233.normalize(safe),isChanged=changed.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}init_knowledge_escalator();init_knowledge_events();init_skill_propagation_gate();var VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([A-Za-z0-9._-]{1,80})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi;function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),id=m[2],evidence2=m[3]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({id,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[]};try{let verifyById=new Map(params.directivesToVerify.map((d)=>[d.id,d]));if(verifyById.size===0)return result;let verdicts=parseReviewerDirectiveCompliance(params.transcript),addressed=new Set,violatedIds=new Set,traceId=newTraceId2(),sessionId=params.sessionId??"unknown",agent=params.agent??"reviewer";for(let v of verdicts){let directive=verifyById.get(v.id);if(!directive)continue;addressed.add(v.id);let type=verdictToEventType(v.verdict),predicateCheck;if(v.verdict==="violated"&&directive.verification_predicate){let outcome=await runDirectivePredicate(directive.verification_predicate,params.directory);predicateCheck={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}if(await recordKnowledgeEvent(params.directory,{type,trace_id:traceId,knowledge_id:v.id,session_id:sessionId,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:v.evidence,predicate_check:predicateCheck}),type==="violated")violatedIds.add(v.id);result.emitted.push({id:v.id,type,source:"reviewer"})}for(let d of params.directivesToVerify){if(d.priority!=="critical")continue;if(addressed.has(d.id))continue;result.omittedCriticals.push(d.id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:d.id,session_id:sessionId,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:"reviewer_omitted"}),violatedIds.add(d.id),result.emitted.push({id:d.id,type:"violated",source:"reviewer"})}if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}function isTaskTool7(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool7(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}init_constants();init_schema();init_scope_binding();init_scope_persistence();init_state2();init_normalize_tool_name();init_pr_workflow_gate();init_write_target_resolver();import*as path234 from"node:path";var WRITE_TOOLS2=new Set(WRITE_TOOL_NAMES);function createScopeGuardHook(config3,fallbackDirectory,injectAdvisory){let enabled=config3.enabled??!0,_skipInTurbo=config3.skip_in_turbo??!1;return{toolBefore:async(input,output)=>{if(!enabled)return;let toolName=normalizeToolName(input.tool);if(!WRITE_TOOLS2.has(toolName))return;let sessionId=input.sessionID,activeAgent=swarmState.activeAgent.get(sessionId),session=swarmState.agentSessions.get(sessionId),agentName=activeAgent??session?.agentName??"unknown",agentRole=stripKnownSwarmPrefix(agentName);if(agentRole===ORCHESTRATOR_NAME)return;if(agentRole!=="coder")return;let directory=_internals162.resolveSessionWorkspaceDirectory(sessionId,fallbackDirectory),targets=_internals162.resolveWriteTargets(toolName,output.args,{directory});if(targets.status==="unverifiable")throw Error(`WRITE TARGET UNVERIFIABLE: ${agentName} invoked ${toolName}: ${targets.reason}`);if(targets.paths.length===0)return;let taskId=_internals162.resolveTaskId(session),binding=taskId?_internals162.resolveAuthorizedScopeBinding({directory,taskId,activeSessionId:sessionId}):_internals162.resolveAuthorizedScopeBindingForSession({directory,activeSessionId:sessionId});if(!binding){if(binding=_internals162.getAuthorizedPrFeedbackScopeBinding({directory,activeSessionId:sessionId,taskId:taskId??void 0})??_internals162.resolveAuthorizedPrFeedbackScopeBindingFromDisk({directory,activeSessionId:sessionId,taskId:taskId??void 0}),binding&&!await _internals162.validatePrFeedbackScopeBinding(directory,binding))binding=null}if(!taskId&&binding&&session)taskId=binding.taskId,session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];let declaredScope=binding?.files??null;if(!declaredScope||declaredScope.length===0){let mismatch=_internals162.describeScopeWorkspaceMismatch({directory,activeSessionId:sessionId,taskId});if(mismatch)throw Error(`${mismatch} ${agentName} cannot invoke ${toolName} for task ${taskId??"unknown"}.`);throw Error(`SCOPE_NOT_DECLARED: ${agentName} cannot invoke ${toolName} without a validated scope for task ${taskId??"unknown"}.`)}for(let rawPath of targets.paths){let filePath=sanitizePath(rawPath);if(!isFileInScope(filePath,declaredScope,directory))reportScopeViolation(agentName,filePath,taskId,session,injectAdvisory,swarmState,declaredScope)}}}}function isFileInScope(filePath,scopeEntries,directory){let dir=directory??process.cwd(),resolvedFile=path234.resolve(dir,filePath);return scopeEntries.filter((scope)=>scope.length>0).some((scope)=>{let resolvedScope=path234.resolve(dir,scope);if(resolvedFile===resolvedScope)return!0;let rel=path234.relative(resolvedScope,resolvedFile);return rel.length>0&&!rel.startsWith("..")&&!path234.isAbsolute(rel)})}function sanitizePath(raw){let result="";for(let i=0;i<raw.length;i++){let c=raw.charCodeAt(i);if(c<=31||c===127||c>=128&&c<=159){result+="_";continue}result+=raw[i]}return result.replace(/\[[\d;]*m/g,"")}var _internals162={sanitizePath,resolveWriteTargets:resolveWriteTargets2,resolveAuthorizedScopeBinding,resolveAuthorizedScopeBindingForSession,getAuthorizedPrFeedbackScopeBinding,resolveAuthorizedPrFeedbackScopeBindingFromDisk,validatePrFeedbackScopeBinding,resolveSessionWorkspaceDirectory,describeScopeWorkspaceMismatch,resolveTaskId:(session)=>session?.currentTaskId??null};function reportScopeViolation(agentName,filePath,taskId,session,injectAdvisory,state,scopeEntries){let violationMessage=`SCOPE VIOLATION: ${agentName} attempted to modify '${filePath}' which is not in declared scope for task ${taskId??"unknown"}. Declared scope: [${scopeEntries.slice(0,3).join(", ")}${scopeEntries.length>3?"...":""}]`;if(session)session.lastScopeViolation=violationMessage,session.scopeViolationDetected=!0;if(injectAdvisory)for(let[archSessionId,archSession]of state.agentSessions){let archAgent=state.activeAgent.get(archSessionId)??archSession.agentName;if(stripKnownSwarmPrefix(archAgent)===ORCHESTRATOR_NAME){try{injectAdvisory(archSessionId,`[SCOPE GUARD] ${violationMessage}`)}catch{}break}}throw Error(violationMessage)}init_constants();init_schema();init_state2();init_normalize_tool_name();function createSelfReviewHook(config3,injectAdvisory){let enabled=config3.enabled??!0,skipInTurbo=config3.skip_in_turbo??!0;return{toolAfter:async(input,output)=>{if(!enabled)return;if(normalizeToolName(input.tool)!=="update_task_status")return;let args2=output.args;if(args2?.status!=="in_progress")return;let taskId=typeof args2?.task_id==="string"?args2.task_id:"unknown",sessionId=input.sessionID,agentName=swarmState.activeAgent.get(sessionId)??swarmState.agentSessions.get(sessionId)?.agentName??"";if(stripKnownSwarmPrefix(agentName)!==ORCHESTRATOR_NAME)return;if(skipInTurbo){let session=swarmState.agentSessions.get(sessionId);if(session&&session.turboMode===!0)return}let advisory=[`[SELF-REVIEW] Task ${taskId} is now delegated to coder.`,"After coder completes, review for:"," • Broken conditionals (inverted if/else, wrong comparisons)"," • Off-by-one errors (array bounds, loop indices)"," • Assumptions contradicting existing codebase patterns"," • Missing error handling (uncaught exceptions, unhandled promises)"," • Scope creep (changes outside the declared task spec)","Delegate to critic with self-review focus before marking complete."].join(`
|
|
6131
6131
|
`);try{injectAdvisory(sessionId,advisory)}catch{}}}}init_skill_propagation_gate();init_skill_scoring();init_skill_usage_log();import*as path235 from"node:path";var SKILL_INJECTION_THRESHOLD=0.5,SKILL_INJECTION_TOP_N=5;function injectSkillsIntoDelegation(directory,args2,recommendedSkills,targetAgent,sessionID,options={}){if(!recommendedSkills||recommendedSkills.length===0)return{injected:!1,injectedSkills:[]};let promptRaw=args2.prompt;if(typeof promptRaw!=="string")return{injected:!1,injectedSkills:[]};let parsedDelegation=parseDelegationArgs(args2);if(!parsedDelegation)return{injected:!1,injectedSkills:[]};if(parsedDelegation.skillsField.trim())return{injected:!1,injectedSkills:[]};let qualified=recommendedSkills.filter((s)=>s.score>=SKILL_INJECTION_THRESHOLD);if(qualified.length===0){if(args2.prompt=`SKILLS: none
|
|
6132
6132
|
|
|
6133
6133
|
${promptRaw}`,!options.quiet)console.warn("[skill-propagation-gate] No skills above threshold 0.5 — injected SKILLS: none");try{writeWarnEvent(directory,{type:"skill_injection_decision",timestamp:new Date().toISOString(),decision:"none",target_agent:targetAgent,sessionID,reason:"no_skill_above_threshold",threshold:SKILL_INJECTION_THRESHOLD,considered:recommendedSkills.map((s)=>({skillPath:s.skillPath,score:s.score}))})}catch{}return{injected:!0,injectedSkills:[]}}let topSkills=qualified.slice(0,SKILL_INJECTION_TOP_N),newPrompt=`${`SKILLS: ${topSkills.map((s)=>{let desc=readSkillMetadata(s.skillPath,directory).description||"";if(!desc||desc==="No description provided")desc=path235.basename(path235.dirname(s.skillPath));return desc=desc.replace(/,/g,";"),`file:${s.skillPath} (-- ${desc})`}).join(", ")}`}
|
|
@@ -6234,9 +6234,9 @@ ${hint}`}]}return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0
|
|
|
6234
6234
|
`)){if(!line.trim())continue;try{let entry=JSON.parse(line),relativePath2=typeof entry.file==="string"?toWorkspaceRelativePath(entry.file,workspace):null;if(!relativePath2)continue;if(total++,matches.length>=maxResults)continue;let start=entry.range?.start??{},end=entry.range?.end??{};matches.push({file:relativePath2,lineNumber:typeof start.line==="number"?start.line+1:1,column:typeof start.column==="number"?start.column+1:1,endLineNumber:typeof end.line==="number"?end.line+1:1,endColumn:typeof end.column==="number"?end.column+1:1,text:typeof entry.text==="string"?entry.text:"",lines:typeof entry.lines==="string"?entry.lines.trimEnd():"",language:typeof entry.language==="string"?entry.language:void 0,metaVariables:entry.metaVariables&&typeof entry.metaVariables==="object"?entry.metaVariables:void 0})}catch{}}return{matches,total}}function validateGlobArg(kind,value){if(!value)return null;if(containsControlChars(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains invalid control characters`};if(containsPathTraversal(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains path traversal sequence`};return null}var ast_grep=createSwarmTool({description:"Read-only structural AST search using ast-grep. Searches code patterns with optional language and glob filters; does not rewrite files.",args:{pattern:exports_external.string().describe("ast-grep pattern to search for"),language:exports_external.string().optional().describe("Optional ast-grep language, e.g. ts, tsx, js, py, rust"),include:exports_external.string().optional().describe("Comma-separated include globs, passed to ast-grep --globs"),exclude:exports_external.string().optional().describe("Comma-separated exclude globs, passed to ast-grep as !glob"),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS2).describe("Maximum number of matches to return")},execute:async(args2,directory)=>{let pattern,language,include,exclude,maxResults=DEFAULT_MAX_RESULTS2;try{let obj=args2;pattern=typeof obj.pattern==="string"?obj.pattern:"",language=typeof obj.language==="string"?obj.language:void 0,include=typeof obj.include==="string"?obj.include:void 0,exclude=typeof obj.exclude==="string"?obj.exclude:void 0;let rawMaxResults=typeof obj.max_results==="number"?obj.max_results:DEFAULT_MAX_RESULTS2,sanitizedMaxResults=Number.isFinite(rawMaxResults)?rawMaxResults:DEFAULT_MAX_RESULTS2;maxResults=Math.min(Math.max(0,sanitizedMaxResults),HARD_CAP_RESULTS2)}catch{return JSON.stringify({error:!0,type:"invalid-pattern",message:"Could not parse ast_grep arguments"},null,2)}if(!pattern||pattern.trim()==="")return JSON.stringify({error:!0,type:"invalid-pattern",message:"Pattern cannot be empty"},null,2);if(pattern.length>MAX_PATTERN_LENGTH||containsControlChars(pattern))return JSON.stringify({error:!0,type:"invalid-pattern",message:`Pattern is invalid or exceeds ${MAX_PATTERN_LENGTH} characters`},null,2);if(language&&!/^[A-Za-z0-9_-]+$/.test(language))return JSON.stringify({error:!0,type:"invalid-pattern",message:"Language must contain only letters, numbers, _ or -"},null,2);let includeError=validateGlobArg("Include",include);if(includeError)return JSON.stringify(includeError,null,2);let excludeError=validateGlobArg("Exclude",exclude);if(excludeError)return JSON.stringify(excludeError,null,2);if(!fs131.existsSync(directory))return JSON.stringify({error:!0,type:"unknown",message:"Workspace directory does not exist"},null,2);let executable=_internals168.resolveAstGrepBinary();if(!executable)return JSON.stringify({error:!0,type:"ast-grep-not-found",message:"ast-grep executable not found. Install ast-grep and ensure ast-grep or sg is on PATH."},null,2);let sgArgs=["run","--pattern",pattern,"--json=stream","--color","never"];if(language)sgArgs.push("--lang",language);for(let glob of splitGlobPatterns(include))sgArgs.push("--globs",glob);for(let glob of splitGlobPatterns(exclude))sgArgs.push("--globs",`!${glob}`);sgArgs.push(".");let run=await _internals168.runExternalTool({executable,args:sgArgs,cwd:directory,timeoutMs:AST_GREP_TIMEOUT_MS,maxStdoutBytes:AST_GREP_MAX_STDOUT_BYTES,maxStderrBytes:AST_GREP_MAX_STDERR_BYTES});if(run.status==="timeout")return JSON.stringify({error:!0,type:"timeout",message:`ast-grep timed out after ${AST_GREP_TIMEOUT_MS}ms`},null,2);if(run.status==="spawn-error")return JSON.stringify({error:!0,type:"unknown",message:run.message??"ast-grep failed to start"},null,2);if(run.exitCode!==0&&run.stderr)return JSON.stringify({error:!0,type:"invalid-pattern",message:run.stderr.split(`
|
|
6235
6235
|
`)[0]},null,2);let{matches,total}=parseAstGrepStream(run.stdout,directory,maxResults);return JSON.stringify({matches,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,total,pattern,language,maxResults,outputTruncated:run.stdoutTruncated||run.stderrTruncated},null,2)}}),_internals168={resolveExecutableFromPath,resolveAstGrepBinary,runExternalTool,parseAstGrepStream};init_dist();init_create_tool();import*as fs132 from"node:fs";import*as path244 from"node:path";init_path_security();var WINDOWS_RESERVED_NAMES4=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks3(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES4.test(part))return!0;return!1}function isPathInWorkspace2(filePath,workspace){try{let resolvedPath=path244.resolve(workspace,filePath);if(!fs132.existsSync(resolvedPath))return!0;let realWorkspace=fs132.realpathSync(workspace),realResolvedPath=fs132.realpathSync(resolvedPath),relativePath2=path244.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path244.isAbsolute(relativePath2))return!1;return!0}catch{return!1}}function processFile(file3,cwd,exportedOnly){let ext=path244.extname(file3);if(containsControlChars(file3))return{file:file3,success:!1,error:"Path contains invalid control characters",errorType:"invalid-path"};if(containsPathTraversal(file3))return{file:file3,success:!1,error:"Path contains path traversal sequence",errorType:"path-traversal"};if(containsWindowsAttacks3(file3))return{file:file3,success:!1,error:"Path contains invalid Windows-specific sequence",errorType:"invalid-path"};if(!isPathInWorkspace2(file3,cwd))return{file:file3,success:!1,error:"Path is outside workspace",errorType:"path-outside-workspace"};let fullPath=path244.join(cwd,file3);if(!fs132.existsSync(fullPath))return{file:file3,success:!1,error:`File not found: ${file3}`,errorType:"file-not-found"};let syms;switch(ext){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(file3,cwd);break;case".py":case".pyw":syms=extractPythonSymbols(file3,cwd);break;case".rs":syms=extractRustSymbols(file3,cwd);break;case".go":syms=extractGoSymbols(file3,cwd);break;default:return{file:file3,success:!1,error:`Unsupported file extension: ${ext}. Supported: .ts, .tsx, .js, .jsx, .mjs, .cjs, .py, .pyw, .rs, .go`,errorType:"unsupported-language"}}let isEmptyFile=!1;try{if(fs132.statSync(fullPath).size===0)isEmptyFile=!0}catch{}if(syms.length===0)try{if(fs132.readFileSync(fullPath,"utf-8").trim().length===0)isEmptyFile=!0}catch{}if(isEmptyFile)return{file:file3,success:!0,symbols:[],error:"empty-file",errorType:"empty-file"};if(exportedOnly)syms=syms.filter((s)=>s.exported);return{file:file3,success:!0,symbols:syms}}var batch_symbols=createSwarmTool({description:"Extract symbols from multiple files in a single batch call. Accepts an array of file paths and returns per-file symbol summaries. One bad file does not crash the batch. Use for surveying a module when you need symbol information from multiple files at once.",args:{files:tool.schema.array(tool.schema.string()).describe("Array of file paths to extract symbols from"),exported_only:tool.schema.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols.")},execute:async(args2,directory)=>{let files,exportedOnly=!0;try{let obj=args2;if(!Array.isArray(obj.files))return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: files must be an array"},null,2);files=obj.files.map((f)=>String(f)),exportedOnly=obj.exported_only!==!1}catch{return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: could not extract files array"},null,2)}let cwd=directory,results=[];for(let file3 of files){let result=processFile(file3,cwd,exportedOnly);results.push(result)}let successCount=results.filter((r)=>r.success).length,failureCount=results.filter((r)=>!r.success).length,batchResult={results,totalFiles:files.length,successCount,failureCount};return JSON.stringify(batchResult,null,2)}});init_zod();init_discovery();init_manager2();init_bun_compat();init_logger();init_create_tool();var DEFAULT_TIMEOUT_MS4=300000,MAX_OUTPUT_BYTES6=10240,MAX_OUTPUT_LINES=100;function truncateOutput(output,maxLines=MAX_OUTPUT_LINES,maxBytes=MAX_OUTPUT_BYTES6){if(!output)return"";let truncated=output;if(truncated.length>maxBytes)truncated=truncated.slice(-maxBytes);let lines=truncated.split(`
|
|
6236
6236
|
`);if(lines.length>maxLines)return lines.slice(-maxLines).join(`
|
|
6237
|
-
`);return truncated}function getCommandKind(command){let lower=command.toLowerCase();if(lower.includes("typecheck")||lower.includes("check")||lower.includes("analyze")||lower.includes("lint"))return"typecheck";if(lower.includes("test")||lower.includes("spec")||lower.includes("jest")||lower.includes("vitest")||lower.includes("mocha")||lower.includes("pytest"))return"test";return"build"}function filterByMode(commands,mode){if(mode==="both")return commands;return commands.filter((cmd)=>getCommandKind(cmd.command)===mode)}async function executeCommand(command){let startTime=Date.now(),kind=getCommandKind(command.command),isWindows=process.platform==="win32",cmd,args2;if(isWindows&&!command.command.includes(" "))cmd=[command.command],args2=[];else if(isWindows)cmd=["cmd","/c",command.command],args2=[];else cmd=["/bin/sh"],args2=["-c",command.command];let result=bunSpawn([...cmd,...args2],{cwd:command.cwd,stdout:"pipe",stderr:"pipe",timeout:DEFAULT_TIMEOUT_MS4}),[exitCode,stdout,stderr]=await Promise.all([result.exited,result.stdout.text(),result.stderr.text()]),duration_ms=Date.now()-startTime;return{kind,command:command.command,cwd:command.cwd,exit_code:exitCode??-1,duration_ms,stdout_tail:truncateOutput(stdout),stderr_tail:truncateOutput(stderr)}}async function runBuildCheck(workingDir,input){let scope=input.scope??"all",mode=input.mode??"both",changedFiles=input.changed_files??[],discoveryResult=await discoverBuildCommands(workingDir,{scope,changedFiles}),commands=filterByMode(discoveryResult.commands,mode),runs=[],failedCount=0;for(let cmd of commands)try{let run=await executeCommand(cmd);if(runs.push(run),run.exit_code!==0)failedCount++}catch(error93){runs.push({kind:getCommandKind(cmd.command),command:cmd.command,cwd:cmd.cwd,exit_code:-1,duration_ms:0,stdout_tail:"",stderr_tail:error93 instanceof Error?error93.message:"Unknown error"}),failedCount++}let verdict,skipped_reason;if(runs.length===0)if(verdict="info",discoveryResult.skipped.length>0)skipped_reason=discoveryResult.skipped.map((s)=>`${s.ecosystem}: ${s.reason}`).join("; ");else skipped_reason="No build commands discovered (no toolchains found)";else if(failedCount>0)verdict="fail";else verdict="pass";return{verdict,runs,summary:{files_scanned:changedFiles.length,runs_count:runs.length,failed_count:failedCount,skipped_reason}}}var build_check=createSwarmTool({description:"Discover and run build commands for various ecosystems in a project directory. Supports build, typecheck, and test commands.",args:{scope:exports_external.enum(["changed","all"]).describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changed_files:exports_external.array(exports_external.string()).optional().describe('List of changed files when scope is "changed"'),mode:exports_external.enum(["build","typecheck","both"]).optional().describe('Mode: "build" for build commands, "typecheck" for type checking, "both" for all (default: both)')},async execute(args2,directory){let obj=args2,scope=obj.scope??"all",changedFiles=obj.changed_files??[],mode=obj.mode??"both",workingDir=directory,result=await runBuildCheck(workingDir,{scope,changed_files:changedFiles,mode}),evidence2={task_id:"build",type:"build",timestamp:new Date().toISOString(),agent:"build_check",verdict:result.verdict,summary:`${result.runs.length} build command(s) executed, ${result.summary.failed_count} failed`,runs:result.runs,files_scanned:result.summary.files_scanned,runs_count:result.summary.runs_count,failed_count:result.summary.failed_count,skipped_reason:result.summary.skipped_reason};try{await saveEvidence(workingDir,"build",evidence2)}catch(error93){log("Failed to save build evidence:",error93 instanceof Error?error93.message:String(error93))}return JSON.stringify(result,null,2)}});init_zod();init_manager2();init_task_id();init_create_tool();init_resolve_working_directory();import*as fs133 from"node:fs";import*as path245 from"node:path";var EVIDENCE_DIR=".swarm/evidence";function isValidTaskId4(taskId){return isStrictTaskId2(taskId)}function isPathWithinSwarm(filePath,workspaceRoot){let normalizedWorkspace=path245.resolve(workspaceRoot),swarmPath3=path245.join(normalizedWorkspace,".swarm","evidence");return path245.resolve(filePath).startsWith(swarmPath3)}function readEvidenceFile(evidencePath){if(!fs133.existsSync(evidencePath))return null;let content;try{content=fs133.readFileSync(evidencePath,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(content)}catch{return null}if(parsed&&typeof parsed==="object"&&Array.isArray(parsed.required_gates)&&typeof parsed.gates==="object"&&parsed.gates!==null)return parsed;return null}var check_gate_status=createSwarmTool({description:"Read-only tool to check the gate status of a specific task. Reads .swarm/evidence/{taskId}.json and returns structured JSON describing required, passed, and missing gates.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "1.2.3", "1.2.3.4")').describe('The task ID to check gate status for (e.g., "1.1", "2.3.1")'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/evidence/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let taskIdInput,workingDirInput;try{if(args2&&typeof args2==="object"){let obj=args2;taskIdInput=typeof obj.task_id==="string"?obj.task_id:void 0,workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}}catch{}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={taskId:taskIdInput??"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:dirResult.message,todo_scan:null};return JSON.stringify(errorResult,null,2)}if(directory=dirResult.directory,!taskIdInput)return JSON.stringify({taskId:"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid task_id: task_id is required",todo_scan:null},null,2);if(!isValidTaskId4(taskIdInput)){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`Invalid task_id format: "${taskIdInput}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3", "1.2.3.4")`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let evidencePath=path245.join(directory,EVIDENCE_DIR,`${taskIdInput}.json`);if(!isPathWithinSwarm(evidencePath,directory))return JSON.stringify({taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid path: evidence path validation failed",todo_scan:null},null,2);let evidenceData=readEvidenceFile(evidencePath);if(!evidenceData){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`No evidence file found for task "${taskIdInput}" at ${evidencePath}. Evidence file may be missing or invalid.`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let requiredGates=evidenceData.required_gates||[],gatesMap=evidenceData.gates||{},passedGates=[],missingGates=[];for(let requiredGate of requiredGates)if(gatesMap[requiredGate])passedGates.push(requiredGate);else missingGates.push(requiredGate);let status=missingGates.length===0?"all_passed":"incomplete",message;if(status==="all_passed")message=`All required gates have passed for task "${taskIdInput}".`;else message=`Task "${taskIdInput}" is incomplete. Missing gates: ${missingGates.join(", ")}.`;let secretscanVerdict="not_run";try{let evidenceResult=await loadEvidence(directory,taskIdInput);if(evidenceResult.status==="found"){let secretscanEntries=evidenceResult.bundle.entries.filter((entry)=>entry.type==="secretscan");if(secretscanEntries.length>0){let lastSecretscan=secretscanEntries[secretscanEntries.length-1];if(isSecretscanEvidence(lastSecretscan)){if(lastSecretscan.verdict==="fail"||lastSecretscan.verdict==="rejected"){if(secretscanVerdict="fail",missingGates.push("secretscan (BLOCKED — secrets detected)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan found secrets in prior scan. ${message}`}else if(lastSecretscan.verdict==="pass"||lastSecretscan.verdict==="approved"||lastSecretscan.verdict==="info")secretscanVerdict="pass"}}else message+=" Advisory: No secretscan evidence found for this task. Consider running secretscan."}}catch{}let todoScan=evidenceData.todo_scan;return JSON.stringify({taskId:taskIdInput,status,required_gates:requiredGates,passed_gates:passedGates,missing_gates:missingGates,gates:gatesMap,message,todo_scan:todoScan??null,secretscan_verdict:secretscanVerdict},null,2)}});init_checkpoint();init_co_change_analyzer();init_zod();init_pr_workflow_gate();init_create_tool();var CompletePrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),pr_head_sha:exports_external.string().trim().min(1).max(80)}).strict();async function executeCompletePrWorkflow(args2,directory,context={}){let parsed=CompletePrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow completion: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow completion requires an active sessionID"});try{let status=await completePrWorkflow(directory,context.sessionID,parsed.data.mode,parsed.data.pr_head_sha);return JSON.stringify({success:!0,mode:parsed.data.mode,pr_head_sha:parsed.data.pr_head_sha,status,ready_to_publish:status==="ready-to-publish",gate_cleared:status==="completed"})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var complete_pr_workflow=createSwarmTool({description:"Validate terminal PR workflow coverage. After the ordered PR_FEEDBACK gates permit one standalone commit, the first call requires a clean tree and a non-merge direct child of intake HEAD, then binds its structured upstream target; the second clears only after both the local tracking ref and an actual-remote query point to that exact commit.",args:{mode:CompletePrWorkflowArgsSchema.shape.mode,pr_head_sha:CompletePrWorkflowArgsSchema.shape.pr_head_sha},execute:executeCompletePrWorkflow});init_zod();init_utils2();init_state2();init_create_tool();init_resolve_working_directory();import*as fs134 from"node:fs";import*as path246 from"node:path";function extractMatches(regex,text){return Array.from(text.matchAll(regex))}function parseIdentifiers(description){let identifiers=new Set,backtickRegex=/`([^`]+)`/g;for(let match of extractMatches(backtickRegex,description))identifiers.add(match[1]);let camelCaseRegex=/\b([a-z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(camelCaseRegex,description)){let word=match[1];if(word==="the"||word==="and"||word==="for"||word==="have"||word==="this"||word==="with"||word==="from"||word==="they"||word==="been"||word==="will"||word==="your"||word==="also")continue;identifiers.add(word)}let pascalCaseRegex=/\b([A-Z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(pascalCaseRegex,description))identifiers.add(match[1]);let configKeyRegex=/\b([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+)\b/g;for(let match of extractMatches(configKeyRegex,description))identifiers.add(match[1]);let quotedPathRegex=/['"](\.{0,3}(?:src|lib|test)[/\\][^'"]+)['"]/g;for(let match of extractMatches(quotedPathRegex,description))identifiers.add(match[1]);return Array.from(identifiers)}function parseFilePaths(description,filesTouched){if(filesTouched&&Array.isArray(filesTouched)&&filesTouched.length>0)return filesTouched;let filePaths=[],srcPathRegex=/\b(?:src|lib|test|app|packages?)[/\\][a-zA-Z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)\b/g;for(let match of extractMatches(srcPathRegex,description))filePaths.push(match[0]);let genericPathRegex=/\b[a-zA-Z0-9_./-]+[/\\][a-zA-Z0-9_./-]+\.[a-zA-Z0-9]+(?=\s|$|[.,;])/g;for(let match of extractMatches(genericPathRegex,description)){let pathStr=match[0];if(pathStr.includes("src/")||pathStr.includes("src\\")||pathStr.includes("lib/")||pathStr.includes("lib\\")||pathStr.includes("test/")||pathStr.includes("test\\"))filePaths.push(pathStr)}return filePaths}function buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked){if(tasksBlocked>0)return`Blocked: ${tasksBlocked} task(s) with missing identifiers`;let verified=tasksChecked-tasksSkipped;if(tasksSkipped===tasksChecked)return`All ${tasksChecked} completed task(s) skipped — research/inventory tasks`;if(tasksSkipped>0)return`${verified} task(s) verified, ${tasksSkipped} skipped (research tasks)`;return`All ${tasksChecked} completed tasks verified successfully`}async function executeCompletionVerify(args2,directory){let phase=Number(args2.phase);if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase))return JSON.stringify({success:!1,phase,status:"blocked",reason:"Invalid phase number",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);if(hasActiveTurboMode(args2.sessionID))return JSON.stringify({success:!0,phase,status:"passed",reason:"Turbo Mode active — completion verification bypassed",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);let plan;try{let planPath=validateSwarmPath(directory,"plan.json"),planRaw=fs134.readFileSync(planPath,"utf-8");plan=JSON.parse(planRaw)}catch{return JSON.stringify({success:!0,phase,status:"passed",reason:"Cannot verify without plan.json",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let targetPhase=plan.phases.find((p)=>p.id===phase);if(!targetPhase){let result2={success:!1,phase,status:"blocked",reason:`Phase ${phase} not found in plan.json`,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]};return JSON.stringify(result2,null,2)}let tasksChecked=0,tasksSkipped=0,tasksBlocked=0,blockedTasks=[];for(let task2 of targetPhase.tasks){if(task2.status!=="completed")continue;tasksChecked++;let fileTargets=parseFilePaths(task2.description,task2.files_touched),identifiers=parseIdentifiers(task2.description);if(fileTargets.length===0){tasksSkipped++;continue}if(identifiers.length===0){blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers — cannot verify completion without identifiers"}),tasksBlocked++;continue}let foundIdentifiers=new Set,hasFileReadFailure=!1;for(let filePath of fileTargets){let normalizedPath2=filePath.replace(/\\/g,"/"),resolvedPath=path246.resolve(directory,normalizedPath2),projectRoot=path246.resolve(directory),relative58=path246.relative(projectRoot,resolvedPath);if(!(relative58===""||!relative58.startsWith("..")&&!path246.isAbsolute(relative58))){blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File path '${filePath}' escapes the project directory — cannot verify completion`}),hasFileReadFailure=!0;continue}let fileContent;try{fileContent=fs134.readFileSync(resolvedPath,"utf-8")}catch{blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File '${filePath}' not found — cannot verify completion`}),hasFileReadFailure=!0;continue}for(let identifier of identifiers)if(fileContent.includes(identifier))foundIdentifiers.add(identifier)}let foundCount=foundIdentifiers.size;if(hasFileReadFailure||foundCount===0){if(!hasFileReadFailure)blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers found in target files"});tasksBlocked++}}let now=new Date().toISOString(),result={success:tasksBlocked===0,phase,status:tasksBlocked===0?"passed":"blocked",reason:tasksBlocked>0?`COMPLETION_INCOMPLETE: ${tasksBlocked} task(s) blocked — missing identifiers or target files`:void 0,tasksChecked,tasksSkipped,tasksBlocked,blockedTasks};try{let evidenceDir=path246.join(directory,".swarm","evidence",`${phase}`),evidencePath=path246.join(evidenceDir,"completion-verify.json");fs134.mkdirSync(evidenceDir,{recursive:!0});let evidenceBundle={schema_version:"1.0.0",task_id:"completion-verify",created_at:now,entries:[{task_id:"completion-verify",type:"completion_verify",timestamp:now,agent:"completion_verify",verdict:tasksBlocked===0?"pass":"fail",summary:buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked),phase,tasks_checked:tasksChecked,tasks_skipped:tasksSkipped,tasks_blocked:tasksBlocked,blocked_tasks:blockedTasks}]};fs134.writeFileSync(evidencePath,JSON.stringify(evidenceBundle,null,2),"utf-8")}catch{}return JSON.stringify(result,null,2)}var completion_verify=createSwarmTool({description:"Deterministic pre-check verifying that plan task identifiers exist in their target source files before phase completion. Blocks if obviously incomplete.",args:{phase:exports_external.number().describe("The phase number to check"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},execute:async(args2,directory)=>{let parsedArgs;try{if(args2&&typeof args2==="object"){let obj=args2;parsedArgs={phase:typeof obj.phase==="number"?obj.phase:typeof obj.phase==="string"?Number(obj.phase):0,sessionID:typeof obj.sessionID==="string"?obj.sessionID:void 0,working_directory:typeof obj.working_directory==="string"?obj.working_directory:void 0}}else parsedArgs={phase:0}}catch{return JSON.stringify({success:!1,phase:0,status:"blocked",reason:"Invalid arguments",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let dirResult=resolveWorkingDirectory(parsedArgs.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:parsedArgs.phase,status:"blocked",reason:dirResult.message,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);return executeCompletionVerify(parsedArgs,dirResult.directory)}});init_zod();init_metrics();init_bun_compat();init_create_tool();init_path_security();import*as fs135 from"node:fs";import*as path247 from"node:path";var MAX_FILE_SIZE_BYTES5=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}async function getGitChurn(days,directory){let churnMap=new Map,proc=bunSpawn(["git","log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",cwd:directory}),[stdout]=await Promise.all([proc.stdout.text(),proc.exited]),lines=stdout.split(/\r?\n/);for(let line of lines){let normalizedPath2=line.replace(/\\/g,"/");if(!normalizedPath2||normalizedPath2.trim()==="")continue;if(normalizedPath2.includes("node_modules")||normalizedPath2.includes("/.git/")||normalizedPath2.includes("/dist/")||normalizedPath2.includes("/build/")||normalizedPath2.includes("__tests__"))continue;if(normalizedPath2.includes(".test.")||normalizedPath2.includes(".spec."))continue;churnMap.set(normalizedPath2,(churnMap.get(normalizedPath2)||0)+1)}return churnMap}function getComplexityForFile2(filePath){try{if(fs135.statSync(filePath).size>MAX_FILE_SIZE_BYTES5)return null;let content=fs135.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory){let churnMap=await getGitChurn(days,directory),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count]of churnMap){let ext=path247.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs135.existsSync(fullPath))fullPath=path247.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_schema();init_miner();init_miner();init_store3();async function mineAndStoreConsensusV1(options){let priorFingerprints=options.deps.priorFingerprints??await listConsensusProposalFingerprints(options.directory),result=await mineConsensus(options.directory,options.request,{...options.deps,priorFingerprints}),report=await writeConsensusReport(options.directory,result.report);return{...result,report}}init_store3();init_memory();init_recommendation_ledger();init_state2();init_logger();init_create_tool();var MAX_FILTER_ENTRIES=200,FilterListSchema=exports_external.array(exports_external.string().min(1).max(512)).max(MAX_FILTER_ENTRIES),MAX_INLINE_ATTRIBUTES=25;function countSummaries(attributes,inlineLimit){let total=0,shown=0;for(let[index,attribute]of attributes.entries()){if(attribute.llmSummary===void 0)continue;if(total+=1,index<inlineLimit)shown+=1}return{total,hidden:total-shown}}function buildMinerRecommendationCandidates(report,sessionId){return report.proposals.map((proposal)=>({kind:"miner",target:proposal.target,statement:proposal.intent,scopeKeys:[],provenance:{mechanism:"consensus_mine",sourceEvidenceRefs:proposal.evidenceRefs,sourceRunIds:proposal.provenance.sourceRunIds,sourceModelIds:proposal.provenance.sourceModelIds,sourceTaskIds:proposal.provenance.sourceTaskIds},origin:{agentRole:"consensus_mine",...sessionId?{sessionId}:{},producedAt:report.generatedAt}}))}var MIRRORED_PROPOSAL_KIND="todo";async function mirrorProposalsToMemory(options){if(options.memoryConfig?.enabled!==!0)return{enabled:!1,attempted:0,proposed:0,rejected:0,failed:0};let proposals=options.report.proposals;if(proposals.length===0)return{enabled:!0,attempted:0,proposed:0,rejected:0,failed:0};let gateway;try{gateway=_internals169.createMemoryGateway({directory:options.directory,...options.sessionId?{sessionID:options.sessionId,runId:options.sessionId}:{},agentRole:"consensus_mine"},{config:options.memoryConfig})}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[consensus_mine] memory mirror unavailable (fail-open): ${message}`),{enabled:!0,attempted:proposals.length,proposed:0,rejected:0,failed:proposals.length,error:message}}let proposed=0,rejected=0,failed=0,error93;try{for(let proposal of proposals)try{if((await gateway.propose({operation:"add",kind:MIRRORED_PROPOSAL_KIND,text:proposal.intent,rationale:`consensus_mine proposal from report ${options.report.reportId}, attribute ${proposal.sourceAttributeId} (target ${proposal.target}, confidence ${proposal.confidence})`,evidenceRefs:proposal.evidenceRefs})).status==="rejected")rejected+=1;else proposed+=1}catch(err){failed+=1,error93??=err instanceof Error?err.message:String(err)}}finally{try{await gateway.dispose()}catch(err){warn(`[consensus_mine] memory gateway dispose failed: ${err instanceof Error?err.message:String(err)}`)}}if(error93!==void 0)warn(`[consensus_mine] memory mirror partially failed: ${error93}`);return{enabled:!0,attempted:proposals.length,proposed,rejected,failed,...error93?{error:error93}:{}}}var _internals169={createMemoryGateway};var consensus_mine=createSwarmTool({description:"Mine cross-run consensus from existing .swarm evidence — evaluation runs, gate audits, gate "+"ground truth, task trajectories, PRM sessions, skill usage, knowledge outcomes, evidence "+"bundles, and curated failures (nine sources) — and persist an immutable report of "+`agreed-upon attributes plus proposals-only recommendations. It never activates a skill, writes a knowledge entry, admits a durable memory record, edits a project file, or mutates any evidence it reads. It is NOT otherwise write-minimal, so plan for these effects: it DELETES its own older reports past consensus.report_retention (default 50) on every run; it rewrites the shared recommendation dedup ledger whole, with FIFO eviction that can drop another producer's oldest entries; it leaves one never-removed lock sentinel per report id under .swarm/locks/; when memory.enabled is true it mirrors each proposal into a PENDING swarm-memory proposal (curator review still required); and when consensus.llm_summarization_enabled is true (the default) it issues up to ${MAX_LLM_SUMMARIES} session.create plus session.prompt calls. Under a knowledge or memory link the ledger and the memory store resolve to the shared cohort root, outside this project's .swarm/.`,args:{run_ids:FilterListSchema.optional().describe("Restrict mining to these run ids (raw or namespaced). Omit for all runs."),task_categories:FilterListSchema.optional().describe("Restrict to these evaluation task categories. Omit for all categories."),agent_roles:FilterListSchema.optional().describe("Restrict to these agent roles. Omit for all roles."),model_ids:FilterListSchema.optional().describe("Restrict to these model ids. Omit for all models."),min_support:exports_external.number().int().min(1).max(1e4).optional().describe("Distinct runs required to emit an attribute. Defaults to consensus.default_min_support."),min_successful_runs:exports_external.number().int().min(0).max(1e4).optional().describe("Successful runs required. Defaults to consensus.default_min_successful_runs."),max_evidence_items:exports_external.number().int().min(1).max(1e4).optional().describe("Cap on corpus observations read. Defaults to consensus.default_max_evidence_items.")},execute:async(args2,directory,ctx)=>{let input=args2??{},loaded=loadPluginConfigWithMeta(directory),config3=ConsensusConfigSchema.parse(loaded.config.consensus??{});if(!config3.enabled)return JSON.stringify({success:!1,disabled:!0,message:"Consensus mining is disabled (consensus.enabled = false). No report was written."},null,2);let request={...input.run_ids?{runIds:input.run_ids}:{},...input.task_categories?{taskCategories:input.task_categories}:{},...input.agent_roles?{agentRoles:input.agent_roles}:{},...input.model_ids?{modelIds:input.model_ids}:{},minSupport:input.min_support??config3.default_min_support,minSuccessfulRuns:input.min_successful_runs??config3.default_min_successful_runs,maxEvidenceItems:input.max_evidence_items??config3.default_max_evidence_items},client=swarmState.opencodeClient,dispatcher=config3.llm_summarization_enabled&&client?createEvaluationModelDispatcher(client):void 0,result=await mineAndStoreConsensusV1({directory,request,deps:{config:config3,...dispatcher?{dispatcher}:{},...ctx?.sessionID?{sessionId:ctx.sessionID}:{},agentRole:"consensus_mine"}}),report=result.report,ledger=await recordEmittedRecommendations(directory,buildMinerRecommendationCandidates(report,ctx?.sessionID),{producedAt:report.generatedAt});if(ledger.degraded)warn("[consensus_mine] recommendation ledger write degraded; proposals were not recorded for cross-producer dedup");let memoryMirror=await mirrorProposalsToMemory({directory,memoryConfig:loaded.config.memory,report,...ctx?.sessionID?{sessionId:ctx.sessionID}:{}}),pruned=await pruneConsensusReports(directory,config3.report_retention),pruningEnabled=config3.report_retention>0,summaries=countSummaries(report.attributes,MAX_INLINE_ATTRIBUTES);return JSON.stringify({success:!0,report_id:report.reportId,report_path:`.swarm/evolution/consensus/${report.reportId}.json`,generated_at:report.generatedAt,integrity_hash:report.integrityHash,config_hash:report.configHash,redaction_policy_version:report.redactionPolicyVersion,thresholds:{min_support:request.minSupport,min_successful_runs:request.minSuccessfulRuns,max_evidence_items:request.maxEvidenceItems,min_task_diversity:MIN_TASK_DIVERSITY_FOR_PROPOSAL,min_support_for_proposal:MIN_SUPPORT_FOR_PROPOSAL},input_run_count:report.inputIds.length,corpus:report.corpusHashes.map((entry)=>({source:entry.source,observations:entry.observations})),corpus_truncated:result.truncated,truncation:{corpus:report.truncation.corpus,observations_tallied:report.truncation.observations,input_ids_truncated:report.truncation.inputIds,total_input_ids:report.truncation.totalInputIds,attributes_dropped:report.truncation.attributesDropped},unreadable_sources:result.unreadableSources,attribute_count:report.attributes.length,investigation_note_count:result.investigationNoteCount,proposal_count:report.proposals.length,deduped_proposal_count:result.dedupedProposalCount,recommendation_ledger:{recorded:ledger.recorded,duplicate_recommendation_count:ledger.suppressed,evicted:ledger.evicted,degraded:ledger.degraded},memory_mirror:memoryMirror,summarized_count:summaries.total,summarized_but_not_shown:summaries.hidden,restatements_accepted_this_run:result.summarizedCount,...result.summarizationSkippedReason?{summarization_skipped_reason:result.summarizationSkippedReason}:{},attributes:report.attributes.slice(0,MAX_INLINE_ATTRIBUTES).map((attribute)=>({id:attribute.id,statement:attribute.statement,...attribute.llmSummary?{llm_summary:attribute.llmSummary}:{},support:attribute.support,success_support:attribute.successSupport,failure_support:attribute.failureSupport,task_diversity:attribute.taskDiversity,model_diversity:attribute.modelDiversity,confidence:attribute.confidence,proposed_target:attribute.proposedTarget,counterexample_count:attribute.counterexampleRefs.length})),attributes_truncated:report.attributes.length>MAX_INLINE_ATTRIBUTES,retention:pruningEnabled?{configured:config3.report_retention,pruning_enabled:!0,deleted:pruned.deleted.length,retained:pruned.retained.length,failed:pruned.failed.length,corrupt:pruned.corrupt.length}:{configured:config3.report_retention,pruning_enabled:!1,deleted:0,failed:0},guarantees:["proposals only — no skill activation, no knowledge write, no durable memory record, and no mutation of any evidence read",'model_diversity 0 means "not measurable from this corpus", never "measured as none"',`attributes below task diversity ${MIN_TASK_DIVERSITY_FOR_PROPOSAL} or below support ${MIN_SUPPORT_FOR_PROPOSAL} are investigation notes, never proposals`,"an attribute counting failing runs always carries counterexample refs (schema-enforced)","truncation is not biased toward successes, but it is still a cut: it balances per source, and drops whole sources once the budget is spent","statement is deterministic; llm_summary is an optional restatement excluded from integrity_hash","reproducible: identical corpus, request, config_hash, and prior proposals yield the same integrity_hash and report_id; model wording never moves it",'truncation is declared on the report; read failure_support 0 on a truncated report as "none survived the cut"']},null,2)}});init_config();init_model_limits();init_utils2();init_state2();init_create_tool();var _internals170={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={}){let{modelID,providerID}=extractModelInfo(messages),modelLimit=resolveModelLimit(modelID,providerID,modelLimitsConfig),totalTokens=0;for(let message of messages){if(!message?.parts)continue;for(let part of message.parts)if(part?.type==="text"&&part.text)totalTokens+=estimateTokens(part.text)}let usagePercent=totalTokens/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:totalTokens,modelLimit,usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({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.",args:{},async execute(_args,directory,ctx){let config3=_internals170.loadPluginConfig(directory),warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,modelLimitsConfig=config3.context_budget?.model_limits??{},messages=[];if(ctx?.sessionID){let sessionMessages=await _internals170.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig);return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;pushAdvisory(session,`${header}
|
|
6238
|
-
${body}`,{dedupeKey:dedupKey})}init_zod();init_task_file();import{existsSync as existsSync124,mkdirSync as mkdirSync64,readFileSync as readFileSync97}from"node:fs";import{join as join199}from"node:path";var EVIDENCE_DIR2=".swarm/evidence",VALID_TASK_ID=/^\d+\.\d+(\.\d+)*$/,COUNCIL_GATE_NAME="council",COUNCIL_AGENT_ID="architect",EvidenceFileSchema=exports_external.record(exports_external.string(),exports_external.unknown()),_internals171={withTaskEvidenceLock},FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);function safeAssignOwnProps(target,source){for(let key of Object.keys(source)){if(FORBIDDEN_KEYS.has(key))continue;let value=source[key];if(value!==null&&typeof value==="object"&&!Array.isArray(value)){let nested=Object.create(null);safeAssignOwnProps(nested,value),target[key]=nested}else if(Array.isArray(value))target[key]=value.map((item)=>{if(item!==null&&typeof item==="object"&&!Array.isArray(item)){let nested=Object.create(null);return safeAssignOwnProps(nested,item),nested}return item});else target[key]=value}return target}async function writeCouncilEvidence(workingDir,synthesis,attemptId){if(!VALID_TASK_ID.test(synthesis.taskId))throw Error(`writeCouncilEvidence: invalid taskId "${synthesis.taskId}" — must match N.M or N.M.P format`);let dir=join199(workingDir,EVIDENCE_DIR2);mkdirSync64(dir,{recursive:!0});let filePath=taskEvidencePath(workingDir,synthesis.taskId);await _internals171.withTaskEvidenceLock(workingDir,synthesis.taskId,COUNCIL_AGENT_ID,async()=>{let existingRoot=Object.create(null);if(existsSync124(filePath))try{let parsed=EvidenceFileSchema.parse(JSON.parse(readFileSync97(filePath,"utf-8")));safeAssignOwnProps(existingRoot,parsed)}catch{}let existingGatesRaw=existingRoot.gates,mergedGates=Object.create(null);if(existingGatesRaw&&typeof existingGatesRaw==="object"&&!Array.isArray(existingGatesRaw))safeAssignOwnProps(mergedGates,existingGatesRaw);mergedGates[COUNCIL_GATE_NAME]={sessionId:synthesis.swarmId,timestamp:synthesis.timestamp,agent:COUNCIL_AGENT_ID,verdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,quorumSize:synthesis.quorumSize,...attemptId?{attemptId}:{}};let updated=Object.create(null);if(safeAssignOwnProps(updated,existingRoot),updated.gates=mergedGates,!updated.taskId)updated.taskId=synthesis.taskId;if(!Array.isArray(updated.required_gates))updated.required_gates=[];await atomicWriteFile(filePath,JSON.stringify(updated,null,2))})}function hasCouncilEvidenceAttempt(workingDir,taskId,attemptId,roundNumber){if(!VALID_TASK_ID.test(taskId))return!1;try{let council=EvidenceFileSchema.parse(JSON.parse(readFileSync97(taskEvidencePath(workingDir,taskId),"utf-8"))).gates?.[COUNCIL_GATE_NAME];return council?.attemptId===attemptId&&council.roundNumber===roundNumber}catch{return!1}}init_lock();init_task_file();import{createHash as createHash43,randomUUID as randomUUID20}from"node:crypto";import{closeSync as closeSync18,existsSync as existsSync125,fsyncSync as fsyncSync7,mkdirSync as mkdirSync65,openSync as openSync18,readFileSync as readFileSync98,readSync as readSync10,statSync as statSync50,writeSync as writeSync2}from"node:fs";import{dirname as dirname92,join as join200}from"node:path";var VERSION=1,MAX_ROUND=10,MAX_AUDIT_TAIL=262144,STATE_AGENT="council-round-state";class CouncilRoundStateUncertainError extends Error{constructor(message){super(message);this.name="CouncilRoundStateUncertainError"}}function sha2562(value){return createHash43("sha256").update(value).digest("hex")}var UUID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,DIGEST_PATTERN=/^[a-f0-9]{64}$/;function isUuid(value){return typeof value==="string"&&UUID_PATTERN.test(value)}function isDigest(value){return typeof value==="string"&&DIGEST_PATTERN.test(value)}function isRound(value){return Number.isInteger(value)&&Number(value)>=1&&Number(value)<=MAX_ROUND}function isDisposition(value){return typeof value==="string"&&value.length>0&&value.length<=80}function isEvidenceRef(value){return typeof value==="string"&&value.length>0&&value.length<=240&&value.startsWith(".swarm/")&&!value.includes("..")}function scopeToken(scope){if(scope.kind==="task"){if(!/^\d+\.\d+(\.\d+)*$/.test(scope.taskId))throw Error("invalid task council scope");return`task-${sha2562(scope.taskId)}`}if(scope.kind==="phase"){if(!Number.isInteger(scope.phaseNumber)||scope.phaseNumber<1||scope.phaseNumber>1000)throw Error("invalid phase council scope");return`phase-${scope.phaseNumber}`}if(typeof scope.generation!=="string"||scope.generation.length===0||scope.generation.length>256)throw Error("invalid final council scope");return`final-${sha2562(scope.generation)}`}function auditScope(scope){if(scopeToken(scope),scope.kind==="task")return{kind:"task",scopeHash:sha2562(scope.taskId)};if(scope.kind==="phase")return{kind:"phase",phaseNumber:scope.phaseNumber};return{kind:"final",scopeHash:sha2562(scope.generation)}}function sameAuditScope(left,right){if(left.kind!==right.kind)return!1;if(left.kind==="phase"&&right.kind==="phase")return left.phaseNumber===right.phaseNumber;if(left.kind!=="phase"&&right.kind!=="phase")return left.scopeHash===right.scopeHash;return!1}function councilRoundStatePaths(directory,scope){let token=scopeToken(scope);return{state:join200(directory,".swarm","council","round-state",`${token}.json`),audit:join200(directory,".swarm","council","attempts",`${token}.jsonl`),lock:join200("council","round-state",`${token}.json`)}}function canonicalize2(value){if(Array.isArray(value))return value.map(canonicalize2);if(value&&typeof value==="object"){let result=Object.create(null);for(let key of Object.keys(value).sort()){if(key==="working_directory"||key==="roundNumber"||key==="provenanceAgentName"||key==="provenanceSessionId")continue;result[key]=canonicalize2(value[key])}return result}return value}function councilRequestDigest(request,round){return sha2562(JSON.stringify({round,request:canonicalize2(request)}))}function isSnapshot(value){if(!value||typeof value!=="object")return!1;let state=value;return state.version===VERSION&&isRound(state.currentRound)&&(state.status==="open"||state.status==="closed")&&typeof state.maxRoundsExhausted==="boolean"&&(state.lastAttemptId===void 0||isUuid(state.lastAttemptId))&&(state.lastDigest===void 0||isDigest(state.lastDigest))&&state.lastAttemptId===void 0===(state.lastDigest===void 0)}function isTransition(value){return value==="stay"||value==="advance"||value==="close"}function isGateEffect(value){return value==="none"||value==="blocked"||value==="allowed"}function isVerdict(value){return value==="APPROVE"||value==="CONCERNS"||value==="REJECT"}function auditTransitionIsConsistent(record3){if(!record3.nextState||!record3.transition)return!1;if(record3.transition==="close")return record3.nextState.status==="closed"&&record3.nextState.currentRound===record3.authoritativeRound;if(record3.transition==="stay"){if(record3.nextState.status==="closed"&&!["duplicate_submission","council_round_closed","council_round_mismatch"].includes(record3.disposition))return!1;return(record3.nextState.status==="open"||record3.nextState.status==="closed")&&record3.nextState.currentRound===record3.authoritativeRound}return record3.nextState.status==="open"&&(record3.nextState.currentRound===record3.authoritativeRound+1&&record3.nextState.maxRoundsExhausted===!1||record3.nextState.currentRound===record3.authoritativeRound&&record3.nextState.maxRoundsExhausted===!0)}function recoverAuditHistory(tail2){let current=tail2.truncated?void 0:initialState(),awaiting,sawTransition=!1;for(let record3 of tail2.records){if(record3.event==="received"){if(awaiting)throw new CouncilRoundStateUncertainError("council audit contains overlapping attempts");if(current&&record3.authoritativeRound!==current.currentRound||!current&&!tail2.truncated&&record3.authoritativeRound!==1)throw new CouncilRoundStateUncertainError("council audit round history is not monotonic");awaiting=record3;continue}if(!record3.nextState||!record3.transition)throw new CouncilRoundStateUncertainError("council audit transition is incomplete");if(awaiting){if(awaiting.attemptId!==record3.attemptId||awaiting.digest!==record3.digest||awaiting.authoritativeRound!==record3.authoritativeRound)throw new CouncilRoundStateUncertainError("council audit attempt pairing is inconsistent");awaiting=void 0}else if(!tail2.truncated||sawTransition)throw new CouncilRoundStateUncertainError("council audit transition has no matching received record");if(current){if(record3.authoritativeRound!==current.currentRound)throw new CouncilRoundStateUncertainError("council audit transition regresses the authoritative round");if(record3.transition==="stay"&&record3.nextState.status!==current.status)throw new CouncilRoundStateUncertainError("council audit stay transition changes scope status");if((record3.transition==="stay"||record3.transition==="close")&&record3.nextState.maxRoundsExhausted!==current.maxRoundsExhausted)throw new CouncilRoundStateUncertainError("council audit changes exhaustion without advancing");if(current.status==="closed"&&(record3.transition!=="stay"||record3.nextState.status!=="closed"))throw new CouncilRoundStateUncertainError("council audit reopens a closed scope")}current=record3.nextState,sawTransition=!0}if(awaiting)throw new CouncilRoundStateUncertainError("council audit ends with an unresolved received attempt");return current}function pendingMatchesParent(state,pending){if(state.status!=="open"||pending.round!==state.currentRound)return!1;if(pending.nextState.lastAttemptId!==pending.attemptId||pending.nextState.lastDigest!==pending.digest)return!1;if(pending.transition==="stay")return pending.nextState.status==="open"&&pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===state.maxRoundsExhausted;if(pending.transition==="close")return pending.nextState.status==="closed"&&pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===state.maxRoundsExhausted;return pending.nextState.status==="open"&&(pending.nextState.currentRound===state.currentRound+1&&pending.nextState.maxRoundsExhausted===!1||pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===!0)}function parseState(raw){let value;try{value=JSON.parse(raw)}catch{throw new CouncilRoundStateUncertainError("council round state is corrupt")}if(!isSnapshot(value))throw new CouncilRoundStateUncertainError("council round state is invalid");let state=value;if(state.pending){let pending=state.pending;if(!isUuid(pending.attemptId)||!isDigest(pending.digest)||!isRound(pending.round)||!isSnapshot(pending.nextState)||!isTransition(pending.transition)||!isDisposition(pending.disposition)||!isGateEffect(pending.gateEffect)||typeof pending.evidenceExpected!=="boolean"||pending.evidenceExpected!==(pending.evidenceRef!==void 0)||pending.evidenceRef!==void 0&&!isEvidenceRef(pending.evidenceRef)||pending.verdict!==void 0&&!isVerdict(pending.verdict)||pending.quorumSize!==void 0&&(!Number.isInteger(pending.quorumSize)||pending.quorumSize<0||pending.quorumSize>5)||pending.verdict===void 0!==(pending.quorumSize===void 0)||!pendingMatchesParent(state,pending))throw new CouncilRoundStateUncertainError("pending council state is invalid")}return state}function parseAuditRecord(line,expectedScope){try{let record3=JSON.parse(line);if(record3.version!==VERSION||!["received","finalized","recovered"].includes(record3.event)||!isUuid(record3.attemptId)||typeof record3.timestamp!=="string"||record3.timestamp.length>40||!Number.isFinite(Date.parse(record3.timestamp))||!sameAuditScope(record3.scope,expectedScope)||record3.clientRound!==void 0&&!isRound(record3.clientRound)||!isRound(record3.authoritativeRound)||!isDigest(record3.digest)||record3.sessionHash!==void 0&&!isDigest(record3.sessionHash)||!isDisposition(record3.disposition)||!Number.isInteger(record3.verdictCount)||record3.verdictCount<0||record3.verdictCount>5||!Array.isArray(record3.members)||record3.members.length>5||record3.members.some((member)=>typeof member!=="string"||member.length===0||member.length>32)||new Set(record3.members).size!==record3.members.length)throw Error("invalid");if(record3.event==="received"){if(record3.disposition!=="received"||record3.transition!==void 0||record3.gateEffect!==void 0||record3.nextState!==void 0||record3.evidenceRef!==void 0)throw Error("invalid")}else if(!isTransition(record3.transition)||!isGateEffect(record3.gateEffect)||!isSnapshot(record3.nextState)||record3.nextState.lastAttemptId!==record3.attemptId||record3.nextState.lastDigest!==record3.digest||!auditTransitionIsConsistent(record3))throw Error("invalid");if(record3.verdict!==void 0&&!isVerdict(record3.verdict))throw Error("invalid");if(record3.quorumSize!==void 0&&(!Number.isInteger(record3.quorumSize)||record3.quorumSize<0||record3.quorumSize>5))throw Error("invalid");if(record3.verdict===void 0!==(record3.quorumSize===void 0))throw Error("invalid");if(record3.evidenceRef!==void 0&&!isEvidenceRef(record3.evidenceRef))throw Error("invalid");return record3}catch{throw new CouncilRoundStateUncertainError("council attempt audit is corrupt")}}function appendAudit2(path248,record3){mkdirSync65(dirname92(path248),{recursive:!0});let descriptor=openSync18(path248,"a");try{writeSync2(descriptor,`${JSON.stringify(record3)}
|
|
6239
|
-
`,void 0,"utf8"),fsyncSync7(descriptor)}finally{closeSync18(descriptor)}}function readAuditTail(path248,scope){if(!existsSync125(path248))return{records:[],truncated:!1};let size=
|
|
6237
|
+
`);return truncated}function getCommandKind(command){let lower=command.toLowerCase();if(lower.includes("typecheck")||lower.includes("check")||lower.includes("analyze")||lower.includes("lint"))return"typecheck";if(lower.includes("test")||lower.includes("spec")||lower.includes("jest")||lower.includes("vitest")||lower.includes("mocha")||lower.includes("pytest"))return"test";return"build"}function filterByMode(commands,mode){if(mode==="both")return commands;return commands.filter((cmd)=>getCommandKind(cmd.command)===mode)}async function executeCommand(command){let startTime=Date.now(),kind=getCommandKind(command.command),isWindows=process.platform==="win32",cmd,args2;if(isWindows&&!command.command.includes(" "))cmd=[command.command],args2=[];else if(isWindows)cmd=["cmd","/c",command.command],args2=[];else cmd=["/bin/sh"],args2=["-c",command.command];let result=bunSpawn([...cmd,...args2],{cwd:command.cwd,stdout:"pipe",stderr:"pipe",timeout:DEFAULT_TIMEOUT_MS4}),[exitCode,stdout,stderr]=await Promise.all([result.exited,result.stdout.text(),result.stderr.text()]),duration_ms=Date.now()-startTime;return{kind,command:command.command,cwd:command.cwd,exit_code:exitCode??-1,duration_ms,stdout_tail:truncateOutput(stdout),stderr_tail:truncateOutput(stderr)}}async function runBuildCheck(workingDir,input){let scope=input.scope??"all",mode=input.mode??"both",changedFiles=input.changed_files??[],discoveryResult=await discoverBuildCommands(workingDir,{scope,changedFiles}),commands=filterByMode(discoveryResult.commands,mode),runs=[],failedCount=0;for(let cmd of commands)try{let run=await executeCommand(cmd);if(runs.push(run),run.exit_code!==0)failedCount++}catch(error93){runs.push({kind:getCommandKind(cmd.command),command:cmd.command,cwd:cmd.cwd,exit_code:-1,duration_ms:0,stdout_tail:"",stderr_tail:error93 instanceof Error?error93.message:"Unknown error"}),failedCount++}let verdict,skipped_reason;if(runs.length===0)if(verdict="info",discoveryResult.skipped.length>0)skipped_reason=discoveryResult.skipped.map((s)=>`${s.ecosystem}: ${s.reason}`).join("; ");else skipped_reason="No build commands discovered (no toolchains found)";else if(failedCount>0)verdict="fail";else verdict="pass";return{verdict,runs,summary:{files_scanned:changedFiles.length,runs_count:runs.length,failed_count:failedCount,skipped_reason}}}var build_check=createSwarmTool({description:"Discover and run build commands for various ecosystems in a project directory. Supports build, typecheck, and test commands.",args:{scope:exports_external.enum(["changed","all"]).describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changed_files:exports_external.array(exports_external.string()).optional().describe('List of changed files when scope is "changed"'),mode:exports_external.enum(["build","typecheck","both"]).optional().describe('Mode: "build" for build commands, "typecheck" for type checking, "both" for all (default: both)')},async execute(args2,directory){let obj=args2,scope=obj.scope??"all",changedFiles=obj.changed_files??[],mode=obj.mode??"both",workingDir=directory,result=await runBuildCheck(workingDir,{scope,changed_files:changedFiles,mode}),evidence2={task_id:"build",type:"build",timestamp:new Date().toISOString(),agent:"build_check",verdict:result.verdict,summary:`${result.runs.length} build command(s) executed, ${result.summary.failed_count} failed`,runs:result.runs,files_scanned:result.summary.files_scanned,runs_count:result.summary.runs_count,failed_count:result.summary.failed_count,skipped_reason:result.summary.skipped_reason};try{await saveEvidence(workingDir,"build",evidence2)}catch(error93){log("Failed to save build evidence:",error93 instanceof Error?error93.message:String(error93))}return JSON.stringify(result,null,2)}});init_zod();init_manager2();init_task_id();init_create_tool();init_resolve_working_directory();import*as fs133 from"node:fs";import*as path245 from"node:path";var EVIDENCE_DIR=".swarm/evidence";function isValidTaskId4(taskId){return isStrictTaskId2(taskId)}function isPathWithinSwarm(filePath,workspaceRoot){let normalizedWorkspace=path245.resolve(workspaceRoot),swarmPath3=path245.join(normalizedWorkspace,".swarm","evidence");return path245.resolve(filePath).startsWith(swarmPath3)}function readEvidenceFile(evidencePath){if(!fs133.existsSync(evidencePath))return null;let content;try{content=fs133.readFileSync(evidencePath,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(content)}catch{return null}if(parsed&&typeof parsed==="object"&&Array.isArray(parsed.required_gates)&&typeof parsed.gates==="object"&&parsed.gates!==null)return parsed;return null}var check_gate_status=createSwarmTool({description:"Read-only tool to check the gate status of a specific task. Reads .swarm/evidence/{taskId}.json and returns structured JSON describing required, passed, and missing gates.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "1.2.3", "1.2.3.4")').describe('The task ID to check gate status for (e.g., "1.1", "2.3.1")'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/evidence/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let taskIdInput,workingDirInput;try{if(args2&&typeof args2==="object"){let obj=args2;taskIdInput=typeof obj.task_id==="string"?obj.task_id:void 0,workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}}catch{}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={taskId:taskIdInput??"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:dirResult.message,todo_scan:null};return JSON.stringify(errorResult,null,2)}if(directory=dirResult.directory,!taskIdInput)return JSON.stringify({taskId:"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid task_id: task_id is required",todo_scan:null},null,2);if(!isValidTaskId4(taskIdInput)){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`Invalid task_id format: "${taskIdInput}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3", "1.2.3.4")`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let evidencePath=path245.join(directory,EVIDENCE_DIR,`${taskIdInput}.json`);if(!isPathWithinSwarm(evidencePath,directory))return JSON.stringify({taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid path: evidence path validation failed",todo_scan:null},null,2);let evidenceData=readEvidenceFile(evidencePath);if(!evidenceData){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`No evidence file found for task "${taskIdInput}" at ${evidencePath}. Evidence file may be missing or invalid.`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let requiredGates=evidenceData.required_gates||[],gatesMap=evidenceData.gates||{},passedGates=[],missingGates=[];for(let requiredGate of requiredGates)if(gatesMap[requiredGate])passedGates.push(requiredGate);else missingGates.push(requiredGate);let status=missingGates.length===0?"all_passed":"incomplete",message;if(status==="all_passed")message=`All required gates have passed for task "${taskIdInput}".`;else message=`Task "${taskIdInput}" is incomplete. Missing gates: ${missingGates.join(", ")}.`;let secretscanVerdict="not_run";try{let evidenceResult=await loadEvidence(directory,taskIdInput);if(evidenceResult.status==="found"){let secretscanEntries=evidenceResult.bundle.entries.filter((entry)=>entry.type==="secretscan");if(secretscanEntries.length>0){let lastSecretscan=secretscanEntries[secretscanEntries.length-1];if(isSecretscanEvidence(lastSecretscan)){let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=lastSecretscan,findingsCount=lastSecretscan.findings_count??0,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasFindings=findingsCount>0,hasZeroCoverage=lastSecretscan.files_scanned===0;if(hasIncompleteCoverage||hasFindings||hasZeroCoverage||lastSecretscan.verdict==="fail"||lastSecretscan.verdict==="rejected")if(secretscanVerdict="fail",hasIncompleteCoverage&&!hasFindings){if(missingGates.push("secretscan (BLOCKED — incomplete coverage)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan incomplete coverage in prior scan. ${message}`}else if(hasFindings&&hasIncompleteCoverage){if(missingGates.push("secretscan (BLOCKED — secrets detected; incomplete coverage)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan found secrets and incomplete coverage in prior scan. ${message}`}else if(hasFindings){if(missingGates.push("secretscan (BLOCKED — secrets detected)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan found secrets in prior scan. ${message}`}else{if(missingGates.push("secretscan (BLOCKED — zero coverage)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan scanned zero files in prior scan. ${message}`}else if(lastSecretscan.verdict==="pass"||lastSecretscan.verdict==="approved"||lastSecretscan.verdict==="info")secretscanVerdict="pass"}}else message+=" Advisory: No secretscan evidence found for this task. Consider running secretscan."}else if(evidenceResult.status==="invalid_schema")secretscanVerdict="fail",missingGates.push("secretscan (BLOCKED — invalid evidence)"),status="incomplete",message=`BLOCKED: Secretscan evidence is invalid and cannot prove complete coverage. ${message}`}catch{}let todoScan=evidenceData.todo_scan;return JSON.stringify({taskId:taskIdInput,status,required_gates:requiredGates,passed_gates:passedGates,missing_gates:missingGates,gates:gatesMap,message,todo_scan:todoScan??null,secretscan_verdict:secretscanVerdict},null,2)}});init_checkpoint();init_co_change_analyzer();init_zod();init_pr_workflow_gate();init_create_tool();var CompletePrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),pr_head_sha:exports_external.string().trim().min(1).max(80)}).strict();async function executeCompletePrWorkflow(args2,directory,context={}){let parsed=CompletePrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow completion: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow completion requires an active sessionID"});try{let status=await completePrWorkflow(directory,context.sessionID,parsed.data.mode,parsed.data.pr_head_sha);return JSON.stringify({success:!0,mode:parsed.data.mode,pr_head_sha:parsed.data.pr_head_sha,status,ready_to_publish:status==="ready-to-publish",gate_cleared:status==="completed"})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var complete_pr_workflow=createSwarmTool({description:"Validate terminal PR workflow coverage. After the ordered PR_FEEDBACK gates permit one standalone commit, the first call requires a clean tree and a non-merge direct child of intake HEAD, then binds its structured upstream target; the second clears only after both the local tracking ref and an actual-remote query point to that exact commit.",args:{mode:CompletePrWorkflowArgsSchema.shape.mode,pr_head_sha:CompletePrWorkflowArgsSchema.shape.pr_head_sha},execute:executeCompletePrWorkflow});init_zod();init_utils2();init_state2();init_create_tool();init_resolve_working_directory();import*as fs134 from"node:fs";import*as path246 from"node:path";function extractMatches(regex,text){return Array.from(text.matchAll(regex))}function parseIdentifiers(description){let identifiers=new Set,backtickRegex=/`([^`]+)`/g;for(let match of extractMatches(backtickRegex,description))identifiers.add(match[1]);let camelCaseRegex=/\b([a-z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(camelCaseRegex,description)){let word=match[1];if(word==="the"||word==="and"||word==="for"||word==="have"||word==="this"||word==="with"||word==="from"||word==="they"||word==="been"||word==="will"||word==="your"||word==="also")continue;identifiers.add(word)}let pascalCaseRegex=/\b([A-Z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(pascalCaseRegex,description))identifiers.add(match[1]);let configKeyRegex=/\b([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+)\b/g;for(let match of extractMatches(configKeyRegex,description))identifiers.add(match[1]);let quotedPathRegex=/['"](\.{0,3}(?:src|lib|test)[/\\][^'"]+)['"]/g;for(let match of extractMatches(quotedPathRegex,description))identifiers.add(match[1]);return Array.from(identifiers)}function parseFilePaths(description,filesTouched){if(filesTouched&&Array.isArray(filesTouched)&&filesTouched.length>0)return filesTouched;let filePaths=[],srcPathRegex=/\b(?:src|lib|test|app|packages?)[/\\][a-zA-Z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)\b/g;for(let match of extractMatches(srcPathRegex,description))filePaths.push(match[0]);let genericPathRegex=/\b[a-zA-Z0-9_./-]+[/\\][a-zA-Z0-9_./-]+\.[a-zA-Z0-9]+(?=\s|$|[.,;])/g;for(let match of extractMatches(genericPathRegex,description)){let pathStr=match[0];if(pathStr.includes("src/")||pathStr.includes("src\\")||pathStr.includes("lib/")||pathStr.includes("lib\\")||pathStr.includes("test/")||pathStr.includes("test\\"))filePaths.push(pathStr)}return filePaths}function buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked){if(tasksBlocked>0)return`Blocked: ${tasksBlocked} task(s) with missing identifiers`;let verified=tasksChecked-tasksSkipped;if(tasksSkipped===tasksChecked)return`All ${tasksChecked} completed task(s) skipped — research/inventory tasks`;if(tasksSkipped>0)return`${verified} task(s) verified, ${tasksSkipped} skipped (research tasks)`;return`All ${tasksChecked} completed tasks verified successfully`}async function executeCompletionVerify(args2,directory){let phase=Number(args2.phase);if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase))return JSON.stringify({success:!1,phase,status:"blocked",reason:"Invalid phase number",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);if(hasActiveTurboMode(args2.sessionID))return JSON.stringify({success:!0,phase,status:"passed",reason:"Turbo Mode active — completion verification bypassed",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);let plan;try{let planPath=validateSwarmPath(directory,"plan.json"),planRaw=fs134.readFileSync(planPath,"utf-8");plan=JSON.parse(planRaw)}catch{return JSON.stringify({success:!0,phase,status:"passed",reason:"Cannot verify without plan.json",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let targetPhase=plan.phases.find((p)=>p.id===phase);if(!targetPhase){let result2={success:!1,phase,status:"blocked",reason:`Phase ${phase} not found in plan.json`,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]};return JSON.stringify(result2,null,2)}let tasksChecked=0,tasksSkipped=0,tasksBlocked=0,blockedTasks=[];for(let task2 of targetPhase.tasks){if(task2.status!=="completed")continue;tasksChecked++;let fileTargets=parseFilePaths(task2.description,task2.files_touched),identifiers=parseIdentifiers(task2.description);if(fileTargets.length===0){tasksSkipped++;continue}if(identifiers.length===0){blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers — cannot verify completion without identifiers"}),tasksBlocked++;continue}let foundIdentifiers=new Set,hasFileReadFailure=!1;for(let filePath of fileTargets){let normalizedPath2=filePath.replace(/\\/g,"/"),resolvedPath=path246.resolve(directory,normalizedPath2),projectRoot=path246.resolve(directory),relative58=path246.relative(projectRoot,resolvedPath);if(!(relative58===""||!relative58.startsWith("..")&&!path246.isAbsolute(relative58))){blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File path '${filePath}' escapes the project directory — cannot verify completion`}),hasFileReadFailure=!0;continue}let fileContent;try{fileContent=fs134.readFileSync(resolvedPath,"utf-8")}catch{blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File '${filePath}' not found — cannot verify completion`}),hasFileReadFailure=!0;continue}for(let identifier of identifiers)if(fileContent.includes(identifier))foundIdentifiers.add(identifier)}let foundCount=foundIdentifiers.size;if(hasFileReadFailure||foundCount===0){if(!hasFileReadFailure)blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers found in target files"});tasksBlocked++}}let now=new Date().toISOString(),result={success:tasksBlocked===0,phase,status:tasksBlocked===0?"passed":"blocked",reason:tasksBlocked>0?`COMPLETION_INCOMPLETE: ${tasksBlocked} task(s) blocked — missing identifiers or target files`:void 0,tasksChecked,tasksSkipped,tasksBlocked,blockedTasks};try{let evidenceDir=path246.join(directory,".swarm","evidence",`${phase}`),evidencePath=path246.join(evidenceDir,"completion-verify.json");fs134.mkdirSync(evidenceDir,{recursive:!0});let evidenceBundle={schema_version:"1.0.0",task_id:"completion-verify",created_at:now,entries:[{task_id:"completion-verify",type:"completion_verify",timestamp:now,agent:"completion_verify",verdict:tasksBlocked===0?"pass":"fail",summary:buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked),phase,tasks_checked:tasksChecked,tasks_skipped:tasksSkipped,tasks_blocked:tasksBlocked,blocked_tasks:blockedTasks}]};fs134.writeFileSync(evidencePath,JSON.stringify(evidenceBundle,null,2),"utf-8")}catch{}return JSON.stringify(result,null,2)}var completion_verify=createSwarmTool({description:"Deterministic pre-check verifying that plan task identifiers exist in their target source files before phase completion. Blocks if obviously incomplete.",args:{phase:exports_external.number().describe("The phase number to check"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},execute:async(args2,directory)=>{let parsedArgs;try{if(args2&&typeof args2==="object"){let obj=args2;parsedArgs={phase:typeof obj.phase==="number"?obj.phase:typeof obj.phase==="string"?Number(obj.phase):0,sessionID:typeof obj.sessionID==="string"?obj.sessionID:void 0,working_directory:typeof obj.working_directory==="string"?obj.working_directory:void 0}}else parsedArgs={phase:0}}catch{return JSON.stringify({success:!1,phase:0,status:"blocked",reason:"Invalid arguments",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let dirResult=resolveWorkingDirectory(parsedArgs.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:parsedArgs.phase,status:"blocked",reason:dirResult.message,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);return executeCompletionVerify(parsedArgs,dirResult.directory)}});init_zod();init_metrics();init_bun_compat();init_create_tool();init_path_security();import*as fs135 from"node:fs";import*as path247 from"node:path";var MAX_FILE_SIZE_BYTES5=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}async function getGitChurn(days,directory){let churnMap=new Map,proc=bunSpawn(["git","log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",cwd:directory}),[stdout]=await Promise.all([proc.stdout.text(),proc.exited]),lines=stdout.split(/\r?\n/);for(let line of lines){let normalizedPath2=line.replace(/\\/g,"/");if(!normalizedPath2||normalizedPath2.trim()==="")continue;if(normalizedPath2.includes("node_modules")||normalizedPath2.includes("/.git/")||normalizedPath2.includes("/dist/")||normalizedPath2.includes("/build/")||normalizedPath2.includes("__tests__"))continue;if(normalizedPath2.includes(".test.")||normalizedPath2.includes(".spec."))continue;churnMap.set(normalizedPath2,(churnMap.get(normalizedPath2)||0)+1)}return churnMap}function getComplexityForFile2(filePath){try{if(fs135.statSync(filePath).size>MAX_FILE_SIZE_BYTES5)return null;let content=fs135.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory){let churnMap=await getGitChurn(days,directory),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count]of churnMap){let ext=path247.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs135.existsSync(fullPath))fullPath=path247.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_schema();init_miner();init_miner();init_store3();async function mineAndStoreConsensusV1(options){let priorFingerprints=options.deps.priorFingerprints??await listConsensusProposalFingerprints(options.directory),result=await mineConsensus(options.directory,options.request,{...options.deps,priorFingerprints}),report=await writeConsensusReport(options.directory,result.report);return{...result,report}}init_store3();init_memory();init_recommendation_ledger();init_state2();init_logger();init_create_tool();var MAX_FILTER_ENTRIES=200,FilterListSchema=exports_external.array(exports_external.string().min(1).max(512)).max(MAX_FILTER_ENTRIES),MAX_INLINE_ATTRIBUTES=25;function countSummaries(attributes,inlineLimit){let total=0,shown=0;for(let[index,attribute]of attributes.entries()){if(attribute.llmSummary===void 0)continue;if(total+=1,index<inlineLimit)shown+=1}return{total,hidden:total-shown}}function buildMinerRecommendationCandidates(report,sessionId){return report.proposals.map((proposal)=>({kind:"miner",target:proposal.target,statement:proposal.intent,scopeKeys:[],provenance:{mechanism:"consensus_mine",sourceEvidenceRefs:proposal.evidenceRefs,sourceRunIds:proposal.provenance.sourceRunIds,sourceModelIds:proposal.provenance.sourceModelIds,sourceTaskIds:proposal.provenance.sourceTaskIds},origin:{agentRole:"consensus_mine",...sessionId?{sessionId}:{},producedAt:report.generatedAt}}))}var MIRRORED_PROPOSAL_KIND="todo";async function mirrorProposalsToMemory(options){if(options.memoryConfig?.enabled!==!0)return{enabled:!1,attempted:0,proposed:0,rejected:0,failed:0};let proposals=options.report.proposals;if(proposals.length===0)return{enabled:!0,attempted:0,proposed:0,rejected:0,failed:0};let gateway;try{gateway=_internals169.createMemoryGateway({directory:options.directory,...options.sessionId?{sessionID:options.sessionId,runId:options.sessionId}:{},agentRole:"consensus_mine"},{config:options.memoryConfig})}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[consensus_mine] memory mirror unavailable (fail-open): ${message}`),{enabled:!0,attempted:proposals.length,proposed:0,rejected:0,failed:proposals.length,error:message}}let proposed=0,rejected=0,failed=0,error93;try{for(let proposal of proposals)try{if((await gateway.propose({operation:"add",kind:MIRRORED_PROPOSAL_KIND,text:proposal.intent,rationale:`consensus_mine proposal from report ${options.report.reportId}, attribute ${proposal.sourceAttributeId} (target ${proposal.target}, confidence ${proposal.confidence})`,evidenceRefs:proposal.evidenceRefs})).status==="rejected")rejected+=1;else proposed+=1}catch(err){failed+=1,error93??=err instanceof Error?err.message:String(err)}}finally{try{await gateway.dispose()}catch(err){warn(`[consensus_mine] memory gateway dispose failed: ${err instanceof Error?err.message:String(err)}`)}}if(error93!==void 0)warn(`[consensus_mine] memory mirror partially failed: ${error93}`);return{enabled:!0,attempted:proposals.length,proposed,rejected,failed,...error93?{error:error93}:{}}}var _internals169={createMemoryGateway};var consensus_mine=createSwarmTool({description:"Mine cross-run consensus from existing .swarm evidence — evaluation runs, gate audits, gate "+"ground truth, task trajectories, PRM sessions, skill usage, knowledge outcomes, evidence "+"bundles, and curated failures (nine sources) — and persist an immutable report of "+`agreed-upon attributes plus proposals-only recommendations. It never activates a skill, writes a knowledge entry, admits a durable memory record, edits a project file, or mutates any evidence it reads. It is NOT otherwise write-minimal, so plan for these effects: it DELETES its own older reports past consensus.report_retention (default 50) on every run; it rewrites the shared recommendation dedup ledger whole, with FIFO eviction that can drop another producer's oldest entries; it leaves one never-removed lock sentinel per report id under .swarm/locks/; when memory.enabled is true it mirrors each proposal into a PENDING swarm-memory proposal (curator review still required); and when consensus.llm_summarization_enabled is true (the default) it issues up to ${MAX_LLM_SUMMARIES} session.create plus session.prompt calls. Under a knowledge or memory link the ledger and the memory store resolve to the shared cohort root, outside this project's .swarm/.`,args:{run_ids:FilterListSchema.optional().describe("Restrict mining to these run ids (raw or namespaced). Omit for all runs."),task_categories:FilterListSchema.optional().describe("Restrict to these evaluation task categories. Omit for all categories."),agent_roles:FilterListSchema.optional().describe("Restrict to these agent roles. Omit for all roles."),model_ids:FilterListSchema.optional().describe("Restrict to these model ids. Omit for all models."),min_support:exports_external.number().int().min(1).max(1e4).optional().describe("Distinct runs required to emit an attribute. Defaults to consensus.default_min_support."),min_successful_runs:exports_external.number().int().min(0).max(1e4).optional().describe("Successful runs required. Defaults to consensus.default_min_successful_runs."),max_evidence_items:exports_external.number().int().min(1).max(1e4).optional().describe("Cap on corpus observations read. Defaults to consensus.default_max_evidence_items.")},execute:async(args2,directory,ctx)=>{let input=args2??{},loaded=loadPluginConfigWithMeta(directory),config3=ConsensusConfigSchema.parse(loaded.config.consensus??{});if(!config3.enabled)return JSON.stringify({success:!1,disabled:!0,message:"Consensus mining is disabled (consensus.enabled = false). No report was written."},null,2);let request={...input.run_ids?{runIds:input.run_ids}:{},...input.task_categories?{taskCategories:input.task_categories}:{},...input.agent_roles?{agentRoles:input.agent_roles}:{},...input.model_ids?{modelIds:input.model_ids}:{},minSupport:input.min_support??config3.default_min_support,minSuccessfulRuns:input.min_successful_runs??config3.default_min_successful_runs,maxEvidenceItems:input.max_evidence_items??config3.default_max_evidence_items},client=swarmState.opencodeClient,dispatcher=config3.llm_summarization_enabled&&client?createEvaluationModelDispatcher(client):void 0,result=await mineAndStoreConsensusV1({directory,request,deps:{config:config3,...dispatcher?{dispatcher}:{},...ctx?.sessionID?{sessionId:ctx.sessionID}:{},agentRole:"consensus_mine"}}),report=result.report,ledger=await recordEmittedRecommendations(directory,buildMinerRecommendationCandidates(report,ctx?.sessionID),{producedAt:report.generatedAt});if(ledger.degraded)warn("[consensus_mine] recommendation ledger write degraded; proposals were not recorded for cross-producer dedup");let memoryMirror=await mirrorProposalsToMemory({directory,memoryConfig:loaded.config.memory,report,...ctx?.sessionID?{sessionId:ctx.sessionID}:{}}),pruned=await pruneConsensusReports(directory,config3.report_retention),pruningEnabled=config3.report_retention>0,summaries=countSummaries(report.attributes,MAX_INLINE_ATTRIBUTES);return JSON.stringify({success:!0,report_id:report.reportId,report_path:`.swarm/evolution/consensus/${report.reportId}.json`,generated_at:report.generatedAt,integrity_hash:report.integrityHash,config_hash:report.configHash,redaction_policy_version:report.redactionPolicyVersion,thresholds:{min_support:request.minSupport,min_successful_runs:request.minSuccessfulRuns,max_evidence_items:request.maxEvidenceItems,min_task_diversity:MIN_TASK_DIVERSITY_FOR_PROPOSAL,min_support_for_proposal:MIN_SUPPORT_FOR_PROPOSAL},input_run_count:report.inputIds.length,corpus:report.corpusHashes.map((entry)=>({source:entry.source,observations:entry.observations})),corpus_truncated:result.truncated,truncation:{corpus:report.truncation.corpus,observations_tallied:report.truncation.observations,input_ids_truncated:report.truncation.inputIds,total_input_ids:report.truncation.totalInputIds,attributes_dropped:report.truncation.attributesDropped},unreadable_sources:result.unreadableSources,attribute_count:report.attributes.length,investigation_note_count:result.investigationNoteCount,proposal_count:report.proposals.length,deduped_proposal_count:result.dedupedProposalCount,recommendation_ledger:{recorded:ledger.recorded,duplicate_recommendation_count:ledger.suppressed,evicted:ledger.evicted,degraded:ledger.degraded},memory_mirror:memoryMirror,summarized_count:summaries.total,summarized_but_not_shown:summaries.hidden,restatements_accepted_this_run:result.summarizedCount,...result.summarizationSkippedReason?{summarization_skipped_reason:result.summarizationSkippedReason}:{},attributes:report.attributes.slice(0,MAX_INLINE_ATTRIBUTES).map((attribute)=>({id:attribute.id,statement:attribute.statement,...attribute.llmSummary?{llm_summary:attribute.llmSummary}:{},support:attribute.support,success_support:attribute.successSupport,failure_support:attribute.failureSupport,task_diversity:attribute.taskDiversity,model_diversity:attribute.modelDiversity,confidence:attribute.confidence,proposed_target:attribute.proposedTarget,counterexample_count:attribute.counterexampleRefs.length})),attributes_truncated:report.attributes.length>MAX_INLINE_ATTRIBUTES,retention:pruningEnabled?{configured:config3.report_retention,pruning_enabled:!0,deleted:pruned.deleted.length,retained:pruned.retained.length,failed:pruned.failed.length,corrupt:pruned.corrupt.length}:{configured:config3.report_retention,pruning_enabled:!1,deleted:0,failed:0},guarantees:["proposals only — no skill activation, no knowledge write, no durable memory record, and no mutation of any evidence read",'model_diversity 0 means "not measurable from this corpus", never "measured as none"',`attributes below task diversity ${MIN_TASK_DIVERSITY_FOR_PROPOSAL} or below support ${MIN_SUPPORT_FOR_PROPOSAL} are investigation notes, never proposals`,"an attribute counting failing runs always carries counterexample refs (schema-enforced)","truncation is not biased toward successes, but it is still a cut: it balances per source, and drops whole sources once the budget is spent","statement is deterministic; llm_summary is an optional restatement excluded from integrity_hash","reproducible: identical corpus, request, config_hash, and prior proposals yield the same integrity_hash and report_id; model wording never moves it",'truncation is declared on the report; read failure_support 0 on a truncated report as "none survived the cut"']},null,2)}});init_config();init_model_limits();init_utils2();init_state2();init_create_tool();var _internals170={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={}){let{modelID,providerID}=extractModelInfo(messages),modelLimit=resolveModelLimit(modelID,providerID,modelLimitsConfig),totalTokens=0;for(let message of messages){if(!message?.parts)continue;for(let part of message.parts)if(part?.type==="text"&&part.text)totalTokens+=estimateTokens(part.text)}let usagePercent=totalTokens/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:totalTokens,modelLimit,usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({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.",args:{},async execute(_args,directory,ctx){let config3=_internals170.loadPluginConfig(directory),warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,modelLimitsConfig=config3.context_budget?.model_limits??{},messages=[];if(ctx?.sessionID){let sessionMessages=await _internals170.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig);return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;pushAdvisory(session,`${header}
|
|
6238
|
+
${body}`,{dedupeKey:dedupKey})}init_zod();init_task_file();import{existsSync as existsSync124,mkdirSync as mkdirSync64,readFileSync as readFileSync97}from"node:fs";import{join as join199}from"node:path";var EVIDENCE_DIR2=".swarm/evidence",VALID_TASK_ID=/^\d+\.\d+(\.\d+)*$/,COUNCIL_GATE_NAME="council",COUNCIL_AGENT_ID="architect",EvidenceFileSchema=exports_external.record(exports_external.string(),exports_external.unknown()),_internals171={withTaskEvidenceLock},FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);function safeAssignOwnProps(target,source){for(let key of Object.keys(source)){if(FORBIDDEN_KEYS.has(key))continue;let value=source[key];if(value!==null&&typeof value==="object"&&!Array.isArray(value)){let nested=Object.create(null);safeAssignOwnProps(nested,value),target[key]=nested}else if(Array.isArray(value))target[key]=value.map((item)=>{if(item!==null&&typeof item==="object"&&!Array.isArray(item)){let nested=Object.create(null);return safeAssignOwnProps(nested,item),nested}return item});else target[key]=value}return target}async function writeCouncilEvidence(workingDir,synthesis,attemptId){if(!VALID_TASK_ID.test(synthesis.taskId))throw Error(`writeCouncilEvidence: invalid taskId "${synthesis.taskId}" — must match N.M or N.M.P format`);let dir=join199(workingDir,EVIDENCE_DIR2);mkdirSync64(dir,{recursive:!0});let filePath=taskEvidencePath(workingDir,synthesis.taskId);await _internals171.withTaskEvidenceLock(workingDir,synthesis.taskId,COUNCIL_AGENT_ID,async()=>{let existingRoot=Object.create(null);if(existsSync124(filePath))try{let parsed=EvidenceFileSchema.parse(JSON.parse(readFileSync97(filePath,"utf-8")));safeAssignOwnProps(existingRoot,parsed)}catch{}let existingGatesRaw=existingRoot.gates,mergedGates=Object.create(null);if(existingGatesRaw&&typeof existingGatesRaw==="object"&&!Array.isArray(existingGatesRaw))safeAssignOwnProps(mergedGates,existingGatesRaw);mergedGates[COUNCIL_GATE_NAME]={sessionId:synthesis.swarmId,timestamp:synthesis.timestamp,agent:COUNCIL_AGENT_ID,verdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,quorumSize:synthesis.quorumSize,...attemptId?{attemptId}:{}};let updated=Object.create(null);if(safeAssignOwnProps(updated,existingRoot),updated.gates=mergedGates,!updated.taskId)updated.taskId=synthesis.taskId;if(!Array.isArray(updated.required_gates))updated.required_gates=[];await atomicWriteFile(filePath,JSON.stringify(updated,null,2))})}function hasCouncilEvidenceAttempt(workingDir,taskId,attemptId,roundNumber){if(!VALID_TASK_ID.test(taskId))return!1;try{let council=EvidenceFileSchema.parse(JSON.parse(readFileSync97(taskEvidencePath(workingDir,taskId),"utf-8"))).gates?.[COUNCIL_GATE_NAME];return council?.attemptId===attemptId&&council.roundNumber===roundNumber}catch{return!1}}init_lock();init_task_file();import{createHash as createHash43,randomUUID as randomUUID20}from"node:crypto";import{closeSync as closeSync18,existsSync as existsSync125,fsyncSync as fsyncSync7,mkdirSync as mkdirSync65,openSync as openSync18,readFileSync as readFileSync98,readSync as readSync11,statSync as statSync49,writeSync as writeSync2}from"node:fs";import{dirname as dirname92,join as join200}from"node:path";var VERSION=1,MAX_ROUND=10,MAX_AUDIT_TAIL=262144,STATE_AGENT="council-round-state";class CouncilRoundStateUncertainError extends Error{constructor(message){super(message);this.name="CouncilRoundStateUncertainError"}}function sha2562(value){return createHash43("sha256").update(value).digest("hex")}var UUID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,DIGEST_PATTERN=/^[a-f0-9]{64}$/;function isUuid(value){return typeof value==="string"&&UUID_PATTERN.test(value)}function isDigest(value){return typeof value==="string"&&DIGEST_PATTERN.test(value)}function isRound(value){return Number.isInteger(value)&&Number(value)>=1&&Number(value)<=MAX_ROUND}function isDisposition(value){return typeof value==="string"&&value.length>0&&value.length<=80}function isEvidenceRef(value){return typeof value==="string"&&value.length>0&&value.length<=240&&value.startsWith(".swarm/")&&!value.includes("..")}function scopeToken(scope){if(scope.kind==="task"){if(!/^\d+\.\d+(\.\d+)*$/.test(scope.taskId))throw Error("invalid task council scope");return`task-${sha2562(scope.taskId)}`}if(scope.kind==="phase"){if(!Number.isInteger(scope.phaseNumber)||scope.phaseNumber<1||scope.phaseNumber>1000)throw Error("invalid phase council scope");return`phase-${scope.phaseNumber}`}if(typeof scope.generation!=="string"||scope.generation.length===0||scope.generation.length>256)throw Error("invalid final council scope");return`final-${sha2562(scope.generation)}`}function auditScope(scope){if(scopeToken(scope),scope.kind==="task")return{kind:"task",scopeHash:sha2562(scope.taskId)};if(scope.kind==="phase")return{kind:"phase",phaseNumber:scope.phaseNumber};return{kind:"final",scopeHash:sha2562(scope.generation)}}function sameAuditScope(left,right){if(left.kind!==right.kind)return!1;if(left.kind==="phase"&&right.kind==="phase")return left.phaseNumber===right.phaseNumber;if(left.kind!=="phase"&&right.kind!=="phase")return left.scopeHash===right.scopeHash;return!1}function councilRoundStatePaths(directory,scope){let token=scopeToken(scope);return{state:join200(directory,".swarm","council","round-state",`${token}.json`),audit:join200(directory,".swarm","council","attempts",`${token}.jsonl`),lock:join200("council","round-state",`${token}.json`)}}function canonicalize2(value){if(Array.isArray(value))return value.map(canonicalize2);if(value&&typeof value==="object"){let result=Object.create(null);for(let key of Object.keys(value).sort()){if(key==="working_directory"||key==="roundNumber"||key==="provenanceAgentName"||key==="provenanceSessionId")continue;result[key]=canonicalize2(value[key])}return result}return value}function councilRequestDigest(request,round){return sha2562(JSON.stringify({round,request:canonicalize2(request)}))}function isSnapshot(value){if(!value||typeof value!=="object")return!1;let state=value;return state.version===VERSION&&isRound(state.currentRound)&&(state.status==="open"||state.status==="closed")&&typeof state.maxRoundsExhausted==="boolean"&&(state.lastAttemptId===void 0||isUuid(state.lastAttemptId))&&(state.lastDigest===void 0||isDigest(state.lastDigest))&&state.lastAttemptId===void 0===(state.lastDigest===void 0)}function isTransition(value){return value==="stay"||value==="advance"||value==="close"}function isGateEffect(value){return value==="none"||value==="blocked"||value==="allowed"}function isVerdict(value){return value==="APPROVE"||value==="CONCERNS"||value==="REJECT"}function auditTransitionIsConsistent(record3){if(!record3.nextState||!record3.transition)return!1;if(record3.transition==="close")return record3.nextState.status==="closed"&&record3.nextState.currentRound===record3.authoritativeRound;if(record3.transition==="stay"){if(record3.nextState.status==="closed"&&!["duplicate_submission","council_round_closed","council_round_mismatch"].includes(record3.disposition))return!1;return(record3.nextState.status==="open"||record3.nextState.status==="closed")&&record3.nextState.currentRound===record3.authoritativeRound}return record3.nextState.status==="open"&&(record3.nextState.currentRound===record3.authoritativeRound+1&&record3.nextState.maxRoundsExhausted===!1||record3.nextState.currentRound===record3.authoritativeRound&&record3.nextState.maxRoundsExhausted===!0)}function recoverAuditHistory(tail2){let current=tail2.truncated?void 0:initialState(),awaiting,sawTransition=!1;for(let record3 of tail2.records){if(record3.event==="received"){if(awaiting)throw new CouncilRoundStateUncertainError("council audit contains overlapping attempts");if(current&&record3.authoritativeRound!==current.currentRound||!current&&!tail2.truncated&&record3.authoritativeRound!==1)throw new CouncilRoundStateUncertainError("council audit round history is not monotonic");awaiting=record3;continue}if(!record3.nextState||!record3.transition)throw new CouncilRoundStateUncertainError("council audit transition is incomplete");if(awaiting){if(awaiting.attemptId!==record3.attemptId||awaiting.digest!==record3.digest||awaiting.authoritativeRound!==record3.authoritativeRound)throw new CouncilRoundStateUncertainError("council audit attempt pairing is inconsistent");awaiting=void 0}else if(!tail2.truncated||sawTransition)throw new CouncilRoundStateUncertainError("council audit transition has no matching received record");if(current){if(record3.authoritativeRound!==current.currentRound)throw new CouncilRoundStateUncertainError("council audit transition regresses the authoritative round");if(record3.transition==="stay"&&record3.nextState.status!==current.status)throw new CouncilRoundStateUncertainError("council audit stay transition changes scope status");if((record3.transition==="stay"||record3.transition==="close")&&record3.nextState.maxRoundsExhausted!==current.maxRoundsExhausted)throw new CouncilRoundStateUncertainError("council audit changes exhaustion without advancing");if(current.status==="closed"&&(record3.transition!=="stay"||record3.nextState.status!=="closed"))throw new CouncilRoundStateUncertainError("council audit reopens a closed scope")}current=record3.nextState,sawTransition=!0}if(awaiting)throw new CouncilRoundStateUncertainError("council audit ends with an unresolved received attempt");return current}function pendingMatchesParent(state,pending){if(state.status!=="open"||pending.round!==state.currentRound)return!1;if(pending.nextState.lastAttemptId!==pending.attemptId||pending.nextState.lastDigest!==pending.digest)return!1;if(pending.transition==="stay")return pending.nextState.status==="open"&&pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===state.maxRoundsExhausted;if(pending.transition==="close")return pending.nextState.status==="closed"&&pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===state.maxRoundsExhausted;return pending.nextState.status==="open"&&(pending.nextState.currentRound===state.currentRound+1&&pending.nextState.maxRoundsExhausted===!1||pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===!0)}function parseState(raw){let value;try{value=JSON.parse(raw)}catch{throw new CouncilRoundStateUncertainError("council round state is corrupt")}if(!isSnapshot(value))throw new CouncilRoundStateUncertainError("council round state is invalid");let state=value;if(state.pending){let pending=state.pending;if(!isUuid(pending.attemptId)||!isDigest(pending.digest)||!isRound(pending.round)||!isSnapshot(pending.nextState)||!isTransition(pending.transition)||!isDisposition(pending.disposition)||!isGateEffect(pending.gateEffect)||typeof pending.evidenceExpected!=="boolean"||pending.evidenceExpected!==(pending.evidenceRef!==void 0)||pending.evidenceRef!==void 0&&!isEvidenceRef(pending.evidenceRef)||pending.verdict!==void 0&&!isVerdict(pending.verdict)||pending.quorumSize!==void 0&&(!Number.isInteger(pending.quorumSize)||pending.quorumSize<0||pending.quorumSize>5)||pending.verdict===void 0!==(pending.quorumSize===void 0)||!pendingMatchesParent(state,pending))throw new CouncilRoundStateUncertainError("pending council state is invalid")}return state}function parseAuditRecord(line,expectedScope){try{let record3=JSON.parse(line);if(record3.version!==VERSION||!["received","finalized","recovered"].includes(record3.event)||!isUuid(record3.attemptId)||typeof record3.timestamp!=="string"||record3.timestamp.length>40||!Number.isFinite(Date.parse(record3.timestamp))||!sameAuditScope(record3.scope,expectedScope)||record3.clientRound!==void 0&&!isRound(record3.clientRound)||!isRound(record3.authoritativeRound)||!isDigest(record3.digest)||record3.sessionHash!==void 0&&!isDigest(record3.sessionHash)||!isDisposition(record3.disposition)||!Number.isInteger(record3.verdictCount)||record3.verdictCount<0||record3.verdictCount>5||!Array.isArray(record3.members)||record3.members.length>5||record3.members.some((member)=>typeof member!=="string"||member.length===0||member.length>32)||new Set(record3.members).size!==record3.members.length)throw Error("invalid");if(record3.event==="received"){if(record3.disposition!=="received"||record3.transition!==void 0||record3.gateEffect!==void 0||record3.nextState!==void 0||record3.evidenceRef!==void 0)throw Error("invalid")}else if(!isTransition(record3.transition)||!isGateEffect(record3.gateEffect)||!isSnapshot(record3.nextState)||record3.nextState.lastAttemptId!==record3.attemptId||record3.nextState.lastDigest!==record3.digest||!auditTransitionIsConsistent(record3))throw Error("invalid");if(record3.verdict!==void 0&&!isVerdict(record3.verdict))throw Error("invalid");if(record3.quorumSize!==void 0&&(!Number.isInteger(record3.quorumSize)||record3.quorumSize<0||record3.quorumSize>5))throw Error("invalid");if(record3.verdict===void 0!==(record3.quorumSize===void 0))throw Error("invalid");if(record3.evidenceRef!==void 0&&!isEvidenceRef(record3.evidenceRef))throw Error("invalid");return record3}catch{throw new CouncilRoundStateUncertainError("council attempt audit is corrupt")}}function appendAudit2(path248,record3){mkdirSync65(dirname92(path248),{recursive:!0});let descriptor=openSync18(path248,"a");try{writeSync2(descriptor,`${JSON.stringify(record3)}
|
|
6239
|
+
`,void 0,"utf8"),fsyncSync7(descriptor)}finally{closeSync18(descriptor)}}function readAuditTail(path248,scope){if(!existsSync125(path248))return{records:[],truncated:!1};let size=statSync49(path248).size;if(size===0)return{records:[],truncated:!1};let offset=Math.max(0,size-MAX_AUDIT_TAIL),length=size-offset,descriptor=openSync18(path248,"r"),buffer=Buffer.alloc(length);try{readSync11(descriptor,buffer,0,length,offset)}finally{closeSync18(descriptor)}let text=buffer.toString("utf8");if(!text.endsWith(`
|
|
6240
6240
|
`))throw new CouncilRoundStateUncertainError("council attempt audit has a partial tail");if(offset>0){let firstNewline=text.indexOf(`
|
|
6241
6241
|
`);if(firstNewline<0)throw new CouncilRoundStateUncertainError("council attempt audit tail is oversized");text=text.slice(firstNewline+1)}let expectedScope=auditScope(scope);return{records:text.split(`
|
|
6242
6242
|
`).filter(Boolean).map((line)=>parseAuditRecord(line,expectedScope)),truncated:offset>0}}function initialState(){return{version:VERSION,currentRound:1,status:"open",maxRoundsExhausted:!1}}function snapshot(state){return{version:VERSION,currentRound:state.currentRound,status:state.status,maxRoundsExhausted:state.maxRoundsExhausted,lastAttemptId:state.lastAttemptId,lastDigest:state.lastDigest}}function sameSnapshot(left,right){return left.version===right.version&&left.currentRound===right.currentRound&&left.status===right.status&&left.maxRoundsExhausted===right.maxRoundsExhausted&&left.lastAttemptId===right.lastAttemptId&&left.lastDigest===right.lastDigest}function pendingTerminalMatches(state,record3){let pending=state.pending;if(!pending||record3.attemptId!==pending.attemptId||record3.digest!==pending.digest||record3.authoritativeRound!==pending.round||!record3.nextState)return!1;if(record3.event==="finalized")return record3.disposition===pending.disposition&&record3.transition===pending.transition&&record3.gateEffect===pending.gateEffect&&record3.verdict===pending.verdict&&record3.quorumSize===pending.quorumSize&&record3.evidenceRef===pending.evidenceRef&&sameSnapshot(record3.nextState,pending.nextState);if(record3.event!=="recovered")return!1;if(record3.disposition==="pending_evidence_recovered")return record3.transition===pending.transition&&record3.gateEffect===pending.gateEffect&&record3.verdict===pending.verdict&&record3.quorumSize===pending.quorumSize&&record3.evidenceRef===pending.evidenceRef&&sameSnapshot(record3.nextState,pending.nextState);if(record3.disposition!=="orphan_recovered")return!1;return record3.transition==="stay"&&record3.gateEffect==="none"&&record3.verdict===pending.verdict&&record3.quorumSize===pending.quorumSize&&record3.evidenceRef===pending.evidenceRef&&sameSnapshot(record3.nextState,{...snapshot(state),lastAttemptId:pending.attemptId,lastDigest:pending.digest})}function transitionState(state,attemptId,digest3,transition,maxRounds){let configuredLimit=Math.max(1,Math.min(MAX_ROUND,maxRounds)),limit=Math.max(state.currentRound,configuredLimit),currentRound=state.currentRound,status="open",maxRoundsExhausted=state.maxRoundsExhausted;if(transition==="advance")if(currentRound<limit)currentRound++,maxRoundsExhausted=!1;else maxRoundsExhausted=!0;else if(transition==="close")status="closed";return{version:VERSION,currentRound,status,maxRoundsExhausted,lastAttemptId:attemptId,lastDigest:digest3}}async function writeState3(path248,state){mkdirSync65(dirname92(path248),{recursive:!0}),await _internals172.atomicWrite(path248,JSON.stringify(state,null,2))}function baseRecord(input,attemptId,digest3,round,disposition){return{version:VERSION,attemptId,timestamp:_internals172.now(),scope:auditScope(input.scope),clientRound:input.clientRound,authoritativeRound:round,digest:digest3,sessionHash:input.sessionID?sha2562(input.sessionID):void 0,disposition:disposition.slice(0,80),verdictCount:Math.max(0,Math.min(5,input.verdictCount)),members:input.members.slice(0,5).map((member)=>member.slice(0,32))}}function latestRecord(records,attemptId){for(let index=records.length-1;index>=0;index--)if(records[index]?.attemptId===attemptId)return records[index];return}async function loadState(paths,scope){if(existsSync125(paths.state))return parseState(readFileSync98(paths.state,"utf8"));let tail2=_internals172.readAuditTail(paths.audit,scope),records=tail2.records,recovered=recoverAuditHistory(tail2);if(tail2.truncated&&!recovered)throw new CouncilRoundStateUncertainError("council state is missing and the bounded audit tail has no recoverable transition");if(!recovered&&records.length>0)throw new CouncilRoundStateUncertainError("council state is missing and the audit has no complete transition");let state=recovered??initialState();return await writeState3(paths.state,state),state}function persistenceFailure(round,error93){return JSON.stringify({success:!1,reason:"council_round_state_persistence_failed",authoritativeRound:round,message:error93 instanceof Error?error93.message:String(error93)},null,2)}function uncertainFailure(error93){return JSON.stringify({success:!1,reason:"council_round_state_uncertain",message:error93 instanceof Error?error93.message:String(error93)},null,2)}async function runCouncilAttempt(input){let paths=councilRoundStatePaths(input.directory,input.scope),authoritativeRound=1;try{return await _internals172.withLock(input.directory,paths.lock,STATE_AGENT,scopeToken(input.scope),async()=>{let state=await loadState(paths,input.scope);if(state.pending){let tail2=_internals172.readAuditTail(paths.audit,input.scope),latest=latestRecord(tail2.records,state.pending.attemptId);if(tail2.truncated&&!latest)throw new CouncilRoundStateUncertainError("pending council attempt is outside the bounded audit tail");if(!latest)throw new CouncilRoundStateUncertainError("pending council attempt has no matching audit record");if((latest.event==="finalized"||latest.event==="recovered")&&latest.nextState){if(!pendingTerminalMatches(state,latest))throw new CouncilRoundStateUncertainError("terminal council audit contradicts pending state");state=latest.nextState}else{let committed=state.pending.evidenceExpected&&input.probePendingEvidence?await input.probePendingEvidence(state.pending.attemptId,state.pending.round,state.pending.evidenceRef):!1,recovered=committed?state.pending.nextState:{...snapshot(state),lastAttemptId:state.pending.attemptId,lastDigest:state.pending.digest};_internals172.appendAudit(paths.audit,{...baseRecord(input,state.pending.attemptId,state.pending.digest,state.pending.round,committed?"pending_evidence_recovered":"orphan_recovered"),event:"recovered",transition:committed?state.pending.transition:"stay",gateEffect:committed?state.pending.gateEffect:"none",verdict:state.pending.verdict,quorumSize:state.pending.quorumSize,evidenceRef:state.pending.evidenceRef,nextState:recovered}),state=recovered}await writeState3(paths.state,state)}authoritativeRound=state.currentRound;let digest3=councilRequestDigest(input.request,authoritativeRound),attemptId=_internals172.uuid(),received=baseRecord(input,attemptId,digest3,authoritativeRound,"received");if(_internals172.appendAudit(paths.audit,{...received,event:"received"}),input.clientRound!==void 0&&input.clientRound!==authoritativeRound){let next2={...snapshot(state),lastAttemptId:attemptId,lastDigest:digest3};return _internals172.appendAudit(paths.audit,{...received,event:"finalized",disposition:"council_round_mismatch",transition:"stay",gateEffect:"none",nextState:next2}),await writeState3(paths.state,next2),JSON.stringify({success:!1,reason:"council_round_mismatch",authoritativeRound,submittedRound:input.clientRound},null,2)}if(state.status==="closed"){let disposition=state.lastDigest===digest3?"duplicate_submission":"council_round_closed",next2={...snapshot(state),lastAttemptId:attemptId,lastDigest:digest3};return _internals172.appendAudit(paths.audit,{...received,event:"finalized",disposition,transition:"stay",gateEffect:"none",nextState:next2}),await writeState3(paths.state,next2),JSON.stringify({success:!1,reason:disposition,authoritativeRound},null,2)}let evaluation;try{evaluation=await input.evaluate(authoritativeRound)}catch(error93){evaluation={disposition:"council_evaluation_failed",response:{success:!1,reason:"council_evaluation_failed",message:error93 instanceof Error?error93.message:String(error93)},transition:"stay",gateEffect:"none"}}let next=transitionState(state,attemptId,digest3,evaluation.transition,input.maxRounds),pending={attemptId,digest:digest3,round:authoritativeRound,transition:evaluation.transition,nextState:next,disposition:evaluation.disposition.slice(0,80),gateEffect:evaluation.gateEffect,evidenceExpected:Boolean(evaluation.evidence),evidenceRef:evaluation.evidence?.reference.slice(0,240),verdict:evaluation.verdict,quorumSize:evaluation.quorumSize};try{await writeState3(paths.state,{...snapshot(state),pending})}catch(error93){let failed={...snapshot(state),lastAttemptId:attemptId,lastDigest:digest3};_internals172.appendAudit(paths.audit,{...received,event:"finalized",disposition:"council_pending_state_write_failed",transition:"stay",gateEffect:"none",nextState:failed});try{await writeState3(paths.state,failed)}catch{}throw error93}await evaluation.evidence?.commit(attemptId),_internals172.appendAudit(paths.audit,{...received,event:"finalized",disposition:evaluation.disposition.slice(0,80),transition:evaluation.transition,gateEffect:evaluation.gateEffect,verdict:evaluation.verdict,quorumSize:evaluation.quorumSize,evidenceRef:evaluation.evidence?.reference.slice(0,240),nextState:next}),await writeState3(paths.state,next);try{await evaluation.afterCommit?.()}catch{}return JSON.stringify({...evaluation.response,authoritativeRound,nextRound:next.currentRound,maxRoundsExhausted:next.maxRoundsExhausted},null,2)})}catch(error93){if(await recordUnscopedCouncilAttempt(input.directory,input.scope.kind,error93 instanceof CouncilRoundStateUncertainError?"council_round_state_uncertain":"council_round_state_persistence_failed",input.request,[],input.sessionID),error93 instanceof CouncilRoundStateUncertainError)return uncertainFailure(error93);return persistenceFailure(authoritativeRound,error93)}}async function recordUnscopedCouncilAttempt(directory,level,disposition,raw,issues,sessionID){let path248=join200(directory,".swarm","council","attempts","unscoped.jsonl"),known=raw&&typeof raw==="object"?raw:{},fingerprint=sha2562(JSON.stringify({level,taskIdType:typeof known.taskId,phaseType:typeof known.phase,phaseNumberType:typeof known.phaseNumber,roundNumberType:typeof known.roundNumber,verdictCount:Array.isArray(known.verdicts)?Math.min(6,known.verdicts.length):-1,issues:issues.slice(0,20).map((issue3)=>({path:issue3.path.slice(0,8).map(String),code:issue3.code.slice(0,40)}))}));try{return await _internals172.withLock(directory,join200("council","attempts","unscoped.jsonl"),STATE_AGENT,"unscoped",async()=>{mkdirSync65(dirname92(path248),{recursive:!0});let descriptor=openSync18(path248,"a");try{writeSync2(descriptor,`${JSON.stringify({version:VERSION,event:"unscoped",attemptId:_internals172.uuid(),timestamp:_internals172.now(),level,disposition:disposition.slice(0,80),fingerprint,sessionHash:sessionID?sha2562(sessionID):void 0})}
|
|
@@ -6366,10 +6366,10 @@ Advisory notes: ${advisoryNotes.join("; ")}`:"";return{blocked:!0,reason:"PHASE_
|
|
|
6366
6366
|
${jsdocContent}`;else if(line.includes("*/"))break;else if(functionKeywords.test(line)||line.startsWith("function ")){_foundFunction=!0;break}else if(line.length>0&&!line.startsWith("//")&&!line.startsWith("*"))break}if(jsdocContent){if(/@returns\s*(?:\{[^}]*\})?\s*(?:undefined|[A-Za-z_]\w*)/i.test(jsdocContent))return!0}let braceCount=0,inFunction=!1;for(let i=currentLineIdx;i>=0;i--){let line=lines[i];for(let char of line)if(char==="{")braceCount++,inFunction=!0;else if(char==="}")braceCount--;if(inFunction&&braceCount===0&&i<currentLineIdx)break}let errorReturnPattern=/return\s+["'`][[:ascii:]]*["'`]\s*;/;for(let i=currentLineIdx-1;i>=0&&i>=currentLineIdx-MAX_SEARCH_LINES;i--){let line=lines[i].trim();if(functionKeywords.test(line)||line.startsWith("function "))break;if(errorReturnPattern.test(line))return!0}return!1}function scanWithRegex(content,filePath,denyPatterns,addedLines){let findings=[],lines=content.split(`
|
|
6367
6367
|
`),filterByAddedLines=addedLines!==void 0;for(let i=0;i<lines.length;i++){let line=lines[i],lineNumber=i+1;if(filterByAddedLines&&!addedLines.has(lineNumber))continue;let lineCommentMatch=line.match(/(?:\/\/|#|<!--)\s*(.*)$/);if(lineCommentMatch){let commentText=lineCommentMatch[1];for(let{pattern,rule_id}of denyPatterns.comment)if(pattern.test(commentText)){findings.push({path:filePath,line:lineNumber,kind:"comment",excerpt:line.substring(0,100),rule_id});break}}let blockCommentMatch=line.match(/\/\*([\s\S]*?)\*\//);if(blockCommentMatch){let commentText=blockCommentMatch[1];for(let{pattern,rule_id}of denyPatterns.comment)if(pattern.test(commentText)){findings.push({path:filePath,line:lineNumber,kind:"comment",excerpt:line.substring(0,100),rule_id});break}}let stringMatches=line.match(/(["'`])(?:(?!\1)[^\\]|\\.)*\1/g);if(stringMatches){for(let stringContent of stringMatches)for(let{pattern,rule_id}of denyPatterns.string)if(pattern.test(stringContent)){findings.push({path:filePath,line:lineNumber,kind:"string",excerpt:line.substring(0,100),rule_id});break}}for(let{pattern,rule_id}of denyPatterns.code)if(!(line.includes("describe(")||line.includes("it(")||line.includes("test(")||line.includes("expect("))&&pattern.test(line)){if(rule_id==="placeholder/code-stub-return"&&/return\s+undefined\s*;/.test(line)){if(isValidationPattern(lines,i))continue}findings.push({path:filePath,line:lineNumber,kind:"function_body",excerpt:line.substring(0,100),rule_id})}}return findings}async function scanWithParser(content,filePath,denyPatterns,addedLines){let findings=[],regexFindings=scanWithRegex(content,filePath,denyPatterns,addedLines);findings.push(...regexFindings);let parser=await getParserForFile(filePath);if(!parser)return findings;try{let walkNode=function(node){let{type:nodeType,text:nodeText}=node,lineNum=node.startPosition.row+1;if(filterByAddedLines?addedLines.has(lineNum):!0){if(nodeType==="comment"||nodeType==="line_comment"||nodeType==="block_comment"||nodeType==="documentation_comment"||nodeType==="doc_comment")for(let{pattern,rule_id}of denyPatterns.comment){let key=`${lineNum}:${rule_id}`;if(!seenKeys.has(key)&&pattern.test(nodeText))seenKeys.add(key),findings.push({path:filePath,line:lineNum,kind:"comment",excerpt:nodeText.substring(0,100),rule_id})}if(nodeType==="string"||nodeType==="template_string"||nodeType==="string_literal"||nodeType==="string_fragment")for(let{pattern,rule_id}of denyPatterns.string){let key=`${lineNum}:${rule_id}`;if(!seenKeys.has(key)&&pattern.test(nodeText))seenKeys.add(key),findings.push({path:filePath,line:lineNum,kind:"string",excerpt:nodeText.substring(0,100),rule_id})}}if(node.children)for(let child of node.children)walkNode(child)},tree=parser.parse(content);if(!tree||!tree.rootNode)return findings;let seenKeys=new Set;for(let f of findings)seenKeys.add(`${f.line}:${f.rule_id}`);let filterByAddedLines=addedLines!==void 0;walkNode(tree.rootNode),tree.delete()}catch{}return findings}async function placeholderScan(input,directory){let{changed_files,allow_globs,deny_patterns,added_lines,sentinel_allowlist,allow_sentinels}=input,sentinelPatterns=[...DEFAULT_SENTINEL_ALLOWLIST,...sentinel_allowlist??allow_sentinels??[]].map((sentinel)=>new RegExp(escapeRegex2(sentinel),"i"));function isSentinelAllowed(excerpt){for(let pattern of sentinelPatterns)if(pattern.test(excerpt))return!0;return!1}let commentPatterns=DEFAULT_COMMENT_PATTERNS,stringPatterns=DEFAULT_STRING_PATTERNS,codePatterns=DEFAULT_CODE_PATTERNS;if(deny_patterns&&deny_patterns.length>0)commentPatterns=deny_patterns.map((p)=>({pattern:new RegExp(`\\b${escapeRegex2(p)}\\b`,"i"),rule_id:`placeholder/custom-${p.toLowerCase()}`})),stringPatterns=[],codePatterns=[];let denyPatterns={comment:commentPatterns,string:stringPatterns,code:codePatterns},findings=[],filesScanned=0,filesWithFindings=new Set;for(let filePath of changed_files){let fullPath=path275.isAbsolute(filePath)?filePath:path275.resolve(directory,filePath),resolvedDirectory=path275.resolve(directory);if(!fullPath.startsWith(resolvedDirectory+path275.sep)&&fullPath!==resolvedDirectory)continue;if(!fs161.existsSync(fullPath))continue;if(isAllowedByGlobs(filePath,allow_globs))continue;let relativeFilePath=path275.relative(directory,fullPath).replace(/\\/g,"/");if(FILE_ALLOWLIST.some((allowed)=>relativeFilePath.endsWith(allowed)))continue;let content;try{if(fs161.statSync(fullPath).size>MAX_FILE_SIZE)continue;content=fs161.readFileSync(fullPath,"utf-8")}catch{continue}if(content.includes("\x00"))continue;let isScaffold=isScaffoldFile(filePath);if(isTestFile2(filePath)&&!isScaffold)continue;filesScanned++;let addedLinesForFile=normalizeAddedLines(added_lines?.[relativeFilePath]??added_lines?.[filePath]),fileFindings;if(isPlanFile(filePath))fileFindings=scanPlanFileForPlaceholders(content,filePath,addedLinesForFile);else if(isParserSupported(filePath))fileFindings=await scanWithParser(content,filePath,denyPatterns,addedLinesForFile);else fileFindings=scanWithRegex(content,filePath,denyPatterns,addedLinesForFile);let filteredFindings=sentinelPatterns.length>0?fileFindings.filter((f)=>!isSentinelAllowed(f.excerpt)):fileFindings;if(filteredFindings.length>0)findings.push(...filteredFindings),filesWithFindings.add(filePath)}let verdict=findings.length>0?"fail":"pass";return await saveEvidence(directory,"placeholder_scan",{task_id:"placeholder_scan",type:"placeholder",timestamp:new Date().toISOString(),agent:"placeholder_scan",verdict,summary:`Scanned ${filesScanned} files, found ${findings.length} placeholder(s)`,files_scanned:filesScanned,findings_count:findings.length,files_with_findings:filesWithFindings.size,findings}),{verdict,findings,summary:{files_scanned:filesScanned,findings_count:findings.length,files_with_findings:filesWithFindings.size}}}var placeholder_scan=createSwarmTool({description:"Scan source files for placeholder content (TODO/FIXME comments, stub implementations, unimplemented functions). Returns JSON with findings grouped by file and rule.",args:{changed_files:exports_external.array(exports_external.string()).describe("Files to scan for placeholders"),allow_globs:exports_external.array(exports_external.string()).optional().describe("Globs to allow (skip scanning)"),deny_patterns:exports_external.array(exports_external.string()).optional().describe("Custom deny patterns to search for"),added_lines:exports_external.record(exports_external.string(),exports_external.array(exports_external.number().int().positive())).optional().describe("Optional map of file path to PR-added line numbers"),sentinel_allowlist:exports_external.array(exports_external.string()).optional().describe("Intentional sentinel strings that suppress matching findings"),allow_sentinels:exports_external.array(exports_external.string()).optional().describe("Deprecated alias for sentinel_allowlist")},async execute(args2,directory){let result=await placeholderScan(args2,directory);return JSON.stringify(result)}});init_zod();init_manager();init_parallel_verdict();init_cochange_source();init_create_tool();var plan_conflict_check_args={task_ids:exports_external.array(exports_external.string().min(1)).min(2,"plan_conflict_check requires at least 2 task ids to compare").max(MAX_PARALLEL_VERDICT_TASKS,`plan_conflict_check accepts at most ${MAX_PARALLEL_VERDICT_TASKS} task ids`).describe('The N proposed parallel task group ids (e.g. ["4.1","4.2","4.3"]). '+"Minimum 2 — fewer than 2 tasks cannot conflict."),use_cochange:exports_external.boolean().optional().describe("When true, fold git co-change signal (from `git log`) into the verdict. "+'Off by default — the path-only verdict is sufficient for the v8 "provably '+'disjoint" gate. Opt in for richer signal on tightly-coupled codebases.'),phase_id:exports_external.string().optional().describe("Optional: scope the check to a phase. Currently informational — task_ids "+"are checked as-is regardless of phase. Reserved for future validation.")};async function executePlanConflictCheck(args2,directory){let useCochange=args2.use_cochange===!0,planLoaded=!1,knownTaskIds=new Set;try{let plan=await loadPlanJsonOnly(directory);if(plan){planLoaded=!0;for(let phase of plan.phases)for(let task2 of phase.tasks)knownTaskIds.add(task2.id)}}catch{planLoaded=!1}let requestedIds=args2.task_ids,unknownToPlan=planLoaded?requestedIds.filter((id)=>!knownTaskIds.has(id)):[],cochangePairs;if(useCochange)try{cochangePairs=await getCoChangePairs(directory)}catch{cochangePairs=void 0}let verdict=computeParallelVerdict(directory,requestedIds,{useCochange,cochangePairs});return{verdict:verdict.verdict,pairs:verdict.pairs,suggested_serial_order:verdict.suggestedSerialOrder,unknown_scope_tasks:verdict.unknownScopeTasks,used_cochange:useCochange&&cochangePairs!==void 0&&cochangePairs.length>0,plan_loaded:planLoaded,...unknownToPlan.length>0?{unknown_to_plan:unknownToPlan}:{}}}var plan_conflict_check=createSwarmTool({description:"Read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes (`.swarm/scopes/scope-<taskId>.json`) and optional git co-change signal. Returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization "+"order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via "+"the same helper. Use this BEFORE attempting parallel dispatch to confirm disjointness.",args:plan_conflict_check_args,execute:async(args2,directory)=>{let result=await executePlanConflictCheck(args2,directory);return JSON.stringify(result,null,2)}});init_workspace_snapshot();init_pr_workflow_state();init_pr_workflow_gate();init_utils2();init_bun_compat();init_create_tool();import*as fsp7 from"node:fs/promises";import*as path276 from"node:path";var GIT_TIMEOUT_MS9=5000,GIT_MAX_STDOUT_BYTES=524288,MAX_DIRTY_FILES=50,MAX_REMOTES=20,MAX_REMOTE_URL_LEN=200,MAX_FIELD_LEN=240,RECEIPT_DIR="pr-workflow-checkouts",utf8Encoder=new TextEncoder,utf8Decoder=new TextDecoder("utf-8",{fatal:!1});function truncateToByteBudget(value,maxBytes){let encoded=utf8Encoder.encode(value);if(encoded.length<=maxBytes)return value;return utf8Decoder.decode(encoded.subarray(0,maxBytes))}function boundUntrusted(value,maxLen){let cleaned=value.replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim();return cleaned.length>maxLen?`${cleaned.slice(0,maxLen)}…`:cleaned}async function runGitCapture2(directory,args2){let proc=bunSpawn(["git",...args2],{cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:GIT_TIMEOUT_MS9});try{let[exitCode,stdout]=await Promise.all([proc.exited,proc.stdout.text()]);if(exitCode!==0)return null;return truncateToByteBudget(stdout,GIT_MAX_STDOUT_BYTES)}catch{return null}finally{try{proc.kill()}catch{}}}async function resolveBranch(directory){let raw=await _internals195.runGitCapture(directory,["rev-parse","--abbrev-ref","HEAD"]);if(raw===null)return{branch:null,detached:null};let value=raw.trim();if(!value||value==="HEAD")return{branch:null,detached:!0};return{branch:boundUntrusted(value,MAX_FIELD_LEN),detached:!1}}function parseDirtyFiles(porcelain){if(!porcelain)return{dirtyFiles:[],dirtyFileCount:0,dirtyFilesTruncated:!1};let lines=porcelain.split(`
|
|
6368
6368
|
`).filter((line)=>line.length>=4),dirtyFiles=[];for(let line of lines){if(dirtyFiles.length>=MAX_DIRTY_FILES)break;let status=line.slice(0,2).trim()||"??",rawPath=line.slice(3);dirtyFiles.push({status:boundUntrusted(status,4),path:boundUntrusted(rawPath,MAX_FIELD_LEN)})}return{dirtyFiles,dirtyFileCount:lines.length,dirtyFilesTruncated:lines.length>dirtyFiles.length}}function parseRemotes(remoteOutput){if(!remoteOutput)return{remotes:[],remotesTruncated:!1};let byName=new Map;for(let line of remoteOutput.split(`
|
|
6369
|
-
`)){let trimmed=line.trim();if(!trimmed)continue;let[name,rest]=trimmed.split(/\s+/,2);if(!name||!rest||byName.has(name))continue;let url3=rest.replace(/\s+\((?:fetch|push)\)\s*$/i,"");byName.set(boundUntrusted(name,64),boundUntrusted(url3,MAX_REMOTE_URL_LEN))}let entries=[...byName.entries()],remotes=entries.slice(0,MAX_REMOTES).map(([name,url3])=>({name,url:url3}));return{remotes,remotesTruncated:entries.length>remotes.length}}async function countCheckoutReceiptFiles(directory,sessionID){try{let receiptDirectory=validateSwarmPath(directory,path276.join(RECEIPT_DIR,prWorkflowSessionFileStem(sessionID)));return(await fsp7.readdir(receiptDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&/^[0-9a-f]{40,64}\.json$/i.test(entry.name)).length}catch(error93){if(error93.code==="ENOENT")return 0;return null}}function describeNextStep(gate,git2,checkout){if(checkout.kind==="recovery-required"||checkout.kind==="indeterminate")return`Manual Git recovery required. code=${checkout.code} retryable=false required_action=${checkout.requiredAction}`;if(!gate.active)return"No active PR workflow gate for this session. Activate with `/swarm pr-review <pr-ref>` or `/swarm pr-feedback <pr-ref>` before PR-workflow tool calls are admitted.";if(!gate.prHeadBound)return gate.mode==="PR_FEEDBACK"?"PR_FEEDBACK gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes). Prefer the intended exact tracking checkout, then bind; if this workflow inherited an already-detached exact intake head, bind it directly and the controller will attach the unique exact local/remote tracking ref. Ambiguity or an existing mismatched upstream fails closed.":"PR_REVIEW gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes), then bind the exact detached PR head.";if(git2.isClean===!1)return`${gate.mode} gate active and head bound, but the working tree is dirty. Read-only observation only; the gate keeps writes and non-tracking fetches fail-closed.`;if(git2.isClean===null)return`${gate.mode} gate active and head bound, but this session could not determine whether the working tree is clean (git status failed). Treat the tree state as unknown and verify manually before assuming it is clean; read-only observation only.`;return`${gate.mode} gate active and head bound. Continue read-only review using the admitted observe/validate tools (diff, gh_evidence, repo_map, lint check, etc.).`}function summarizeGate(state,receiptFiles){if(!state)return{active:!1,reason:"no-active-gate"};return{active:!0,mode:state.mode,prHeadBound:Boolean(state.prHeadSha),prHeadSha:state.prHeadSha??null,prFeedbackTargetUrl:state.prFeedbackTargetUrl?boundUntrusted(state.prFeedbackTargetUrl,MAX_FIELD_LEN):null,prReviewBaseRef:state.prReviewBaseRef?boundUntrusted(state.prReviewBaseRef,MAX_FIELD_LEN):null,prReviewBaseSha:state.prReviewBaseSha??null,prReviewDepthTier:state.prReviewDepthTier??null,baseDispatchBatches:state.prReviewBaseDispatches?.length??0,validationBatches:state.prReviewValidationBatches?.length??0,feedbackVerificationBatches:state.prFeedbackVerifications?.length??0,checkoutReceiptFiles:receiptFiles,activatedAt:state.activatedAt,updatedAt:state.updatedAt,revision:state.revision}}async function executePrWorkflowStatus(directory,rawSessionID){let sessionID=rawSessionID?.trim()?rawSessionID.trim():null,[head2,isClean,branchInfo,porcelain,remoteOutput,liveCheckout]=await Promise.all([_internals195.resolveCurrentGitHeadAsync(directory),_internals195.resolveIsWorkingTreeCleanAsync(directory),resolveBranch(directory),_internals195.runGitCapture(directory,["status","--porcelain=v1","--untracked-files=all"]),_internals195.runGitCapture(directory,["remote","-v"]),_internals195.classifyGitState(directory)]),dirty=parseDirtyFiles(porcelain),{remotes,remotesTruncated}=parseRemotes(remoteOutput),git2={head:head2,branch:branchInfo.branch,detached:branchInfo.detached,isClean,dirtyFileCount:dirty.dirtyFileCount,dirtyFiles:dirty.dirtyFiles,dirtyFilesTruncated:dirty.dirtyFilesTruncated,remotes,remotesTruncated},gate,activeState=null;if(!sessionID)gate={active:!1,reason:"no-session-context"};else{activeState=await _internals195.readPrWorkflowGateState(directory,sessionID);let receiptFiles=activeState?await countCheckoutReceiptFiles(directory,sessionID):null;gate=summarizeGate(activeState,receiptFiles)}let recovery=activeState?.checkoutRecovery,checkout=recovery?{kind:recovery.code==="GIT_STATE_INDETERMINATE"?"indeterminate":"recovery-required",code:recovery.code,retryable:!1,requiredAction:recovery.requiredAction,evidence:recovery.evidence}:liveCheckout,result={success:!0,sessionID,git:git2,checkout,gate,nextStep:describeNextStep(gate,git2,checkout)};return JSON.stringify(result,null,2)}var pr_workflow_status=createSwarmTool({description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary (mode, bound PR head, base ref/sha, depth tier, dispatch/validation batch counts). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",args:{},execute:async(_args,directory,ctx)=>executePrWorkflowStatus(directory,ctx?.sessionID)}),_internals195={readPrWorkflowGateState,resolveCurrentGitHeadAsync,resolveIsWorkingTreeCleanAsync,runGitCapture:runGitCapture2,classifyGitState:classifyPrWorkflowGitState,truncateToByteBudget};init_p_limit();init_zod();init_manager2();init_utils();init_bun_compat();init_create_tool();init_lint();init_quality_budget();init_sast_scan();init_secretscan();import*as path277 from"node:path";var TOOL_TIMEOUT_MS=60000,MAX_COMBINED_BYTES=500000,MAX_CONCURRENT=4,MAX_FILES=100,_internals196={qualityBudget,runLintWrapped,runSecretscanWrapped,runSastScanWrapped,runQualityBudgetWrapped,getChangedLineRanges};function isWindowsAbsolutePath(inputPath){return/^[A-Za-z]:[/\\]/.test(inputPath)}function validatePath(inputPath,baseDir,workspaceDir){if(typeof inputPath!=="string")return"path must be a string";if(!inputPath||inputPath.trim().length===0)return"path is required";let resolved,isWinAbs=isWindowsAbsolutePath(inputPath);if(isWinAbs)resolved=path277.win32.resolve(inputPath);else if(path277.isAbsolute(inputPath))resolved=path277.resolve(inputPath);else resolved=path277.resolve(baseDir,inputPath);let workspaceResolved=path277.resolve(workspaceDir),relative66;if(isWinAbs)relative66=path277.win32.relative(workspaceResolved,resolved);else relative66=path277.relative(workspaceResolved,resolved);if(relative66.startsWith(".."))return"path traversal detected";return null}function validateDirectory2(dir,workspaceDir){if(!dir||dir.length===0)return"directory is required";if(dir.length>500)return"directory path too long";let traversalCheck=validatePath(dir,workspaceDir,workspaceDir);if(traversalCheck)return traversalCheck;return null}async function runWithTimeout2(promise3,timeoutMs){let timeoutPromise=new Promise((_,reject2)=>{setTimeout(()=>reject2(Error(`Timeout after ${timeoutMs}ms`)),timeoutMs)});return Promise.race([promise3,timeoutPromise])}async function runLintWrapped(files,directory,_config){let start=process.hrtime.bigint();try{let linter=await detectAvailableLinter(directory);if(!linter)return{ran:!1,error:"No linter found (biome or eslint)",duration_ms:Number(process.hrtime.bigint()-start)/1e6};if(files&&files.length>0)return{ran:!0,result:await runLintOnFiles(linter,files,directory),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await runWithTimeout2(runLint(linter,"check",directory),TOOL_TIMEOUT_MS),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runLintOnFiles(linter,files,workspaceDir){let validatedFiles=[];for(let file3 of files){if(typeof file3!=="string")continue;let resolvedPath=path277.resolve(file3);if(validatePath(resolvedPath,workspaceDir,workspaceDir))continue;validatedFiles.push(resolvedPath)}if(validatedFiles.length===0)return{success:!1,mode:"check",linter,command:[],error:"No valid files after security validation"};let resolvedBin=resolveLinterBinPath(linter,workspaceDir),command;if(linter==="biome")command=[resolvedBin,"check",...validatedFiles];else command=[resolvedBin,...validatedFiles];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:workspaceDir}),[stdout,stderr]=await Promise.all([proc.stdout.text(),proc.stderr.text()]),exitCode=await proc.exited,output=stdout;if(stderr)output+=(output?`
|
|
6369
|
+
`)){let trimmed=line.trim();if(!trimmed)continue;let[name,rest]=trimmed.split(/\s+/,2);if(!name||!rest||byName.has(name))continue;let url3=rest.replace(/\s+\((?:fetch|push)\)\s*$/i,"");byName.set(boundUntrusted(name,64),boundUntrusted(url3,MAX_REMOTE_URL_LEN))}let entries=[...byName.entries()],remotes=entries.slice(0,MAX_REMOTES).map(([name,url3])=>({name,url:url3}));return{remotes,remotesTruncated:entries.length>remotes.length}}async function countCheckoutReceiptFiles(directory,sessionID){try{let receiptDirectory=validateSwarmPath(directory,path276.join(RECEIPT_DIR,prWorkflowSessionFileStem(sessionID)));return(await fsp7.readdir(receiptDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&/^[0-9a-f]{40,64}\.json$/i.test(entry.name)).length}catch(error93){if(error93.code==="ENOENT")return 0;return null}}function describeNextStep(gate,git2,checkout){if(checkout.kind==="recovery-required"||checkout.kind==="indeterminate")return`Manual Git recovery required. code=${checkout.code} retryable=false required_action=${checkout.requiredAction}`;if(!gate.active)return"No active PR workflow gate for this session. Activate with `/swarm pr-review <pr-ref>` or `/swarm pr-feedback <pr-ref>` before PR-workflow tool calls are admitted.";if(!gate.prHeadBound)return gate.mode==="PR_FEEDBACK"?"PR_FEEDBACK gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes). Prefer the intended exact tracking checkout, then bind; if this workflow inherited an already-detached exact intake head, bind it directly and the controller will attach the unique exact local/remote tracking ref. Ambiguity or an existing mismatched upstream fails closed.":"PR_REVIEW gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes), then bind the exact detached PR head.";if(git2.isClean===!1)return`${gate.mode} gate active and head bound, but the working tree is dirty. Read-only observation only; the gate keeps writes and non-tracking fetches fail-closed.`;if(git2.isClean===null)return`${gate.mode} gate active and head bound, but this session could not determine whether the working tree is clean (git status failed). Treat the tree state as unknown and verify manually before assuming it is clean; read-only observation only.`;return`${gate.mode} gate active and head bound. Continue read-only review using the admitted observe/validate tools (diff, gh_evidence, repo_map, lint check, etc.).`}function summarizeGate(state,receiptFiles){if(!state)return{active:!1,reason:"no-active-gate"};return{active:!0,mode:state.mode,prHeadBound:Boolean(state.prHeadSha),prHeadSha:state.prHeadSha??null,prFeedbackTargetUrl:state.prFeedbackTargetUrl?boundUntrusted(state.prFeedbackTargetUrl,MAX_FIELD_LEN):null,prReviewBaseRef:state.prReviewBaseRef?boundUntrusted(state.prReviewBaseRef,MAX_FIELD_LEN):null,prReviewBaseSha:state.prReviewBaseSha??null,prReviewDepthTier:state.prReviewDepthTier??null,baseDispatchBatches:state.prReviewBaseDispatches?.length??0,validationBatches:state.prReviewValidationBatches?.length??0,feedbackVerificationBatches:state.prFeedbackVerifications?.length??0,checkoutReceiptFiles:receiptFiles,activatedAt:state.activatedAt,updatedAt:state.updatedAt,revision:state.revision}}async function executePrWorkflowStatus(directory,rawSessionID){let sessionID=rawSessionID?.trim()?rawSessionID.trim():null,[head2,isClean,branchInfo,porcelain,remoteOutput,liveCheckout]=await Promise.all([_internals195.resolveCurrentGitHeadAsync(directory),_internals195.resolveIsWorkingTreeCleanAsync(directory),resolveBranch(directory),_internals195.runGitCapture(directory,["status","--porcelain=v1","--untracked-files=all"]),_internals195.runGitCapture(directory,["remote","-v"]),_internals195.classifyGitState(directory)]),dirty=parseDirtyFiles(porcelain),{remotes,remotesTruncated}=parseRemotes(remoteOutput),git2={head:head2,branch:branchInfo.branch,detached:branchInfo.detached,isClean,dirtyFileCount:dirty.dirtyFileCount,dirtyFiles:dirty.dirtyFiles,dirtyFilesTruncated:dirty.dirtyFilesTruncated,remotes,remotesTruncated},gate,activeState=null;if(!sessionID)gate={active:!1,reason:"no-session-context"};else{activeState=await _internals195.readPrWorkflowGateState(directory,sessionID);let receiptFiles=activeState?await countCheckoutReceiptFiles(directory,sessionID):null;gate=summarizeGate(activeState,receiptFiles)}let recovery=activeState?.checkoutRecovery,checkout=recovery?{kind:recovery.code==="GIT_STATE_INDETERMINATE"?"indeterminate":"recovery-required",code:recovery.code,retryable:!1,requiredAction:recovery.requiredAction,evidence:recovery.evidence}:liveCheckout,result={success:!0,sessionID,git:git2,checkout,gate,nextStep:describeNextStep(gate,git2,checkout)};return JSON.stringify(result,null,2)}var pr_workflow_status=createSwarmTool({description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary (mode, bound PR head, base ref/sha, depth tier, dispatch/validation batch counts). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",args:{},execute:async(_args,directory,ctx)=>executePrWorkflowStatus(directory,ctx?.sessionID)}),_internals195={readPrWorkflowGateState,resolveCurrentGitHeadAsync,resolveIsWorkingTreeCleanAsync,runGitCapture:runGitCapture2,classifyGitState:classifyPrWorkflowGitState,truncateToByteBudget};init_p_limit();init_zod();init_manager2();init_utils();init_bun_compat();init_create_tool();init_lint();init_quality_budget();init_sast_scan();init_secretscan();import*as path277 from"node:path";var TOOL_TIMEOUT_MS=60000,MAX_COMBINED_BYTES=500000,MAX_CONCURRENT=4,MAX_FILES=100,_internals196={qualityBudget,runLintWrapped,runSecretscanWrapped,runSastScanWrapped,runQualityBudgetWrapped,getChangedLineRanges,saveEvidence};function formatIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function evaluateSecretscanGate(toolResult,requestedFiles){if(toolResult.error)return{passed:!1,summary:`Secretscan wrapper error: ${toolResult.error}`,findingsCount:0};if(!toolResult.ran||!toolResult.result)return{passed:!1,summary:"Secretscan did not return a result",findingsCount:0};if("error"in toolResult.result)return{passed:!1,summary:`Secretscan error: ${toolResult.result.error}`,findingsCount:0};let result=toolResult.result;if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{passed:!1,summary:"Secretscan failed: scanner returned incomplete coverage metadata",result,findingsCount:Math.max(result.count,result.findings.length)};let findingsCount=Math.max(result.count,result.findings.length),failures=[];if(findingsCount>0)failures.push(`${findingsCount} secret finding(s)`);if(result.incomplete_files>0||result.incomplete_paths.length>0){let incompletePaths=result.incomplete_paths.length>0?`; incomplete paths: ${formatIncompletePaths(result.incomplete_paths)}`:"";failures.push(`${result.incomplete_files} incomplete file(s)${incompletePaths}`)}if(result.count!==result.findings.length)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(requestedFiles>0&&result.files_scanned===0)failures.push("zero requested files scanned");let statistics=`Secretscan: ${findingsCount} finding(s), ${result.files_scanned} files scanned, ${result.skipped_files} skipped`;return{passed:failures.length===0,summary:failures.length>0?`${statistics}; failed: ${failures.join("; ")}`:statistics,result,findingsCount}}function isWindowsAbsolutePath(inputPath){return/^[A-Za-z]:[/\\]/.test(inputPath)}function validatePath(inputPath,baseDir,workspaceDir){if(typeof inputPath!=="string")return"path must be a string";if(!inputPath||inputPath.trim().length===0)return"path is required";let resolved,isWinAbs=isWindowsAbsolutePath(inputPath);if(isWinAbs)resolved=path277.win32.resolve(inputPath);else if(path277.isAbsolute(inputPath))resolved=path277.resolve(inputPath);else resolved=path277.resolve(baseDir,inputPath);let workspaceResolved=path277.resolve(workspaceDir),relative66;if(isWinAbs)relative66=path277.win32.relative(workspaceResolved,resolved);else relative66=path277.relative(workspaceResolved,resolved);if(relative66.startsWith(".."))return"path traversal detected";return null}function validateDirectory2(dir,workspaceDir){if(!dir||dir.length===0)return"directory is required";if(dir.length>500)return"directory path too long";let traversalCheck=validatePath(dir,workspaceDir,workspaceDir);if(traversalCheck)return traversalCheck;return null}async function runWithTimeout2(promise3,timeoutMs){let timeoutPromise=new Promise((_,reject2)=>{setTimeout(()=>reject2(Error(`Timeout after ${timeoutMs}ms`)),timeoutMs)});return Promise.race([promise3,timeoutPromise])}async function runLintWrapped(files,directory,_config){let start=process.hrtime.bigint();try{let linter=await detectAvailableLinter(directory);if(!linter)return{ran:!1,error:"No linter found (biome or eslint)",duration_ms:Number(process.hrtime.bigint()-start)/1e6};if(files&&files.length>0)return{ran:!0,result:await runLintOnFiles(linter,files,directory),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await runWithTimeout2(runLint(linter,"check",directory),TOOL_TIMEOUT_MS),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runLintOnFiles(linter,files,workspaceDir){let validatedFiles=[];for(let file3 of files){if(typeof file3!=="string")continue;let resolvedPath=path277.resolve(file3);if(validatePath(resolvedPath,workspaceDir,workspaceDir))continue;validatedFiles.push(resolvedPath)}if(validatedFiles.length===0)return{success:!1,mode:"check",linter,command:[],error:"No valid files after security validation"};let resolvedBin=resolveLinterBinPath(linter,workspaceDir),command;if(linter==="biome")command=[resolvedBin,"check",...validatedFiles];else command=[resolvedBin,...validatedFiles];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:workspaceDir}),[stdout,stderr]=await Promise.all([proc.stdout.text(),proc.stderr.text()]),exitCode=await proc.exited,output=stdout;if(stderr)output+=(output?`
|
|
6370
6370
|
`:"")+stderr;if(output.length>512000)output=`${output.slice(0,512000)}
|
|
6371
6371
|
... (output truncated)`;let result={success:!0,mode:"check",linter,command,exitCode,output};if(exitCode===0)result.message=`${linter} check completed successfully with no issues`;else result.message=`${linter} check found issues (exit code ${exitCode}).`;return result}catch(error93){return{success:!1,mode:"check",linter,command,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error"}}}async function runSecretscanWrapped(files,directory,_config){let start=process.hrtime.bigint();try{if(files&&files.length>0)return{ran:!0,result:await runWithTimeout2(runSecretscanOnFiles(files,directory),TOOL_TIMEOUT_MS),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await runWithTimeout2(runSecretscan(directory),TOOL_TIMEOUT_MS),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runSastScanWrapped(changedFiles,directory,severityThreshold,config3,phase){let start=process.hrtime.bigint();try{return{ran:!0,result:await runWithTimeout2(sastScan({changed_files:changedFiles,severity_threshold:severityThreshold,phase},directory,config3),TOOL_TIMEOUT_MS),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runQualityBudgetWrapped(changedFiles,directory,config3){let start=process.hrtime.bigint();try{return{ran:!0,result:await runWithTimeout2(_internals196.qualityBudget({changed_files:changedFiles,config:config3?.gates?.quality_budget},directory),TOOL_TIMEOUT_MS),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}var GATE_SEVERITIES=new Set(["high","critical"]),SEVERITY_ORDER_PCB={low:0,medium:1,high:2,critical:3};function meetsThresholdForTriage(severity,threshold){return(SEVERITY_ORDER_PCB[severity]??0)>=(SEVERITY_ORDER_PCB[threshold]??1)}async function runGitDiff(args2,directory){try{let proc=bunSpawn(["git","diff",...args2],{cwd:directory,stdout:"pipe",stderr:"pipe"}),[exitCode,stdout]=await Promise.all([proc.exited,proc.stdout.text()]);if(exitCode!==0)return null;let trimmed=stdout.trim();return trimmed.length>0?trimmed:null}catch{return null}}function parseDiffLineRanges(diffOutput){let result=new Map,currentFile=null;for(let line of diffOutput.split(`
|
|
6372
|
-
`)){if(line.startsWith("+++ b/")){if(currentFile=line.slice(6).trim(),!result.has(currentFile))result.set(currentFile,new Set);continue}if(line.startsWith("@@")&¤tFile){let match=line.match(/^@@ [^+]*\+(\d+)(?:,(\d+))? @@/);if(match){let start=parseInt(match[1],10),count=match[2]!==void 0?parseInt(match[2],10):1,lines=result.get(currentFile);for(let i=start;i<start+count;i++)lines.add(i)}}}return result}async function getChangedLineRanges(directory){try{for(let baseBranch of["origin/main","origin/master","main","master"]){let mergeBaseProc=bunSpawn(["git","merge-base",baseBranch,"HEAD"],{cwd:directory,stdout:"pipe",stderr:"pipe"}),[mbExit,mbOut]=await Promise.all([mergeBaseProc.exited,mergeBaseProc.stdout.text()]);if(mbExit===0&&mbOut.trim()){let mergeBase=mbOut.trim(),diffOut=await runGitDiff(["-U0",`${mergeBase}..HEAD`],directory);if(diffOut)return parseDiffLineRanges(diffOut)}}let diffHead1=await runGitDiff(["-U0","HEAD~1"],directory);if(diffHead1)return parseDiffLineRanges(diffHead1);let diffHead=await runGitDiff(["-U0","HEAD"],directory);if(diffHead)return parseDiffLineRanges(diffHead);return null}catch{return null}}function classifySastFindings(findings,changedLineRanges,directory){if(!changedLineRanges||changedLineRanges.size===0)return{newFindings:findings,preexistingFindings:[]};let newFindings=[],preexistingFindings=[];for(let finding of findings){let filePath=finding.location.file,normalised=path277.relative(directory,filePath).replace(/\\/g,"/");if(changedLineRanges.get(normalised)?.has(finding.location.line))newFindings.push(finding);else preexistingFindings.push(finding)}return{newFindings,preexistingFindings}}async function runPreCheckBatch(input,workspaceDir,contextDir){let effectiveWorkspaceDir=workspaceDir||input.directory||contextDir,{files,directory,sast_threshold="medium",config:config3,phase}=input,dirError=validateDirectory2(directory,effectiveWorkspaceDir);if(dirError)return warn(`pre_check_batch: Invalid directory: ${dirError}`),{gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0};if(!files||files.length===0)return warn("pre_check_batch: No files provided, skipping all tools (fail-closed)"),{gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};let changedFiles=[];for(let file3 of files){if(typeof file3!=="string"){warn(`pre_check_batch: Non-string file entry rejected: ${String(file3)}`);continue}if(validatePath(file3,directory,effectiveWorkspaceDir)){warn(`pre_check_batch: Invalid file path: ${file3}`);continue}changedFiles.push(path277.resolve(directory,file3))}if(changedFiles.length===0)return warn("pre_check_batch: No valid files after validation, skipping all tools (fail-closed)"),{gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};if(changedFiles.length>MAX_FILES)throw Error(`Input exceeds maximum file count: ${changedFiles.length} > ${MAX_FILES}`);let limit=pLimit(MAX_CONCURRENT),[lintResult,secretscanResult,sastScanResult,qualityBudgetResult]=await Promise.all([limit(()=>_internals196.runLintWrapped(changedFiles,directory,config3)),limit(()=>_internals196.runSecretscanWrapped(changedFiles,directory,config3)),limit(()=>_internals196.runSastScanWrapped(changedFiles,directory,sast_threshold,config3,phase)),limit(()=>_internals196.runQualityBudgetWrapped(changedFiles,directory,config3))]),totalDuration=lintResult.duration_ms+secretscanResult.duration_ms+sastScanResult.duration_ms+qualityBudgetResult.duration_ms,gatesPassed=!0;if(lintResult.ran&&lintResult.result){let lintRes=lintResult.result;if("success"in lintRes&&lintRes.success===!1)warn("pre_check_batch: Lint found issues (informational only)")}else if(lintResult.error)warn(`pre_check_batch: Lint error (informational only): ${lintResult.error}`);if(secretscanResult.ran&&secretscanResult.result){let scanResult=secretscanResult.result;if("error"in scanResult&&scanResult.error)gatesPassed=!1,warn(`pre_check_batch: Secretscan error - GATE FAILED: ${scanResult.error}`);else if("findings"in scanResult&&scanResult.findings.length>0)gatesPassed=!1,warn("pre_check_batch: Secretscan found secrets - GATE FAILED");else if(files&&files.length>0&&(scanResult.files_scanned??0)===0)gatesPassed=!1,warn("pre_check_batch: Secretscan scanned 0 files despite requested file scope - GATE FAILED (possible vacuous pass)")}else if(secretscanResult.error)gatesPassed=!1,warn(`pre_check_batch: Secretscan error - GATE FAILED: ${secretscanResult.error}`);if(secretscanResult.ran&&secretscanResult.result)try{let scanResult=secretscanResult.result,secretscanEvidence={task_id:"secretscan",type:"secretscan",timestamp:new Date().toISOString(),agent:"pre_check_batch",verdict:scanResult.count>0?"fail":"pass",summary:`Secretscan: ${scanResult.count} finding(s), ${scanResult.files_scanned??0} files scanned, ${scanResult.skipped_files??0} skipped`,findings_count:scanResult.count,scan_directory:scanResult.scan_dir,files_scanned:scanResult.files_scanned,skipped_files:scanResult.skipped_files};await saveEvidence(directory,"secretscan",secretscanEvidence)}catch(e){warn(`Failed to persist secretscan evidence: ${e instanceof Error?e.message:String(e)}`)}let sastPreexistingFindings;if(sastScanResult.ran&&sastScanResult.result){let sastResult=sastScanResult.result;if(sastResult.baseline_used){if(sastResult.pre_existing_findings&&sastResult.pre_existing_findings.length>0){if(sastPreexistingFindings=sastResult.pre_existing_findings.filter((f)=>meetsThresholdForTriage(f.severity,sast_threshold)),sastPreexistingFindings.length>0)warn(`pre_check_batch: SAST baseline diff found ${sastPreexistingFindings.length} pre-existing finding(s) - passing to reviewer for triage`)}if(sastResult.verdict==="fail")gatesPassed=!1,warn("pre_check_batch: SAST scan found new findings above threshold - GATE FAILED")}else if(sastResult.verdict==="fail"){let gateFindings=sastResult.findings.filter((f)=>GATE_SEVERITIES.has(f.severity));if(gateFindings.length>0){let changedLineRanges=await _internals196.getChangedLineRanges(directory),{newFindings,preexistingFindings}=classifySastFindings(gateFindings,changedLineRanges,directory);if(newFindings.length>0)gatesPassed=!1,warn(`pre_check_batch: SAST scan found ${newFindings.length} new HIGH/CRITICAL finding(s) on changed lines - GATE FAILED`);else if(preexistingFindings.length>0)sastPreexistingFindings=preexistingFindings,warn(`pre_check_batch: SAST scan found ${preexistingFindings.length} pre-existing HIGH/CRITICAL finding(s) on unchanged lines - passing to reviewer for triage`)}else gatesPassed=!1,warn("pre_check_batch: SAST scan found vulnerabilities - GATE FAILED")}}else if(sastScanResult.error)gatesPassed=!1,warn(`pre_check_batch: SAST scan error - GATE FAILED: ${sastScanResult.error}`);if(qualityBudgetResult.ran&&qualityBudgetResult.result){if(qualityBudgetResult.result.verdict==="fail")warn("pre_check_batch: Quality budget exceeded (informational only)")}else if(qualityBudgetResult.error)warn(`pre_check_batch: Quality budget error (informational only): ${qualityBudgetResult.error}`);let result={gates_passed:gatesPassed,lint:lintResult,secretscan:secretscanResult,sast_scan:sastScanResult,quality_budget:qualityBudgetResult,total_duration_ms:Math.round(totalDuration),...sastPreexistingFindings&&sastPreexistingFindings.length>0&&{sast_preexisting_findings:sastPreexistingFindings}},outputSize=JSON.stringify(result).length;if(outputSize>MAX_COMBINED_BYTES)warn(`pre_check_batch: Large output (${outputSize} bytes)`);return result}var pre_check_batch=createSwarmTool({description:"Run multiple verification tools in parallel: lint, secretscan, SAST scan, and quality budget. Returns unified result with gates_passed status. Security tools (secretscan, sast_scan) are HARD GATES - failures block merging.",args:{files:exports_external.array(exports_external.string()).optional().describe("Specific files to check (optional, scans directory if not provided)"),directory:exports_external.string().describe("Project root directory — must be the workspace root, subdirectories are rejected"),sast_threshold:exports_external.enum(["low","medium","high","critical"]).optional().describe("Minimum severity for SAST findings to cause failure (default: medium)"),phase:exports_external.number().int().min(1).optional().describe("Current phase number (positive integer >= 1). When provided, enables SAST baseline diffing: only findings absent from the phase-scoped baseline fail the gate.")},async execute(args2,directory){if(!args2||typeof args2!=="object")return JSON.stringify({gates_passed:!1,lint:{ran:!1,error:"Invalid arguments",duration_ms:0},secretscan:{ran:!1,error:"Invalid arguments",duration_ms:0},sast_scan:{ran:!1,error:"Invalid arguments",duration_ms:0},quality_budget:{ran:!1,error:"Invalid arguments",duration_ms:0},total_duration_ms:0},null,2);if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({gates_passed:!1,lint:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},secretscan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},sast_scan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},quality_budget:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},total_duration_ms:0},null,2);let typedArgs=args2;if(!typedArgs.directory)return JSON.stringify({gates_passed:!1,lint:{ran:!1,error:"directory is required",duration_ms:0},secretscan:{ran:!1,error:"directory is required",duration_ms:0},sast_scan:{ran:!1,error:"directory is required",duration_ms:0},quality_budget:{ran:!1,error:"directory is required",duration_ms:0},total_duration_ms:0},null,2);let resolvedDirectory=path277.resolve(typedArgs.directory),workspaceAnchor=path277.resolve(directory);if(resolvedDirectory!==workspaceAnchor&&resolvedDirectory.startsWith(workspaceAnchor+path277.sep)){let subDirError=`directory "${typedArgs.directory}" is a subdirectory of the project root — pre_check_batch requires the project root directory "${workspaceAnchor}"`;return JSON.stringify({gates_passed:!1,lint:{ran:!1,error:subDirError,duration_ms:0},secretscan:{ran:!1,error:subDirError,duration_ms:0},sast_scan:{ran:!1,error:subDirError,duration_ms:0},quality_budget:{ran:!1,error:subDirError,duration_ms:0},total_duration_ms:0},null,2)}let dirError=validateDirectory2(resolvedDirectory,workspaceAnchor);if(dirError)return JSON.stringify({gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0},null,2);try{let rawPhase=typedArgs.phase,safePhase=typeof rawPhase==="number"&&Number.isInteger(rawPhase)&&rawPhase>=1?rawPhase:void 0,result=await runPreCheckBatch({files:typedArgs.files,directory:resolvedDirectory,sast_threshold:typedArgs.sast_threshold,config:typedArgs.config,phase:safePhase},workspaceAnchor,directory);return JSON.stringify(result,null,2)}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return JSON.stringify({gates_passed:!1,lint:{ran:!1,error:errorMessage3,duration_ms:0},secretscan:{ran:!1,error:errorMessage3,duration_ms:0},sast_scan:{ran:!1,error:errorMessage3,duration_ms:0},quality_budget:{ran:!1,error:errorMessage3,duration_ms:0},total_duration_ms:0},null,2)}}});init_zod();init_guardrails2();init_pr_workflow_gate();init_scope_binding();init_create_tool();var PreparePrFeedbackScopeArgsSchema=exports_external.object({task_id:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/,"task_id must use N.M notation"),files:exports_external.array(exports_external.string().min(1).max(4096)).min(1).max(1e4)}).strict();function failure(message){return JSON.stringify({success:!1,message},null,2)}async function executePreparePrFeedbackScope(args2,directory,context={}){let parsed=PreparePrFeedbackScopeArgsSchema.safeParse(args2);if(!parsed.success)return failure(`Invalid PR-feedback scope: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure("PR-feedback scope requires an active session");let files=normalizeScopeFiles(parsed.data.files);if(!files)return failure("PR-feedback scope contains an unsafe file path");for(let file3 of files){let symlinkBlock=checkWriteTargetForSymlink(file3,directory);if(symlinkBlock)return failure(symlinkBlock)}try{await declarePrFeedbackScope(directory,sessionID,parsed.data.task_id,files)}catch(error93){return failure(error93 instanceof Error?error93.message:String(error93))}return JSON.stringify({success:!0,task_id:parsed.data.task_id,files,message:"Scope is bound to the verified PR-feedback revision and will authorize only the next matching coder Task."},null,2)}var prepare_pr_feedback_scope=createSwarmTool({description:"Prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles.",args:{task_id:PreparePrFeedbackScopeArgsSchema.shape.task_id,files:PreparePrFeedbackScopeArgsSchema.shape.files},execute:executePreparePrFeedbackScope});init_zod();init_pr_workflow_state();init_pr_workflow_gate();init_utils2();init_bun_compat();init_path_security();init_create_tool();import{randomUUID as randomUUID24}from"node:crypto";import*as fsp8 from"node:fs/promises";import*as path278 from"node:path";var GIT_TIMEOUT_MS10=30000,MAX_CHECKOUT_PATHS=32,MAX_CHECKOUT_RECEIPTS=8,MAX_RECEIPT_PATHS=64,MAX_ECHOED_PATH_LEN=200,RECEIPT_DIR2="pr-workflow-checkouts",PreparePrWorkflowCheckoutArgsSchema=exports_external.object({paths:exports_external.array(exports_external.string().min(1).max(240)).min(1).max(32).optional()}).strict();async function executePreparePrWorkflowCheckout(args2,directory,context={}){let parsed=PreparePrWorkflowCheckoutArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow checkout preparation: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow checkout preparation requires an active sessionID"});try{let outcome=await preparePrWorkflowCheckout(directory,context.sessionID,parsed.data.paths);if(outcome.kind==="already_clean")return JSON.stringify({success:!0,already_clean:!0,message:"Working tree is already clean; no checkout preparation was needed. Proceed to bind the PR head."});if(outcome.kind==="recovery_required"){let affectedPaths=outcome.recovery.evidence.paths.map(boundUntrustedPath).filter(Boolean),pathSummary=affectedPaths.length>0?` Affected paths: ${affectedPaths.join(", ")}.`:"";return JSON.stringify({success:!1,code:outcome.recovery.code,retryable:!1,required_action:outcome.recovery.requiredAction,evidence:outcome.recovery.evidence,message:`PR workflow checkout requires manual Git recovery (${outcome.recovery.code}); no stash command was attempted. ${outcome.recovery.requiredAction}${pathSummary}`})}let{preparation}=outcome,response={success:!0,stash_oid:preparation.stashOid,paths:preparation.paths,recovery:recoveryInstruction(preparation.stashOid)};if(preparation.discovered)response.discovered=!0,response.included_untracked=preparation.includedUntracked??!1,response.paths_truncated=preparation.pathsTruncated??!1;return JSON.stringify(response)}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}async function preparePrWorkflowCheckout(directory,rawSessionID,requestedPaths){let sessionID=normalizeSessionID3(rawSessionID),discoveryMode=!requestedPaths||requestedPaths.length===0,paths=discoveryMode?[]:normalizePaths(directory,requestedPaths);return withPrWorkflowCheckoutPreparationLock(directory,sessionID,async(gate,controls)=>{if(gate.checkoutRecovery)return{kind:"recovery_required",recovery:gate.checkoutRecovery};let checkoutState=await _internals197.classifyGitState(directory);if(checkoutState.kind==="recovery-required"||checkoutState.kind==="indeterminate")return{kind:"recovery_required",recovery:(await controls.markRecoveryRequired(checkoutState)).checkoutRecovery};if(discoveryMode&&checkoutState.kind==="clean")return{kind:"already_clean"};if(await countOutstandingReceipts(directory,sessionID)>=MAX_CHECKOUT_RECEIPTS)throw Error("BLOCKED: PR workflow checkout preparation limit reached; resolve the existing preserved stashes before continuing");let openLanes=await countOpenPrWorkflowLanes(directory,sessionID);if(openLanes>0)throw Error(`BLOCKED: ${gate.mode} checkout preparation is refused while ${openLanes} PR workflow lane(s) are in flight`);if(discoveryMode)return prepareDiscoveredCheckout(directory,sessionID,gate);await assertExactDirtyPathSet(directory,paths);let stashMarker=`pr-workflow-checkout-${randomUUID24()}`;if((await _internals197.runGit(directory,["stash","push",`--message=${stashMarker}`,"--",...paths])).exitCode!==0)throw Error("BLOCKED: Git could not preserve the requested checkout-preparation paths; resolve the working tree manually or abort the workflow");let stashOid=await resolveMarkedStashOid(directory,stashMarker,paths),preparation={stashOid,paths,preparedAt:new Date().toISOString(),mode:gate.mode,gateRevision:gate.revision,gateActivatedAt:gate.activatedAt};try{await writeReceipt(directory,sessionID,preparation)}catch(error93){throw Error(`BLOCKED: stash ${stashOid} was created but its durable checkout-preparation receipt could not be recorded (${error93 instanceof Error?error93.message:String(error93)}). Do not continue; ${recoveryInstruction(stashOid)}.`)}return await assertCleanWorkingTree2(directory,stashOid),await appendPreparationEvent(directory,sessionID,preparation),{kind:"prepared",preparation}})}async function prepareDiscoveredCheckout(directory,sessionID,gate){let status=await readPorcelainStatus(directory);if(status.dirtyTrackedPaths.length===0&&status.untrackedPaths.length===0&&!status.renameOrCopy)return{kind:"already_clean"};let swarmUntracked=status.untrackedPaths.filter((candidate2)=>candidate2===".swarm"||candidate2.startsWith(".swarm/"));if(swarmUntracked.length>0)throw Error(`BLOCKED: checkout preparation refuses untracked churn under .swarm/ (${swarmUntracked.slice(0,5).map((entry)=>boundUntrustedPath(entry)).join(", ")}); that directory must stay git-excluded (.git/info/exclude). Resolve the .swarm/ tracking regression before preparing a checkout.`);let includedUntracked=status.untrackedPaths.length>0,stashMarker=`pr-workflow-checkout-${randomUUID24()}`;if((await _internals197.runGit(directory,["stash","push","--include-untracked",`--message=${stashMarker}`],{literalPathspecs:!1})).exitCode!==0)throw Error("BLOCKED: Git could not preserve the discovered working-tree changes; resolve the working tree manually or abort the workflow");let stashOid=await resolveMarkedStashOidByMarker(directory,stashMarker),discoveredPaths=[...status.dirtyTrackedPaths,...status.untrackedPaths].sort(),pathsTruncated=discoveredPaths.length>MAX_RECEIPT_PATHS,receiptPaths=pathsTruncated?discoveredPaths.slice(0,MAX_RECEIPT_PATHS):discoveredPaths,preparation={stashOid,paths:receiptPaths,preparedAt:new Date().toISOString(),mode:gate.mode,gateRevision:gate.revision,gateActivatedAt:gate.activatedAt,discovered:!0,includedUntracked,pathsTruncated};try{await writeReceipt(directory,sessionID,preparation)}catch(error93){throw Error(`BLOCKED: stash ${stashOid} was created but its durable checkout-preparation receipt could not be recorded (${error93 instanceof Error?error93.message:String(error93)}). Do not continue; ${recoveryInstruction(stashOid)}.`)}return await assertCleanWorkingTree2(directory,stashOid,{discovery:!0}),await appendPreparationEvent(directory,sessionID,preparation),{kind:"prepared",preparation}}function normalizeSessionID3(sessionID){let normalized=sessionID.trim();if(!normalized)throw Error("BLOCKED: PR workflow checkout preparation requires a non-empty sessionID");return normalized}function normalizePaths(directory,requestedPaths){if(!Array.isArray(requestedPaths)||requestedPaths.length===0||requestedPaths.length>MAX_CHECKOUT_PATHS)throw Error(`BLOCKED: checkout preparation requires 1-${MAX_CHECKOUT_PATHS} explicit paths`);let root=path278.resolve(directory),normalized=[],seen=new Set;for(let value of requestedPaths){if(typeof value!=="string"||!value)throw Error("BLOCKED: checkout preparation paths must be non-empty strings");if(value.includes("\\")||path278.posix.normalize(value)!==value||path278.posix.isAbsolute(value)||/^[A-Za-z]:/.test(value)||containsControlChars(value))throw Error("BLOCKED: checkout preparation path must be a literal slash-separated repository-relative path");let segments=value.split("/");if(segments.some((segment)=>!segment||segment==="."||segment==="..")||segments[0]===".git"||segments[0]===".swarm")throw Error("BLOCKED: checkout preparation path is not an allowed repository file path");let resolved=path278.resolve(root,...segments),relative67=path278.relative(root,resolved);if(!relative67||relative67.startsWith(`..${path278.sep}`)||path278.isAbsolute(relative67))throw Error("BLOCKED: checkout preparation path escapes the project root");if(seen.has(value))throw Error("BLOCKED: checkout preparation path was supplied more than once");seen.add(value),normalized.push(value)}return normalized}async function countOpenPrWorkflowLanes(directory,sessionID){let filePath=validateSwarmPath(directory,"background-delegations.jsonl"),raw;try{raw=await fsp8.readFile(filePath,"utf-8")}catch(error93){if(error93.code==="ENOENT")return 0;throw Error("BLOCKED: unable to inspect PR workflow lanes; cannot safely prepare checkout")}let latestByCorrelationID=new Map;for(let rawLine of raw.split(`
|
|
6372
|
+
`)){if(line.startsWith("+++ b/")){if(currentFile=line.slice(6).trim(),!result.has(currentFile))result.set(currentFile,new Set);continue}if(line.startsWith("@@")&¤tFile){let match=line.match(/^@@ [^+]*\+(\d+)(?:,(\d+))? @@/);if(match){let start=parseInt(match[1],10),count=match[2]!==void 0?parseInt(match[2],10):1,lines=result.get(currentFile);for(let i=start;i<start+count;i++)lines.add(i)}}}return result}async function getChangedLineRanges(directory){try{for(let baseBranch of["origin/main","origin/master","main","master"]){let mergeBaseProc=bunSpawn(["git","merge-base",baseBranch,"HEAD"],{cwd:directory,stdout:"pipe",stderr:"pipe"}),[mbExit,mbOut]=await Promise.all([mergeBaseProc.exited,mergeBaseProc.stdout.text()]);if(mbExit===0&&mbOut.trim()){let mergeBase=mbOut.trim(),diffOut=await runGitDiff(["-U0",`${mergeBase}..HEAD`],directory);if(diffOut)return parseDiffLineRanges(diffOut)}}let diffHead1=await runGitDiff(["-U0","HEAD~1"],directory);if(diffHead1)return parseDiffLineRanges(diffHead1);let diffHead=await runGitDiff(["-U0","HEAD"],directory);if(diffHead)return parseDiffLineRanges(diffHead);return null}catch{return null}}function classifySastFindings(findings,changedLineRanges,directory){if(!changedLineRanges||changedLineRanges.size===0)return{newFindings:findings,preexistingFindings:[]};let newFindings=[],preexistingFindings=[];for(let finding of findings){let filePath=finding.location.file,normalised=path277.relative(directory,filePath).replace(/\\/g,"/");if(changedLineRanges.get(normalised)?.has(finding.location.line))newFindings.push(finding);else preexistingFindings.push(finding)}return{newFindings,preexistingFindings}}async function runPreCheckBatch(input,workspaceDir,contextDir){let effectiveWorkspaceDir=workspaceDir||input.directory||contextDir,{files,directory,sast_threshold="medium",config:config3,phase}=input,dirError=validateDirectory2(directory,effectiveWorkspaceDir);if(dirError)return warn(`pre_check_batch: Invalid directory: ${dirError}`),{gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0};if(!files||files.length===0)return warn("pre_check_batch: No files provided, skipping all tools (fail-closed)"),{gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};let changedFiles=[];for(let file3 of files){if(typeof file3!=="string"){warn(`pre_check_batch: Non-string file entry rejected: ${String(file3)}`);continue}if(validatePath(file3,directory,effectiveWorkspaceDir)){warn(`pre_check_batch: Invalid file path: ${file3}`);continue}changedFiles.push(path277.resolve(directory,file3))}if(changedFiles.length===0)return warn("pre_check_batch: No valid files after validation, skipping all tools (fail-closed)"),{gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};if(changedFiles.length>MAX_FILES)throw Error(`Input exceeds maximum file count: ${changedFiles.length} > ${MAX_FILES}`);let limit=pLimit(MAX_CONCURRENT),[lintResult,secretscanResult,sastScanResult,qualityBudgetResult]=await Promise.all([limit(()=>_internals196.runLintWrapped(changedFiles,directory,config3)),limit(()=>_internals196.runSecretscanWrapped(changedFiles,directory,config3)),limit(()=>_internals196.runSastScanWrapped(changedFiles,directory,sast_threshold,config3,phase)),limit(()=>_internals196.runQualityBudgetWrapped(changedFiles,directory,config3))]),totalDuration=lintResult.duration_ms+secretscanResult.duration_ms+sastScanResult.duration_ms+qualityBudgetResult.duration_ms,gatesPassed=!0;if(lintResult.ran&&lintResult.result){let lintRes=lintResult.result;if("success"in lintRes&&lintRes.success===!1)warn("pre_check_batch: Lint found issues (informational only)")}else if(lintResult.error)warn(`pre_check_batch: Lint error (informational only): ${lintResult.error}`);let secretscanDecision=evaluateSecretscanGate(secretscanResult,changedFiles.length);if(!secretscanDecision.passed)gatesPassed=!1,warn(`pre_check_batch: ${secretscanDecision.summary} - GATE FAILED`);if(secretscanResult.ran||secretscanResult.error)try{let scanResult=secretscanDecision.result,secretscanEvidence={task_id:"secretscan",type:"secretscan",timestamp:new Date().toISOString(),agent:"pre_check_batch",verdict:secretscanDecision.passed?"pass":"fail",summary:secretscanDecision.summary,findings_count:secretscanDecision.findingsCount,scan_directory:scanResult?.scan_dir??directory,files_scanned:scanResult?.files_scanned??0,skipped_files:scanResult?.skipped_files??0,incomplete_files:scanResult?.incomplete_files??changedFiles.length,incomplete_paths:scanResult?.incomplete_paths??[{path:".",reason:"missing_coverage_metadata"}]};await _internals196.saveEvidence(directory,"secretscan",secretscanEvidence)}catch(e){warn(`Failed to persist secretscan evidence: ${e instanceof Error?e.message:String(e)}`)}let sastPreexistingFindings;if(sastScanResult.ran&&sastScanResult.result){let sastResult=sastScanResult.result;if(sastResult.baseline_used){if(sastResult.pre_existing_findings&&sastResult.pre_existing_findings.length>0){if(sastPreexistingFindings=sastResult.pre_existing_findings.filter((f)=>meetsThresholdForTriage(f.severity,sast_threshold)),sastPreexistingFindings.length>0)warn(`pre_check_batch: SAST baseline diff found ${sastPreexistingFindings.length} pre-existing finding(s) - passing to reviewer for triage`)}if(sastResult.verdict==="fail")gatesPassed=!1,warn("pre_check_batch: SAST scan found new findings above threshold - GATE FAILED")}else if(sastResult.verdict==="fail"){let gateFindings=sastResult.findings.filter((f)=>GATE_SEVERITIES.has(f.severity));if(gateFindings.length>0){let changedLineRanges=await _internals196.getChangedLineRanges(directory),{newFindings,preexistingFindings}=classifySastFindings(gateFindings,changedLineRanges,directory);if(newFindings.length>0)gatesPassed=!1,warn(`pre_check_batch: SAST scan found ${newFindings.length} new HIGH/CRITICAL finding(s) on changed lines - GATE FAILED`);else if(preexistingFindings.length>0)sastPreexistingFindings=preexistingFindings,warn(`pre_check_batch: SAST scan found ${preexistingFindings.length} pre-existing HIGH/CRITICAL finding(s) on unchanged lines - passing to reviewer for triage`)}else gatesPassed=!1,warn("pre_check_batch: SAST scan found vulnerabilities - GATE FAILED")}}else if(sastScanResult.error)gatesPassed=!1,warn(`pre_check_batch: SAST scan error - GATE FAILED: ${sastScanResult.error}`);if(qualityBudgetResult.ran&&qualityBudgetResult.result){if(qualityBudgetResult.result.verdict==="fail")warn("pre_check_batch: Quality budget exceeded (informational only)")}else if(qualityBudgetResult.error)warn(`pre_check_batch: Quality budget error (informational only): ${qualityBudgetResult.error}`);let result={gates_passed:gatesPassed,lint:lintResult,secretscan:secretscanResult,sast_scan:sastScanResult,quality_budget:qualityBudgetResult,total_duration_ms:Math.round(totalDuration),...sastPreexistingFindings&&sastPreexistingFindings.length>0&&{sast_preexisting_findings:sastPreexistingFindings}},outputSize=JSON.stringify(result).length;if(outputSize>MAX_COMBINED_BYTES)warn(`pre_check_batch: Large output (${outputSize} bytes)`);return result}var pre_check_batch=createSwarmTool({description:"Run multiple verification tools in parallel: lint, secretscan, SAST scan, and quality budget. Returns unified result with gates_passed status. Security tools (secretscan, sast_scan) are HARD GATES - failures block merging.",args:{files:exports_external.array(exports_external.string()).optional().describe("Specific files to check (optional, scans directory if not provided)"),directory:exports_external.string().describe("Project root directory — must be the workspace root, subdirectories are rejected"),sast_threshold:exports_external.enum(["low","medium","high","critical"]).optional().describe("Minimum severity for SAST findings to cause failure (default: medium)"),phase:exports_external.number().int().min(1).optional().describe("Current phase number (positive integer >= 1). When provided, enables SAST baseline diffing: only findings absent from the phase-scoped baseline fail the gate.")},async execute(args2,directory){if(!args2||typeof args2!=="object")return JSON.stringify({gates_passed:!1,lint:{ran:!1,error:"Invalid arguments",duration_ms:0},secretscan:{ran:!1,error:"Invalid arguments",duration_ms:0},sast_scan:{ran:!1,error:"Invalid arguments",duration_ms:0},quality_budget:{ran:!1,error:"Invalid arguments",duration_ms:0},total_duration_ms:0},null,2);if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({gates_passed:!1,lint:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},secretscan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},sast_scan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},quality_budget:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},total_duration_ms:0},null,2);let typedArgs=args2;if(!typedArgs.directory)return JSON.stringify({gates_passed:!1,lint:{ran:!1,error:"directory is required",duration_ms:0},secretscan:{ran:!1,error:"directory is required",duration_ms:0},sast_scan:{ran:!1,error:"directory is required",duration_ms:0},quality_budget:{ran:!1,error:"directory is required",duration_ms:0},total_duration_ms:0},null,2);let resolvedDirectory=path277.resolve(typedArgs.directory),workspaceAnchor=path277.resolve(directory);if(resolvedDirectory!==workspaceAnchor&&resolvedDirectory.startsWith(workspaceAnchor+path277.sep)){let subDirError=`directory "${typedArgs.directory}" is a subdirectory of the project root — pre_check_batch requires the project root directory "${workspaceAnchor}"`;return JSON.stringify({gates_passed:!1,lint:{ran:!1,error:subDirError,duration_ms:0},secretscan:{ran:!1,error:subDirError,duration_ms:0},sast_scan:{ran:!1,error:subDirError,duration_ms:0},quality_budget:{ran:!1,error:subDirError,duration_ms:0},total_duration_ms:0},null,2)}let dirError=validateDirectory2(resolvedDirectory,workspaceAnchor);if(dirError)return JSON.stringify({gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0},null,2);try{let rawPhase=typedArgs.phase,safePhase=typeof rawPhase==="number"&&Number.isInteger(rawPhase)&&rawPhase>=1?rawPhase:void 0,result=await runPreCheckBatch({files:typedArgs.files,directory:resolvedDirectory,sast_threshold:typedArgs.sast_threshold,config:typedArgs.config,phase:safePhase},workspaceAnchor,directory);return JSON.stringify(result,null,2)}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return JSON.stringify({gates_passed:!1,lint:{ran:!1,error:errorMessage3,duration_ms:0},secretscan:{ran:!1,error:errorMessage3,duration_ms:0},sast_scan:{ran:!1,error:errorMessage3,duration_ms:0},quality_budget:{ran:!1,error:errorMessage3,duration_ms:0},total_duration_ms:0},null,2)}}});init_zod();init_guardrails2();init_pr_workflow_gate();init_scope_binding();init_create_tool();var PreparePrFeedbackScopeArgsSchema=exports_external.object({task_id:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/,"task_id must use N.M notation"),files:exports_external.array(exports_external.string().min(1).max(4096)).min(1).max(1e4)}).strict();function failure(message){return JSON.stringify({success:!1,message},null,2)}async function executePreparePrFeedbackScope(args2,directory,context={}){let parsed=PreparePrFeedbackScopeArgsSchema.safeParse(args2);if(!parsed.success)return failure(`Invalid PR-feedback scope: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure("PR-feedback scope requires an active session");let files=normalizeScopeFiles(parsed.data.files);if(!files)return failure("PR-feedback scope contains an unsafe file path");for(let file3 of files){let symlinkBlock=checkWriteTargetForSymlink(file3,directory);if(symlinkBlock)return failure(symlinkBlock)}try{await declarePrFeedbackScope(directory,sessionID,parsed.data.task_id,files)}catch(error93){return failure(error93 instanceof Error?error93.message:String(error93))}return JSON.stringify({success:!0,task_id:parsed.data.task_id,files,message:"Scope is bound to the verified PR-feedback revision and will authorize only the next matching coder Task."},null,2)}var prepare_pr_feedback_scope=createSwarmTool({description:"Prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles.",args:{task_id:PreparePrFeedbackScopeArgsSchema.shape.task_id,files:PreparePrFeedbackScopeArgsSchema.shape.files},execute:executePreparePrFeedbackScope});init_zod();init_pr_workflow_state();init_pr_workflow_gate();init_utils2();init_bun_compat();init_path_security();init_create_tool();import{randomUUID as randomUUID24}from"node:crypto";import*as fsp8 from"node:fs/promises";import*as path278 from"node:path";var GIT_TIMEOUT_MS10=30000,MAX_CHECKOUT_PATHS=32,MAX_CHECKOUT_RECEIPTS=8,MAX_RECEIPT_PATHS=64,MAX_ECHOED_PATH_LEN=200,RECEIPT_DIR2="pr-workflow-checkouts",PreparePrWorkflowCheckoutArgsSchema=exports_external.object({paths:exports_external.array(exports_external.string().min(1).max(240)).min(1).max(32).optional()}).strict();async function executePreparePrWorkflowCheckout(args2,directory,context={}){let parsed=PreparePrWorkflowCheckoutArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow checkout preparation: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow checkout preparation requires an active sessionID"});try{let outcome=await preparePrWorkflowCheckout(directory,context.sessionID,parsed.data.paths);if(outcome.kind==="already_clean")return JSON.stringify({success:!0,already_clean:!0,message:"Working tree is already clean; no checkout preparation was needed. Proceed to bind the PR head."});if(outcome.kind==="recovery_required"){let affectedPaths=outcome.recovery.evidence.paths.map(boundUntrustedPath).filter(Boolean),pathSummary=affectedPaths.length>0?` Affected paths: ${affectedPaths.join(", ")}.`:"";return JSON.stringify({success:!1,code:outcome.recovery.code,retryable:!1,required_action:outcome.recovery.requiredAction,evidence:outcome.recovery.evidence,message:`PR workflow checkout requires manual Git recovery (${outcome.recovery.code}); no stash command was attempted. ${outcome.recovery.requiredAction}${pathSummary}`})}let{preparation}=outcome,response={success:!0,stash_oid:preparation.stashOid,paths:preparation.paths,recovery:recoveryInstruction(preparation.stashOid)};if(preparation.discovered)response.discovered=!0,response.included_untracked=preparation.includedUntracked??!1,response.paths_truncated=preparation.pathsTruncated??!1;return JSON.stringify(response)}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}async function preparePrWorkflowCheckout(directory,rawSessionID,requestedPaths){let sessionID=normalizeSessionID3(rawSessionID),discoveryMode=!requestedPaths||requestedPaths.length===0,paths=discoveryMode?[]:normalizePaths(directory,requestedPaths);return withPrWorkflowCheckoutPreparationLock(directory,sessionID,async(gate,controls)=>{if(gate.checkoutRecovery)return{kind:"recovery_required",recovery:gate.checkoutRecovery};let checkoutState=await _internals197.classifyGitState(directory);if(checkoutState.kind==="recovery-required"||checkoutState.kind==="indeterminate")return{kind:"recovery_required",recovery:(await controls.markRecoveryRequired(checkoutState)).checkoutRecovery};if(discoveryMode&&checkoutState.kind==="clean")return{kind:"already_clean"};if(await countOutstandingReceipts(directory,sessionID)>=MAX_CHECKOUT_RECEIPTS)throw Error("BLOCKED: PR workflow checkout preparation limit reached; resolve the existing preserved stashes before continuing");let openLanes=await countOpenPrWorkflowLanes(directory,sessionID);if(openLanes>0)throw Error(`BLOCKED: ${gate.mode} checkout preparation is refused while ${openLanes} PR workflow lane(s) are in flight`);if(discoveryMode)return prepareDiscoveredCheckout(directory,sessionID,gate);await assertExactDirtyPathSet(directory,paths);let stashMarker=`pr-workflow-checkout-${randomUUID24()}`;if((await _internals197.runGit(directory,["stash","push",`--message=${stashMarker}`,"--",...paths])).exitCode!==0)throw Error("BLOCKED: Git could not preserve the requested checkout-preparation paths; resolve the working tree manually or abort the workflow");let stashOid=await resolveMarkedStashOid(directory,stashMarker,paths),preparation={stashOid,paths,preparedAt:new Date().toISOString(),mode:gate.mode,gateRevision:gate.revision,gateActivatedAt:gate.activatedAt};try{await writeReceipt(directory,sessionID,preparation)}catch(error93){throw Error(`BLOCKED: stash ${stashOid} was created but its durable checkout-preparation receipt could not be recorded (${error93 instanceof Error?error93.message:String(error93)}). Do not continue; ${recoveryInstruction(stashOid)}.`)}return await assertCleanWorkingTree2(directory,stashOid),await appendPreparationEvent(directory,sessionID,preparation),{kind:"prepared",preparation}})}async function prepareDiscoveredCheckout(directory,sessionID,gate){let status=await readPorcelainStatus(directory);if(status.dirtyTrackedPaths.length===0&&status.untrackedPaths.length===0&&!status.renameOrCopy)return{kind:"already_clean"};let swarmUntracked=status.untrackedPaths.filter((candidate2)=>candidate2===".swarm"||candidate2.startsWith(".swarm/"));if(swarmUntracked.length>0)throw Error(`BLOCKED: checkout preparation refuses untracked churn under .swarm/ (${swarmUntracked.slice(0,5).map((entry)=>boundUntrustedPath(entry)).join(", ")}); that directory must stay git-excluded (.git/info/exclude). Resolve the .swarm/ tracking regression before preparing a checkout.`);let includedUntracked=status.untrackedPaths.length>0,stashMarker=`pr-workflow-checkout-${randomUUID24()}`;if((await _internals197.runGit(directory,["stash","push","--include-untracked",`--message=${stashMarker}`],{literalPathspecs:!1})).exitCode!==0)throw Error("BLOCKED: Git could not preserve the discovered working-tree changes; resolve the working tree manually or abort the workflow");let stashOid=await resolveMarkedStashOidByMarker(directory,stashMarker),discoveredPaths=[...status.dirtyTrackedPaths,...status.untrackedPaths].sort(),pathsTruncated=discoveredPaths.length>MAX_RECEIPT_PATHS,receiptPaths=pathsTruncated?discoveredPaths.slice(0,MAX_RECEIPT_PATHS):discoveredPaths,preparation={stashOid,paths:receiptPaths,preparedAt:new Date().toISOString(),mode:gate.mode,gateRevision:gate.revision,gateActivatedAt:gate.activatedAt,discovered:!0,includedUntracked,pathsTruncated};try{await writeReceipt(directory,sessionID,preparation)}catch(error93){throw Error(`BLOCKED: stash ${stashOid} was created but its durable checkout-preparation receipt could not be recorded (${error93 instanceof Error?error93.message:String(error93)}). Do not continue; ${recoveryInstruction(stashOid)}.`)}return await assertCleanWorkingTree2(directory,stashOid,{discovery:!0}),await appendPreparationEvent(directory,sessionID,preparation),{kind:"prepared",preparation}}function normalizeSessionID3(sessionID){let normalized=sessionID.trim();if(!normalized)throw Error("BLOCKED: PR workflow checkout preparation requires a non-empty sessionID");return normalized}function normalizePaths(directory,requestedPaths){if(!Array.isArray(requestedPaths)||requestedPaths.length===0||requestedPaths.length>MAX_CHECKOUT_PATHS)throw Error(`BLOCKED: checkout preparation requires 1-${MAX_CHECKOUT_PATHS} explicit paths`);let root=path278.resolve(directory),normalized=[],seen=new Set;for(let value of requestedPaths){if(typeof value!=="string"||!value)throw Error("BLOCKED: checkout preparation paths must be non-empty strings");if(value.includes("\\")||path278.posix.normalize(value)!==value||path278.posix.isAbsolute(value)||/^[A-Za-z]:/.test(value)||containsControlChars(value))throw Error("BLOCKED: checkout preparation path must be a literal slash-separated repository-relative path");let segments=value.split("/");if(segments.some((segment)=>!segment||segment==="."||segment==="..")||segments[0]===".git"||segments[0]===".swarm")throw Error("BLOCKED: checkout preparation path is not an allowed repository file path");let resolved=path278.resolve(root,...segments),relative67=path278.relative(root,resolved);if(!relative67||relative67.startsWith(`..${path278.sep}`)||path278.isAbsolute(relative67))throw Error("BLOCKED: checkout preparation path escapes the project root");if(seen.has(value))throw Error("BLOCKED: checkout preparation path was supplied more than once");seen.add(value),normalized.push(value)}return normalized}async function countOpenPrWorkflowLanes(directory,sessionID){let filePath=validateSwarmPath(directory,"background-delegations.jsonl"),raw;try{raw=await fsp8.readFile(filePath,"utf-8")}catch(error93){if(error93.code==="ENOENT")return 0;throw Error("BLOCKED: unable to inspect PR workflow lanes; cannot safely prepare checkout")}let latestByCorrelationID=new Map;for(let rawLine of raw.split(`
|
|
6373
6373
|
`)){let line=rawLine.trim();if(!line)continue;let record3;try{record3=JSON.parse(line)}catch{throw Error("BLOCKED: PR workflow lane registry is malformed; cannot safely prepare checkout")}if(typeof record3!=="object"||record3===null||typeof record3.correlationId!=="string"||typeof record3.parentSessionId!=="string"||typeof record3.status!=="string")throw Error("BLOCKED: PR workflow lane registry is invalid; cannot safely prepare checkout");let typed=record3;if(typed.parentSessionId===sessionID&&typeof typed.mode!=="string")throw Error("BLOCKED: active-session lane metadata is invalid; cannot safely prepare checkout");latestByCorrelationID.set(typed.correlationId,typed)}return[...latestByCorrelationID.values()].filter((record3)=>record3.parentSessionId===sessionID&&typeof record3.mode==="string"&&record3.mode.startsWith("swarm-pr-")&&(record3.status==="pending"||record3.status==="running")).length}async function assertExactDirtyPathSet(directory,requestedPaths){let status=await readPorcelainStatus(directory);if(status.untrackedPaths.length>0)throw Error(`BLOCKED: checkout preparation refuses untracked paths (${status.untrackedPaths.slice(0,5).join(", ")}); move or remove them before checkout`);if(status.renameOrCopy)throw Error("BLOCKED: checkout preparation refuses rename or copy changes; resolve them manually before checkout");let dirtySet=new Set(status.dirtyTrackedPaths),requestedSet=new Set(requestedPaths),omitted=[...dirtySet].filter((candidate2)=>!requestedSet.has(candidate2)),notDirty=requestedPaths.filter((candidate2)=>!dirtySet.has(candidate2));if(omitted.length>0||notDirty.length>0)throw Error(`BLOCKED: checkout preparation paths must exactly cover every dirty tracked path (omitted: ${omitted.length?omitted.join(", "):"none"}; not dirty: ${notDirty.length?notDirty.join(", "):"none"})`)}async function assertCleanWorkingTree2(directory,stashOid,options={}){let status;try{status=await readPorcelainStatus(directory)}catch(error93){throw Error(`BLOCKED: stash ${stashOid} was created, but the post-stash working-tree status could not be verified (${error93 instanceof Error?error93.message:String(error93)}). Do not continue; ${recoveryInstruction(stashOid)} and resolve manually.`)}if(status.dirtyTrackedPaths.length>0||status.untrackedPaths.length>0||status.renameOrCopy){if(options.discovery){let remaining=[...status.dirtyTrackedPaths,...status.untrackedPaths].slice(0,5),remainingText=remaining.length>0?remaining.map((entry)=>boundUntrustedPath(entry)).join(", "):"rename/copy changes only";throw Error(`BLOCKED: stash ${stashOid} was created, but the checkout is still not clean (remaining: ${remainingText}). Submodule pointer changes are not preserved by --include-untracked and must be resolved manually. Do not continue; ${recoveryInstruction(stashOid)} and resolve manually.`)}throw Error(`BLOCKED: stash ${stashOid} was created, but the checkout is still not clean. Do not continue; ${recoveryInstruction(stashOid)} and resolve manually.`)}}async function readPorcelainStatus(directory){let result=await _internals197.runGit(directory,["status","--porcelain=v1","-z","--untracked-files=all"],{captureStdout:!0});if(result.exitCode!==0)throw Error("BLOCKED: unable to inspect the full working-tree status safely");let dirtyTrackedPaths=[],untrackedPaths=[],renameOrCopy=!1,records=result.stdout.split("\x00");for(let index=0;index<records.length;index++){let record3=records[index];if(!record3)continue;if(record3.length<4||record3[2]!==" ")throw Error("BLOCKED: working-tree status is malformed; cannot safely prepare checkout");let xy=record3.slice(0,2),filePath=record3.slice(3);if(!filePath)throw Error("BLOCKED: working-tree status contains an empty path; cannot safely prepare checkout");if(xy==="??"){untrackedPaths.push(filePath);continue}if(xy==="!!")continue;if(xy.includes("R")||xy.includes("C"))renameOrCopy=!0,index++;dirtyTrackedPaths.push(filePath)}return{dirtyTrackedPaths,untrackedPaths,renameOrCopy}}async function runGit7(directory,args2,options={}){let literalPathspecs=options.literalPathspecs??!0,proc=bunSpawn(["git",...literalPathspecs?["--literal-pathspecs"]:[],...args2],{cwd:directory,stdin:"ignore",stdout:options.captureStdout?"pipe":"ignore",stderr:"ignore",timeout:GIT_TIMEOUT_MS10});try{let[exitCode,stdout]=await Promise.all([proc.exited,options.captureStdout?proc.stdout.text():Promise.resolve("")]);return{exitCode,stdout}}finally{try{proc.kill()}catch{}}}async function findUniqueMarkedStashOid(directory,stashMarker,notFoundMessage){let list=await _internals197.runGit(directory,["stash","list","--format=%H%x00%gs"],{captureStdout:!0});if(list.exitCode!==0)throw Error("BLOCKED: unable to identify the checkout-preparation stash safely");let matching=list.stdout.split(`
|
|
6374
6374
|
`).map((line)=>line.split("\x00")).filter((parts)=>parts.length===2&&/^[0-9a-f]{40,64}$/i.test(parts[0])&&parts[1].includes(stashMarker));if(matching.length!==1)throw Error(notFoundMessage);return matching[0][0]}async function resolveMarkedStashOid(directory,stashMarker,paths){let stashOid=await findUniqueMarkedStashOid(directory,stashMarker,"BLOCKED: Git did not expose one uniquely identifiable checkout-preparation stash; do not continue to checkout until the requested changes are preserved manually"),changed=await _internals197.runGit(directory,["stash","show","--name-only","--format=","-z",stashOid],{captureStdout:!0}),changedPaths2=changed.stdout.split("\x00").filter(Boolean).sort(),expectedPaths=[...paths].sort();if(changed.exitCode!==0||changedPaths2.length!==expectedPaths.length||changedPaths2.some((value,index)=>value!==expectedPaths[index]))throw Error(`BLOCKED: stash ${stashOid} does not contain exactly the requested checkout-preparation paths; do not continue. ${recoveryInstruction(stashOid)} and resolve manually.`);return stashOid}async function resolveMarkedStashOidByMarker(directory,stashMarker){return findUniqueMarkedStashOid(directory,stashMarker,"BLOCKED: Git did not expose one uniquely identifiable checkout-preparation stash; do not continue to checkout until the discovered changes are preserved manually")}async function countOutstandingReceipts(directory,sessionID){let receiptDirectory=validateSwarmPath(directory,path278.join(RECEIPT_DIR2,prWorkflowSessionFileStem(sessionID)));try{let receiptOids=(await fsp8.readdir(receiptDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&/^[0-9a-f]{40,64}\.json$/i.test(entry.name)).map((entry)=>entry.name.replace(/\.json$/i,"").toLowerCase());if(receiptOids.length===0)return 0;let activeStashOids=await readCurrentStashOids(directory);return receiptOids.filter((oid)=>activeStashOids.has(oid)).length}catch(error93){if(error93.code==="ENOENT")return 0;throw Error("BLOCKED: unable to inspect checkout-preparation receipts safely")}}async function readCurrentStashOids(directory){let list=await _internals197.runGit(directory,["stash","list","--format=%H"],{captureStdout:!0});if(list.exitCode!==0)throw Error("BLOCKED: unable to inspect checkout-preparation stashes safely");return new Set(list.stdout.split(/\r?\n/).map((value)=>value.trim().toLowerCase()).filter((value)=>/^[0-9a-f]{40,64}$/i.test(value)))}async function writeReceipt(directory,sessionID,preparation){let receiptPath=validateSwarmPath(directory,path278.join(RECEIPT_DIR2,prWorkflowSessionFileStem(sessionID),`${preparation.stashOid}.json`));await writePrWorkflowAtomicJson(directory,receiptPath,{schemaVersion:1,sessionID,...preparation})}async function appendPreparationEvent(directory,sessionID,preparation){try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp8.appendFile(eventsPath,`${JSON.stringify({type:"pr_workflow_checkout_prepared",timestamp:preparation.preparedAt,sessionID,mode:preparation.mode,gateRevision:preparation.gateRevision,stashOid:preparation.stashOid,paths:preparation.paths})}
|
|
6375
6375
|
`,"utf-8")}catch{}}var _internals197={runGit:runGit7,classifyGitState:classifyPrWorkflowGitState};function boundUntrustedPath(value){let cleaned="";for(let ch of value){let code=ch.codePointAt(0)??0,strip=code<=31||code>=127&&code<=159||code>=8234&&code<=8238||code>=8294&&code<=8297||ch==="`"||ch==="<"||ch===">";cleaned+=strip?" ":ch}return cleaned=cleaned.replace(/\s+/g," ").trim(),cleaned.length>MAX_ECHOED_PATH_LEN?`${cleaned.slice(0,MAX_ECHOED_PATH_LEN)}…`:cleaned}function recoveryInstruction(stashOid){return`After complete_pr_workflow or abort_pr_workflow clears the gate, restore only these preserved changes with: git stash apply --index ${stashOid}`}var prepare_pr_workflow_checkout=createSwarmTool({description:"Before binding a PR_REVIEW or PR_FEEDBACK checkout, preserve dirty working-tree changes in an auditable Git stash so the unbound checkout cannot lose them. Provide `paths` to preserve an exact set of named dirty tracked files (untracked files are refused in this explicit mode). Omit `paths` for self-discovery mode: it reads the full working-tree status and stashes every dirty tracked AND untracked change (git stash push --include-untracked); an already-clean tree is a no-op that writes no stash and no receipt. Untracked churn under .swarm/ is refused because that directory must stay git-excluded. This architect-only controller uses a fixed safe Git argv, records the stash OID and recovery instructions under .swarm, and refuses after head binding or while workflow lanes are running. It does not allow arbitrary git stash shell commands.",args:{paths:PreparePrWorkflowCheckoutArgsSchema.shape.paths},execute:executePreparePrWorkflowCheckout});init_quality_budget();init_zod();init_loader();init_schema();init_path_security();init_create_tool();import*as path279 from"node:path";var VALID_ACTIONS=["build","importers","dependencies","blast_radius","localization","key_files","ontology","package_boundaries","preflight_packet","callers","dead_exports","context_pack","graph_health"],MAX_FILE_PATH_LENGTH3=500,MAX_SYMBOL_LENGTH2=256,REPO_GRAPH_DISABLED_NOTICE="Repository graph is disabled by configuration (repo_graph.enabled=false).",_internals198={loadPluginConfigWithMeta,probeFreshness,updateGraphForFiles,writeFingerprint};function validateFile(p){if(!p||typeof p!=="string")return"file is required";if(p.length===0)return"file is empty";if(p.length>MAX_FILE_PATH_LENGTH3)return`file exceeds maximum length of ${MAX_FILE_PATH_LENGTH3}`;if(containsControlChars(p))return"file contains control characters";if(containsPathTraversal(p))return"file contains path traversal";if(path279.isAbsolute(p)||/^[a-zA-Z]:[\\/]/.test(p))return"file must be a workspace-relative path, not absolute";return null}function validateSymbol(s){if(s.length===0)return"symbol is empty";if(s.length>MAX_SYMBOL_LENGTH2)return`symbol exceeds maximum length of ${MAX_SYMBOL_LENGTH2}`;if(containsControlChars(s))return"symbol contains control characters";return null}function err(action,message){return JSON.stringify({success:!1,action,error:message},null,2)}function ok(action,payload){return JSON.stringify({success:!0,action,...payload},null,2)}function resolveRepoGraphConfig(directory){try{let{config:config3}=_internals198.loadPluginConfigWithMeta(directory);return RepoGraphConfigSchema.parse(config3.repo_graph??{})}catch{return RepoGraphConfigSchema.parse({})}}function freshnessOptions(config3){return{maxFiles:config3.max_files,walkBudgetMs:config3.walk_budget_ms,excludeDirs:config3.exclude_dirs}}function uniqueDriftPaths(probe2){return[...new Set([...probe2.changed,...probe2.removed])]}function metadataForProbe(probe2,detectedFiles,refreshedFiles,freshnessNote){return{stale:probe2.state==="drifted"||probe2.state==="no-fingerprint",probeState:probe2.state,changedFiles:detectedFiles,refreshedFiles,...freshnessNote?{freshnessNote}:{}}}function toRelativeGraphPath(input,workspaceRoot){let normalized=input.replace(/\\/g,"/");if(path279.isAbsolute(normalized)){let rel=path279.relative(workspaceRoot,normalized).replace(/\\/g,"/");return normalizeGraphPath(rel)}return normalizeGraphPath(normalized)}async function loadOrError(directory,action){try{let graph=await loadGraph(directory);if(!graph)return{ok:!1,response:err(action,'No repo graph found at .swarm/repo-graph.json. Run repo_map with action="build" first.')};return{ok:!0,graph}}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return{ok:!1,response:err(action,`failed to load repo graph: ${message}`)}}}var repo_map=createSwarmTool({description:'Query the repository code graph for structural awareness before editing. Actions: "build" (build/refresh .swarm/repo-graph.json), "importers" (who imports a file), "dependencies" (what a file imports), "blast_radius" (transitive dependents + risk), "localization" (compact context block for a target file), "key_files" (top-N most-imported files), "ontology" (file roles/routes/data/security/findings), "package_boundaries" (inferred package/layer boundaries), "preflight_packet" (bounded ontology packet for planning), "callers" (files that reference an exported symbol, call-site granularity; needs file+symbol), "dead_exports" (advisory: exported symbols with no detected in-repo reference; results are review candidates, not delete directives), '+'"context_pack" (token-budgeted slice of source spans for a target symbol — definition + transitive callers/callees; advisory/conservative; needs file+symbol; uses max_depth for traversal depth, top_n for span cap), '+'"graph_health" (freshness and bounded extraction diagnostics; no file required). Use this before refactoring shared modules to avoid breaking unseen consumers. Note: "callers"/"dead_exports"/"context_pack" use conservative regex analysis (TS/JS/Python) and cannot see dynamic dispatch or namespace/barrel re-export usage; "dead_exports" results are review candidates, not delete directives.',args:{action:exports_external.enum(["build","importers","dependencies","blast_radius","localization","key_files","ontology","package_boundaries","preflight_packet","callers","dead_exports","context_pack","graph_health"]).describe('Query action: "build" | "importers" | "dependencies" | "blast_radius" | "localization" | "key_files" | "ontology" | "package_boundaries" | "preflight_packet" | "callers" | "dead_exports" | "context_pack" | "graph_health"'),file:exports_external.string().optional().describe("Target file (workspace-relative or absolute). Required for importers/dependencies/localization/ontology. Optional for preflight_packet."),files:exports_external.array(exports_external.string()).optional().describe("Multiple target files for blast_radius/preflight_packet. If omitted, falls back to `file`."),symbol:exports_external.string().optional().describe('Exported symbol name. Restricts consumers on action="importers"; required for action="callers"/"context_pack".'),top_n:exports_external.number().int().min(1).max(100).optional().describe('For action="key_files"/"package_boundaries": entries to return (default 10). For action="dead_exports": max candidates (default 100). For action="context_pack": max spans returned (default ~40 via token budget).'),max_depth:exports_external.number().int().min(1).max(10).optional().describe('For action="blast_radius": max BFS depth (default 3). For action="context_pack": traversal depth (default 2).')},async execute(args2,directory,_ctx){let a=args2??{},action=String(a.action??"");if(!VALID_ACTIONS.includes(action))return err(action||"(none)",`unknown action; expected one of: ${VALID_ACTIONS.join(", ")}`);let repoGraphConfig=resolveRepoGraphConfig(directory);if(!repoGraphConfig.enabled)return err(action,REPO_GRAPH_DISABLED_NOTICE);let probeOptions=freshnessOptions(repoGraphConfig);if(action==="build")try{let start=Date.now(),graph2=await buildWorkspaceGraphAsync(directory,probeOptions);await saveGraph(directory,graph2);let fingerprintWritten=await _internals198.writeFingerprint(directory,graph2,probeOptions),elapsedMs=Date.now()-start,fileCount=Object.keys(graph2.nodes).length,edgeCount=graph2.edges.length,ontologyFileCount=Object.values(graph2.nodes).filter((node)=>node.ontology!==void 0).length;return ok(action,{fileCount,edgeCount,ontologyFileCount,buildTimestamp:graph2.metadata.generatedAt,elapsedMs,truncated:graph2.diagnostics?.walkTruncated===!0,fingerprintWritten,path:".swarm/repo-graph.json"})}catch(e){let message=e instanceof Error?e.message:String(e);return err(action,`build failed: ${message}`)}if(action==="graph_health")try{let graph2=await loadGraph(directory),probe3=await _internals198.probeFreshness(directory,probeOptions);return ok(action,{...getGraphHealth(graph2,directory,probe3)})}catch(e){let message=e instanceof Error?e.message:String(e);return err(action,`failed to load repo graph: ${message}`)}let loaded=await loadOrError(directory,action);if(!loaded.ok)return loaded.response;let graph=loaded.graph,probe2=await _internals198.probeFreshness(directory,probeOptions),driftPaths=uniqueDriftPaths(probe2),detectedFiles=driftPaths.length,refreshedFiles=0,freshnessNote;if(probe2.state==="drifted"&&detectedFiles>0)if(driftPaths.some(isGraphWideInputPath))freshnessNote="Graph-wide package manifest drift requires a full repo_map build; the stale graph was served without mutation.";else if(repoGraphConfig.refresh_cap>0&&detectedFiles<=repoGraphConfig.refresh_cap)try{if(graph=await _internals198.updateGraphForFiles(directory,driftPaths,{buildOptions:probeOptions}),refreshedFiles=detectedFiles,probe2=await _internals198.probeFreshness(directory,probeOptions),probe2.state!=="clean")freshnessNote="Incremental refresh completed, but the follow-up probe did not certify a clean graph."}catch(error93){freshnessNote=`Incremental refresh failed; serving the stale graph: ${error93 instanceof Error?error93.message:String(error93)}`}else freshnessNote=repoGraphConfig.refresh_cap===0?"Automatic read-time refresh is disabled by repo_graph.refresh_cap=0; serving the stale graph.":`Detected ${detectedFiles} changed files, above repo_graph.refresh_cap=${repoGraphConfig.refresh_cap}; serving the stale graph.`;else if(probe2.state==="no-fingerprint")freshnessNote='No matching repository-graph fingerprint is available; run repo_map action="build" to certify the graph.';else if(probe2.state==="inconclusive")freshnessNote="Workspace freshness is unknown because the bounded probe did not complete; the existing graph was served without refresh or deletion.";let freshness=metadataForProbe(probe2,detectedFiles,refreshedFiles,freshnessNote);if(action==="key_files"){let topN=a.top_n??10,reverseCounts=getKeyFiles(graph,topN).map((n)=>({file:n.moduleName,language:n.language,exports:n.exports.length,roles:n.ontology?.roles??[],findings:n.ontology?.findings.length??0,inDegree:getImporters(graph,n.moduleName).length}));return ok(action,{count:reverseCounts.length,files:reverseCounts,...freshness})}if(action==="package_boundaries"){let topN=a.top_n??10,boundaries=getPackageBoundaries(graph,topN);return ok(action,{count:boundaries.length,boundaries,...freshness})}if(action==="dead_exports"){let result=getDeadExports(graph,{maxCandidates:a.top_n??100});return ok(action,{...result,...freshness})}if(action==="preflight_packet"){let inputs=a.files&&a.files.length>0?a.files:a.file?[a.file]:[];for(let f of inputs){let v=validateFile(f);if(v)return err(action,`invalid file: ${v}`)}let targets=inputs.map((f)=>toRelativeGraphPath(f,directory));return ok(action,{packet:buildOntologyPreflightPacket(graph,targets,{maxFiles:a.top_n??12,maxBoundaries:10}),...freshness})}if(action==="blast_radius"){let inputs=a.files&&a.files.length>0?a.files:a.file?[a.file]:null;if(!inputs)return err(action,"blast_radius requires `file` or `files`");for(let f of inputs){let v=validateFile(f);if(v)return err(action,`invalid file: ${v}`)}let targets=inputs.map((f)=>toRelativeGraphPath(f,directory)),result=getBlastRadius(graph,targets,a.max_depth??3);return ok(action,{...result,...freshness})}if(!a.file)return err(action,`${action} requires \`file\``);let fileErr=validateFile(a.file);if(fileErr)return err(action,`invalid file: ${fileErr}`);let target=toRelativeGraphPath(a.file,directory);if(action==="importers"){if(a.symbol!==void 0){let sErr=validateSymbol(a.symbol);if(sErr)return err(action,`invalid symbol: ${sErr}`);let consumers=getSymbolConsumers(graph,target,a.symbol);return ok(action,{target,symbol:a.symbol,count:consumers.length,consumers,...freshness})}let importers=getImporters(graph,target);return ok(action,{target,count:importers.length,importers,...freshness})}if(action==="callers"){if(a.symbol===void 0)return err(action,"callers requires `symbol` (the exported name)");let sErr=validateSymbol(a.symbol);if(sErr)return err(action,`invalid symbol: ${sErr}`);let callers=getCallers(graph,target,a.symbol);return ok(action,{target,symbol:a.symbol,count:callers.length,callers,...freshness})}if(action==="context_pack"){if(a.symbol===void 0)return err(action,"context_pack requires `symbol` (the exported name)");let sErr=validateSymbol(a.symbol);if(sErr)return err(action,`invalid symbol: ${sErr}`);let raw=getContextPack(graph,target,a.symbol,{maxDepth:a.max_depth??2,maxTokens:4000}),toRel=(p)=>{if(!path279.isAbsolute(p))return p.replace(/\\/g,"/");try{return path279.relative(directory,p).replace(/\\/g,"/")}catch{return p}},normalizedTarget={...raw.target,file:toRel(raw.target.file)},normalizedSpans=raw.spans.map((s)=>({...s,file:toRel(s.file)})).filter((s)=>s.file.length>0),truncated=raw.truncated||a.top_n!==void 0&&normalizedSpans.length>a.top_n,cappedSpans=a.top_n!==void 0?normalizedSpans.slice(0,a.top_n):normalizedSpans;return ok(action,{target:normalizedTarget,spans:cappedSpans,truncated,estimatedTokens:raw.estimatedTokens,...freshness,schemaSupported:raw.schemaSupported,...raw.note?{note:raw.note}:{}})}if(action==="dependencies"){let deps=getDependencies(graph,target);return ok(action,{target,count:deps.length,dependencies:deps,...freshness})}if(action==="localization"){let ctx=getLocalizationContext(graph,target,{maxDepth:a.max_depth});return ok(action,{...ctx,...freshness})}if(action==="ontology"){let ontology=getFileOntology(graph,target);if(!ontology)return err(action,`No ontology facts found for ${target}. Rebuild the graph if the file was recently added.`);return ok(action,{target,ontology,...freshness})}return err(action,"unhandled action")}});init_zod();init_effective_spec();init_logger();init_create_tool();import*as fs162 from"node:fs";import*as path280 from"node:path";var EVIDENCE_DIR4=".swarm/evidence",OBLIGATION_KEYWORDS2=["MUST","SHOULD","SHALL"],MAX_FILE_SIZE_BYTES8=1048576;function extractRequirements(specContent){let requirements=[],lines=specContent.split(`
|
|
@@ -6398,7 +6398,7 @@ ${page.content}`;if(page.endLine<page.totalLines){let remaining=page.totalLines-
|
|
|
6398
6398
|
${paginatedContent}`;if(endLine<totalLines){let remaining=totalLines-endLine;response+=`
|
|
6399
6399
|
|
|
6400
6400
|
... ${remaining} more line${remaining===1?"":"s"}. Use offset=${endLine} to retrieve more.`}return response}});init_zod();init_workspace_snapshot();init_pr_workflow_gate();init_manager4();init_external_tool_runner();init_create_tool();import{randomInt}from"node:crypto";import*as fs163 from"node:fs";import*as path281 from"node:path";var STAGE_A_CATEGORIES=["build","typecheck","lint","diff-check","reproduction"],OPTIONAL_STAGE_A_CATEGORIES=["build","typecheck","lint"],ALWAYS_REQUIRED_CATEGORIES=["diff-check","reproduction"],MAX_OUTPUT_BYTES9=65536,FAILING_CHECK_TAIL_BYTES=4096,FULL_OUTPUT_MAX_STORED_BYTES=10485760,BLOCKED_EXECUTABLES=new Set(["aws","az","bash","cmd","curl","docker","echo","env","false","ftp","gcloud","gh","git","kubectl","podman","powershell","printf","pwsh","rsync","scp","sh","sleep","ssh","test","true","wget","zsh"]),MUTATING_ARGUMENT=/(?:^|[-_:])(publish|deploy|push|upload|login|logout|release|promote|destroy|delete|remove|prune)(?:$|[-_:])/i,StageACheckSchema=exports_external.object({category:exports_external.enum(STAGE_A_CATEGORIES),command:exports_external.array(exports_external.string().min(1).max(2000)).min(1).max(64).describe("Array-form executable and arguments; no shell string"),targets:exports_external.array(exports_external.string().trim().min(1).max(500)).min(1).max(32).optional().describe("Required for reproduction: exact test path, test name, package, or regression selector present in the command"),feedback_targets:exports_external.array(exports_external.object({feedback_item_id:exports_external.string().trim().min(1).max(120),target:exports_external.string().trim().min(1).max(500),expected_behavior:exports_external.string().trim().min(8).max(1000)}).strict()).min(1).max(128).optional().describe("Required for reproduction: one exact mapping from every immutable feedback item to an executed target and expected post-fix behavior"),working_directory:exports_external.string().trim().min(1).max(500).optional().describe("Repository-relative workspace directory for this concrete validation obligation; defaults to the repository root"),obligation_id:exports_external.string().trim().min(1).max(1000).optional().describe("Exact controller-discovered workspace/category/source obligation id; required when a category has more than one applicable obligation in a workspace"),validator_contract:exports_external.object({path:exports_external.string().trim().min(1).max(500),id:exports_external.string().trim().min(1).max(120)}).strict().optional().describe("Optional exact validator entry from a bounded repository-owned .pr-validation.json contract"),timeout_ms:exports_external.number().int().min(1000).max(600000).optional()}).strict(),RunPrFeedbackStageAArgsSchema=exports_external.object({pr_head_sha:exports_external.string().trim().min(1).max(80),base_ref:exports_external.string().trim().min(1).max(256).optional(),base_sha:exports_external.string().trim().min(6).max(80).optional(),checks:exports_external.array(StageACheckSchema).min(2).max(258)}).strict(),RepositoryValidationContractSchema=exports_external.object({version:exports_external.literal(1),validators:exports_external.array(exports_external.object({id:exports_external.string().trim().min(1).max(120),category:exports_external.enum(OPTIONAL_STAGE_A_CATEGORIES),working_directory:exports_external.string().trim().min(1).max(500).default("."),command:exports_external.array(exports_external.string().min(1).max(2000)).min(1).max(64)}).strict()).min(1).max(256)}).strict().superRefine((value,context)=>{let seen=new Set;for(let[index,validator]of value.validators.entries()){if(seen.has(validator.id))context.addIssue({code:exports_external.ZodIssueCode.custom,path:["validators",index,"id"],message:`duplicate validator id ${validator.id}`});seen.add(validator.id)}});function generateFullOutputId(){return`S${Date.now()}${randomInt(1e5,999999)}`}function summarizeCheckEntry(entry){let{stdout:_stdout,stderr:_stderr,...rest}=entry;return rest}function tailBytes(text,maxBytes){let buf=Buffer.from(text,"utf8");if(buf.length<=maxBytes)return text;return buf.subarray(buf.length-maxBytes).toString("utf8")}async function persistFullOutput(directory,sessionID,checks5){let id=generateFullOutputId(),fullOutput=JSON.stringify(checks5,null,2),summaryText=`Stage A run (session ${sessionID}): full stdout/stderr for ${checks5.length} check(s).`;try{return await _internals199.storeSummary(directory,id,fullOutput,summaryText,FULL_OUTPUT_MAX_STORED_BYTES),{ref:id}}catch(error93){return{error:`Failed to persist full Stage A output: ${error93 instanceof Error?error93.message:String(error93)}`}}}async function buildBoundedChecksPayload(checks5,directory,sessionID){let persisted=checks5.length>0&&directory&&sessionID?await persistFullOutput(directory,sessionID,checks5):void 0;return{checks:checks5.map((entry,index)=>{let summary=summarizeCheckEntry(entry);if(index===checks5.length-1)if(persisted?.error)summary.stdout=typeof entry.stdout==="string"?entry.stdout:"",summary.stderr=typeof entry.stderr==="string"?entry.stderr:"";else summary.stdout_tail=tailBytes(typeof entry.stdout==="string"?entry.stdout:"",FAILING_CHECK_TAIL_BYTES),summary.stderr_tail=tailBytes(typeof entry.stderr==="string"?entry.stderr:"",FAILING_CHECK_TAIL_BYTES);return summary}),fullOutputRef:persisted?.ref,fullOutputStorageError:persisted?.error}}async function failure2(message,checks5=[],directory,sessionID){let bounded=await buildBoundedChecksPayload(checks5,directory,sessionID),payload={success:!1,message,checks:bounded.checks};if(bounded.fullOutputRef)payload.full_output_ref=bounded.fullOutputRef,payload.full_output_retrieval=`Full stdout/stderr for all ${checks5.length} check(s) in this run was persisted. Use retrieve_summary with id "${bounded.fullOutputRef}" to read it.`;if(bounded.fullOutputStorageError)payload.full_output_storage_error=bounded.fullOutputStorageError;return JSON.stringify(payload,null,2)}function isExactDiffCheck(command){let executable=path281.basename(command[0]).toLowerCase();return(executable==="git"||executable==="git.exe")&&command.length===3&&command[1]==="diff"&&command[2]==="--check"}function isPlausibleBuildCommand(executable,args2){let cleanOnlyPositionals=(optionsWithValue)=>{let positionals=[];for(let index=0;index<args2.length;index+=1){let arg=args2[index];if(optionsWithValue.has(arg)){index+=1;continue}if(arg.startsWith("-")||arg.startsWith("/"))continue;positionals.push(arg.toLowerCase())}return positionals.length>0&&positionals.every((arg)=>arg==="clean")};switch(executable){case"make":return!cleanOnlyPositionals(new Set(["-C","--directory","-f","--file","-I","--include-dir"]))&&!args2.some((arg)=>/^(?:-n|--just-print|--dry-run|--recon|-q|--question|-t|--touch|-p|--print-data-base)$/i.test(arg));case"ninja":return!cleanOnlyPositionals(new Set(["-C","-f","-j","-k","-l","-d"]))&&!args2.some((arg)=>/^(?:-n|--dry-run|-t|--tool)$/i.test(arg));case"cmake":if(!args2.includes("--build"))return!1;{let targetIndex=args2.indexOf("--target");if(targetIndex>=0){let declaredTargets=[];for(let index=targetIndex+1;index<args2.length;index+=1){if(args2[index].startsWith("-"))break;declaredTargets.push(args2[index].toLowerCase())}if(declaredTargets.length>0&&declaredTargets.every((target)=>target==="clean"))return!1}}return!0;case"msbuild":{let targetArgs=args2.map((arg)=>arg.match(/^(?:-|\/)(?:t|target):(.+)$/i)?.[1]).filter((value)=>Boolean(value));if(targetArgs.length>0&&targetArgs.flatMap((value)=>value.split(/[;,]/)).every((target)=>target.trim().toLowerCase()==="clean"))return!1;return args2.some((arg)=>/\.(?:sln|slnx|proj|csproj|fsproj|vbproj)$/i.test(arg)||/^(?:-|\/)(?:t|target):/i.test(arg))&&!args2.some((arg)=>/^(?:-|\/)(?:preprocess|pp|version|ver)(?::|$)/i.test(arg))}case"cargo":return args2[0]==="build";case"go":return args2[0]==="build"&&!args2.some((arg)=>/^-n(?:=.*)?$/i.test(arg));case"dotnet":case"swift":case"stack":case"cabal":case"bazel":case"buck":return args2[0]==="build";case"mix":return args2[0]==="compile";case"mvn":case"mvnw":return args2.some((arg)=>/^(?:compile|package|verify|install|pre-integration-test|integration-test|post-integration-test)$/i.test(arg));case"gradle":case"gradlew":return!args2.some((arg)=>/^(?:-m|--dry-run)(?:=.*)?$/i.test(arg))&&args2.some((arg)=>/(?:^|:)(?:build|assemble|classes|jar|war|compile[A-Za-z0-9_-]*)(?:$|:)/i.test(arg));case"ant":return!cleanOnlyPositionals(new Set(["-f","-file","-buildfile","-lib"]))&&(args2.length===0||args2.some((arg)=>!arg.startsWith("-")&&!arg.startsWith("/")));case"swiftc":return args2.some((arg)=>/\.swift$/i.test(arg));case"rustc":return args2.some((arg)=>/\.rs$/i.test(arg));case"xcodebuild":return args2.some((arg)=>arg.toLowerCase()==="build")&&!args2.some((arg)=>/^-(?:list|showBuildSettings|showdestinations|showsdks|version|help)$/i.test(arg));default:if(["python","python3"].includes(executable)&&(args2[0]==="-m"&&args2[1]==="build"||args2[0]==="setup.py"&&args2.includes("build")))return!0;return["vite","webpack","rollup","parcel","esbuild","tsup"].includes(executable)&&args2.some((arg)=>arg.toLowerCase()==="build")}}function categoryMatchesScriptName(category,scriptName){switch(category){case"build":return/(?:^|[:_-])(?:build|compile|package|assemble)(?:$|[:_-])/i.test(scriptName);case"typecheck":return/(?:type[:_-]*check|check[:_-]*types|types?)(?:$|[:_-])/i.test(scriptName);case"lint":return/(?:^|[:_-])(?:lint|format[:_-]*check|check[:_-]*format)(?:$|[:_-])/i.test(scriptName);case"reproduction":return/(?:^|[:_-])(?:test|spec|repro(?:duction)?|regression)(?:$|[:_-])/i.test(scriptName);case"diff-check":return!1}}function isPlausiblePackageManagerCommand(category,executable,args2){if(args2.some((arg)=>/^(?:--(?:cwd|filter|prefix|workspace)(?:=|$)|-[CFw](?:$|=))/.test(arg))||executable==="yarn"&&args2.includes("workspace"))return!1;let optionTakesValue=new Set(["--cwd","--filter","--prefix","--workspace","-C","-F","-w"]),commandTokens=[];for(let index=0;index<args2.length;index+=1){let arg=args2[index];if(optionTakesValue.has(arg)){index+=1;continue}if(arg.startsWith("-"))continue;commandTokens.push({index,value:arg.toLowerCase()})}if(commandTokens.length===0)return!1;let firstArgIndex=commandTokens[0].index,first=commandTokens[0].value;if(executable==="npm"){let runToken=commandTokens.find(({value})=>["run","run-script"].includes(value));if(!runToken)return!1;let script=commandTokens.find(({index})=>index>runToken.index)?.value;return Boolean(script&&categoryMatchesScriptName(category,script))}if(executable==="bun"){if(category==="build"&&first==="build")return!0;if(category==="reproduction"&&first==="test")return!0;if(first!=="run")return!1;let script=args2.slice(firstArgIndex+1).find((arg)=>!arg.startsWith("-"));return Boolean(script&&categoryMatchesScriptName(category,script))}if(executable==="pnpm"||executable==="yarn"){let script;if(executable==="yarn"&&first==="workspace"){let runToken=commandTokens.find(({value},index)=>index>=2&&value==="run");script=runToken?commandTokens.find(({index})=>index>runToken.index)?.value:commandTokens[2]?.value}else{let runToken=commandTokens.find(({value})=>value==="run");script=runToken?commandTokens.find(({index})=>index>runToken.index)?.value:commandTokens[0]?.value}return Boolean(script&&categoryMatchesScriptName(category,script))}if(executable==="npx"){let invokedArgs=args2.slice(firstArgIndex),invokedExecutable=path281.basename(invokedArgs[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,""),invokedToolArgs=invokedArgs.slice(1);switch(category){case"build":return["vite","webpack","rollup","parcel","esbuild"].includes(invokedExecutable)&&invokedToolArgs.some((arg)=>arg.toLowerCase()==="build");case"typecheck":return isPlausibleTypecheckCommand(invokedExecutable,invokedToolArgs,invokedExecutable);case"lint":return isPlausibleLintCommand(invokedExecutable,invokedToolArgs,invokedExecutable);case"reproduction":return isPlausibleReproductionCommand(invokedExecutable,invokedToolArgs,invokedExecutable,invokedArgs[0]);case"diff-check":return!1}}return!1}function isPlausibleLintCommand(executable,args2,_directCommandName){let hasTarget=(from=0)=>args2.slice(from).some((arg)=>!arg.startsWith("-")&&!arg.startsWith("/"));switch(executable){case"eslint":case"shellcheck":case"pylint":case"flake8":case"stylelint":case"hadolint":case"ktlint":case"checkstyle":case"cppcheck":return hasTarget();case"biome":return["check","lint"].includes(args2[0]?.toLowerCase())&&hasTarget(1);case"ruff":return args2[0]?.toLowerCase()==="check"&&hasTarget(1);case"golangci-lint":return args2[0]?.toLowerCase()==="run";case"swiftlint":return args2.length===0||args2[0]?.toLowerCase()==="lint";case"rubocop":return!args2.some((arg)=>/^--show-cops(?:=.*)?$/i.test(arg));case"cargo":return args2[0]==="clippy";case"dotnet":return args2[0]==="format"&&args2.includes("--verify-no-changes");default:return!1}}function outputReportsZeroTests(result){if(result.stdoutTruncated||result.stderrTruncated)return!0;let output=`${result.stdout}
|
|
6401
|
-
${result.stderr}`;return/(?:\b(?:ran|running|collected)\s+0\s+(?:tests?|items?)\b|\btests? run:\s*0\b|\b0\s+(?:tests?\s+(?:ran|passed)|pass(?:ed)?|passing|examples?)\b|\bno tests? (?:ran|to run|found|were found|executed|is available)\b|\bno test is available\b|\btests? (?:are|were) skipped\b|\btest\b[^\n]*\bskipped\b|\bNO-SOURCE\b|\[no test files\])/i.test(output)}function reproductionSelectorValues(command){let runnerVerbs=new Set(["run","run-script","test","tests","spec","check"]),selectorFlags=new Set(["--test-name-pattern","--testNamePattern","--tests","--filter","--grep","-k","-m","-run"]),selectors=new Set;for(let index=1;index<command.length;index+=1){let arg=command[index];if(selectorFlags.has(arg)){let value=command[index+1];if(value&&!value.startsWith("-"))selectors.add(value);index+=1;continue}let assignment=arg.match(/^(?:--(?:test-name-pattern|testNamePattern|tests|filter|grep)|-run|-Dtest)=(.+)$/);if(assignment?.[1]){selectors.add(assignment[1]);continue}if(arg.startsWith("-")||arg.startsWith("/"))continue;if(runnerVerbs.has(arg.toLowerCase()))continue;selectors.add(arg)}return selectors}function isPlausibleTypecheckCommand(executable,args2,_directCommandName){if(executable==="go")return args2[0]==="vet"&&!args2.some((arg)=>/^-n(?:=.*)?$/i.test(arg));if(executable==="flow")return["check","status","focus-check"].includes(args2[0]?.toLowerCase());if(executable==="phpstan")return["analyse","analyze"].includes(args2[0]?.toLowerCase())&&!args2.some((arg)=>/^--generate-baseline(?:=.*)?$/i.test(arg));return/^(?:tsc|pyright|mypy|sorbet|psalm)$/.test(executable)||executable==="cargo"&&args2[0]==="check"||executable==="dotnet"&&args2[0]==="build"}function isPlausibleReproductionCommand(executable,args2,_directCommandName,_commandPath){if(executable==="python"||executable==="python3")return args2[0]==="-m"&&args2[1]?.toLowerCase()==="pytest";if(executable==="bundle")return args2[0]==="exec"&&args2[1]?.toLowerCase()==="rspec";if(executable==="cargo")return args2[0]==="test"||args2[0]==="nextest"&&args2[1]?.toLowerCase()==="run";if(executable==="go")return args2[0]==="test"&&!args2.some((arg)=>/^(?:-c|-list(?:=.*)?)$/i.test(arg));if(executable==="node")return args2[0]==="--test";if(executable==="deno")return args2[0]==="test";if(executable==="zig")return args2[0]==="test";if(executable==="meson")return args2[0]==="test";if(executable==="make"||executable==="ninja")return args2.some((arg)=>/^(?:test|check|verify|regression)$/i.test(arg));if(executable==="playwright")return args2[0]==="test";if(executable==="dart"||executable==="flutter")return args2[0]==="test";if(executable==="xcodebuild")return args2.some((arg)=>["test","test-without-building"].includes(arg.toLowerCase()))&&!args2.some((arg)=>/^-(?:list|enumerate-tests|showBuildSettings|showdestinations|showTestPlans|showsdks|version|help)$/i.test(arg));if(executable==="cypress")return args2[0]==="run";if(/^(?:pytest|ctest|rspec|phpunit|vitest|jest|mocha|ava|go-test-sum)$/.test(executable))return!0;if(executable==="dotnet")return args2[0]?.toLowerCase()==="test";if(["mvn","mvnw"].includes(executable))return args2.some((arg)=>/^(?:test|verify|integration-test|failsafe:integration-test)$/i.test(arg));if(["gradle","gradlew"].includes(executable)){let invokesExecutableTestTask=args2.some((arg)=>{if(arg.startsWith("-"))return!1;let task2=arg.split(":").filter(Boolean).at(-1)??"";if(/^(?:compile|process|generate|assemble|classes|jar|source|kapt|prepare)/i.test(task2))return!1;return task2.toLowerCase()==="test"||/^test[A-Z0-9_-]/.test(task2)&&/Test$/.test(task2)||/^[a-z][A-Za-z0-9_-]*Test$/.test(task2)});return!args2.some((arg)=>/^(?:-m|--dry-run)(?:=.*)?$/i.test(arg))&&invokesExecutableTestTask}return!1}function isPlausibleStageACommand(category,command){if(category==="diff-check")return isExactDiffCheck(command);let executable=path281.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"");if(BLOCKED_EXECUTABLES.has(executable))return!1;if(command.slice(1).some((arg)=>/^(?:-h|--help|--version|version|help|list|-N|--fixtures(?:-per-test)?|--markers|--trace-config|--cache-show|--list(?:-?(?:tests?|suites|groups))?(?:-xml)?(?:=.*)?|--show-only(?:=.*)?|--print-labels|--listFilesOnly|--noCheck|--no-check|--no-run(?:=.*)?|--test-dry-run(?:=.*)?|--createStub|--createstub|--print-config|--env-info|--show-settings|--show-files|--list-msgs|--generate-rcfile|--show-?config(?:=.*)?|--init|--dry-run(?:=.*)?|--collect-only|--setup-(?:only|plan)|--co|--if-present(?:=.*)?)$/i.test(arg)))return!1;if(command.slice(1).some((arg)=>MUTATING_ARGUMENT.test(arg))||["bun","node","python","python3","ruby","perl","npx"].includes(executable)&&command.slice(1).some((arg)=>["-e","--eval","-c","--call"].includes(arg)))return!1;if(category==="lint"&&command.some((arg)=>/^(?:--fix(?:-only)?|--write|--apply|--auto-?correct)(?:=.*)?$|^-[aAw]$/.test(arg)))return!1;if(category==="reproduction"&&(command.some((arg)=>/^(?:--passWithNoTests|--allow-no-tests|--collect-only|--list|--dry-run|--only|--todo|--update-snapshot|--bless|--accept|-w|-x(?:.+)?|--exclude-task(?:=.+)?)$/i.test(arg))||command.some((arg)=>/^-D(?:skipTests|skipITs|maven\.test\.(?:skip|skip\.exec))(?:=true)?$/i.test(arg))))return!1;if(["npm","pnpm","yarn"].includes(executable)||executable==="bun"&&["build","run","test"].includes(command[1]))return isPlausiblePackageManagerCommand(category,executable,command.slice(1));if(executable==="npx")return isPlausiblePackageManagerCommand(category,executable,command.slice(1));let directCommandName=executable.replace(/\.(?:sh|ps1|py|js|mjs|cjs|rb|pl)$/,"");switch(category){case"build":return isPlausibleBuildCommand(executable,command.slice(1));case"typecheck":return isPlausibleTypecheckCommand(executable,command.slice(1),directCommandName);case"lint":return isPlausibleLintCommand(executable,command.slice(1),directCommandName);case"reproduction":return isPlausibleReproductionCommand(executable,command.slice(1),directCommandName,command[0])}}function readBoundedText(filePath){try{let stat18=fs163.statSync(filePath);if(!stat18.isFile()||stat18.size>524288)return;return fs163.readFileSync(filePath,"utf8")}catch{return}}function readPresentRepositoryText(directory,filePath,label){let stat18;try{stat18=fs163.statSync(filePath)}catch(error93){if(error93.code==="ENOENT")return;throw Error(`BLOCKED: Stage A cannot inspect present ${label}`)}if(!stat18.isFile()||stat18.size>524288)throw Error(`BLOCKED: Stage A cannot inspect present ${label}`);try{let canonicalRoot=fs163.realpathSync(path281.resolve(directory)),canonicalFile=fs163.realpathSync(filePath),relative69=path281.relative(canonicalRoot,canonicalFile);if(relative69===".."||relative69.startsWith(`..${path281.sep}`)||path281.isAbsolute(relative69))throw Error("escaping manifest");return fs163.readFileSync(canonicalFile,"utf8")}catch{throw Error(`BLOCKED: Stage A cannot inspect present ${label}`)}}function resolveContainedDirectory(directory,workingDirectory="."){let root=path281.resolve(directory),canonicalRoot=(()=>{try{return fs163.realpathSync(root)}catch{return root}})(),candidate2=path281.resolve(root,workingDirectory);try{if(!fs163.statSync(candidate2).isDirectory())return;let absolute=fs163.realpathSync(candidate2),relativePath2=path281.relative(canonicalRoot,absolute);if(relativePath2===".."||relativePath2.startsWith(`..${path281.sep}`)||path281.isAbsolute(relativePath2))return;return{absolute,relative:relativePath2.replaceAll("\\","/")||"."}}catch{return}}function readRepositoryValidationContract(directory,contractPath){let root=path281.resolve(directory),canonicalRoot=(()=>{try{return fs163.realpathSync(root)}catch{return root}})(),resolved=path281.resolve(root,contractPath),canonicalContract;try{canonicalContract=fs163.realpathSync(resolved)}catch{return}let relative69=path281.relative(canonicalRoot,canonicalContract);if(!relative69||relative69===".."||relative69.startsWith(`..${path281.sep}`)||path281.isAbsolute(relative69)||path281.basename(canonicalContract)!==".pr-validation.json")return;let text=readBoundedText(canonicalContract);if(!text)return;try{return RepositoryValidationContractSchema.parse(JSON.parse(text))}catch{return}}async function resolveContractBaseProvenance(directory,prHeadSha,baseRef,baseSha){if(!baseRef&&!baseSha)return;if(!baseRef||!baseSha)throw Error("BLOCKED: Stage A contract authorization requires both base_ref and base_sha");let resolvedBase=await _internals199.resolveExactMergeBaseAsync(directory,baseRef,prHeadSha);if(!resolvedBase||resolvedBase.toLowerCase()!==baseSha.toLowerCase()||resolvedBase.toLowerCase()===prHeadSha.toLowerCase())throw Error("Stage A contract authorization requires base_sha to be the immutable merge base of base_ref and pr_head_sha");return{baseRef,baseSha:resolvedBase.toLowerCase()}}function readTrustedRepositoryValidationContract(directory,contractPath,provenance){if(!provenance)return;let current=readRepositoryValidationContract(directory,contractPath),currentText=readBoundedText(path281.resolve(directory,contractPath)),baseText=_internals199.readGitTextAtRevision(directory,provenance.baseSha,contractPath.replaceAll("\\","/").replace(/^\.\//,""));if(!current||!currentText||baseText===null||currentText!==baseText)return;return current}function isExactRepositoryContractValidator(directory,check3,provenance){if(!check3.validator_contract)return!1;let validator=readTrustedRepositoryValidationContract(directory,check3.validator_contract.path,provenance)?.validators.find((candidate2)=>candidate2.id===check3.validator_contract?.id);if(!validator||validator.category!==check3.category)return!1;let requestedDirectory=resolveContainedDirectory(directory,check3.working_directory??"."),declaredDirectory=resolveContainedDirectory(directory,validator.working_directory);return Boolean(requestedDirectory&&declaredDirectory)&&requestedDirectory?.absolute===declaredDirectory?.absolute&&validator.command.length===check3.command.length&&validator.command.every((part,index)=>part===check3.command[index])}function isExactObligationContractAuthorization(directory,obligation,check3,provenance){let identity=obligation.validatorContract;if(!identity||check3.validator_contract?.path!==identity.path||check3.validator_contract.id!==identity.id)return!1;let validator=readTrustedRepositoryValidationContract(directory,identity.path,provenance)?.validators.find(({id})=>id===identity.id),workspace=resolveContainedDirectory(directory,obligation.workingDirectory),validatorWorkspace=validator?resolveContainedDirectory(directory,validator.working_directory):void 0;if(!validator||validator.category!==obligation.category||validatorWorkspace?.absolute!==workspace?.absolute)return!1;if(!obligation.source.startsWith("package.json#")||!workspace)return!1;let scriptName=obligation.source.slice(13),packageText=readBoundedText(path281.join(workspace.absolute,"package.json"));if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared&&declared.length===validator.command.length&&declared.every((part,index)=>part===validator.command[index])&&(packageManagerSelectsExactScript(check3.command,scriptName)||declared.length===check3.command.length&&declared.every((part,index)=>part===check3.command[index])))}catch{return!1}}function isSafeContractCommand(command){let executable=path281.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"");return!BLOCKED_EXECUTABLES.has(executable)&&!command.slice(1).some((arg)=>MUTATING_ARGUMENT.test(arg))&&!command.some((arg)=>/^(?:-h|--help|--version|help|version|--dry-run|--if-present)$/i.test(arg))&&!(["bun","node","python","python3","ruby","perl","npx"].includes(executable)&&command.slice(1).some((arg)=>["-e","--eval","-c","--call"].includes(arg)))}function isAllowedRepositoryExecutable(directory,workingDirectory,executable,contractValidated){if(!/[\\/]/.test(executable))return!0;if(path281.isAbsolute(executable))return!1;let workspace=resolveContainedDirectory(directory,workingDirectory);if(!workspace)return!1;let resolved=path281.resolve(workspace.absolute,executable),canonicalExecutable;try{canonicalExecutable=fs163.realpathSync(resolved)}catch{return!1}let canonicalRoot=(()=>{try{return fs163.realpathSync(path281.resolve(directory))}catch{return path281.resolve(directory)}})(),relative69=path281.relative(canonicalRoot,canonicalExecutable);if(relative69===".."||relative69.startsWith(`..${path281.sep}`)||path281.isAbsolute(relative69))return!1;let basename34=path281.basename(canonicalExecutable).toLowerCase().replace(/\.(?:cmd|bat|exe)$/,"");if(!contractValidated&&!["gradlew","mvnw"].includes(basename34))return!1;return fs163.statSync(canonicalExecutable).isFile()}function normalizedExecutable(command){return path281.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"")}function parseSimpleRepositoryScript(script){if(/[;&|><`\r\n]/.test(script)||script.includes("$(")||script.includes("${"))return;let tokens=script.match(/"(?:\\.|[^"\\])*"|'[^']*'|[^\s]+/g)?.map((token)=>{if(token.startsWith('"')&&token.endsWith('"')||token.startsWith("'")&&token.endsWith("'"))return token.slice(1,-1);return token})??[];return tokens.length>0?tokens:void 0}function packageManagerSelectedScriptName(command){let executable=normalizedExecutable(command);if(!["npm","bun","pnpm","yarn"].includes(executable))return;let positional=command.slice(1,command.indexOf("--")>=0?command.indexOf("--"):void 0).filter((arg)=>!arg.startsWith("-"));if(executable==="npm")return["run","run-script"].includes(positional[0]??"")?positional[1]:void 0;if(executable==="bun")return positional[0]==="run"?positional[1]:void 0;return positional[0]==="run"?positional[1]:positional[0]}function packageManagerSelectsExactScript(command,scriptName){return packageManagerSelectedScriptName(command)===scriptName}function isExactRepositoryPackageManagerScript(directory,workingDirectory,category,command){let scriptName=packageManagerSelectedScriptName(command),workspace=resolveContainedDirectory(directory,workingDirectory);if(!scriptName||!workspace||!categoryMatchesScriptName(category,scriptName))return!1;let packageText=readBoundedText(path281.join(workspace.absolute,"package.json"));if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared&&isPlausibleStageACommand(category,declared))}catch{return!1}}function commandMatchesObligationSource(directory,obligation,check3,contractValidated){let executable=normalizedExecutable(check3.command),effectiveExecutable=executable==="npx"&&check3.command[1]?path281.basename(check3.command[1]).toLowerCase():executable,source=obligation.source;if(source.includes(".pr-validation.json#")){let separator=source.lastIndexOf("#"),contractPath=source.slice(0,separator),validatorId=source.slice(separator+1);return contractValidated&&check3.validator_contract?.id===validatorId&&check3.validator_contract?.path.replaceAll("\\","/").replace(/^\.\//,"")===contractPath.replace(/^\.\//,"")}if(source.startsWith("package.json#")){let scriptName=source.slice(13),workspace=resolveContainedDirectory(directory,obligation.workingDirectory),packageText=workspace?readBoundedText(path281.join(workspace.absolute,"package.json")):void 0;if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared)&&declared?.length===check3.command.length&&declared.every((part,index)=>part===check3.command[index])||packageManagerSelectsExactScript(check3.command,scriptName)}catch{return!1}}if(source==="Cargo.toml")return effectiveExecutable==="cargo";if(source==="go.mod")return effectiveExecutable==="go";if(source==="pom.xml")return["mvn","mvnw"].includes(effectiveExecutable);if(/^build\.gradle(?:\.kts)?$/.test(source))return["gradle","gradlew"].includes(effectiveExecutable);if(/^(?:Makefile|makefile)$/.test(source))return effectiveExecutable==="make";if(source==="CMakeLists.txt")return effectiveExecutable==="cmake";if(source==="Package.swift")return["swift","swiftc"].includes(effectiveExecutable);if(source==="setup.py"||source==="pyproject.toml#build-system")return["python","python3"].includes(effectiveExecutable);if(/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(source))return["dotnet","msbuild"].includes(effectiveExecutable);if(/\.(?:xcodeproj|xcworkspace)$/i.test(source))return effectiveExecutable==="xcodebuild";let sourceExecutables={"tsconfig.json":["tsc"],"pyrightconfig.json":["pyright"],".flowconfig":["flow"],"phpstan.neon":["phpstan"],"phpstan.neon.dist":["phpstan"],"psalm.xml":["psalm"],"psalm.xml.dist":["psalm"],"mypy.ini":["mypy"],"pyproject.toml#mypy":["mypy"],"biome.json":["biome"],"biome.jsonc":["biome"],"ruff.toml":["ruff"],".ruff.toml":["ruff"],"pyproject.toml#ruff":["ruff"],".rubocop.yml":["rubocop"],".swiftlint.yml":["swiftlint"],".golangci.yml":["golangci-lint"],".golangci.yaml":["golangci-lint"],".stylelintrc":["stylelint"],".stylelintrc.json":["stylelint"]};if(/^(?:\.eslintrc|eslint\.config\.)/.test(source))return effectiveExecutable==="eslint";return sourceExecutables[source]?.includes(effectiveExecutable)??!1}function discoverApplicableStageAObligations(directory,contractBase){let root=path281.resolve(directory),canonicalRoot=(()=>{try{return fs163.realpathSync(root)}catch{return root}})(),candidateRoots=[],seenRoots=new Set,discoveryOverflow,addCandidateRoot=(candidate2)=>{if(candidateRoots.length>=256){discoveryOverflow="Stage A repository discovery exceeded 256 contained workspace roots";return}try{if(!fs163.statSync(candidate2).isDirectory())return;let canonicalCandidate=fs163.realpathSync(candidate2),relative69=path281.relative(canonicalRoot,canonicalCandidate);if(relative69.startsWith(`..${path281.sep}`)||relative69===".."||path281.isAbsolute(relative69)||seenRoots.has(canonicalCandidate))return;seenRoots.add(canonicalCandidate),candidateRoots.push(canonicalCandidate)}catch{}},addWorkspacePattern=(pattern)=>{let normalized=pattern.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!normalized||normalized.startsWith("!")||path281.posix.isAbsolute(normalized)||normalized.split("/").includes("..")){discoveryOverflow=`Stage A cannot safely expand declared workspace pattern "${pattern}"`;return}if(!normalized.includes("*")){addCandidateRoot(path281.resolve(root,normalized));return}let wildcard=normalized.match(/^([^*?[\]]+)\/\*\/?$/);if(!wildcard){discoveryOverflow=`Stage A cannot safely expand declared workspace pattern "${pattern}"`;return}let container=path281.resolve(root,wildcard[1]);try{let entries=fs163.readdirSync(container,{withFileTypes:!0});if(entries.length>256){discoveryOverflow=`Stage A workspace container ${wildcard[1]} exceeds the 256-entry bounded discovery limit`;return}for(let entry of entries)if(entry.isDirectory())addCandidateRoot(path281.join(container,entry.name))}catch{}};addCandidateRoot(root);for(let containerName of["packages","apps","services","libs","crates"])addWorkspacePattern(`${containerName}/*`);let rootPackageText=readPresentRepositoryText(canonicalRoot,path281.join(root,"package.json"),"root package.json workspace declaration");if(rootPackageText)try{let value=JSON.parse(rootPackageText),workspacePatterns=Array.isArray(value.workspaces)?value.workspaces:value.workspaces?.packages;for(let pattern of workspacePatterns??[])if(typeof pattern==="string")addWorkspacePattern(pattern)}catch{discoveryOverflow="Stage A cannot safely inspect malformed root package.json workspace metadata"}let pnpmWorkspaceText=readPresentRepositoryText(canonicalRoot,path281.join(root,"pnpm-workspace.yaml"),"pnpm-workspace.yaml declaration");for(let match of pnpmWorkspaceText?.matchAll(/^\s*-\s*['"]?([^'"#\r\n]+?)['"]?\s*$/gm)??[])addWorkspacePattern(match[1]);let cargoMembers=readPresentRepositoryText(canonicalRoot,path281.join(root,"Cargo.toml"),"Cargo.toml workspace declaration")?.match(/\bmembers\s*=\s*\[([\s\S]*?)\]/m)?.[1];for(let match of cargoMembers?.matchAll(/['"]([^'"]+)['"]/g)??[])addWorkspacePattern(match[1]);let mavenText=readPresentRepositoryText(canonicalRoot,path281.join(root,"pom.xml"),"pom.xml module declaration");for(let match of mavenText?.matchAll(/<module>\s*([^<]+?)\s*<\/module>/gi)??[])addWorkspacePattern(match[1]);let goWorkText=readPresentRepositoryText(canonicalRoot,path281.join(root,"go.work"),"go.work workspace declaration");for(let match of goWorkText?.matchAll(/^\s*(?:use\s+)?(\.\.?\/[^\s/]+(?:\/[^\s]+)*)\s*$/gm)??[])addWorkspacePattern(match[1]);for(let settingsName of["settings.gradle","settings.gradle.kts"]){let settingsText=readPresentRepositoryText(canonicalRoot,path281.join(root,settingsName),`${settingsName} workspace declaration`);for(let includeMatch of settingsText?.matchAll(/\binclude\s*\(?([^\r\n)]+)/g)??[])for(let projectMatch of includeMatch[1].matchAll(/['"]:?(.*?)['"]/g)){let projectPath=projectMatch[1].replaceAll(":","/");if(projectPath)addWorkspacePattern(projectPath)}}let obligations=new Map,addObligation=(category,candidateRoot,source,validatorContract)=>{let workspace=path281.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||".",id=`${category}:${workspace}:${source}`;if(!obligations.has(id)&&obligations.size>=256){discoveryOverflow="Stage A repository discovery exceeded 256 concrete validation obligations";return}obligations.set(id,{id,category,workingDirectory:workspace,source,...validatorContract?{validatorContract}:{}})},buildFiles=new Set(["Cargo.toml","go.mod","pom.xml","build.gradle","build.gradle.kts","Makefile","makefile","CMakeLists.txt","Package.swift","setup.py"]),typecheckFiles=new Set(["tsconfig.json","pyrightconfig.json",".flowconfig","phpstan.neon","phpstan.neon.dist","psalm.xml","psalm.xml.dist","mypy.ini"]),lintFiles=new Set(["biome.json","biome.jsonc",".eslintrc",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml",".eslintrc.js",".eslintrc.cjs",".eslintrc.mjs","eslint.config.js","eslint.config.mjs","eslint.config.cjs","eslint.config.ts","ruff.toml",".ruff.toml",".rubocop.yml",".swiftlint.yml",".golangci.yml",".golangci.yaml",".stylelintrc",".stylelintrc.json"]);for(let candidateRoot of candidateRoots){let entries=[];try{if(entries=fs163.readdirSync(candidateRoot,{withFileTypes:!0}),entries.length>2048){discoveryOverflow=`Stage A workspace ${path281.relative(canonicalRoot,candidateRoot)||"."} exceeds the 2048-entry bounded manifest scan`;continue}}catch{continue}for(let entry of entries){if(entry.isFile()&&buildFiles.has(entry.name))addObligation("build",candidateRoot,entry.name);if(entry.isFile()&&typecheckFiles.has(entry.name))addObligation("typecheck",candidateRoot,entry.name);if(entry.isFile()&&lintFiles.has(entry.name))addObligation("lint",candidateRoot,entry.name);if(entry.isFile()&&/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(entry.name))addObligation("build",candidateRoot,entry.name);if(entry.isDirectory()&&/\.(?:xcodeproj|xcworkspace)$/i.test(entry.name))addObligation("build",candidateRoot,entry.name)}let contractPath=path281.join(candidateRoot,".pr-validation.json"),contractRelative=path281.relative(canonicalRoot,contractPath).replaceAll("\\","/"),untrustedContract=readRepositoryValidationContract(canonicalRoot,contractRelative),contract=readTrustedRepositoryValidationContract(canonicalRoot,contractRelative,contractBase);if(fs163.existsSync(contractPath)&&!untrustedContract)discoveryOverflow=`Stage A found an invalid, oversized, unreadable, or escaping validation contract at ${contractRelative}`;else if(untrustedContract&&!contract)discoveryOverflow=`Stage A validation contract at ${contractRelative} must be unchanged from the immutable merge base named by base_ref and base_sha`;let contractValidatorsCoveredByScripts=new Set,packageText=readPresentRepositoryText(canonicalRoot,path281.join(candidateRoot,"package.json"),`${path281.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json manifest`);if(packageText)try{let value=JSON.parse(packageText);for(let[script,commandText]of Object.entries(value.scripts??{})){let declaredCommand=typeof commandText==="string"?parseSimpleRepositoryScript(commandText):void 0;for(let category of OPTIONAL_STAGE_A_CATEGORIES){if(!categoryMatchesScriptName(category,script))continue;let authorizingValidator=contract?.validators.find((validator)=>{let validatorWorkspace=resolveContainedDirectory(canonicalRoot,validator.working_directory);return validator.category===category&&validatorWorkspace?.absolute===candidateRoot&&(!declaredCommand||declaredCommand.length===validator.command.length&&declaredCommand.every((part,index)=>part===validator.command[index]))});if(!declaredCommand){if(!authorizingValidator)discoveryOverflow=`Stage A opaque package script ${path281.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json#${script} requires a trusted base-identical contract validator for ${category}`;continue}if(isPlausibleStageACommand(category,declaredCommand)||Boolean(authorizingValidator)){if(addObligation(category,candidateRoot,`package.json#${script}`,authorizingValidator?{path:contractRelative,id:authorizingValidator.id}:void 0),authorizingValidator)contractValidatorsCoveredByScripts.add(authorizingValidator.id)}}}}catch{discoveryOverflow=`Stage A cannot safely inspect malformed package manifest at ${path281.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json`}let pyprojectText=readPresentRepositoryText(canonicalRoot,path281.join(candidateRoot,"pyproject.toml"),`${path281.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/pyproject.toml manifest`);if(pyprojectText?.match(/\[build-system\]/i))addObligation("build",candidateRoot,"pyproject.toml#build-system");if(pyprojectText?.match(/\[(?:tool\.)?mypy\]/i))addObligation("typecheck",candidateRoot,"pyproject.toml#mypy");if(pyprojectText?.match(/\[tool\.ruff(?:\.|\])/i))addObligation("lint",candidateRoot,"pyproject.toml#ruff");for(let validator of contract?.validators??[]){if(contractValidatorsCoveredByScripts.has(validator.id))continue;if(OPTIONAL_STAGE_A_CATEGORIES.includes(validator.category)){let validatorWorkspace=resolveContainedDirectory(canonicalRoot,validator.working_directory);if(!validatorWorkspace)continue;addObligation(validator.category,validatorWorkspace.absolute,`${contractRelative}#${validator.id}`)}}}if(discoveryOverflow)throw Error(`BLOCKED: ${discoveryOverflow}`);return[...obligations.values()]}function discoverApplicableStageACategories(directory,contractBase){let applicable=new Set(discoverApplicableStageAObligations(directory,contractBase).map(({category})=>category));return OPTIONAL_STAGE_A_CATEGORIES.filter((category)=>applicable.has(category))}async function executeRunPrFeedbackStageA(args2,directory,context={}){let parsed=RunPrFeedbackStageAArgsSchema.safeParse(args2);if(!parsed.success)return failure2(`Invalid PR-feedback Stage A request: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);if(!context.sessionID?.trim())return failure2("PR-feedback Stage A requires an active sessionID");let categories=parsed.data.checks.map((check3)=>check3.category);for(let requiredSingleton of ALWAYS_REQUIRED_CATEGORIES)if(categories.filter((category)=>category===requiredSingleton).length!==1)return failure2(`Stage A requires exactly one ${requiredSingleton} receipt`);let contractBase;try{contractBase=await resolveContractBaseProvenance(directory,parsed.data.pr_head_sha,parsed.data.base_ref,parsed.data.base_sha)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}let applicableObligations;try{applicableObligations=_internals199.discoverApplicableStageAObligations(directory,contractBase)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}let applicableCategories=OPTIONAL_STAGE_A_CATEGORIES.filter((category)=>applicableObligations.some((obligation)=>obligation.category===category)),matchedObligationIds=new Set,selectedObligations=new Map,normalizedCheckDirectories=new Map;for(let check3 of parsed.data.checks){let workspace=resolveContainedDirectory(directory,check3.working_directory??".");if(!workspace)return failure2(`Stage A ${check3.category} working_directory is not a contained repository workspace`);if(normalizedCheckDirectories.set(check3,workspace.relative),!OPTIONAL_STAGE_A_CATEGORIES.includes(check3.category))continue;let candidates=applicableObligations.filter((obligation)=>obligation.category===check3.category&&obligation.workingDirectory===workspace.relative);if(candidates.length===0&&!check3.obligation_id)continue;let selected=check3.obligation_id?candidates.find((candidate2)=>candidate2.id===check3.obligation_id):candidates.length===1?candidates[0]:void 0;if(!selected)return failure2(`Stage A ${check3.category} must name one exact discovered obligation_id for workspace ${workspace.relative}: ${candidates.map(({id})=>id).join(", ")||"none discovered"}`);if(matchedObligationIds.has(selected.id))return failure2(`Stage A repeats discovered obligation ${selected.id}`);matchedObligationIds.add(selected.id),selectedObligations.set(check3,selected),check3.obligation_id=selected.id,check3.working_directory=workspace.relative}let missingObligations=applicableObligations.filter(({id})=>!matchedObligationIds.has(id));if(missingObligations.length>0)return failure2(`Stage A is missing concrete repository validation obligations: ${missingObligations.map(({id})=>id).join(", ")}`);let diffCheck=parsed.data.checks.find((check3)=>check3.category==="diff-check");if(!diffCheck||!isExactDiffCheck(diffCheck.command))return failure2('Stage A diff-check must execute array-form ["git", "diff", "--check"]');for(let check3 of parsed.data.checks){let directContractValidated=isExactRepositoryContractValidator(directory,check3,contractBase),selectedObligation=selectedObligations.get(check3),obligationContractValidated=selectedObligation?isExactObligationContractAuthorization(directory,selectedObligation,check3,contractBase):!1,contractValidated=directContractValidated||obligationContractValidated;if(selectedObligation?.validatorContract&&!obligationContractValidated)return failure2(`Stage A obligation ${selectedObligation.id} requires exact validator_contract ${selectedObligation.validatorContract.path}#${selectedObligation.validatorContract.id}`);let executable=normalizedExecutable(check3.command);if(selectedObligation&&!commandMatchesObligationSource(directory,selectedObligation,check3,contractValidated))return failure2(`Stage A command does not prove its exact source obligation ${selectedObligation.id}`);if(!isPlausibleStageACommand(check3.category,check3.command)&&!(contractValidated&&isSafeContractCommand(check3.command)))return failure2(`Stage A ${check3.category} command is not a recognized non-publishing ${check3.category} validation command`);let isPackageManagerCommand=["npm","pnpm","yarn"].includes(executable)||executable==="bun"&&check3.command[1]==="run";if(!selectedObligation&&isPackageManagerCommand&&(check3.category!=="reproduction"||!isExactRepositoryPackageManagerScript(directory,normalizedCheckDirectories.get(check3)??".",check3.category,check3.command)))return failure2(`Stage A ${check3.category} package-manager command must select one exact inspected repository script`);if(!isAllowedRepositoryExecutable(directory,normalizedCheckDirectories.get(check3)??".",check3.command[0],contractValidated))return failure2(`Stage A rejects escaping or undeclared repository wrapper executables: ${check3.command[0]}`)}let normalizedCommands=parsed.data.checks.map((check3)=>`${check3.obligation_id??check3.category}\x00${normalizedCheckDirectories.get(check3)??"."}\x00${check3.command.join("\x00")}`.toLowerCase());if(new Set(normalizedCommands).size!==normalizedCommands.length)return failure2("Stage A categories require distinct commands; one command cannot prove multiple obligations");let reproduction=parsed.data.checks.find((check3)=>check3.category==="reproduction");if(!reproduction?.targets?.length)return failure2("Stage A reproduction requires at least one explicit test/regression target");let reproductionSelectors=reproductionSelectorValues(reproduction.command),missingTargets=reproduction.targets.filter((target)=>![...reproductionSelectors].some((selector)=>selector===target||selector.replaceAll("\\","/")===target.replaceAll("\\","/")));if(missingTargets.length>0)return failure2(`Stage A reproduction command does not select declared target(s): ${missingTargets.join(", ")}`);for(let target of reproduction.targets){if(!/[\\/]/.test(target))continue;let pathTarget=target.split("::",1)[0].replace(/:\d+(?::\d+)?$/,""),resolved=path281.resolve(directory,pathTarget),relative69=path281.relative(path281.resolve(directory),resolved);if(!relative69||relative69.startsWith("..")||path281.isAbsolute(relative69)||!fs163.existsSync(resolved)||!fs163.statSync(resolved).isFile())return failure2(`Stage A reproduction target is not a contained existing file: ${target}`)}try{let state=await assertPrFeedbackVerificationSettled(directory,context.sessionID),feedbackTargets=reproduction.feedback_targets??[],mappedFeedbackIds=feedbackTargets.map((mapping)=>mapping.feedback_item_id);if(mappedFeedbackIds.length!==new Set(mappedFeedbackIds).size||mappedFeedbackIds.length!==(state.prFeedbackInventory?.length??0)||!mappedFeedbackIds.every((itemId,index)=>itemId===state.prFeedbackInventory?.[index])||feedbackTargets.some((mapping)=>!reproduction.targets?.includes(mapping.target)))return failure2("Stage A reproduction requires one exact target and expected-behavior mapping for every immutable feedback item in declared order");if(state.prHeadSha!==parsed.data.pr_head_sha)return failure2(`PR_FEEDBACK head mismatch: expected ${state.prHeadSha??"(unbound)"}, received ${parsed.data.pr_head_sha}`);await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha,"PR_FEEDBACK");let beforeDigest=await _internals199.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha);if(!beforeDigest)return failure2("Could not compute a bounded Stage A revision digest");let boundHead=(await _internals199.resolveCurrentGitHeadAsync(directory))?.trim(),boundControlState=await _internals199.resolveGitControlStateDigestAsync(directory);if(!boundHead||!boundControlState)return failure2("Could not bind Stage A to the current Git HEAD, refs, config, and index state");let results=[],receipts=[];for(let check3 of parsed.data.checks){let commandRevision=await _internals199.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),commandControl=await _internals199.resolveGitControlStateDigestAsync(directory);if(commandRevision!==beforeDigest||commandControl!==boundControlState||(await _internals199.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A Git or content state changed before ${check3.category}; restart the complete sequence`,results,directory,context.sessionID);let started=Date.now(),[executable,...commandArgs]=check3.command,checkDirectory=resolveContainedDirectory(directory,check3.working_directory??".");if(!checkDirectory)return failure2(`Stage A ${check3.category} workspace disappeared before execution`,results,directory,context.sessionID);let result;try{result=await _internals199.runExternalTool({executable,args:commandArgs,cwd:checkDirectory.absolute,timeoutMs:check3.timeout_ms??120000,maxStdoutBytes:MAX_OUTPUT_BYTES9,maxStderrBytes:MAX_OUTPUT_BYTES9})}catch(error93){let afterThrowRevision=await _internals199.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),afterThrowControl=await _internals199.resolveGitControlStateDigestAsync(directory);if(afterThrowRevision!==beforeDigest||afterThrowControl!==boundControlState||(await _internals199.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A ${check3.category} threw after mutating content, HEAD, refs, Git config, or index state`,results,directory,context.sessionID);return failure2(`Stage A ${check3.category} execution threw: ${error93 instanceof Error?error93.message:String(error93)}`,results,directory,context.sessionID)}let durationMs=Date.now()-started;results.push({category:check3.category,working_directory:checkDirectory.relative,...check3.obligation_id?{obligation_id:check3.obligation_id}:{},command:check3.command,status:result.status,exit_code:result.exitCode,duration_ms:durationMs,stdout:result.stdout,stderr:result.stderr,stdout_truncated:result.stdoutTruncated,stderr_truncated:result.stderrTruncated,...result.message?{message:result.message}:{}});let afterCommandRevision=await _internals199.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),afterCommandControl=await _internals199.resolveGitControlStateDigestAsync(directory);if(afterCommandRevision!==beforeDigest||afterCommandControl!==boundControlState||(await _internals199.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A ${check3.category} mutated content, HEAD, refs, Git config, or index state`,results,directory,context.sessionID);if(result.status!=="completed"||result.exitCode!==0)return failure2(`Stage A ${check3.category} failed (${result.status}, exit ${result.exitCode??"unknown"})`,results,directory,context.sessionID);if(check3.validator_contract&&!`${result.stdout}
|
|
6401
|
+
${result.stderr}`;return/(?:\b(?:ran|running|collected)\s+0\s+(?:tests?|items?)\b|\btests? run:\s*0\b|\b0\s+(?:tests?\s+(?:ran|passed)|pass(?:ed)?|passing|examples?)\b|\bno tests? (?:ran|to run|found|were found|executed|is available)\b|\bno test is available\b|\btests? (?:are|were) skipped\b|\btest\b[^\n]*\bskipped\b|\bNO-SOURCE\b|\[no test files\])/i.test(output)}function reproductionSelectorValues(command){let runnerVerbs=new Set(["run","run-script","test","tests","spec","check"]),selectorFlags=new Set(["--test-name-pattern","--testNamePattern","--tests","--filter","--grep","-k","-m","-run"]),selectors=new Set;for(let index=1;index<command.length;index+=1){let arg=command[index];if(selectorFlags.has(arg)){let value=command[index+1];if(value&&!value.startsWith("-"))selectors.add(value);index+=1;continue}let assignment=arg.match(/^(?:--(?:test-name-pattern|testNamePattern|tests|filter|grep)|-run|-Dtest)=(.+)$/);if(assignment?.[1]){selectors.add(assignment[1]);continue}if(arg.startsWith("-")||arg.startsWith("/"))continue;if(runnerVerbs.has(arg.toLowerCase()))continue;selectors.add(arg)}return selectors}function isPlausibleTypecheckCommand(executable,args2,_directCommandName){if(executable==="go")return args2[0]==="vet"&&!args2.some((arg)=>/^-n(?:=.*)?$/i.test(arg));if(executable==="flow")return["check","status","focus-check"].includes(args2[0]?.toLowerCase());if(executable==="phpstan")return["analyse","analyze"].includes(args2[0]?.toLowerCase())&&!args2.some((arg)=>/^--generate-baseline(?:=.*)?$/i.test(arg));return/^(?:tsc|pyright|mypy|sorbet|psalm)$/.test(executable)||executable==="cargo"&&args2[0]==="check"||executable==="dotnet"&&args2[0]==="build"}function isPlausibleReproductionCommand(executable,args2,_directCommandName,_commandPath){if(executable==="python"||executable==="python3")return args2[0]==="-m"&&args2[1]?.toLowerCase()==="pytest";if(executable==="bundle")return args2[0]==="exec"&&args2[1]?.toLowerCase()==="rspec";if(executable==="cargo")return args2[0]==="test"||args2[0]==="nextest"&&args2[1]?.toLowerCase()==="run";if(executable==="go")return args2[0]==="test"&&!args2.some((arg)=>/^(?:-c|-list(?:=.*)?)$/i.test(arg));if(executable==="node")return args2[0]==="--test";if(executable==="deno")return args2[0]==="test";if(executable==="zig")return args2[0]==="test";if(executable==="meson")return args2[0]==="test";if(executable==="make"||executable==="ninja")return args2.some((arg)=>/^(?:test|check|verify|regression)$/i.test(arg));if(executable==="playwright")return args2[0]==="test";if(executable==="dart"||executable==="flutter")return args2[0]==="test";if(executable==="xcodebuild")return args2.some((arg)=>["test","test-without-building"].includes(arg.toLowerCase()))&&!args2.some((arg)=>/^-(?:list|enumerate-tests|showBuildSettings|showdestinations|showTestPlans|showsdks|version|help)$/i.test(arg));if(executable==="cypress")return args2[0]==="run";if(/^(?:pytest|ctest|rspec|phpunit|vitest|jest|mocha|ava|go-test-sum)$/.test(executable))return!0;if(executable==="dotnet")return args2[0]?.toLowerCase()==="test";if(["mvn","mvnw"].includes(executable))return args2.some((arg)=>/^(?:test|verify|integration-test|failsafe:integration-test)$/i.test(arg));if(["gradle","gradlew"].includes(executable)){let invokesExecutableTestTask=args2.some((arg)=>{if(arg.startsWith("-"))return!1;let task2=arg.split(":").filter(Boolean).at(-1)??"";if(/^(?:compile|process|generate|assemble|classes|jar|source|kapt|prepare)/i.test(task2))return!1;return task2.toLowerCase()==="test"||/^test[A-Z0-9_-]/.test(task2)&&/Test$/.test(task2)||/^[a-z][A-Za-z0-9_-]*Test$/.test(task2)});return!args2.some((arg)=>/^(?:-m|--dry-run)(?:=.*)?$/i.test(arg))&&invokesExecutableTestTask}return!1}function isPlausibleStageACommand(category,command){if(category==="diff-check")return isExactDiffCheck(command);let executable=path281.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"");if(BLOCKED_EXECUTABLES.has(executable))return!1;if(command.slice(1).some((arg)=>/^(?:-h|--help|--version|version|help|list|-N|--fixtures(?:-per-test)?|--markers|--trace-config|--cache-show|--list(?:-?(?:tests?|suites|groups))?(?:-xml)?(?:=.*)?|--show-only(?:=.*)?|--print-labels|--listFilesOnly|--noCheck|--no-check|--no-run(?:=.*)?|--test-dry-run(?:=.*)?|--createStub|--createstub|--print-config|--env-info|--show-settings|--show-files|--list-msgs|--generate-rcfile|--show-?config(?:=.*)?|--init|--dry-run(?:=.*)?|--collect-only|--setup-(?:only|plan)|--co|--if-present(?:=.*)?)$/i.test(arg)))return!1;if(command.slice(1).some((arg)=>MUTATING_ARGUMENT.test(arg))||["bun","node","python","python3","ruby","perl","npx"].includes(executable)&&command.slice(1).some((arg)=>["-e","--eval","-c","--call"].includes(arg)))return!1;if(category==="lint"&&command.some((arg)=>/^(?:--fix(?:-only)?|--write|--apply|--auto-?correct)(?:=.*)?$|^-[aAw]$/.test(arg)))return!1;if(category==="reproduction"&&(command.some((arg)=>/^(?:--passWithNoTests|--allow-no-tests|--collect-only|--list|--dry-run|--only|--todo|--update-snapshot|--bless|--accept|-w|-x(?:.+)?|--exclude-task(?:=.+)?)$/i.test(arg))||command.some((arg)=>/^-D(?:skipTests|skipITs|maven\.test\.(?:skip|skip\.exec))(?:=true)?$/i.test(arg))))return!1;if(["npm","pnpm","yarn"].includes(executable)||executable==="bun"&&["build","run","test"].includes(command[1]))return isPlausiblePackageManagerCommand(category,executable,command.slice(1));if(executable==="npx")return isPlausiblePackageManagerCommand(category,executable,command.slice(1));let directCommandName=executable.replace(/\.(?:sh|ps1|py|js|mjs|cjs|rb|pl)$/,"");switch(category){case"build":return isPlausibleBuildCommand(executable,command.slice(1));case"typecheck":return isPlausibleTypecheckCommand(executable,command.slice(1),directCommandName);case"lint":return isPlausibleLintCommand(executable,command.slice(1),directCommandName);case"reproduction":return isPlausibleReproductionCommand(executable,command.slice(1),directCommandName,command[0])}}function readBoundedText(filePath){try{let stat18=fs163.statSync(filePath);if(!stat18.isFile()||stat18.size>524288)return;return fs163.readFileSync(filePath,"utf8")}catch{return}}function readPresentRepositoryText(directory,filePath,label){let stat18;try{stat18=fs163.statSync(filePath)}catch(error93){if(error93.code==="ENOENT")return;throw Error(`BLOCKED: Stage A cannot inspect present ${label}`)}if(!stat18.isFile()||stat18.size>524288)throw Error(`BLOCKED: Stage A cannot inspect present ${label}`);try{let canonicalRoot=fs163.realpathSync(path281.resolve(directory)),canonicalFile=fs163.realpathSync(filePath),relative69=path281.relative(canonicalRoot,canonicalFile);if(relative69===".."||relative69.startsWith(`..${path281.sep}`)||path281.isAbsolute(relative69))throw Error("escaping manifest");return fs163.readFileSync(canonicalFile,"utf8")}catch{throw Error(`BLOCKED: Stage A cannot inspect present ${label}`)}}function resolveContainedDirectory(directory,workingDirectory="."){let root=path281.resolve(directory),canonicalRoot=(()=>{try{return fs163.realpathSync(root)}catch{return root}})(),candidate2=path281.resolve(root,workingDirectory);try{if(!fs163.statSync(candidate2).isDirectory())return;let absolute=fs163.realpathSync(candidate2),relativePath2=path281.relative(canonicalRoot,absolute);if(relativePath2===".."||relativePath2.startsWith(`..${path281.sep}`)||path281.isAbsolute(relativePath2))return;return{absolute,relative:relativePath2.replaceAll("\\","/")||"."}}catch{return}}function readRepositoryValidationContract(directory,contractPath){let root=path281.resolve(directory),canonicalRoot=(()=>{try{return fs163.realpathSync(root)}catch{return root}})(),resolved=path281.resolve(root,contractPath),canonicalContract;try{canonicalContract=fs163.realpathSync(resolved)}catch{return}let relative69=path281.relative(canonicalRoot,canonicalContract);if(!relative69||relative69===".."||relative69.startsWith(`..${path281.sep}`)||path281.isAbsolute(relative69)||path281.basename(canonicalContract)!==".pr-validation.json")return;let text=readBoundedText(canonicalContract);if(!text)return;try{return RepositoryValidationContractSchema.parse(JSON.parse(text))}catch{return}}async function resolveContractBaseProvenance(directory,prHeadSha,baseRef,baseSha){if(!baseRef&&!baseSha)return;if(!baseRef||!baseSha)throw Error("BLOCKED: Stage A contract authorization requires both base_ref and base_sha");let resolvedBase=await _internals199.resolveExactMergeBaseAsync(directory,baseRef,prHeadSha);if(!resolvedBase||resolvedBase.toLowerCase()!==baseSha.toLowerCase()||resolvedBase.toLowerCase()===prHeadSha.toLowerCase())throw Error("Stage A contract authorization requires base_sha to be the immutable merge base of base_ref and pr_head_sha");return{baseRef,baseSha:resolvedBase.toLowerCase()}}function readTrustedRepositoryValidationContract(directory,contractPath,provenance){if(!provenance)return;let current=readRepositoryValidationContract(directory,contractPath),currentText=readBoundedText(path281.resolve(directory,contractPath)),baseText=_internals199.readGitTextAtRevision(directory,provenance.baseSha,contractPath.replaceAll("\\","/").replace(/^\.\//,""));if(!current||!currentText||baseText===null||currentText!==baseText)return;return current}function isExactRepositoryContractValidator(directory,check3,provenance){if(!check3.validator_contract)return!1;let validator=readTrustedRepositoryValidationContract(directory,check3.validator_contract.path,provenance)?.validators.find((candidate2)=>candidate2.id===check3.validator_contract?.id);if(!validator||validator.category!==check3.category)return!1;let requestedDirectory=resolveContainedDirectory(directory,check3.working_directory??"."),declaredDirectory=resolveContainedDirectory(directory,validator.working_directory);return Boolean(requestedDirectory&&declaredDirectory)&&requestedDirectory?.absolute===declaredDirectory?.absolute&&validator.command.length===check3.command.length&&validator.command.every((part,index)=>part===check3.command[index])}function isExactObligationContractAuthorization(directory,obligation,check3,provenance){let identity=obligation.validatorContract;if(!identity||check3.validator_contract?.path!==identity.path||check3.validator_contract.id!==identity.id)return!1;let validator=readTrustedRepositoryValidationContract(directory,identity.path,provenance)?.validators.find(({id})=>id===identity.id),workspace=resolveContainedDirectory(directory,obligation.workingDirectory),validatorWorkspace=validator?resolveContainedDirectory(directory,validator.working_directory):void 0;if(!validator||validator.category!==obligation.category||validatorWorkspace?.absolute!==workspace?.absolute)return!1;if(!obligation.source.startsWith("package.json#")||!workspace)return!1;let scriptName=obligation.source.slice(13),packageText=readBoundedText(path281.join(workspace.absolute,"package.json"));if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared&&declared.length===validator.command.length&&declared.every((part,index)=>part===validator.command[index])&&(packageManagerSelectsExactScript(check3.command,scriptName)||declared.length===check3.command.length&&declared.every((part,index)=>part===check3.command[index])))}catch{return!1}}function isSafeContractCommand(command){let executable=path281.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"");return!BLOCKED_EXECUTABLES.has(executable)&&!command.slice(1).some((arg)=>MUTATING_ARGUMENT.test(arg))&&!command.some((arg)=>/^(?:-h|--help|--version|help|version|--dry-run|--if-present)$/i.test(arg))&&!(["bun","node","python","python3","ruby","perl","npx"].includes(executable)&&command.slice(1).some((arg)=>["-e","--eval","-c","--call"].includes(arg)))}function isAllowedRepositoryExecutable(directory,workingDirectory,executable,contractValidated){if(!/[\\/]/.test(executable))return!0;if(path281.isAbsolute(executable))return!1;let workspace=resolveContainedDirectory(directory,workingDirectory);if(!workspace)return!1;let resolved=path281.resolve(workspace.absolute,executable),canonicalExecutable;try{canonicalExecutable=fs163.realpathSync(resolved)}catch{return!1}let canonicalRoot=(()=>{try{return fs163.realpathSync(path281.resolve(directory))}catch{return path281.resolve(directory)}})(),relative69=path281.relative(canonicalRoot,canonicalExecutable);if(relative69===".."||relative69.startsWith(`..${path281.sep}`)||path281.isAbsolute(relative69))return!1;let basename35=path281.basename(canonicalExecutable).toLowerCase().replace(/\.(?:cmd|bat|exe)$/,"");if(!contractValidated&&!["gradlew","mvnw"].includes(basename35))return!1;return fs163.statSync(canonicalExecutable).isFile()}function normalizedExecutable(command){return path281.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"")}function parseSimpleRepositoryScript(script){if(/[;&|><`\r\n]/.test(script)||script.includes("$(")||script.includes("${"))return;let tokens=script.match(/"(?:\\.|[^"\\])*"|'[^']*'|[^\s]+/g)?.map((token)=>{if(token.startsWith('"')&&token.endsWith('"')||token.startsWith("'")&&token.endsWith("'"))return token.slice(1,-1);return token})??[];return tokens.length>0?tokens:void 0}function packageManagerSelectedScriptName(command){let executable=normalizedExecutable(command);if(!["npm","bun","pnpm","yarn"].includes(executable))return;let positional=command.slice(1,command.indexOf("--")>=0?command.indexOf("--"):void 0).filter((arg)=>!arg.startsWith("-"));if(executable==="npm")return["run","run-script"].includes(positional[0]??"")?positional[1]:void 0;if(executable==="bun")return positional[0]==="run"?positional[1]:void 0;return positional[0]==="run"?positional[1]:positional[0]}function packageManagerSelectsExactScript(command,scriptName){return packageManagerSelectedScriptName(command)===scriptName}function isExactRepositoryPackageManagerScript(directory,workingDirectory,category,command){let scriptName=packageManagerSelectedScriptName(command),workspace=resolveContainedDirectory(directory,workingDirectory);if(!scriptName||!workspace||!categoryMatchesScriptName(category,scriptName))return!1;let packageText=readBoundedText(path281.join(workspace.absolute,"package.json"));if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared&&isPlausibleStageACommand(category,declared))}catch{return!1}}function commandMatchesObligationSource(directory,obligation,check3,contractValidated){let executable=normalizedExecutable(check3.command),effectiveExecutable=executable==="npx"&&check3.command[1]?path281.basename(check3.command[1]).toLowerCase():executable,source=obligation.source;if(source.includes(".pr-validation.json#")){let separator=source.lastIndexOf("#"),contractPath=source.slice(0,separator),validatorId=source.slice(separator+1);return contractValidated&&check3.validator_contract?.id===validatorId&&check3.validator_contract?.path.replaceAll("\\","/").replace(/^\.\//,"")===contractPath.replace(/^\.\//,"")}if(source.startsWith("package.json#")){let scriptName=source.slice(13),workspace=resolveContainedDirectory(directory,obligation.workingDirectory),packageText=workspace?readBoundedText(path281.join(workspace.absolute,"package.json")):void 0;if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared)&&declared?.length===check3.command.length&&declared.every((part,index)=>part===check3.command[index])||packageManagerSelectsExactScript(check3.command,scriptName)}catch{return!1}}if(source==="Cargo.toml")return effectiveExecutable==="cargo";if(source==="go.mod")return effectiveExecutable==="go";if(source==="pom.xml")return["mvn","mvnw"].includes(effectiveExecutable);if(/^build\.gradle(?:\.kts)?$/.test(source))return["gradle","gradlew"].includes(effectiveExecutable);if(/^(?:Makefile|makefile)$/.test(source))return effectiveExecutable==="make";if(source==="CMakeLists.txt")return effectiveExecutable==="cmake";if(source==="Package.swift")return["swift","swiftc"].includes(effectiveExecutable);if(source==="setup.py"||source==="pyproject.toml#build-system")return["python","python3"].includes(effectiveExecutable);if(/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(source))return["dotnet","msbuild"].includes(effectiveExecutable);if(/\.(?:xcodeproj|xcworkspace)$/i.test(source))return effectiveExecutable==="xcodebuild";let sourceExecutables={"tsconfig.json":["tsc"],"pyrightconfig.json":["pyright"],".flowconfig":["flow"],"phpstan.neon":["phpstan"],"phpstan.neon.dist":["phpstan"],"psalm.xml":["psalm"],"psalm.xml.dist":["psalm"],"mypy.ini":["mypy"],"pyproject.toml#mypy":["mypy"],"biome.json":["biome"],"biome.jsonc":["biome"],"ruff.toml":["ruff"],".ruff.toml":["ruff"],"pyproject.toml#ruff":["ruff"],".rubocop.yml":["rubocop"],".swiftlint.yml":["swiftlint"],".golangci.yml":["golangci-lint"],".golangci.yaml":["golangci-lint"],".stylelintrc":["stylelint"],".stylelintrc.json":["stylelint"]};if(/^(?:\.eslintrc|eslint\.config\.)/.test(source))return effectiveExecutable==="eslint";return sourceExecutables[source]?.includes(effectiveExecutable)??!1}function discoverApplicableStageAObligations(directory,contractBase){let root=path281.resolve(directory),canonicalRoot=(()=>{try{return fs163.realpathSync(root)}catch{return root}})(),candidateRoots=[],seenRoots=new Set,discoveryOverflow,addCandidateRoot=(candidate2)=>{if(candidateRoots.length>=256){discoveryOverflow="Stage A repository discovery exceeded 256 contained workspace roots";return}try{if(!fs163.statSync(candidate2).isDirectory())return;let canonicalCandidate=fs163.realpathSync(candidate2),relative69=path281.relative(canonicalRoot,canonicalCandidate);if(relative69.startsWith(`..${path281.sep}`)||relative69===".."||path281.isAbsolute(relative69)||seenRoots.has(canonicalCandidate))return;seenRoots.add(canonicalCandidate),candidateRoots.push(canonicalCandidate)}catch{}},addWorkspacePattern=(pattern)=>{let normalized=pattern.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!normalized||normalized.startsWith("!")||path281.posix.isAbsolute(normalized)||normalized.split("/").includes("..")){discoveryOverflow=`Stage A cannot safely expand declared workspace pattern "${pattern}"`;return}if(!normalized.includes("*")){addCandidateRoot(path281.resolve(root,normalized));return}let wildcard=normalized.match(/^([^*?[\]]+)\/\*\/?$/);if(!wildcard){discoveryOverflow=`Stage A cannot safely expand declared workspace pattern "${pattern}"`;return}let container=path281.resolve(root,wildcard[1]);try{let entries=fs163.readdirSync(container,{withFileTypes:!0});if(entries.length>256){discoveryOverflow=`Stage A workspace container ${wildcard[1]} exceeds the 256-entry bounded discovery limit`;return}for(let entry of entries)if(entry.isDirectory())addCandidateRoot(path281.join(container,entry.name))}catch{}};addCandidateRoot(root);for(let containerName of["packages","apps","services","libs","crates"])addWorkspacePattern(`${containerName}/*`);let rootPackageText=readPresentRepositoryText(canonicalRoot,path281.join(root,"package.json"),"root package.json workspace declaration");if(rootPackageText)try{let value=JSON.parse(rootPackageText),workspacePatterns=Array.isArray(value.workspaces)?value.workspaces:value.workspaces?.packages;for(let pattern of workspacePatterns??[])if(typeof pattern==="string")addWorkspacePattern(pattern)}catch{discoveryOverflow="Stage A cannot safely inspect malformed root package.json workspace metadata"}let pnpmWorkspaceText=readPresentRepositoryText(canonicalRoot,path281.join(root,"pnpm-workspace.yaml"),"pnpm-workspace.yaml declaration");for(let match of pnpmWorkspaceText?.matchAll(/^\s*-\s*['"]?([^'"#\r\n]+?)['"]?\s*$/gm)??[])addWorkspacePattern(match[1]);let cargoMembers=readPresentRepositoryText(canonicalRoot,path281.join(root,"Cargo.toml"),"Cargo.toml workspace declaration")?.match(/\bmembers\s*=\s*\[([\s\S]*?)\]/m)?.[1];for(let match of cargoMembers?.matchAll(/['"]([^'"]+)['"]/g)??[])addWorkspacePattern(match[1]);let mavenText=readPresentRepositoryText(canonicalRoot,path281.join(root,"pom.xml"),"pom.xml module declaration");for(let match of mavenText?.matchAll(/<module>\s*([^<]+?)\s*<\/module>/gi)??[])addWorkspacePattern(match[1]);let goWorkText=readPresentRepositoryText(canonicalRoot,path281.join(root,"go.work"),"go.work workspace declaration");for(let match of goWorkText?.matchAll(/^\s*(?:use\s+)?(\.\.?\/[^\s/]+(?:\/[^\s]+)*)\s*$/gm)??[])addWorkspacePattern(match[1]);for(let settingsName of["settings.gradle","settings.gradle.kts"]){let settingsText=readPresentRepositoryText(canonicalRoot,path281.join(root,settingsName),`${settingsName} workspace declaration`);for(let includeMatch of settingsText?.matchAll(/\binclude\s*\(?([^\r\n)]+)/g)??[])for(let projectMatch of includeMatch[1].matchAll(/['"]:?(.*?)['"]/g)){let projectPath=projectMatch[1].replaceAll(":","/");if(projectPath)addWorkspacePattern(projectPath)}}let obligations=new Map,addObligation=(category,candidateRoot,source,validatorContract)=>{let workspace=path281.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||".",id=`${category}:${workspace}:${source}`;if(!obligations.has(id)&&obligations.size>=256){discoveryOverflow="Stage A repository discovery exceeded 256 concrete validation obligations";return}obligations.set(id,{id,category,workingDirectory:workspace,source,...validatorContract?{validatorContract}:{}})},buildFiles=new Set(["Cargo.toml","go.mod","pom.xml","build.gradle","build.gradle.kts","Makefile","makefile","CMakeLists.txt","Package.swift","setup.py"]),typecheckFiles=new Set(["tsconfig.json","pyrightconfig.json",".flowconfig","phpstan.neon","phpstan.neon.dist","psalm.xml","psalm.xml.dist","mypy.ini"]),lintFiles=new Set(["biome.json","biome.jsonc",".eslintrc",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml",".eslintrc.js",".eslintrc.cjs",".eslintrc.mjs","eslint.config.js","eslint.config.mjs","eslint.config.cjs","eslint.config.ts","ruff.toml",".ruff.toml",".rubocop.yml",".swiftlint.yml",".golangci.yml",".golangci.yaml",".stylelintrc",".stylelintrc.json"]);for(let candidateRoot of candidateRoots){let entries=[];try{if(entries=fs163.readdirSync(candidateRoot,{withFileTypes:!0}),entries.length>2048){discoveryOverflow=`Stage A workspace ${path281.relative(canonicalRoot,candidateRoot)||"."} exceeds the 2048-entry bounded manifest scan`;continue}}catch{continue}for(let entry of entries){if(entry.isFile()&&buildFiles.has(entry.name))addObligation("build",candidateRoot,entry.name);if(entry.isFile()&&typecheckFiles.has(entry.name))addObligation("typecheck",candidateRoot,entry.name);if(entry.isFile()&&lintFiles.has(entry.name))addObligation("lint",candidateRoot,entry.name);if(entry.isFile()&&/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(entry.name))addObligation("build",candidateRoot,entry.name);if(entry.isDirectory()&&/\.(?:xcodeproj|xcworkspace)$/i.test(entry.name))addObligation("build",candidateRoot,entry.name)}let contractPath=path281.join(candidateRoot,".pr-validation.json"),contractRelative=path281.relative(canonicalRoot,contractPath).replaceAll("\\","/"),untrustedContract=readRepositoryValidationContract(canonicalRoot,contractRelative),contract=readTrustedRepositoryValidationContract(canonicalRoot,contractRelative,contractBase);if(fs163.existsSync(contractPath)&&!untrustedContract)discoveryOverflow=`Stage A found an invalid, oversized, unreadable, or escaping validation contract at ${contractRelative}`;else if(untrustedContract&&!contract)discoveryOverflow=`Stage A validation contract at ${contractRelative} must be unchanged from the immutable merge base named by base_ref and base_sha`;let contractValidatorsCoveredByScripts=new Set,packageText=readPresentRepositoryText(canonicalRoot,path281.join(candidateRoot,"package.json"),`${path281.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json manifest`);if(packageText)try{let value=JSON.parse(packageText);for(let[script,commandText]of Object.entries(value.scripts??{})){let declaredCommand=typeof commandText==="string"?parseSimpleRepositoryScript(commandText):void 0;for(let category of OPTIONAL_STAGE_A_CATEGORIES){if(!categoryMatchesScriptName(category,script))continue;let authorizingValidator=contract?.validators.find((validator)=>{let validatorWorkspace=resolveContainedDirectory(canonicalRoot,validator.working_directory);return validator.category===category&&validatorWorkspace?.absolute===candidateRoot&&(!declaredCommand||declaredCommand.length===validator.command.length&&declaredCommand.every((part,index)=>part===validator.command[index]))});if(!declaredCommand){if(!authorizingValidator)discoveryOverflow=`Stage A opaque package script ${path281.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json#${script} requires a trusted base-identical contract validator for ${category}`;continue}if(isPlausibleStageACommand(category,declaredCommand)||Boolean(authorizingValidator)){if(addObligation(category,candidateRoot,`package.json#${script}`,authorizingValidator?{path:contractRelative,id:authorizingValidator.id}:void 0),authorizingValidator)contractValidatorsCoveredByScripts.add(authorizingValidator.id)}}}}catch{discoveryOverflow=`Stage A cannot safely inspect malformed package manifest at ${path281.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json`}let pyprojectText=readPresentRepositoryText(canonicalRoot,path281.join(candidateRoot,"pyproject.toml"),`${path281.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/pyproject.toml manifest`);if(pyprojectText?.match(/\[build-system\]/i))addObligation("build",candidateRoot,"pyproject.toml#build-system");if(pyprojectText?.match(/\[(?:tool\.)?mypy\]/i))addObligation("typecheck",candidateRoot,"pyproject.toml#mypy");if(pyprojectText?.match(/\[tool\.ruff(?:\.|\])/i))addObligation("lint",candidateRoot,"pyproject.toml#ruff");for(let validator of contract?.validators??[]){if(contractValidatorsCoveredByScripts.has(validator.id))continue;if(OPTIONAL_STAGE_A_CATEGORIES.includes(validator.category)){let validatorWorkspace=resolveContainedDirectory(canonicalRoot,validator.working_directory);if(!validatorWorkspace)continue;addObligation(validator.category,validatorWorkspace.absolute,`${contractRelative}#${validator.id}`)}}}if(discoveryOverflow)throw Error(`BLOCKED: ${discoveryOverflow}`);return[...obligations.values()]}function discoverApplicableStageACategories(directory,contractBase){let applicable=new Set(discoverApplicableStageAObligations(directory,contractBase).map(({category})=>category));return OPTIONAL_STAGE_A_CATEGORIES.filter((category)=>applicable.has(category))}async function executeRunPrFeedbackStageA(args2,directory,context={}){let parsed=RunPrFeedbackStageAArgsSchema.safeParse(args2);if(!parsed.success)return failure2(`Invalid PR-feedback Stage A request: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);if(!context.sessionID?.trim())return failure2("PR-feedback Stage A requires an active sessionID");let categories=parsed.data.checks.map((check3)=>check3.category);for(let requiredSingleton of ALWAYS_REQUIRED_CATEGORIES)if(categories.filter((category)=>category===requiredSingleton).length!==1)return failure2(`Stage A requires exactly one ${requiredSingleton} receipt`);let contractBase;try{contractBase=await resolveContractBaseProvenance(directory,parsed.data.pr_head_sha,parsed.data.base_ref,parsed.data.base_sha)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}let applicableObligations;try{applicableObligations=_internals199.discoverApplicableStageAObligations(directory,contractBase)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}let applicableCategories=OPTIONAL_STAGE_A_CATEGORIES.filter((category)=>applicableObligations.some((obligation)=>obligation.category===category)),matchedObligationIds=new Set,selectedObligations=new Map,normalizedCheckDirectories=new Map;for(let check3 of parsed.data.checks){let workspace=resolveContainedDirectory(directory,check3.working_directory??".");if(!workspace)return failure2(`Stage A ${check3.category} working_directory is not a contained repository workspace`);if(normalizedCheckDirectories.set(check3,workspace.relative),!OPTIONAL_STAGE_A_CATEGORIES.includes(check3.category))continue;let candidates=applicableObligations.filter((obligation)=>obligation.category===check3.category&&obligation.workingDirectory===workspace.relative);if(candidates.length===0&&!check3.obligation_id)continue;let selected=check3.obligation_id?candidates.find((candidate2)=>candidate2.id===check3.obligation_id):candidates.length===1?candidates[0]:void 0;if(!selected)return failure2(`Stage A ${check3.category} must name one exact discovered obligation_id for workspace ${workspace.relative}: ${candidates.map(({id})=>id).join(", ")||"none discovered"}`);if(matchedObligationIds.has(selected.id))return failure2(`Stage A repeats discovered obligation ${selected.id}`);matchedObligationIds.add(selected.id),selectedObligations.set(check3,selected),check3.obligation_id=selected.id,check3.working_directory=workspace.relative}let missingObligations=applicableObligations.filter(({id})=>!matchedObligationIds.has(id));if(missingObligations.length>0)return failure2(`Stage A is missing concrete repository validation obligations: ${missingObligations.map(({id})=>id).join(", ")}`);let diffCheck=parsed.data.checks.find((check3)=>check3.category==="diff-check");if(!diffCheck||!isExactDiffCheck(diffCheck.command))return failure2('Stage A diff-check must execute array-form ["git", "diff", "--check"]');for(let check3 of parsed.data.checks){let directContractValidated=isExactRepositoryContractValidator(directory,check3,contractBase),selectedObligation=selectedObligations.get(check3),obligationContractValidated=selectedObligation?isExactObligationContractAuthorization(directory,selectedObligation,check3,contractBase):!1,contractValidated=directContractValidated||obligationContractValidated;if(selectedObligation?.validatorContract&&!obligationContractValidated)return failure2(`Stage A obligation ${selectedObligation.id} requires exact validator_contract ${selectedObligation.validatorContract.path}#${selectedObligation.validatorContract.id}`);let executable=normalizedExecutable(check3.command);if(selectedObligation&&!commandMatchesObligationSource(directory,selectedObligation,check3,contractValidated))return failure2(`Stage A command does not prove its exact source obligation ${selectedObligation.id}`);if(!isPlausibleStageACommand(check3.category,check3.command)&&!(contractValidated&&isSafeContractCommand(check3.command)))return failure2(`Stage A ${check3.category} command is not a recognized non-publishing ${check3.category} validation command`);let isPackageManagerCommand=["npm","pnpm","yarn"].includes(executable)||executable==="bun"&&check3.command[1]==="run";if(!selectedObligation&&isPackageManagerCommand&&(check3.category!=="reproduction"||!isExactRepositoryPackageManagerScript(directory,normalizedCheckDirectories.get(check3)??".",check3.category,check3.command)))return failure2(`Stage A ${check3.category} package-manager command must select one exact inspected repository script`);if(!isAllowedRepositoryExecutable(directory,normalizedCheckDirectories.get(check3)??".",check3.command[0],contractValidated))return failure2(`Stage A rejects escaping or undeclared repository wrapper executables: ${check3.command[0]}`)}let normalizedCommands=parsed.data.checks.map((check3)=>`${check3.obligation_id??check3.category}\x00${normalizedCheckDirectories.get(check3)??"."}\x00${check3.command.join("\x00")}`.toLowerCase());if(new Set(normalizedCommands).size!==normalizedCommands.length)return failure2("Stage A categories require distinct commands; one command cannot prove multiple obligations");let reproduction=parsed.data.checks.find((check3)=>check3.category==="reproduction");if(!reproduction?.targets?.length)return failure2("Stage A reproduction requires at least one explicit test/regression target");let reproductionSelectors=reproductionSelectorValues(reproduction.command),missingTargets=reproduction.targets.filter((target)=>![...reproductionSelectors].some((selector)=>selector===target||selector.replaceAll("\\","/")===target.replaceAll("\\","/")));if(missingTargets.length>0)return failure2(`Stage A reproduction command does not select declared target(s): ${missingTargets.join(", ")}`);for(let target of reproduction.targets){if(!/[\\/]/.test(target))continue;let pathTarget=target.split("::",1)[0].replace(/:\d+(?::\d+)?$/,""),resolved=path281.resolve(directory,pathTarget),relative69=path281.relative(path281.resolve(directory),resolved);if(!relative69||relative69.startsWith("..")||path281.isAbsolute(relative69)||!fs163.existsSync(resolved)||!fs163.statSync(resolved).isFile())return failure2(`Stage A reproduction target is not a contained existing file: ${target}`)}try{let state=await assertPrFeedbackVerificationSettled(directory,context.sessionID),feedbackTargets=reproduction.feedback_targets??[],mappedFeedbackIds=feedbackTargets.map((mapping)=>mapping.feedback_item_id);if(mappedFeedbackIds.length!==new Set(mappedFeedbackIds).size||mappedFeedbackIds.length!==(state.prFeedbackInventory?.length??0)||!mappedFeedbackIds.every((itemId,index)=>itemId===state.prFeedbackInventory?.[index])||feedbackTargets.some((mapping)=>!reproduction.targets?.includes(mapping.target)))return failure2("Stage A reproduction requires one exact target and expected-behavior mapping for every immutable feedback item in declared order");if(state.prHeadSha!==parsed.data.pr_head_sha)return failure2(`PR_FEEDBACK head mismatch: expected ${state.prHeadSha??"(unbound)"}, received ${parsed.data.pr_head_sha}`);await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha,"PR_FEEDBACK");let beforeDigest=await _internals199.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha);if(!beforeDigest)return failure2("Could not compute a bounded Stage A revision digest");let boundHead=(await _internals199.resolveCurrentGitHeadAsync(directory))?.trim(),boundControlState=await _internals199.resolveGitControlStateDigestAsync(directory);if(!boundHead||!boundControlState)return failure2("Could not bind Stage A to the current Git HEAD, refs, config, and index state");let results=[],receipts=[];for(let check3 of parsed.data.checks){let commandRevision=await _internals199.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),commandControl=await _internals199.resolveGitControlStateDigestAsync(directory);if(commandRevision!==beforeDigest||commandControl!==boundControlState||(await _internals199.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A Git or content state changed before ${check3.category}; restart the complete sequence`,results,directory,context.sessionID);let started=Date.now(),[executable,...commandArgs]=check3.command,checkDirectory=resolveContainedDirectory(directory,check3.working_directory??".");if(!checkDirectory)return failure2(`Stage A ${check3.category} workspace disappeared before execution`,results,directory,context.sessionID);let result;try{result=await _internals199.runExternalTool({executable,args:commandArgs,cwd:checkDirectory.absolute,timeoutMs:check3.timeout_ms??120000,maxStdoutBytes:MAX_OUTPUT_BYTES9,maxStderrBytes:MAX_OUTPUT_BYTES9})}catch(error93){let afterThrowRevision=await _internals199.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),afterThrowControl=await _internals199.resolveGitControlStateDigestAsync(directory);if(afterThrowRevision!==beforeDigest||afterThrowControl!==boundControlState||(await _internals199.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A ${check3.category} threw after mutating content, HEAD, refs, Git config, or index state`,results,directory,context.sessionID);return failure2(`Stage A ${check3.category} execution threw: ${error93 instanceof Error?error93.message:String(error93)}`,results,directory,context.sessionID)}let durationMs=Date.now()-started;results.push({category:check3.category,working_directory:checkDirectory.relative,...check3.obligation_id?{obligation_id:check3.obligation_id}:{},command:check3.command,status:result.status,exit_code:result.exitCode,duration_ms:durationMs,stdout:result.stdout,stderr:result.stderr,stdout_truncated:result.stdoutTruncated,stderr_truncated:result.stderrTruncated,...result.message?{message:result.message}:{}});let afterCommandRevision=await _internals199.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),afterCommandControl=await _internals199.resolveGitControlStateDigestAsync(directory);if(afterCommandRevision!==beforeDigest||afterCommandControl!==boundControlState||(await _internals199.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A ${check3.category} mutated content, HEAD, refs, Git config, or index state`,results,directory,context.sessionID);if(result.status!=="completed"||result.exitCode!==0)return failure2(`Stage A ${check3.category} failed (${result.status}, exit ${result.exitCode??"unknown"})`,results,directory,context.sessionID);if(check3.validator_contract&&!`${result.stdout}
|
|
6402
6402
|
${result.stderr}`.trim())return failure2(`Stage A repository-contract validator ${check3.validator_contract.id} produced no machine-observable evidence`,results,directory,context.sessionID);if(check3.category==="reproduction"&&outputReportsZeroTests(result))return failure2("Stage A reproduction produced truncated proof or reported that zero tests executed",results,directory,context.sessionID);if(check3.category==="reproduction"&&!`${result.stdout}
|
|
6403
6403
|
${result.stderr}`.trim())return failure2("Stage A reproduction produced no machine-observable execution evidence",results,directory,context.sessionID);receipts.push({category:check3.category,workingDirectory:checkDirectory.relative,...check3.obligation_id?{obligationId:check3.obligation_id}:{},...check3.validator_contract?{validatorContract:{path:check3.validator_contract.path,id:check3.validator_contract.id}}:{},command:check3.command,...check3.targets?{targets:check3.targets}:{},...check3.feedback_targets?{feedbackTargets:check3.feedback_targets.map((mapping)=>({feedbackItemId:mapping.feedback_item_id,target:mapping.target,expectedBehavior:mapping.expected_behavior}))}:{},durationMs})}let afterDigest=await _internals199.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha);if(!afterDigest||afterDigest!==beforeDigest)return failure2("Stage A changed the working-tree revision; rerun all Stage A checks on the resulting diff",results,directory,context.sessionID);if(await _internals199.resolveGitControlStateDigestAsync(directory)!==boundControlState||(await _internals199.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2("Stage A changed HEAD, refs, Git config, or index state; rerun the complete sequence",results,directory,context.sessionID);await recordPrFeedbackStageA(directory,context.sessionID,afterDigest,receipts,{applicableCategories,applicableObligations});let successPayload={success:!0,pr_head_sha:parsed.data.pr_head_sha,revision_digest:afterDigest,checks:results.map(summarizeCheckEntry)};return JSON.stringify(successPayload,null,2)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}}var _internals199={runExternalTool,storeSummary,readGitTextAtRevision,resolveExactMergeBase,resolveExactMergeBaseAsync,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveGitControlStateDigest,resolveGitControlStateDigestAsync,resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,isPlausibleStageACommand,discoverApplicableStageACategories,discoverApplicableStageAObligations,commandMatchesObligationSource},run_pr_feedback_stage_a=createSwarmTool({description:"Execute and persist mandatory PR-feedback Stage A diff-check and targeted reproduction receipts plus every build, typecheck, or lint check mechanically applicable to this repository, on one content-bound revision.",args:{pr_head_sha:RunPrFeedbackStageAArgsSchema.shape.pr_head_sha,checks:RunPrFeedbackStageAArgsSchema.shape.checks},execute:executeRunPrFeedbackStageA});init_sast_scan();init_zod();init_plan_schema();init_qa_gate_profile();init_file_locks();import*as fs164 from"node:fs";import*as path282 from"node:path";init_ledger();init_manager();init_utils3();init_effective_spec();init_state2();init_create_tool();function executionProfilesEqual(a,b){return a.parallelization_enabled===b.parallelization_enabled&&a.max_concurrent_tasks===b.max_concurrent_tasks&&a.council_parallel===b.council_parallel&&a.locked===b.locked&&a.auto_proceed===b.auto_proceed}function evaluateRequirementCoverage(specContent,args2){if(!specContent)return null;let requirements=extractRequirements(specContent);if(requirements.length===0)return null;let covered=[],missing=[];for(let requirement of requirements){let mappedTaskIds=[],idPattern=new RegExp(`\\b${requirement.id}\\b`,"i");for(let phase of args2.phases)for(let task2 of phase.tasks){let taskText=`${task2.description}
|
|
6404
6404
|
${task2.acceptance??""}`,matchesFreeText=idPattern.test(taskText),matchesFrRefs=task2.fr_refs?.includes(requirement.id)??!1;if(matchesFreeText||matchesFrRefs)mappedTaskIds.push(task2.id)}let entry={id:requirement.id,obligation:requirement.obligation,text:requirement.text,mapped_task_ids:mappedTaskIds};if(mappedTaskIds.length>0)covered.push(entry);else missing.push(entry)}let blockingMissing=missing.filter((entry)=>entry.obligation==="MUST"||entry.obligation==="SHALL");return{status:blockingMissing.length>0?args2.confirm_requirement_coverage_gaps===!0?"override":"failed":"passed",total_requirements:requirements.length,covered_count:covered.length,missing_count:missing.length,blocking_missing_count:blockingMissing.length,covered,missing,blocking_missing:blockingMissing}}function detectPlaceholderContent(args2){let issues=[],placeholderPattern=/^\[\w[\w\s]*\]$/;if(placeholderPattern.test(args2.title.trim()))issues.push(`Plan title appears to be a template placeholder: "${args2.title}"`);for(let phase of args2.phases){if(placeholderPattern.test(phase.name.trim()))issues.push(`Phase ${phase.id} name appears to be a template placeholder: "${phase.name}"`);for(let task2 of phase.tasks)if(placeholderPattern.test(task2.description.trim()))issues.push(`Task ${task2.id} description appears to be a template placeholder: "${task2.description}"`)}return issues}function validateTargetWorkspace(target,source){if(target===void 0||target===null)return`Target workspace is required: ${source} not provided`;let trimmed=target.trim();if(trimmed.length===0)return`Target workspace cannot be empty or whitespace: ${source}`;if(trimmed.replace(/\\/g,"/").includes(".."))return`Target workspace cannot contain path traversal: ${source} contains ".."`;return}async function executeSavePlan(args2,fallbackDir){let validationErrors=[];for(let phase of args2.phases){if(!Number.isInteger(phase.id)||phase.id<=0)validationErrors.push(`Phase ${phase.id} has invalid id: must be a positive integer`);let taskIdPattern=/^\d+\.\d+(\.\d+)*$/;for(let task2 of phase.tasks)if(!taskIdPattern.test(task2.id))validationErrors.push(`Task '${task2.id}' in phase ${phase.id} has invalid id format: must match N.M pattern (e.g. '1.1', '2.3')`)}if(validationErrors.length>0)return{success:!1,message:"Plan rejected: invalid phase or task IDs",errors:validationErrors,recovery_guidance:'Phase IDs must be positive integers: 1, 2, 3 (not 0, -1, or decimals). Task IDs must use N.M format: "1.1", "2.3", "3.1". Call save_plan again with corrected ids. Never write .swarm/plan.json or .swarm/plan.md directly.'};let placeholderIssues=detectPlaceholderContent(args2);if(placeholderIssues.length>0)return{success:!1,message:"Plan rejected: contains template placeholder content",errors:placeholderIssues,recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."};let targetWorkspace=args2.working_directory??fallbackDir,workspaceError=validateTargetWorkspace(targetWorkspace,args2.working_directory?"working_directory":"fallbackDir");if(workspaceError)return{success:!1,message:"Target workspace validation failed: provide working_directory parameter to save_plan",errors:[workspaceError],recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."};if(args2.working_directory&&fallbackDir){let resolvedTarget=path282.resolve(args2.working_directory),resolvedRoot=path282.resolve(fallbackDir),fallbackExists=!1;try{fs164.accessSync(resolvedRoot,fs164.constants.F_OK),fallbackExists=!0}catch{fallbackExists=!1}if(fallbackExists){if(resolvedTarget.startsWith(resolvedRoot+path282.sep))return{success:!1,message:`working_directory must be the project root. Got "${args2.working_directory}" (resolves to "${resolvedTarget}"), which is a subdirectory of fallback "${resolvedRoot}". Omit working_directory or pass the project root explicitly.`,errors:[`working_directory "${resolvedTarget}" is a subdirectory of fallback "${resolvedRoot}"`],recovery_guidance:`Pass working_directory: "${resolvedRoot}" or omit the field entirely.`}}}let specMtime,specHash,specContent;if(process.env.SWARM_SKIP_SPEC_GATE!=="1"){let spec=readEffectiveSpecSync(targetWorkspace);if(!spec)return{success:!1,message:"SPEC_REQUIRED: an effective spec (native .swarm/spec.md, OpenSpec openspec/specs or openspec/changes, or Spec-Kit .specify/) must exist before saving a plan.",errors:["No effective spec found — .swarm/spec.md is absent and no OpenSpec/Spec-Kit projection succeeded."],recovery_guidance:"Obtain explicit user consent, then run /swarm sdd project (agent-invocable) to materialize an effective spec from SDD sources. If .swarm/spec.md already exists, pass --overwrite after consent. Alternatively, run /swarm specify to author a native spec. Never write .swarm/plan.json or .swarm/plan.md directly."};specMtime=spec.mtime??void 0,specHash=spec.hash,specContent=spec.content;try{let snapshotPath=path282.join(targetWorkspace,".swarm","spec-snapshot.md");await fs164.promises.writeFile(snapshotPath,spec.content,"utf-8")}catch{}}if(process.env.SWARM_SKIP_GATE_SELECTION!=="1"){let contextPath=path282.join(targetWorkspace,".swarm","context.md"),contextContent="";try{contextContent=await fs164.promises.readFile(contextPath,"utf8")}catch{}if(!contextContent.includes("## Pending QA Gate Selection")){let candidatePlanId=derivePlanId({swarm:args2.swarm_id,title:args2.title}),existingProfile=null;try{existingProfile=getProfile(targetWorkspace,candidatePlanId)}catch{}if(!existingProfile)return{success:!1,message:'QA_GATE_SELECTION_REQUIRED: QA gate selection has not been completed. Present the gate selection question to the user (step 5b of MODE: SPECIFY or Phase 6 of MODE: BRAINSTORM), write their response to .swarm/context.md under "## Pending QA Gate Selection", then retry save_plan.',errors:["Missing ## Pending QA Gate Selection in .swarm/context.md","No existing QaGateProfile found for this plan"],recovery_guidance:"Do not call set_qa_gates with assumed values. Present the gate dialogue, wait for the user's answer, write it to context.md, then retry save_plan."}}}let requirementCoverage=evaluateRequirementCoverage(specContent,args2);if(requirementCoverage?.status==="failed"&&args2.confirm_requirement_coverage_gaps!==!0)return{success:!1,message:"REQUIREMENT_COVERAGE_GAPS: save_plan rejected because required FR-### MUST/SHALL requirements are not mapped to any task.",errors:requirementCoverage.blocking_missing.map((requirement)=>`${requirement.id} (${requirement.obligation}): ${requirement.text}`),recovery_guidance:"Add each required FR-### id to a task description or acceptance criterion, or retry with confirm_requirement_coverage_gaps: true only after surfacing the gaps to the user.",requirement_coverage:requirementCoverage};let dir=targetWorkspace,existingStatusMap=new Map,priorTaskIds=new Set,preservedExecutionProfile;{let existing=null;try{existing=await loadPlanJsonOnly(dir)}catch{}if(existing){for(let phase of existing.phases)for(let task2 of phase.tasks)priorTaskIds.add(task2.id);if(!args2.reset_statuses)for(let phase of existing.phases)for(let task2 of phase.tasks)existingStatusMap.set(task2.id,task2.status);if(args2.confirm_identity_change!==!0){let existingId=derivePlanId(existing),incomingId=derivePlanId({swarm:args2.swarm_id,title:args2.title});if(existingId!==incomingId)return{success:!1,message:"PLAN_IDENTITY_MISMATCH: The incoming plan identity does not match the existing plan. To overwrite with a new identity, set confirm_identity_change: true.",errors:[`Existing plan identity: ${existingId} (swarm: "${existing.swarm}", title: "${existing.title}")`,`Incoming plan identity: ${incomingId} (swarm: "${args2.swarm_id}", title: "${args2.title}")`],recovery_guidance:"Verify the title and swarm_id match the intended plan. If the identity change is intentional, retry with confirm_identity_change: true. Never write .swarm/plan.json or .swarm/plan.md directly."}}if(existing.execution_profile?.locked){if(args2.execution_profile!==void 0&&!args2.reset_statuses){let requestedProfile=ExecutionProfileSchema.safeParse({...existing.execution_profile,...args2.execution_profile});if(!requestedProfile.success)return{success:!1,message:"Invalid execution_profile: schema validation failed",errors:requestedProfile.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`),recovery_guidance:"Check execution_profile fields: parallelization_enabled (boolean), max_concurrent_tasks (integer 1-64), council_parallel (boolean), locked (boolean), auto_proceed (boolean)."};if(executionProfilesEqual(existing.execution_profile,requestedProfile.data))preservedExecutionProfile=existing.execution_profile;else return{success:!1,message:"EXECUTION_PROFILE_LOCKED: The execution_profile for this plan is locked and cannot be changed.",errors:["execution_profile.locked is true — to change the profile you must first unlock it via a separate plan revision that explicitly sets locked: false, or reset the plan with reset_statuses."],recovery_guidance:"Remove the execution_profile field from this save_plan call to preserve the locked profile, or use reset_statuses: true to start fresh (this clears the lock). Never modify execution_profile directly in plan.json."}}else if(!args2.reset_statuses)preservedExecutionProfile=existing.execution_profile}else preservedExecutionProfile=existing.execution_profile}}let resolvedProfile=preservedExecutionProfile;if(args2.execution_profile!==void 0){let merged={...preservedExecutionProfile??(args2.execution_profile.parallelization_enabled===void 0?{parallelization_enabled:!0}:{}),...args2.execution_profile},parsed=ExecutionProfileSchema.safeParse(merged);if(!parsed.success)return{success:!1,message:"Invalid execution_profile: schema validation failed",errors:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`),recovery_guidance:"Check execution_profile fields: parallelization_enabled (boolean), max_concurrent_tasks (integer 1-64), council_parallel (boolean), locked (boolean)."};resolvedProfile=parsed.data}if(resolvedProfile===void 0)resolvedProfile={...ExecutionProfileSchema.parse({}),parallelization_enabled:!0};let incomingTaskIds=new Set;for(let phase of args2.phases)for(let task2 of phase.tasks)incomingTaskIds.add(task2.id);let missingTaskIds=[];for(let id of priorTaskIds)if(!incomingTaskIds.has(id))missingTaskIds.push(id);let rawRemovedIds=args2.removed_task_ids??[];if(rawRemovedIds.length>0){let seen=new Set;for(let id of rawRemovedIds){if(seen.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains duplicate entries",errors:[`Duplicate id in removed_task_ids: "${id}"`],recovery_guidance:"Deduplicate removed_task_ids and retry save_plan."};seen.add(id)}for(let id of rawRemovedIds)if(incomingTaskIds.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains a task that also appears in args.phases",errors:[`Task "${id}" appears in both removed_task_ids and args.phases — these are contradictory`],recovery_guidance:"A task cannot be both kept and removed in the same save_plan call. Either drop it from args.phases or remove it from removed_task_ids."};for(let id of rawRemovedIds)if(!priorTaskIds.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains an id that was not in the prior plan",errors:[`Task "${id}" is in removed_task_ids but not present in the prior plan`],recovery_guidance:"Re-read the prior plan and update removed_task_ids to only list tasks that actually existed."}}let resolvedRemovedIds=[...rawRemovedIds],resolvedRemovalReason=args2.removal_reason;if(args2.reset_statuses===!0&&missingTaskIds.length>0){if(args2.confirm_destructive_reset!==!0)return{success:!1,message:"PLAN_DESTRUCTIVE_RESET_NOT_CONFIRMED: reset_statuses with missing tasks requires confirm_destructive_reset: true",errors:[`reset_statuses: true would drop ${missingTaskIds.length} task(s) from the prior plan: ${missingTaskIds.join(", ")}`],recovery_guidance:"Surface the list of dropped tasks to the user and confirm intent before retrying. Pass confirm_destructive_reset: true (with reset_statuses: true) to acknowledge the destructive reset, or list removed_task_ids explicitly with a removal_reason."};if(rawRemovedIds.length===0)resolvedRemovedIds=[...missingTaskIds],resolvedRemovalReason="destructive reset acknowledged"}if(resolvedRemovedIds.length>0){if((resolvedRemovalReason??"").trim().length===0)return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removal_reason is required when removed_task_ids is non-empty",errors:["removal_reason must be a non-empty, non-whitespace string"],recovery_guidance:"Provide a removal_reason describing why these tasks are being dropped."}}if(missingTaskIds.length>0){let ackSet=new Set(resolvedRemovedIds),unacked=missingTaskIds.filter((id)=>!ackSet.has(id));if(unacked.length>0)return{success:!1,message:"PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: this save would silently drop tasks from the prior plan",errors:[`The following prior tasks are missing from the new save and were not listed in removed_task_ids: ${unacked.join(", ")}`],recovery_guidance:`Re-read the current plan, then retry save_plan with removed_task_ids: ${JSON.stringify(unacked)} and a non-empty removal_reason. Tasks not yet finished (status pending/in_progress/blocked) MUST NOT be removed without explicit user confirmation.`}}let plan={schema_version:"1.0.0",title:args2.title,swarm:args2.swarm_id,migration_status:"native",current_phase:args2.phases[0]?.id,specMtime,specHash,...resolvedProfile!==void 0?{execution_profile:resolvedProfile}:{},phases:args2.phases.map((phase)=>{return{id:phase.id,name:phase.name,status:"pending",tasks:phase.tasks.map((task2)=>{return{id:task2.id,phase:phase.id,status:existingStatusMap.get(task2.id)??"pending",size:task2.size??"small",description:task2.description,depends:task2.depends??[],acceptance:task2.acceptance,files_touched:[],fr_refs:task2.fr_refs}})}})},tasksCount=plan.phases.reduce((acc,phase)=>acc+phase.tasks.length,0),lockTaskId=`save-plan-${Date.now()}`,planFilePath="plan.json";try{let lockResult=await tryAcquireLock(dir,planFilePath,"architect",lockTaskId);if(!lockResult.acquired)return{success:!1,message:`Plan write blocked: file is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`,errors:["Concurrent plan write detected — retry after the current write completes"],recovery_guidance:"Wait a moment and retry save_plan. The lock will expire automatically if the holding agent fails."};try{await savePlan(dir,plan,{preserveCompletedStatuses:!args2.reset_statuses,...resolvedRemovedIds.length>0?{acknowledged_removals:{ids:resolvedRemovedIds,reason:(resolvedRemovalReason??"").trim(),source:"save_plan_tool"}}:{}});let savedPlan=await loadPlanJsonOnly(dir);if(savedPlan)await takeSnapshotWithRetry(dir,savedPlan);if(resolvedProfile!==void 0&&savedPlan){let planId=derivePlanId(plan),planHashAfter=computePlanHash(savedPlan);if(JSON.stringify(resolvedProfile)!==JSON.stringify(preservedExecutionProfile))await appendLedgerEvent(dir,{event_type:"execution_profile_set",source:"save_plan",plan_id:planId,payload:{execution_profile:resolvedProfile}},{planHashAfter}).catch(()=>{});let wasAlreadyLocked=preservedExecutionProfile?.locked===!0;if(resolvedProfile.locked&&!wasAlreadyLocked)await appendLedgerEvent(dir,{event_type:"execution_profile_locked",source:"save_plan",plan_id:planId},{planHashAfter}).catch(()=>{})}await writeCheckpoint(dir).catch(()=>{});try{let markerPath=path282.join(dir,".swarm",".plan-write-marker"),marker=JSON.stringify({source:"save_plan",timestamp:new Date().toISOString(),phases_count:plan.phases.length,tasks_count:tasksCount});await fs164.promises.writeFile(markerPath,marker,"utf8")}catch{}let warnings=[],criticReviewFound=!1;for(let[,session]of swarmState.agentSessions)if(session.phaseAgentsDispatched?.has("critic")||session.lastCompletedPhaseAgentsDispatched?.has("critic")){criticReviewFound=!0;break}if(!criticReviewFound)warnings.push("No critic review detected before plan save. Consider delegating to critic for plan validation.");if(requirementCoverage?.status==="override"){let missingIds=requirementCoverage.blocking_missing.map((requirement)=>requirement.id).join(", ");warnings.push(`Requirement coverage override used. Missing required FR mappings: ${missingIds}`)}return{success:!0,message:"Plan saved successfully",plan_path:path282.join(dir,".swarm","plan.json"),phases_count:plan.phases.length,tasks_count:tasksCount,...requirementCoverage?{requirement_coverage:requirementCoverage}:{},...resolvedProfile!==void 0?{execution_profile:resolvedProfile}:{},...warnings.length>0?{warnings}:{}}}finally{if(lockResult.acquired&&lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}catch(error93){if(error93 instanceof PlanTaskRemovalNotAcknowledgedError){let ids=error93.missingTasks.map((t)=>t.id);return{success:!1,message:"PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: this save would silently drop tasks from the prior plan",errors:[error93.message],recovery_guidance:`Re-read the current plan, then retry save_plan with removed_task_ids: ${JSON.stringify(ids)} and a non-empty removal_reason.`}}return{success:!1,message:"Failed to save plan: retry with save_plan after resolving the error above",errors:[error93 instanceof Error?error93.message:String(error93)],recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."}}}var save_plan=createSwarmTool({description:"Save or revise a structured implementation plan to .swarm/plan.json and .swarm/plan.md. "+"Use this tool for all structural plan changes on an existing plan (adding/removing tasks, updating descriptions, dependencies, or phase names) — existing task statuses are preserved by default (set reset_statuses: true to start fresh). "+"Task descriptions and phase names MUST contain real content from the spec — "+"bracket placeholders like [task] or [Project] will be rejected.",args:{title:exports_external.string().min(1).describe("Plan title — the REAL project name from the spec. NOT a placeholder like [Project]."),swarm_id:exports_external.string().min(1).describe('Swarm identifier (e.g. "mega")'),phases:exports_external.array(exports_external.object({id:exports_external.number().int().min(1).describe("Phase number — a positive integer starting at 1. Use 1, 2, 3, etc."),name:exports_external.string().min(1).describe("Descriptive phase name derived from the spec"),tasks:exports_external.array(exports_external.object({id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M format, e.g. "1.1"').describe('Task ID in N.M format, e.g. "1.1", "2.3"'),description:exports_external.string().min(1).describe("Specific task description from the spec. NOT a placeholder like [task]."),size:exports_external.enum(["small","medium","large"]).optional().describe("Task size estimate (default: small)"),depends:exports_external.array(exports_external.string()).optional().describe('Task IDs this task depends on, e.g. ["1.1", "1.2"]'),acceptance:exports_external.string().optional().describe("Acceptance criteria for this task"),fr_refs:exports_external.array(exports_external.string()).optional().describe('Spec FR-###/SC-### IDs this task maps to, e.g. ["FR-001", "SC-002"]')})).min(1).describe("Tasks in this phase")})).min(1).describe("Implementation phases"),working_directory:exports_external.string().optional().describe("Working directory (explicit path, required - no fallback)"),reset_statuses:exports_external.boolean().optional().describe("When true, reset ALL task statuses to pending regardless of prior completion state. Use only when deliberately re-planning a phase from scratch. Default false (preserves existing task statuses across plan revisions)."),removed_task_ids:exports_external.array(exports_external.string()).optional().describe("Task IDs that are present in the prior plan but intentionally being removed by this save. Every task missing from `phases` MUST be enumerated here, otherwise save_plan rejects with PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED. Tasks not yet finished (status pending/in_progress/blocked) MUST NOT be removed without explicit user confirmation."),removal_reason:exports_external.string().optional().describe("Required when removed_task_ids is non-empty. Human-readable reason recorded on each task_removed ledger event."),confirm_destructive_reset:exports_external.boolean().optional().describe("Required when reset_statuses is true AND at least one task is missing from the new plan. Set true to acknowledge that the destructive reset drops unfinished work. When set together with reset_statuses, save_plan auto-populates removed_task_ids from the missing set."),confirm_identity_change:exports_external.boolean().optional().describe("When true, allows overwriting an existing plan that has a different identity (swarm_id + title). Without this flag, save_plan rejects with PLAN_IDENTITY_MISMATCH if the identity differs."),confirm_requirement_coverage_gaps:exports_external.boolean().optional().describe("When true, allows saving a plan even when required FR-### MUST/SHALL requirements from the effective spec are not explicitly mapped in task descriptions or acceptance criteria. Use only after surfacing the structured requirement_coverage gaps to the user."),execution_profile:exports_external.object({parallelization_enabled:exports_external.boolean().optional().describe("When true, enables parallel task dispatch for this plan. Default false (serial)."),max_concurrent_tasks:exports_external.number().int().min(1).max(64).optional().describe("Maximum tasks that may run concurrently when parallelization is enabled. Default 10."),council_parallel:exports_external.boolean().optional().describe("When true, council review phases may run in parallel. Default true."),locked:exports_external.boolean().optional().describe("When true, locks the profile — future save_plan calls that include "+"execution_profile will be rejected (fail-closed). Unlock by resetting the plan (reset_statuses: true)."),auto_proceed:exports_external.boolean().optional().describe("When true, the architect advances to the next phase automatically without asking for confirmation. Default false.")}).optional().describe("Architect-facing concurrency controls. Once locked, cannot be changed without resetting. Omit to preserve the existing profile.")},execute:async(args2,_directory)=>{return JSON.stringify(await executeSavePlan(args2,_directory),null,2)}});init_zod();init_manager2();import*as fs165 from"node:fs";import*as path283 from"node:path";init_utils();init_logger();function parsePubspecLock(content){let components=[];if(!content.match(/^packages:\s*$/m))return components;let lines=content.split(`
|