opencode-swarm 7.188.9 → 7.188.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
  2. package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
  3. package/dist/cli/{auto-checkpoint-8hn7sczv.js → auto-checkpoint-kyb5rw8j.js} +5 -5
  4. package/dist/cli/{checkpoint-zagm80g6.js → checkpoint-9e3f8ers.js} +9 -9
  5. package/dist/cli/{coder-settlement-ea9wk0fa.js → coder-settlement-9j4ejab4.js} +3 -3
  6. package/dist/cli/{config-doctor-482f83pc.js → config-doctor-jd5yckkb.js} +7 -7
  7. package/dist/cli/{core-jev9px23.js → core-eyzqvwpk.js} +1 -1
  8. package/dist/cli/{curator-drift-tzr8cq9d.js → curator-drift-wyt8jf7r.js} +5 -5
  9. package/dist/cli/{curator-llm-factory-vwxengt1.js → curator-llm-factory-3b0jvvkd.js} +27 -27
  10. package/dist/cli/{curator-sw5w1yxn.js → curator-q6f0e79e.js} +27 -27
  11. package/dist/cli/{dispatch-h8m1jntz.js → dispatch-1pbmmj8z.js} +5 -7
  12. package/dist/cli/{doctor-knowledge-receipt-phase-id-78hqh9ds.js → doctor-knowledge-receipt-phase-id-19qdy72k.js} +5 -5
  13. package/dist/cli/{evidence-summary-service-dpx7844s.js → evidence-summary-service-k5ztgaca.js} +10 -10
  14. package/dist/cli/{gate-evidence-v5fbpnfe.js → gate-evidence-6gw4w2e8.js} +2 -2
  15. package/dist/cli/{guardrail-explain-020gkz5c.js → guardrail-explain-ewgj1gyw.js} +28 -28
  16. package/dist/cli/{guardrail-log-z14b98cn.js → guardrail-log-vp628cge.js} +3 -3
  17. package/dist/cli/{guardrail-reset-cg6kfk8r.js → guardrail-reset-qycc0pns.js} +27 -27
  18. package/dist/cli/{hive-promoter-bse7dh34.js → hive-promoter-z8r9xc9r.js} +27 -27
  19. package/dist/cli/{index-bzeegaem.js → index-03syhrv4.js} +2 -2
  20. package/dist/cli/{index-7jtxt3qp.js → index-0r1nrgq3.js} +1 -1
  21. package/dist/cli/{index-64e9z08z.js → index-0rd6br4q.js} +2 -2
  22. package/dist/cli/{index-0dp2ak7d.js → index-0tazb5m3.js} +1 -1
  23. package/dist/cli/{index-4xc838p0.js → index-1dhbk164.js} +1 -1
  24. package/dist/cli/{index-ng5n8tp0.js → index-1yx34x6m.js} +3 -3
  25. package/dist/cli/{index-0whh6em0.js → index-2262zz0m.js} +2 -2
  26. package/dist/cli/{index-byfk6w9a.js → index-3jx1yhqk.js} +3 -3
  27. package/dist/cli/{index-qdp9ny78.js → index-4paxe7hp.js} +1 -1
  28. package/dist/cli/{index-akkskstq.js → index-58pk41rj.js} +4 -4
  29. package/dist/cli/{index-peyrzden.js → index-5kcjrkme.js} +29 -29
  30. package/dist/cli/{index-b2g020d7.js → index-5m77ayzt.js} +1 -1
  31. package/dist/cli/{index-d1z2yrwq.js → index-66e6yba5.js} +2 -2
  32. package/dist/cli/{index-g0we5tpv.js → index-6xppxtfc.js} +4 -4
  33. package/dist/cli/{index-ps6fyxfc.js → index-8ndndvcw.js} +5 -5
  34. package/dist/cli/{index-dhkgby53.js → index-axreszvd.js} +2 -2
  35. package/dist/cli/{index-ddgmj923.js → index-bgv93ngx.js} +27 -27
  36. package/dist/cli/{index-gd602ztc.js → index-c562pan0.js} +1 -1
  37. package/dist/cli/{index-c0tjwb5k.js → index-j2vv0h13.js} +12 -12
  38. package/dist/cli/{index-q6y176gs.js → index-m0e1xjee.js} +6 -6
  39. package/dist/cli/{index-hjyakvcq.js → index-m1v2qd3z.js} +1 -1
  40. package/dist/cli/{index-v71w06rr.js → index-mzyvv3hz.js} +2 -2
  41. package/dist/cli/{index-kjb143pz.js → index-n1pntydp.js} +3 -3
  42. package/dist/cli/{index-kbkk7vnh.js → index-pkhbd2t5.js} +2 -1
  43. package/dist/cli/{index-2mmbzyqb.js → index-pqx85rk1.js} +1 -1
  44. package/dist/cli/{index-sndyex1t.js → index-rbgg2q19.js} +69 -77
  45. package/dist/cli/{index-t6tew3pf.js → index-sgawa007.js} +1 -1
  46. package/dist/cli/{index-804rs273.js → index-wh9h5vj1.js} +1 -1
  47. package/dist/cli/{index-b913b1yc.js → index-xr1bfzee.js} +1 -1
  48. package/dist/cli/{index-6nx6qf7v.js → index-yvp5c2e2.js} +1 -1
  49. package/dist/cli/{index-cxybg712.js → index-z55btbf2.js} +2 -2
  50. package/dist/cli/{index-0e49htcs.js → index-zpsc691s.js} +1 -1
  51. package/dist/cli/index.js +28 -28
  52. package/dist/cli/{knowledge-escalator-wah5yybk.js → knowledge-escalator-1hk1sxaj.js} +8 -8
  53. package/dist/cli/{knowledge-events-akz8013r.js → knowledge-events-12jxfydt.js} +6 -6
  54. package/dist/cli/{knowledge-store-hy12373e.js → knowledge-store-xr64wqmj.js} +1 -1
  55. package/dist/cli/{knowledge-validator-yrqkdt1w.js → knowledge-validator-978b1j5n.js} +2 -2
  56. package/dist/cli/{mcp-0srnsd05.js → mcp-qxwxzchp.js} +1 -1
  57. package/dist/cli/{model-preflight-m3v8hn9k.js → model-preflight-b9mbnymf.js} +27 -27
  58. package/dist/cli/{pending-delegations-40txwk2h.js → pending-delegations-0ej13k7z.js} +2 -2
  59. package/dist/cli/{pr-subscriptions-w6n5s9c7.js → pr-subscriptions-c35gt902.js} +1 -1
  60. package/dist/cli/{pr-workflow-gate-mx9t1p5j.js → pr-workflow-gate-a17sdc22.js} +27 -27
  61. package/dist/cli/{scan-cursor-phbwfaya.js → scan-cursor-a9y3qfj0.js} +2 -2
  62. package/dist/cli/{schema-t1xwd728.js → schema-dn0247wt.js} +1 -1
  63. package/dist/cli/{scope-persistence-m6qrwt3d.js → scope-persistence-v62cew31.js} +5 -5
  64. package/dist/cli/{server-7pt2zhnc.js → server-tna0jzhz.js} +27 -27
  65. package/dist/cli/{skill-generator-pnv8efrw.js → skill-generator-yr4dc37y.js} +9 -9
  66. package/dist/cli/{snapshot-coordination-init-514wtctt.js → snapshot-coordination-init-f2dsrgvy.js} +27 -27
  67. package/dist/cli/{speckit-checkoff-beh1nw7v.js → speckit-checkoff-gwjz28vf.js} +3 -3
  68. package/dist/cli/{worktree-collision-ownership-f5wca0gg.js → worktree-collision-ownership-p7g40dpp.js} +2 -2
  69. package/dist/cli/{worktree-isolation-bd6c5x8h.js → worktree-isolation-f76g3j4v.js} +27 -27
  70. package/dist/config/evidence-schema.d.ts +3 -0
  71. package/dist/index.js +8 -8
  72. package/dist/lang/backend.d.ts +7 -0
  73. package/dist/lang/default-backend.d.ts +25 -0
  74. package/dist/tools/build-check.d.ts +13 -0
  75. package/dist/turbo/lean/phase-ready.d.ts +15 -1
  76. package/dist/utils/windows-batch.d.ts +9 -4
  77. 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.188.9",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",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; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.188.11",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",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; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -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(),diff_scoped:exports_external.boolean().optional(),added_lines_files:exports_external.number().int().min(0).optional(),added_lines_total:exports_external.number().int().min(0).optional()}),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(),moved_findings:exports_external.array(SastFindingSchema).optional(),baseline_used:exports_external.boolean().optional(),truncated_pre_existing:exports_external.boolean().optional(),truncated_moved_findings: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(),environment_unavailable:exports_external.array(exports_external.object({ecosystem:exports_external.string(),reason:exports_external.string(),code:exports_external.literal("environment_unavailable"),required_commands:exports_external.array(exports_external.string()).optional()})).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(),base_resolved:exports_external.boolean().default(!1)}),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),policy_skipped_files:exports_external.number().int().min(0).optional(),requested_files:exports_external.number().int().min(0).optional(),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 roundMs(value){return Math.round(value*10)/10}function emitContractRow(payload){try{if(!_internals.isDebugEnabled())return;_internals.emitLine(`STARTUP-CONTRACT ${JSON.stringify(payload)}`)}catch{}}function boundErrorText(err){let text="unknown error";try{text=err instanceof Error?err.message:String(err)}catch{}return text=text.replace(/\s+/g," ").trim().slice(0,200),text}function isPromiseLike(value){return typeof value==="object"&&value!==null&&typeof value.then==="function"}function markStartupImportComplete(){if(state.importMarkMs!==null)return;state.importMarkMs=_internals.performance.now()}function beginStartupServerInterval(){state.serverStartMark=_internals.performance.now(),state.serverResolvedMark=null,state.serverMs=null,state.queueScheduledAt=null,state.queuePending=0,state.queueTasks=0,state.queueCompleted=0,state.queueFailed=0,state.queueSettled=!1,state.queueSettledMs=null,state.advisoryCount=0,state.advisoryWindowOpen=!0,state.firstTurnDone=!1,state.firstToolDone=!1,state.firstToolName=null,state.firstTurnMs=null,state.firstToolMs=null}function endStartupServerInterval(){if(state.serverStartMark===null)return;let now=_internals.performance.now();if(state.serverResolvedMark=now,state.serverMs=roundMs(now-state.serverStartMark),state.queueScheduledAt===null)state.advisoryWindowOpen=!1;emitContractRow({v:1,stage:"init",importMs:state.importMarkMs===null?null:roundMs(state.importMarkMs),serverMs:state.serverMs})}function noteQueueScheduled(){state.queueScheduledAt=_internals.performance.now()}function maybeEmitQueueSettled(){if(state.queueSettled||state.queueScheduledAt===null)return;if(state.queueTasks===0||state.queuePending>0)return;state.queueSettled=!0;let now=_internals.performance.now();state.queueSettledMs=state.queueScheduledAt===null?null:roundMs(now-state.queueScheduledAt),state.advisoryWindowOpen=!1,emitContractRow({v:1,stage:"queue_settled",tasks:state.queueTasks,completed:state.queueCompleted,failed:state.queueFailed,ms:state.queueSettledMs,advisories:state.advisoryCount})}function recordTaskOutcome(name,outcome,ms,err){if(state.queuePending-=1,outcome==="completed")state.queueCompleted+=1;else state.queueFailed+=1;let row={v:1,stage:"optional_task",task:name,outcome,ms:roundMs(ms)};if(outcome==="failed")row.error=boundErrorText(err);emitContractRow(row),maybeEmitQueueSettled()}function wrapPostResolutionTask(task){let name=task.name||"anonymous";state.queueTasks+=1,state.queuePending+=1;let wrapped=async()=>{let startedAt=_internals.performance.now();try{await task(),recordTaskOutcome(name,"completed",_internals.performance.now()-startedAt)}catch(err){throw recordTaskOutcome(name,"failed",_internals.performance.now()-startedAt,err),err}};try{Object.defineProperty(wrapped,"name",{value:name,configurable:!0})}catch{}return wrapped}function noteFirstUseSettled(stage,label){try{if(stage==="first_turn"){if(state.firstTurnDone)return;state.firstTurnDone=!0,state.firstTurnMs=state.serverResolvedMark===null?null:roundMs(_internals.performance.now()-state.serverResolvedMark),emitContractRow({v:1,stage:"first_turn",ms:state.firstTurnMs})}else{if(state.firstToolDone)return;state.firstToolDone=!0,state.firstToolName=label??null,state.firstToolMs=state.serverResolvedMark===null?null:roundMs(_internals.performance.now()-state.serverResolvedMark),emitContractRow({v:1,stage:"first_tool",tool:state.firstToolName,ms:state.firstToolMs})}}catch{}}function withStartupFirstUseTracking(stage,label,handler){let tracked=(...args2)=>{let result=handler(...args2),settle=()=>noteFirstUseSettled(stage,label);if(isPromiseLike(result))Promise.resolve(result).then(settle,settle);else settle();return result};try{Object.defineProperty(tracked,"name",{value:handler.name||`tracked${stage}`,configurable:!0})}catch{}return tracked}function withStartupFirstToolTracking(name,execute){let tracked=(args2,ctx)=>{let result=execute(args2,ctx),settle=()=>noteFirstUseSettled("first_tool",name);if(isPromiseLike(result))Promise.resolve(result).then(settle,settle);else settle();return result};try{Object.defineProperty(tracked,"name",{value:execute.name||"trackedFirstToolExecute",configurable:!0})}catch{}return tracked}function noteStartupAdvisory(){if(!state.advisoryWindowOpen)return;state.advisoryCount+=1}var state,_internals;var init_startup_contract=__esm(()=>{state={importMarkMs:null,serverStartMark:null,serverResolvedMark:null,serverMs:null,queueScheduledAt:null,queuePending:0,queueTasks:0,queueCompleted:0,queueFailed:0,queueSettled:!1,queueSettledMs:null,advisoryCount:0,advisoryWindowOpen:!1,firstTurnDone:!1,firstToolDone:!1,firstToolName:null,firstTurnMs:null,firstToolMs:null};_internals={performance,isDebugEnabled:()=>process.env.OPENCODE_SWARM_DEBUG==="1",emitLine:(line)=>{console.log(line)}}});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){noteStartupAdvisory();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_startup_contract();init_logger();deferredWarnings=[],CONTROL_CHARS_RE=/[\x00-\x1F\x7F-\x9F]/g});import{spawnSync}from"node:child_process";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";function excerptProbeOutput(raw){return raw.slice(0,PROBE_OUTPUT_EXCERPT_CHARS).replace(/[^\x20-\x7E]/g," ").trim()}function unique(values){return[...new Set(values.filter(Boolean))]}function envOverride(){let raw=_internals2.env()[GIT_BINARY_ENV_VAR];return raw&&raw.trim()!==""?raw:void 0}function effectiveOverride(){return envOverride()??configuredOverride}function overrideSource(){if(envOverride()!==void 0)return"env";if(configuredOverride!==void 0)return"config";return}function isAbsoluteForPlatform(candidate,platform){return platform==="win32"?path.win32.isAbsolute(candidate):path.posix.isAbsolute(candidate)}function windowsPlatformCandidates(){let env=_internals2.env(),installed=unique([env.ProgramFiles??"",env["ProgramFiles(x86)"]??"",env.LOCALAPPDATA?`${env.LOCALAPPDATA}\\Programs`:""]).flatMap((root)=>[`${root}\\Git\\cmd\\git.exe`,`${root}\\Git\\bin\\git.exe`]);return unique(installed)}function platformCandidates(platform){if(platform==="darwin")return["/opt/homebrew/bin/git","/usr/local/bin/git","/usr/bin/git"];if(platform==="win32")return windowsPlatformCandidates();return["/usr/bin/git","/usr/local/bin/git","/bin/git"]}function pathDelimiterFor(platform){return platform==="win32"?";":":"}function joinDirAndName(dir,name,platform){let sep=platform==="win32"?"\\":"/",trimmed=dir.replace(/[\\/]+$/,"");return trimmed?`${trimmed}${sep}${name}`:`${sep}${name}`}function pathCandidates(platform){let pathValue=_internals2.env().PATH??"";if(!pathValue)return[];let dirs=pathValue.split(pathDelimiterFor(platform)).filter(Boolean),names=platform==="win32"?[...WINDOWS_PATH_EXTENSIONS.map((ext)=>`git${ext}`),"git"]:["git"],out=[];for(let dir of dirs)for(let name of names)out.push(joinDirAndName(dir,name,platform));return unique(out)}function buildCandidates(platform){let override=effectiveOverride(),overrideCandidate=override?[{source:"override",path:override}]:[],seen=new Set(overrideCandidate.map((c)=>c.path)),rest=[];for(let p of platformCandidates(platform)){if(seen.has(p))continue;seen.add(p),rest.push({source:"platform",path:p})}for(let p of pathCandidates(platform)){if(seen.has(p))continue;seen.add(p),rest.push({source:"path",path:p})}return[...overrideCandidate,...rest]}function probeCandidate(candidatePath,platform){if(!isAbsoluteForPlatform(candidatePath,platform))return{accepted:!1,reason:"not an absolute path"};let stat;try{stat=fs.statSync(candidatePath)}catch(err){let code=err?.code;if(code==="ENOENT")return{accepted:!1,reason:"no such file"};return{accepted:!1,reason:`cannot stat (${code??"unknown error"})`}}if(stat.isDirectory())return{accepted:!1,reason:"is a directory"};if(!stat.isFile())return{accepted:!1,reason:"not a regular file"};let result;try{result=_internals2.spawnSync(candidatePath,["--version"],{cwd:os.tmpdir(),stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:PER_PROBE_TIMEOUT_MS,maxBuffer:PROBE_MAX_BUFFER_BYTES})}catch(err){return{accepted:!1,reason:`spawn threw: ${err instanceof Error?err.message:String(err)}`}}if(result.error)return{accepted:!1,reason:`spawn failed: ${result.error.message}`};if(result.status!==0)return{accepted:!1,reason:`git --version returned ${result.status!==null?`exit ${result.status}`:`signal ${result.signal??"unknown"}`}`};let versionOutput=(result.stdout??"").toString().trim();if(!GIT_VERSION_PATTERN.test(versionOutput)){let excerpt=excerptProbeOutput(versionOutput);return{accepted:!1,reason:excerpt?`not git: --version printed "${excerpt}"`:"not git: --version printed nothing"}}return{accepted:!0}}function*probeCycle(candidates,platform,attempts){let start=_internals2.now(),budgetExceeded=!1;for(let candidate of candidates){if(_internals2.now()-start>TOTAL_BUDGET_MS){budgetExceeded=!0;break}let result=probeCandidate(candidate.path,platform);if(attempts.push({source:candidate.source,candidate:candidate.path,accepted:result.accepted,reason:result.reason}),candidate.source==="override"&&!result.accepted)advisoryWarn(`[opencode-swarm] git.binary override "${candidate.path}" is unusable (${result.reason}); falling back to automatic git resolution.`);if(result.accepted)return{outcome:"accepted",path:candidate.path};yield}return budgetExceeded?{outcome:"exhausted-budget"}:{outcome:"all-rejected"}}function driveSync(gen){let step=gen.next();while(!step.done)step=gen.next();return step.value}async function driveAsync(gen){let step=gen.next();while(!step.done)await _internals2.yieldToEventLoop(),step=gen.next();return step.value}function readCache(){if(cache===null)return null;if(cache.kind==="success")return cache;if(_internals2.now()<cache.expiresAt)return cache;return cache=null,null}function applyProbeResult(result,attempts,generation){if(generation!==cacheGeneration)return result.outcome==="accepted"?result.path:BARE_GIT;if(lastAttempts=attempts,result.outcome==="accepted")return cache={kind:"success",path:result.path},result.path;return cache={kind:"fallback",expiresAt:_internals2.now()+NEGATIVE_CACHE_TTL_MS},BARE_GIT}function resolveGitExecutable(){let cached2=readCache();if(cached2)return cached2.kind==="success"?cached2.path:BARE_GIT;let platform=_internals2.platform(),attempts=[],generation=cacheGeneration,candidates=buildCandidates(platform),result=driveSync(probeCycle(candidates,platform,attempts));return applyProbeResult(result,attempts,generation)}async function resolveGitExecutableAsync(){let cached2=readCache();if(cached2)return cached2.kind==="success"?cached2.path:BARE_GIT;if(inFlightAsync)return inFlightAsync;let platform=_internals2.platform(),attempts=[],generation=cacheGeneration,candidates=buildCandidates(platform),run=(async()=>{let result=await driveAsync(probeCycle(candidates,platform,attempts));return applyProbeResult(result,attempts,generation)})();inFlightAsync=run;try{return await run}finally{if(inFlightAsync===run)inFlightAsync=null}}function resetGitExecutableCache(){cache=null,lastAttempts=[],inFlightAsync=null,cacheGeneration++}function setGitBinaryOverride(value){let normalized=value&&value.trim()!==""?value:void 0;if(normalized===configuredOverride)return;configuredOverride=normalized,resetGitExecutableCache()}function describeGitResolution(){let cached2=cache;return{resolved:cached2?.kind==="success",resolvedPath:cached2?.kind==="success"?cached2.path:void 0,attempts:[...lastAttempts],overrideValue:effectiveOverride(),overrideSource:overrideSource()}}var GIT_BINARY_ENV_VAR="OPENCODE_SWARM_GIT_BINARY",PER_PROBE_TIMEOUT_MS=250,TOTAL_BUDGET_MS=1000,NEGATIVE_CACHE_TTL_MS=60000,BARE_GIT="git",PROBE_MAX_BUFFER_BYTES=65536,WINDOWS_PATH_EXTENSIONS,GIT_VERSION_PATTERN,PROBE_OUTPUT_EXCERPT_CHARS=60,cache=null,lastAttempts,configuredOverride,inFlightAsync=null,cacheGeneration=0,_internals2;var init_git_executable=__esm(()=>{init_warning_buffer();WINDOWS_PATH_EXTENSIONS=[".exe",".cmd",".bat"],GIT_VERSION_PATTERN=/^git version \d+\.\d+/;lastAttempts=[];_internals2={spawnSync,platform:()=>process.platform,env:()=>process.env,now:()=>Date.now(),yieldToEventLoop:()=>new Promise((resolve)=>setTimeout(resolve,0))}});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(path2,prefix){if(prefix.length>path2.length)return!1;for(let i=0;i<prefix.length;i++)if(path2[i]!==prefix[i])return!1;return!0}function removeAtPath(obj,path2){if(path2.length===0)return!1;let node=obj;for(let i=0;i<path2.length-1;i++){if(node===null||node===void 0||typeof node!=="object")return!1;let key=path2[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=path2[path2.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(path2,issues){let key=keyOf(path2);for(let issue2 of issues)if(keyOf(issue2.path)===key)return{path:path2,code:issue2.code,message:issue2.message};return{path:path2,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"])});function normalizeLimitKey(key){return key.trim().toLowerCase()}function isUsableConfiguredWindow(value){return typeof value==="number"&&Number.isFinite(value)&&value>=1}function isUsableContextWindow(value){return typeof value==="number"&&Number.isFinite(value)&&value>=1000}function readModelContextLimit(model){if(typeof model!=="object"||model===null)return;let limit=model.limit;if(typeof limit!=="object"||limit===null)return;return limit.context}function readModelIdentity(model,key){if(typeof model!=="object"||model===null)return;let value=model[key];return typeof value==="string"&&value.length>0?value:void 0}function resolveContextWindow(inputs){let{userLimits,modelID,providerID,liveContextLimit,fallbackLookup}=inputs;if(userLimits){let normalized,normalizedLimits=()=>{if(normalized===void 0){normalized={};for(let[key,value]of Object.entries(userLimits))normalized[normalizeLimitKey(key)]=value}return normalized};if(modelID&&providerID){let compound=normalizedLimits()[normalizeLimitKey(`${providerID}/${modelID}`)];if(isUsableConfiguredWindow(compound))return{tokens:Math.floor(compound),source:"user_provider_model"}}if(modelID){let byModel=normalizedLimits()[normalizeLimitKey(modelID)];if(isUsableConfiguredWindow(byModel))return{tokens:Math.floor(byModel),source:"user_model"}}let byDefault=normalizedLimits().default;if(isUsableConfiguredWindow(byDefault))return{tokens:Math.floor(byDefault),source:"user_default"}}if(isUsableContextWindow(liveContextLimit))return{tokens:Math.floor(liveContextLimit),source:"live_model_limit"};if(fallbackLookup){let fromTable=fallbackLookup(modelID,providerID);if(fromTable!==void 0&&isUsableContextWindow(fromTable.tokens))return{tokens:Math.floor(fromTable.tokens),source:fromTable.table==="provider_cap"?"static_provider_cap":"static_native"}}return{tokens:128000,source:"static_default"}}function resolveContextWindowTokens(inputs){return resolveContextWindow(inputs).tokens}var DEFAULT_MODEL_CONTEXT_TOKENS=128000;var exports_schema={};__export(exports_schema,{stripKnownSwarmPrefix:()=>stripKnownSwarmPrefix,resolveGuardrailsConfig:()=>resolveGuardrailsConfig,resolveGeneratedAgentRole:()=>resolveGeneratedAgentRole,resolveExternalSkillsConfig:()=>resolveExternalSkillsConfig,resolveAutoReviewConfig:()=>resolveAutoReviewConfig,isKnownCanonicalRole:()=>isKnownCanonicalRole,getCanonicalAgentRole:()=>getCanonicalAgentRole,_internals:()=>_internals3,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,ReviewRoutingConfigSchema:()=>ReviewRoutingConfigSchema,ReviewPassesConfigSchema:()=>ReviewPassesConfigSchema,RetentionConfigSchema:()=>RetentionConfigSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QualityBudgetConfigSchema:()=>QualityBudgetConfigSchema,PrmConfigSchema:()=>PrmConfigSchema,PricingConfigSchema:()=>PricingConfigSchema,PrReviewResilienceConfigSchema:()=>PrReviewResilienceConfigSchema,PrMonitorConfigSchema:()=>PrMonitorConfigSchema,PrFeedbackLoopConfigSchema:()=>PrFeedbackLoopConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanCursorConfigSchema:()=>PlanCursorConfigSchema,PlaceholderScanConfigSchema:()=>PlaceholderScanConfigSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,ParallelizationConfigSchema:()=>ParallelizationConfigSchema,OtlpExportConfigSchema:()=>OtlpExportConfigSchema,ObservabilityConfigSchema:()=>ObservabilityConfigSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LintConfigSchema:()=>LintConfigSchema,LearningConfigSchema:()=>LearningConfigSchema,LeanTurboStrategyConfigSchema:()=>LeanTurboStrategyConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,LaneLivenessWatchdogConfigSchema:()=>LaneLivenessWatchdogConfigSchema,KnowledgeConfigSchema:()=>KnowledgeConfigSchema,KnowledgeApplicationConfigSchema:()=>KnowledgeApplicationConfigSchema,IntegrationAnalysisConfigSchema:()=>IntegrationAnalysisConfigSchema,IncrementalVerifyConfigSchema:()=>IncrementalVerifyConfigSchema,HooksConfigSchema:()=>HooksConfigSchema,HarnessOptConfigSchema:()=>HarnessOptConfigSchema,HarnessEvolutionConfigSchema:()=>HarnessEvolutionConfigSchema,GuardrailsProfileSchema:()=>GuardrailsProfileSchema,GuardrailsConfigSchema:()=>GuardrailsConfigSchema,GitConfigSchema:()=>GitConfigSchema,GeneralCouncilConfigSchema:()=>GeneralCouncilConfigSchema,GateFeatureSchema:()=>GateFeatureSchema,GateConfigSchema:()=>GateConfigSchema,GATE_SECTION_SCHEMAS:()=>GATE_SECTION_SCHEMAS,GATE_CONFIG_READERS:()=>GATE_CONFIG_READERS,GATE_CONFIG_KNOWN_SECTION_KEYS:()=>GATE_CONFIG_KNOWN_SECTION_KEYS,ForgeConfigSchema:()=>ForgeConfigSchema,FALLBACK_MODELS_MAX:()=>FALLBACK_MODELS_MAX,ExternalSkillsConfigSchema:()=>ExternalSkillsConfigSchema,ExternalSkillCandidateSourceTypeSchema:()=>ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateSchema:()=>ExternalSkillCandidateSchema,ExternalSkillCandidateEvaluationVerdictSchema:()=>ExternalSkillCandidateEvaluationVerdictSchema,EvidenceConfigSchema:()=>EvidenceConfigSchema,EpicConfigSchema:()=>EpicConfigSchema,DocsConfigSchema:()=>DocsConfigSchema,DispatchProtectionConfigSchema:()=>DispatchProtectionConfigSchema,DiscoverySourceSchema:()=>DiscoverySourceSchema,DesignDocsConfigSchema:()=>DesignDocsConfigSchema,DecisionDecaySchema:()=>DecisionDecaySchema,DashboardConfigSchema:()=>DashboardConfigSchema,DEFAULT_SKILL_OPT_CONFIG:()=>DEFAULT_SKILL_OPT_CONFIG,DEFAULT_SKILLS_CONFIG:()=>DEFAULT_SKILLS_CONFIG,DEFAULT_REVIEW_ROUTING_CONFIG:()=>DEFAULT_REVIEW_ROUTING_CONFIG,DEFAULT_PR_REVIEW_RESILIENCE_CONFIG:()=>DEFAULT_PR_REVIEW_RESILIENCE_CONFIG,DEFAULT_PR_REVIEW_LEGACY_TRANSCRIPT_COMPATIBILITY:()=>DEFAULT_PR_REVIEW_LEGACY_TRANSCRIPT_COMPATIBILITY,DEFAULT_MODEL_CONTEXT_TOKENS:()=>DEFAULT_MODEL_CONTEXT_TOKENS,DEFAULT_HARNESS_OPT_CONFIG:()=>DEFAULT_HARNESS_OPT_CONFIG,DEFAULT_HARNESS_EVOLUTION_CONFIG:()=>DEFAULT_HARNESS_EVOLUTION_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,CONSERVATIVE_PRESET_BASE:()=>CONSERVATIVE_PRESET_BASE,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 _internals3.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={}){if(context.preset==="conservative")return!1;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=_internals3.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 _internals3,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_SECTION_SCHEMAS,GateConfigSchema,GATE_CONFIG_KNOWN_SECTION_KEYS,GATE_CONFIG_READERS,PipelineConfigSchema,PhaseCompleteConfigSchema,SummaryConfigSchema,RetentionConfigSchema,ReviewPassesConfigSchema,AUTO_REVIEW_V8_BURN_IN_DECISION,CONSERVATIVE_PRESET_BASE,AutoReviewFinalConfigSchema,AutoReviewConfigObjectSchema,AutoReviewConfigSchema,AdversarialDetectionConfigSchema,AdversarialTestingConfigSchemaBase,AdversarialTestingConfigSchema,IntegrationAnalysisConfigSchema,DocsConfigSchema,DesignDocsConfigSchema,GitConfigSchema,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,OtlpExportConfigSchema,ObservabilityConfigSchema,ForgeConfigSchema,MemoryConfigSchema,CuratorConfigSchema,ArchitecturalSupervisionConfigSchema,KnowledgeApplicationConfigSchema,SkillPropagationAudienceSchema,SkillPropagationConfigSchema,HarnessRelativePathSchema,HarnessEvolutionConfigSchema,DEFAULT_HARNESS_EVOLUTION_CONFIG,HarnessOptConfigSchema,DEFAULT_HARNESS_OPT_CONFIG,SkillImproverConfigSchema,SkillsConfigSchema,SkillOptConfigSchema,DEFAULT_SKILL_OPT_CONFIG,SpecWriterConfigSchema,SlopDetectorConfigSchema,IncrementalVerifyConfigSchema,CompactionConfigSchema,PrmConfigSchema,AgentAuthorityRuleSchema,AuthorityConfigSchema,GeneralCouncilMemberConfigSchema,GeneralCouncilConfigSchema,CouncilConfigSchema,PrMonitorConfigSchema,PrFeedbackLoopConfigSchema,ParallelizationConfigSchema,WorktreeIsolationConfigSchema,LeanTurboConfigSchema,EpicConfigSchema,StandardTurboConfigSchema,LeanTurboStrategyConfigSchema,TurboConfigSchema,ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateEvaluationVerdictSchema,DiscoverySourceSchema,ExternalSkillCandidateSchema,ExternalSkillsConfigSchema,DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_SKILLS_CONFIG,DEFAULT_PR_REVIEW_RESILIENCE_CONFIG,PrReviewResilienceConfigSchema,ReviewRoutingConfigSchema,DEFAULT_REVIEW_ROUTING_CONFIG,LaneLivenessWatchdogConfigSchema,DispatchProtectionConfigSchema,DashboardConfigSchema,DEFAULT_PR_REVIEW_LEGACY_TRANSCRIPT_COMPATIBILITY=!1,PluginConfigSchema;var init_schema=__esm(()=>{init_zod();init_package();init_knowledge_types();init_constants();_internals3={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({currency:exports_external.literal("USD").optional().default("USD"),version:exports_external.string().min(1).max(128).optional(),effective_at:exports_external.string().datetime().optional(),billing_basis:exports_external.enum(["token","request","subscription"]).optional(),reported_cost_currency:exports_external.record(exports_external.string().min(1).max(128),exports_external.literal("USD")).optional().default({}),subscription_unbilled:exports_external.boolean().optional().default(!1),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({}),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_SECTION_SCHEMAS={syntax_check:GateFeatureSchema,placeholder_scan:PlaceholderScanConfigSchema,sast_scan:GateFeatureSchema,sbom_generate:GateFeatureSchema,build_check:GateFeatureSchema,quality_budget:QualityBudgetConfigSchema},GateConfigSchema=exports_external.object({syntax_check:GATE_SECTION_SCHEMAS.syntax_check.default({enabled:!0}),placeholder_scan:GATE_SECTION_SCHEMAS.placeholder_scan.default(()=>GATE_SECTION_SCHEMAS.placeholder_scan.parse({})),sast_scan:GATE_SECTION_SCHEMAS.sast_scan.default({enabled:!0}),sbom_generate:GATE_SECTION_SCHEMAS.sbom_generate.default({enabled:!0}),build_check:GATE_SECTION_SCHEMAS.build_check.default({enabled:!0}),quality_budget:GATE_SECTION_SCHEMAS.quality_budget.default(()=>GATE_SECTION_SCHEMAS.quality_budget.parse({}))}),GATE_CONFIG_KNOWN_SECTION_KEYS=Object.fromEntries(Object.entries(GATE_SECTION_SCHEMAS).map(([section,schema])=>[section,Object.keys(schema.shape)])),GATE_CONFIG_READERS={syntax_check:["src/tools/syntax-check.ts"],placeholder_scan:["src/tools/placeholder-scan.ts"],sast_scan:["src/tools/sast-scan.ts","src/tools/pre-check-batch.ts"],sbom_generate:["src/tools/sbom-generate.ts"],build_check:["src/tools/build-check.ts"],quality_budget:["src/tools/quality-budget.ts","src/tools/pre-check-batch.ts"]},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])}),RetentionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),dry_run:exports_external.boolean().default(!1)}).prefault({}),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"};CONSERVATIVE_PRESET_BASE={auto_review:{enabled:!1}},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()}),GitConfigSchema=exports_external.object({binary: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),sandbox_macos_enabled:exports_external.boolean().optional(),sandbox:exports_external.object({mode:exports_external.enum(["advisory","required"]).default("advisory"),require_filesystem:exports_external.boolean().default(!1),require_network:exports_external.boolean().default(!1),require_process:exports_external.boolean().default(!1),network_mode:exports_external.enum(["off","on"]).default("off"),network_allowlist:exports_external.array(exports_external.string().min(1)).max(128).default([]),writable_roots:exports_external.array(exports_external.string().min(1)).max(128).default([])}).optional()}),WatchdogConfigSchema=exports_external.object({scope_guard:exports_external.boolean().default(!0),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([]),storage:exports_external.enum(["json","indexed"]).default("json")}),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("Number of completed tasks that trigger an automatic checkpoint. Retention of old checkpoints is controlled separately by max_retention."),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),receipt_close_grace_days:exports_external.number().int().min(0).max(3650).default(7),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)}),OtlpExportConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),endpoint:exports_external.string().min(1).default(""),convention:exports_external.enum(["genai","openinference"]).default("genai"),headers:exports_external.record(exports_external.string(),exports_external.string()).optional(),batchSize:exports_external.number().int().min(1).max(512).default(64),flushIntervalMs:exports_external.number().int().min(250).max(300000).default(5000),requestTimeoutMs:exports_external.number().int().min(250).max(60000).default(5000),spoolMaxBytes:exports_external.number().int().min(16384).max(16777216).default(1048576),spoolMaxAgeMs:exports_external.number().int().min(60000).max(2592000000).default(86400000),maxRetries:exports_external.number().int().min(0).max(10).default(3),backoffBaseMs:exports_external.number().int().min(10).max(1e4).default(200),backoffMaxMs:exports_external.number().int().min(100).max(300000).default(30000),circuitThreshold:exports_external.number().int().min(1).max(50).default(5),circuitCooldownMs:exports_external.number().int().min(1000).max(600000).default(60000)}),ObservabilityConfigSchema=exports_external.object({export:OtlpExportConfigSchema.optional()}),ForgeConfigSchema=exports_external.object({provider:exports_external.enum(["github","gitlab","auto"]).default("auto"),base_url:exports_external.string().url().optional()}),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}}),reflection:exports_external.object({enabled:exports_external.boolean().default(!1),halfLifeDays:exports_external.number().finite().positive().max(3650).default(30)}).default({enabled:!1,halfLifeDays:30}),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),detectPii:exports_external.boolean().default(!1),piiDetector:exports_external.enum(["regex","ner"]).default("regex"),rejectDurablePii:exports_external.boolean().default(!1),piiThreshold:exports_external.number().min(0).max(1).refine((v)=>v<1,"piiThreshold must be strictly less than 1 (rejection is score > threshold and scores never reach 1, so 1 would silently disable PII rejection)").default(0.7)}).default({rejectDurableSecrets:!0,detectPii:!1,piiDetector:"regex",rejectDurablePii:!1,piiThreshold:0.7}),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([])}),HarnessRelativePathSchema=exports_external.string().min(1).max(1024).refine((value)=>!value.includes("\x00"),"path contains a NUL byte").refine((value)=>!/^(?:[A-Za-z]:[\\/]|[\\/]{1,2})/.test(value),{message:"path must be project-relative"}).refine((value)=>!value.replace(/\\/g,"/").split("/").some((segment)=>segment===".."),"path must not traverse outside the project"),HarnessEvolutionConfigSchema=exports_external.object({source_allowlist:exports_external.array(HarnessRelativePathSchema).max(128).default([]),extra_protected_paths:exports_external.array(HarnessRelativePathSchema).max(128).default([]),max_patch_bytes:exports_external.number().int().min(1).max(16777216).default(1048576),max_files:exports_external.number().int().min(1).max(1024).default(64),max_file_bytes:exports_external.number().int().min(1).max(8388608).default(524288),max_total_bytes:exports_external.number().int().min(1).max(67108864).default(4194304),max_changed_lines:exports_external.number().int().min(1).max(1e5).default(1e4),max_versions:exports_external.number().int().min(1).max(1e4).default(100),max_inactive_candidates:exports_external.number().int().min(0).max(128).default(32),max_replay_records:exports_external.number().int().min(1).max(1e5).default(1e4),max_output_bytes:exports_external.number().int().min(1024).max(1048576).default(262144)}).strict(),DEFAULT_HARNESS_EVOLUTION_CONFIG=Object.freeze(HarnessEvolutionConfigSchema.parse({})),HarnessOptConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),max_rounds:exports_external.number().int().min(1).max(50).default(5),max_transient_retries:exports_external.number().int().min(0).max(10).default(2),max_wall_clock_ms:exports_external.number().int().min(1e4).max(86400000).default(3600000),max_spend_usd:exports_external.number().finite().nonnegative().max(1000).optional(),run_ablation_arm:exports_external.boolean().default(!0),run_simple_agent_arm:exports_external.boolean().default(!0)}).strict(),DEFAULT_HARNESS_OPT_CONFIG=Object.freeze(HarnessOptConfigSchema.parse({})),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(10)}).default(()=>({repetition_loop:2,ping_pong:2,expansion_drift:3,stuck_on_test:3,context_thrash:10})),max_trajectory_lines:exports_external.number().min(10).max(1e4).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).describe("DEPRECATED — inert. Accepted for parse compatibility only; no runtime consumer exists and no timeout is enforced. Config doctor warns when this is explicitly set. Remove the key; dispatch timeouts are governed by the agent host. Scheduled for removal in a future release."),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 (task/phase councils only — the final council uses finalCompletionPolicy). 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 declared for escalation when maxRounds is reached without APPROVE. REMAINS INERT — no handler or webhook execution exists or is added; config doctor warns when it is set (issue #1650). Max-rounds exhaustion emits a durable structured event and a user escalation message; wiring real outbound escalation requires a separate security review."),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."),finalCompletionPolicy:exports_external.object({mode:exports_external.enum(["all_required","quorum"]).default("all_required").describe("'all_required' (default) preserves the exact legacy final council: all five canonical roles, five distinct members, zero absentees. 'quorum' is an explicit weakening that accepts a bounded minimum of distinct canonical members instead of all five."),minimumMembers:exports_external.number().int().min(3).max(5).optional().describe('Required when mode is "quorum": minimum distinct canonical council members (3–5) that must vote. Unknown, duplicate, and cross-swarm identities never count.')}).default({mode:"all_required"}).superRefine((policy,ctx)=>{if(policy.mode==="quorum"&&policy.minimumMembers===void 0)ctx.addIssue({code:"custom",path:["minimumMembers"],message:'finalCompletionPolicy.mode "quorum" requires an explicit minimumMembers between 3 and 5.'})}).describe("Final-council completion policy. Missing/default is all_required (strict five-member requirement). The normalized policy participates in the council policy digest, so any change invalidates previously accepted final-council evidence."),freshnessMaxAgeHours:exports_external.number().int().min(1).max(720).default(24).describe("Maximum age (hours, 1–720) of phase-council, architecture-supervisor, and final-council evidence. Default 24 preserves prior behavior. Part of the council policy digest, so changing it invalidates prior council evidence."),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(),PrFeedbackLoopConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),max_actions_per_pr:exports_external.number().int().min(1).max(10).default(3),max_session_actions:exports_external.number().int().min(1).max(50).default(10),publication:exports_external.enum(["none"]).default("none")}),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),session_create_timeout_ms:exports_external.number().int().min(1000).max(120000).default(30000),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};DEFAULT_PR_REVIEW_RESILIENCE_CONFIG={enabled:!1,canary_probe_ms:300000,status_probe_timeout_ms:2000,correlated_failure_threshold:2,max_retry_attempts_after_initial:2,circuit_open_duration_ms:60000},PrReviewResilienceConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),canary_probe_ms:exports_external.number().int().min(1).max(3600000).default(300000),status_probe_timeout_ms:exports_external.number().int().min(1).max(60000).default(2000),correlated_failure_threshold:exports_external.number().int().min(2).max(8).default(2),max_retry_attempts_after_initial:exports_external.number().int().min(0).max(2).default(2),circuit_open_duration_ms:exports_external.number().int().min(1000).max(1800000).default(60000)}).strict(),ReviewRoutingConfigSchema=exports_external.object({enforce_receipts:exports_external.boolean().default(!0)}).strict(),DEFAULT_REVIEW_ROUTING_CONFIG={enforce_receipts:!0},LaneLivenessWatchdogConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),timeout_ms:exports_external.number().int().min(0).max(86400000).default(1800000),stall_threshold_ms:exports_external.number().int().min(0).max(86400000).default(300000),stall_min_steps:exports_external.number().int().min(0).max(1e4).default(5),stall_token_threshold:exports_external.number().int().min(0).max(1e6).default(200)}).strict(),DispatchProtectionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),spawn_failure_threshold:exports_external.number().int().min(1).max(50).default(3),half_open_after_ms:exports_external.number().int().min(1).max(3600000).default(30000),rate_per_second:exports_external.number().min(0).max(1e4).default(10),burst_capacity:exports_external.number().int().min(1).max(1e4).default(10)}).strict(),DashboardConfigSchema=exports_external.object({port:exports_external.number().int().min(0).max(65535).default(0).describe("Loopback port for the opt-in local dashboard (issue #2509). 0 or absent = disabled (default).")}).strict(),PluginConfigSchema=exports_external.object({$schema:exports_external.string().optional().catch(void 0).describe("JSON Schema URL for editor validation/autocomplete of this file (issue #1663). Ignored at runtime; malformed values are ignored too."),config_format_version:exports_external.number().int().min(0).default(1).describe("Config format version for the migration table. Increment when fields are deprecated. Distinct from knowledge.schema_version."),preset:exports_external.enum(["default","conservative"]).optional().describe('Defaults profile: "default" applies the governed v8 defaults; "conservative" restores the pre-flip (v7) defaults for every flipped surface (#2504).'),agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional().describe('Per-agent overrides keyed by agent name for the default swarm (e.g. "architect", "coder"). Multi-swarm setups configure agents under swarms.<id>.agents instead.'),default_agent:exports_external.string().optional().transform((v)=>{if(v===void 0)return;let trimmed=v.trim();return trimmed===""?void 0:trimmed}).describe('Agent set as the primary mode. Omitted: every generated *_architect is primary. Exact generated name (e.g. "local_architect"): only that agent. Base role name (e.g. "coder"): every generated agent with that base role. Unknown strings warn once and fall back to architect primaries.'),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}).describe('Auto-select the swarm architect for new sessions instead of OpenCode built-ins. Omitted or false: manual selection (omitted behaves as false). true: enable auto-select and disable built-in build/plan agents. "<architect_name>" (e.g. "mega_architect"): enable targeting one architect in multi-swarm setups.'),swarms:exports_external.record(exports_external.string().regex(/^[^_]+$/,"Swarm ID must not contain underscores"),SwarmConfigSchema).optional().describe('Multiple swarms keyed by swarm ID (no underscores allowed). The first swarm, or one named "default", provides the primary architect.'),max_iterations:exports_external.number().min(1).max(10).default(5).describe("Maximum pipeline iterations per task (1-10)."),pipeline:PipelineConfigSchema.optional().describe("Pipeline stage/model settings."),phase_complete:PhaseCompleteConfigSchema.optional().describe("Phase-completion gate settings."),qa_retry_limit:exports_external.number().min(1).max(10).default(3).describe("Maximum QA retry rounds per task (1-10)."),execution_mode:exports_external.enum(["strict","balanced","fast"]).default("balanced").describe('Performance mode controlling optional hook execution overhead: "strict", "balanced", or "fast".'),inject_phase_reminders:exports_external.boolean().default(!0).describe("Inject phase reminder directives during execution."),hooks:HooksConfigSchema.optional().describe("Hook subsystem toggles and settings."),pr_review_resilience:PrReviewResilienceConfigSchema.optional().describe("PR review base-wave staged canary/fanout resilience settings."),review_routing:ReviewRoutingConfigSchema.optional().describe("Semantic review routing receipt enforcement for Stage B (default on; set enforce_receipts=false only as a one-release rollback)."),lane_liveness_watchdog:LaneLivenessWatchdogConfigSchema.optional().describe("Lane liveness watchdog: execution deadline and stall escalation for PR workflow lanes."),dispatch_protection:DispatchProtectionConfigSchema.optional().describe("Dispatch protection: action-local spawn-failure circuit breaker and token-bucket rate limiting for native task delegations."),pr_review_legacy_transcript_compatibility:exports_external.boolean().optional().describe("Deprecated migration-only opt-in for transcript-row PR-review base and micro discovery lanes."),gates:GateConfigSchema.optional().describe("Quality gate configuration (v6.9 anti-slop features)."),context_budget:ContextBudgetConfigSchema.optional().describe("Context budget thresholds."),pricing:PricingConfigSchema.optional().describe("Token/cost estimation fallback table. Provider-reported cost wins when present; entries only estimate from usage tokens when reports omit cost."),guardrails:GuardrailsConfigSchema.optional().describe("Loop containment and safety guardrails: tool-call caps, denial tracking, destructive-command blocking, shell audit."),watchdog:WatchdogConfigSchema.optional().describe("Scope-guard and delegation-ledger watchdog settings."),self_review:SelfReviewConfigSchema.optional().describe("Advisory self-review after coder delegation."),auto_review:AutoReviewConfigSchema.optional().describe("Opt-in execution-diff review by the reviewer model in a fresh ephemeral session at task/phase boundaries."),tool_filter:ToolFilterConfigSchema.optional().describe("Controls which plugin tools each agent is allowed to use; enforced through host-side per-agent permission denies (issue #2528). enabled: false lifts the plugin-tool allow-list but keeps each role's read-only write-family floor."),authority:AuthorityConfigSchema.optional().describe("Per-agent file write authority rules."),plan_cursor:PlanCursorConfigSchema.optional().describe("Compressed plan summary injection settings."),context_map:ContextMapConfigSchema.optional().describe("Context Map (issue #1104, FR-006) — opt-in."),repo_graph:RepoGraphConfigSchema.prefault({}).describe("Repository dependency-graph settings (builder excludes, incremental refresh). Nested defaults materialize when the whole section is omitted."),evidence:EvidenceConfigSchema.optional().describe("Evidence retention and storage settings."),summaries:SummaryConfigSchema.optional().describe("Summary generation settings."),retention:RetentionConfigSchema.describe("Retention sweep settings (issue #2483)."),review_passes:ReviewPassesConfigSchema.optional().describe("Dual-pass security review settings."),adversarial_detection:AdversarialDetectionConfigSchema.optional().describe("Same-model adversarial checker detection settings."),adversarial_testing:AdversarialTestingConfigSchema.optional().describe("Cross-model adversarial testing settings."),integration_analysis:IntegrationAnalysisConfigSchema.optional().describe("Integration analysis settings."),docs:DocsConfigSchema.optional().describe("Documentation synthesizer (docs agent) settings."),design_docs:DesignDocsConfigSchema.optional().describe("Structured design-doc generation (issue #1080, docs_design agent) — opt-in."),speckit_checkoff:exports_external.object({enabled:exports_external.boolean().default(!1).describe("Check off mapped Spec-Kit tasks in the source tasks.md when Swarm completes a plan task (issue #2501). Off by default — write-back to user-owned files is opt-in.")}).optional().describe("Spec-Kit tasks.md check-off round trip (issue #2501) — opt-in, never on by default."),git:GitConfigSchema.optional().describe("Git executable resolution override (issue #2236 hardening)."),ui_review:UIReviewConfigSchema.optional().describe("UI/UX review (designer agent) settings."),compaction_advisory:CompactionAdvisoryConfigSchema.optional().describe("Compaction advisory settings."),lint:LintConfigSchema.optional().describe("Lint gate settings."),secretscan:SecretscanConfigSchema.optional().describe("Secret scanning settings."),checkpoint:CheckpointConfigSchema.optional().describe("Checkpoint settings."),apply_patch:ApplyPatchConfigSchema.optional().describe("Apply-patch opt-in fuzzy matching fallback (issue #1718)."),automation:AutomationConfigSchema.optional().describe("Background automation mode and per-feature toggles (v6.7 background-first rollout)."),knowledge:KnowledgeConfigSchema.optional().describe("Two-tier cross-project knowledge base (v6.17)."),memory:MemoryConfigSchema.optional().describe("Swarm memory substrate — disabled by default so existing flows are unchanged."),forge:ForgeConfigSchema.optional().describe('Forge provider (GitHub/GitLab) selection for PR/issue workflows (issue #2733). Ambiguous git remotes (mixed providers, unrecognized self-hosted hosts, or no remote) fail closed and require an explicit selection; forge.base_url passes through the same HTTPS-only / non-private / ASCII-host guards as every forge URL and is never a trust whitelist; combining base_url with provider "github" is rejected as a configuration conflict.'),observability:ObservabilityConfigSchema.optional().describe("Observability options — remote OTLP/OpenInference export is opt-in and disabled by default (issue #2485)."),learning:LearningConfigSchema.optional().describe("Learning subsystem: real-time admission, PRM persistence, dedup sweep (issue #1821)."),consensus:ConsensusConfigSchema.optional().describe("Consensus mining over completed run evidence (issue #1821)."),curator:CuratorConfigSchema.optional().describe("Phase context consolidation and drift detection."),architectural_supervision:ArchitecturalSupervisionConfigSchema.optional().describe("Hierarchical summary review (issue #893)."),knowledge_application:KnowledgeApplicationConfigSchema.optional().describe("Knowledge-application contract (v2): warn or enforce modes, ack tracking."),skillPropagation:SkillPropagationConfigSchema.optional().describe("Skill propagation gate/injection settings."),skill_improver:SkillImproverConfigSchema.optional().describe("Low-frequency, expensive-model skill improvement loop (issue #629, v2)."),harness_evolution:HarnessEvolutionConfigSchema.optional().describe("Declarative, non-executing HarnessOpt mutation policy (issue #1825)."),harness_opt:HarnessOptConfigSchema.optional().describe("Governed HarnessOpt optimization capstone (issue #2503). Disabled by default; /swarm harness-opt run requires enabled: true plus --confirm."),spec_writer:SpecWriterConfigSchema.optional().describe("Spec writer agent (v2) — independent model for .swarm/spec.md authorship."),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().describe("Tool output truncation settings (enable/disable, max lines, per-tool overrides)."),slop_detector:SlopDetectorConfigSchema.optional().describe("Slop detector settings (v6.29)."),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().describe("TODO gate (v6.32): warn or block on new high-priority TODOs (FIXME/HACK/XXX)."),incremental_verify:IncrementalVerifyConfigSchema.optional().describe("Incremental verification settings (v6.29)."),compaction_service:CompactionConfigSchema.optional().describe("Compaction service settings (v6.29)."),prm:PrmConfigSchema.optional().describe("PRM (Process Remediation Manager) settings."),council:CouncilConfigSchema.optional().describe("Work Complete Council — parallel four-member verification gate, off by default."),parallelization:ParallelizationConfigSchema.optional().describe("Parallelization (PR 1 dark foundation) — disabled by default; no production code path branches on enabled=true yet."),worktree:WorktreeIsolationConfigSchema.optional().describe("Worktree isolation policy for parallel coder dispatch lanes (general surface; Lean Turbo keeps its legacy per-mode fields)."),turbo:TurboConfigSchema.optional().describe("Turbo execution strategy block (Phase 1). Absent means current behavior unchanged."),turbo_mode:exports_external.boolean().default(!1).optional().describe("Bypass reviewer/test gates for rapid iteration (v6.40). When true, new sessions start with turbo mode on (session default); /swarm turbo still toggles per session. Directory-less constructions default off."),quiet:exports_external.boolean().default(!0).optional().describe("Suppress non-critical startup warnings (default true keeps the TUI clean). Set false to restore verbose warnings for debugging."),version_check:exports_external.boolean().default(!0).optional().describe("Background staleness check against npm, throttled to once per 24h (issue #675). Set false to fully disable the network call."),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),total_timeout_ms:exports_external.number().int().min(1000).max(300000).default(120000),cleanup_timeout_ms:exports_external.number().int().min(100).max(1e4).default(2000)}).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,total_timeout_ms:120000,cleanup_timeout_ms:2000}))}).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,total_timeout_ms:120000,cleanup_timeout_ms:2000}})).describe("Full-auto autonomous orchestration with critic oversight: permission policy, denial accounting, oversight cadence triggers (v2 preserves v1 fields so existing configs load unchanged)."),pr_feedback_loop:PrFeedbackLoopConfigSchema.optional().describe("Autonomous PR babysitting settling loop (issue #2502) — triple opt-in with pr_monitor.enabled + pr_monitor.auto_pr_feedback; off by default; publication profile is none-only."),pr_monitor:PrMonitorConfigSchema.optional().describe("GitHub PR subscription and polling (FR-001) — disabled by default; opt-in for real-time PR status updates."),external_skills:ExternalSkillsConfigSchema.optional().describe("External skills: candidate model, discovery, and quarantine store (FR-001) — all subsystems opt-in."),skills:SkillsConfigSchema.optional().describe("Opt-in gate for the 7 skill_* management tools (FR-004). Default false: the tools are host-denied for every agent except skill_improver (genuinely unreachable, not merely unlisted — issue #2528)."),skill_opt:SkillOptConfigSchema.optional().describe("Governed skill optimizer (issue #1822). Disabled by default; /swarm skill-opt run requires enabled: true. All other subcommands are proposal-only/read-only by default."),dashboard:DashboardConfigSchema.optional().describe("Opt-in local mission-control dashboard over durable swarm state (issue #2509). Disabled by default; set port > 0 to enable the loopback-only read-only view.")})});var exports_loader={};__export(exports_loader,{resetConfigAdvisoryDedup:()=>resetConfigAdvisoryDedup,loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadGateOverrides:()=>loadGateOverrides,loadAgentPrompt:()=>loadAgentPrompt,getSafeDefaultConfigLoadResult:()=>getSafeDefaultConfigLoadResult,formatZodIssues:()=>formatZodIssues,deepMerge:()=>deepMerge,_internals:()=>_internals4,MAX_MERGE_DEPTH:()=>MAX_MERGE_DEPTH,MAX_CONFIG_FILE_BYTES:()=>MAX_CONFIG_FILE_BYTES});import*as fs2 from"node:fs";import*as fsPromises from"node:fs/promises";import*as os2 from"node:os";import*as path2 from"node:path";function gatesAdvisoryWarn(message,data){if(gatesAdvisorySignatures.has(message))return;if(gatesAdvisorySignatures.size>=MAX_GATES_ADVISORY_SIGNATURES)gatesAdvisorySignatures.clear();gatesAdvisorySignatures.add(message),advisoryWarn(message,data)}function getUserConfigDir(){return process.env.XDG_CONFIG_HOME||path2.join(os2.homedir(),".config")}function loadRawConfigFromPath(configPath){try{if(fs2.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=fs2.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}}let dormantLegacyKeys=["preset","presets","swarm_mode"].filter((key)=>(key in raw)&&(key!=="preset"||raw.preset!=="default"&&raw.preset!=="conservative"));if(dormantLegacyKeys.length>0&&raw.agents){let cleaned={...raw};for(let key of dormantLegacyKeys)delete cleaned[key];return advisoryWarn(`[opencode-swarm] Ignored legacy v6.12 config key(s): ${dormantLegacyKeys.join(", ")}. The agents block takes precedence — consider removing them from your opencode-swarm.json.`),cleaned}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)){gatesAdvisoryWarn("[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){gatesAdvisoryWarn(`[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))gatesAdvisoryWarn(`[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(gatesAdvisoryWarn(`[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,rawGates:cleanedGates};gatesAdvisoryWarn("[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,rawGates}=sanitizeGatesConfig(afterExternal);return{result,strippedKeys:[...externalStripped,...gatesStripped],rawGates}}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 exposedGitBinary(raw){if(!raw||typeof raw!=="object")return;let git=raw.git;if(!git||typeof git!=="object"||Array.isArray(git))return;return git.binary}function enforceGitBinaryProvenance(mergedRaw,rawUserConfig){let userBinary=exposedGitBinary(rawUserConfig),exposedBinary=exposedGitBinary(mergedRaw);if(Object.is(exposedBinary,userBinary))return mergedRaw;advisoryWarn(`[opencode-swarm] ⚠️ SECURITY: Ignoring "git.binary" supplied by the project config (.opencode/${CONFIG_FILENAME}). That file lives inside the repository, so it is untrusted content, and "git.binary" selects the executable this plugin spawns for every git command. Set it in your user config (<config dir>/opencode/${CONFIG_FILENAME}) or the ${GIT_BINARY_ENV_VAR} environment variable instead.`);let exposedGit=mergedRaw.git,nextGit=exposedGit&&typeof exposedGit==="object"&&!Array.isArray(exposedGit)?{...exposedGit}:{},rebuilt={...mergedRaw};if(userBinary===void 0){if(delete nextGit.binary,Object.keys(nextGit).length===0)return delete rebuilt.git,rebuilt}else nextGit.binary=userBinary;return rebuilt.git=nextGit,rebuilt}function buildConfigWithMeta(rawUserConfig,rawProjectConfig,loadedFromFile,configHadErrors){let mergedRaw=rawUserConfig??{};if(rawProjectConfig)try{mergedRaw=deepMerge(mergedRaw,rawProjectConfig)}catch(err){if(err instanceof DangerousMergeKeyError)advisoryWarn(`[opencode-swarm] ⚠️ SECURITY: Ignoring the entire project config (.opencode/${CONFIG_FILENAME}): it carries the dangerous key "${err.key}" at "${err.path}", a prototype-pollution payload. Continuing with user-level configuration only.`);else throw err}if(mergedRaw=enforceGitBinaryProvenance(mergedRaw,rawUserConfig),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}}}if(mergedRaw=migratePresetsConfig(mergedRaw),mergedRaw.preset==="conservative")mergedRaw=deepMerge(CONSERVATIVE_PRESET_BASE,mergedRaw);let{result:sanitized,strippedKeys:gatesStripped,rawGates}=sanitizeSectionConfigs(mergedRaw);mergedRaw=sanitized;let knownTopLevel=new Set(Object.keys(PluginConfigSchema.shape)),unknownTopLevel=Object.keys(mergedRaw).filter((key)=>!knownTopLevel.has(key));if(unknownTopLevel.length>0){let signature=unknownTopLevel.join("\x00");if(signature!==lastUnknownTopLevelSig)lastUnknownTopLevelSig=signature,advisoryWarn(`[opencode-swarm] Ignored ${unknownTopLevel.length} unknown top-level config key(s): ${unknownTopLevel.join(", ")}. These keys have no effect — see docs/configuration.md (Top-level configuration keys) for the valid key list.`)}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:[],rawGates};return{config:config2,recovery:gatesStripped.length>0?"stripped_keys":"none",removedKeys:[...gatesStripped],warnings:[],rawGates}}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:[],rawGates}}if(rawUserConfig){let{result:userSanitized,strippedKeys:userGatesStripped,rawGates:userRawGates}=sanitizeSectionConfigs(rawUserConfig),userPresetMigrated=migratePresetsConfig(userSanitized),userPresetReady=userPresetMigrated.preset==="conservative"?deepMerge(CONSERVATIVE_PRESET_BASE,userPresetMigrated):userPresetMigrated,userParseResult=PluginConfigSchema.safeParse(userPresetReady);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."],rawGates:userRawGates};let userStripped=stripUnrecognizedKeys(userPresetReady,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."],rawGates:userRawGates}}}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:[],rawGates}}}}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=path2.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path2.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=path2.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path2.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,rawGates}=buildConfigWithMeta(userResult.config,projectResult.config,loadedFromFile,configHadErrors);return{config:config2,loadedFromFile,configHadErrors,recovery,removedKeys,warnings,rawGates}}function loadGateOverrides(directory){try{return loadPluginConfigWithMeta(directory).rawGates}catch{return}}function resetConfigAdvisoryDedup(){gatesAdvisorySignatures.clear(),lastUnknownTopLevelSig=null}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=path2.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path2.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,rawGates}=buildConfigWithMeta(userResult.config,projectResult.config,loadedFromFile,configHadErrors);return{config:config2,loadedFromFile,configHadErrors,recovery,removedKeys,warnings,rawGates}}function loadAgentPrompt(agentName){let promptsDir=path2.join(getUserConfigDir(),"opencode",PROMPTS_DIR_NAME),result={},promptPath=path2.join(promptsDir,`${agentName}.md`);if(fs2.existsSync(promptPath))try{result.prompt=fs2.readFileSync(promptPath,"utf-8")}catch(error49){advisoryWarn(`[opencode-swarm] Error reading prompt file ${promptPath}:`,error49 instanceof Error?error49.message:String(error49))}let appendPromptPath=path2.join(promptsDir,`${agentName}_append.md`);if(fs2.existsSync(appendPromptPath))try{result.appendPrompt=fs2.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,lastUnknownTopLevelSig=null,gatesAdvisorySignatures,MAX_GATES_ADVISORY_SIGNATURES=64,_internals4;var init_loader=__esm(()=>{init_warning_buffer();init_git_executable();init_schema();init_merge();init_merge();gatesAdvisorySignatures=new Set;_internals4={resetUnknownTopLevelKeyWarning(){lastUnknownTopLevelSig=null},resetGatesAdvisoryDedup(){gatesAdvisorySignatures.clear()}}});function isPhaseStatusTerminal(status){return status==="complete"||status==="completed"||status==="closed"}function isPhaseEffectivelyTerminal(phase){if(isPhaseStatusTerminal(phase.status))return!0;let tasks=phase.tasks??[];return tasks.length>0&&tasks.every((task)=>task.status==="completed"||task.status==="closed")}function resolveActivePhaseId(plan){let cursor=plan.current_phase;if(cursor!==void 0){let cursorPhase=plan.phases.find((phase)=>phase.id===cursor);if(cursorPhase&&!isPhaseEffectivelyTerminal(cursorPhase))return cursorPhase.id}let firstNonTerminal=plan.phases.find((phase)=>!isPhaseEffectivelyTerminal(phase));if(firstNonTerminal)return firstNonTerminal.id;return plan.phases[plan.phases.length-1]?.id??1}function normalizeCurrentPhaseInPlace(plan){plan.current_phase=resolveActivePhaseId(plan)}function getCurrentPhase(plan){return resolveActivePhaseId(plan)}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),commit_after_each_completed_task:exports_external.boolean().default(!1),planning_profile:exports_external.enum(["balanced","strict"]).optional()}),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(/^(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)?FR-(?!000)\d{3}$/,"Requirement ID must match FR-### (e.g., FR-001) or a feature-scoped <featureId>/FR-### form (e.g., 001-login/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",session_create_timeout_ms:DEFAULT_WORKTREE_ISOLATION_CONFIG.session_create_timeout_ms,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,resetConfigAdvisoryDedup:()=>resetConfigAdvisoryDedup,loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadGateOverrides:()=>loadGateOverrides,loadAgentPrompt:()=>loadAgentPrompt,isSubagent:()=>isSubagent,isQAAgent:()=>isQAAgent,getSafeDefaultConfigLoadResult:()=>getSafeDefaultConfigLoadResult,_internals:()=>_internals5,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,ReviewRoutingConfigSchema:()=>ReviewRoutingConfigSchema,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,GATE_SECTION_SCHEMAS:()=>GATE_SECTION_SCHEMAS,GATE_CONFIG_READERS:()=>GATE_CONFIG_READERS,ExecutionProfileSchema:()=>ExecutionProfileSchema,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 _internals5;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();_internals5={loadPluginConfigWithMeta}});function splitEmbeddedAgentVariant(model){let segments=model.split("/"),lastSegment=segments[segments.length-1]??"";if(segments.length<3||!KNOWN_EMBEDDED_VARIANTS.has(lastSegment))return{model};return{model:segments.slice(0,-1).join("/"),variant:lastSegment}}function safeGet(entries,key){if(!entries||!Object.hasOwn(entries,key))return;return entries[key]}function canonicalAgentName(agentName){let normalized=agentName.trim().toLowerCase();if(CANONICAL_AGENT_NAMES.has(normalized))return normalized;for(let candidate of ALL_AGENT_NAMES)if(normalized.endsWith(`_${candidate}`))return candidate;return}function resolveAgentTarget(config2,exactAgentName){let normalizedTarget=exactAgentName.trim().toLowerCase();if(!normalizedTarget)return;let baseAgentName=canonicalAgentName(normalizedTarget);if(!baseAgentName)return;let swarms=config2.swarms,swarmIDs=swarms?Object.keys(swarms):[];if(swarmIDs.length===0){if(normalizedTarget!==baseAgentName)return;return{baseAgentName,override:safeGet(config2.agents,baseAgentName)}}for(let swarmID of swarmIDs){if((swarmID==="default"?baseAgentName:`${swarmID}_${baseAgentName}`).toLowerCase()!==normalizedTarget)continue;let swarmOverride=safeGet(swarms?.[swarmID]?.agents,baseAgentName);return{baseAgentName,override:swarmOverride??safeGet(config2.agents,baseAgentName)}}return}function resolveConfiguredAgentModel(config2,exactAgentName){let configuredModel=resolveAgentTarget(config2,exactAgentName)?.override?.model;if(typeof configuredModel!=="string")return;let trimmed=configuredModel.trim();return trimmed?splitEmbeddedAgentVariant(trimmed).model:void 0}function resolveRegisteredAgentModel(config2,exactAgentName){let target=resolveAgentTarget(config2,exactAgentName);if(!target)return;return resolveConfiguredAgentModel(config2,exactAgentName)??DEFAULT_MODELS[target.baseAgentName]??DEFAULT_MODELS.default}function resolveEffectiveAgentOverride(config2,exactAgentName){let target=resolveAgentTarget(config2,exactAgentName);if(!target)return;return{baseAgentName:target.baseAgentName,model:target.override?.model,fallbackModels:target.override?.fallback_models,disabled:target.override?.disabled}}function resolveRuntimeAgentModel(config2,registeredAgents,exactAgentName){let normalizedTarget=exactAgentName.trim().toLowerCase();if(!normalizedTarget)return;let registeredName=Object.keys(registeredAgents).find((name)=>name.toLowerCase()===normalizedTarget);if(!registeredName)return;let registeredAgent=registeredAgents[registeredName];if(registeredAgent?.mode==="primary")return;let configuredModel=resolveConfiguredAgentModel(config2,registeredName);if(configuredModel)return configuredModel;if(typeof registeredAgent?.model!=="string")return;return registeredAgent.model.trim()||void 0}function parseAgentModel(model){let trimmed=model.trim();if(!trimmed)return;let separatorIndex=trimmed.indexOf("/");if(separatorIndex===-1)return{modelID:trimmed};let providerID=trimmed.slice(0,separatorIndex).trim(),modelID=trimmed.slice(separatorIndex+1).trim();if(!providerID||!modelID||modelID.startsWith("/")||modelID.endsWith("/"))return;return{modelID,providerID}}var CANONICAL_AGENT_NAMES,KNOWN_EMBEDDED_VARIANTS;var init_agent_model=__esm(()=>{init_agent_names();init_constants();CANONICAL_AGENT_NAMES=new Set(ALL_AGENT_NAMES),KNOWN_EMBEDDED_VARIANTS=new Set(["low","medium","high","max","xhigh","thinking"])});function renderPlanningProfileDirective(resolution,context="runtime"){let header=context==="repository_default"?`[PLANNING PROFILE DEFAULT — USE ONLY WHEN NO RUNTIME RESOLUTION EXISTS] effective=${resolution.effective} source=${resolution.source}`:`[PLANNING PROFILE — CURRENT RUNTIME AUTHORITY] effective=${resolution.effective} source=${resolution.source}`,precedence=context==="runtime"?`
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(),diff_scoped:exports_external.boolean().optional(),added_lines_files:exports_external.number().int().min(0).optional(),added_lines_total:exports_external.number().int().min(0).optional()}),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(),moved_findings:exports_external.array(SastFindingSchema).optional(),baseline_used:exports_external.boolean().optional(),truncated_pre_existing:exports_external.boolean().optional(),truncated_moved_findings: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(),spawn_error:exports_external.string().optional()})).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(),environment_unavailable:exports_external.array(exports_external.object({ecosystem:exports_external.string(),reason:exports_external.string(),code:exports_external.literal("environment_unavailable"),required_commands:exports_external.array(exports_external.string()).optional()})).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(),base_resolved:exports_external.boolean().default(!1)}),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),policy_skipped_files:exports_external.number().int().min(0).optional(),requested_files:exports_external.number().int().min(0).optional(),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 roundMs(value){return Math.round(value*10)/10}function emitContractRow(payload){try{if(!_internals.isDebugEnabled())return;_internals.emitLine(`STARTUP-CONTRACT ${JSON.stringify(payload)}`)}catch{}}function boundErrorText(err){let text="unknown error";try{text=err instanceof Error?err.message:String(err)}catch{}return text=text.replace(/\s+/g," ").trim().slice(0,200),text}function isPromiseLike(value){return typeof value==="object"&&value!==null&&typeof value.then==="function"}function markStartupImportComplete(){if(state.importMarkMs!==null)return;state.importMarkMs=_internals.performance.now()}function beginStartupServerInterval(){state.serverStartMark=_internals.performance.now(),state.serverResolvedMark=null,state.serverMs=null,state.queueScheduledAt=null,state.queuePending=0,state.queueTasks=0,state.queueCompleted=0,state.queueFailed=0,state.queueSettled=!1,state.queueSettledMs=null,state.advisoryCount=0,state.advisoryWindowOpen=!0,state.firstTurnDone=!1,state.firstToolDone=!1,state.firstToolName=null,state.firstTurnMs=null,state.firstToolMs=null}function endStartupServerInterval(){if(state.serverStartMark===null)return;let now=_internals.performance.now();if(state.serverResolvedMark=now,state.serverMs=roundMs(now-state.serverStartMark),state.queueScheduledAt===null)state.advisoryWindowOpen=!1;emitContractRow({v:1,stage:"init",importMs:state.importMarkMs===null?null:roundMs(state.importMarkMs),serverMs:state.serverMs})}function noteQueueScheduled(){state.queueScheduledAt=_internals.performance.now()}function maybeEmitQueueSettled(){if(state.queueSettled||state.queueScheduledAt===null)return;if(state.queueTasks===0||state.queuePending>0)return;state.queueSettled=!0;let now=_internals.performance.now();state.queueSettledMs=state.queueScheduledAt===null?null:roundMs(now-state.queueScheduledAt),state.advisoryWindowOpen=!1,emitContractRow({v:1,stage:"queue_settled",tasks:state.queueTasks,completed:state.queueCompleted,failed:state.queueFailed,ms:state.queueSettledMs,advisories:state.advisoryCount})}function recordTaskOutcome(name,outcome,ms,err){if(state.queuePending-=1,outcome==="completed")state.queueCompleted+=1;else state.queueFailed+=1;let row={v:1,stage:"optional_task",task:name,outcome,ms:roundMs(ms)};if(outcome==="failed")row.error=boundErrorText(err);emitContractRow(row),maybeEmitQueueSettled()}function wrapPostResolutionTask(task){let name=task.name||"anonymous";state.queueTasks+=1,state.queuePending+=1;let wrapped=async()=>{let startedAt=_internals.performance.now();try{await task(),recordTaskOutcome(name,"completed",_internals.performance.now()-startedAt)}catch(err){throw recordTaskOutcome(name,"failed",_internals.performance.now()-startedAt,err),err}};try{Object.defineProperty(wrapped,"name",{value:name,configurable:!0})}catch{}return wrapped}function noteFirstUseSettled(stage,label){try{if(stage==="first_turn"){if(state.firstTurnDone)return;state.firstTurnDone=!0,state.firstTurnMs=state.serverResolvedMark===null?null:roundMs(_internals.performance.now()-state.serverResolvedMark),emitContractRow({v:1,stage:"first_turn",ms:state.firstTurnMs})}else{if(state.firstToolDone)return;state.firstToolDone=!0,state.firstToolName=label??null,state.firstToolMs=state.serverResolvedMark===null?null:roundMs(_internals.performance.now()-state.serverResolvedMark),emitContractRow({v:1,stage:"first_tool",tool:state.firstToolName,ms:state.firstToolMs})}}catch{}}function withStartupFirstUseTracking(stage,label,handler){let tracked=(...args2)=>{let result=handler(...args2),settle=()=>noteFirstUseSettled(stage,label);if(isPromiseLike(result))Promise.resolve(result).then(settle,settle);else settle();return result};try{Object.defineProperty(tracked,"name",{value:handler.name||`tracked${stage}`,configurable:!0})}catch{}return tracked}function withStartupFirstToolTracking(name,execute){let tracked=(args2,ctx)=>{let result=execute(args2,ctx),settle=()=>noteFirstUseSettled("first_tool",name);if(isPromiseLike(result))Promise.resolve(result).then(settle,settle);else settle();return result};try{Object.defineProperty(tracked,"name",{value:execute.name||"trackedFirstToolExecute",configurable:!0})}catch{}return tracked}function noteStartupAdvisory(){if(!state.advisoryWindowOpen)return;state.advisoryCount+=1}var state,_internals;var init_startup_contract=__esm(()=>{state={importMarkMs:null,serverStartMark:null,serverResolvedMark:null,serverMs:null,queueScheduledAt:null,queuePending:0,queueTasks:0,queueCompleted:0,queueFailed:0,queueSettled:!1,queueSettledMs:null,advisoryCount:0,advisoryWindowOpen:!1,firstTurnDone:!1,firstToolDone:!1,firstToolName:null,firstTurnMs:null,firstToolMs:null};_internals={performance,isDebugEnabled:()=>process.env.OPENCODE_SWARM_DEBUG==="1",emitLine:(line)=>{console.log(line)}}});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){noteStartupAdvisory();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_startup_contract();init_logger();deferredWarnings=[],CONTROL_CHARS_RE=/[\x00-\x1F\x7F-\x9F]/g});import{spawnSync}from"node:child_process";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";function excerptProbeOutput(raw){return raw.slice(0,PROBE_OUTPUT_EXCERPT_CHARS).replace(/[^\x20-\x7E]/g," ").trim()}function unique(values){return[...new Set(values.filter(Boolean))]}function envOverride(){let raw=_internals2.env()[GIT_BINARY_ENV_VAR];return raw&&raw.trim()!==""?raw:void 0}function effectiveOverride(){return envOverride()??configuredOverride}function overrideSource(){if(envOverride()!==void 0)return"env";if(configuredOverride!==void 0)return"config";return}function isAbsoluteForPlatform(candidate,platform){return platform==="win32"?path.win32.isAbsolute(candidate):path.posix.isAbsolute(candidate)}function windowsPlatformCandidates(){let env=_internals2.env(),installed=unique([env.ProgramFiles??"",env["ProgramFiles(x86)"]??"",env.LOCALAPPDATA?`${env.LOCALAPPDATA}\\Programs`:""]).flatMap((root)=>[`${root}\\Git\\cmd\\git.exe`,`${root}\\Git\\bin\\git.exe`]);return unique(installed)}function platformCandidates(platform){if(platform==="darwin")return["/opt/homebrew/bin/git","/usr/local/bin/git","/usr/bin/git"];if(platform==="win32")return windowsPlatformCandidates();return["/usr/bin/git","/usr/local/bin/git","/bin/git"]}function pathDelimiterFor(platform){return platform==="win32"?";":":"}function joinDirAndName(dir,name,platform){let sep=platform==="win32"?"\\":"/",trimmed=dir.replace(/[\\/]+$/,"");return trimmed?`${trimmed}${sep}${name}`:`${sep}${name}`}function pathCandidates(platform){let pathValue=_internals2.env().PATH??"";if(!pathValue)return[];let dirs=pathValue.split(pathDelimiterFor(platform)).filter(Boolean),names=platform==="win32"?[...WINDOWS_PATH_EXTENSIONS.map((ext)=>`git${ext}`),"git"]:["git"],out=[];for(let dir of dirs)for(let name of names)out.push(joinDirAndName(dir,name,platform));return unique(out)}function buildCandidates(platform){let override=effectiveOverride(),overrideCandidate=override?[{source:"override",path:override}]:[],seen=new Set(overrideCandidate.map((c)=>c.path)),rest=[];for(let p of platformCandidates(platform)){if(seen.has(p))continue;seen.add(p),rest.push({source:"platform",path:p})}for(let p of pathCandidates(platform)){if(seen.has(p))continue;seen.add(p),rest.push({source:"path",path:p})}return[...overrideCandidate,...rest]}function probeCandidate(candidatePath,platform){if(!isAbsoluteForPlatform(candidatePath,platform))return{accepted:!1,reason:"not an absolute path"};let stat;try{stat=fs.statSync(candidatePath)}catch(err){let code=err?.code;if(code==="ENOENT")return{accepted:!1,reason:"no such file"};return{accepted:!1,reason:`cannot stat (${code??"unknown error"})`}}if(stat.isDirectory())return{accepted:!1,reason:"is a directory"};if(!stat.isFile())return{accepted:!1,reason:"not a regular file"};let result;try{result=_internals2.spawnSync(candidatePath,["--version"],{cwd:os.tmpdir(),stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:PER_PROBE_TIMEOUT_MS,maxBuffer:PROBE_MAX_BUFFER_BYTES})}catch(err){return{accepted:!1,reason:`spawn threw: ${err instanceof Error?err.message:String(err)}`}}if(result.error)return{accepted:!1,reason:`spawn failed: ${result.error.message}`};if(result.status!==0)return{accepted:!1,reason:`git --version returned ${result.status!==null?`exit ${result.status}`:`signal ${result.signal??"unknown"}`}`};let versionOutput=(result.stdout??"").toString().trim();if(!GIT_VERSION_PATTERN.test(versionOutput)){let excerpt=excerptProbeOutput(versionOutput);return{accepted:!1,reason:excerpt?`not git: --version printed "${excerpt}"`:"not git: --version printed nothing"}}return{accepted:!0}}function*probeCycle(candidates,platform,attempts){let start=_internals2.now(),budgetExceeded=!1;for(let candidate of candidates){if(_internals2.now()-start>TOTAL_BUDGET_MS){budgetExceeded=!0;break}let result=probeCandidate(candidate.path,platform);if(attempts.push({source:candidate.source,candidate:candidate.path,accepted:result.accepted,reason:result.reason}),candidate.source==="override"&&!result.accepted)advisoryWarn(`[opencode-swarm] git.binary override "${candidate.path}" is unusable (${result.reason}); falling back to automatic git resolution.`);if(result.accepted)return{outcome:"accepted",path:candidate.path};yield}return budgetExceeded?{outcome:"exhausted-budget"}:{outcome:"all-rejected"}}function driveSync(gen){let step=gen.next();while(!step.done)step=gen.next();return step.value}async function driveAsync(gen){let step=gen.next();while(!step.done)await _internals2.yieldToEventLoop(),step=gen.next();return step.value}function readCache(){if(cache===null)return null;if(cache.kind==="success")return cache;if(_internals2.now()<cache.expiresAt)return cache;return cache=null,null}function applyProbeResult(result,attempts,generation){if(generation!==cacheGeneration)return result.outcome==="accepted"?result.path:BARE_GIT;if(lastAttempts=attempts,result.outcome==="accepted")return cache={kind:"success",path:result.path},result.path;return cache={kind:"fallback",expiresAt:_internals2.now()+NEGATIVE_CACHE_TTL_MS},BARE_GIT}function resolveGitExecutable(){let cached2=readCache();if(cached2)return cached2.kind==="success"?cached2.path:BARE_GIT;let platform=_internals2.platform(),attempts=[],generation=cacheGeneration,candidates=buildCandidates(platform),result=driveSync(probeCycle(candidates,platform,attempts));return applyProbeResult(result,attempts,generation)}async function resolveGitExecutableAsync(){let cached2=readCache();if(cached2)return cached2.kind==="success"?cached2.path:BARE_GIT;if(inFlightAsync)return inFlightAsync;let platform=_internals2.platform(),attempts=[],generation=cacheGeneration,candidates=buildCandidates(platform),run=(async()=>{let result=await driveAsync(probeCycle(candidates,platform,attempts));return applyProbeResult(result,attempts,generation)})();inFlightAsync=run;try{return await run}finally{if(inFlightAsync===run)inFlightAsync=null}}function resetGitExecutableCache(){cache=null,lastAttempts=[],inFlightAsync=null,cacheGeneration++}function setGitBinaryOverride(value){let normalized=value&&value.trim()!==""?value:void 0;if(normalized===configuredOverride)return;configuredOverride=normalized,resetGitExecutableCache()}function describeGitResolution(){let cached2=cache;return{resolved:cached2?.kind==="success",resolvedPath:cached2?.kind==="success"?cached2.path:void 0,attempts:[...lastAttempts],overrideValue:effectiveOverride(),overrideSource:overrideSource()}}var GIT_BINARY_ENV_VAR="OPENCODE_SWARM_GIT_BINARY",PER_PROBE_TIMEOUT_MS=250,TOTAL_BUDGET_MS=1000,NEGATIVE_CACHE_TTL_MS=60000,BARE_GIT="git",PROBE_MAX_BUFFER_BYTES=65536,WINDOWS_PATH_EXTENSIONS,GIT_VERSION_PATTERN,PROBE_OUTPUT_EXCERPT_CHARS=60,cache=null,lastAttempts,configuredOverride,inFlightAsync=null,cacheGeneration=0,_internals2;var init_git_executable=__esm(()=>{init_warning_buffer();WINDOWS_PATH_EXTENSIONS=[".exe",".cmd",".bat"],GIT_VERSION_PATTERN=/^git version \d+\.\d+/;lastAttempts=[];_internals2={spawnSync,platform:()=>process.platform,env:()=>process.env,now:()=>Date.now(),yieldToEventLoop:()=>new Promise((resolve)=>setTimeout(resolve,0))}});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(path2,prefix){if(prefix.length>path2.length)return!1;for(let i=0;i<prefix.length;i++)if(path2[i]!==prefix[i])return!1;return!0}function removeAtPath(obj,path2){if(path2.length===0)return!1;let node=obj;for(let i=0;i<path2.length-1;i++){if(node===null||node===void 0||typeof node!=="object")return!1;let key=path2[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=path2[path2.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(path2,issues){let key=keyOf(path2);for(let issue2 of issues)if(keyOf(issue2.path)===key)return{path:path2,code:issue2.code,message:issue2.message};return{path:path2,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"])});function normalizeLimitKey(key){return key.trim().toLowerCase()}function isUsableConfiguredWindow(value){return typeof value==="number"&&Number.isFinite(value)&&value>=1}function isUsableContextWindow(value){return typeof value==="number"&&Number.isFinite(value)&&value>=1000}function readModelContextLimit(model){if(typeof model!=="object"||model===null)return;let limit=model.limit;if(typeof limit!=="object"||limit===null)return;return limit.context}function readModelIdentity(model,key){if(typeof model!=="object"||model===null)return;let value=model[key];return typeof value==="string"&&value.length>0?value:void 0}function resolveContextWindow(inputs){let{userLimits,modelID,providerID,liveContextLimit,fallbackLookup}=inputs;if(userLimits){let normalized,normalizedLimits=()=>{if(normalized===void 0){normalized={};for(let[key,value]of Object.entries(userLimits))normalized[normalizeLimitKey(key)]=value}return normalized};if(modelID&&providerID){let compound=normalizedLimits()[normalizeLimitKey(`${providerID}/${modelID}`)];if(isUsableConfiguredWindow(compound))return{tokens:Math.floor(compound),source:"user_provider_model"}}if(modelID){let byModel=normalizedLimits()[normalizeLimitKey(modelID)];if(isUsableConfiguredWindow(byModel))return{tokens:Math.floor(byModel),source:"user_model"}}let byDefault=normalizedLimits().default;if(isUsableConfiguredWindow(byDefault))return{tokens:Math.floor(byDefault),source:"user_default"}}if(isUsableContextWindow(liveContextLimit))return{tokens:Math.floor(liveContextLimit),source:"live_model_limit"};if(fallbackLookup){let fromTable=fallbackLookup(modelID,providerID);if(fromTable!==void 0&&isUsableContextWindow(fromTable.tokens))return{tokens:Math.floor(fromTable.tokens),source:fromTable.table==="provider_cap"?"static_provider_cap":"static_native"}}return{tokens:128000,source:"static_default"}}function resolveContextWindowTokens(inputs){return resolveContextWindow(inputs).tokens}var DEFAULT_MODEL_CONTEXT_TOKENS=128000;var exports_schema={};__export(exports_schema,{stripKnownSwarmPrefix:()=>stripKnownSwarmPrefix,resolveGuardrailsConfig:()=>resolveGuardrailsConfig,resolveGeneratedAgentRole:()=>resolveGeneratedAgentRole,resolveExternalSkillsConfig:()=>resolveExternalSkillsConfig,resolveAutoReviewConfig:()=>resolveAutoReviewConfig,isKnownCanonicalRole:()=>isKnownCanonicalRole,getCanonicalAgentRole:()=>getCanonicalAgentRole,_internals:()=>_internals3,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,ReviewRoutingConfigSchema:()=>ReviewRoutingConfigSchema,ReviewPassesConfigSchema:()=>ReviewPassesConfigSchema,RetentionConfigSchema:()=>RetentionConfigSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QualityBudgetConfigSchema:()=>QualityBudgetConfigSchema,PrmConfigSchema:()=>PrmConfigSchema,PricingConfigSchema:()=>PricingConfigSchema,PrReviewResilienceConfigSchema:()=>PrReviewResilienceConfigSchema,PrMonitorConfigSchema:()=>PrMonitorConfigSchema,PrFeedbackLoopConfigSchema:()=>PrFeedbackLoopConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanCursorConfigSchema:()=>PlanCursorConfigSchema,PlaceholderScanConfigSchema:()=>PlaceholderScanConfigSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,ParallelizationConfigSchema:()=>ParallelizationConfigSchema,OtlpExportConfigSchema:()=>OtlpExportConfigSchema,ObservabilityConfigSchema:()=>ObservabilityConfigSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LintConfigSchema:()=>LintConfigSchema,LearningConfigSchema:()=>LearningConfigSchema,LeanTurboStrategyConfigSchema:()=>LeanTurboStrategyConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,LaneLivenessWatchdogConfigSchema:()=>LaneLivenessWatchdogConfigSchema,KnowledgeConfigSchema:()=>KnowledgeConfigSchema,KnowledgeApplicationConfigSchema:()=>KnowledgeApplicationConfigSchema,IntegrationAnalysisConfigSchema:()=>IntegrationAnalysisConfigSchema,IncrementalVerifyConfigSchema:()=>IncrementalVerifyConfigSchema,HooksConfigSchema:()=>HooksConfigSchema,HarnessOptConfigSchema:()=>HarnessOptConfigSchema,HarnessEvolutionConfigSchema:()=>HarnessEvolutionConfigSchema,GuardrailsProfileSchema:()=>GuardrailsProfileSchema,GuardrailsConfigSchema:()=>GuardrailsConfigSchema,GitConfigSchema:()=>GitConfigSchema,GeneralCouncilConfigSchema:()=>GeneralCouncilConfigSchema,GateFeatureSchema:()=>GateFeatureSchema,GateConfigSchema:()=>GateConfigSchema,GATE_SECTION_SCHEMAS:()=>GATE_SECTION_SCHEMAS,GATE_CONFIG_READERS:()=>GATE_CONFIG_READERS,GATE_CONFIG_KNOWN_SECTION_KEYS:()=>GATE_CONFIG_KNOWN_SECTION_KEYS,ForgeConfigSchema:()=>ForgeConfigSchema,FALLBACK_MODELS_MAX:()=>FALLBACK_MODELS_MAX,ExternalSkillsConfigSchema:()=>ExternalSkillsConfigSchema,ExternalSkillCandidateSourceTypeSchema:()=>ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateSchema:()=>ExternalSkillCandidateSchema,ExternalSkillCandidateEvaluationVerdictSchema:()=>ExternalSkillCandidateEvaluationVerdictSchema,EvidenceConfigSchema:()=>EvidenceConfigSchema,EpicConfigSchema:()=>EpicConfigSchema,DocsConfigSchema:()=>DocsConfigSchema,DispatchProtectionConfigSchema:()=>DispatchProtectionConfigSchema,DiscoverySourceSchema:()=>DiscoverySourceSchema,DesignDocsConfigSchema:()=>DesignDocsConfigSchema,DecisionDecaySchema:()=>DecisionDecaySchema,DashboardConfigSchema:()=>DashboardConfigSchema,DEFAULT_SKILL_OPT_CONFIG:()=>DEFAULT_SKILL_OPT_CONFIG,DEFAULT_SKILLS_CONFIG:()=>DEFAULT_SKILLS_CONFIG,DEFAULT_REVIEW_ROUTING_CONFIG:()=>DEFAULT_REVIEW_ROUTING_CONFIG,DEFAULT_PR_REVIEW_RESILIENCE_CONFIG:()=>DEFAULT_PR_REVIEW_RESILIENCE_CONFIG,DEFAULT_PR_REVIEW_LEGACY_TRANSCRIPT_COMPATIBILITY:()=>DEFAULT_PR_REVIEW_LEGACY_TRANSCRIPT_COMPATIBILITY,DEFAULT_MODEL_CONTEXT_TOKENS:()=>DEFAULT_MODEL_CONTEXT_TOKENS,DEFAULT_HARNESS_OPT_CONFIG:()=>DEFAULT_HARNESS_OPT_CONFIG,DEFAULT_HARNESS_EVOLUTION_CONFIG:()=>DEFAULT_HARNESS_EVOLUTION_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,CONSERVATIVE_PRESET_BASE:()=>CONSERVATIVE_PRESET_BASE,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 _internals3.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={}){if(context.preset==="conservative")return!1;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=_internals3.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 _internals3,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_SECTION_SCHEMAS,GateConfigSchema,GATE_CONFIG_KNOWN_SECTION_KEYS,GATE_CONFIG_READERS,PipelineConfigSchema,PhaseCompleteConfigSchema,SummaryConfigSchema,RetentionConfigSchema,ReviewPassesConfigSchema,AUTO_REVIEW_V8_BURN_IN_DECISION,CONSERVATIVE_PRESET_BASE,AutoReviewFinalConfigSchema,AutoReviewConfigObjectSchema,AutoReviewConfigSchema,AdversarialDetectionConfigSchema,AdversarialTestingConfigSchemaBase,AdversarialTestingConfigSchema,IntegrationAnalysisConfigSchema,DocsConfigSchema,DesignDocsConfigSchema,GitConfigSchema,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,OtlpExportConfigSchema,ObservabilityConfigSchema,ForgeConfigSchema,MemoryConfigSchema,CuratorConfigSchema,ArchitecturalSupervisionConfigSchema,KnowledgeApplicationConfigSchema,SkillPropagationAudienceSchema,SkillPropagationConfigSchema,HarnessRelativePathSchema,HarnessEvolutionConfigSchema,DEFAULT_HARNESS_EVOLUTION_CONFIG,HarnessOptConfigSchema,DEFAULT_HARNESS_OPT_CONFIG,SkillImproverConfigSchema,SkillsConfigSchema,SkillOptConfigSchema,DEFAULT_SKILL_OPT_CONFIG,SpecWriterConfigSchema,SlopDetectorConfigSchema,IncrementalVerifyConfigSchema,CompactionConfigSchema,PrmConfigSchema,AgentAuthorityRuleSchema,AuthorityConfigSchema,GeneralCouncilMemberConfigSchema,GeneralCouncilConfigSchema,CouncilConfigSchema,PrMonitorConfigSchema,PrFeedbackLoopConfigSchema,ParallelizationConfigSchema,WorktreeIsolationConfigSchema,LeanTurboConfigSchema,EpicConfigSchema,StandardTurboConfigSchema,LeanTurboStrategyConfigSchema,TurboConfigSchema,ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateEvaluationVerdictSchema,DiscoverySourceSchema,ExternalSkillCandidateSchema,ExternalSkillsConfigSchema,DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_SKILLS_CONFIG,DEFAULT_PR_REVIEW_RESILIENCE_CONFIG,PrReviewResilienceConfigSchema,ReviewRoutingConfigSchema,DEFAULT_REVIEW_ROUTING_CONFIG,LaneLivenessWatchdogConfigSchema,DispatchProtectionConfigSchema,DashboardConfigSchema,DEFAULT_PR_REVIEW_LEGACY_TRANSCRIPT_COMPATIBILITY=!1,PluginConfigSchema;var init_schema=__esm(()=>{init_zod();init_package();init_knowledge_types();init_constants();_internals3={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({currency:exports_external.literal("USD").optional().default("USD"),version:exports_external.string().min(1).max(128).optional(),effective_at:exports_external.string().datetime().optional(),billing_basis:exports_external.enum(["token","request","subscription"]).optional(),reported_cost_currency:exports_external.record(exports_external.string().min(1).max(128),exports_external.literal("USD")).optional().default({}),subscription_unbilled:exports_external.boolean().optional().default(!1),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({}),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_SECTION_SCHEMAS={syntax_check:GateFeatureSchema,placeholder_scan:PlaceholderScanConfigSchema,sast_scan:GateFeatureSchema,sbom_generate:GateFeatureSchema,build_check:GateFeatureSchema,quality_budget:QualityBudgetConfigSchema},GateConfigSchema=exports_external.object({syntax_check:GATE_SECTION_SCHEMAS.syntax_check.default({enabled:!0}),placeholder_scan:GATE_SECTION_SCHEMAS.placeholder_scan.default(()=>GATE_SECTION_SCHEMAS.placeholder_scan.parse({})),sast_scan:GATE_SECTION_SCHEMAS.sast_scan.default({enabled:!0}),sbom_generate:GATE_SECTION_SCHEMAS.sbom_generate.default({enabled:!0}),build_check:GATE_SECTION_SCHEMAS.build_check.default({enabled:!0}),quality_budget:GATE_SECTION_SCHEMAS.quality_budget.default(()=>GATE_SECTION_SCHEMAS.quality_budget.parse({}))}),GATE_CONFIG_KNOWN_SECTION_KEYS=Object.fromEntries(Object.entries(GATE_SECTION_SCHEMAS).map(([section,schema])=>[section,Object.keys(schema.shape)])),GATE_CONFIG_READERS={syntax_check:["src/tools/syntax-check.ts"],placeholder_scan:["src/tools/placeholder-scan.ts"],sast_scan:["src/tools/sast-scan.ts","src/tools/pre-check-batch.ts"],sbom_generate:["src/tools/sbom-generate.ts"],build_check:["src/tools/build-check.ts"],quality_budget:["src/tools/quality-budget.ts","src/tools/pre-check-batch.ts"]},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])}),RetentionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),dry_run:exports_external.boolean().default(!1)}).prefault({}),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"};CONSERVATIVE_PRESET_BASE={auto_review:{enabled:!1}},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()}),GitConfigSchema=exports_external.object({binary: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),sandbox_macos_enabled:exports_external.boolean().optional(),sandbox:exports_external.object({mode:exports_external.enum(["advisory","required"]).default("advisory"),require_filesystem:exports_external.boolean().default(!1),require_network:exports_external.boolean().default(!1),require_process:exports_external.boolean().default(!1),network_mode:exports_external.enum(["off","on"]).default("off"),network_allowlist:exports_external.array(exports_external.string().min(1)).max(128).default([]),writable_roots:exports_external.array(exports_external.string().min(1)).max(128).default([])}).optional()}),WatchdogConfigSchema=exports_external.object({scope_guard:exports_external.boolean().default(!0),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([]),storage:exports_external.enum(["json","indexed"]).default("json")}),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("Number of completed tasks that trigger an automatic checkpoint. Retention of old checkpoints is controlled separately by max_retention."),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),receipt_close_grace_days:exports_external.number().int().min(0).max(3650).default(7),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)}),OtlpExportConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),endpoint:exports_external.string().min(1).default(""),convention:exports_external.enum(["genai","openinference"]).default("genai"),headers:exports_external.record(exports_external.string(),exports_external.string()).optional(),batchSize:exports_external.number().int().min(1).max(512).default(64),flushIntervalMs:exports_external.number().int().min(250).max(300000).default(5000),requestTimeoutMs:exports_external.number().int().min(250).max(60000).default(5000),spoolMaxBytes:exports_external.number().int().min(16384).max(16777216).default(1048576),spoolMaxAgeMs:exports_external.number().int().min(60000).max(2592000000).default(86400000),maxRetries:exports_external.number().int().min(0).max(10).default(3),backoffBaseMs:exports_external.number().int().min(10).max(1e4).default(200),backoffMaxMs:exports_external.number().int().min(100).max(300000).default(30000),circuitThreshold:exports_external.number().int().min(1).max(50).default(5),circuitCooldownMs:exports_external.number().int().min(1000).max(600000).default(60000)}),ObservabilityConfigSchema=exports_external.object({export:OtlpExportConfigSchema.optional()}),ForgeConfigSchema=exports_external.object({provider:exports_external.enum(["github","gitlab","auto"]).default("auto"),base_url:exports_external.string().url().optional()}),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}}),reflection:exports_external.object({enabled:exports_external.boolean().default(!1),halfLifeDays:exports_external.number().finite().positive().max(3650).default(30)}).default({enabled:!1,halfLifeDays:30}),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),detectPii:exports_external.boolean().default(!1),piiDetector:exports_external.enum(["regex","ner"]).default("regex"),rejectDurablePii:exports_external.boolean().default(!1),piiThreshold:exports_external.number().min(0).max(1).refine((v)=>v<1,"piiThreshold must be strictly less than 1 (rejection is score > threshold and scores never reach 1, so 1 would silently disable PII rejection)").default(0.7)}).default({rejectDurableSecrets:!0,detectPii:!1,piiDetector:"regex",rejectDurablePii:!1,piiThreshold:0.7}),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([])}),HarnessRelativePathSchema=exports_external.string().min(1).max(1024).refine((value)=>!value.includes("\x00"),"path contains a NUL byte").refine((value)=>!/^(?:[A-Za-z]:[\\/]|[\\/]{1,2})/.test(value),{message:"path must be project-relative"}).refine((value)=>!value.replace(/\\/g,"/").split("/").some((segment)=>segment===".."),"path must not traverse outside the project"),HarnessEvolutionConfigSchema=exports_external.object({source_allowlist:exports_external.array(HarnessRelativePathSchema).max(128).default([]),extra_protected_paths:exports_external.array(HarnessRelativePathSchema).max(128).default([]),max_patch_bytes:exports_external.number().int().min(1).max(16777216).default(1048576),max_files:exports_external.number().int().min(1).max(1024).default(64),max_file_bytes:exports_external.number().int().min(1).max(8388608).default(524288),max_total_bytes:exports_external.number().int().min(1).max(67108864).default(4194304),max_changed_lines:exports_external.number().int().min(1).max(1e5).default(1e4),max_versions:exports_external.number().int().min(1).max(1e4).default(100),max_inactive_candidates:exports_external.number().int().min(0).max(128).default(32),max_replay_records:exports_external.number().int().min(1).max(1e5).default(1e4),max_output_bytes:exports_external.number().int().min(1024).max(1048576).default(262144)}).strict(),DEFAULT_HARNESS_EVOLUTION_CONFIG=Object.freeze(HarnessEvolutionConfigSchema.parse({})),HarnessOptConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),max_rounds:exports_external.number().int().min(1).max(50).default(5),max_transient_retries:exports_external.number().int().min(0).max(10).default(2),max_wall_clock_ms:exports_external.number().int().min(1e4).max(86400000).default(3600000),max_spend_usd:exports_external.number().finite().nonnegative().max(1000).optional(),run_ablation_arm:exports_external.boolean().default(!0),run_simple_agent_arm:exports_external.boolean().default(!0)}).strict(),DEFAULT_HARNESS_OPT_CONFIG=Object.freeze(HarnessOptConfigSchema.parse({})),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(10)}).default(()=>({repetition_loop:2,ping_pong:2,expansion_drift:3,stuck_on_test:3,context_thrash:10})),max_trajectory_lines:exports_external.number().min(10).max(1e4).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).describe("DEPRECATED — inert. Accepted for parse compatibility only; no runtime consumer exists and no timeout is enforced. Config doctor warns when this is explicitly set. Remove the key; dispatch timeouts are governed by the agent host. Scheduled for removal in a future release."),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 (task/phase councils only — the final council uses finalCompletionPolicy). 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 declared for escalation when maxRounds is reached without APPROVE. REMAINS INERT — no handler or webhook execution exists or is added; config doctor warns when it is set (issue #1650). Max-rounds exhaustion emits a durable structured event and a user escalation message; wiring real outbound escalation requires a separate security review."),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."),finalCompletionPolicy:exports_external.object({mode:exports_external.enum(["all_required","quorum"]).default("all_required").describe("'all_required' (default) preserves the exact legacy final council: all five canonical roles, five distinct members, zero absentees. 'quorum' is an explicit weakening that accepts a bounded minimum of distinct canonical members instead of all five."),minimumMembers:exports_external.number().int().min(3).max(5).optional().describe('Required when mode is "quorum": minimum distinct canonical council members (3–5) that must vote. Unknown, duplicate, and cross-swarm identities never count.')}).default({mode:"all_required"}).superRefine((policy,ctx)=>{if(policy.mode==="quorum"&&policy.minimumMembers===void 0)ctx.addIssue({code:"custom",path:["minimumMembers"],message:'finalCompletionPolicy.mode "quorum" requires an explicit minimumMembers between 3 and 5.'})}).describe("Final-council completion policy. Missing/default is all_required (strict five-member requirement). The normalized policy participates in the council policy digest, so any change invalidates previously accepted final-council evidence."),freshnessMaxAgeHours:exports_external.number().int().min(1).max(720).default(24).describe("Maximum age (hours, 1–720) of phase-council, architecture-supervisor, and final-council evidence. Default 24 preserves prior behavior. Part of the council policy digest, so changing it invalidates prior council evidence."),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(),PrFeedbackLoopConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),max_actions_per_pr:exports_external.number().int().min(1).max(10).default(3),max_session_actions:exports_external.number().int().min(1).max(50).default(10),publication:exports_external.enum(["none"]).default("none")}),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),session_create_timeout_ms:exports_external.number().int().min(1000).max(120000).default(30000),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};DEFAULT_PR_REVIEW_RESILIENCE_CONFIG={enabled:!1,canary_probe_ms:300000,status_probe_timeout_ms:2000,correlated_failure_threshold:2,max_retry_attempts_after_initial:2,circuit_open_duration_ms:60000},PrReviewResilienceConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),canary_probe_ms:exports_external.number().int().min(1).max(3600000).default(300000),status_probe_timeout_ms:exports_external.number().int().min(1).max(60000).default(2000),correlated_failure_threshold:exports_external.number().int().min(2).max(8).default(2),max_retry_attempts_after_initial:exports_external.number().int().min(0).max(2).default(2),circuit_open_duration_ms:exports_external.number().int().min(1000).max(1800000).default(60000)}).strict(),ReviewRoutingConfigSchema=exports_external.object({enforce_receipts:exports_external.boolean().default(!0)}).strict(),DEFAULT_REVIEW_ROUTING_CONFIG={enforce_receipts:!0},LaneLivenessWatchdogConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),timeout_ms:exports_external.number().int().min(0).max(86400000).default(1800000),stall_threshold_ms:exports_external.number().int().min(0).max(86400000).default(300000),stall_min_steps:exports_external.number().int().min(0).max(1e4).default(5),stall_token_threshold:exports_external.number().int().min(0).max(1e6).default(200)}).strict(),DispatchProtectionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),spawn_failure_threshold:exports_external.number().int().min(1).max(50).default(3),half_open_after_ms:exports_external.number().int().min(1).max(3600000).default(30000),rate_per_second:exports_external.number().min(0).max(1e4).default(10),burst_capacity:exports_external.number().int().min(1).max(1e4).default(10)}).strict(),DashboardConfigSchema=exports_external.object({port:exports_external.number().int().min(0).max(65535).default(0).describe("Loopback port for the opt-in local dashboard (issue #2509). 0 or absent = disabled (default).")}).strict(),PluginConfigSchema=exports_external.object({$schema:exports_external.string().optional().catch(void 0).describe("JSON Schema URL for editor validation/autocomplete of this file (issue #1663). Ignored at runtime; malformed values are ignored too."),config_format_version:exports_external.number().int().min(0).default(1).describe("Config format version for the migration table. Increment when fields are deprecated. Distinct from knowledge.schema_version."),preset:exports_external.enum(["default","conservative"]).optional().describe('Defaults profile: "default" applies the governed v8 defaults; "conservative" restores the pre-flip (v7) defaults for every flipped surface (#2504).'),agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional().describe('Per-agent overrides keyed by agent name for the default swarm (e.g. "architect", "coder"). Multi-swarm setups configure agents under swarms.<id>.agents instead.'),default_agent:exports_external.string().optional().transform((v)=>{if(v===void 0)return;let trimmed=v.trim();return trimmed===""?void 0:trimmed}).describe('Agent set as the primary mode. Omitted: every generated *_architect is primary. Exact generated name (e.g. "local_architect"): only that agent. Base role name (e.g. "coder"): every generated agent with that base role. Unknown strings warn once and fall back to architect primaries.'),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}).describe('Auto-select the swarm architect for new sessions instead of OpenCode built-ins. Omitted or false: manual selection (omitted behaves as false). true: enable auto-select and disable built-in build/plan agents. "<architect_name>" (e.g. "mega_architect"): enable targeting one architect in multi-swarm setups.'),swarms:exports_external.record(exports_external.string().regex(/^[^_]+$/,"Swarm ID must not contain underscores"),SwarmConfigSchema).optional().describe('Multiple swarms keyed by swarm ID (no underscores allowed). The first swarm, or one named "default", provides the primary architect.'),max_iterations:exports_external.number().min(1).max(10).default(5).describe("Maximum pipeline iterations per task (1-10)."),pipeline:PipelineConfigSchema.optional().describe("Pipeline stage/model settings."),phase_complete:PhaseCompleteConfigSchema.optional().describe("Phase-completion gate settings."),qa_retry_limit:exports_external.number().min(1).max(10).default(3).describe("Maximum QA retry rounds per task (1-10)."),execution_mode:exports_external.enum(["strict","balanced","fast"]).default("balanced").describe('Performance mode controlling optional hook execution overhead: "strict", "balanced", or "fast".'),inject_phase_reminders:exports_external.boolean().default(!0).describe("Inject phase reminder directives during execution."),hooks:HooksConfigSchema.optional().describe("Hook subsystem toggles and settings."),pr_review_resilience:PrReviewResilienceConfigSchema.optional().describe("PR review base-wave staged canary/fanout resilience settings."),review_routing:ReviewRoutingConfigSchema.optional().describe("Semantic review routing receipt enforcement for Stage B (default on; set enforce_receipts=false only as a one-release rollback)."),lane_liveness_watchdog:LaneLivenessWatchdogConfigSchema.optional().describe("Lane liveness watchdog: execution deadline and stall escalation for PR workflow lanes."),dispatch_protection:DispatchProtectionConfigSchema.optional().describe("Dispatch protection: action-local spawn-failure circuit breaker and token-bucket rate limiting for native task delegations."),pr_review_legacy_transcript_compatibility:exports_external.boolean().optional().describe("Deprecated migration-only opt-in for transcript-row PR-review base and micro discovery lanes."),gates:GateConfigSchema.optional().describe("Quality gate configuration (v6.9 anti-slop features)."),context_budget:ContextBudgetConfigSchema.optional().describe("Context budget thresholds."),pricing:PricingConfigSchema.optional().describe("Token/cost estimation fallback table. Provider-reported cost wins when present; entries only estimate from usage tokens when reports omit cost."),guardrails:GuardrailsConfigSchema.optional().describe("Loop containment and safety guardrails: tool-call caps, denial tracking, destructive-command blocking, shell audit."),watchdog:WatchdogConfigSchema.optional().describe("Scope-guard and delegation-ledger watchdog settings."),self_review:SelfReviewConfigSchema.optional().describe("Advisory self-review after coder delegation."),auto_review:AutoReviewConfigSchema.optional().describe("Opt-in execution-diff review by the reviewer model in a fresh ephemeral session at task/phase boundaries."),tool_filter:ToolFilterConfigSchema.optional().describe("Controls which plugin tools each agent is allowed to use; enforced through host-side per-agent permission denies (issue #2528). enabled: false lifts the plugin-tool allow-list but keeps each role's read-only write-family floor."),authority:AuthorityConfigSchema.optional().describe("Per-agent file write authority rules."),plan_cursor:PlanCursorConfigSchema.optional().describe("Compressed plan summary injection settings."),context_map:ContextMapConfigSchema.optional().describe("Context Map (issue #1104, FR-006) — opt-in."),repo_graph:RepoGraphConfigSchema.prefault({}).describe("Repository dependency-graph settings (builder excludes, incremental refresh). Nested defaults materialize when the whole section is omitted."),evidence:EvidenceConfigSchema.optional().describe("Evidence retention and storage settings."),summaries:SummaryConfigSchema.optional().describe("Summary generation settings."),retention:RetentionConfigSchema.describe("Retention sweep settings (issue #2483)."),review_passes:ReviewPassesConfigSchema.optional().describe("Dual-pass security review settings."),adversarial_detection:AdversarialDetectionConfigSchema.optional().describe("Same-model adversarial checker detection settings."),adversarial_testing:AdversarialTestingConfigSchema.optional().describe("Cross-model adversarial testing settings."),integration_analysis:IntegrationAnalysisConfigSchema.optional().describe("Integration analysis settings."),docs:DocsConfigSchema.optional().describe("Documentation synthesizer (docs agent) settings."),design_docs:DesignDocsConfigSchema.optional().describe("Structured design-doc generation (issue #1080, docs_design agent) — opt-in."),speckit_checkoff:exports_external.object({enabled:exports_external.boolean().default(!1).describe("Check off mapped Spec-Kit tasks in the source tasks.md when Swarm completes a plan task (issue #2501). Off by default — write-back to user-owned files is opt-in.")}).optional().describe("Spec-Kit tasks.md check-off round trip (issue #2501) — opt-in, never on by default."),git:GitConfigSchema.optional().describe("Git executable resolution override (issue #2236 hardening)."),ui_review:UIReviewConfigSchema.optional().describe("UI/UX review (designer agent) settings."),compaction_advisory:CompactionAdvisoryConfigSchema.optional().describe("Compaction advisory settings."),lint:LintConfigSchema.optional().describe("Lint gate settings."),secretscan:SecretscanConfigSchema.optional().describe("Secret scanning settings."),checkpoint:CheckpointConfigSchema.optional().describe("Checkpoint settings."),apply_patch:ApplyPatchConfigSchema.optional().describe("Apply-patch opt-in fuzzy matching fallback (issue #1718)."),automation:AutomationConfigSchema.optional().describe("Background automation mode and per-feature toggles (v6.7 background-first rollout)."),knowledge:KnowledgeConfigSchema.optional().describe("Two-tier cross-project knowledge base (v6.17)."),memory:MemoryConfigSchema.optional().describe("Swarm memory substrate — disabled by default so existing flows are unchanged."),forge:ForgeConfigSchema.optional().describe('Forge provider (GitHub/GitLab) selection for PR/issue workflows (issue #2733). Ambiguous git remotes (mixed providers, unrecognized self-hosted hosts, or no remote) fail closed and require an explicit selection; forge.base_url passes through the same HTTPS-only / non-private / ASCII-host guards as every forge URL and is never a trust whitelist; combining base_url with provider "github" is rejected as a configuration conflict.'),observability:ObservabilityConfigSchema.optional().describe("Observability options — remote OTLP/OpenInference export is opt-in and disabled by default (issue #2485)."),learning:LearningConfigSchema.optional().describe("Learning subsystem: real-time admission, PRM persistence, dedup sweep (issue #1821)."),consensus:ConsensusConfigSchema.optional().describe("Consensus mining over completed run evidence (issue #1821)."),curator:CuratorConfigSchema.optional().describe("Phase context consolidation and drift detection."),architectural_supervision:ArchitecturalSupervisionConfigSchema.optional().describe("Hierarchical summary review (issue #893)."),knowledge_application:KnowledgeApplicationConfigSchema.optional().describe("Knowledge-application contract (v2): warn or enforce modes, ack tracking."),skillPropagation:SkillPropagationConfigSchema.optional().describe("Skill propagation gate/injection settings."),skill_improver:SkillImproverConfigSchema.optional().describe("Low-frequency, expensive-model skill improvement loop (issue #629, v2)."),harness_evolution:HarnessEvolutionConfigSchema.optional().describe("Declarative, non-executing HarnessOpt mutation policy (issue #1825)."),harness_opt:HarnessOptConfigSchema.optional().describe("Governed HarnessOpt optimization capstone (issue #2503). Disabled by default; /swarm harness-opt run requires enabled: true plus --confirm."),spec_writer:SpecWriterConfigSchema.optional().describe("Spec writer agent (v2) — independent model for .swarm/spec.md authorship."),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().describe("Tool output truncation settings (enable/disable, max lines, per-tool overrides)."),slop_detector:SlopDetectorConfigSchema.optional().describe("Slop detector settings (v6.29)."),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().describe("TODO gate (v6.32): warn or block on new high-priority TODOs (FIXME/HACK/XXX)."),incremental_verify:IncrementalVerifyConfigSchema.optional().describe("Incremental verification settings (v6.29)."),compaction_service:CompactionConfigSchema.optional().describe("Compaction service settings (v6.29)."),prm:PrmConfigSchema.optional().describe("PRM (Process Remediation Manager) settings."),council:CouncilConfigSchema.optional().describe("Work Complete Council — parallel four-member verification gate, off by default."),parallelization:ParallelizationConfigSchema.optional().describe("Parallelization (PR 1 dark foundation) — disabled by default; no production code path branches on enabled=true yet."),worktree:WorktreeIsolationConfigSchema.optional().describe("Worktree isolation policy for parallel coder dispatch lanes (general surface; Lean Turbo keeps its legacy per-mode fields)."),turbo:TurboConfigSchema.optional().describe("Turbo execution strategy block (Phase 1). Absent means current behavior unchanged."),turbo_mode:exports_external.boolean().default(!1).optional().describe("Bypass reviewer/test gates for rapid iteration (v6.40). When true, new sessions start with turbo mode on (session default); /swarm turbo still toggles per session. Directory-less constructions default off."),quiet:exports_external.boolean().default(!0).optional().describe("Suppress non-critical startup warnings (default true keeps the TUI clean). Set false to restore verbose warnings for debugging."),version_check:exports_external.boolean().default(!0).optional().describe("Background staleness check against npm, throttled to once per 24h (issue #675). Set false to fully disable the network call."),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),total_timeout_ms:exports_external.number().int().min(1000).max(300000).default(120000),cleanup_timeout_ms:exports_external.number().int().min(100).max(1e4).default(2000)}).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,total_timeout_ms:120000,cleanup_timeout_ms:2000}))}).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,total_timeout_ms:120000,cleanup_timeout_ms:2000}})).describe("Full-auto autonomous orchestration with critic oversight: permission policy, denial accounting, oversight cadence triggers (v2 preserves v1 fields so existing configs load unchanged)."),pr_feedback_loop:PrFeedbackLoopConfigSchema.optional().describe("Autonomous PR babysitting settling loop (issue #2502) — triple opt-in with pr_monitor.enabled + pr_monitor.auto_pr_feedback; off by default; publication profile is none-only."),pr_monitor:PrMonitorConfigSchema.optional().describe("GitHub PR subscription and polling (FR-001) — disabled by default; opt-in for real-time PR status updates."),external_skills:ExternalSkillsConfigSchema.optional().describe("External skills: candidate model, discovery, and quarantine store (FR-001) — all subsystems opt-in."),skills:SkillsConfigSchema.optional().describe("Opt-in gate for the 7 skill_* management tools (FR-004). Default false: the tools are host-denied for every agent except skill_improver (genuinely unreachable, not merely unlisted — issue #2528)."),skill_opt:SkillOptConfigSchema.optional().describe("Governed skill optimizer (issue #1822). Disabled by default; /swarm skill-opt run requires enabled: true. All other subcommands are proposal-only/read-only by default."),dashboard:DashboardConfigSchema.optional().describe("Opt-in local mission-control dashboard over durable swarm state (issue #2509). Disabled by default; set port > 0 to enable the loopback-only read-only view.")})});var exports_loader={};__export(exports_loader,{resetConfigAdvisoryDedup:()=>resetConfigAdvisoryDedup,loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadGateOverrides:()=>loadGateOverrides,loadAgentPrompt:()=>loadAgentPrompt,getSafeDefaultConfigLoadResult:()=>getSafeDefaultConfigLoadResult,formatZodIssues:()=>formatZodIssues,deepMerge:()=>deepMerge,_internals:()=>_internals4,MAX_MERGE_DEPTH:()=>MAX_MERGE_DEPTH,MAX_CONFIG_FILE_BYTES:()=>MAX_CONFIG_FILE_BYTES});import*as fs2 from"node:fs";import*as fsPromises from"node:fs/promises";import*as os2 from"node:os";import*as path2 from"node:path";function gatesAdvisoryWarn(message,data){if(gatesAdvisorySignatures.has(message))return;if(gatesAdvisorySignatures.size>=MAX_GATES_ADVISORY_SIGNATURES)gatesAdvisorySignatures.clear();gatesAdvisorySignatures.add(message),advisoryWarn(message,data)}function getUserConfigDir(){return process.env.XDG_CONFIG_HOME||path2.join(os2.homedir(),".config")}function loadRawConfigFromPath(configPath){try{if(fs2.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=fs2.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}}let dormantLegacyKeys=["preset","presets","swarm_mode"].filter((key)=>(key in raw)&&(key!=="preset"||raw.preset!=="default"&&raw.preset!=="conservative"));if(dormantLegacyKeys.length>0&&raw.agents){let cleaned={...raw};for(let key of dormantLegacyKeys)delete cleaned[key];return advisoryWarn(`[opencode-swarm] Ignored legacy v6.12 config key(s): ${dormantLegacyKeys.join(", ")}. The agents block takes precedence — consider removing them from your opencode-swarm.json.`),cleaned}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)){gatesAdvisoryWarn("[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){gatesAdvisoryWarn(`[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))gatesAdvisoryWarn(`[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(gatesAdvisoryWarn(`[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,rawGates:cleanedGates};gatesAdvisoryWarn("[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,rawGates}=sanitizeGatesConfig(afterExternal);return{result,strippedKeys:[...externalStripped,...gatesStripped],rawGates}}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 exposedGitBinary(raw){if(!raw||typeof raw!=="object")return;let git=raw.git;if(!git||typeof git!=="object"||Array.isArray(git))return;return git.binary}function enforceGitBinaryProvenance(mergedRaw,rawUserConfig){let userBinary=exposedGitBinary(rawUserConfig),exposedBinary=exposedGitBinary(mergedRaw);if(Object.is(exposedBinary,userBinary))return mergedRaw;advisoryWarn(`[opencode-swarm] ⚠️ SECURITY: Ignoring "git.binary" supplied by the project config (.opencode/${CONFIG_FILENAME}). That file lives inside the repository, so it is untrusted content, and "git.binary" selects the executable this plugin spawns for every git command. Set it in your user config (<config dir>/opencode/${CONFIG_FILENAME}) or the ${GIT_BINARY_ENV_VAR} environment variable instead.`);let exposedGit=mergedRaw.git,nextGit=exposedGit&&typeof exposedGit==="object"&&!Array.isArray(exposedGit)?{...exposedGit}:{},rebuilt={...mergedRaw};if(userBinary===void 0){if(delete nextGit.binary,Object.keys(nextGit).length===0)return delete rebuilt.git,rebuilt}else nextGit.binary=userBinary;return rebuilt.git=nextGit,rebuilt}function buildConfigWithMeta(rawUserConfig,rawProjectConfig,loadedFromFile,configHadErrors){let mergedRaw=rawUserConfig??{};if(rawProjectConfig)try{mergedRaw=deepMerge(mergedRaw,rawProjectConfig)}catch(err){if(err instanceof DangerousMergeKeyError)advisoryWarn(`[opencode-swarm] ⚠️ SECURITY: Ignoring the entire project config (.opencode/${CONFIG_FILENAME}): it carries the dangerous key "${err.key}" at "${err.path}", a prototype-pollution payload. Continuing with user-level configuration only.`);else throw err}if(mergedRaw=enforceGitBinaryProvenance(mergedRaw,rawUserConfig),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}}}if(mergedRaw=migratePresetsConfig(mergedRaw),mergedRaw.preset==="conservative")mergedRaw=deepMerge(CONSERVATIVE_PRESET_BASE,mergedRaw);let{result:sanitized,strippedKeys:gatesStripped,rawGates}=sanitizeSectionConfigs(mergedRaw);mergedRaw=sanitized;let knownTopLevel=new Set(Object.keys(PluginConfigSchema.shape)),unknownTopLevel=Object.keys(mergedRaw).filter((key)=>!knownTopLevel.has(key));if(unknownTopLevel.length>0){let signature=unknownTopLevel.join("\x00");if(signature!==lastUnknownTopLevelSig)lastUnknownTopLevelSig=signature,advisoryWarn(`[opencode-swarm] Ignored ${unknownTopLevel.length} unknown top-level config key(s): ${unknownTopLevel.join(", ")}. These keys have no effect — see docs/configuration.md (Top-level configuration keys) for the valid key list.`)}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:[],rawGates};return{config:config2,recovery:gatesStripped.length>0?"stripped_keys":"none",removedKeys:[...gatesStripped],warnings:[],rawGates}}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:[],rawGates}}if(rawUserConfig){let{result:userSanitized,strippedKeys:userGatesStripped,rawGates:userRawGates}=sanitizeSectionConfigs(rawUserConfig),userPresetMigrated=migratePresetsConfig(userSanitized),userPresetReady=userPresetMigrated.preset==="conservative"?deepMerge(CONSERVATIVE_PRESET_BASE,userPresetMigrated):userPresetMigrated,userParseResult=PluginConfigSchema.safeParse(userPresetReady);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."],rawGates:userRawGates};let userStripped=stripUnrecognizedKeys(userPresetReady,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."],rawGates:userRawGates}}}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:[],rawGates}}}}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=path2.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path2.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=path2.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path2.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,rawGates}=buildConfigWithMeta(userResult.config,projectResult.config,loadedFromFile,configHadErrors);return{config:config2,loadedFromFile,configHadErrors,recovery,removedKeys,warnings,rawGates}}function loadGateOverrides(directory){try{return loadPluginConfigWithMeta(directory).rawGates}catch{return}}function resetConfigAdvisoryDedup(){gatesAdvisorySignatures.clear(),lastUnknownTopLevelSig=null}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=path2.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path2.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,rawGates}=buildConfigWithMeta(userResult.config,projectResult.config,loadedFromFile,configHadErrors);return{config:config2,loadedFromFile,configHadErrors,recovery,removedKeys,warnings,rawGates}}function loadAgentPrompt(agentName){let promptsDir=path2.join(getUserConfigDir(),"opencode",PROMPTS_DIR_NAME),result={},promptPath=path2.join(promptsDir,`${agentName}.md`);if(fs2.existsSync(promptPath))try{result.prompt=fs2.readFileSync(promptPath,"utf-8")}catch(error49){advisoryWarn(`[opencode-swarm] Error reading prompt file ${promptPath}:`,error49 instanceof Error?error49.message:String(error49))}let appendPromptPath=path2.join(promptsDir,`${agentName}_append.md`);if(fs2.existsSync(appendPromptPath))try{result.appendPrompt=fs2.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,lastUnknownTopLevelSig=null,gatesAdvisorySignatures,MAX_GATES_ADVISORY_SIGNATURES=64,_internals4;var init_loader=__esm(()=>{init_warning_buffer();init_git_executable();init_schema();init_merge();init_merge();gatesAdvisorySignatures=new Set;_internals4={resetUnknownTopLevelKeyWarning(){lastUnknownTopLevelSig=null},resetGatesAdvisoryDedup(){gatesAdvisorySignatures.clear()}}});function isPhaseStatusTerminal(status){return status==="complete"||status==="completed"||status==="closed"}function isPhaseEffectivelyTerminal(phase){if(isPhaseStatusTerminal(phase.status))return!0;let tasks=phase.tasks??[];return tasks.length>0&&tasks.every((task)=>task.status==="completed"||task.status==="closed")}function resolveActivePhaseId(plan){let cursor=plan.current_phase;if(cursor!==void 0){let cursorPhase=plan.phases.find((phase)=>phase.id===cursor);if(cursorPhase&&!isPhaseEffectivelyTerminal(cursorPhase))return cursorPhase.id}let firstNonTerminal=plan.phases.find((phase)=>!isPhaseEffectivelyTerminal(phase));if(firstNonTerminal)return firstNonTerminal.id;return plan.phases[plan.phases.length-1]?.id??1}function normalizeCurrentPhaseInPlace(plan){plan.current_phase=resolveActivePhaseId(plan)}function getCurrentPhase(plan){return resolveActivePhaseId(plan)}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),commit_after_each_completed_task:exports_external.boolean().default(!1),planning_profile:exports_external.enum(["balanced","strict"]).optional()}),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(/^(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)?FR-(?!000)\d{3}$/,"Requirement ID must match FR-### (e.g., FR-001) or a feature-scoped <featureId>/FR-### form (e.g., 001-login/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",session_create_timeout_ms:DEFAULT_WORKTREE_ISOLATION_CONFIG.session_create_timeout_ms,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,resetConfigAdvisoryDedup:()=>resetConfigAdvisoryDedup,loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadGateOverrides:()=>loadGateOverrides,loadAgentPrompt:()=>loadAgentPrompt,isSubagent:()=>isSubagent,isQAAgent:()=>isQAAgent,getSafeDefaultConfigLoadResult:()=>getSafeDefaultConfigLoadResult,_internals:()=>_internals5,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,ReviewRoutingConfigSchema:()=>ReviewRoutingConfigSchema,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,GATE_SECTION_SCHEMAS:()=>GATE_SECTION_SCHEMAS,GATE_CONFIG_READERS:()=>GATE_CONFIG_READERS,ExecutionProfileSchema:()=>ExecutionProfileSchema,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 _internals5;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();_internals5={loadPluginConfigWithMeta}});function splitEmbeddedAgentVariant(model){let segments=model.split("/"),lastSegment=segments[segments.length-1]??"";if(segments.length<3||!KNOWN_EMBEDDED_VARIANTS.has(lastSegment))return{model};return{model:segments.slice(0,-1).join("/"),variant:lastSegment}}function safeGet(entries,key){if(!entries||!Object.hasOwn(entries,key))return;return entries[key]}function canonicalAgentName(agentName){let normalized=agentName.trim().toLowerCase();if(CANONICAL_AGENT_NAMES.has(normalized))return normalized;for(let candidate of ALL_AGENT_NAMES)if(normalized.endsWith(`_${candidate}`))return candidate;return}function resolveAgentTarget(config2,exactAgentName){let normalizedTarget=exactAgentName.trim().toLowerCase();if(!normalizedTarget)return;let baseAgentName=canonicalAgentName(normalizedTarget);if(!baseAgentName)return;let swarms=config2.swarms,swarmIDs=swarms?Object.keys(swarms):[];if(swarmIDs.length===0){if(normalizedTarget!==baseAgentName)return;return{baseAgentName,override:safeGet(config2.agents,baseAgentName)}}for(let swarmID of swarmIDs){if((swarmID==="default"?baseAgentName:`${swarmID}_${baseAgentName}`).toLowerCase()!==normalizedTarget)continue;let swarmOverride=safeGet(swarms?.[swarmID]?.agents,baseAgentName);return{baseAgentName,override:swarmOverride??safeGet(config2.agents,baseAgentName)}}return}function resolveConfiguredAgentModel(config2,exactAgentName){let configuredModel=resolveAgentTarget(config2,exactAgentName)?.override?.model;if(typeof configuredModel!=="string")return;let trimmed=configuredModel.trim();return trimmed?splitEmbeddedAgentVariant(trimmed).model:void 0}function resolveRegisteredAgentModel(config2,exactAgentName){let target=resolveAgentTarget(config2,exactAgentName);if(!target)return;return resolveConfiguredAgentModel(config2,exactAgentName)??DEFAULT_MODELS[target.baseAgentName]??DEFAULT_MODELS.default}function resolveEffectiveAgentOverride(config2,exactAgentName){let target=resolveAgentTarget(config2,exactAgentName);if(!target)return;return{baseAgentName:target.baseAgentName,model:target.override?.model,fallbackModels:target.override?.fallback_models,disabled:target.override?.disabled}}function resolveRuntimeAgentModel(config2,registeredAgents,exactAgentName){let normalizedTarget=exactAgentName.trim().toLowerCase();if(!normalizedTarget)return;let registeredName=Object.keys(registeredAgents).find((name)=>name.toLowerCase()===normalizedTarget);if(!registeredName)return;let registeredAgent=registeredAgents[registeredName];if(registeredAgent?.mode==="primary")return;let configuredModel=resolveConfiguredAgentModel(config2,registeredName);if(configuredModel)return configuredModel;if(typeof registeredAgent?.model!=="string")return;return registeredAgent.model.trim()||void 0}function parseAgentModel(model){let trimmed=model.trim();if(!trimmed)return;let separatorIndex=trimmed.indexOf("/");if(separatorIndex===-1)return{modelID:trimmed};let providerID=trimmed.slice(0,separatorIndex).trim(),modelID=trimmed.slice(separatorIndex+1).trim();if(!providerID||!modelID||modelID.startsWith("/")||modelID.endsWith("/"))return;return{modelID,providerID}}var CANONICAL_AGENT_NAMES,KNOWN_EMBEDDED_VARIANTS;var init_agent_model=__esm(()=>{init_agent_names();init_constants();CANONICAL_AGENT_NAMES=new Set(ALL_AGENT_NAMES),KNOWN_EMBEDDED_VARIANTS=new Set(["low","medium","high","max","xhigh","thinking"])});function renderPlanningProfileDirective(resolution,context="runtime"){let header=context==="repository_default"?`[PLANNING PROFILE DEFAULT — USE ONLY WHEN NO RUNTIME RESOLUTION EXISTS] effective=${resolution.effective} source=${resolution.source}`:`[PLANNING PROFILE — CURRENT RUNTIME AUTHORITY] effective=${resolution.effective} source=${resolution.source}`,precedence=context==="runtime"?`
159
159
  This runtime resolution supersedes any planning-profile default in the base prompt.`:"";if(resolution.effective==="balanced")return`${header}${precedence}
160
160
  BALANCED ceremony: use durable QA and execution defaults without pausing for the full questionnaire. Do not require a spec solely as ceremony. Ask the user only about unresolved material ambiguity, destructive or high-risk authorization, or another decision only they can make. save_plan exact-binds the default QA profile; persist planning_profile: "balanced" in the execution profile. Follow persisted QA gates after save.`;return`${header}${precedence}
161
161
  STRICT ceremony: require an effective spec, run the complete clarification funnel, present the unified QA/execution questionnaire, wait for the user's answers, exact-bind those choices, and persist planning_profile: "strict". A locked legacy profile with no field uses this ceremony without materializing a new hash field.`}function resolveRepositoryDefaultPlanningProfile(config2){return config2.execution_mode==="strict"?"strict":"balanced"}function resolvePlanningProfile({directory,incomingExecutionProfile,existingExecutionProfile,resetStatuses,config:config2}){if(incomingExecutionProfile?.planning_profile)return{effective:incomingExecutionProfile.planning_profile,persisted:incomingExecutionProfile.planning_profile,source:"incoming"};let existingProfile=resetStatuses?void 0:existingExecutionProfile;if(existingProfile?.planning_profile)return{effective:existingProfile.planning_profile,persisted:existingProfile.planning_profile,source:"persisted"};if(existingProfile?.locked===!0)return{effective:"strict",persisted:void 0,source:"legacy_locked_default"};let loadedConfig=config2??loadPluginConfig(directory),repositoryDefault=resolveRepositoryDefaultPlanningProfile(loadedConfig);return{effective:repositoryDefault,persisted:repositoryDefault,source:"repository_default"}}function normalizeExecutionProfileForHash(profile){if(!profile)return;return{...profile,commit_after_each_completed_task:profile.commit_after_each_completed_task===!0?!0:void 0}}var init_planning_profile=__esm(()=>{init_loader()});import*as fsSync from"node:fs";import*as fs3 from"node:fs/promises";import*as path3 from"node:path";function noteKnownToExist(resolvedPath){if(knownToExist.has(resolvedPath))return;if(knownToExist.add(resolvedPath),knownToExist.size>MAX_KNOWN_TO_EXIST_PATHS){let oldest=knownToExist.values().next().value;if(oldest!==void 0)knownToExist.delete(oldest)}}function wasObservedToExist(filePath){return knownToExist.has(path3.resolve(filePath))}function sameStamp(a,b){return a.mtimeMs===b.mtimeMs&&a.ctimeMs===b.ctimeMs&&a.size===b.size}async function getStamp(filePath){try{let stat3=await _internals6.stat(filePath);if(!stat3.isFile())return null;return{mtimeMs:stat3.mtimeMs,ctimeMs:stat3.ctimeMs,size:stat3.size}}catch{return stats.statFailureCount++,null}}function getStampSync(filePath){try{let stat3=_internals6.statSync(filePath);if(!stat3.isFile())return null;return{mtimeMs:stat3.mtimeMs,ctimeMs:stat3.ctimeMs,size:stat3.size}}catch{return stats.statFailureCount++,null}}function canStoreRead(before,after){return after!==null&&sameStamp(before,after)}function setBounded(cache2,key,value,cacheKind){cache2.set(key,value);while(cache2.size>MAX_CACHE_ENTRIES){let oldest=cache2.keys().next().value;if(oldest===void 0)break;if(cache2.delete(oldest),stats.evictionCount++,cacheKind==="text")stats.textEvictionCount++;else stats.parsedEvictionCount++}stats.textEntryCount=textCache.size,stats.parsedEntryCount=parsedCache.size}function cloneCachedValue(value){if(value===null||typeof value!=="object")return value;if(typeof structuredClone==="function")return structuredClone(value);return stats.cloneFallbackCount++,JSON.parse(JSON.stringify(value))}function readCachedTextFileSync(filePath,directRead){let cacheKey=path3.resolve(filePath),stamp=getStampSync(cacheKey);if(!stamp)return stats.textReadCount++,directRead();noteKnownToExist(cacheKey);let cached2=textCache.get(cacheKey);if(cached2&&sameStamp(cached2,stamp))return stats.textCacheHitCount++,cached2.value;stats.textCacheMissCount++,stats.textReadCount++;let value=directRead(),afterReadStamp=getStampSync(cacheKey);if(value!==null&&canStoreRead(stamp,afterReadStamp))setBounded(textCache,cacheKey,{...afterReadStamp,value},"text");return value}async function readCachedTextFile(filePath,directRead){let cacheKey=path3.resolve(filePath),stamp=await getStamp(cacheKey);if(!stamp)return stats.textReadCount++,directRead();noteKnownToExist(cacheKey);let cached2=textCache.get(cacheKey);if(cached2&&sameStamp(cached2,stamp))return stats.textCacheHitCount++,cached2.value;stats.textCacheMissCount++,stats.textReadCount++;let value=await directRead(),afterReadStamp=await getStamp(cacheKey);if(value!==null&&canStoreRead(stamp,afterReadStamp))setBounded(textCache,cacheKey,{...afterReadStamp,value},"text");return value}function readCachedParsedFileSync(filePath,namespace,readText,parse5){let resolvedPath=path3.resolve(filePath),cacheKey=`${resolvedPath}\x00${namespace}`,stamp=getStampSync(resolvedPath);if(!stamp){stats.parsedReadCount++;let content2=readText();if(content2===null)return null;return stats.parseCount++,parse5(content2)}let cached2=parsedCache.get(cacheKey);if(cached2&&sameStamp(cached2,stamp))return stats.parsedCacheHitCount++,cloneCachedValue(cached2.value);stats.parsedCacheMissCount++,stats.parsedReadCount++;let content=readText();if(content===null)return null;stats.parseCount++;let value=parse5(content),afterReadStamp=getStampSync(resolvedPath);if(canStoreRead(stamp,afterReadStamp))setBounded(parsedCache,cacheKey,{...afterReadStamp,value},"parsed");return cloneCachedValue(value)}async function readCachedParsedFile(filePath,namespace,readText,parse5){let resolvedPath=path3.resolve(filePath),cacheKey=`${resolvedPath}\x00${namespace}`,stamp=await getStamp(resolvedPath);if(!stamp){stats.parsedReadCount++;let content2=await readText();if(content2===null)return null;return stats.parseCount++,parse5(content2)}let cached2=parsedCache.get(cacheKey);if(cached2&&sameStamp(cached2,stamp))return stats.parsedCacheHitCount++,cloneCachedValue(cached2.value);stats.parsedCacheMissCount++,stats.parsedReadCount++;let content=await readText();if(content===null)return null;stats.parseCount++;let value=parse5(content),afterReadStamp=await getStamp(resolvedPath);if(canStoreRead(stamp,afterReadStamp))setBounded(parsedCache,cacheKey,{...afterReadStamp,value},"parsed");return cloneCachedValue(value)}function invalidateCachedArtifact(filePath){let resolvedPath=path3.resolve(filePath);textCache.delete(resolvedPath);let prefix=`${resolvedPath}\x00`;for(let key of parsedCache.keys())if(key.startsWith(prefix))parsedCache.delete(key)}function resetSwarmArtifactCache(){textCache.clear(),parsedCache.clear(),stats.textReadCount=0,stats.textCacheHitCount=0,stats.textCacheMissCount=0,stats.parsedReadCount=0,stats.parseCount=0,stats.parsedCacheHitCount=0,stats.parsedCacheMissCount=0,stats.statFailureCount=0,stats.evictionCount=0,stats.textEvictionCount=0,stats.parsedEvictionCount=0,stats.cloneFallbackCount=0,stats.textEntryCount=0,stats.parsedEntryCount=0}var MAX_CACHE_ENTRIES=128,textCache,parsedCache,MAX_KNOWN_TO_EXIST_PATHS=512,knownToExist,stats,_internals6;var init_swarm_artifact_cache=__esm(()=>{textCache=new Map,parsedCache=new Map,knownToExist=new Set;stats={textReadCount:0,textCacheHitCount:0,textCacheMissCount:0,parsedReadCount:0,parseCount:0,parsedCacheHitCount:0,parsedCacheMissCount:0,statFailureCount:0,evictionCount:0,textEvictionCount:0,parsedEvictionCount:0,cloneFallbackCount:0,textEntryCount:0,parsedEntryCount:0};_internals6={stat:fs3.stat,statSync:fsSync.statSync}});function resolvePrompt(base,custom2,append){if(custom2)return custom2;if(append)return`${base}
@@ -4057,7 +4057,7 @@ ${USAGE12}`;let councilFlag=parsed.council?"council=true":"council=false",signal
4057
4057
  ... (output truncated)`,NODE_MODULES="node_modules",BIN_DIRECTORY=".bin",MAX_PACKAGE_MANIFEST_BYTES=262144,MAX_PATH_SHIM_BYTES=65536,UNSAFE_SHELL_WRAPPER_EXTENSIONS,lintWindowsBatchDeps,LINTER_PACKAGES,lint,_internals187;var init_lint=__esm(()=>{init_zod();init_discovery();init_utils();init_external_tool_runner();init_windows_batch();init_create_tool();init_path_security();SUPPORTED_LINTERS=["biome","eslint"],UNSAFE_SHELL_WRAPPER_EXTENSIONS=new Set([".bat",".cmd",".ps1"]),lintWindowsBatchDeps={platform:()=>_internals187.platform(),comSpec:()=>_internals187.comSpec(),realpathSync:(candidate2)=>_internals187.realpathSync(candidate2),statSync:(candidate2)=>_internals187.statSync(candidate2)},LINTER_PACKAGES={biome:"@biomejs/biome",eslint:"eslint"};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,ctx){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,resolvedLinter=await _internals187.detectResolvedLinter(directory,ctx?.abort);if(resolvedLinter){let result=await _internals187.runResolvedLint(resolvedLinter,mode,directory,ctx?.abort);return JSON.stringify(result,null,2)}let additionalLinter=_internals187.detectAdditionalLinter(cwd);if(additionalLinter){warn(`[lint] Using ${additionalLinter} linter for this project`);let result=await _internals187.runAdditionalLint(additionalLinter,mode,cwd,ctx?.abort);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
4058
4058
  For Python: pip install ruff
4059
4059
  For Rust: rustup component add clippy`},null,2)}}),_internals187={MAX_PACKAGE_MANIFEST_BYTES,MAX_PATH_SHIM_BYTES,arch:()=>process.arch,closeSync:fs124.closeSync,comSpec:()=>process.env.ComSpec,detectAdditionalLinter,detectAvailableLinter,detectResolvedLinter,execPath:()=>process.execPath,existsSync:fs124.existsSync,fstatSync:fs124.fstatSync,isCommandAvailable,openSync:fs124.openSync,pathEnv:()=>process.env.PATH??"",platform:()=>process.platform,readFileSync:fs124.readFileSync,readSync:fs124.readSync,readdirSync:fs124.readdirSync,realpathSync:fs124.realpathSync,resolveLinterCommand,runAdditionalLint,runExternalTool,runLint,runResolvedLint,statSync:fs124.statSync}});import*as fs125 from"node:fs";import*as path236 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=path236.join(scanDir,".secretscanignore");try{if(!fs125.existsSync(ignorePath))return[];let content=fs125.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(path236.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=path236.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 sorted2=[...findings].sort((a,b)=>a.matchStart-b.matchStart),result="",lastEnd=0;for(let finding of sorted2){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 getStableFileIdentity(stat23){let{dev,ino}=stat23;if(dev<0n||ino<0n||dev===0n&&ino===0n)return null;return`${dev}:${ino}`}function readBoundedFile2(filePath,expectedPathStat){let expectedIdentity=getStableFileIdentity(expectedPathStat);if(expectedIdentity===null)return{status:"incomplete",reason:"read_error"};let fd=null;try{let flags=fs125.constants.O_RDONLY|(O_NOFOLLOW!==void 0?O_NOFOLLOW:0);fd=_internals188.openFile(filePath,flags)}catch{return{status:"incomplete",reason:"read_error"}}let outcome,closeFailed=!1;try{let stat23=_internals188.fstatFile(fd),descriptorIdentity=getStableFileIdentity(stat23),initialSize=stat23.size;if(!stat23.isFile())outcome={status:"incomplete",reason:"non_file"};else if(descriptorIdentity===null||descriptorIdentity!==expectedIdentity)outcome={status:"incomplete",reason:"read_error"};else{let bufferLength=initialSize>=BigInt(MAX_FILE_SIZE_BYTES4)?MAX_FILE_SIZE_BYTES4+1:Number(initialSize)+1,buffer=Buffer.allocUnsafe(bufferLength),bytesRead=0;while(bytesRead<buffer.length){let count=_internals188.readFileChunk(fd,buffer,bytesRead,buffer.length-bytesRead,null);if(count===0)break;bytesRead+=count}let postStat=_internals188.fstatFile(fd),postDescriptorIdentity=getStableFileIdentity(postStat),postPathStat=_internals188.lstatFile(filePath),postPathIdentity=getStableFileIdentity(postPathStat);if(!postStat.isFile()||postDescriptorIdentity===null||postDescriptorIdentity!==descriptorIdentity||postPathStat.isSymbolicLink()||!postPathStat.isFile()||postPathIdentity===null||postPathIdentity!==descriptorIdentity)outcome={status:"incomplete",reason:"read_error"};else if(postStat.size!==initialSize)outcome={status:"incomplete",reason:postStat.size>BigInt(MAX_FILE_SIZE_BYTES4)?"oversized":"read_error"};else outcome={status:"ok",buffer:buffer.subarray(0,bytesRead),truncated:initialSize>MAX_FILE_SIZE_BYTES4}}}catch{outcome={status:"incomplete",reason:"read_error"}}finally{if(fd!==null)try{_internals188.closeFile(fd)}catch{closeFailed=!0}}if(closeFailed)return{status:"incomplete",reason:"read_error"};return outcome}function scanFileForSecrets(filePath,mode){let findings=[];try{let lstat11=_internals188.lstatFile(filePath);if(lstat11.isSymbolicLink())return mode==="explicit"?{status:"incomplete",reason:"symlink"}:{status:"skipped",reason:"symlink"};if(!lstat11.isFile())return{status:"incomplete",reason:"non_file"};let readOutcome=readBoundedFile2(filePath,lstat11);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(`
4060
- `);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((resolve94)=>setImmediate(resolve94))}function serializeSecretscanResult(result){let findings=result.findings,candidate2=result,json3=JSON.stringify(candidate2,null,2);while(Buffer.byteLength(json3,"utf8")>MAX_OUTPUT_BYTES4&&findings.length>0)findings=findings.slice(0,Math.floor(findings.length/2)),candidate2={...result,findings,message:"Output truncated due to size limits."},json3=JSON.stringify(candidate2,null,2);if(Buffer.byteLength(json3,"utf8")>MAX_OUTPUT_BYTES4)candidate2={...result,findings:[],message:"Output truncated due to size limits."},json3=JSON.stringify(candidate2,null,2);return json3}function isSymlinkLoop(realPath,visited){if(visited.has(realPath))return!0;return visited.add(realPath),!1}function isPathWithinScope(realPath,scanDir){return isCanonicalPathWithinRoot(realPath,scanDir)}function toSafeRelativePath(rootDir2,targetPath){let relative54=path236.relative(rootDir2,targetPath).replace(/\\/g,"/");if(!relative54||relative54===".")return".";if(relative54.startsWith("..")||path236.isAbsolute(relative54))return path236.basename(targetPath).replace(/\\/g,"/")||".";return relative54}function recordIncompletePath(target,rootDir2,targetPath,reason){if(target.length>=MAX_INCOMPLETE_PATHS){target[MAX_INCOMPLETE_PATHS-1]={path:".",reason:"truncated"};return}target.push({path:toSafeRelativePath(rootDir2,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(state2,filePath){state2.totalCandidates++;let heap=state2.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,state2){let pending=[dir];while(pending.length>0){if(state2.deadlineExceeded||state2.cleanupFailed)return;let currentDir=pending.pop();if(!currentDir)continue;let directory;try{directory=fs125.opendirSync(currentDir)}catch{stats2.fileErrors++,recordIncompletePath(state2.incompletePaths,scanDir,currentDir,"read_error");continue}let stoppedEarly=!1;try{while(!0){if(state2.entriesSinceYield>=DISCOVERY_YIELD_INTERVAL){if(state2.entriesSinceYield=0,await _internals188.yieldToEventLoop(),_internals188.now()>=state2.deadline){state2.deadlineExceeded=!0,recordIncompletePath(state2.incompletePaths,scanDir,currentDir,"deadline"),stoppedEarly=!0;break}}let entry=directory.readSync();if(!entry)break;state2.entriesSinceYield++;let fullPath=path236.join(currentDir,entry.name),relPath=path236.relative(scanDir,fullPath).replace(/\\/g,"/");if(isExcluded(entry.name,relPath,excludeExact,excludeGlobs)){stats2.skippedDirs++;continue}let lstat11;try{lstat11=fs125.lstatSync(fullPath)}catch{stats2.fileErrors++,recordIncompletePath(state2.incompletePaths,scanDir,fullPath,"read_error");continue}if(lstat11.isSymbolicLink()){stats2.symlinkSkipped++;continue}if(lstat11.isDirectory()){if(state2.directoriesQueued>=MAX_DISCOVERY_DIRECTORIES){state2.unexaminedDirectories++,recordIncompletePath(state2.incompletePaths,scanDir,fullPath,"directory_limit");continue}let realPath;try{realPath=fs125.realpathSync(fullPath)}catch{stats2.fileErrors++,recordIncompletePath(state2.incompletePaths,scanDir,fullPath,"read_error");continue}if(isSymlinkLoop(realPath,visited)||!isPathWithinScope(realPath,scanDir)){stats2.symlinkSkipped++;continue}pending.push(fullPath),state2.directoriesQueued++}else if(lstat11.isFile()){let ext=path236.extname(fullPath).toLowerCase();if(!DEFAULT_EXCLUDE_EXTENSIONS.has(ext))addBoundedCandidate(state2,fullPath);else stats2.skippedFiles++}else stats2.fileErrors++,recordIncompletePath(state2.incompletePaths,scanDir,fullPath,"non_file")}}finally{try{_internals188.closeDirectory(directory)}catch(error93){if(error93.code!=="ERR_DIR_CLOSED")state2.cleanupFailed=!0,recordIncompletePath(state2.incompletePaths,scanDir,currentDir,"cleanup_failed")}}if(stoppedEarly)break}}async function runSecretscan(directory){try{let result=await _internals188.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,rawRequestedFiles){try{let findings=[],filesScanned=0,skippedFiles=0,policySkippedFiles=0,requestedFiles=Math.max(0,rawRequestedFiles??files.length),incompletePaths=[],rawRoot=path236.resolve(directory),canonicalRoot=(()=>{try{return fs125.realpathSync(rawRoot)}catch{return rawRoot}})(),rootStat;try{rootStat=fs125.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=_internals188.now()+SCAN_TIME_BUDGET_MS;await _internals188.yieldToEventLoop();for(let index=0;index<filesToScan.length;index++){if(_internals188.now()>=deadline){for(let remaining of filesToScan.slice(index)){let remainingPath=path236.isAbsolute(remaining)?path236.resolve(remaining):path236.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++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,canonicalRoot,"invalid_entry");continue}let resolvedPath=path236.isAbsolute(file3)?path236.resolve(file3):path236.resolve(rawRoot,file3);if(!isPathWithinScope(resolvedPath,rawRoot)){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"scope_escape");continue}let lstat11;try{lstat11=_internals188.lstatFile(resolvedPath)}catch(error93){if(error93.code==="ENOENT"){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"missing");continue}skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"read_error");continue}if(lstat11.isSymbolicLink()){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"symlink");continue}if(!lstat11.isFile()){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"non_file");continue}let ext=path236.extname(resolvedPath).toLowerCase();if(DEFAULT_EXCLUDE_EXTENSIONS.has(ext)){if(skippedFiles++,DOCS_SAFE_EXCLUDE_EXTENSIONS.has(ext))policySkippedFiles++;continue}let scanPath=resolvedPath;try{scanPath=_internals188.realpathSync(resolvedPath)}catch(error93){if(error93.code==="ENOENT"){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"missing");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 _internals188.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,policy_skipped_files:policySkippedFiles,requested_files:requestedFiles,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_BYTES4=524288,MAX_FILES_SCANNED2=1000,MAX_EXPLICIT_FILES_SCANNED=100,MAX_FINDINGS2=100,MAX_OUTPUT_BYTES4=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,DOCS_SAFE_EXCLUDE_EXTENSIONS,SECRET_PATTERNS2,O_NOFOLLOW,DISCOVERY_YIELD_INTERVAL=100,secretscan,_internals188;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"]),DOCS_SAFE_EXCLUDE_EXTENSIONS=new Set([".md",".markdown",".mdx"]),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 key2=m.match(/[a-zA-Z0-9_-]{16,64}/)?.[0]||"";return`api_key=${key2.slice(0,4)}...${key2.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"?fs125.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,_directory2,_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=path236.resolve(directory),scanDir=(()=>{try{return fs125.realpathSync(scanDirRaw)}catch{return scanDirRaw}})(),dirStat;try{dirStat=fs125.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=_internals188.now()+SCAN_TIME_BUDGET_MS,discovery={files:[],totalCandidates:0,deadline,deadlineExceeded:!1,cleanupFailed:!1,entriesSinceYield:0,incompletePaths:[],directoriesQueued:1,unexaminedDirectories:0};await _internals188.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(_internals188.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 _internals188.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,policy_skipped_files:0,requested_files:0,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)}}});_internals188={secretscan,runSecretscan,runSecretscanOnFiles,SECRET_PATTERNS:SECRET_PATTERNS2,now:Date.now,yieldToEventLoop:yieldToEventLoop2,openFile:fs125.openSync,fstatFile:(fd)=>fs125.fstatSync(fd,{bigint:!0}),readFileChunk:fs125.readSync,closeFile:fs125.closeSync,lstatFile:(path237)=>fs125.lstatSync(path237,{bigint:!0}),realpathSync:(path237)=>fs125.realpathSync(path237),closeDirectory:(directory)=>directory.closeSync()}});import*as fs126 from"node:fs";import*as path237 from"node:path";function detectFileExists(dir,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs126.readdirSync(dir),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs126.accessSync(path237.join(dir,pattern)),!0}catch{return!1}}async function defaultSelectTestFramework(profile,dir){let sorted2=[...profile.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted2){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 buildGradleTestCommand(dir,targets){let args2=["test"];if(targets&&targets.length>0)for(let target of targets)args2.push("--tests",target);if(process.platform==="win32"){if(fs126.existsSync(path237.join(dir,"gradlew.bat"))){if(args2.some((arg)=>arg.endsWith("\\")))return["gradle",...args2];return resolveContainedWindowsBatchCommand(dir,"gradlew.bat",args2)??["gradle",...args2]}}return fs126.existsSync(path237.join(dir,"gradlew"))?["./gradlew",...args2]:["gradle",...args2]}function defaultBuildTestCommand(profile,framework,files,dir=".",opts={}){let scope=opts.scope??"all",coverage=opts.coverage??!1,bail=opts.bail??!1,targets=opts.targets,nativeTarget=opts.nativeTarget;if(nativeTarget){if(nativeTarget.framework!==framework)return null;return buildNativeTargetCommand(nativeTarget)}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=resolveLocalNodeTool("vitest",["run","--reporter=json","--outputFile",".swarm/cache/test-runner-vitest.json"],dir,process.platform,isCommandAvailable);if(!args2)return null;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=resolveLocalNodeTool("jest",["--json"],dir,process.platform,isCommandAvailable);if(!args2)return null;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=resolveLocalNodeTool("mocha",[],dir,process.platform,isCommandAvailable);if(!args2)return null;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(targets&&targets.length>0)args2.push("--",...targets);else 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":{let args2=["go","test"];if(targets&&targets.length>0)args2.push("-run",targets.join("|"));return args2.push("./..."),args2}case"maven":{let args2=["mvn","test"];if(targets&&targets.length>0)args2.push(`-Dtest=${targets.join(",")}`);return args2}case"gradle":return buildGradleTestCommand(dir,targets);case"dotnet-test":{let args2=["dotnet","test"];if(targets&&targets.length>0)args2.push("--filter",targets.join("|"));return args2}case"ctest":{let args2=["ctest","--test-dir",["build","_build","cmake-build-debug","cmake-build-release","out"].find((d)=>fs126.existsSync(path237.join(dir,d,"CMakeCache.txt")))??"build"];if(targets&&targets.length>0)args2.push("-R",targets.join("|"));return args2}case"swift-test":{let args2=["swift","test"];if(targets&&targets.length>0)for(let target of targets)args2.push("--filter",target);return args2}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=[phpVendorBin("pest")];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"phpunit":{let args2=[phpVendorBin("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 escapeRegexLiteral(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function buildNativeTargetCommand(target){if(target.framework==="ctest")return["ctest","--test-dir",target.path,"-R",`^${escapeRegexLiteral(target.name)}$`];let selector=target.name.split("/").map((part)=>`^${escapeRegexLiteral(part)}$`).join("/"),packagePath=target.path==="."?".":target.path.startsWith("./")?target.path:`./${target.path.replace(/\\/g,"/")}`;return["go","test","-v","-run",selector,packagePath]}function phpVendorBin(name){return path237.join("vendor","bin",process.platform==="win32"?`${name}.bat`:name)}function defaultParseTestOutput(framework,stdout,stderr,exitCode){let output=stdout&&stderr?`${stdout}
4060
+ `);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((resolve94)=>setImmediate(resolve94))}function serializeSecretscanResult(result){let findings=result.findings,candidate2=result,json3=JSON.stringify(candidate2,null,2);while(Buffer.byteLength(json3,"utf8")>MAX_OUTPUT_BYTES4&&findings.length>0)findings=findings.slice(0,Math.floor(findings.length/2)),candidate2={...result,findings,message:"Output truncated due to size limits."},json3=JSON.stringify(candidate2,null,2);if(Buffer.byteLength(json3,"utf8")>MAX_OUTPUT_BYTES4)candidate2={...result,findings:[],message:"Output truncated due to size limits."},json3=JSON.stringify(candidate2,null,2);return json3}function isSymlinkLoop(realPath,visited){if(visited.has(realPath))return!0;return visited.add(realPath),!1}function isPathWithinScope(realPath,scanDir){return isCanonicalPathWithinRoot(realPath,scanDir)}function toSafeRelativePath(rootDir2,targetPath){let relative54=path236.relative(rootDir2,targetPath).replace(/\\/g,"/");if(!relative54||relative54===".")return".";if(relative54.startsWith("..")||path236.isAbsolute(relative54))return path236.basename(targetPath).replace(/\\/g,"/")||".";return relative54}function recordIncompletePath(target,rootDir2,targetPath,reason){if(target.length>=MAX_INCOMPLETE_PATHS){target[MAX_INCOMPLETE_PATHS-1]={path:".",reason:"truncated"};return}target.push({path:toSafeRelativePath(rootDir2,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(state2,filePath){state2.totalCandidates++;let heap=state2.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,state2){let pending=[dir];while(pending.length>0){if(state2.deadlineExceeded||state2.cleanupFailed)return;let currentDir=pending.pop();if(!currentDir)continue;let directory;try{directory=fs125.opendirSync(currentDir)}catch{stats2.fileErrors++,recordIncompletePath(state2.incompletePaths,scanDir,currentDir,"read_error");continue}let stoppedEarly=!1;try{while(!0){if(state2.entriesSinceYield>=DISCOVERY_YIELD_INTERVAL){if(state2.entriesSinceYield=0,await _internals188.yieldToEventLoop(),_internals188.now()>=state2.deadline){state2.deadlineExceeded=!0,recordIncompletePath(state2.incompletePaths,scanDir,currentDir,"deadline"),stoppedEarly=!0;break}}let entry=directory.readSync();if(!entry)break;state2.entriesSinceYield++;let fullPath=path236.join(currentDir,entry.name),relPath=path236.relative(scanDir,fullPath).replace(/\\/g,"/");if(isExcluded(entry.name,relPath,excludeExact,excludeGlobs)){stats2.skippedDirs++;continue}let lstat11;try{lstat11=fs125.lstatSync(fullPath)}catch{stats2.fileErrors++,recordIncompletePath(state2.incompletePaths,scanDir,fullPath,"read_error");continue}if(lstat11.isSymbolicLink()){stats2.symlinkSkipped++;continue}if(lstat11.isDirectory()){if(state2.directoriesQueued>=MAX_DISCOVERY_DIRECTORIES){state2.unexaminedDirectories++,recordIncompletePath(state2.incompletePaths,scanDir,fullPath,"directory_limit");continue}let realPath;try{realPath=fs125.realpathSync(fullPath)}catch{stats2.fileErrors++,recordIncompletePath(state2.incompletePaths,scanDir,fullPath,"read_error");continue}if(isSymlinkLoop(realPath,visited)||!isPathWithinScope(realPath,scanDir)){stats2.symlinkSkipped++;continue}pending.push(fullPath),state2.directoriesQueued++}else if(lstat11.isFile()){let ext=path236.extname(fullPath).toLowerCase();if(!DEFAULT_EXCLUDE_EXTENSIONS.has(ext))addBoundedCandidate(state2,fullPath);else stats2.skippedFiles++}else stats2.fileErrors++,recordIncompletePath(state2.incompletePaths,scanDir,fullPath,"non_file")}}finally{try{_internals188.closeDirectory(directory)}catch(error93){if(error93.code!=="ERR_DIR_CLOSED")state2.cleanupFailed=!0,recordIncompletePath(state2.incompletePaths,scanDir,currentDir,"cleanup_failed")}}if(stoppedEarly)break}}async function runSecretscan(directory){try{let result=await _internals188.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,rawRequestedFiles){try{let findings=[],filesScanned=0,skippedFiles=0,policySkippedFiles=0,requestedFiles=Math.max(0,rawRequestedFiles??files.length),incompletePaths=[],rawRoot=path236.resolve(directory),canonicalRoot=(()=>{try{return fs125.realpathSync(rawRoot)}catch{return rawRoot}})(),rootStat;try{rootStat=fs125.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=_internals188.now()+SCAN_TIME_BUDGET_MS;await _internals188.yieldToEventLoop();for(let index=0;index<filesToScan.length;index++){if(_internals188.now()>=deadline){for(let remaining of filesToScan.slice(index)){let remainingPath=path236.isAbsolute(remaining)?path236.resolve(remaining):path236.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++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,canonicalRoot,"invalid_entry");continue}let resolvedPath=path236.isAbsolute(file3)?path236.resolve(file3):path236.resolve(rawRoot,file3);if(!isPathWithinScope(resolvedPath,rawRoot)){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"scope_escape");continue}let lstat11;try{lstat11=_internals188.lstatFile(resolvedPath)}catch(error93){if(error93.code==="ENOENT"){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"missing");continue}skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"read_error");continue}if(lstat11.isSymbolicLink()){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"symlink");continue}if(!lstat11.isFile()){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"non_file");continue}let ext=path236.extname(resolvedPath).toLowerCase();if(DEFAULT_EXCLUDE_EXTENSIONS.has(ext)){if(skippedFiles++,DOCS_SAFE_EXCLUDE_EXTENSIONS.has(ext))policySkippedFiles++;continue}let scanPath=resolvedPath;try{scanPath=_internals188.realpathSync(resolvedPath)}catch(error93){if(error93.code==="ENOENT"){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"missing");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 _internals188.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,policy_skipped_files:policySkippedFiles,requested_files:requestedFiles,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_BYTES4=524288,MAX_FILES_SCANNED2=1000,MAX_EXPLICIT_FILES_SCANNED=100,MAX_FINDINGS2=100,MAX_OUTPUT_BYTES4=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,DOCS_SAFE_EXCLUDE_EXTENSIONS,SECRET_PATTERNS2,O_NOFOLLOW,DISCOVERY_YIELD_INTERVAL=100,secretscan,_internals188;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"]),DOCS_SAFE_EXCLUDE_EXTENSIONS=new Set([".md",".markdown",".mdx"]),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 key2=m.match(/[a-zA-Z0-9_-]{16,64}/)?.[0]||"";return`api_key=${key2.slice(0,4)}...${key2.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"?fs125.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,_directory2,_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=path236.resolve(directory),scanDir=(()=>{try{return fs125.realpathSync(scanDirRaw)}catch{return scanDirRaw}})(),dirStat;try{dirStat=fs125.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=_internals188.now()+SCAN_TIME_BUDGET_MS,discovery={files:[],totalCandidates:0,deadline,deadlineExceeded:!1,cleanupFailed:!1,entriesSinceYield:0,incompletePaths:[],directoriesQueued:1,unexaminedDirectories:0};await _internals188.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(_internals188.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 _internals188.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,policy_skipped_files:0,requested_files:0,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)}}});_internals188={secretscan,runSecretscan,runSecretscanOnFiles,SECRET_PATTERNS:SECRET_PATTERNS2,now:Date.now,yieldToEventLoop:yieldToEventLoop2,openFile:fs125.openSync,fstatFile:(fd)=>fs125.fstatSync(fd,{bigint:!0}),readFileChunk:fs125.readSync,closeFile:fs125.closeSync,lstatFile:(path237)=>fs125.lstatSync(path237,{bigint:!0}),realpathSync:(path237)=>fs125.realpathSync(path237),closeDirectory:(directory)=>directory.closeSync()}});import*as fs126 from"node:fs";import*as path237 from"node:path";function detectFileExists(dir,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs126.readdirSync(dir),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs126.accessSync(path237.join(dir,pattern)),!0}catch{return!1}}async function defaultSelectTestFramework(profile,dir){let sorted2=[...profile.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted2){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 buildGradleTestCommand(dir,targets){let args2=["test"];if(targets&&targets.length>0)for(let target of targets)args2.push("--tests",target);if(process.platform==="win32"){if(fs126.existsSync(path237.join(dir,"gradlew.bat"))){if(args2.some((arg)=>arg.endsWith("\\")))return["gradle",...args2];return resolveContainedWindowsBatchCommand(dir,"gradlew.bat",args2)??["gradle",...args2]}}return fs126.existsSync(path237.join(dir,"gradlew"))?["./gradlew",...args2]:["gradle",...args2]}function buildPhpVendorCommand(dir,name,args2=[]){let proxy=path237.join("vendor","bin",name);if(process.platform!=="win32")return[proxy,...args2];let interpreterFallback=()=>fs126.existsSync(path237.join(dir,proxy))?["php",proxy,...args2]:[proxy,...args2];if(args2.some((arg)=>arg.endsWith("\\")))return interpreterFallback();return resolveContainedWindowsBatchCommand(dir,path237.join("vendor","bin",`${name}.bat`),args2)??interpreterFallback()}function defaultBuildTestCommand(profile,framework,files,dir=".",opts={}){let scope=opts.scope??"all",coverage=opts.coverage??!1,bail=opts.bail??!1,targets=opts.targets,nativeTarget=opts.nativeTarget;if(nativeTarget){if(nativeTarget.framework!==framework)return null;return buildNativeTargetCommand(nativeTarget)}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=resolveLocalNodeTool("vitest",["run","--reporter=json","--outputFile",".swarm/cache/test-runner-vitest.json"],dir,process.platform,isCommandAvailable);if(!args2)return null;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=resolveLocalNodeTool("jest",["--json"],dir,process.platform,isCommandAvailable);if(!args2)return null;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=resolveLocalNodeTool("mocha",[],dir,process.platform,isCommandAvailable);if(!args2)return null;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(targets&&targets.length>0)args2.push("--",...targets);else 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":{let args2=["go","test"];if(targets&&targets.length>0)args2.push("-run",targets.join("|"));return args2.push("./..."),args2}case"maven":{let args2=["mvn","test"];if(targets&&targets.length>0)args2.push(`-Dtest=${targets.join(",")}`);return args2}case"gradle":return buildGradleTestCommand(dir,targets);case"dotnet-test":{let args2=["dotnet","test"];if(targets&&targets.length>0)args2.push("--filter",targets.join("|"));return args2}case"ctest":{let args2=["ctest","--test-dir",["build","_build","cmake-build-debug","cmake-build-release","out"].find((d)=>fs126.existsSync(path237.join(dir,d,"CMakeCache.txt")))??"build"];if(targets&&targets.length>0)args2.push("-R",targets.join("|"));return args2}case"swift-test":{let args2=["swift","test"];if(targets&&targets.length>0)for(let target of targets)args2.push("--filter",target);return args2}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":return buildPhpVendorCommand(dir,"pest",scope!=="all"&&files.length>0?files:[]);case"phpunit":return buildPhpVendorCommand(dir,"phpunit",scope!=="all"&&files.length>0?files:[]);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 escapeRegexLiteral(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function buildNativeTargetCommand(target){if(target.framework==="ctest")return["ctest","--test-dir",target.path,"-R",`^${escapeRegexLiteral(target.name)}$`];let selector=target.name.split("/").map((part)=>`^${escapeRegexLiteral(part)}$`).join("/"),packagePath=target.path==="."?".":target.path.startsWith("./")?target.path:`./${target.path.replace(/\\/g,"/")}`;return["go","test","-v","-run",selector,packagePath]}function defaultParseTestOutput(framework,stdout,stderr,exitCode){let output=stdout&&stderr?`${stdout}
4061
4061
  ${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 disabledCount=[...output.matchAll(/\*{3}Not Run\s+\(Disabled\)/gi)].length;skipped=disabledCount;let ctestMatch=output.match(/(\d+) tests? failed out of (\d+)/);if(ctestMatch){failed=parseInt(ctestMatch[1],10);let executedTotal=parseInt(ctestMatch[2],10);total=executedTotal+disabledCount,passed=executedTotal-failed}else{let allPassMatch=output.match(/100% tests passed.*?(\d+) tests?/);if(allPassMatch){let executedTotal=parseInt(allPassMatch[1],10);total=executedTotal+disabledCount,passed=executedTotal}else if(disabledCount>0)total=disabledCount}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 sorted2=[...profile.build.commands].sort((a,b)=>b.priority-a.priority);for(let cmd of sorted2){if(cmd.detectFile&&!detectFileExists(dir,cmd.detectFile))continue;let resolved=resolveLocalCommand(cmd.cmd,dir,isCommandAvailable);if(!resolved)continue;return{name:cmd.name,cmd:resolved.argv,cwd:dir,detectedVia:cmd.detectFile??`${profile.id} default`}}return null}async function defaultTestFilesFor(profile,sourceFile,dir){let ext=path237.extname(sourceFile);if(!profile.extensions.includes(ext))return[];let base=path237.basename(sourceFile,ext),rel=path237.relative(dir,sourceFile),stripSrc=path237.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(path237.join(dir,tDir,stripSrc,`${base}${suffix}${ext}`));let existing=[];for(let c of candidates)try{fs126.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_command_resolution();init_discovery();init_windows_batch();init_command_resolution()});import*as fs127 from"node:fs";import*as path238 from"node:path";function isMainClass(source){let masked=maskCommentsAndLiterals(source);return/\b(?:public\s+static|static\s+public)\s+void\s+main\s*\(/.test(masked)}function scanForMainClasses(dir){let results=[],stack=[{dir,depth:0}],entriesVisited=0,totalBytes=0;while(stack.length>0){let current=stack.pop();if(!current||current.depth>MAX_ENTRY_POINT_DEPTH)continue;let entries2;try{entries2=fs127.readdirSync(current.dir,{withFileTypes:!0})}catch{continue}let deferredDirs=[],preferredDirs=[];for(let entry of entries2){if(entriesVisited++,entriesVisited>MAX_ENTRY_POINT_ENTRIES)return results;let full=path238.join(current.dir,entry.name);if(entry.isDirectory()){if(IGNORED_ENTRY_POINT_DIRS.has(entry.name))continue;if(DEFERRED_ENTRY_POINT_DIRS.has(entry.name))deferredDirs.push(full);else preferredDirs.push(full)}else if(entry.isFile()&&entry.name.endsWith(".java")){let size;try{size=fs127.statSync(full).size}catch{continue}if(size>MAX_ENTRY_POINT_FILE_BYTES)continue;if(totalBytes+size>MAX_ENTRY_POINT_TOTAL_BYTES)return results;try{let source=fs127.readFileSync(full,"utf-8");if(totalBytes+=size,isMainClass(source))results.push(path238.relative(dir,full))}catch{}}}for(let d of deferredDirs)stack.push({dir:d,depth:current.depth+1});for(let d of preferredDirs)stack.push({dir:d,depth:current.depth+1})}return results}function detectFramework(content){if(content.length===0)return null;if(/\bspring-boot-starter-web\b|\bspring-boot\b|\bspring-web\b|\bspring-context\b/.test(content))return{name:"spring",detectedVia:"spring-boot/spring dependency"};if(/\bjakarta\.servlet\b|\bjavax\.servlet\b/.test(content))return{name:"servlet",detectedVia:"jakarta/javax servlet dependency"};return null}function extractImports(_sourceFile,source){let seen=new Set;for(let imp of parseJavaImports(source))seen.add(imp.specifier);return[...seen]}function wrapperExists(dir,name){return fs127.existsSync(path238.join(dir,name))}function resolveMvnwCommand(dir){let isWindows=process.platform==="win32",hasMvnwCmd=wrapperExists(dir,"mvnw.cmd");return isWindows&&hasMvnwCmd?"mvnw.cmd":"./mvnw"}function resolveGradlewCommand(dir){let isWindows=process.platform==="win32",hasGradlewBat=wrapperExists(dir,"gradlew.bat");return isWindows&&hasGradlewBat?"gradlew.bat":"./gradlew"}async function selectTestFramework(dir){if(wrapperExists(dir,"gradlew"))return{name:"gradle",cmd:[resolveGradlewCommand(dir),"test","-q"],cwd:dir,detectedVia:"./gradlew",filesIgnored:!1};if(wrapperExists(dir,"mvnw"))return{name:"maven",cmd:[resolveMvnwCommand(dir),"test","-q"],cwd:dir,detectedVia:"./mvnw",filesIgnored:!1};let profile=LANGUAGE_REGISTRY.get(PROFILE_ID);if(!profile)return null;return defaultSelectTestFramework(profile,dir)}async function selectEntryPoints(dir){return await new Promise((resolve94)=>setImmediate(resolve94)),scanForMainClasses(dir)}async function selectFramework(dir){let content="";for(let file3 of["pom.xml","build.gradle","build.gradle.kts"])try{content+=`
4062
4062
  ${fs127.readFileSync(path238.join(dir,file3),"utf-8")}`}catch{}return detectFramework(content)}function isExecutableFile2(filePath){try{let stats2=fs127.statSync(filePath,{throwIfNoEntry:!1});return stats2?.isFile()===!0&&(stats2.mode&73)!==0}catch{return!1}}function resolveMavenWrapperCommand(dir,args2){if(process.platform==="win32")return resolveContainedWindowsBatchCommand(dir,"mvnw.cmd",args2);return _internals189.isExecutableFile(path238.join(dir,"mvnw"))?["./mvnw",...args2]:null}function buildMavenTestCommand(dir,targets){let args2=["test"];if(targets&&targets.length>0)args2.push(`-Dtest=${targets.join(",")}`);if(process.platform==="win32"&&args2.some((a)=>a.endsWith("\\")))return["mvn",...args2];return resolveMavenWrapperCommand(dir,args2)??["mvn",...args2]}function buildTestCommand(framework,_files,dir,opts){if(framework!=="maven")return null;if(opts?.nativeTarget)return null;return buildMavenTestCommand(dir,opts?.targets)}function buildJavaBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID);if(!profile)throw Error("buildJavaBackend: java profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...defaultBackendFor(profile),extractImports,selectTestFramework,selectEntryPoints,selectFramework,buildTestCommand}}var PROFILE_ID="java",MAX_ENTRY_POINT_DEPTH=8,MAX_ENTRY_POINT_ENTRIES=5000,MAX_ENTRY_POINT_FILE_BYTES=262144,MAX_ENTRY_POINT_TOTAL_BYTES=524288,IGNORED_ENTRY_POINT_DIRS,DEFERRED_ENTRY_POINT_DIRS,_internals189;var init_java2=__esm(()=>{init_windows_batch();init_default_backend();init_java_extraction();init_profiles();IGNORED_ENTRY_POINT_DIRS=new Set([".git",".gradle","target","build","node_modules",".idea","out","bin",".venv","venv","dist"]),DEFERRED_ENTRY_POINT_DIRS=new Set(["test","tests","androidTest","integrationTest","testFixtures"]);_internals189={extractImports,isMainClass,detectFramework,wrapperExists,isExecutableFile:isExecutableFile2,resolveMvnwCommand,resolveGradlewCommand,MAX_ENTRY_POINT_ENTRIES}});import*as fs128 from"node:fs";import*as path239 from"node:path";function stripGoComments(source){let state2="normal",out="",escaped=!1;for(let index=0;index<source.length;index++){let current=source[index],next=source[index+1];if(state2==="line"){if(current===`
4063
4063
  `||current==="\r")state2="normal",out+=current;else out+=" ";continue}if(state2==="block"){if(current==="*"&&next==="/")out+=" ",index++,state2="normal";else out+=current===`
@@ -4068,7 +4068,7 @@ ${fs127.readFileSync(path238.join(dir,file3),"utf-8")}`}catch{}return detectFram
4068
4068
  `||current==="\r"?current:" ";continue}if(state2==="string"||state2==="template"){if(out+=current,escaped)escaped=!1;else if(current==="\\")escaped=!0;else if(state2==="string"&&current===stringQuote||state2==="template"&&current==="`")state2="normal",stringQuote=void 0;continue}if(current==="/"&&next==="/")out+=" ",index++,state2="line";else if(current==="/"&&next==="*")out+=" ",index++,state2="block";else if(out+=current,current==='"'||current==="'")state2="string",stringQuote=current;else if(current==="`")state2="template"}return out}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 digestContent(content){return createHash91("sha256").update(content).digest("hex")}function scanTestFilesSync(cwd){let result={files:[],totalBytes:0,exceeded:!1},visitedRealPaths=new Set,visitedEntries=0;function walk(dir,depth){if(result.exceeded)return;if(depth>MAX_IMPACT_SCAN_DEPTH){result.exceeded=!0;return}let directory;try{directory=fs130.opendirSync(dir)}catch{return}try{let realPath;try{realPath=normalizePath2(fs130.realpathSync.native(dir))}catch{return}let directoryKey=process.platform==="win32"?realPath.toLowerCase():realPath;if(visitedRealPaths.has(directoryKey))return;visitedRealPaths.add(directoryKey);while(!0){let entry=directory.readSync();if(entry===null)break;if(++visitedEntries>MAX_IMPACT_WALK_ENTRIES){result.exceeded=!0;return}if(entry.isDirectory()){if(!SKIP_TEST_SCAN_DIRS.has(entry.name))walk(path241.join(dir,entry.name),depth+1);if(result.exceeded)return;continue}if(!entry.isFile())continue;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(`${path241.sep}tests${path241.sep}`)&&name.endsWith(".py"),isGoTest=/.+_test\.go$/.test(name);if(!isTsTest&&!isPyTest&&!isGoTest)continue;let size;try{size=fs130.statSync(path241.join(dir,name)).size}catch{continue}if(size>MAX_IMPACT_TEST_FILE_BYTES||result.files.length>=MAX_IMPACT_TEST_FILES||result.totalBytes+size>MAX_IMPACT_SCAN_BYTES){result.exceeded=!0;return}result.totalBytes+=size,result.files.push(normalizePath2(path241.join(dir,name)))}}catch{}finally{try{directory.closeSync()}catch{}}}return walk(cwd,0),result}function getBoundedTestFiles(cwd){let scan=scanTestFilesSync(cwd);if(scan.exceeded)throw new ImpactScanLimitError;return scan.files}function readBoundedTestFile(testFile,state2){let fd;try{fd=fs130.openSync(testFile,"r");let stat23=fs130.fstatSync(fd),remainingBudget=MAX_IMPACT_SCAN_BYTES-state2.totalBytes,allowedBytes=Math.min(MAX_IMPACT_TEST_FILE_BYTES,remainingBudget);if(stat23.size>allowedBytes)throw new ImpactScanLimitError;let chunks=[],totalBytes=0;while(!0){let remaining=allowedBytes+1-totalBytes;if(remaining<=0)throw new ImpactScanLimitError;let chunk=Buffer.allocUnsafe(Math.min(65536,remaining)),bytesRead=fs130.readSync(fd,chunk,0,chunk.length,totalBytes);if(bytesRead===0)break;if(totalBytes+=bytesRead,totalBytes>allowedBytes)throw new ImpactScanLimitError;chunks.push(chunk.subarray(0,bytesRead))}return state2.totalBytes+=totalBytes,Buffer.concat(chunks,totalBytes).toString("utf8")}finally{if(fd!==void 0)try{fs130.closeSync(fd)}catch{}}}function readBoundedUtf8File(filePath,maxBytes){let fd;try{fd=fs130.openSync(filePath,"r");let initial=fs130.fstatSync(fd);if(!initial.isFile()||initial.size>maxBytes)return null;let chunks=[],chunk=Buffer.allocUnsafe(65536),totalBytes=0;while(totalBytes<=maxBytes){let bytesToRead=Math.min(chunk.length,maxBytes+1-totalBytes),bytesRead=fs130.readSync(fd,chunk,0,bytesToRead,totalBytes);if(bytesRead===0)break;if(totalBytes+=bytesRead,totalBytes>maxBytes)return null;chunks.push(Buffer.from(chunk.subarray(0,bytesRead)))}let final=fs130.fstatSync(fd);if(!final.isFile()||final.size>maxBytes||final.size!==totalBytes||final.dev!==initial.dev||final.ino!==initial.ino)return null;return Buffer.concat(chunks,totalBytes).toString("utf8")}catch{return null}finally{if(fd!==void 0)try{fs130.closeSync(fd)}catch{}}}function buildTestFileManifest(cwd,testFiles){let manifest=[],files=testFiles??getBoundedTestFiles(cwd);if(files.length>MAX_IMPACT_TEST_FILES)throw new ImpactScanLimitError;let state2={totalBytes:0};for(let testFile of files.sort())try{let stat23=fs130.statSync(testFile),content=readBoundedTestFile(testFile,state2);manifest.push({path:normalizePath2(testFile),size:stat23.size,mtimeMs:stat23.mtimeMs,digest:digestContent(content)})}catch(error93){if(error93 instanceof ImpactScanLimitError)throw error93}return manifest}function testManifestChanged(cached3,cwd){if(cached3.length>MAX_IMPACT_TEST_FILES)throw new ImpactScanLimitError;let scan=scanTestFilesSync(cwd);if(scan.exceeded)throw new ImpactScanLimitError;let currentFiles=scan.files.map(normalizePath2).sort(),cachedFiles=cached3.map((entry)=>normalizePath2(entry.path)).sort();if(currentFiles.length!==cachedFiles.length||currentFiles.some((file3,index)=>file3!==cachedFiles[index]))return!0;let cachedByPath=new Map(cached3.map((entry)=>[normalizePath2(entry.path),entry])),state2={totalBytes:0};for(let file3 of currentFiles){let previous=cachedByPath.get(file3);if(!previous)return!0;try{let content=readBoundedTestFile(file3,state2),stat23=fs130.statSync(file3);if(stat23.size!==previous.size||stat23.mtimeMs!==previous.mtimeMs||digestContent(content)!==previous.digest)return!0}catch(error93){if(error93 instanceof ImpactScanLimitError)throw error93;return!0}}return!1}function isCacheStale(impactMap,generatedAtMs,testFiles,cwd){if(testFiles&&cwd&&testManifestChanged(testFiles,cwd))return!0;let sourceCount=0;for(let sourcePath in impactMap){if(!Object.hasOwn(impactMap,sourcePath))continue;if(++sourceCount>MAX_IMPACT_MAP_SOURCES)throw new ImpactScanLimitError;try{if(fs130.statSync(sourcePath).mtimeMs>generatedAtMs)return!0}catch{return!0}}return!1}function resolveRelativeImport(fromDir,importPath){if(!importPath.startsWith("."))return null;let resolved=path241.resolve(fromDir,importPath);if(path241.extname(resolved)){if(fs130.existsSync(resolved)&&fs130.statSync(resolved).isFile())return normalizePath2(resolved)}else for(let ext of EXTENSIONS_TO_TRY){let withExt=resolved+ext;if(fs130.existsSync(withExt)&&fs130.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=path241.dirname(baseDir);let rest=module.slice(leadingDots);if(rest.length===0){let initPath=path241.join(baseDir,"__init__.py");if(fs130.existsSync(initPath)&&fs130.statSync(initPath).isFile())return normalizePath2(initPath);return null}let subpath=rest.replace(/\./g,path241.sep),candidates=[`${path241.join(baseDir,subpath)}.py`,path241.join(baseDir,subpath,"__init__.py")];for(let c of candidates)if(fs130.existsSync(c)&&fs130.statSync(c).isFile())return normalizePath2(c);return null}function findGoModule(fromDir){let cur=path241.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=path241.join(cur,"go.mod"),content=readBoundedUtf8File(goMod,MAX_IMPACT_GO_MOD_BYTES);if(content===null)throw Error("go.mod unavailable or oversized");let moduleMatch=content.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{fs130.accessSync(path241.join(cur,".git"));break}catch{}let parent=path241.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=path241.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=path241.join(mod.moduleRoot,subpath)}}if(dir===null)return[];if(!fs130.existsSync(dir)||!fs130.statSync(dir).isDirectory())return[];let directory;try{directory=fs130.opendirSync(dir);let files=[],entries2=0;while(!0){let entry=directory.readSync();if(entry===null)break;if(++entries2>MAX_IMPACT_WALK_ENTRIES)return[];if(entry.isFile()&&entry.name.endsWith(".go")&&!entry.name.endsWith("_test.go"))files.push(normalizePath2(path241.join(dir,entry.name)))}return files}catch{return[]}finally{directory?.closeSync()}}function _clearGoModuleCache(){goModuleCache.clear()}function findTestFilesSync(cwd){return scanTestFilesSync(cwd).files}function extractImports4(content){function execRegex(regex,content2){let results=[];regex.lastIndex=0;let match;while((match=regex.exec(content2))!==null)results.push(match[1]);return results}let sourceWithoutComments=stripTsComments(content);return[...execRegex(IMPORT_REGEX_ES_SIDE_EFFECT,sourceWithoutComments),...execRegex(IMPORT_REGEX_ES_FROM,sourceWithoutComments),...execRegex(IMPORT_REGEX_REQUIRE,sourceWithoutComments),...execRegex(IMPORT_REGEX_REEXPORT,sourceWithoutComments)]}function addImpactEdgesForTestFile(testFile,content,impactMap){let ext=path241.extname(testFile).toLowerCase(),testDir=path241.dirname(testFile);function addEdge2(source){if(!impactMap[source])impactMap[source]=[];if(!impactMap[source].includes(testFile))impactMap[source].push(testFile)}if(TS_EXTENSIONS.has(ext)){let imports=extractImports4(content);for(let importPath of imports){let resolved=resolveRelativeImport(testDir,importPath);if(resolved!==null)addEdge2(resolved)}return}if(PYTHON_EXTENSIONS.has(ext)){let modules=_internals191.extractImports(testFile,content);for(let mod of modules){let resolved=resolvePythonImport(testDir,mod);if(resolved!==null)addEdge2(resolved)}return}if(GO_EXTENSIONS.has(ext)){let imports=_internals190.extractImports(testFile,content);for(let importPath of imports){let sourceFiles=resolveGoImport(testDir,importPath);for(let source of sourceFiles)addEdge2(source)}return}}async function buildImpactMapInternal(cwd,testFilesOverride){_clearGoModuleCache();let testFiles=testFilesOverride??getBoundedTestFiles(cwd);if(testFiles.length>MAX_IMPACT_TEST_FILES)throw new ImpactScanLimitError;let impactMap={},state2={totalBytes:0};for(let testFile of testFiles){let content;try{content=readBoundedTestFile(testFile,state2)}catch(error93){if(error93 instanceof ImpactScanLimitError)throw error93;continue}if(content.substring(0,8192).includes("\x00"))continue;addImpactEdgesForTestFile(testFile,content,impactMap)}return impactMap}function validateImpactMap(value){if(value===null||typeof value!=="object"||Array.isArray(value))return"invalid";let sourceCount=0,referenceCount=0;for(let sourcePath in value){if(!Object.hasOwn(value,sourcePath))continue;if(++sourceCount>MAX_IMPACT_MAP_SOURCES)return"overflow";let tests=value[sourcePath];if(!Array.isArray(tests))return"invalid";for(let test of tests){if(++referenceCount>MAX_IMPACT_MAP_REFERENCES)return"overflow";if(typeof test!=="string")return"invalid"}}return"valid"}function unverifiedStatus(status2){if(status2==="fresh"||status2==="stale")return"fresh_unverified";if(status2==="missing")return"missing_unverified";if(status2==="corrupt")return"corrupt_unverified";if(status2==="legacy")return"legacy_unverified";if(status2==="overflow")return"overflow_unverified";return status2}function readBoundedCacheText(filePath){let fd;try{fd=fs130.openSync(filePath,"r");let initial=fs130.fstatSync(fd);if(initial.size>MAX_IMPACT_CACHE_BYTES)return{status:"overflow"};let chunks=[],chunk=Buffer.allocUnsafe(65536),totalBytes=0;while(totalBytes<=MAX_IMPACT_CACHE_BYTES){let bytesToRead=Math.min(chunk.length,MAX_IMPACT_CACHE_BYTES+1-totalBytes),bytesRead=fs130.readSync(fd,chunk,0,bytesToRead,totalBytes);if(bytesRead===0)break;if(chunks.push(Buffer.from(chunk.subarray(0,bytesRead))),totalBytes+=bytesRead,totalBytes>MAX_IMPACT_CACHE_BYTES)return{status:"overflow"}}let final=fs130.fstatSync(fd);if(final.size>MAX_IMPACT_CACHE_BYTES||totalBytes>MAX_IMPACT_CACHE_BYTES)return{status:"overflow"};if(final.size!==totalBytes||final.dev!==initial.dev||final.ino!==initial.ino)return{status:"unstable"};return{status:"ok",text:Buffer.concat(chunks,totalBytes).toString("utf8")}}catch(error93){return{status:error93.code==="ENOENT"?"missing":"unavailable"}}finally{if(fd!==void 0)try{fs130.closeSync(fd)}catch{}}}function readImpactCache(cwd,verify=!0){let cachePath=path241.join(cwd,".swarm","cache","impact-map.json"),boundedRead=readBoundedCacheText(cachePath);if(boundedRead.status==="missing")return{envelope:null,status:verify?"missing":"missing_unverified"};if(boundedRead.status==="overflow")return{envelope:null,status:verify?"overflow":"overflow_unverified"};if(boundedRead.status!=="ok")return{envelope:null,status:verify?"corrupt":"corrupt_unverified"};try{let data=JSON.parse(boundedRead.text),mapStatus=validateImpactMap(data.map);if(data.version!==IMPACT_CACHE_VERSION||typeof data.generatedAt!=="string"||mapStatus!=="valid"||typeof data.fileCount!=="number"||!Array.isArray(data.testFiles)||data.testFiles.length>MAX_IMPACT_TEST_FILES||!data.testFiles.every((entry)=>typeof entry==="object"&&entry!==null&&typeof entry.path==="string"&&typeof entry.size==="number"&&typeof entry.mtimeMs==="number"&&typeof entry.digest==="string")){if(mapStatus==="overflow"||Array.isArray(data.testFiles)&&data.testFiles.length>MAX_IMPACT_TEST_FILES)return{envelope:null,status:verify?"overflow":"overflow_unverified"};let status2=data.map!==void 0&&(data.version===void 0||typeof data.version==="number"&&data.version<IMPACT_CACHE_VERSION)?"legacy":"corrupt";return{envelope:null,status:verify?status2:unverifiedStatus(status2)}}let envelope=data,generatedAtMs=new Date(envelope.generatedAt).getTime();if(!Number.isFinite(generatedAtMs))return{envelope:null,status:verify?"corrupt":"corrupt_unverified"};if(!verify)return{envelope,status:"fresh_unverified"};try{if(_internals192.isCacheStale(envelope.map,generatedAtMs,envelope.testFiles,cwd))return{envelope,status:"stale"}}catch(error93){if(error93 instanceof ImpactScanLimitError)return{envelope:null,status:"overflow"};throw error93}return{envelope,status:"fresh"}}catch(error93){if(error93 instanceof ImpactScanLimitError)return{envelope:null,status:verify?"overflow":"overflow_unverified"};return{envelope:null,status:verify?"corrupt":"corrupt_unverified"}}}function getImpactCacheStatus(cwd,options){let cachePath=path241.join(cwd,".swarm","cache","impact-map.json");return{status:readImpactCache(cwd,options?.verify??!0).status,cachePath}}async function buildImpactMap(cwd){let testFiles=getBoundedTestFiles(cwd),impactMap=await _internals192.buildImpactMapInternal(cwd,testFiles);return await _internals192.saveImpactMap(cwd,impactMap,testFiles),impactMap}function rebuiltCacheStatus(status2){if(status2==="missing"||status2==="corrupt"||status2==="legacy"||status2==="stale")return`rebuilt_${status2}`;return status2}async function loadImpactMapWithStatus(cwd,options){let inspection=readImpactCache(cwd,!options?.skipRebuild);if(inspection.envelope){if(inspection.status==="fresh"||options?.skipRebuild)return{map:inspection.envelope.map,status:inspection.status}}if(options?.skipRebuild)return{map:{},status:inspection.status};try{return{map:await _internals192.buildImpactMap(cwd),status:rebuiltCacheStatus(inspection.status)}}catch(error93){if(error93 instanceof ImpactScanLimitError)return{map:{},status:"overflow"};throw error93}}async function loadImpactMap(cwd,options){return(await loadImpactMapWithStatus(cwd,options)).map}async function saveImpactMap(cwd,impactMap,testFiles){if(!path241.isAbsolute(cwd))throw Error(`saveImpactMap requires an absolute project root path, got: "${cwd}"`);let mapStatus=validateImpactMap(impactMap);if(mapStatus!=="valid")throw Error(mapStatus==="overflow"?"saveImpactMap impact map exceeds bounded source/reference limits":"saveImpactMap received an invalid impact map");_internals192.validateProjectRoot(cwd);let cacheDir2=path241.join(cwd,".swarm","cache"),cachePath=path241.join(cacheDir2,"impact-map.json");if(!fs130.existsSync(cacheDir2))fs130.mkdirSync(cacheDir2,{recursive:!0});let data={version:IMPACT_CACHE_VERSION,generatedAt:new Date().toISOString(),fileCount:Object.keys(impactMap).length,map:impactMap,testFiles:buildTestFileManifest(cwd,testFiles)};await atomicWriteSwarmFile(cachePath,JSON.stringify(data,null,2))}async function analyzeImpact(changedFiles,cwd,budget,impactMapOverride){if(!Array.isArray(changedFiles))return{impactedTests:[],unrelatedTests:[],untestedFiles:[],impactMap:{}};let validFiles=changedFiles.filter((f)=>typeof f==="string"&&f.length>0&&!f.includes("\x00")),impactMap=impactMapOverride??await _internals192.loadImpactMap(cwd),impactedTestsSet=new Set,impactedTestKeys=new Set,untestedFiles=[],budgetExceeded=!1,traversedReferences=0,traversedSources=0,testKey=(test)=>{let resolved=path241.isAbsolute(test)?test:path241.resolve(cwd,test),normalized=normalizePath2(resolved);return process.platform==="win32"?normalized.toLowerCase():normalized},addImpactedTest=(test)=>{if(++traversedReferences>MAX_IMPACT_MAP_REFERENCES)return budgetExceeded=!0,!1;let key2=testKey(test);if(impactedTestKeys.has(key2))return!0;if(budget!==void 0&&impactedTestKeys.size>=budget)return budgetExceeded=!0,!1;return impactedTestKeys.add(key2),impactedTestsSet.add(test),!0};for(let changedFile of validFiles){let normalizedChanged=normalizePath2(path241.resolve(cwd,changedFile)),tests=impactMap[normalizedChanged];if(tests&&tests.length>0){for(let test of tests)if(addImpactedTest(test),budgetExceeded)break;if(budgetExceeded)break}else{let changedDir=normalizePath2(path241.dirname(normalizedChanged)),changedInputDir=normalizePath2(path241.dirname(changedFile)),suffixMatches=[];for(let sourcePath in impactMap){if(!Object.hasOwn(impactMap,sourcePath))continue;if(++traversedSources>MAX_IMPACT_MAP_SOURCES){budgetExceeded=!0;break}let tests2=impactMap[sourcePath];if(!Array.isArray(tests2))continue;if(sourcePath.endsWith(changedFile)||changedFile.endsWith(sourcePath)||sourcePath.endsWith(normalizedChanged)||normalizedChanged.endsWith(sourcePath))suffixMatches.push([sourcePath,tests2])}if(budgetExceeded)break;suffixMatches.sort(([sourceA],[sourceB])=>{let sourceDirA=normalizePath2(path241.dirname(sourceA)),sourceDirB=normalizePath2(path241.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)});let found=suffixMatches.length>0;for(let[,tests2]of suffixMatches){for(let test of tests2)if(addImpactedTest(test),budgetExceeded)break;if(budgetExceeded)break}if(budgetExceeded)break;if(!found)untestedFiles.push(changedFile)}}let impactedTests=[...impactedTestsSet],allTestFiles=new Map;if(!budgetExceeded)traversedReferences=0,traversedSources=0;for(let sourcePath in impactMap){if(budgetExceeded)break;if(!Object.hasOwn(impactMap,sourcePath))continue;if(++traversedSources>MAX_IMPACT_MAP_SOURCES){budgetExceeded=!0;break}let tests=impactMap[sourcePath];if(!Array.isArray(tests))continue;for(let test of tests){if(++traversedReferences>MAX_IMPACT_MAP_REFERENCES){budgetExceeded=!0;break}if(typeof test!=="string")continue;let key2=testKey(test);if(!allTestFiles.has(key2))allTestFiles.set(key2,test)}}let unrelatedTests=[...allTestFiles.entries()].filter(([key2])=>!impactedTestKeys.has(key2)).map(([,test])=>test);return{impactedTests,unrelatedTests,untestedFiles,impactMap,budgetExceeded}}var MAX_IMPACT_TEST_FILES=4096,MAX_IMPACT_TEST_FILE_BYTES=4194304,MAX_IMPACT_GO_MOD_BYTES=1048576,MAX_IMPACT_SCAN_BYTES=134217728,MAX_IMPACT_WALK_ENTRIES=1e5,MAX_IMPACT_SCAN_DEPTH=32,MAX_IMPACT_CACHE_BYTES=33554432,MAX_IMPACT_MAP_SOURCES=1e4,MAX_IMPACT_MAP_REFERENCES=1e5,ImpactScanLimitError,IMPORT_REGEX_ES_SIDE_EFFECT,IMPORT_REGEX_ES_FROM,IMPORT_REGEX_REQUIRE,IMPORT_REGEX_REEXPORT,TS_EXTENSIONS,PYTHON_EXTENSIONS,GO_EXTENSIONS,EXTENSIONS_TO_TRY,SKIP_TEST_SCAN_DIRS,goModuleCache,_internals192;var init_analyzer=__esm(()=>{init_manager2();init_go2();init_python2();init_atomic_write();ImpactScanLimitError=class ImpactScanLimitError extends Error{code="IMPACT_SCAN_LIMIT";constructor(){super("impact analysis scan limits exceeded");this.name="ImpactScanLimitError"}};IMPORT_REGEX_ES_SIDE_EFFECT=/\bimport\s*['"]([^'"]+)['"]/g,IMPORT_REGEX_ES_FROM=/\bimport\s+(?:(?!\b(?:import|export)\b)[^;])*?\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"];SKIP_TEST_SCAN_DIRS=new Set(["node_modules","dist",".git",".swarm",".cache"]);goModuleCache=new Map;_internals192={validateProjectRoot,normalizePath:normalizePath2,isCacheStale,resolveRelativeImport,findTestFilesSync,extractImports:extractImports4,findGoModule,buildImpactMapInternal,buildImpactMap,loadImpactMap,loadImpactMapWithStatus,saveImpactMap,analyzeImpact,getImpactCacheStatus,_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 key2=`${record3.testFile.toLowerCase()}\x00${record3.testName.toLowerCase()}`;if(!grouped.has(key2))grouped.set(key2,{records:[],originalFile:record3.testFile,originalName:record3.testName});grouped.get(key2).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 fs131 from"node:fs";import path242 from"node:path";function normalizedTestKey(rec){return`${rec.testFile.toLowerCase()}|${rec.testName.toLowerCase()}`}function enforceGlobalHistoryCaps(records){let entryCap=resolveRetentionCap("MAX_TEST_HISTORY_ENTRIES",MAX_TEST_HISTORY_ENTRIES),keyCap=resolveRetentionCap("MAX_TEST_HISTORY_KEYS",MAX_TEST_HISTORY_KEYS),out=records;if(out.length>entryCap)out=out.slice(out.length-entryCap);if(out.length===0)return out;let lastSeenIndex=new Map;for(let i=0;i<out.length;i++)lastSeenIndex.set(normalizedTestKey(out[i]),i);if(lastSeenIndex.size<=keyCap)return out;let keysByRecency=[...lastSeenIndex.entries()].sort((a,b)=>a[1]-b[1]).map(([key2])=>key2),dropKeys=new Set(keysByRecency.slice(0,lastSeenIndex.size-keyCap));if(out=out.filter((rec)=>!dropKeys.has(normalizedTestKey(rec))),out.length>entryCap)out=out.slice(out.length-entryCap);return out}function getHistoryPath(workingDir){if(!workingDir)throw Error("getHistoryPath requires a working directory — project root must be provided by the caller");if(!path242.isAbsolute(workingDir))throw Error(`getHistoryPath requires an absolute project root path, got: "${workingDir}"`);return path242.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=path242.dirname(historyPath);if(_internals193.validateProjectRoot(workingDir),!fs131.existsSync(historyDir))fs131.mkdirSync(historyDir,{recursive:!0});withHistoryWriteLock(historyPath,()=>{let existingRecords=readAllRecords(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());let cappedRecords=enforceGlobalHistoryCaps(prunedRecords);try{let content=`${cappedRecords.map((rec)=>JSON.stringify(rec)).join(`
4069
4069
  `)}
4070
4070
  `,tempPath=`${historyPath}.tmp`;fs131.writeFileSync(tempPath,content,"utf-8"),fs131.renameSync(tempPath,historyPath)}catch(err){try{let tempPath=`${historyPath}.tmp`;if(fs131.existsSync(tempPath))fs131.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{fs131.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=fs131.statSync(lockPath);if(Date.now()-lockStat.mtimeMs>=HISTORY_WRITE_LOCK_STALE_MS){fs131.rmSync(lockPath,{recursive:!0,force:!0});continue}}catch{}let remainingMs2=Math.max(0,deadline-Date.now()),sleepMs=Math.min(HISTORY_WRITE_LOCK_BACKOFF_MS,remainingMs2);if(sleepMs>0)sleepSync4(sleepMs)}try{return fn2()}finally{try{fs131.rmSync(lockPath,{recursive:!0,force:!0})}catch{}}function sleepSync4(ms){let until=Date.now()+ms;while(Date.now()<until);}}function readAllRecords(historyPath){if(!fs131.existsSync(historyPath))return[];try{let lines=fs131.readFileSync(historyPath,"utf-8").split(`
4071
- `),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=readAllRecords(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,MAX_TEST_HISTORY_ENTRIES=5000,MAX_TEST_HISTORY_KEYS=1000,DANGEROUS_PROPERTY_NAMES,_internals193;var init_history_store=__esm(()=>{init_manager2();init_caps();DANGEROUS_PROPERTY_NAMES=new Set(["__proto__","constructor","prototype"]);_internals193={validateProjectRoot}});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 fs132 from"node:fs";import*as path243 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=path243.join(directory,"artisan");if(!fs132.existsSync(artisanPath))return!1;try{return fs132.statSync(artisanPath).isFile()}catch{return!1}}function checkLaravelFrameworkDep(directory){let composerPath=path243.join(directory,"composer.json");if(!fs132.existsSync(composerPath))return!1;try{let content=fs132.readFileSync(composerPath,"utf-8");return typeof(JSON.parse(content)?.require??{})["laravel/framework"]==="string"}catch{return!1}}function checkConfigApp(directory){return fs132.existsSync(path243.join(directory,"config","app.php"))}function isLarastanConfigured(directory){let neonPath=path243.join(directory,"phpstan.neon");if(!fs132.existsSync(neonPath))return!1;try{let fd=fs132.openSync(neonPath,"r");try{let buf=Buffer.alloc(4096),bytesRead=fs132.readSync(fd,buf,0,4096,0),content=buf.subarray(0,bytesRead).toString("utf-8");return content.includes("nunomaduro/larastan")||content.includes("larastan/larastan")}finally{fs132.closeSync(fd)}}catch{return!1}}function getLaravelCommandOverlay(directory){if(!detectLaravelProject(directory))return null;let lintCommand=null;if(fs132.existsSync(path243.join(directory,"pint.json")))lintCommand="vendor/bin/pint --test";else if(fs132.existsSync(path243.join(directory,".php-cs-fixer.php")))lintCommand="vendor/bin/php-cs-fixer fix --dry-run --diff";let staticAnalysisCommand=null,staticAnalysisTool=null,hasPhpstanNeon=fs132.existsSync(path243.join(directory,"phpstan.neon")),hasPhpstanNeonDist=fs132.existsSync(path243.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 fs133 from"node:fs";import*as path244 from"node:path";async function selectFramework4(dir){if(detectLaravelProject(dir))return{name:"laravel",detectedVia:"Laravel signals (artisan / composer.json / config/app.php)"};return null}async function selectTestFramework2(dir){if(detectLaravelProject(dir))return{name:"php-artisan",cmd:["php","artisan","test"],cwd:dir,detectedVia:"Laravel signals (artisan / composer.json / config/app.php)"};if(fs133.existsSync(path244.join(dir,"Pest.php")))return{name:"pest",cmd:[phpVendorBin2("pest")],cwd:dir,detectedVia:"Pest.php"};if(fs133.existsSync(path244.join(dir,"phpunit.xml")))return{name:"phpunit",cmd:[phpVendorBin2("phpunit")],cwd:dir,detectedVia:"phpunit.xml"};if(fs133.existsSync(path244.join(dir,"phpunit.xml.dist")))return{name:"phpunit",cmd:[phpVendorBin2("phpunit")],cwd:dir,detectedVia:"phpunit.xml.dist"};return null}function phpVendorBin2(name){return path244.join("vendor","bin",process.platform==="win32"?`${name}.bat`:name)}function buildPhpBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)throw Error("buildPhpBackend: php profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...defaultBackendFor(profile),selectFramework:selectFramework4,selectTestFramework:selectTestFramework2}}var PROFILE_ID4="php";var init_php2=__esm(()=>{init_default_backend();init_framework_detector();init_profiles()});import*as fs134 from"node:fs";import*as path245 from"node:path";function readPackageJsonRaw(dir){try{let content=fs134.readFileSync(path245.join(dir,"package.json"),"utf-8");return JSON.parse(content)}catch{return null}}function readPackageJson(dir){return _internals194.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 selectTestFramework3(dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);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 buildTestCommand2(framework,files,dir,opts){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);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 selectFramework5(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 selectEntryPoints4(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 extractImports5(_sourceFile,source){let out=new Set;for(let re of[IMPORT_REGEX_ES,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_ID5);if(!profile)return null;return defaultSelectBuildCommand(profile,dir)}async function testFilesFor(sourceFile,dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)return[];return defaultTestFilesFor(profile,sourceFile,dir)}function buildTypescriptBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)throw Error("buildTypescriptBackend: typescript profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...profile,selectTestFramework:selectTestFramework3,buildTestCommand:buildTestCommand2,parseTestOutput,extractImports:extractImports5,selectBuildCommand,testFilesFor,selectFramework:selectFramework5,selectEntryPoints:selectEntryPoints4}}var PROFILE_ID5="typescript",IMPORT_REGEX_ES,IMPORT_REGEX_BARE,IMPORT_REGEX_REQUIRE2,IMPORT_REGEX_DYNAMIC,IMPORT_REGEX_REEXPORT2,_internals194;var init_typescript=__esm(()=>{init_default_backend();init_profiles();IMPORT_REGEX_ES=/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;_internals194={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(buildJavaBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildPhpBackend()),registered=!0}var registered=!1;var init_backends=__esm(()=>{init_registry_backend();init_go2();init_java2();init_php2();init_python2();init_typescript();registerAllBackends()});import*as fs135 from"node:fs";import*as path246 from"node:path";function hasManifestInDirectory(directory){try{return fs135.readdirSync(directory).some((entry)=>MANIFEST_SET.has(entry))}catch{return!1}}function findGitMarkerAncestor(start){let current=path246.resolve(start);for(let depth=0;depth<32;depth++){let marker=path246.join(current,".git");try{if(!fs135.lstatSync(marker).isSymbolicLink())return current}catch(error93){let code=error93.code;if(code!=="ENOENT"&&code!=="ENOTDIR")return}let parent=path246.dirname(current);if(parent===current)return null;current=parent}return}function hasManifestAncestor(start){let resolved=path246.resolve(start),gitRoot=findGitMarkerAncestor(resolved);if(gitRoot===void 0)return!0;if(gitRoot===null)return hasManifestInDirectory(resolved);let current=resolved;for(let depth=0;depth<32;depth++){if(hasManifestInDirectory(current))return!0;if(current===gitRoot)return!1;let parent=path246.dirname(current);if(parent===current)return!1;current=parent}return!0}function hasGitMarkerAncestor(start){return findGitMarkerAncestor(start)!==null}function hasSwarmState(start){try{return fs135.lstatSync(path246.join(path246.resolve(start),".swarm")),!0}catch(error93){let code=error93.code;return code!=="ENOENT"&&code!=="ENOTDIR"}}var MANIFEST_FILES,MANIFEST_SET;var init_manifest_files=__esm(()=>{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)});var exports_dispatch={};__export(exports_dispatch,{pickedProfiles:()=>pickedProfiles,pickBackend:()=>pickBackend,clearDispatchCache:()=>clearDispatchCache,_internals:()=>_internals195});import*as fs136 from"node:fs";import*as path247 from"node:path";async function tryReadDirectoryAsync(dir){try{return new Set(await fs136.promises.readdir(dir))}catch{return null}}async function manifestHash(dir,signal){let entries2=await tryReadDirectoryAsync(dir);if(throwIfAborted3(signal),entries2===null||entries2.size===0)return"";let names=MANIFEST_FILES.filter((name)=>entries2.has(name)),parts=await Promise.all(names.map(async(name)=>{try{let stat23=await fs136.promises.stat(path247.join(dir,name));return`${name}:${stat23.size}:${stat23.mtimeMs}:${stat23.ino}`}catch{return null}}));return throwIfAborted3(signal),parts.filter((part)=>part!==null).join("|")}function cacheProfileKey(input,cacheKey){let key2=canonicalRootKeyLexical(input);profileCacheKeyByInput.delete(key2),profileCacheKeyByInput.set(key2,cacheKey);while(profileCacheKeyByInput.size>_internals195.cacheCapacity){let oldest=profileCacheKeyByInput.keys().next().value;if(oldest===void 0)break;profileCacheKeyByInput.delete(oldest)}}async function directoryFingerprint(dir){try{let stat23=await fs136.promises.stat(dir);if(!stat23.isDirectory())return null;return{directory:dir,dev:stat23.dev,ino:stat23.ino,size:stat23.size,mtimeMs:stat23.mtimeMs,ctimeMs:stat23.ctimeMs}}catch{return null}}function fingerprintsMatch(expected,actual){return expected.dev===actual.dev&&expected.ino===actual.ino&&expected.size===actual.size&&expected.mtimeMs===actual.mtimeMs&&expected.ctimeMs===actual.ctimeMs}async function readDirectoryForManifestWalk(dir){let entries2=await tryReadDirectoryAsync(dir),fingerprint2=await directoryFingerprint(dir),after=await tryReadDirectoryAsync(dir);if(entries2===null||fingerprint2===null||after===null)return{entries:null,complete:!1,stopAtCurrent:!0};if(entries2.size!==after.size||[...entries2].some((entry)=>!after.has(entry)))return{entries:null,complete:!1,stopAtCurrent:!1};return{entries:entries2,fingerprint:fingerprint2,complete:!0}}async function isManifestRootCacheEntryValid(entry){for(let fingerprint2 of entry.trace){let current=await directoryFingerprint(fingerprint2.directory);if(current===null||!fingerprintsMatch(fingerprint2,current))return!1}return!0}async function isSelectedRootObservationStillValid(resolution,hash5,signal){let currentHash=await manifestHash(resolution.root,signal);if(throwIfAborted3(signal),currentHash!==hash5||resolution.rootHadManifest&&currentHash==="")return!1;return!0}function evictManifestRootCacheIfNeeded(){if(manifestRootCache.size<=_internals195.cacheCapacity)return;let oldestKey,oldestOrder=1/0;for(let[key2,value]of manifestRootCache)if(value.insertOrder<oldestOrder)oldestKey=key2,oldestOrder=value.insertOrder;if(oldestKey!==void 0)manifestRootCache.delete(oldestKey)}function cacheManifestRoot(key2,root,rootHadManifest,trace,cacheable,signal){if(!cacheable||signal?.aborted)return;manifestRootCache.set(key2,{root,rootHadManifest,trace,insertOrder:manifestRootInsertCounter++}),evictManifestRootCacheIfNeeded()}function throwIfAborted3(signal){if(signal?.aborted)throw signal.reason??Error("manifest-root lookup aborted")}async function findManifestRoot(start,signal){throwIfAborted3(signal);let resolved=path247.resolve(start),key2=await canonicalRootKeyFreshAsync(resolved);throwIfAborted3(signal);let cached3=manifestRootCache.get(key2);if(cached3!==void 0){if(await isManifestRootCacheEntryValid(cached3))return throwIfAborted3(signal),{root:cached3.root,rootHadManifest:cached3.rootHadManifest,key:key2,trace:[],cacheable:!1};manifestRootCache.delete(key2)}let cur=resolved,trace=[],cacheable=!0;for(let i=0;i<MAX_MANIFEST_SEARCH_DEPTH;i++){let snapshot=await readDirectoryForManifestWalk(cur);if(throwIfAborted3(signal),!snapshot.complete){if(snapshot.stopAtCurrent)return{root:cur,rootHadManifest:!1,key:key2,trace,cacheable:!1};cacheable=!1}else trace.push(snapshot.fingerprint);let{entries:entries2}=snapshot;if(entries2!==null){if(entries2.size>0){for(let name of MANIFEST_FILES)if(entries2.has(name))return{root:cur,rootHadManifest:!0,key:key2,trace,cacheable};if(entries2.has(".git"))return{root:cur,rootHadManifest:!1,key:key2,trace,cacheable}}}let parent=path247.dirname(cur);if(parent===cur)break;cur=parent}return{root:start,rootHadManifest:!1,key:key2,trace,cacheable}}function evictIfNeeded(){if(cache5.size<=_internals195.cacheCapacity)return;let oldestKey,oldestOrder=1/0;for(let[k,v]of cache5.entries())if(v.insertOrder<oldestOrder)oldestOrder=v.insertOrder,oldestKey=k;if(oldestKey!==void 0)cache5.delete(oldestKey)}async function pickBackend(dir,signal){for(let attempt=0;attempt<2;attempt++){let resolution=await findManifestRoot(dir,signal),{root}=resolution;throwIfAborted3(signal);let hash5=await manifestHash(root,signal);if(throwIfAborted3(signal),resolution.rootHadManifest&&hash5===""){if(manifestRootCache.delete(resolution.key),attempt===0)continue;return profileCacheKeyByInput.delete(canonicalRootKeyLexical(dir)),null}let cacheKey=await canonicalRootKeyFreshAsync(root);throwIfAborted3(signal);let cached3=cache5.get(cacheKey);if(cached3&&cached3.hash===hash5)return cacheManifestRoot(resolution.key,root,resolution.rootHadManifest,resolution.trace,resolution.cacheable,signal),cacheProfileKey(dir,cacheKey),cached3.backend;if(hash5==="")return cacheManifestRoot(resolution.key,root,resolution.rootHadManifest,resolution.trace,resolution.cacheable,signal),cache5.set(cacheKey,{hash:hash5,backend:null,profiles:[],insertOrder:insertCounter++}),evictIfNeeded(),cacheProfileKey(dir,cacheKey),null;let profiles=await _internals195.detectProjectLanguages(root);if(throwIfAborted3(signal),!await isSelectedRootObservationStillValid(resolution,hash5,signal)){if(manifestRootCache.delete(resolution.key),attempt===0)continue;return profileCacheKeyByInput.delete(canonicalRootKeyLexical(dir)),null}if(cacheManifestRoot(resolution.key,root,resolution.rootHadManifest,resolution.trace,resolution.cacheable,signal),profiles.length===0)return cache5.set(cacheKey,{hash:hash5,backend:null,profiles:[],insertOrder:insertCounter++}),evictIfNeeded(),cacheProfileKey(dir,cacheKey),null;let winner=profiles[0],backend=LANGUAGE_BACKEND_REGISTRY.getOrDefault(winner.id)??null;return cache5.set(cacheKey,{hash:hash5,backend,profiles:profiles.map((p)=>({id:p.id})),insertOrder:insertCounter++}),evictIfNeeded(),cacheProfileKey(dir,cacheKey),backend}return null}function pickedProfiles(dir){let cacheKey=profileCacheKeyByInput.get(canonicalRootKeyLexical(dir));if(cacheKey===void 0)return[];return cache5.get(cacheKey)?.profiles??[]}function clearDispatchCache(){cache5.clear(),manifestRootCache.clear(),profileCacheKeyByInput.clear(),insertCounter=0,manifestRootInsertCounter=0}var _internals195,cache5,insertCounter=0,MAX_MANIFEST_SEARCH_DEPTH=32,manifestRootCache,manifestRootInsertCounter=0,profileCacheKeyByInput;var init_dispatch=__esm(()=>{init_backends();init_canonical_root();init_detector();init_manifest_files();init_registry_backend();_internals195={detectProjectLanguages,cacheCapacity:64,get manifestRootCacheSize(){return manifestRootCache.size}},cache5=new Map;manifestRootCache=new Map,profileCacheKeyByInput=new Map});import*as fs137 from"node:fs";import*as path248 from"node:path";async function estimateFanOut(sourceFiles,cwd){try{let impactMap=await _internals196.loadImpactMap(cwd,{skipRebuild:!0}),uniqueTestFiles=new Set;for(let sourceFile of sourceFiles){let normalizedPath=path248.resolve(cwd,sourceFile).replace(/\\/g,"/"),testFiles=impactMap[normalizedPath];if(testFiles)for(let testFile of testFiles){let normalized=testFile.replace(/\\/g,"/");uniqueTestFiles.add(process.platform==="win32"?normalized.toLowerCase():normalized)}}return{estimatedCount:uniqueTestFiles.size,status:"advisory"}}catch{return{estimatedCount:0,status:"unavailable"}}}function normalizeSelectionFiles(files,workingDir){let seen=new Set,normalized=[];for(let file3 of files){let absolute=path248.resolve(workingDir,file3),relative57=path248.relative(workingDir,absolute),output=(path248.isAbsolute(relative57)?absolute:relative57).replace(/\\/g,"/"),key2=process.platform==="win32"?output.toLowerCase():output;if(!seen.has(key2))seen.add(key2),normalized.push(output)}return normalized}function makeResolution(requestedScope,effectiveScope,sourceFiles,resolvedFiles,decision,workingDir,options){let estimateCount=options?.estimate?.estimatedCount??0,estimateStatus=options?.estimate?.status??"not_run",fallbackReason=options?.fallbackReason??(options?.cacheStatus?.startsWith("rebuilt_")?`impact cache rebuild completed (${options.cacheStatus}) before resolution`:null);return{requestedScope,effectiveScope,sourceFiles:normalizeSelectionFiles(sourceFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1),resolvedFiles:normalizeSelectionFiles(resolvedFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1),cap:MAX_SAFE_TEST_FILES2,decision,estimate:{count:estimateCount,status:estimateStatus},estimateCount,estimateStatus,...options?.cacheStatus&&{cacheStatus:options.cacheStatus},fallbackReason,evaluable:decision==="execute"}}function resolutionFields(resolution){return{resolved_test_files:resolution.resolvedFiles,cap_decision:{decision:resolution.decision==="scope_exceeded"?"cap_exceeded":"within_cap",resolved_test_count:resolution.resolvedFiles.length,limit:resolution.cap},...resolution.fallbackReason?{fallback_reason:resolution.fallbackReason}:{}}}function cacheStatusAfterRebuild(before,after){let normalize25=(status2)=>status2.endsWith("_unverified")?status2.slice(0,-11):status2,beforeState=normalize25(before),afterState=normalize25(after);if(afterState==="fresh"){if(beforeState==="missing"||beforeState==="corrupt"||beforeState==="legacy"||beforeState==="stale")return`rebuilt_${beforeState}`}return afterState===beforeState?afterState:after}async function loadImpactMapForImpactScope(workingDir){if(_internals196.loadImpactMap!==DEFAULT_LOAD_IMPACT_MAP){let before=getImpactCacheStatus(workingDir,{verify:!1}).status,map3=await _internals196.loadImpactMap(workingDir),after=getImpactCacheStatus(workingDir,{verify:!1}).status;return{map:map3,status:cacheStatusAfterRebuild(before,after)}}return _internals196.loadImpactMapWithStatus(workingDir)}function cacheStatusForAdvisory(status2){if(status2==="missing")return"missing_unverified";if(status2==="corrupt")return"corrupt_unverified";if(status2==="legacy")return"legacy_unverified";return status2}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 containsShellMetacharacters(str){return SHELL_METACHARACTERS2.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"&&obj.scope!=="target")return!1}if(obj.native_target!==void 0){if(typeof obj.native_target!=="object"||obj.native_target===null)return!1;let target=obj.native_target;if(target.framework!=="go-test"&&target.framework!=="ctest")return!1;if(typeof target.name!=="string"||typeof target.path!=="string")return!1;if(target.name.length===0||target.name.length>256)return!1;if(target.path.length===0||target.path.length>1024)return!1;if(containsControlChars(target.name)||containsControlChars(target.path))return!1;if(target.framework==="go-test"&&target.name.split("/").some((p)=>!p))return!1;if(isAbsolutePath(target.path)||containsPathTraversal(target.path))return!1}if(obj.scope==="target"){if(obj.native_target===void 0)return!1;if(Array.isArray(obj.files)&&obj.files.length>0)return!1;if(obj.coverage===!0||obj.bail===!0)return!1}else if(obj.native_target!==void 0)return!1;if(obj.files!==void 0){if(!Array.isArray(obj.files))return!1;if(obj.files.length>MAX_RAW_FILE_ENTRIES)return!1;for(let f of obj.files){if(typeof f!=="string")return!1;if(f.length===0||f.length>MAX_FILE_PATH_LENGTH2)return!1;if(isAbsolutePath(f))return!1;if(containsPathTraversal(f))return!1;if(containsControlChars(f))return!1;if(containsPowerShellMetacharacters(f))return!1}}if(obj.targets!==void 0){if(!Array.isArray(obj.targets))return!1;for(let t of obj.targets){if(typeof t!=="string")return!1;if(t.length===0)return!1;if(isAbsolutePath(t))return!1;if(containsPathTraversal(t))return!1;if(containsControlChars(t))return!1;if(containsShellMetacharacters(t))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_MS3)return!1}return!0}function validateNativeTargetInput(target){if(target.framework!=="go-test"&&target.framework!=="ctest")return'Native target framework must be "go-test" or "ctest"';if(typeof target.name!=="string"||target.name.length===0||target.name.length>256)return"Native target name must be a non-empty string up to 256 characters";if(typeof target.path!=="string"||target.path.length===0||target.path.length>1024)return"Native target path must be a non-empty string up to 1024 characters";if(containsControlChars(target.name)||containsControlChars(target.path))return"Native target values must not contain control characters";if(target.framework==="go-test"&&target.name.split("/").some((p)=>!p))return"Go native target name must not contain empty slash-separated segments";if(isAbsolutePath(target.path))return"Native target path must be workspace-relative, not absolute";if(containsPathTraversal(target.path))return"Native target path escapes project root";return}function resolveNativeTarget(target,workingDir){let rootReal,targetReal;try{if(rootReal=fs137.realpathSync(workingDir),targetReal=fs137.realpathSync(path248.resolve(rootReal,target.path)),!fs137.statSync(targetReal).isDirectory())return{success:!1,error:"Native target path must be a directory"}}catch{return{success:!1,error:"Native target path does not exist"}}let relative57=path248.relative(rootReal,targetReal);if(relative57.startsWith("..")||path248.isAbsolute(relative57))return{success:!1,error:"Native target path escapes project root"};if(!_internals196.isCommandAvailable(target.framework==="go-test"?"go":"ctest"))return{success:!1,error:`Native target framework "${target.framework}" is unavailable`};let executionDirectory=rootReal,commandRelative=relative57;if(target.framework==="go-test"){let hasRootWorkspace=fs137.existsSync(path248.join(rootReal,"go.work")),moduleRoot;for(let current=targetReal;;current=path248.dirname(current)){if(fs137.existsSync(path248.join(current,"go.mod"))){moduleRoot=current;break}if(current===rootReal)break;let parent=path248.dirname(current);if(parent===current||path248.relative(rootReal,parent).startsWith(".."))break}if(!hasRootWorkspace&&!moduleRoot)return{success:!1,error:"Go native target requires an enclosing go.mod or go.work at the project root"};if(!hasRootWorkspace&&moduleRoot)executionDirectory=moduleRoot,commandRelative=path248.relative(moduleRoot,targetReal)}else if(!fs137.existsSync(path248.join(targetReal,"CMakeCache.txt")))return{success:!1,error:"CTest native target requires CMakeCache.txt in the target directory"};return{success:!0,target:{...target,path:commandRelative.length===0?".":commandRelative.replace(/\\/g,"/")},executionDirectory,historyPath:relative57.length===0?".":relative57.replace(/\\/g,"/")}}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 _internals196.existsSync(path248.join(cwd,"go.mod"))&&_internals196.isCommandAvailable("go")}function detectJavaMaven(cwd){return _internals196.existsSync(path248.join(cwd,"pom.xml"))&&_internals196.isCommandAvailable("mvn")}function detectGradle(cwd){let hasBuildFile=_internals196.existsSync(path248.join(cwd,"build.gradle"))||_internals196.existsSync(path248.join(cwd,"build.gradle.kts")),hasGradlew=_internals196.existsSync(path248.join(cwd,"gradlew"))||_internals196.existsSync(path248.join(cwd,"gradlew.bat"));return hasBuildFile&&(hasGradlew||_internals196.isCommandAvailable("gradle"))}function detectDotnetTest(cwd){try{return _internals196.readdirSync(cwd).some((f)=>f.endsWith(".csproj"))&&_internals196.isCommandAvailable("dotnet")}catch{return!1}}function detectCTest(cwd){let hasSource=_internals196.existsSync(path248.join(cwd,"CMakeLists.txt")),hasBuildCache=_internals196.existsSync(path248.join(cwd,"CMakeCache.txt"))||_internals196.existsSync(path248.join(cwd,"build","CMakeCache.txt"));return(hasSource||hasBuildCache)&&_internals196.isCommandAvailable("ctest")}function detectSwiftTest(cwd){return _internals196.existsSync(path248.join(cwd,"Package.swift"))&&_internals196.isCommandAvailable("swift")}function detectDartTest(cwd){return _internals196.existsSync(path248.join(cwd,"pubspec.yaml"))&&(_internals196.isCommandAvailable("dart")||_internals196.isCommandAvailable("flutter"))}function detectRSpec(cwd){let hasRSpecFile=_internals196.existsSync(path248.join(cwd,".rspec")),hasGemfile=_internals196.existsSync(path248.join(cwd,"Gemfile")),hasSpecDir=_internals196.existsSync(path248.join(cwd,"spec"));return(hasRSpecFile||hasGemfile&&hasSpecDir)&&(_internals196.isCommandAvailable("bundle")||_internals196.isCommandAvailable("rspec"))}function detectMinitest(cwd){return _internals196.existsSync(path248.join(cwd,"test"))&&(_internals196.existsSync(path248.join(cwd,"Gemfile"))||_internals196.existsSync(path248.join(cwd,"Rakefile")))&&_internals196.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,targets,nativeTarget){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,targets,nativeTarget});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}}function relativeEscapesRoot(relative57){return relative57===".."||relative57.startsWith(`..${path248.sep}`)||path248.isAbsolute(relative57)}function resolveMavenModuleDir(root,files){let resolvedRoot=path248.resolve(root),rootReal,isContainedModuleDir=(dir)=>{if(rootReal===void 0)try{rootReal=_internals196.realpathSync(resolvedRoot)}catch{rootReal=null}if(rootReal===null)return!1;let dirReal;try{dirReal=_internals196.realpathSync(dir)}catch{return!1}return!relativeEscapesRoot(path248.relative(rootReal,dirReal))};if(files&&files.length>0){for(let file3 of files){let resolvedFile=path248.resolve(resolvedRoot,file3),relativeToRoot=path248.relative(resolvedRoot,resolvedFile);if(relativeEscapesRoot(relativeToRoot))continue;let current=path248.dirname(resolvedFile);while(!0){if(_internals196.existsSync(path248.join(current,"pom.xml"))&&isContainedModuleDir(current))return current;if(current===resolvedRoot)break;let parent=path248.dirname(current);if(parent===current)break;if(relativeEscapesRoot(path248.relative(resolvedRoot,parent)))break;current=parent}}return null}let entries2;try{entries2=_internals196.readdirSync(resolvedRoot)}catch{return null}entries2.sort((a,b)=>a.localeCompare(b));let inspected=0;for(let entry of entries2){if(entry.startsWith(".")||entry==="node_modules")continue;if(inspected>=MAX_MAVEN_MODULE_PROBE_ENTRIES)break;inspected++;let candidate2=path248.join(resolvedRoot,entry);if(_internals196.existsSync(path248.join(candidate2,"pom.xml"))&&isContainedModuleDir(candidate2))return candidate2}return null}function resolveNestedMavenModuleDir(root,files){if(_internals196.existsSync(path248.join(root,"pom.xml")))return null;return resolveMavenModuleDir(root,files)}async function detectTestFramework(cwd,files){let baseDir=cwd;try{let packageJsonPath=path248.join(baseDir,"package.json");if(_internals196.existsSync(packageJsonPath)){let content=_internals196.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(_internals196.existsSync(path248.join(baseDir,"bun.lockb"))||_internals196.existsSync(path248.join(baseDir,"bun.lock"))){if(scripts.test?.includes("bun"))return"bun"}}}catch{}try{let pyprojectTomlPath=path248.join(baseDir,"pyproject.toml"),setupCfgPath=path248.join(baseDir,"setup.cfg"),requirementsTxtPath=path248.join(baseDir,"requirements.txt");if(_internals196.existsSync(pyprojectTomlPath)){let content=_internals196.readFileSync(pyprojectTomlPath,"utf-8");if(content.includes("[tool.pytest"))return"pytest";if(content.includes("pytest"))return"pytest"}if(_internals196.existsSync(setupCfgPath)){if(_internals196.readFileSync(setupCfgPath,"utf-8").includes("[pytest]"))return"pytest"}if(_internals196.existsSync(requirementsTxtPath)){if(_internals196.readFileSync(requirementsTxtPath,"utf-8").includes("pytest"))return"pytest"}}catch{}try{let cargoTomlPath=path248.join(baseDir,"Cargo.toml");if(_internals196.existsSync(cargoTomlPath)){let content=_internals196.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=path248.join(baseDir,"pester.config.ps1"),pesterConfigJsonPath=path248.join(baseDir,"pester.config.ps1.json"),pesterPs1Path=path248.join(baseDir,"tests.ps1");if(_internals196.existsSync(pesterConfigPath)||_internals196.existsSync(pesterConfigJsonPath)||_internals196.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";let mavenModuleDir=resolveNestedMavenModuleDir(baseDir,files);if(mavenModuleDir&&(_internals196.isCommandAvailable("mvn")||resolveMavenWrapperCommand(mavenModuleDir,["test"])!==null))return"maven";return"none"}function detectPhpTest(cwd){if(_internals196.existsSync(path248.join(cwd,"artisan"))&&_internals196.existsSync(path248.join(cwd,"composer.json")))return"php-artisan";if(_internals196.existsSync(path248.join(cwd,"Pest.php")))return"pest";if(_internals196.existsSync(path248.join(cwd,"phpunit.xml"))||_internals196.existsSync(path248.join(cwd,"phpunit.xml.dist")))return"phpunit";return null}function isTestDirectoryPath(normalizedPath){return normalizedPath.split("/").some((segment)=>TEST_DIRECTORY_NAMES.includes(segment))}function resolveWorkspacePath(file3,workingDir){return path248.isAbsolute(file3)?path248.resolve(file3):path248.resolve(workingDir,file3)}function toWorkspaceOutputPath(absolutePath2,workingDir,preferRelative){if(!preferRelative)return absolutePath2;return path248.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=path248.dirname(relativePath2),nestedRelativeDir=relativeDir==="."?"":relativeDir,directories=TEST_DIRECTORY_NAMES.flatMap((dirName)=>{let rootDir2=path248.join(workingDir,dirName);return nestedRelativeDir?[rootDir2,path248.join(rootDir2,nestedRelativeDir)]:[rootDir2]}),normalizedRelativePath=relativePath2.replace(/\\/g,"/");if(ext===".java"&&normalizedRelativePath.startsWith("src/main/java/"))directories.push(path248.join(workingDir,"src/test/java",path248.dirname(normalizedRelativePath.slice(14))));if((ext===".kt"||ext===".java")&&normalizedRelativePath.startsWith("src/main/kotlin/"))directories.push(path248.join(workingDir,"src/test/kotlin",path248.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(basename45){let lower=basename45.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(basename45)||basename45.endsWith("Test.java")||basename45.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(basename45)||lower.endsWith("test.kt")||lower.endsWith("tests.kt")))return!0;if(lower.endsWith(".php")&&(/^Test[A-Z]/.test(basename45)||basename45.endsWith("Test.php")||basename45.endsWith("Tests.php")))return!0;if(lower.endsWith(".tests.ps1"))return!0;return!1}function isConventionTestFilePath(filePath){let normalizedPath=filePath.replace(/\\/g,"/"),basename45=path248.basename(filePath);return hasCompoundTestExtension(basename45)||basename45.includes(".spec.")||basename45.includes(".test.")||isLanguageSpecificTestFile(basename45)||isTestDirectoryPath(normalizedPath)}function getTestFilesFromConvention(sourceFiles,workingDir=process.cwd()){let testFiles=[];for(let file3 of sourceFiles){let absoluteFile=resolveWorkspacePath(file3,workingDir),relativeFile=path248.relative(workingDir,absoluteFile),basename45=path248.basename(absoluteFile),dirname99=path248.dirname(absoluteFile),preferRelativeOutput=!path248.isAbsolute(file3);if(isConventionTestFilePath(relativeFile)||isConventionTestFilePath(file3)){dedupePush(testFiles,toWorkspaceOutputPath(absoluteFile,workingDir,preferRelativeOutput));continue}let nameWithoutExt=basename45.replace(/\.[^.]+$/,""),ext=path248.extname(basename45),genericTestNames=[`${nameWithoutExt}.spec${ext}`,`${nameWithoutExt}.test${ext}`],languageSpecificTestNames=buildLanguageSpecificTestNames(nameWithoutExt,ext),colocatedCandidates=[...genericTestNames,...languageSpecificTestNames].map((candidateName)=>path248.join(dirname99,candidateName)),testDirectoryNames=[basename45,...genericTestNames,...languageSpecificTestNames],repoLevelDirectories=getRepoLevelCandidateDirectories(workingDir,relativeFile,ext),possibleTestFiles=[...colocatedCandidates,...TEST_DIRECTORY_NAMES.flatMap((dirName)=>testDirectoryNames.map((candidateName)=>path248.join(dirname99,dirName,candidateName))),...repoLevelDirectories.flatMap((candidateDir3)=>testDirectoryNames.map((candidateName)=>path248.join(candidateDir3,candidateName)))];for(let testFile of possibleTestFiles)if(fs137.existsSync(testFile))dedupePush(testFiles,toWorkspaceOutputPath(testFile,workingDir,preferRelativeOutput))}return testFiles}async function getTestFilesFromGraph(sourceFiles,workingDir,maxFiles=MAX_SAFE_TEST_FILES2+1){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);if(fs137.statSync(absoluteTestFile).size>MAX_GRAPH_FILE_BYTES)continue;let content=fs137.readFileSync(absoluteTestFile,"utf-8");if(Buffer.byteLength(content,"utf8")>MAX_GRAPH_FILE_BYTES)continue;let testDir=path248.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=path248.resolve(testDir,importPath),!path248.extname(resolvedImport))for(let extToTry of[".ts",".tsx",".js",".jsx",".mjs",".cjs"]){let withExt=resolvedImport+extToTry;if(absoluteSourceFiles.includes(withExt)||fs137.existsSync(withExt)){resolvedImport=withExt;break}}}else{let nextIndex=match.index+Math.max(match[0].length,1);if(importRegex.lastIndex<=match.index)importRegex.lastIndex=nextIndex;match=importRegex.exec(content);continue}let importBasename=path248.basename(resolvedImport,path248.extname(resolvedImport)),importDir=path248.dirname(resolvedImport);for(let sourceFile of absoluteSourceFiles){let sourceDir=path248.dirname(sourceFile),sourceBasename=path248.basename(sourceFile,path248.extname(sourceFile)),isRelatedDir=importDir===sourceDir||importDir===path248.join(sourceDir,"__tests__")||importDir===path248.join(sourceDir,"tests")||importDir===path248.join(sourceDir,"test")||importDir===path248.join(sourceDir,"spec");if(resolvedImport===sourceFile||importBasename===sourceBasename&&isRelatedDir){if(dedupePush(testFiles,testFile),testFiles.length>=maxFiles)return testFiles;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=path248.resolve(testDir,importPath);if(!path248.extname(resolvedImport))for(let extToTry of[".ts",".tsx",".js",".jsx",".mjs",".cjs"]){let withExt=resolvedImport+extToTry;if(absoluteSourceFiles.includes(withExt)||fs137.existsSync(withExt)){resolvedImport=withExt;break}}let importDir=path248.dirname(resolvedImport),importBasename=path248.basename(resolvedImport,path248.extname(resolvedImport));for(let sourceFile of absoluteSourceFiles){let sourceDir=path248.dirname(sourceFile),sourceBasename=path248.basename(sourceFile,path248.extname(sourceFile)),isRelatedDir=importDir===sourceDir||importDir===path248.join(sourceDir,"__tests__")||importDir===path248.join(sourceDir,"tests")||importDir===path248.join(sourceDir,"test")||importDir===path248.join(sourceDir,"spec");if(resolvedImport===sourceFile||importBasename===sourceBasename&&isRelatedDir){if(dedupePush(testFiles,testFile),testFiles.length>=maxFiles)return testFiles;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 buildTestCommand3(framework,scope,files,coverage,baseDir,bail,targets,nativeTarget){if(nativeTarget)return nativeTarget.framework===framework?buildNativeTargetCommand(nativeTarget):null;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=_internals196.resolveLocalNodeTool("vitest",["run","--reporter=json","--outputFile",VITEST_JSON_OUTPUT_RELATIVE_PATH],baseDir,process.platform,_internals196.isCommandAvailable);if(!args2)return null;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=_internals196.resolveLocalNodeTool("jest",["--json"],baseDir,process.platform,_internals196.isCommandAvailable);if(!args2)return null;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=_internals196.resolveLocalNodeTool("mocha",[],baseDir,process.platform,_internals196.isCommandAvailable);if(!args2)return null;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(targets&&targets.length>0)args2.push("--",...targets);else 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":{let args2=["go","test"];if(targets&&targets.length>0)args2.push("-run",targets.join("|"));return args2.push("./..."),args2}case"maven":return buildMavenTestCommand(baseDir,targets);case"gradle":return buildGradleTestCommand(baseDir,targets);case"dotnet-test":{let args2=["dotnet","test"];if(targets&&targets.length>0)args2.push("--filter",targets.join("|"));return args2}case"ctest":{let args2=["ctest","--test-dir",["build","_build","cmake-build-debug","cmake-build-release","out"].find((d)=>fs137.existsSync(path248.join(baseDir,d,"CMakeCache.txt")))??"build"];if(targets&&targets.length>0)args2.push("-R",targets.join("|"));return args2}case"swift-test":{let args2=["swift","test"];if(targets&&targets.length>0)for(let target of targets)args2.push("--filter",target);return args2}case"dart-test":return _internals196.isCommandAvailable("flutter")?["flutter","test",...files]:["dart","test",...files];case"rspec":{let args2=_internals196.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=[phpVendorBin3("pest")];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"phpunit":{let args2=[phpVendorBin3("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 phpVendorBin3(name){return path248.join("vendor","bin",process.platform==="win32"?`${name}.bat`:name)}function mapFrameworkStatusToResult(status2){if(typeof status2!=="string")return null;let normalized=status2.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(`
4071
+ `),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=readAllRecords(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,MAX_TEST_HISTORY_ENTRIES=5000,MAX_TEST_HISTORY_KEYS=1000,DANGEROUS_PROPERTY_NAMES,_internals193;var init_history_store=__esm(()=>{init_manager2();init_caps();DANGEROUS_PROPERTY_NAMES=new Set(["__proto__","constructor","prototype"]);_internals193={validateProjectRoot}});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 fs132 from"node:fs";import*as path243 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=path243.join(directory,"artisan");if(!fs132.existsSync(artisanPath))return!1;try{return fs132.statSync(artisanPath).isFile()}catch{return!1}}function checkLaravelFrameworkDep(directory){let composerPath=path243.join(directory,"composer.json");if(!fs132.existsSync(composerPath))return!1;try{let content=fs132.readFileSync(composerPath,"utf-8");return typeof(JSON.parse(content)?.require??{})["laravel/framework"]==="string"}catch{return!1}}function checkConfigApp(directory){return fs132.existsSync(path243.join(directory,"config","app.php"))}function isLarastanConfigured(directory){let neonPath=path243.join(directory,"phpstan.neon");if(!fs132.existsSync(neonPath))return!1;try{let fd=fs132.openSync(neonPath,"r");try{let buf=Buffer.alloc(4096),bytesRead=fs132.readSync(fd,buf,0,4096,0),content=buf.subarray(0,bytesRead).toString("utf-8");return content.includes("nunomaduro/larastan")||content.includes("larastan/larastan")}finally{fs132.closeSync(fd)}}catch{return!1}}function getLaravelCommandOverlay(directory){if(!detectLaravelProject(directory))return null;let lintCommand=null;if(fs132.existsSync(path243.join(directory,"pint.json")))lintCommand="vendor/bin/pint --test";else if(fs132.existsSync(path243.join(directory,".php-cs-fixer.php")))lintCommand="vendor/bin/php-cs-fixer fix --dry-run --diff";let staticAnalysisCommand=null,staticAnalysisTool=null,hasPhpstanNeon=fs132.existsSync(path243.join(directory,"phpstan.neon")),hasPhpstanNeonDist=fs132.existsSync(path243.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 fs133 from"node:fs";import*as path244 from"node:path";async function selectFramework4(dir){if(detectLaravelProject(dir))return{name:"laravel",detectedVia:"Laravel signals (artisan / composer.json / config/app.php)"};return null}async function selectTestFramework2(dir){if(detectLaravelProject(dir))return{name:"php-artisan",cmd:["php","artisan","test"],cwd:dir,detectedVia:"Laravel signals (artisan / composer.json / config/app.php)"};if(fs133.existsSync(path244.join(dir,"Pest.php")))return{name:"pest",cmd:buildPhpVendorCommand(dir,"pest"),cwd:dir,detectedVia:"Pest.php"};if(fs133.existsSync(path244.join(dir,"phpunit.xml")))return{name:"phpunit",cmd:buildPhpVendorCommand(dir,"phpunit"),cwd:dir,detectedVia:"phpunit.xml"};if(fs133.existsSync(path244.join(dir,"phpunit.xml.dist")))return{name:"phpunit",cmd:buildPhpVendorCommand(dir,"phpunit"),cwd:dir,detectedVia:"phpunit.xml.dist"};return null}function buildPhpBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)throw Error("buildPhpBackend: php profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...defaultBackendFor(profile),selectFramework:selectFramework4,selectTestFramework:selectTestFramework2}}var PROFILE_ID4="php";var init_php2=__esm(()=>{init_default_backend();init_framework_detector();init_profiles()});import*as fs134 from"node:fs";import*as path245 from"node:path";function readPackageJsonRaw(dir){try{let content=fs134.readFileSync(path245.join(dir,"package.json"),"utf-8");return JSON.parse(content)}catch{return null}}function readPackageJson(dir){return _internals194.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 selectTestFramework3(dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);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 buildTestCommand2(framework,files,dir,opts){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);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 selectFramework5(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 selectEntryPoints4(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 extractImports5(_sourceFile,source){let out=new Set;for(let re of[IMPORT_REGEX_ES,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_ID5);if(!profile)return null;return defaultSelectBuildCommand(profile,dir)}async function testFilesFor(sourceFile,dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)return[];return defaultTestFilesFor(profile,sourceFile,dir)}function buildTypescriptBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)throw Error("buildTypescriptBackend: typescript profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...profile,selectTestFramework:selectTestFramework3,buildTestCommand:buildTestCommand2,parseTestOutput,extractImports:extractImports5,selectBuildCommand,testFilesFor,selectFramework:selectFramework5,selectEntryPoints:selectEntryPoints4}}var PROFILE_ID5="typescript",IMPORT_REGEX_ES,IMPORT_REGEX_BARE,IMPORT_REGEX_REQUIRE2,IMPORT_REGEX_DYNAMIC,IMPORT_REGEX_REEXPORT2,_internals194;var init_typescript=__esm(()=>{init_default_backend();init_profiles();IMPORT_REGEX_ES=/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;_internals194={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(buildJavaBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildPhpBackend()),registered=!0}var registered=!1;var init_backends=__esm(()=>{init_registry_backend();init_go2();init_java2();init_php2();init_python2();init_typescript();registerAllBackends()});import*as fs135 from"node:fs";import*as path246 from"node:path";function hasManifestInDirectory(directory){try{return fs135.readdirSync(directory).some((entry)=>MANIFEST_SET.has(entry))}catch{return!1}}function findGitMarkerAncestor(start){let current=path246.resolve(start);for(let depth=0;depth<32;depth++){let marker=path246.join(current,".git");try{if(!fs135.lstatSync(marker).isSymbolicLink())return current}catch(error93){let code=error93.code;if(code!=="ENOENT"&&code!=="ENOTDIR")return}let parent=path246.dirname(current);if(parent===current)return null;current=parent}return}function hasManifestAncestor(start){let resolved=path246.resolve(start),gitRoot=findGitMarkerAncestor(resolved);if(gitRoot===void 0)return!0;if(gitRoot===null)return hasManifestInDirectory(resolved);let current=resolved;for(let depth=0;depth<32;depth++){if(hasManifestInDirectory(current))return!0;if(current===gitRoot)return!1;let parent=path246.dirname(current);if(parent===current)return!1;current=parent}return!0}function hasGitMarkerAncestor(start){return findGitMarkerAncestor(start)!==null}function hasSwarmState(start){try{return fs135.lstatSync(path246.join(path246.resolve(start),".swarm")),!0}catch(error93){let code=error93.code;return code!=="ENOENT"&&code!=="ENOTDIR"}}var MANIFEST_FILES,MANIFEST_SET;var init_manifest_files=__esm(()=>{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)});var exports_dispatch={};__export(exports_dispatch,{pickedProfiles:()=>pickedProfiles,pickBackend:()=>pickBackend,clearDispatchCache:()=>clearDispatchCache,_internals:()=>_internals195});import*as fs136 from"node:fs";import*as path247 from"node:path";async function tryReadDirectoryAsync(dir){try{return new Set(await fs136.promises.readdir(dir))}catch{return null}}async function manifestHash(dir,signal){let entries2=await tryReadDirectoryAsync(dir);if(throwIfAborted3(signal),entries2===null||entries2.size===0)return"";let names=MANIFEST_FILES.filter((name)=>entries2.has(name)),parts=await Promise.all(names.map(async(name)=>{try{let stat23=await fs136.promises.stat(path247.join(dir,name));return`${name}:${stat23.size}:${stat23.mtimeMs}:${stat23.ino}`}catch{return null}}));return throwIfAborted3(signal),parts.filter((part)=>part!==null).join("|")}function cacheProfileKey(input,cacheKey){let key2=canonicalRootKeyLexical(input);profileCacheKeyByInput.delete(key2),profileCacheKeyByInput.set(key2,cacheKey);while(profileCacheKeyByInput.size>_internals195.cacheCapacity){let oldest=profileCacheKeyByInput.keys().next().value;if(oldest===void 0)break;profileCacheKeyByInput.delete(oldest)}}async function directoryFingerprint(dir){try{let stat23=await fs136.promises.stat(dir);if(!stat23.isDirectory())return null;return{directory:dir,dev:stat23.dev,ino:stat23.ino,size:stat23.size,mtimeMs:stat23.mtimeMs,ctimeMs:stat23.ctimeMs}}catch{return null}}function fingerprintsMatch(expected,actual){return expected.dev===actual.dev&&expected.ino===actual.ino&&expected.size===actual.size&&expected.mtimeMs===actual.mtimeMs&&expected.ctimeMs===actual.ctimeMs}async function readDirectoryForManifestWalk(dir){let entries2=await tryReadDirectoryAsync(dir),fingerprint2=await directoryFingerprint(dir),after=await tryReadDirectoryAsync(dir);if(entries2===null||fingerprint2===null||after===null)return{entries:null,complete:!1,stopAtCurrent:!0};if(entries2.size!==after.size||[...entries2].some((entry)=>!after.has(entry)))return{entries:null,complete:!1,stopAtCurrent:!1};return{entries:entries2,fingerprint:fingerprint2,complete:!0}}async function isManifestRootCacheEntryValid(entry){for(let fingerprint2 of entry.trace){let current=await directoryFingerprint(fingerprint2.directory);if(current===null||!fingerprintsMatch(fingerprint2,current))return!1}return!0}async function isSelectedRootObservationStillValid(resolution,hash5,signal){let currentHash=await manifestHash(resolution.root,signal);if(throwIfAborted3(signal),currentHash!==hash5||resolution.rootHadManifest&&currentHash==="")return!1;return!0}function evictManifestRootCacheIfNeeded(){if(manifestRootCache.size<=_internals195.cacheCapacity)return;let oldestKey,oldestOrder=1/0;for(let[key2,value]of manifestRootCache)if(value.insertOrder<oldestOrder)oldestKey=key2,oldestOrder=value.insertOrder;if(oldestKey!==void 0)manifestRootCache.delete(oldestKey)}function cacheManifestRoot(key2,root,rootHadManifest,trace,cacheable,signal){if(!cacheable||signal?.aborted)return;manifestRootCache.set(key2,{root,rootHadManifest,trace,insertOrder:manifestRootInsertCounter++}),evictManifestRootCacheIfNeeded()}function throwIfAborted3(signal){if(signal?.aborted)throw signal.reason??Error("manifest-root lookup aborted")}async function findManifestRoot(start,signal){throwIfAborted3(signal);let resolved=path247.resolve(start),key2=await canonicalRootKeyFreshAsync(resolved);throwIfAborted3(signal);let cached3=manifestRootCache.get(key2);if(cached3!==void 0){if(await isManifestRootCacheEntryValid(cached3))return throwIfAborted3(signal),{root:cached3.root,rootHadManifest:cached3.rootHadManifest,key:key2,trace:[],cacheable:!1};manifestRootCache.delete(key2)}let cur=resolved,trace=[],cacheable=!0;for(let i=0;i<MAX_MANIFEST_SEARCH_DEPTH;i++){let snapshot=await readDirectoryForManifestWalk(cur);if(throwIfAborted3(signal),!snapshot.complete){if(snapshot.stopAtCurrent)return{root:cur,rootHadManifest:!1,key:key2,trace,cacheable:!1};cacheable=!1}else trace.push(snapshot.fingerprint);let{entries:entries2}=snapshot;if(entries2!==null){if(entries2.size>0){for(let name of MANIFEST_FILES)if(entries2.has(name))return{root:cur,rootHadManifest:!0,key:key2,trace,cacheable};if(entries2.has(".git"))return{root:cur,rootHadManifest:!1,key:key2,trace,cacheable}}}let parent=path247.dirname(cur);if(parent===cur)break;cur=parent}return{root:start,rootHadManifest:!1,key:key2,trace,cacheable}}function evictIfNeeded(){if(cache5.size<=_internals195.cacheCapacity)return;let oldestKey,oldestOrder=1/0;for(let[k,v]of cache5.entries())if(v.insertOrder<oldestOrder)oldestOrder=v.insertOrder,oldestKey=k;if(oldestKey!==void 0)cache5.delete(oldestKey)}async function pickBackend(dir,signal){for(let attempt=0;attempt<2;attempt++){let resolution=await findManifestRoot(dir,signal),{root}=resolution;throwIfAborted3(signal);let hash5=await manifestHash(root,signal);if(throwIfAborted3(signal),resolution.rootHadManifest&&hash5===""){if(manifestRootCache.delete(resolution.key),attempt===0)continue;return profileCacheKeyByInput.delete(canonicalRootKeyLexical(dir)),null}let cacheKey=await canonicalRootKeyFreshAsync(root);throwIfAborted3(signal);let cached3=cache5.get(cacheKey);if(cached3&&cached3.hash===hash5)return cacheManifestRoot(resolution.key,root,resolution.rootHadManifest,resolution.trace,resolution.cacheable,signal),cacheProfileKey(dir,cacheKey),cached3.backend;if(hash5==="")return cacheManifestRoot(resolution.key,root,resolution.rootHadManifest,resolution.trace,resolution.cacheable,signal),cache5.set(cacheKey,{hash:hash5,backend:null,profiles:[],insertOrder:insertCounter++}),evictIfNeeded(),cacheProfileKey(dir,cacheKey),null;let profiles=await _internals195.detectProjectLanguages(root);if(throwIfAborted3(signal),!await isSelectedRootObservationStillValid(resolution,hash5,signal)){if(manifestRootCache.delete(resolution.key),attempt===0)continue;return profileCacheKeyByInput.delete(canonicalRootKeyLexical(dir)),null}if(cacheManifestRoot(resolution.key,root,resolution.rootHadManifest,resolution.trace,resolution.cacheable,signal),profiles.length===0)return cache5.set(cacheKey,{hash:hash5,backend:null,profiles:[],insertOrder:insertCounter++}),evictIfNeeded(),cacheProfileKey(dir,cacheKey),null;let winner=profiles[0],backend=LANGUAGE_BACKEND_REGISTRY.getOrDefault(winner.id)??null;return cache5.set(cacheKey,{hash:hash5,backend,profiles:profiles.map((p)=>({id:p.id})),insertOrder:insertCounter++}),evictIfNeeded(),cacheProfileKey(dir,cacheKey),backend}return null}function pickedProfiles(dir){let cacheKey=profileCacheKeyByInput.get(canonicalRootKeyLexical(dir));if(cacheKey===void 0)return[];return cache5.get(cacheKey)?.profiles??[]}function clearDispatchCache(){cache5.clear(),manifestRootCache.clear(),profileCacheKeyByInput.clear(),insertCounter=0,manifestRootInsertCounter=0}var _internals195,cache5,insertCounter=0,MAX_MANIFEST_SEARCH_DEPTH=32,manifestRootCache,manifestRootInsertCounter=0,profileCacheKeyByInput;var init_dispatch=__esm(()=>{init_backends();init_canonical_root();init_detector();init_manifest_files();init_registry_backend();_internals195={detectProjectLanguages,cacheCapacity:64,get manifestRootCacheSize(){return manifestRootCache.size}},cache5=new Map;manifestRootCache=new Map,profileCacheKeyByInput=new Map});import*as fs137 from"node:fs";import*as path248 from"node:path";async function estimateFanOut(sourceFiles,cwd){try{let impactMap=await _internals196.loadImpactMap(cwd,{skipRebuild:!0}),uniqueTestFiles=new Set;for(let sourceFile of sourceFiles){let normalizedPath=path248.resolve(cwd,sourceFile).replace(/\\/g,"/"),testFiles=impactMap[normalizedPath];if(testFiles)for(let testFile of testFiles){let normalized=testFile.replace(/\\/g,"/");uniqueTestFiles.add(process.platform==="win32"?normalized.toLowerCase():normalized)}}return{estimatedCount:uniqueTestFiles.size,status:"advisory"}}catch{return{estimatedCount:0,status:"unavailable"}}}function normalizeSelectionFiles(files,workingDir){let seen=new Set,normalized=[];for(let file3 of files){let absolute=path248.resolve(workingDir,file3),relative57=path248.relative(workingDir,absolute),output=(path248.isAbsolute(relative57)?absolute:relative57).replace(/\\/g,"/"),key2=process.platform==="win32"?output.toLowerCase():output;if(!seen.has(key2))seen.add(key2),normalized.push(output)}return normalized}function makeResolution(requestedScope,effectiveScope,sourceFiles,resolvedFiles,decision,workingDir,options){let estimateCount=options?.estimate?.estimatedCount??0,estimateStatus=options?.estimate?.status??"not_run",fallbackReason=options?.fallbackReason??(options?.cacheStatus?.startsWith("rebuilt_")?`impact cache rebuild completed (${options.cacheStatus}) before resolution`:null);return{requestedScope,effectiveScope,sourceFiles:normalizeSelectionFiles(sourceFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1),resolvedFiles:normalizeSelectionFiles(resolvedFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1),cap:MAX_SAFE_TEST_FILES2,decision,estimate:{count:estimateCount,status:estimateStatus},estimateCount,estimateStatus,...options?.cacheStatus&&{cacheStatus:options.cacheStatus},fallbackReason,evaluable:decision==="execute"}}function resolutionFields(resolution){return{resolved_test_files:resolution.resolvedFiles,cap_decision:{decision:resolution.decision==="scope_exceeded"?"cap_exceeded":"within_cap",resolved_test_count:resolution.resolvedFiles.length,limit:resolution.cap},...resolution.fallbackReason?{fallback_reason:resolution.fallbackReason}:{}}}function cacheStatusAfterRebuild(before,after){let normalize25=(status2)=>status2.endsWith("_unverified")?status2.slice(0,-11):status2,beforeState=normalize25(before),afterState=normalize25(after);if(afterState==="fresh"){if(beforeState==="missing"||beforeState==="corrupt"||beforeState==="legacy"||beforeState==="stale")return`rebuilt_${beforeState}`}return afterState===beforeState?afterState:after}async function loadImpactMapForImpactScope(workingDir){if(_internals196.loadImpactMap!==DEFAULT_LOAD_IMPACT_MAP){let before=getImpactCacheStatus(workingDir,{verify:!1}).status,map3=await _internals196.loadImpactMap(workingDir),after=getImpactCacheStatus(workingDir,{verify:!1}).status;return{map:map3,status:cacheStatusAfterRebuild(before,after)}}return _internals196.loadImpactMapWithStatus(workingDir)}function cacheStatusForAdvisory(status2){if(status2==="missing")return"missing_unverified";if(status2==="corrupt")return"corrupt_unverified";if(status2==="legacy")return"legacy_unverified";return status2}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 containsShellMetacharacters(str){return SHELL_METACHARACTERS2.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"&&obj.scope!=="target")return!1}if(obj.native_target!==void 0){if(typeof obj.native_target!=="object"||obj.native_target===null)return!1;let target=obj.native_target;if(target.framework!=="go-test"&&target.framework!=="ctest")return!1;if(typeof target.name!=="string"||typeof target.path!=="string")return!1;if(target.name.length===0||target.name.length>256)return!1;if(target.path.length===0||target.path.length>1024)return!1;if(containsControlChars(target.name)||containsControlChars(target.path))return!1;if(target.framework==="go-test"&&target.name.split("/").some((p)=>!p))return!1;if(isAbsolutePath(target.path)||containsPathTraversal(target.path))return!1}if(obj.scope==="target"){if(obj.native_target===void 0)return!1;if(Array.isArray(obj.files)&&obj.files.length>0)return!1;if(obj.coverage===!0||obj.bail===!0)return!1}else if(obj.native_target!==void 0)return!1;if(obj.files!==void 0){if(!Array.isArray(obj.files))return!1;if(obj.files.length>MAX_RAW_FILE_ENTRIES)return!1;for(let f of obj.files){if(typeof f!=="string")return!1;if(f.length===0||f.length>MAX_FILE_PATH_LENGTH2)return!1;if(isAbsolutePath(f))return!1;if(containsPathTraversal(f))return!1;if(containsControlChars(f))return!1;if(containsPowerShellMetacharacters(f))return!1}}if(obj.targets!==void 0){if(!Array.isArray(obj.targets))return!1;for(let t of obj.targets){if(typeof t!=="string")return!1;if(t.length===0)return!1;if(isAbsolutePath(t))return!1;if(containsPathTraversal(t))return!1;if(containsControlChars(t))return!1;if(containsShellMetacharacters(t))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_MS3)return!1}return!0}function validateNativeTargetInput(target){if(target.framework!=="go-test"&&target.framework!=="ctest")return'Native target framework must be "go-test" or "ctest"';if(typeof target.name!=="string"||target.name.length===0||target.name.length>256)return"Native target name must be a non-empty string up to 256 characters";if(typeof target.path!=="string"||target.path.length===0||target.path.length>1024)return"Native target path must be a non-empty string up to 1024 characters";if(containsControlChars(target.name)||containsControlChars(target.path))return"Native target values must not contain control characters";if(target.framework==="go-test"&&target.name.split("/").some((p)=>!p))return"Go native target name must not contain empty slash-separated segments";if(isAbsolutePath(target.path))return"Native target path must be workspace-relative, not absolute";if(containsPathTraversal(target.path))return"Native target path escapes project root";return}function resolveNativeTarget(target,workingDir){let rootReal,targetReal;try{if(rootReal=fs137.realpathSync(workingDir),targetReal=fs137.realpathSync(path248.resolve(rootReal,target.path)),!fs137.statSync(targetReal).isDirectory())return{success:!1,error:"Native target path must be a directory"}}catch{return{success:!1,error:"Native target path does not exist"}}let relative57=path248.relative(rootReal,targetReal);if(relative57.startsWith("..")||path248.isAbsolute(relative57))return{success:!1,error:"Native target path escapes project root"};if(!_internals196.isCommandAvailable(target.framework==="go-test"?"go":"ctest"))return{success:!1,error:`Native target framework "${target.framework}" is unavailable`};let executionDirectory=rootReal,commandRelative=relative57;if(target.framework==="go-test"){let hasRootWorkspace=fs137.existsSync(path248.join(rootReal,"go.work")),moduleRoot;for(let current=targetReal;;current=path248.dirname(current)){if(fs137.existsSync(path248.join(current,"go.mod"))){moduleRoot=current;break}if(current===rootReal)break;let parent=path248.dirname(current);if(parent===current||path248.relative(rootReal,parent).startsWith(".."))break}if(!hasRootWorkspace&&!moduleRoot)return{success:!1,error:"Go native target requires an enclosing go.mod or go.work at the project root"};if(!hasRootWorkspace&&moduleRoot)executionDirectory=moduleRoot,commandRelative=path248.relative(moduleRoot,targetReal)}else if(!fs137.existsSync(path248.join(targetReal,"CMakeCache.txt")))return{success:!1,error:"CTest native target requires CMakeCache.txt in the target directory"};return{success:!0,target:{...target,path:commandRelative.length===0?".":commandRelative.replace(/\\/g,"/")},executionDirectory,historyPath:relative57.length===0?".":relative57.replace(/\\/g,"/")}}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 _internals196.existsSync(path248.join(cwd,"go.mod"))&&_internals196.isCommandAvailable("go")}function detectJavaMaven(cwd){return _internals196.existsSync(path248.join(cwd,"pom.xml"))&&_internals196.isCommandAvailable("mvn")}function detectGradle(cwd){let hasBuildFile=_internals196.existsSync(path248.join(cwd,"build.gradle"))||_internals196.existsSync(path248.join(cwd,"build.gradle.kts")),hasGradlew=_internals196.existsSync(path248.join(cwd,"gradlew"))||_internals196.existsSync(path248.join(cwd,"gradlew.bat"));return hasBuildFile&&(hasGradlew||_internals196.isCommandAvailable("gradle"))}function detectDotnetTest(cwd){try{return _internals196.readdirSync(cwd).some((f)=>f.endsWith(".csproj"))&&_internals196.isCommandAvailable("dotnet")}catch{return!1}}function detectCTest(cwd){let hasSource=_internals196.existsSync(path248.join(cwd,"CMakeLists.txt")),hasBuildCache=_internals196.existsSync(path248.join(cwd,"CMakeCache.txt"))||_internals196.existsSync(path248.join(cwd,"build","CMakeCache.txt"));return(hasSource||hasBuildCache)&&_internals196.isCommandAvailable("ctest")}function detectSwiftTest(cwd){return _internals196.existsSync(path248.join(cwd,"Package.swift"))&&_internals196.isCommandAvailable("swift")}function detectDartTest(cwd){return _internals196.existsSync(path248.join(cwd,"pubspec.yaml"))&&(_internals196.isCommandAvailable("dart")||_internals196.isCommandAvailable("flutter"))}function detectRSpec(cwd){let hasRSpecFile=_internals196.existsSync(path248.join(cwd,".rspec")),hasGemfile=_internals196.existsSync(path248.join(cwd,"Gemfile")),hasSpecDir=_internals196.existsSync(path248.join(cwd,"spec"));return(hasRSpecFile||hasGemfile&&hasSpecDir)&&(_internals196.isCommandAvailable("bundle")||_internals196.isCommandAvailable("rspec"))}function detectMinitest(cwd){return _internals196.existsSync(path248.join(cwd,"test"))&&(_internals196.existsSync(path248.join(cwd,"Gemfile"))||_internals196.existsSync(path248.join(cwd,"Rakefile")))&&_internals196.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,targets,nativeTarget){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,targets,nativeTarget});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}}function relativeEscapesRoot(relative57){return relative57===".."||relative57.startsWith(`..${path248.sep}`)||path248.isAbsolute(relative57)}function resolveMavenModuleDir(root,files){let resolvedRoot=path248.resolve(root),rootReal,isContainedModuleDir=(dir)=>{if(rootReal===void 0)try{rootReal=_internals196.realpathSync(resolvedRoot)}catch{rootReal=null}if(rootReal===null)return!1;let dirReal;try{dirReal=_internals196.realpathSync(dir)}catch{return!1}return!relativeEscapesRoot(path248.relative(rootReal,dirReal))};if(files&&files.length>0){for(let file3 of files){let resolvedFile=path248.resolve(resolvedRoot,file3),relativeToRoot=path248.relative(resolvedRoot,resolvedFile);if(relativeEscapesRoot(relativeToRoot))continue;let current=path248.dirname(resolvedFile);while(!0){if(_internals196.existsSync(path248.join(current,"pom.xml"))&&isContainedModuleDir(current))return current;if(current===resolvedRoot)break;let parent=path248.dirname(current);if(parent===current)break;if(relativeEscapesRoot(path248.relative(resolvedRoot,parent)))break;current=parent}}return null}let entries2;try{entries2=_internals196.readdirSync(resolvedRoot)}catch{return null}entries2.sort((a,b)=>a.localeCompare(b));let inspected=0;for(let entry of entries2){if(entry.startsWith(".")||entry==="node_modules")continue;if(inspected>=MAX_MAVEN_MODULE_PROBE_ENTRIES)break;inspected++;let candidate2=path248.join(resolvedRoot,entry);if(_internals196.existsSync(path248.join(candidate2,"pom.xml"))&&isContainedModuleDir(candidate2))return candidate2}return null}function resolveNestedMavenModuleDir(root,files){if(_internals196.existsSync(path248.join(root,"pom.xml")))return null;return resolveMavenModuleDir(root,files)}async function detectTestFramework(cwd,files){let baseDir=cwd;try{let packageJsonPath=path248.join(baseDir,"package.json");if(_internals196.existsSync(packageJsonPath)){let content=_internals196.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(_internals196.existsSync(path248.join(baseDir,"bun.lockb"))||_internals196.existsSync(path248.join(baseDir,"bun.lock"))){if(scripts.test?.includes("bun"))return"bun"}}}catch{}try{let pyprojectTomlPath=path248.join(baseDir,"pyproject.toml"),setupCfgPath=path248.join(baseDir,"setup.cfg"),requirementsTxtPath=path248.join(baseDir,"requirements.txt");if(_internals196.existsSync(pyprojectTomlPath)){let content=_internals196.readFileSync(pyprojectTomlPath,"utf-8");if(content.includes("[tool.pytest"))return"pytest";if(content.includes("pytest"))return"pytest"}if(_internals196.existsSync(setupCfgPath)){if(_internals196.readFileSync(setupCfgPath,"utf-8").includes("[pytest]"))return"pytest"}if(_internals196.existsSync(requirementsTxtPath)){if(_internals196.readFileSync(requirementsTxtPath,"utf-8").includes("pytest"))return"pytest"}}catch{}try{let cargoTomlPath=path248.join(baseDir,"Cargo.toml");if(_internals196.existsSync(cargoTomlPath)){let content=_internals196.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=path248.join(baseDir,"pester.config.ps1"),pesterConfigJsonPath=path248.join(baseDir,"pester.config.ps1.json"),pesterPs1Path=path248.join(baseDir,"tests.ps1");if(_internals196.existsSync(pesterConfigPath)||_internals196.existsSync(pesterConfigJsonPath)||_internals196.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";let mavenModuleDir=resolveNestedMavenModuleDir(baseDir,files);if(mavenModuleDir&&(_internals196.isCommandAvailable("mvn")||resolveMavenWrapperCommand(mavenModuleDir,["test"])!==null))return"maven";return"none"}function detectPhpTest(cwd){if(_internals196.existsSync(path248.join(cwd,"artisan"))&&_internals196.existsSync(path248.join(cwd,"composer.json")))return"php-artisan";if(_internals196.existsSync(path248.join(cwd,"Pest.php")))return"pest";if(_internals196.existsSync(path248.join(cwd,"phpunit.xml"))||_internals196.existsSync(path248.join(cwd,"phpunit.xml.dist")))return"phpunit";return null}function isTestDirectoryPath(normalizedPath){return normalizedPath.split("/").some((segment)=>TEST_DIRECTORY_NAMES.includes(segment))}function resolveWorkspacePath(file3,workingDir){return path248.isAbsolute(file3)?path248.resolve(file3):path248.resolve(workingDir,file3)}function toWorkspaceOutputPath(absolutePath2,workingDir,preferRelative){if(!preferRelative)return absolutePath2;return path248.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=path248.dirname(relativePath2),nestedRelativeDir=relativeDir==="."?"":relativeDir,directories=TEST_DIRECTORY_NAMES.flatMap((dirName)=>{let rootDir2=path248.join(workingDir,dirName);return nestedRelativeDir?[rootDir2,path248.join(rootDir2,nestedRelativeDir)]:[rootDir2]}),normalizedRelativePath=relativePath2.replace(/\\/g,"/");if(ext===".java"&&normalizedRelativePath.startsWith("src/main/java/"))directories.push(path248.join(workingDir,"src/test/java",path248.dirname(normalizedRelativePath.slice(14))));if((ext===".kt"||ext===".java")&&normalizedRelativePath.startsWith("src/main/kotlin/"))directories.push(path248.join(workingDir,"src/test/kotlin",path248.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(basename45){let lower=basename45.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(basename45)||basename45.endsWith("Test.java")||basename45.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(basename45)||lower.endsWith("test.kt")||lower.endsWith("tests.kt")))return!0;if(lower.endsWith(".php")&&(/^Test[A-Z]/.test(basename45)||basename45.endsWith("Test.php")||basename45.endsWith("Tests.php")))return!0;if(lower.endsWith(".tests.ps1"))return!0;return!1}function isConventionTestFilePath(filePath){let normalizedPath=filePath.replace(/\\/g,"/"),basename45=path248.basename(filePath);return hasCompoundTestExtension(basename45)||basename45.includes(".spec.")||basename45.includes(".test.")||isLanguageSpecificTestFile(basename45)||isTestDirectoryPath(normalizedPath)}function getTestFilesFromConvention(sourceFiles,workingDir=process.cwd()){let testFiles=[];for(let file3 of sourceFiles){let absoluteFile=resolveWorkspacePath(file3,workingDir),relativeFile=path248.relative(workingDir,absoluteFile),basename45=path248.basename(absoluteFile),dirname99=path248.dirname(absoluteFile),preferRelativeOutput=!path248.isAbsolute(file3);if(isConventionTestFilePath(relativeFile)||isConventionTestFilePath(file3)){dedupePush(testFiles,toWorkspaceOutputPath(absoluteFile,workingDir,preferRelativeOutput));continue}let nameWithoutExt=basename45.replace(/\.[^.]+$/,""),ext=path248.extname(basename45),genericTestNames=[`${nameWithoutExt}.spec${ext}`,`${nameWithoutExt}.test${ext}`],languageSpecificTestNames=buildLanguageSpecificTestNames(nameWithoutExt,ext),colocatedCandidates=[...genericTestNames,...languageSpecificTestNames].map((candidateName)=>path248.join(dirname99,candidateName)),testDirectoryNames=[basename45,...genericTestNames,...languageSpecificTestNames],repoLevelDirectories=getRepoLevelCandidateDirectories(workingDir,relativeFile,ext),possibleTestFiles=[...colocatedCandidates,...TEST_DIRECTORY_NAMES.flatMap((dirName)=>testDirectoryNames.map((candidateName)=>path248.join(dirname99,dirName,candidateName))),...repoLevelDirectories.flatMap((candidateDir3)=>testDirectoryNames.map((candidateName)=>path248.join(candidateDir3,candidateName)))];for(let testFile of possibleTestFiles)if(fs137.existsSync(testFile))dedupePush(testFiles,toWorkspaceOutputPath(testFile,workingDir,preferRelativeOutput))}return testFiles}async function getTestFilesFromGraph(sourceFiles,workingDir,maxFiles=MAX_SAFE_TEST_FILES2+1){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);if(fs137.statSync(absoluteTestFile).size>MAX_GRAPH_FILE_BYTES)continue;let content=fs137.readFileSync(absoluteTestFile,"utf-8");if(Buffer.byteLength(content,"utf8")>MAX_GRAPH_FILE_BYTES)continue;let testDir=path248.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=path248.resolve(testDir,importPath),!path248.extname(resolvedImport))for(let extToTry of[".ts",".tsx",".js",".jsx",".mjs",".cjs"]){let withExt=resolvedImport+extToTry;if(absoluteSourceFiles.includes(withExt)||fs137.existsSync(withExt)){resolvedImport=withExt;break}}}else{let nextIndex=match.index+Math.max(match[0].length,1);if(importRegex.lastIndex<=match.index)importRegex.lastIndex=nextIndex;match=importRegex.exec(content);continue}let importBasename=path248.basename(resolvedImport,path248.extname(resolvedImport)),importDir=path248.dirname(resolvedImport);for(let sourceFile of absoluteSourceFiles){let sourceDir=path248.dirname(sourceFile),sourceBasename=path248.basename(sourceFile,path248.extname(sourceFile)),isRelatedDir=importDir===sourceDir||importDir===path248.join(sourceDir,"__tests__")||importDir===path248.join(sourceDir,"tests")||importDir===path248.join(sourceDir,"test")||importDir===path248.join(sourceDir,"spec");if(resolvedImport===sourceFile||importBasename===sourceBasename&&isRelatedDir){if(dedupePush(testFiles,testFile),testFiles.length>=maxFiles)return testFiles;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=path248.resolve(testDir,importPath);if(!path248.extname(resolvedImport))for(let extToTry of[".ts",".tsx",".js",".jsx",".mjs",".cjs"]){let withExt=resolvedImport+extToTry;if(absoluteSourceFiles.includes(withExt)||fs137.existsSync(withExt)){resolvedImport=withExt;break}}let importDir=path248.dirname(resolvedImport),importBasename=path248.basename(resolvedImport,path248.extname(resolvedImport));for(let sourceFile of absoluteSourceFiles){let sourceDir=path248.dirname(sourceFile),sourceBasename=path248.basename(sourceFile,path248.extname(sourceFile)),isRelatedDir=importDir===sourceDir||importDir===path248.join(sourceDir,"__tests__")||importDir===path248.join(sourceDir,"tests")||importDir===path248.join(sourceDir,"test")||importDir===path248.join(sourceDir,"spec");if(resolvedImport===sourceFile||importBasename===sourceBasename&&isRelatedDir){if(dedupePush(testFiles,testFile),testFiles.length>=maxFiles)return testFiles;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 buildTestCommand3(framework,scope,files,coverage,baseDir,bail,targets,nativeTarget){if(nativeTarget)return nativeTarget.framework===framework?buildNativeTargetCommand(nativeTarget):null;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=_internals196.resolveLocalNodeTool("vitest",["run","--reporter=json","--outputFile",VITEST_JSON_OUTPUT_RELATIVE_PATH],baseDir,process.platform,_internals196.isCommandAvailable);if(!args2)return null;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=_internals196.resolveLocalNodeTool("jest",["--json"],baseDir,process.platform,_internals196.isCommandAvailable);if(!args2)return null;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=_internals196.resolveLocalNodeTool("mocha",[],baseDir,process.platform,_internals196.isCommandAvailable);if(!args2)return null;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(targets&&targets.length>0)args2.push("--",...targets);else 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":{let args2=["go","test"];if(targets&&targets.length>0)args2.push("-run",targets.join("|"));return args2.push("./..."),args2}case"maven":return buildMavenTestCommand(baseDir,targets);case"gradle":return buildGradleTestCommand(baseDir,targets);case"dotnet-test":{let args2=["dotnet","test"];if(targets&&targets.length>0)args2.push("--filter",targets.join("|"));return args2}case"ctest":{let args2=["ctest","--test-dir",["build","_build","cmake-build-debug","cmake-build-release","out"].find((d)=>fs137.existsSync(path248.join(baseDir,d,"CMakeCache.txt")))??"build"];if(targets&&targets.length>0)args2.push("-R",targets.join("|"));return args2}case"swift-test":{let args2=["swift","test"];if(targets&&targets.length>0)for(let target of targets)args2.push("--filter",target);return args2}case"dart-test":return _internals196.isCommandAvailable("flutter")?["flutter","test",...files]:["dart","test",...files];case"rspec":{let args2=_internals196.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":return buildPhpVendorCommand(baseDir,"pest",scope!=="all"&&files.length>0?files:[]);case"phpunit":return buildPhpVendorCommand(baseDir,"phpunit",scope!=="all"&&files.length>0?files:[]);case"php-artisan":{let args2=["php","artisan","test"];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}default:return null}}function mapFrameworkStatusToResult(status2){if(typeof status2!=="string")return null;let normalized=status2.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(`
4072
4072
  `).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(`
4073
4073
  `)){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(`
4074
4074
  `)){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 disabledCount=[...output.matchAll(/\*{3}Not Run\s+\(Disabled\)/gi)].length;totals.skipped=disabledCount;let ctestMatch=output.match(/(\d+) tests? failed out of (\d+)/);if(ctestMatch){totals.failed=parseInt(ctestMatch[1],10);let executedTotal=parseInt(ctestMatch[2],10);totals.total=executedTotal+disabledCount,totals.passed=executedTotal-totals.failed}else{let allPassMatch=output.match(/100% tests passed.*?(\d+) tests?/);if(allPassMatch){let executedTotal=parseInt(allPassMatch[1],10);totals.total=executedTotal+disabledCount,totals.passed=executedTotal}else if(disabledCount>0)totals.total=disabledCount}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 readBoundedStream2(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}}function formatPassingMessage(framework,totals,coveragePercent){let message=totals.total>0&&totals.passed===0&&totals.failed===0&&totals.skipped===totals.total?`${framework} tests completed with ${totals.skipped} skipped (${totals.total} total)`:`${framework} tests passed (${totals.passed}/${totals.total})`;if(coveragePercent!==void 0)message+=` with ${coveragePercent}% coverage`;return message}function formatNativeHistoryTestFile(target,historyPath){return`native:${target.framework}:path=${encodeURIComponent(historyPath)}#name=${encodeURIComponent(target.name)}`}async function runTests(framework,scope,files,coverage,timeout_ms,cwd,bail,targets,nativeTarget){let executionCwd=cwd,resolvedNativeTarget=nativeTarget;if(scope==="target"&&!nativeTarget||scope!=="target"&&nativeTarget!==void 0||nativeTarget!==void 0&&nativeTarget.framework!==framework)return{success:!1,framework,scope,error:"Invalid native target pairing; refusing broad test fallback",message:'scope "target" requires one matching native target, and native targets are not valid with other scopes.',outcome:"error"};if(scope==="target"){if(files.length>0||coverage||bail)return{success:!1,framework,scope,error:'scope "target" cannot be combined with files, coverage, or bail',message:"Native target mode runs one exact framework-native name only. Omit files and leave coverage and bail disabled.",outcome:"error"};let nativeTargetError=validateNativeTargetInput(nativeTarget);if(nativeTargetError)return{success:!1,framework,scope,error:nativeTargetError,outcome:"error"};let resolvedTarget=resolveNativeTarget(nativeTarget,cwd);if(!resolvedTarget.success)return{success:!1,framework,scope,error:resolvedTarget.error,outcome:"error"};resolvedNativeTarget=resolvedTarget.target,executionCwd=resolvedTarget.executionDirectory}if(scope!=="all"&&scope!=="target"&&files.length>0&&!(targets&&targets.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,executionCwd,bail,targets,resolvedNativeTarget)??buildTestCommand3(framework,scope,files,coverage,executionCwd,bail,targets,resolvedNativeTarget):buildTestCommand3(framework,scope,files,coverage,executionCwd,bail,targets,resolvedNativeTarget);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"?path248.join(executionCwd,".swarm","cache","test-runner-vitest.json"):void 0,proc,timeoutHandle,timedOutByDeadline=!1;try{if(vitestJsonOutputPath)try{if(fs137.mkdirSync(path248.dirname(vitestJsonOutputPath),{recursive:!0}),fs137.existsSync(vitestJsonOutputPath))fs137.unlinkSync(vitestJsonOutputPath)}catch{}let timeoutPromise=new Promise((resolve97)=>{timeoutHandle=setTimeout(()=>{resolve97({kind:"timeout"})},timeout_ms)});proc=_internals196.bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:executionCwd,timeout:timeout_ms,killProcessTree:!0,...isWindowsCommandInterpreterLaunch(command)?{windowsVerbatimArguments:!0}:{}});let stdoutPromise=readBoundedStream2(proc.stdout,MAX_OUTPUT_BYTES5),stderrPromise=readBoundedStream2(proc.stderr,MAX_OUTPUT_BYTES5),raceResult=await Promise.race([proc.exited.then((exitCode2)=>({kind:"exit",exitCode:exitCode2})),timeoutPromise]);if(timedOutByDeadline=raceResult.kind==="timeout",timeoutHandle!==void 0)clearTimeout(timeoutHandle),timeoutHandle=void 0;let[stdoutResult,stderrResult]=await Promise.all([stdoutPromise,stderrPromise]),exitCode=raceResult.kind==="timeout"?-1:raceResult.exitCode,duration_ms=Date.now()-startTime,output=stdoutResult.text;if(stderrResult.text)output+=(output?`
@@ -7496,7 +7496,7 @@ OR
7496
7496
 
7497
7497
  VERDICT: REJECTED
7498
7498
  REASON: [critical blocking issues]`,result=await activeDispatcher.dispatch({directory,parentSessionId,agentName,model,system,prompt,title:parentSessionId?"lean_turbo_reviewer background":void 0,timeoutMs});if(result.status==="completed")return result.text;if(result.status==="timeout"){let timeoutDescription=timeoutMs>0?`${timeoutMs}ms`:"the bounded default";throw Error(`Reviewer dispatch timed out after ${timeoutDescription}`)}throw Error(result.error??`Reviewer dispatch ${result.status==="cancelled"?"cancelled":"failed"}`)}var _internals251={compileReviewPackage,parseReviewerVerdict,writeReviewerEvidence,dispatchReviewerAgent:defaultDispatchReviewerAgent,resolveDefaultReviewerAgent,listLaneEvidence,readPhaseEvidence,readPersisted:readPersisted3};async function dispatchPhaseReviewer(directory,phase,sessionID,config3){let mergedConfig={...DEFAULT_CONFIG3,...config3},generatedAgentNames=config3?.generatedAgentNames??swarmState.generatedAgentNames,agentName=mergedConfig.reviewerAgent||resolveDefaultReviewerAgent(generatedAgentNames,config3?.activeAgentName),pkg=await _internals251.compileReviewPackage(directory,phase,sessionID,mergedConfig.requireDiffSummary),fallbackModels=reviewFallbackModelStrings(agentName,config3?.agentModelRegistry),legacyModelConfig=resolveLegacyReviewerModelConfig(agentName,config3),responseText;try{responseText=(await dispatchWithModelFallback({dispatch:(model)=>_internals251.dispatchReviewerAgent(directory,pkg,agentName,mergedConfig.timeoutMs,sessionID,model,config3?.dispatcher),resolveFallback:(index)=>config3?.agentModelRegistry?fallbackModels[index-1]??null:legacyModelConfig?resolveFallbackModel(legacyModelConfig.agentBaseName,index,legacyModelConfig.swarmAgents):null,maxTransientRetriesPerModel:0,classify:(err)=>{let msg=err instanceof Error?err.message:String(err);if(/Reviewer dispatch timed out/i.test(msg))return"permanent";return isTransientProviderError(msg)?"transient":"permanent"},onFallback:({toModel,fallbackIndex})=>{telemetry.modelFallback(sessionID,agentName,reviewPrimaryModel(agentName,config3?.agentModelRegistry)??legacyModelConfig?.swarmAgents?.[legacyModelConfig.agentBaseName]?.model??"default",toModel,"transient_model_error");let session=getAgentSession(sessionID);if(session)pushAdvisory(session,`MODEL FALLBACK: reviewer failed over to "${toModel}" (fallback ${fallbackIndex}) after a transient/quota dispatch error.`)}})).result}catch(error93){let isQuota=isQuotaError(error93 instanceof Error?error93.message:String(error93)),evidencePath2=await _internals251.writeReviewerEvidence(directory,phase,"REJECTED",error93 instanceof Error?error93.message:String(error93));return{verdict:"REJECTED",reason:`Reviewer dispatch failed${isQuota?" (model quota/usage limit exhausted across all configured fallbacks)":""}: ${error93 instanceof Error?error93.message:String(error93)}`,evidencePath:evidencePath2}}let parsed=_internals251.parseReviewerVerdict(responseText);if(!parsed)return{verdict:"REJECTED",reason:"Reviewer response could not be parsed",evidencePath:await _internals251.writeReviewerEvidence(directory,phase,"REJECTED","Reviewer response could not be parsed")};let evidencePath=await _internals251.writeReviewerEvidence(directory,phase,parsed.verdict,parsed.reason);return{verdict:parsed.verdict,reason:parsed.reason,evidencePath}}init_create_tool();async function executeLeanTurboReview(args2,dispatcher,generatedAgentNames,agentModelRegistry,activeAgentName){let{directory,phase,sessionID}=args2,requireDiffSummary=!0;try{let{config:config3}=loadPluginConfigWithMeta(directory);if(config3?.turbo?.lean?.integrated_diff_required!==void 0)requireDiffSummary=config3.turbo.lean.integrated_diff_required}catch{}try{let result=await dispatchPhaseReviewer(directory,phase,sessionID,{requireDiffSummary,dispatcher,generatedAgentNames,agentModelRegistry,activeAgentName});return{success:!0,verdict:result.verdict,reason:result.reason,evidencePath:result.evidencePath}}catch(error93){return{success:!1,errors:[error93 instanceof Error?error93.message:String(error93)]}}}function createLeanTurboReviewTool(dispatcher,generatedAgentNames,agentModelRegistry,getActiveAgentName){return createSwarmTool({description:"Dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase. Wraps dispatchPhaseReviewer from src/turbo/lean/reviewer. Returns verdict (APPROVED/NEEDS_REVISION/REJECTED), reason, and evidence path.",args:{directory:exports_external.string().describe("Project root directory"),phase:exports_external.number().int().positive().describe("Phase number being reviewed"),sessionID:exports_external.string().describe("Lean Turbo session ID")},execute:async(args2,_directory2,ctx)=>{let parsed=args2;return JSON.stringify(await executeLeanTurboReview({...parsed,directory:_directory2},dispatcher,generatedAgentNames,agentModelRegistry,ctx?.agent!==void 0?String(ctx.agent):getActiveAgentName?.(ctx?.sessionID??parsed.sessionID)),null,2)}})}var lean_turbo_review=createLeanTurboReviewTool();init_zod();init_config();init_swarm_branch();init_state2();init_agents2();init_constants();init_schema();init_state3();init_file_locks();init_lane_owners();init_manager();init_utils3();init_state2();init_telemetry();init_ephemeral_session_teardown();init_logger();init_model_dispatch_fallback();init_provider_error_classification();init_manager();init_scope_binding();init_scope_persistence();init_state2();var LEAN_TURBO_LANE_DISPATCH_PREFIX="lean-turbo-lane";function deriveLeanTurboLaneDispatchCallId(input){return`${LEAN_TURBO_LANE_DISPATCH_PREFIX}:${input.parentSessionId}:${input.laneId}:${input.childSessionId}`}function normalizeOne(file3){let normalized=normalizeScopeFiles([file3]);return normalized?normalized[0]??null:null}function resolveLeanTurboLaneAuthorityFiles(plan,lane){let laneTaskIds=new Set(lane.taskIds);if(laneTaskIds.size===0)return null;let planAuthority=[];for(let phase of plan.phases)for(let task2 of phase.tasks){if(!laneTaskIds.has(task2.id))continue;for(let file3 of task2.files_touched??[]){let normalized=normalizeOne(file3);if(normalized)planAuthority.push(normalized)}}if(planAuthority.length===0)return null;let authorized=new Set;for(let file3 of lane.files){let normalized=normalizeOne(file3);if(!normalized)continue;if(scopeContains(planAuthority,normalized))authorized.add(normalized)}if(authorized.size===0)return null;return normalizeScopeFiles([...authorized])}async function publishLeanTurboLaneScopeBinding(input){let parentSessionId=input.parentSessionId.trim(),childSessionId=input.childSessionId.trim();if(!parentSessionId||!childSessionId||parentSessionId===childSessionId)return null;let taskId=input.lane.taskIds[0];if(!taskId)return null;let files=resolveLeanTurboLaneAuthorityFiles(input.plan,input.lane);if(!files)return null;let dispatchCallId=deriveLeanTurboLaneDispatchCallId({parentSessionId,laneId:input.lane.laneId,childSessionId}),parentBinding=createScopeBinding({directory:input.primaryDirectory,plan:input.plan,taskId,files,ownerSessionId:parentSessionId,ownerMessageId:dispatchCallId,source:"plan",dispatchCallId,activation:"pending_child"});if(!parentBinding)return null;if(input.isolated)await savePlan(input.laneRoot,input.plan,{preserveCompletedStatuses:!1});let derivedBinding=deriveChildScopeBinding(parentBinding,{childDirectory:input.laneRoot,childSessionId,parentCallId:dispatchCallId}),published=await persistAndRegisterScopeBinding(input.laneRoot,derivedBinding);if(!published.ok)return null;let childBinding=published.value,childSession=ensureAgentSession(childSessionId,"coder",input.laneRoot);if(childSession.currentTaskId=childBinding.taskId,childSession.declaredCoderScope=[...childBinding.files],input.isolated)recordSessionWorkspaceRoot(childSessionId,input.laneRoot);return childBinding}init_merge2();function getMergeStrategy2(config3){return getMergeStrategy({merge_strategy:config3.merge_strategy})}init_conflicts();init_logger();init_conflicts();import*as path309 from"node:path";init_conflicts();function assessTaskRisk(files,hasDeclaredScope,hasInvalidScope,config3){let globalFiles=files.filter(isGlobalFile);if(globalFiles.length>0)return{category:"global",reason:"global file conflict",files:globalFiles};let protectedFiles=files.filter(isProtectedPath2);if(protectedFiles.length>0)return{category:"protected",reason:"protected path",files:protectedFiles};if(hasInvalidScope)return{category:"invalid-scope",reason:"invalid scope entries",files};if(!hasDeclaredScope&&config3.require_declared_scope)return{category:"no-scope",reason:"undeclared scope",files};return{category:"normal",files:[]}}function getValidatedFiles(files,directory){let validFiles=[],invalidCount=0;for(let file3 of files){let pathToCheck;if(file3.startsWith("/")||file3.match(/^[a-zA-Z]:/))pathToCheck=file3;else pathToCheck=`${directory}/${file3}`;if(!isPathSafe(pathToCheck)){invalidCount++;continue}let relativePath2=path309.relative(path309.resolve(directory),path309.resolve(pathToCheck));if(!relativePath2||!isPathSafe(relativePath2)||path309.isAbsolute(relativePath2)){invalidCount++;continue}validFiles.push(normalizePath(relativePath2))}return[validFiles,invalidCount]}function runPartitionPreflight(directory,pendingTasks,config3,scopes){let tasksWithScopes=[];for(let task2 of pendingTasks){let files=[],hasDeclaredScope=!1;if(scopes&&task2.id in scopes)files=scopes[task2.id],hasDeclaredScope=!0;else{let scopeFiles=readTaskScopes(directory,task2.id);if(scopeFiles!==null)files=scopeFiles,hasDeclaredScope=!0}if(hasDeclaredScope&&files.length===0)hasDeclaredScope=!1;if(!hasDeclaredScope&&!config3.require_declared_scope)files=task2.files_touched??[],hasDeclaredScope=!1;if(files.length===0&&!hasDeclaredScope){tasksWithScopes.push({task:task2,files:[],hasDeclaredScope:!1,hasInvalidScope:!0});continue}let[validFiles,invalidCount]=getValidatedFiles(files,directory),hasInvalidScope=invalidCount>0;tasksWithScopes.push({task:task2,files:validFiles,hasDeclaredScope,hasInvalidScope})}let classifiedTasks=[];for(let tws of tasksWithScopes){let assessment=assessTaskRisk(tws.files,tws.hasDeclaredScope,tws.hasInvalidScope,config3);classifiedTasks.push({task:tws.task,files:tws.files,hasDeclaredScope:tws.hasDeclaredScope,category:assessment.category,conflictReason:assessment.reason})}let taskMap=new Map,duplicateIds=[];for(let ct of classifiedTasks){if(taskMap.has(ct.task.id)){duplicateIds.push(ct.task.id);continue}taskMap.set(ct.task.id,ct)}if(duplicateIds.length>0)criticalWarn(`[partition-common] plan.json has duplicate task id(s): ${Array.from(new Set(duplicateIds)).join(", ")}. The first occurrence wins; later duplicates are dropped from planning. Fix the plan file to avoid silent task loss.`);let inDegree=new Map,adjacency=new Map;for(let ct of taskMap.values())inDegree.set(ct.task.id,0),adjacency.set(ct.task.id,[]);for(let ct of taskMap.values()){let deps=ct.task.depends??[];for(let dep of deps)if(taskMap.has(dep))adjacency.get(dep).push(ct.task.id),inDegree.set(ct.task.id,(inDegree.get(ct.task.id)??0)+1)}let sortedTasks=[],tasksInCycle=new Set,queue=[];for(let[taskId,degree]of inDegree)if(degree===0)queue.push(taskId);queue.sort((a,b)=>a.localeCompare(b));while(queue.length>0){let current=queue.shift(),task2=taskMap.get(current);sortedTasks.push(task2);for(let neighbor of adjacency.get(current)??[]){let newDegree=(inDegree.get(neighbor)??0)-1;if(inDegree.set(neighbor,newDegree),newDegree===0){let insertIdx=queue.findIndex((id)=>id.localeCompare(neighbor)>0);if(insertIdx===-1)queue.push(neighbor);else queue.splice(insertIdx,0,neighbor)}}}for(let[taskId,degree]of inDegree)if(degree>0)tasksInCycle.add(taskId);return{sortedTasks,taskMap,tasksInCycle}}function makeDependencySatisfactionChecker(taskMap,assignedTasks,isUpstreamCommitted){return(task2)=>{let deps=task2.task.depends??[];for(let dep of deps)if(taskMap.has(dep)){if(!assignedTasks.has(dep))return!1}else if(isUpstreamCommitted&&!isUpstreamCommitted(dep))return!1;return!0}}function getReadyTasks(sortedTasks,assignedTasks,isSatisfied){let ready=[];for(let classified of sortedTasks)if(!assignedTasks.has(classified.task.id)&&isSatisfied(classified))ready.push(classified);return ready.sort((a,b)=>a.task.id.localeCompare(b.task.id)),ready}init_conflicts();function planLeanTurboLanes(directory,phaseNumber,plan,config3,scopes,isUpstreamCommitted){let phase=plan.phases.find((p)=>p.id===phaseNumber);if(!phase)return createEmptyPlan(phaseNumber,"");let pendingTasks=phase.tasks.filter((t)=>t.status!=="completed");if(pendingTasks.length===0)return createEmptyPlan(phaseNumber,"");let{sortedTasks,taskMap,tasksInCycle}=runPartitionPreflight(directory,pendingTasks,config3,scopes),lanes=[],serializedTasks=[],degradedTasks=[],maxLanes=config3.max_parallel_coders,claimedFiles=new Set,assignedTasks=new Set,taskToLane=new Map,crossLaneDependencies={};for(let taskId of tasksInCycle)serializedTasks.push(taskId),assignedTasks.add(taskId),taskToLane.set(taskId,-1);let isSatisfied=makeDependencySatisfactionChecker(taskMap,assignedTasks,isUpstreamCommitted);while(!0){let readyTasks=getReadyTasks(sortedTasks,assignedTasks,isSatisfied);if(readyTasks.length===0)break;for(let classified of readyTasks){if(assignedTasks.has(classified.task.id))continue;if(classified.category==="global"){degradedTasks.push({taskId:classified.task.id,reason:"global file conflict",files:classified.files,requiredMode:"balanced"}),assignedTasks.add(classified.task.id);continue}if(classified.category==="protected"){if(config3.degrade_on_risk)degradedTasks.push({taskId:classified.task.id,reason:"protected path",files:classified.files,requiredMode:"balanced"});else serializedTasks.push(classified.task.id),taskToLane.set(classified.task.id,-1);assignedTasks.add(classified.task.id);continue}if(classified.category==="no-scope"||classified.category==="invalid-scope"){serializedTasks.push(classified.task.id),taskToLane.set(classified.task.id,-1),assignedTasks.add(classified.task.id);continue}if(classified.files.some((file3)=>claimedFiles.has(file3))){if(config3.conflict_policy==="degrade")degradedTasks.push({taskId:classified.task.id,reason:"file conflict with parallel task",files:classified.files,requiredMode:"balanced"});else serializedTasks.push(classified.task.id),taskToLane.set(classified.task.id,-1);assignedTasks.add(classified.task.id);continue}let hasParentChildConflict=!1;for(let file3 of classified.files){for(let claimed of Array.from(claimedFiles))if(pathsConflict(file3,claimed)){hasParentChildConflict=!0;break}if(hasParentChildConflict)break}if(hasParentChildConflict){if(config3.conflict_policy==="degrade")degradedTasks.push({taskId:classified.task.id,reason:"file conflict with parallel task",files:classified.files,requiredMode:"balanced"});else serializedTasks.push(classified.task.id),taskToLane.set(classified.task.id,-1);assignedTasks.add(classified.task.id);continue}let candidateLaneIndex=-1;for(let i=0;i<lanes.length;i++)if(!lanes[i].files.some((laneFile)=>classified.files.some((taskFile)=>pathsConflict(laneFile,taskFile)))){candidateLaneIndex=i;break}if(candidateLaneIndex===-1&&lanes.length<maxLanes)candidateLaneIndex=lanes.length;if(candidateLaneIndex!==-1){let depsInOtherLanes=[],deps=classified.task.depends??[];for(let dep of deps){if(!taskMap.has(dep))continue;let depLane=taskToLane.get(dep);if(depLane!==void 0&&depLane!==-1&&depLane!==candidateLaneIndex)depsInOtherLanes.push(dep)}if(depsInOtherLanes.length>0){serializedTasks.push(classified.task.id),assignedTasks.add(classified.task.id),taskToLane.set(classified.task.id,-1),crossLaneDependencies[classified.task.id]=depsInOtherLanes;continue}if(candidateLaneIndex<lanes.length){let lane=lanes[candidateLaneIndex];lane.taskIds.push(classified.task.id),lane.files.push(...classified.files),assignedTasks.add(classified.task.id),taskToLane.set(classified.task.id,candidateLaneIndex)}else lanes.push({laneId:`lane-${lanes.length+1}`,taskIds:[classified.task.id],files:[...classified.files],status:"pending"}),assignedTasks.add(classified.task.id),taskToLane.set(classified.task.id,lanes.length-1);for(let file3 of classified.files)claimedFiles.add(file3)}else serializedTasks.push(classified.task.id),assignedTasks.add(classified.task.id),taskToLane.set(classified.task.id,-1)}}if(isUpstreamCommitted)for(let classified of sortedTasks){if(assignedTasks.has(classified.task.id))continue;let deps=classified.task.depends??[],uncommittedCrossBatch=[],unassignedInBatch=[];for(let dep of deps)if(taskMap.has(dep)){if(!assignedTasks.has(dep))unassignedInBatch.push(dep)}else if(!isUpstreamCommitted(dep))uncommittedCrossBatch.push(dep);let reason;if(uncommittedCrossBatch.length>0){let sample=uncommittedCrossBatch.slice(0,3).join(", "),more=uncommittedCrossBatch.length>3?`, +${uncommittedCrossBatch.length-3} more`:"";reason=`cross-batch upstream not committed (greenfield-smart Rule 3): ${sample}${more}`}else if(unassignedInBatch.length>0){let sample=unassignedInBatch.slice(0,3).join(", "),more=unassignedInBatch.length>3?`, +${unassignedInBatch.length-3} more`:"";reason=`unresolved in-batch dependency: ${sample}${more}`}else reason="planning leftover (no identifiable blocker)";degradedTasks.push({taskId:classified.task.id,reason,files:classified.files,requiredMode:"balanced"}),assignedTasks.add(classified.task.id),taskToLane.set(classified.task.id,-1)}let degradationSummary;if(degradedTasks.length>0&&degradedTasks.length+serializedTasks.length===pendingTasks.length){let reasons=Array.from(new Set(degradedTasks.map((t)=>t.reason))),rule3Count=degradedTasks.filter((t)=>t.reason.includes("greenfield-smart Rule 3")).length;if(rule3Count>0&&rule3Count>=degradedTasks.length/2)degradationSummary=`All ${pendingTasks.length} tasks degraded. ${rule3Count} blocked by greenfield-smart Rule 3 — cross-batch upstream(s) not in git history. Remediation: verify Epic Mode commit-on-completion is succeeding for upstream phases, or commit those tasks manually before re-running.`;else degradationSummary=`All ${pendingTasks.length} tasks degraded. Reasons: ${reasons.join(", ")}. Consider running in standard (serial) mode.`}let counters={lanesPlanned:lanes.length,lanesStarted:0,lanesCompleted:0,lanesFailed:0,tasksSerialized:serializedTasks.length,tasksDegraded:degradedTasks.length},planId=`plan-${phaseNumber}-${Date.now()}`;return{phase:phaseNumber,planId,lanes,degradedTasks,serializedTasks,degradationSummary,counters,crossLaneDependencies}}function createEmptyPlan(phaseNumber,planId){return{phase:phaseNumber,planId,lanes:[],degradedTasks:[],serializedTasks:[],counters:{lanesPlanned:0,lanesStarted:0,lanesCompleted:0,lanesFailed:0,tasksSerialized:0,tasksDegraded:0},crossLaneDependencies:{}}}init_recovery();init_state4();init_file_locks();init_logger();var _internals252={tryAcquireLock};class TurboStateLockTimeoutError extends Error{directory;sessionID;constructor(directory,sessionID,timeoutMs){super(`Turbo state lock timeout after ${timeoutMs}ms for session ${sessionID}`);this.name="TurboStateLockTimeoutError",this.directory=directory,this.sessionID=sessionID}}var BACKOFF_START_MS2=50,BACKOFF_MAX_MS2=2000,BACKOFF_JITTER_RATIO2=0.25;function backoffMs3(attempt){let base=Math.min(BACKOFF_START_MS2*2**attempt,BACKOFF_MAX_MS2),jitter=base*BACKOFF_JITTER_RATIO2*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withTurboStateLock(directory,sessionID,fn2,timeoutMs=30000){let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result;try{result=await _internals252.tryAcquireLock(directory,".swarm/turbo-state.json","lean-turbo-runner",sessionID)}catch(acquireErr){log(`[lean-turbo] state lock acquisition error for ${sessionID} (.swarm/turbo-state.json), will retry: ${acquireErr instanceof Error?acquireErr.message:String(acquireErr)}`)}if(result?.acquired){let lock=result.lock;try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch(releaseErr){log(`[lean-turbo] state lock release failed for ${sessionID} (.swarm/turbo-state.json): ${releaseErr instanceof Error?releaseErr.message:String(releaseErr)}`)}}}if(Date.now()>=deadline)throw new TurboStateLockTimeoutError(directory,sessionID,timeoutMs);let delay4=Math.min(backoffMs3(attempt),deadline-Date.now());if(delay4>0)await new Promise((resolve120)=>setTimeout(resolve120,delay4));attempt++}}init_worktree_isolation();init_core3();import*as path310 from"node:path";function computeLaneRuntimeProfile2(runtime,laneIndex,worktreePath){if(!runtime?.enabled)return;let portStride=runtime.port_stride??1,envOverrides={};if(runtime.port_base!==void 0){let portBase=runtime.port_base,port=Math.min(portBase+laneIndex*portStride,65535);envOverrides.PORT=String(port)}if(runtime.env_overrides)Object.assign(envOverrides,runtime.env_overrides);if(runtime.cache_redirects)for(let[envName,basePath]of Object.entries(runtime.cache_redirects))envOverrides[envName]=path310.join(basePath,`lane-${laneIndex}`);return{laneIndex,worktreePath,envOverrides}}async function provisionWorktree2(directory,laneId,sessionId,config3,scope){let laneIndex=parseLeanLaneIndex(laneId),result=await provisionWorktree(directory,laneId,sessionId,{purpose:"lane",branchStyle:"legacy-lane",worktreeDir:config3.worktree_dir,mergeStrategy:config3.merge_strategy,depsStrategy:config3.deps_strategy,scope});if("error"in result)return result;let laneProfile=computeLaneRuntimeProfile2(config3.runtime_isolation,laneIndex,result.worktreePath);if(laneProfile)try{let{writeLaneProfileToDiskReal:writeLaneProfileToDiskReal2}=await Promise.resolve().then(() => (init_core3(),exports_core3));await writeLaneProfileToDiskReal2(result.worktreePath,laneProfile.laneIndex,laneProfile.envOverrides)}catch{}return{worktreePath:result.worktreePath,branchName:result.branchName}}function isTransientProvisionError(errorMsg){let lower=errorMsg.toLowerCase();if(lower.includes("already exists")||lower.includes("not a git repository"))return!1;let transientCodes=["enoent","econnrefused","etimedout","ebusy","eperm","enomem"];for(let code of transientCodes)if(lower.includes(code))return!0;let transientMessages=["disk full","no space left","resource temporarily unavailable"];for(let msg of transientMessages)if(lower.includes(msg))return!0;if(lower.includes("fatal:"))return!0;return!1}var LANE_SCOPE_DENIED_CODE="LEAN_TURBO_LANE_SCOPE_DENIED";function pushDirtyTreeDowngradeAdvisory(sessionID,reason,lanesAffected=[]){let affected=lanesAffected.length>0?`; affected lanes: ${lanesAffected.join(", ")}`:"",advisory=`LEAN_TURBO_DIRTY_TREE_DOWNGRADE: ${reason}${affected}. Worktree isolation is OFF for this phase; lanes run in the shared working tree.`,session=getAgentSession(sessionID);if(!session){criticalWarn(`[lean-turbo] ${advisory} (advisory not delivered: session ${sessionID} is not registered)`);return}pushAdvisory(session,advisory)}class LeanTurboRunner{static _internals={loadPlanJsonOnly,planLeanTurboLanes,acquireLaneLocks,releaseLaneLocks,loadLeanTurboRunState,saveLeanTurboRunState,hasActiveFullAuto,loadFullAutoRunState,writeLaneEvidence,writePhaseEvidence,laneDispatchTimeoutMs:void 0,provisionWorktree:provisionWorktree2,removeWorktree,removeLaneProfileFromDisk:removeLaneProfileFromDiskReal,mergeLaneBranch,postMergeCleanup,attemptMergeBackFromDirty,startupOrphanRecovery,getMergeStrategy:getMergeStrategy2,assertCleanWorkingTree,publishLeanTurboLaneScopeBinding};_sessionOps=null;_directory;_sessionID;_client;_availableAgents;_laneLockMap={};_laneStatuses=new Map;_agentIndex=0;_timedOutLanes=new Map;_stateLock=Promise.resolve();_leanConfig;_pendingDowngrade=null;constructor(options){if(this._directory=options.directory,this._sessionID=options.sessionID,this._leanConfig=options.leanConfig,"opencodeClient"in options){if(this._client=options.opencodeClient??null,this._client)this._sessionOps=this._client.session}let names=options.generatedAgentNames??swarmState.generatedAgentNames;this._availableAgents=this._resolveCoderAgents(names)}async runPhase(phaseNumber){if(this._client===null)return{ok:!1,reason:"NO_CLIENT",lanes:[],degradedTasks:[],serializedTasks:[]};let plan=await LeanTurboRunner._internals.loadPlanJsonOnly(this._directory);if(!plan)return{ok:!1,reason:"NO_PLAN",lanes:[],degradedTasks:[],serializedTasks:[]};if(LeanTurboRunner._internals.hasActiveFullAuto(this._sessionID)){let fullAutoState=LeanTurboRunner._internals.loadFullAutoRunState(this._directory,this._sessionID);if(fullAutoState&&(fullAutoState.status==="paused"||fullAutoState.status==="terminated"))return{ok:!1,reason:"FULL_AUTO_BLOCKED",lanes:[],degradedTasks:[],serializedTasks:[]}}let leanConfig=this._getLeanConfig(this._leanConfig),phaseStartedAt=new Date().toISOString();if(leanConfig.worktree_isolation){await LeanTurboRunner._internals.startupOrphanRecovery(this._directory,[this._sessionID]);try{let cleanResult=await LeanTurboRunner._internals.assertCleanWorkingTree(this._directory);if(!cleanResult.clean)this._pendingDowngrade={reason:cleanResult.error??"uncommitted changes"},log(`[lean-turbo] worktree isolation requires clean working tree: ${cleanResult.error}`),leanConfig.worktree_isolation=!1}catch(assertErr){let assertMsg=assertErr instanceof Error?assertErr.message:String(assertErr);this._pendingDowngrade={reason:`cleanliness check failed: ${assertMsg}`},log(`[lean-turbo] unable to verify working tree cleanliness: ${assertMsg} — degrading to shared directory`),leanConfig.worktree_isolation=!1}}let lanePlan=LeanTurboRunner._internals.planLeanTurboLanes(this._directory,phaseNumber,{phases:plan.phases},leanConfig);if(this._pendingDowngrade){let lanesAffected=lanePlan.lanes.map((l)=>l.laneId);pushDirtyTreeDowngradeAdvisory(this._sessionID,this._pendingDowngrade.reason,lanesAffected),this._pendingDowngrade=null}let degradedTasks=lanePlan.degradedTasks.map((d)=>d.taskId),degradedDetails=lanePlan.degradedTasks;if(lanePlan.lanes.length===0&&degradedTasks.length===0&&lanePlan.serializedTasks.length===0)return{ok:!1,reason:"NO_LANES",lanes:[],degradedTasks,degradedDetails,serializedTasks:lanePlan.serializedTasks};if(lanePlan.lanes.length===0)return await this._withStateLock(()=>this._updateDurableState(lanePlan)),await this._writePhaseEvidenceSafely({phaseNumber,plan,lanePlan,laneResults:[],leanConfig,status:"completed",startedAt:phaseStartedAt}),{ok:!0,lanes:[],degradedTasks,degradedDetails,serializedTasks:lanePlan.serializedTasks};await this._withStateLock(()=>this._updateDurableState(lanePlan)),this._laneStatuses=new Map(lanePlan.lanes.map((lane)=>[lane.laneId,{...lane}]));let laneResults=[],results=await Promise.all(lanePlan.lanes.map((lane)=>this._processLane(lane,leanConfig,plan)));laneResults.push(...results);let mergeBackFailures=await this._sequentialWorktreeCleanup(laneResults,leanConfig),phaseResult={ok:mergeBackFailures.length===0,reason:mergeBackFailures.length>0?`Lean Turbo merge-back failed for ${mergeBackFailures.length} lane(s); preserved affected worktrees for manual recovery.`:void 0,lanes:laneResults,degradedTasks,degradedDetails,serializedTasks:lanePlan.serializedTasks,mergeBackFailures:mergeBackFailures.length>0?mergeBackFailures:void 0};return await this._writePhaseEvidenceSafely({phaseNumber,plan,lanePlan,laneResults,leanConfig,status:phaseResult.ok?"completed":"failed",startedAt:phaseStartedAt,mergeBackFailures}),phaseResult}async dispatchLane(lane,agentName,worktreeDirectory,model,plan){let session=this._sessionOps??this._client?.session;if(!session)return{ok:!1,error:"NO_CLIENT"};let promptController=new AbortController,dispatchPromise=this._doDispatch(session,lane,agentName,worktreeDirectory,promptController,model,plan),timeoutMs=LeanTurboRunner._internals.laneDispatchTimeoutMs;if(timeoutMs!==void 0&&timeoutMs>0){let timeoutHandle,timeoutPromise=new Promise((_,reject2)=>{timeoutHandle=setTimeout(()=>{promptController.abort(),reject2(Error(`Lane dispatch timed out after ${timeoutMs}ms`))},timeoutMs)});try{return await Promise.race([dispatchPromise,timeoutPromise])}catch(err){if(err instanceof Error&&err.message.includes("timed out"))return this._timedOutLanes.set(lane.laneId,"__pending__"),dispatchPromise.then((result)=>{if(result.ok&&result.sessionId)if(this._timedOutLanes.get(lane.laneId)!==void 0)this._timedOutLanes.delete(lane.laneId),teardownEphemeralSession(session,result.sessionId),endAgentSession(result.sessionId,worktreeDirectory??this._directory);else this._timedOutLanes.delete(lane.laneId);else this._timedOutLanes.delete(lane.laneId)}).catch(()=>{this._timedOutLanes.delete(lane.laneId)}),{ok:!1,error:err.message};throw err}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle)}}return dispatchPromise}async _doDispatch(session,lane,agentName,worktreeDirectory,abortController,model,plan){let sessionId,effectiveDirectory=worktreeDirectory??this._directory;try{let createResult=await session.create({...this._sessionID?{body:{parentID:this._sessionID,title:`lean_turbo_lane_${lane.laneId} background`}}:{},query:{directory:effectiveDirectory}});if(!createResult.data)return{ok:!1,error:`session.create failed: ${typeof createResult.error==="string"?createResult.error:JSON.stringify(createResult.error)}`};if(sessionId=createResult.data.id,plan){let laneScopeError=await this._publishLaneScope(session,lane,plan,sessionId,worktreeDirectory,effectiveDirectory,abortController);if(laneScopeError)return laneScopeError}let promptText=this._buildLanePrompt(lane),promptResult=await session.prompt({path:{id:sessionId},body:{agent:agentName,...model?{model}:{},tools:plan?{write:!0,edit:!0,patch:!0}:{write:!1,edit:!1,patch:!1},parts:[{type:"text",text:promptText}]},signal:abortController?.signal});if(!promptResult.data)return abortController?.abort(),teardownEphemeralSession(session,sessionId),endAgentSession(sessionId,effectiveDirectory),{ok:!1,error:`session.prompt failed: ${typeof promptResult.error==="string"?promptResult.error:JSON.stringify(promptResult.error)}`};return{ok:!0,sessionId}}catch(err){if(sessionId)abortController?.abort(),teardownEphemeralSession(session,sessionId),endAgentSession(sessionId,effectiveDirectory);return{ok:!1,error:err instanceof Error?err.message:String(err)}}}async _publishLaneScope(session,lane,plan,childSessionId,worktreeDirectory,effectiveDirectory,abortController){let published;try{published=await LeanTurboRunner._internals.publishLeanTurboLaneScopeBinding({primaryDirectory:this._directory,laneRoot:effectiveDirectory,isolated:worktreeDirectory!==void 0,plan,lane,parentSessionId:this._sessionID,childSessionId})}catch(scopeErr){let reason=scopeErr instanceof Error?scopeErr.message:String(scopeErr);return abortController?.abort(),teardownEphemeralSession(session,childSessionId),endAgentSession(childSessionId,effectiveDirectory),log(`[lean-turbo] lane ${lane.laneId} write authority could not be published: ${reason}`),{ok:!1,error:`${LANE_SCOPE_DENIED_CODE}: ${reason}`}}if(!published){if(log(`[lean-turbo] lane ${lane.laneId} has no plan-backed scope authority (tasks: ${lane.taskIds.join(", ")}) — the lane coder will be blocked on every write`),this._sessionID)try{let unscopedAdvisory=`LEAN_TURBO_LANE_UNSCOPED: lane ${lane.laneId} (tasks: ${lane.taskIds.join(", ")}) could not be given a validated write scope, so its coder is blocked from writing. Declare a scope for the lane's tasks or give them files_touched in the plan.`,architectSession=getAgentSession(this._sessionID);if(architectSession)pushAdvisory(architectSession,unscopedAdvisory);else criticalWarn(`[lean-turbo] ${unscopedAdvisory} (advisory not delivered: session ${this._sessionID} is not registered)`)}catch{}}return null}async waitForLanes(){let statuses=[];for(let[laneId,lane]of this._laneStatuses)statuses.push({laneId,status:lane.status,taskIds:lane.taskIds,agent:lane.agent,sessionId:lane.sessionId,error:lane.error});return statuses}async cleanup(){for(let[laneId]of Object.entries(this._laneLockMap))try{await LeanTurboRunner._internals.releaseLaneLocks(this._directory,laneId)}catch{}this._laneLockMap={};for(let[_laneId,lane]of this._laneStatuses)if(lane.worktreePath)try{await LeanTurboRunner._internals.removeWorktree(lane.worktreePath,this._directory,{force:!0,worktreeDir:this._leanConfig?.worktree_dir})}catch{}await this._withStateLock(async()=>{let runState=LeanTurboRunner._internals.loadLeanTurboRunState(this._directory,this._sessionID);if(runState)runState.lanes=runState.lanes.map((lane)=>lane.status==="running"||lane.status==="pending"?{...lane,status:"blocked"}:lane),LeanTurboRunner._internals.saveLeanTurboRunState(this._directory,runState)})}async cleanupAfterSuccess(){for(let[laneId]of Object.entries(this._laneLockMap)){let laneStatus=this._laneStatuses.get(laneId);if(laneStatus&&(laneStatus.status==="completed"||laneStatus.status==="failed"||laneStatus.status==="blocked")){try{await LeanTurboRunner._internals.releaseLaneLocks(this._directory,laneId)}catch{}delete this._laneLockMap[laneId]}}}async cleanupAfterFailure(){return this.cleanup()}_resolveCoderAgents(names){let coders=names.filter((n)=>n.toLowerCase().includes("coder"));if(coders.length===0)return["coder"];let prefixed=coders.filter((n)=>/[_-]coder$/i.test(n)||/^[a-z]+_[a-z]+_coder$/i.test(n)),bare=coders.filter((n)=>!n.includes("_")&&!n.includes("-")&&n==="coder"),sorted2=[...prefixed.sort((a,b)=>b.length-a.length),...bare],seen=new Set,deduped=[];for(let name of sorted2)if(!seen.has(name.toLowerCase()))seen.add(name.toLowerCase()),deduped.push(name);return deduped.length>0?deduped:["coder"]}_getLeanConfig(config3){if(config3)return structuredClone({...DEFAULT_LEAN_TURBO_CONFIG,...config3});return{...DEFAULT_LEAN_TURBO_CONFIG}}async _processLane(lane,leanConfig,plan){let laneInState=this._laneStatuses.get(lane.laneId);if(laneInState)laneInState.status="running",laneInState.startedAt=new Date().toISOString();let taskId=lane.taskIds[0]??lane.laneId,agent=this._selectNextAgent();if(!(await LeanTurboRunner._internals.acquireLaneLocks(this._directory,lane.laneId,lane.files,agent,taskId,this._sessionID)).acquired){if(await this._withStateLock(async()=>{try{let runState=LeanTurboRunner._internals.loadLeanTurboRunState(this._directory,this._sessionID);if(runState){let existingSerialized=new Set(runState.serializedTasks??[]);for(let tid of lane.taskIds)existingSerialized.add(tid);runState.serializedTasks=Array.from(existingSerialized),runState.counters.tasksSerialized+=lane.taskIds.length,LeanTurboRunner._internals.saveLeanTurboRunState(this._directory,runState)}}catch{}}),laneInState)laneInState.status="failed",laneInState.error="lock conflict - tasks routed to serial fallback";return await this._updateDurableStateLaneStatus(lane.laneId,"failed"),{laneId:lane.laneId,status:"failed",taskIds:lane.taskIds,error:"lock conflict - tasks routed to serial fallback"}}this._laneLockMap[lane.laneId]=[...lane.files];let worktreeDirectory;if(leanConfig.worktree_isolation){let provisionError;try{let provisionResult=await LeanTurboRunner._internals.provisionWorktree(this._directory,lane.laneId,this._sessionID,leanConfig);if("worktreePath"in provisionResult){if(worktreeDirectory=provisionResult.worktreePath,laneInState)laneInState.worktreePath=provisionResult.worktreePath,laneInState.branchName=provisionResult.branchName;await this._persistLaneWorktreeFields(lane.laneId,provisionResult.worktreePath,provisionResult.branchName),recordLiveLaneOwner(this._directory,{lanePath:provisionResult.worktreePath,branchName:provisionResult.branchName,sessionId:this._sessionID,taskId:lane.laneId})}else provisionError=provisionResult.error}catch(provisionErr){provisionError=provisionErr instanceof Error?provisionErr.message:String(provisionErr)}if(provisionError)if(isTransientProvisionError(provisionError)){log(`[lean-turbo] worktree provision failed for lane ${lane.laneId}: ${provisionError} — retrying once...`),await new Promise((r)=>setTimeout(r,100));try{let retryResult=await LeanTurboRunner._internals.provisionWorktree(this._directory,lane.laneId,this._sessionID,leanConfig);if("worktreePath"in retryResult){if(worktreeDirectory=retryResult.worktreePath,laneInState)laneInState.worktreePath=retryResult.worktreePath,laneInState.branchName=retryResult.branchName;await this._persistLaneWorktreeFields(lane.laneId,retryResult.worktreePath,retryResult.branchName),recordLiveLaneOwner(this._directory,{lanePath:retryResult.worktreePath,branchName:retryResult.branchName,sessionId:this._sessionID,taskId:lane.laneId}),log(`[lean-turbo] worktree provision retry succeeded for lane ${lane.laneId}`),provisionError=void 0}else provisionError=retryResult.error,log(`[lean-turbo] worktree provision retry failed for lane ${lane.laneId}: ${retryResult.error}`)}catch(retryErr){let retryMsg=retryErr instanceof Error?retryErr.message:String(retryErr);log(`[lean-turbo] worktree provision retry threw for lane ${lane.laneId}: ${retryMsg}`)}}else log(`[lean-turbo] worktree provision failed for lane ${lane.laneId}: ${provisionError}`);if(!worktreeDirectory){let failMsg=`worktree provision failed: ${provisionError??"unknown error"}`;try{await LeanTurboRunner._internals.releaseLaneLocks(this._directory,lane.laneId)}catch{}if(delete this._laneLockMap[lane.laneId],laneInState)laneInState.status="failed",laneInState.error=failMsg;return await this._updateDurableStateLaneStatus(lane.laneId,"failed"),await this._writeLaneEvidenceSafely(lane,"failed",{status:"failed",error:failMsg,agent}),{laneId:lane.laneId,status:"failed",taskIds:lane.taskIds,agent,error:failMsg}}}let coderBase=stripKnownSwarmPrefix(agent),coderSwarmId=coderBase!==agent?agent.slice(0,agent.length-coderBase.length-1):void 0,coderSwarmAgents=getSwarmAgents(coderSwarmId),dispatchResult;try{dispatchResult=(await dispatchWithModelFallback({dispatch:async(model)=>{let r=await this.dispatchLane(lane,agent,worktreeDirectory,model,plan);if(!r.ok)throw Error(r.error??"lane dispatch failed");return r},scope:this._sessionID?{sessionID:this._sessionID,invocationID:`lean-runner:${lane.laneId}`,swarmID:coderSwarmId,role:coderBase}:void 0,primaryModel:coderSwarmAgents?.[coderBase]?.model,fallbackModels:coderSwarmAgents?.[coderBase]?.fallback_models??[],resolveFallback:(index)=>resolveFallbackModel(coderBase,index,coderSwarmAgents),maxTransientRetriesPerModel:0,classify:(err)=>{let msg=err instanceof Error?err.message:String(err);if(/Lane dispatch timed out/i.test(msg))return"permanent";if(msg.includes(LANE_SCOPE_DENIED_CODE))return"permanent";return isTransientProviderError(msg)?"transient":"permanent"},onFallback:({toModel,fallbackIndex})=>{telemetry.modelFallback(this._sessionID??"",agent,coderSwarmAgents?.[coderBase]?.model??"default",toModel,"transient_model_error");let session=this._sessionID?getAgentSession(this._sessionID):void 0;if(session)pushAdvisory(session,`MODEL FALLBACK: coder lane ${lane.laneId} failed over to "${toModel}" (fallback ${fallbackIndex}) after a transient/quota dispatch error.`)}})).result}catch(err){let msg=err instanceof Error?err.message:String(err);dispatchResult={ok:!1,error:isQuotaError(msg)?`${msg} (model quota/usage limit exhausted across all configured fallbacks)`:msg}}if(!dispatchResult.ok){try{await LeanTurboRunner._internals.releaseLaneLocks(this._directory,lane.laneId)}catch{}if(delete this._laneLockMap[lane.laneId],worktreeDirectory&&laneInState)laneInState._failureCleanupPending=!0;if(laneInState)laneInState.status="failed",laneInState.error=dispatchResult.error;return await this._updateDurableStateLaneStatus(lane.laneId,"failed"),await this._writeLaneEvidenceSafely(lane,"failed",{status:"failed",error:dispatchResult.error,agent}),{laneId:lane.laneId,status:"failed",taskIds:lane.taskIds,agent,error:dispatchResult.error}}let completedAt=new Date().toISOString();if(laneInState)laneInState.status="completed",laneInState.agent=agent,laneInState.sessionId=dispatchResult.sessionId,laneInState.completedAt=completedAt;await this._updateDurableStateLaneStatus(lane.laneId,"completed");try{await LeanTurboRunner._internals.releaseLaneLocks(this._directory,lane.laneId)}catch{}return delete this._laneLockMap[lane.laneId],await this._writeLaneEvidenceSafely(lane,"completed",{status:"completed",agent,sessionId:dispatchResult.sessionId,completedAt}),{laneId:lane.laneId,status:"completed",taskIds:lane.taskIds,agent,sessionId:dispatchResult.sessionId}}_persistRecovery(info){writeRecoveryRecord(this._directory,{laneId:info.laneId,sessionId:this._sessionID,branchName:info.branchName,worktreePath:info.worktreePath,status:info.status,reason:info.reason,conflictFiles:info.conflictFiles,replayHint:"Open the directory in worktreePath and run git status with that directory as the working directory."})}async _sequentialWorktreeCleanup(laneResults,leanConfig){let mergeBackFailures=[];for(let lr of laneResults){let laneInState=this._laneStatuses.get(lr.laneId);if(!laneInState?.worktreePath)continue;let needsPostMergeCleanup=!1;if(lr.status==="completed"){if(!laneInState.branchName)continue;try{let strategy=LeanTurboRunner._internals.getMergeStrategy(leanConfig),mergeResult=await LeanTurboRunner._internals.attemptMergeBackFromDirty(laneInState.worktreePath,laneInState.branchName,this._directory,strategy,{commitLanding:!0});if("merged"in mergeResult&&mergeResult.merged){needsPostMergeCleanup=!0,clearRecoveryRecord(this._directory,lr.laneId,this._sessionID);let leanLaneIndex=parseLeanLaneIndex(lr.laneId);try{await LeanTurboRunner._internals.removeLaneProfileFromDisk(laneInState.worktreePath,leanLaneIndex)}catch{}}else if("conflict"in mergeResult&&mergeResult.conflict||"partial"in mergeResult&&mergeResult.partial){let conflictFiles="conflictFiles"in mergeResult&&Array.isArray(mergeResult.conflictFiles)?mergeResult.conflictFiles:[],isConflict="conflict"in mergeResult&&mergeResult.conflict===!0||conflictFiles.length>0,reason="message"in mergeResult&&typeof mergeResult.message==="string"&&(mergeResult.message||"")||"merge-back partially failed",failureInfo={laneId:lr.laneId,branchName:laneInState.branchName,worktreePath:laneInState.worktreePath,status:isConflict?"conflict":"partial",reason,conflictFiles};mergeBackFailures.push(failureInfo),lr.status="failed",lr.error=failureInfo.reason,lr.mergeBackFailure=failureInfo,laneInState.status="failed",laneInState.error=failureInfo.reason,await this._updateDurableStateLaneStatus(lr.laneId,"failed"),await this._writeLaneEvidenceSafely({laneId:lr.laneId,taskIds:lr.taskIds,files:[],status:"failed"},"failed",{status:"failed",error:failureInfo.reason,mergeBackFailure:failureInfo}),this._persistRecovery(failureInfo),log(`[lean-turbo] merge-back PARTIAL for lane ${lr.laneId}: ${failureInfo.reason} — worktree preserved at ${laneInState.worktreePath} for manual recovery`);continue}else if("failed"in mergeResult&&mergeResult.failed){let failureInfo={laneId:lr.laneId,branchName:laneInState.branchName,worktreePath:laneInState.worktreePath,status:"failed",reason:mergeResult.message};mergeBackFailures.push(failureInfo),lr.status="failed",lr.error=failureInfo.reason,lr.mergeBackFailure=failureInfo,laneInState.status="failed",laneInState.error=failureInfo.reason,await this._updateDurableStateLaneStatus(lr.laneId,"failed"),await this._writeLaneEvidenceSafely({laneId:lr.laneId,taskIds:lr.taskIds,files:[],status:"failed"},"failed",{status:"failed",error:failureInfo.reason,mergeBackFailure:failureInfo}),log(`[lean-turbo] merge-back ERROR for lane ${lr.laneId}: ${failureInfo.reason} — worktree preserved at ${laneInState.worktreePath} for manual recovery`),this._persistRecovery(failureInfo);continue}}catch(err){let errMsg=err instanceof Error?err.message:String(err),failureInfo={laneId:lr.laneId,branchName:laneInState.branchName,worktreePath:laneInState.worktreePath,status:"failed",reason:errMsg};mergeBackFailures.push(failureInfo),lr.status="failed",lr.error=failureInfo.reason,lr.mergeBackFailure=failureInfo,laneInState.status="failed",laneInState.error=failureInfo.reason,await this._updateDurableStateLaneStatus(lr.laneId,"failed"),await this._writeLaneEvidenceSafely({laneId:lr.laneId,taskIds:lr.taskIds,files:[],status:"failed"},"failed",{status:"failed",error:failureInfo.reason,mergeBackFailure:failureInfo}),log(`[lean-turbo] merge-back EXCEPTION for lane ${lr.laneId}: ${errMsg} — worktree preserved at ${laneInState.worktreePath} for manual recovery`),this._persistRecovery(failureInfo);continue}}else if(lr.status==="failed"&&laneInState._failureCleanupPending){let failureInfo={laneId:lr.laneId,branchName:laneInState.branchName,worktreePath:laneInState.worktreePath,status:"failed",reason:lr.error||"Lane failed before completion; worktree preserved without merge-back"};mergeBackFailures.push(failureInfo),lr.mergeBackFailure=failureInfo,log(`[lean-turbo] failed lane ${lr.laneId}: ${failureInfo.reason} — worktree preserved at ${laneInState.worktreePath}; not merging partial work`),this._persistRecovery(failureInfo);continue}try{await LeanTurboRunner._internals.removeWorktree(laneInState.worktreePath,this._directory,{force:!0,worktreeDir:leanConfig.worktree_dir})}catch{}if(needsPostMergeCleanup&&laneInState.branchName)try{await LeanTurboRunner._internals.postMergeCleanup(this._directory,laneInState.branchName)}catch{}}return mergeBackFailures}_buildIntegratedDiffSummary(lanePlan,laneResults,mergeBackFailures=[]){let resultByLane=new Map(laneResults.map((lane)=>[lane.laneId,lane])),files=new Set;for(let lane of lanePlan.lanes)for(let file3 of lane.files)files.add(file3);let completed=laneResults.filter((lane)=>lane.status==="completed").length,failed=laneResults.filter((lane)=>lane.status==="failed").length,blocked=laneResults.filter((lane)=>lane.status==="blocked").length,fileList=[...files].sort(),displayedFiles=fileList.slice(0,50),hiddenFileCount=Math.max(0,fileList.length-displayedFiles.length),lines=[`Lean Turbo phase ${lanePlan.phase}: ${completed}/${lanePlan.lanes.length} lanes completed, ${failed} failed, ${blocked} blocked.`,`Files declared changed (${fileList.length}): ${displayedFiles.length>0?displayedFiles.join(", "):"none"}${hiddenFileCount>0?`, ... +${hiddenFileCount} more`:""}.`];if(lanePlan.serializedTasks.length>0)lines.push(`Serialized tasks pending standard execution: ${lanePlan.serializedTasks.join(", ")}.`);if(lanePlan.degradedTasks.length>0)lines.push(`Degraded tasks: ${lanePlan.degradedTasks.map((task2)=>`${task2.taskId} (${task2.reason})`).join(", ")}.`);if(mergeBackFailures.length>0)lines.push(`Merge-back failures: ${mergeBackFailures.map((failure)=>`${failure.laneId}: ${failure.reason}`).join("; ")}.`);for(let lane of lanePlan.lanes){let result=resultByLane.get(lane.laneId);if(result?.error)lines.push(`${lane.laneId} error: ${result.error}.`)}return lines.join(`
7499
- `)}async _writePhaseEvidenceSafely(args2){let completedAt=new Date().toISOString(),resultByLane=new Map(args2.laneResults.map((lane)=>[lane.laneId,lane])),lanes=args2.lanePlan.lanes.map((lane)=>{let result=resultByLane.get(lane.laneId),evidenceLane={laneId:lane.laneId,taskIds:lane.taskIds,files:lane.files,status:result?.status??lane.status,startedAt:lane.startedAt,completedAt:result?.status==="completed"||result?.status==="failed"?lane.completedAt??completedAt:lane.completedAt,error:result?.error??lane.error,agent:result?.agent??lane.agent,sessionId:result?.sessionId??lane.sessionId};if(result?.mergeBackFailure)evidenceLane.mergeBackFailure=result.mergeBackFailure;return evidenceLane}),planId=args2.lanePlan.planId||derivePlanId({swarm:args2.plan.swarm??"default",title:args2.plan.title??"Untitled Plan"}),evidence2={phase:args2.phaseNumber,planId,lanes,degradedTasks:args2.lanePlan.degradedTasks.map((task2)=>({taskId:task2.taskId,reason:task2.reason})),startedAt:args2.startedAt,completedAt,status:args2.status,evidencePaths:lanes.map((lane)=>`.swarm/evidence/${args2.phaseNumber}/lean-turbo/${lane.laneId}.json`),integratedDiffSummary:this._buildIntegratedDiffSummary(args2.lanePlan,args2.laneResults,args2.mergeBackFailures??[]),configSnapshot:args2.leanConfig,timestamp:completedAt};try{await LeanTurboRunner._internals.writePhaseEvidence(this._directory,evidence2)}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);log(`[lean-turbo] phase evidence write failed: ${msg}`)}}_selectNextAgent(){if(this._availableAgents.length===0)return"coder";let agent=this._availableAgents[this._agentIndex%this._availableAgents.length];return this._agentIndex++,agent}async _writeLaneEvidenceSafely(lane,status2,extras){for(let attempt=0;attempt<3;attempt++)try{let evidence2={laneId:lane.laneId,taskIds:lane.taskIds,files:lane.files,status:status2,startedAt:lane.startedAt,...extras},phase=LeanTurboRunner._internals.loadLeanTurboRunState(this._directory,this._sessionID)?.phase;if(phase===void 0){log(`[lean-turbo] evidence write skipped for lane ${lane.laneId}: phase not set in run state`);return}await LeanTurboRunner._internals.writeLaneEvidence(this._directory,phase,evidence2);return}catch(error93){let errCode=error93 instanceof Error?error93.code??"":"",isTransient=errCode.length>0&&["ENOENT","EBUSY","EPERM","EIO","EAGAIN","ETIMEDOUT","ENOSPC"].includes(errCode);if(attempt<2&&isTransient){let delayMs=100*2**attempt;await new Promise((resolve120)=>setTimeout(resolve120,delayMs));continue}let msg=error93 instanceof Error?error93.message:String(error93);log(`[lean-turbo] evidence write failed for lane ${lane.laneId}: ${msg}`);return}}_buildLanePrompt(lane){let taskList=lane.taskIds.map((id)=>` - ${id}`).join(`
7499
+ `)}async _writePhaseEvidenceSafely(args2){let completedAt=new Date().toISOString(),resultByLane=new Map(args2.laneResults.map((lane)=>[lane.laneId,lane])),lanes=args2.lanePlan.lanes.map((lane)=>{let result=resultByLane.get(lane.laneId),evidenceLane={laneId:lane.laneId,taskIds:lane.taskIds,files:lane.files,status:result?.status??lane.status,startedAt:lane.startedAt,completedAt:result?.status==="completed"||result?.status==="failed"?lane.completedAt??completedAt:lane.completedAt,error:result?.error??lane.error,agent:result?.agent??lane.agent,sessionId:result?.sessionId??lane.sessionId};if(result?.mergeBackFailure)evidenceLane.mergeBackFailure=result.mergeBackFailure;return evidenceLane}),planId=args2.lanePlan.planId||derivePlanId({swarm:args2.plan.swarm??"default",title:args2.plan.title??"Untitled Plan"}),evidence2={phase:args2.phaseNumber,planId,lanes,degradedTasks:args2.lanePlan.degradedTasks.map((task2)=>({taskId:task2.taskId,reason:task2.reason})),startedAt:args2.startedAt,completedAt,status:args2.status,evidencePaths:lanes.map((lane)=>`.swarm/evidence/${args2.phaseNumber}/lean-turbo/${lane.laneId}.json`),integratedDiffSummary:this._buildIntegratedDiffSummary(args2.lanePlan,args2.laneResults,args2.mergeBackFailures??[]),configSnapshot:args2.leanConfig,timestamp:completedAt};try{await LeanTurboRunner._internals.writePhaseEvidence(this._directory,evidence2)}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);criticalWarn(`[lean-turbo] phase evidence write failed for phase ${evidence2.phase}: ${msg}. The phase will not be able to advance at phase_complete until the evidence exists (.swarm/evidence/${evidence2.phase}/lean-turbo/lean-turbo-phase.json) or turbo.lean.integrated_diff_required is set to false.`)}}_selectNextAgent(){if(this._availableAgents.length===0)return"coder";let agent=this._availableAgents[this._agentIndex%this._availableAgents.length];return this._agentIndex++,agent}async _writeLaneEvidenceSafely(lane,status2,extras){for(let attempt=0;attempt<3;attempt++)try{let evidence2={laneId:lane.laneId,taskIds:lane.taskIds,files:lane.files,status:status2,startedAt:lane.startedAt,...extras},phase=LeanTurboRunner._internals.loadLeanTurboRunState(this._directory,this._sessionID)?.phase;if(phase===void 0){log(`[lean-turbo] evidence write skipped for lane ${lane.laneId}: phase not set in run state`);return}await LeanTurboRunner._internals.writeLaneEvidence(this._directory,phase,evidence2);return}catch(error93){let errCode=error93 instanceof Error?error93.code??"":"",isTransient=errCode.length>0&&["ENOENT","EBUSY","EPERM","EIO","EAGAIN","ETIMEDOUT","ENOSPC"].includes(errCode);if(attempt<2&&isTransient){let delayMs=100*2**attempt;await new Promise((resolve120)=>setTimeout(resolve120,delayMs));continue}let msg=error93 instanceof Error?error93.message:String(error93);log(`[lean-turbo] evidence write failed for lane ${lane.laneId}: ${msg}`);return}}_buildLanePrompt(lane){let taskList=lane.taskIds.map((id)=>` - ${id}`).join(`
7500
7500
  `),fileList=lane.files.map((f)=>` - ${f}`).join(`
7501
7501
  `);return`You are assigned to implement the following task(s) in lane "${lane.laneId}".
7502
7502
 
@@ -7563,7 +7563,7 @@ ${hint}`}]}return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0
7563
7563
  `)){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(!fs179.existsSync(directory))return JSON.stringify({error:!0,type:"unknown",message:"Workspace directory does not exist"},null,2);let executable=_internals257.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 _internals257.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(`
7564
7564
  `)[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)}}),_internals257={resolveExecutableFromPath,resolveAstGrepBinary,runExternalTool,parseAstGrepStream};init_zod();init_authorization();init_create_tool();var AuthorizePrReviewReentryArgsSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),role:exports_external.enum(["reviewer","test_engineer"])}).strict();async function executeAuthorizePrReviewReentry(args2,directory,context={}){let parsed=AuthorizePrReviewReentryArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR-review re-entry authorization: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR-review re-entry authorization requires an active sessionID"});try{let record3=await issuePrReviewReentryAuthorization(directory,context.sessionID,{...parsed.data.run_id?{runId:parsed.data.run_id}:{},prHeadSha:parsed.data.pr_head_sha,role:parsed.data.role});return JSON.stringify({success:!0,authorization_id:record3.authorizationId,role:record3.role,pr_head_sha:record3.prHeadSha,run_id:record3.runId,generation:record3.generation,revision_digest:record3.revisionDigest,expires_at:record3.expiresAt,instructions:`Immediately dispatch exactly one direct subagent_type Task call with role "${record3.role}" for this PR-review re-entry; if a plan or task workflow state exists, include the exact task_id (or task identifier in the prompt). A taskless dispatch is allowed only for a plan-free standalone review and does not advance plan-task gate state. The PR workflow controller admits and reserves this authorization once, and the delegation gate verifies the same call-bound reservation; a later unrelated gate rejection still burns it. Any other dispatch falls back to normal gating.`},null,2)}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var authorize_pr_review_reentry=createSwarmTool({description:"Issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383). The authorization is reserved atomically by the PR workflow controller for the very next direct subagent_type Task dispatch of the declared role (admitting that one dispatch past the PR_REVIEW read-only restriction), then verified for that same call by the delegation gate, which bypasses ONLY the generic Stage-A task-workflow requirement; all other delegation gates remain authoritative. If a plan or task workflow state exists, the dispatch must include an exact task_id or task identifier; taskless dispatch is standalone-only and never guesses from plan/session state. Bound to the exact session, workflow, run, PR head SHA, worktree revision digest, role, and gate generation; replay, cross-session use, wrong role, expiry (10 minutes), or workflow progress since issuance fails closed. A dispatch the delegation gate later rejects for another reason still burns the authorization. Requires an active head-bound PR_REVIEW gate. Issue immediately before the Task dispatch; unconsumed same-role authorizations at the same generation are refused.",args:{run_id:AuthorizePrReviewReentryArgsSchema.shape.run_id,pr_head_sha:AuthorizePrReviewReentryArgsSchema.shape.pr_head_sha,role:AuthorizePrReviewReentryArgsSchema.shape.role},execute:executeAuthorizePrReviewReentry});init_dist();init_create_tool();init_symbols();init_path_security();import*as fs180 from"node:fs";import*as path315 from"node:path";var WINDOWS_RESERVED_NAMES4=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks3(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES4.test(part))return!0;return!1}function isPathInWorkspace2(filePath,workspace){try{let resolvedPath=path315.resolve(workspace,filePath);if(!fs180.existsSync(resolvedPath))return!0;let realWorkspace=fs180.realpathSync(workspace),realResolvedPath=fs180.realpathSync(resolvedPath),relativePath2=path315.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path315.isAbsolute(relativePath2))return!1;return!0}catch{return!1}}function processFile(file3,cwd,exportedOnly){let ext=path315.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=path315.join(cwd,file3);if(!fs180.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(fs180.statSync(fullPath).size===0)isEmptyFile=!0}catch{}if(syms.length===0)try{if(fs180.readFileSync(fullPath,"utf-8").trim().length===0)isEmptyFile=!0}catch{}if(isEmptyFile)return{file:file3,success:!0,symbols:[],error:"empty-file",errorType:"empty-file"};if(exportedOnly)syms=syms.filter((s)=>s.exported);return{file:file3,success:!0,symbols:syms}}var batch_symbols=createSwarmTool({description:"Extract symbols from multiple files in a single batch call. Accepts an array of file paths and returns per-file symbol summaries. One bad file does not crash the batch. Use for surveying a module when you need symbol information from multiple files at once.",args:{files:tool.schema.array(tool.schema.string()).describe("Array of file paths to extract symbols from"),exported_only:tool.schema.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols.")},execute:async(args2,directory)=>{let files,exportedOnly=!0;try{let obj=args2;if(!Array.isArray(obj.files))return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: files must be an array"},null,2);files=obj.files.map((f)=>String(f)),exportedOnly=obj.exported_only!==!1}catch{return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: could not extract files array"},null,2)}let cwd=directory,results=[];for(let file3 of files){let result=processFile(file3,cwd,exportedOnly);results.push(result)}let successCount=results.filter((r)=>r.success).length,failureCount=results.filter((r)=>!r.success).length,batchResult={results,totalFiles:files.length,successCount,failureCount};return JSON.stringify(batchResult,null,2)}});init_zod();init_discovery();init_config();init_manager2();init_bun_compat();init_logger();init_create_tool();var _internals258={loadGateOverrides,bunSpawn},DEFAULT_TIMEOUT_MS4=300000,MAX_OUTPUT_BYTES6=10240,MAX_OUTPUT_LINES=100,NO_BUILD_FILES_DISCOVERED_REASON="No build commands discovered (no supported build files found)";function truncateOutput(output,maxLines=MAX_OUTPUT_LINES,maxBytes=MAX_OUTPUT_BYTES6){if(!output)return"";let truncated=output;if(truncated.length>maxBytes)truncated=truncated.slice(-maxBytes);let lines=truncated.split(`
7565
7565
  `);if(lines.length>maxLines)return lines.slice(-maxLines).join(`
7566
- `);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 proc=_internals258.bunSpawn([...cmd,...args2],{cwd:command.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:DEFAULT_TIMEOUT_MS4,maxBuffer:DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES});try{let[exitCode,stdout,stderr]=await Promise.all([proc.exited,proc.stdout.text(),proc.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)}}finally{try{proc.kill()}catch{}}}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,environmentUnavailable=discoveryResult.skipped.filter((skip)=>skip.code==="environment_unavailable");if(runs.length===0)if(verdict=environmentUnavailable.length>0?"skip":"info",discoveryResult.skipped.length>0)skipped_reason=discoveryResult.skipped.map((s)=>`${s.ecosystem}: ${s.reason}`).join("; ");else skipped_reason=NO_BUILD_FILES_DISCOVERED_REASON;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,environment_unavailable:environmentUnavailable.length>0?environmentUnavailable:void 0}}}var build_check=createSwarmTool({allowWorkingDirectoryOverride:!0,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){if(_internals258.loadGateOverrides(directory)?.build_check?.enabled===!1)return JSON.stringify({verdict:"skip",runs:[],summary:{files_scanned:0,runs_count:0,failed_count:0,skipped_reason:"build_check disabled by configuration"}},null,2);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,environment_unavailable:result.summary.environment_unavailable};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_delegation_lifecycle();init_pending_delegations();init_state2();init_create_tool();import{createHash as createHash103}from"node:crypto";var MAX_BATCH_ID_CHARS=120,MAX_CANCEL_REASON_CHARS=200,CANCEL_PROBE_BUDGET_MS=2000,CANCEL_ABORT_BUDGET_MS=2000,CANCEL_TOTAL_BUDGET_MS=30000,CancelLaneBatchArgsSchema=exports_external.object({batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS),reason:exports_external.string().trim().min(1).max(MAX_CANCEL_REASON_CHARS).describe("Bounded operator reason recorded on every cancelled lane terminal"),confirm:exports_external.literal(!0).describe("Explicit confirmation: cancellation is destructive and authorized by the operator"),lanes:exports_external.array(exports_external.string().min(1).max(128)).max(64).optional().describe("Optional lane-id filter; default is every active lane")}).strict(),_internals260={getSessionOps:()=>swarmState.opencodeClient?.session??null,now:()=>Date.now(),probeBudgetMs:CANCEL_PROBE_BUDGET_MS,abortBudgetMs:CANCEL_ABORT_BUDGET_MS,totalBudgetMs:CANCEL_TOTAL_BUDGET_MS},LIVE_NEXT_ACTION="lane is live (busy/retry): wait for it to finish or poll again; live work can only be ended by the human force path (/swarm abort-pr-workflow)",DEGRADED_NEXT_ACTION="observer degraded: poll again with collect_lane_results; an observer failure never authorizes cancellation",NO_CLIENT_NEXT_ACTION="host status client unavailable: cancellation needs positive liveness evidence; use the human force path (/swarm abort-pr-workflow) for an unrecoverable orphan";async function raceWithBudget(op,budgetMs){if(budgetMs<=0)return{kind:"timeout"};let startedAt=_internals260.now(),timedOut=!1,timer,deadline=new Promise((resolve125)=>{timer=setTimeout(()=>{timedOut=!0,resolve125("timeout")},budgetMs)}),guarded=op().then((value)=>({kind:"ok",value}),()=>({kind:"error"}));try{let raced=await Promise.race([guarded,deadline]);if(raced==="timeout")return{kind:"timeout"};if(timedOut||_internals260.now()-startedAt>=budgetMs)return{kind:"timeout"};return raced}finally{if(timer)clearTimeout(timer)}}async function probeBatchStatus(session,directory){if(typeof session.status!=="function")return{kind:"degraded",reason:"probe-unavailable"};let outcome=await raceWithBudget(()=>session.status({query:{directory}}),_internals260.probeBudgetMs);if(outcome.kind==="timeout")return{kind:"degraded",reason:"probe-timeout"};if(outcome.kind==="error")return{kind:"degraded",reason:"probe-error"};let response=outcome.value;if(response.error||!response.data)return{kind:"degraded",reason:"probe-no-data"};return{kind:"ok",map:response.data}}async function boundedAbort(session,subagentSessionId,budgetMs){if(typeof session.abort!=="function")return"error";return(await raceWithBudget(()=>session.abort({path:{id:subagentSessionId}}),budgetMs)).kind}function emptyDigest(){return createHash103("sha256").update("").digest("hex")}async function executeCancelLaneBatch(args2,directory,context={}){let parsed=CancelLaneBatchArgsSchema.safeParse(args2);if(!parsed.success)return{success:!1,failure_class:"invalid_args",message:`Invalid cancel_lane_batch arguments: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`,batch_id:"",total_active:0,cancelled:0,refused:[],preserved_completions:[],already_settled:[],errors:[]};let{batch_id,lanes}=parsed.data,reason=stripControlCharacters(parsed.data.reason),batchFilter=context.sessionID?{parentSessionId:context.sessionID}:void 0,batchRead=findByBatchIdDetailed(directory,batch_id,batchFilter);if(batchRead.status==="uncertain")return{success:!1,failure_class:"store_unreadable",message:`cancel_lane_batch refused: delegation store unreadable (${batchRead.reason})`,batch_id,total_active:0,cancelled:0,refused:[],preserved_completions:[],already_settled:[],errors:[]};if(batchRead.value.length===0)return{success:!1,failure_class:"not_found",message:`cancel_lane_batch: no delegation records for batch "${batch_id}"`,batch_id,total_active:0,cancelled:0,refused:[],preserved_completions:[],already_settled:[],errors:[]};let laneFilter=lanes?new Set(lanes):null,activeRecords=batchRead.value.filter((record3)=>(record3.status==="pending"||record3.status==="running")&&(!laneFilter||record3.laneId!==void 0&&laneFilter.has(record3.laneId))),result={success:!0,batch_id,total_active:activeRecords.length,cancelled:0,refused:[],preserved_completions:[],already_settled:[],errors:[]};if(activeRecords.length===0)return result.message="cancel_lane_batch: no active (pending/running) lanes matched",result;let session=_internals260.getSessionOps();if(!session){for(let record3 of activeRecords)result.refused.push({lane_id:record3.laneId??record3.correlationId,degraded_reason:"probe-unavailable",next_action:NO_CLIENT_NEXT_ACTION});return result.success=!1,result.failure_class="no_client",result.message="cancel_lane_batch refused: no host session client for a liveness preflight",result}let probe2=await probeBatchStatus(session,directory);if(probe2.kind==="degraded")return result.success=!1,result.failure_class="probe_degraded",result.message=`cancel_lane_batch refused: liveness probe degraded (${probe2.reason}); no lane was aborted or settled; ${DEGRADED_NEXT_ACTION}`,result;let totalDeadline=_internals260.now()+_internals260.totalBudgetMs,unprocessed=0;for(let record3 of activeRecords){let laneId=record3.laneId??record3.correlationId,sessionEntry=record3.subagentSessionId?probe2.map[record3.subagentSessionId]:void 0;if(sessionEntry===void 0);else{let type=sessionEntry.type;if(type==="busy"||type==="retry"){result.refused.push({lane_id:laneId,host_status:type,next_action:LIVE_NEXT_ACTION});continue}if(type!=="idle"){result.refused.push({lane_id:laneId,host_status:type??"unknown",next_action:"unrecognized host status type: refused fail-closed; poll again before cancelling"});continue}}let reread=findByCorrelationIdDetailed(directory,record3.correlationId);if(reread.status==="uncertain"){result.errors.push(`lane ${laneId}: store unreadable (${reread.reason}); not cancelled`),unprocessed+=1;continue}let current=reread.value;if(!current){result.already_settled.push(laneId);continue}if(current.status!=="pending"&&current.status!=="running"){result.already_settled.push(laneId);continue}if(current.generation!==void 0&&record3.generation!==void 0&&current.generation!==record3.generation){result.refused.push({lane_id:laneId,degraded_reason:"identity-changed",next_action:"lane generation changed since the batch read: re-issue cancel_lane_batch"});continue}let remainingMs2=totalDeadline-_internals260.now();if(remainingMs2<=0){result.errors.push(`lane ${laneId}: cancel_lane_batch total budget exhausted before abort`),unprocessed+=1;continue}let abortOutcome=await boundedAbort(session,current.subagentSessionId,Math.min(_internals260.abortBudgetMs,remainingMs2));if(abortOutcome==="timeout"){result.errors.push(`session.abort for lane session "${current.subagentSessionId}" exceeded the bounded cancel budget; lane left pending`),unprocessed+=1;continue}if(abortOutcome==="error")result.errors.push(`session.abort for lane session "${current.subagentSessionId}" failed; the best-effort exactly-once settle still runs`);let afterRead=findByCorrelationIdDetailed(directory,record3.correlationId);if(afterRead.status==="uncertain"){result.errors.push(`lane ${laneId}: store unreadable after abort (${afterRead.reason}); not settled by this call`),unprocessed+=1;continue}let after=afterRead.value;if(after&&after.status!=="pending"&&after.status!=="running"){if(after.status==="completed")result.preserved_completions.push(laneId);else result.already_settled.push(laneId);continue}if((await settleDelegationTerminal(directory,after??current,{status:"cancelled",result:{error:`lane cancelled via cancel_lane_batch: ${reason}`,chars:0,truncated:!1,digest:emptyDigest(),workflowLaneFailureClass:"operator_cancelled"}},{},_internals260.now())).kind==="claimed")result.cancelled+=1;else result.already_settled.push(laneId)}let tail2=unprocessed>0?`; ${unprocessed} not processed (see errors[])`:"";return result.message=result.cancelled>0?`cancel_lane_batch: ${result.cancelled} lane(s) cancelled (operator_cancelled); ${result.refused.length} refused; ${result.preserved_completions.length} preserved completions${tail2}`:`cancel_lane_batch: no lanes cancelled; ${result.refused.length} refused, ${result.already_settled.length} already settled, ${result.preserved_completions.length} preserved completions${tail2}`,result}var cancel_lane_batch=createSwarmTool({description:"Cancel ACTIVE lanes of a dispatch_lanes_async batch — the ONLY cancellation surface; collect_lane_results cannot cancel. DESTRUCTIVE and authorization-gated: requires confirm: true plus a bounded reason, recorded on every cancelled lane terminal as the distinct operator_cancelled failure class (never liveness). Race-safe per lane: a fresh liveness snapshot REFUSES busy/retry lanes (live work is never destroyed here — the human force path is /swarm abort-pr-workflow); a degraded/absent status probe refuses the whole batch fail-closed; a session the host does not know or reports idle may be cancelled; a child completing between preflight and abort wins; an abort timeout never claims cancellation. Terminal and exactly-once; operator-cancelled dimensions are not auto-retryable and never consume the retry budget — re-dispatch explicitly.",args:{batch_id:CancelLaneBatchArgsSchema.shape.batch_id,reason:CancelLaneBatchArgsSchema.shape.reason,confirm:CancelLaneBatchArgsSchema.shape.confirm,lanes:CancelLaneBatchArgsSchema.shape.lanes},execute:async(args2,directory,ctx)=>{let context=ctx,result=await executeCancelLaneBatch(args2,directory,{sessionID:context&&typeof context.sessionID==="string"?context.sessionID:void 0});return JSON.stringify(result,null,2)}});init_zod();init_config();init_manager2();init_gate_evidence();import*as fs182 from"node:fs";import*as path317 from"node:path";var TODO_GATE_DEFAULTS={enabled:!0,max_high_priority:0,block_on_threshold:!1};function formatDetails(details,count){if(!details||details.length===0)return"";let lines=details.map((line)=>` - ${line}`).join(`
7566
+ `);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 proc=_internals258.bunSpawn([...cmd,...args2],{cwd:command.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:DEFAULT_TIMEOUT_MS4,maxBuffer:DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES});try{let[exitCode,stdout,stderr]=await Promise.all([proc.exited,proc.stdout.text(),proc.stderr.text()]),duration_ms=Date.now()-startTime,spawnErrorMessage=proc.spawnError?.message;return{kind,command:command.command,cwd:command.cwd,exit_code:exitCode??-1,duration_ms,stdout_tail:truncateOutput(stdout),stderr_tail:truncateOutput(stderr),...spawnErrorMessage?{spawn_error:truncateOutput(spawnErrorMessage)}:{}}}finally{try{proc.kill()}catch{}}}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,environmentUnavailable=discoveryResult.skipped.filter((skip)=>skip.code==="environment_unavailable");if(runs.length===0)if(verdict=environmentUnavailable.length>0?"skip":"info",discoveryResult.skipped.length>0)skipped_reason=discoveryResult.skipped.map((s)=>`${s.ecosystem}: ${s.reason}`).join("; ");else skipped_reason=NO_BUILD_FILES_DISCOVERED_REASON;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,environment_unavailable:environmentUnavailable.length>0?environmentUnavailable:void 0}}}var build_check=createSwarmTool({allowWorkingDirectoryOverride:!0,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){if(_internals258.loadGateOverrides(directory)?.build_check?.enabled===!1)return JSON.stringify({verdict:"skip",runs:[],summary:{files_scanned:0,runs_count:0,failed_count:0,skipped_reason:"build_check disabled by configuration"}},null,2);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,environment_unavailable:result.summary.environment_unavailable};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_delegation_lifecycle();init_pending_delegations();init_state2();init_create_tool();import{createHash as createHash103}from"node:crypto";var MAX_BATCH_ID_CHARS=120,MAX_CANCEL_REASON_CHARS=200,CANCEL_PROBE_BUDGET_MS=2000,CANCEL_ABORT_BUDGET_MS=2000,CANCEL_TOTAL_BUDGET_MS=30000,CancelLaneBatchArgsSchema=exports_external.object({batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS),reason:exports_external.string().trim().min(1).max(MAX_CANCEL_REASON_CHARS).describe("Bounded operator reason recorded on every cancelled lane terminal"),confirm:exports_external.literal(!0).describe("Explicit confirmation: cancellation is destructive and authorized by the operator"),lanes:exports_external.array(exports_external.string().min(1).max(128)).max(64).optional().describe("Optional lane-id filter; default is every active lane")}).strict(),_internals260={getSessionOps:()=>swarmState.opencodeClient?.session??null,now:()=>Date.now(),probeBudgetMs:CANCEL_PROBE_BUDGET_MS,abortBudgetMs:CANCEL_ABORT_BUDGET_MS,totalBudgetMs:CANCEL_TOTAL_BUDGET_MS},LIVE_NEXT_ACTION="lane is live (busy/retry): wait for it to finish or poll again; live work can only be ended by the human force path (/swarm abort-pr-workflow)",DEGRADED_NEXT_ACTION="observer degraded: poll again with collect_lane_results; an observer failure never authorizes cancellation",NO_CLIENT_NEXT_ACTION="host status client unavailable: cancellation needs positive liveness evidence; use the human force path (/swarm abort-pr-workflow) for an unrecoverable orphan";async function raceWithBudget(op,budgetMs){if(budgetMs<=0)return{kind:"timeout"};let startedAt=_internals260.now(),timedOut=!1,timer,deadline=new Promise((resolve125)=>{timer=setTimeout(()=>{timedOut=!0,resolve125("timeout")},budgetMs)}),guarded=op().then((value)=>({kind:"ok",value}),()=>({kind:"error"}));try{let raced=await Promise.race([guarded,deadline]);if(raced==="timeout")return{kind:"timeout"};if(timedOut||_internals260.now()-startedAt>=budgetMs)return{kind:"timeout"};return raced}finally{if(timer)clearTimeout(timer)}}async function probeBatchStatus(session,directory){if(typeof session.status!=="function")return{kind:"degraded",reason:"probe-unavailable"};let outcome=await raceWithBudget(()=>session.status({query:{directory}}),_internals260.probeBudgetMs);if(outcome.kind==="timeout")return{kind:"degraded",reason:"probe-timeout"};if(outcome.kind==="error")return{kind:"degraded",reason:"probe-error"};let response=outcome.value;if(response.error||!response.data)return{kind:"degraded",reason:"probe-no-data"};return{kind:"ok",map:response.data}}async function boundedAbort(session,subagentSessionId,budgetMs){if(typeof session.abort!=="function")return"error";return(await raceWithBudget(()=>session.abort({path:{id:subagentSessionId}}),budgetMs)).kind}function emptyDigest(){return createHash103("sha256").update("").digest("hex")}async function executeCancelLaneBatch(args2,directory,context={}){let parsed=CancelLaneBatchArgsSchema.safeParse(args2);if(!parsed.success)return{success:!1,failure_class:"invalid_args",message:`Invalid cancel_lane_batch arguments: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`,batch_id:"",total_active:0,cancelled:0,refused:[],preserved_completions:[],already_settled:[],errors:[]};let{batch_id,lanes}=parsed.data,reason=stripControlCharacters(parsed.data.reason),batchFilter=context.sessionID?{parentSessionId:context.sessionID}:void 0,batchRead=findByBatchIdDetailed(directory,batch_id,batchFilter);if(batchRead.status==="uncertain")return{success:!1,failure_class:"store_unreadable",message:`cancel_lane_batch refused: delegation store unreadable (${batchRead.reason})`,batch_id,total_active:0,cancelled:0,refused:[],preserved_completions:[],already_settled:[],errors:[]};if(batchRead.value.length===0)return{success:!1,failure_class:"not_found",message:`cancel_lane_batch: no delegation records for batch "${batch_id}"`,batch_id,total_active:0,cancelled:0,refused:[],preserved_completions:[],already_settled:[],errors:[]};let laneFilter=lanes?new Set(lanes):null,activeRecords=batchRead.value.filter((record3)=>(record3.status==="pending"||record3.status==="running")&&(!laneFilter||record3.laneId!==void 0&&laneFilter.has(record3.laneId))),result={success:!0,batch_id,total_active:activeRecords.length,cancelled:0,refused:[],preserved_completions:[],already_settled:[],errors:[]};if(activeRecords.length===0)return result.message="cancel_lane_batch: no active (pending/running) lanes matched",result;let session=_internals260.getSessionOps();if(!session){for(let record3 of activeRecords)result.refused.push({lane_id:record3.laneId??record3.correlationId,degraded_reason:"probe-unavailable",next_action:NO_CLIENT_NEXT_ACTION});return result.success=!1,result.failure_class="no_client",result.message="cancel_lane_batch refused: no host session client for a liveness preflight",result}let probe2=await probeBatchStatus(session,directory);if(probe2.kind==="degraded")return result.success=!1,result.failure_class="probe_degraded",result.message=`cancel_lane_batch refused: liveness probe degraded (${probe2.reason}); no lane was aborted or settled; ${DEGRADED_NEXT_ACTION}`,result;let totalDeadline=_internals260.now()+_internals260.totalBudgetMs,unprocessed=0;for(let record3 of activeRecords){let laneId=record3.laneId??record3.correlationId,sessionEntry=record3.subagentSessionId?probe2.map[record3.subagentSessionId]:void 0;if(sessionEntry===void 0);else{let type=sessionEntry.type;if(type==="busy"||type==="retry"){result.refused.push({lane_id:laneId,host_status:type,next_action:LIVE_NEXT_ACTION});continue}if(type!=="idle"){result.refused.push({lane_id:laneId,host_status:type??"unknown",next_action:"unrecognized host status type: refused fail-closed; poll again before cancelling"});continue}}let reread=findByCorrelationIdDetailed(directory,record3.correlationId);if(reread.status==="uncertain"){result.errors.push(`lane ${laneId}: store unreadable (${reread.reason}); not cancelled`),unprocessed+=1;continue}let current=reread.value;if(!current){result.already_settled.push(laneId);continue}if(current.status!=="pending"&&current.status!=="running"){result.already_settled.push(laneId);continue}if(current.generation!==void 0&&record3.generation!==void 0&&current.generation!==record3.generation){result.refused.push({lane_id:laneId,degraded_reason:"identity-changed",next_action:"lane generation changed since the batch read: re-issue cancel_lane_batch"});continue}let remainingMs2=totalDeadline-_internals260.now();if(remainingMs2<=0){result.errors.push(`lane ${laneId}: cancel_lane_batch total budget exhausted before abort`),unprocessed+=1;continue}let abortOutcome=await boundedAbort(session,current.subagentSessionId,Math.min(_internals260.abortBudgetMs,remainingMs2));if(abortOutcome==="timeout"){result.errors.push(`session.abort for lane session "${current.subagentSessionId}" exceeded the bounded cancel budget; lane left pending`),unprocessed+=1;continue}if(abortOutcome==="error")result.errors.push(`session.abort for lane session "${current.subagentSessionId}" failed; the best-effort exactly-once settle still runs`);let afterRead=findByCorrelationIdDetailed(directory,record3.correlationId);if(afterRead.status==="uncertain"){result.errors.push(`lane ${laneId}: store unreadable after abort (${afterRead.reason}); not settled by this call`),unprocessed+=1;continue}let after=afterRead.value;if(after&&after.status!=="pending"&&after.status!=="running"){if(after.status==="completed")result.preserved_completions.push(laneId);else result.already_settled.push(laneId);continue}if((await settleDelegationTerminal(directory,after??current,{status:"cancelled",result:{error:`lane cancelled via cancel_lane_batch: ${reason}`,chars:0,truncated:!1,digest:emptyDigest(),workflowLaneFailureClass:"operator_cancelled"}},{},_internals260.now())).kind==="claimed")result.cancelled+=1;else result.already_settled.push(laneId)}let tail2=unprocessed>0?`; ${unprocessed} not processed (see errors[])`:"";return result.message=result.cancelled>0?`cancel_lane_batch: ${result.cancelled} lane(s) cancelled (operator_cancelled); ${result.refused.length} refused; ${result.preserved_completions.length} preserved completions${tail2}`:`cancel_lane_batch: no lanes cancelled; ${result.refused.length} refused, ${result.already_settled.length} already settled, ${result.preserved_completions.length} preserved completions${tail2}`,result}var cancel_lane_batch=createSwarmTool({description:"Cancel ACTIVE lanes of a dispatch_lanes_async batch — the ONLY cancellation surface; collect_lane_results cannot cancel. DESTRUCTIVE and authorization-gated: requires confirm: true plus a bounded reason, recorded on every cancelled lane terminal as the distinct operator_cancelled failure class (never liveness). Race-safe per lane: a fresh liveness snapshot REFUSES busy/retry lanes (live work is never destroyed here — the human force path is /swarm abort-pr-workflow); a degraded/absent status probe refuses the whole batch fail-closed; a session the host does not know or reports idle may be cancelled; a child completing between preflight and abort wins; an abort timeout never claims cancellation. Terminal and exactly-once; operator-cancelled dimensions are not auto-retryable and never consume the retry budget — re-dispatch explicitly.",args:{batch_id:CancelLaneBatchArgsSchema.shape.batch_id,reason:CancelLaneBatchArgsSchema.shape.reason,confirm:CancelLaneBatchArgsSchema.shape.confirm,lanes:CancelLaneBatchArgsSchema.shape.lanes},execute:async(args2,directory,ctx)=>{let context=ctx,result=await executeCancelLaneBatch(args2,directory,{sessionID:context&&typeof context.sessionID==="string"?context.sessionID:void 0});return JSON.stringify(result,null,2)}});init_zod();init_config();init_manager2();init_gate_evidence();import*as fs182 from"node:fs";import*as path317 from"node:path";var TODO_GATE_DEFAULTS={enabled:!0,max_high_priority:0,block_on_threshold:!1};function formatDetails(details,count){if(!details||details.length===0)return"";let lines=details.map((line)=>` - ${line}`).join(`
7567
7567
  `);return details.length<count?`${lines}
7568
7568
  (showing first ${details.length} of ${count})`:lines}function repairStep(){return"Repair: resolve or remove the high-priority TODO comments listed above, or adjust the todo_gate config (raise max_high_priority / set enabled: false), then re-run todo_extract with the same task_id to refresh the recorded evidence."}function isTodoThresholdExceeded(count,maxHighPriority){return maxHighPriority>=0&&count>maxHighPriority}function evaluateTodoGate(todoScan,todoGate){let enabled=todoGate?.enabled??TODO_GATE_DEFAULTS.enabled,max=todoGate?.max_high_priority??TODO_GATE_DEFAULTS.max_high_priority,blockOnThreshold=todoGate?.block_on_threshold??TODO_GATE_DEFAULTS.block_on_threshold;if(enabled===!1)return{status:"disabled",blocked:!1,advisory:!1,count:0,max};if(!todoScan)return{status:"no-evidence",blocked:!1,advisory:!1,count:0,max};let count=todoScan.count;if(!isTodoThresholdExceeded(count,max))return{status:"pass",blocked:!1,advisory:!1,count,max};let evidence2=formatDetails(todoScan.details,count),summary=`todo_gate: ${count} high-priority TODOs (FIXME/HACK/XXX) exceed max_high_priority=${max}.${evidence2?`
7569
7569
  Evidence:
@@ -7750,12 +7750,12 @@ Regenerated on: save_plan and phase_complete.
7750
7750
  `;_fsInternals.writeFileSync(mdPath,header+md)}catch(error93){log(`[checkpoint] Failed to write SWARM_PLAN checkpoint: ${error93 instanceof Error?error93.message:String(error93)}`)}}init_ledger();init_manager();init_curator_llm_factory();init_zod();init_config2();init_curator_decision_helpers();function computeDecayExpiry(memory,halfLifeDays,_now=new Date){if(memory.kind==="scratch")return;let halfLife=halfLifeDays[memory.kind]??0;if(halfLife<=0)return;let created=Date.parse(memory.createdAt);if(!Number.isFinite(created))return;let candidateMs=created+halfLife*86400000,existing=memory.expiresAt?Date.parse(memory.expiresAt):void 0;if(existing!==void 0&&Number.isFinite(existing)&&existing<=candidateMs)return;let candidate2=new Date(candidateMs).toISOString();if(memory.expiresAt===candidate2)return;return candidate2}function isPastDecayHorizon(memory,halfLifeDays,now2=new Date){if(memory.kind==="scratch")return!1;let halfLife=halfLifeDays[memory.kind]??0;if(halfLife<=0)return!1;let created=Date.parse(memory.createdAt);if(!Number.isFinite(created))return!1;return created+halfLife*86400000<=now2.getTime()}init_scoring();init_sentinel();var CONSOLIDATION_AGENT_ROLE="curator_consolidation",DistilledFactSchema=exports_external.object({text:exports_external.string().min(1).max(2000),kind:exports_external.enum(["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"]),confidence:exports_external.number().min(0).max(1),contradictsMemoryId:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional()}),DistillationOutputSchema=exports_external.object({facts:exports_external.array(DistilledFactSchema).max(50)});function parseDistillationOutput(raw){let candidates=[],fenceMatch=raw.match(/```(?:json)?\s*([\s\S]*?)```/i);if(fenceMatch?.[1])candidates.push(fenceMatch[1].trim());let firstBrace=raw.indexOf("{"),lastBrace=raw.lastIndexOf("}");if(firstBrace!==-1&&lastBrace>firstBrace)candidates.push(raw.slice(firstBrace,lastBrace+1));candidates.push(raw.trim());for(let candidate2 of candidates)try{return DistillationOutputSchema.parse(JSON.parse(candidate2)).facts}catch{}return[]}function deriveDecision(fact,existing,options){if(fact.text.includes(MEMORY_RECALL_SENTINEL))return{type:"skip",fact,reason:"contains recall sentinel"};if(fact.text.includes("bundle_"))return{type:"skip",fact,reason:"contains recall bundle marker prefix"};if(fact.kind==="scratch")return{type:"skip",fact,reason:"scratch is not promoted to semantic memory"};let eligible=DURABLE_MEMORY_KINDS.has(fact.kind)&&fact.text.length<=CURATOR_PROMOTED_MEMORY_MAX_TEXT_LENGTH&&fact.confidence>=options.autoApplyMinConfidence,factTokens=tokenize(fact.text);for(let memory of existing)if(jaccard(factTokens,tokenize(memory.text))>=options.jaccardThreshold)return{type:"dedup",fact,duplicateOf:memory.id};if(fact.contradictsMemoryId){let target=existing.find((m)=>m.id===fact.contradictsMemoryId);if(target&&eligible)return{type:"supersede",fact,oldMemoryId:target.id};return{type:"proposal",fact,reason:target?"contradiction not auto-appliable (kind/length/confidence)":"contradiction target not found"}}if(!eligible){let reason=!DURABLE_MEMORY_KINDS.has(fact.kind)?`kind ${fact.kind} is not auto-promotable`:fact.text.length>CURATOR_PROMOTED_MEMORY_MAX_TEXT_LENGTH?"text exceeds promotable length":"confidence below auto-apply threshold";return{type:"proposal",fact,reason}}return{type:"add",fact}}function hasRealEvidence(evidenceRefs){return evidenceRefs.some((r)=>/^https?:\/\//i.test(r)||/^[a-f0-9]{40}$/i.test(r)||r.includes("/")||r.includes("\\"))}function sourceForDistilled(evidenceRefs,phaseNumber){let url3=evidenceRefs.find((r)=>/^https?:\/\//i.test(r));if(url3)return{type:"web",url:url3,createdBy:"curator_consolidation"};let file3=evidenceRefs.find((r)=>r.includes("/")||r.includes("\\"));if(file3)return{type:"file",filePath:file3,createdBy:"curator_consolidation"};return{type:"agent",ref:`consolidation:phase-${phaseNumber}`,createdBy:"curator_consolidation"}}function buildDistillationPrompt(cluster,relatedExisting){let episodic=cluster.map((p,i)=>{let text=p.proposedRecord?.text??p.rationale;return`[E${i+1}] kind=${p.proposedRecord?.kind??"n/a"} | ${text}`}).join(`
7751
7751
  `),existing=relatedExisting.slice(0,20).map((m)=>`[${m.id}] kind=${m.kind} | ${m.text}`).join(`
7752
7752
  `);return["You are consolidating raw episodic memory into durable semantic facts.","","Episodic events (verbatim):",episodic,"","Existing durable memories (for dedup/contradiction):",existing||"(none)","",'Emit STRICT JSON only: {"facts":[{"text":..,"kind":..,"confidence":0-1,"contradictsMemoryId"?:"mem_..."}]}',"Rules: only emit facts directly supported by the cited episodic evidence.","If uncertain, omit the fact (emit fewer facts or an empty array).",`Use durable kinds (${Array.from(DURABLE_MEMORY_KINDS).join(", ")}); keep each fact under ${CURATOR_PROMOTED_MEMORY_MAX_TEXT_LENGTH} characters.`,"Set contradictsMemoryId only when a fact directly conflicts with an existing memory above.",'Never include the literal text "## Retrieved Swarm Memory".'].join(`
7753
- `)}function aggregateEvidence(cluster,phaseNumber){let refs=new Set;for(let p of cluster)for(let ref of p.evidenceRefs)refs.add(ref);let list=Array.from(refs).slice(0,19);return list.push(`consolidation:phase-${phaseNumber}`),list}async function runConsolidationPass(input,deps){let{phaseNumber,runId,config:config3}=input,consolidation=config3.consolidation,base={skipped:!0,phaseNumber,clusterCount:0,clustersDeferred:0,decisionsEmitted:0,added:0,superseded:0,contradictionsDetected:0,deduped:0,proposed:0,memoriesDecayed:0,errored:0};if(!config3.enabled||!consolidation.enabled||!deps.gateway.isEnabled())return{...base,skipReason:"disabled"};let priorLog=await deps.readLog();if(priorLog.some((r)=>r.phaseNumber===phaseNumber))return{...base,skipReason:"already_consolidated"};let processedBefore=new Set(priorLog.flatMap((r)=>r.processedProposalIds)),startedAt=deps.now().toISOString(),logKey=runId??"unknown";await deps.logEvent({event:"consolidation_started",runId:logKey,phaseNumber,timestamp:startedAt});let pendingProposals=(await deps.gateway.listProposals({status:"pending"})).filter((p)=>p.proposedBy?.agentRole!==CONSOLIDATION_AGENT_ROLE&&!processedBefore.has(p.id)).sort((a,b)=>a.id.localeCompare(b.id)),deadAnchorMemoryIds=deps.readDeadAnchorMemoryIds?.()??new Set,existingMemories=(await deps.gateway.listMemories({})).filter((memory)=>!deadAnchorMemoryIds.has(memory.id)),clusters=clusterByJaccard(pendingProposals,(p)=>p.proposedRecord?.text??p.rationale,consolidation.jaccardThreshold),processable=clusters.slice(0,consolidation.maxClustersPerPass),clustersDeferred=Math.max(0,clusters.length-processable.length);await deps.logEvent({event:"cluster_count",runId:logKey,phaseNumber,clusterCount:clusters.length});let result={...base,skipped:!1,clusterCount:clusters.length,clustersDeferred},processedProposalIds=new Set;if(!deps.llmDelegate){if(result.memoriesDecayed=await applyDecay(existingMemories,input,deps),deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};return await finalize2(input,deps,result,startedAt,processedProposalIds),{...result,skipReason:"no_llm_delegate_decay_only"}}let seenFactTexts=new Set;for(let cluster of processable){if(deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};for(let p of cluster)processedProposalIds.add(p.id);let raw;try{let prompt=buildDistillationPrompt(cluster,existingMemories);raw=await deps.llmDelegate("",prompt,deps.signal)}catch{result.errored++;continue}let facts=parseDistillationOutput(raw),evidenceRefs=aggregateEvidence(cluster,phaseNumber);for(let fact of facts){let normalized=fact.text.replace(/\s+/g," ").trim().toLowerCase();if(seenFactTexts.has(normalized))continue;seenFactTexts.add(normalized);let plan=deriveDecision(fact,existingMemories,{autoApplyMinConfidence:consolidation.autoApplyMinConfidence,jaccardThreshold:consolidation.jaccardThreshold});try{await executePlan(plan,evidenceRefs,input,deps,result)}catch{result.errored++}}}if(deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};if(result.memoriesDecayed=await applyDecay(existingMemories,input,deps),deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};return await finalize2(input,deps,result,startedAt,processedProposalIds),result}async function executePlan(plan,evidenceRefs,input,deps,result){let{phaseNumber}=input;if(plan.type==="skip")return;if(plan.type==="dedup"){result.deduped++;return}let newRecord={kind:plan.fact.kind,text:plan.fact.text,confidence:plan.fact.confidence,stability:"durable",source:sourceForDistilled(evidenceRefs,phaseNumber),metadata:{consolidatedFromPhase:phaseNumber}},rationale=`consolidation phase ${phaseNumber}`;if(((plan.type==="add"||plan.type==="supersede")&&EVIDENCE_REQUIRED_KINDS.has(plan.fact.kind)&&!hasRealEvidence(evidenceRefs)?"proposal":plan.type)==="proposal"){await deps.gateway.propose({operation:plan.type==="supersede"?"supersede":"add",kind:plan.fact.kind,text:plan.fact.text,rationale:plan.type==="proposal"?`${rationale}: ${plan.reason}`:`${rationale}: evidence-required kind lacks real evidence source`,evidenceRefs,...plan.type==="supersede"?{targetMemoryId:plan.oldMemoryId}:{}}),result.proposed++;return}if(plan.type==="supersede"){let proposal2=await deps.gateway.propose({operation:"supersede",kind:plan.fact.kind,text:plan.fact.text,targetMemoryId:plan.oldMemoryId,rationale,evidenceRefs});if(proposal2.status!=="pending"){result.proposed++;return}await deps.gateway.applyCuratorDecision({action:"supersede",proposalId:proposal2.id,oldMemoryId:plan.oldMemoryId,replacement:newRecord,reason:`contradiction superseded during phase ${phaseNumber} consolidation`}),result.superseded++,result.contradictionsDetected++,result.decisionsEmitted++;return}let proposal=await deps.gateway.propose({operation:"add",kind:plan.fact.kind,text:plan.fact.text,rationale,evidenceRefs});if(proposal.status!=="pending"){result.proposed++;return}await deps.gateway.applyCuratorDecision({action:"add",proposalId:proposal.id,memory:newRecord}),result.added++,result.decisionsEmitted++}async function applyDecay(memories,input,deps){let decayed=0,halfLives=input.config.consolidation.decayHalfLifeDays,now2=deps.now();for(let memory of memories){if(deps.signal?.aborted)break;if(memory.metadata.deleted===!0||memory.supersededBy)continue;if(isPastDecayHorizon(memory,halfLives,now2))continue;let nextExpiry=computeDecayExpiry(memory,halfLives,now2);if(!nextExpiry)continue;try{await deps.gateway.upsertCurated({...memory,expiresAt:nextExpiry}),decayed++}catch{}}return decayed}async function finalize2(input,deps,result,startedAt,processedProposalIds){let{phaseNumber,runId}=input,logKey=runId??"unknown",completedAt=deps.now().toISOString();await deps.logEvent({event:"decisions_emitted",runId:logKey,phaseNumber,decisionsEmitted:result.decisionsEmitted}),await deps.logEvent({event:"contradictions_detected",runId:logKey,phaseNumber,contradictionsDetected:result.contradictionsDetected}),await deps.logEvent({event:"memories_decayed",runId:logKey,phaseNumber,memoriesDecayed:result.memoriesDecayed}),await deps.logEvent({event:"consolidation_completed",runId:logKey,phaseNumber,clusterCount:result.clusterCount,decisionsEmitted:result.decisionsEmitted,contradictionsDetected:result.contradictionsDetected,memoriesDecayed:result.memoriesDecayed,timestamp:completedAt}),await deps.appendLog({phaseNumber,runId,startedAt,completedAt,clusterCount:result.clusterCount,clustersDeferred:result.clustersDeferred,decisionsEmitted:result.decisionsEmitted,added:result.added,superseded:result.superseded,contradictionsDetected:result.contradictionsDetected,deduped:result.deduped,proposed:result.proposed,memoriesDecayed:result.memoriesDecayed,errored:result.errored,processedProposalIds:Array.from(processedProposalIds)})}init_consolidation_log();init_gateway();init_reflection_service();init_run_log();init_storage_root();init_canonical_root();var CONSOLIDATION_TIMEOUT_MS=300000,runningByDirectory2=new Map;async function runMemoryConsolidation(req){let key2=canonicalRootKeyFresh(req.directory),existing=runningByDirectory2.get(key2);if(existing)return existing;let run=(async()=>{if(!req.config.enabled||!req.config.consolidation.enabled)return{started:!1,reason:"disabled"};let gateway=createMemoryGateway({directory:req.directory,sessionID:req.sessionId,runId:req.sessionId,agentRole:"curator_consolidation"},{config:req.config}),controller=new AbortController,timer=setTimeout(()=>controller.abort(),CONSOLIDATION_TIMEOUT_MS);timer.unref?.();try{if(!gateway.isEnabled())return{started:!1,reason:"disabled"};let llmDelegate=createCuratorLLMDelegate(req.directory,"consolidation",req.sessionId),result=await runConsolidationPass({directory:req.directory,phaseNumber:req.phase,runId:req.sessionId,config:req.config},{gateway,llmDelegate,now:()=>new Date,logEvent:(event)=>appendMemoryRunLog(req.directory,req.sessionId,event),readLog:()=>readConsolidationLog(resolveVettedMemoryRoot(req.directory,req.config)),appendLog:(record3)=>appendConsolidationLog(resolveVettedMemoryRoot(req.directory,req.config),record3),readDeadAnchorMemoryIds:()=>readDeadAnchorMemoryIds(req.directory),signal:controller.signal});return{started:!result.skipped,reason:result.skipReason,result}}finally{clearTimeout(timer),await gateway.dispose()}})();runningByDirectory2.set(key2,run);try{return await run}finally{if(runningByDirectory2.get(key2)===run)runningByDirectory2.delete(key2)}}function runMemoryConsolidationFireAndForget(req,onComplete,onError){queueMicrotask(()=>{runMemoryConsolidation(req).then(onComplete).catch(onError)})}init_skill_consolidation();init_snapshot_writer();init_state2();init_telemetry();init_state();init_file_locks();import*as fs202 from"node:fs";import*as path340 from"node:path";init_state4();var DEFAULT_CONFIG4={phase_reviewer:!0,phase_critic:!0,integrated_diff_required:!1};function defaultReadPlanJson(dir){try{let planPath=path340.join(dir,".swarm","plan.json");if(!fs202.existsSync(planPath))return null;let raw=fs202.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw);if(typeof plan!=="object"||plan===null||!Array.isArray(plan.phases))return null;return plan}catch{return null}}function readReviewerEvidenceFromFile(directory,phase){try{let evidencePath=path340.join(directory,".swarm","evidence",String(phase),"lean-turbo-reviewer.json");if(!fs202.existsSync(evidencePath))return null;let raw=fs202.readFileSync(evidencePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||typeof parsed.verdict!=="string")return null;let verdict=parsed.verdict;if(verdict!=="APPROVED"&&verdict!=="NEEDS_REVISION"&&verdict!=="REJECTED")return null;return parsed}catch{return null}}function readCriticEvidenceFromFile(directory,phase){try{let evidencePath=path340.join(directory,".swarm","evidence",String(phase),"lean-turbo-critic.json");if(!fs202.existsSync(evidencePath))return null;let raw=fs202.readFileSync(evidencePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||typeof parsed.verdict!=="string")return null;let verdict=parsed.verdict;if(verdict!=="APPROVED"&&verdict!=="NEEDS_REVISION"&&verdict!=="REJECTED"&&verdict!=="ESCALATE_TO_HUMAN")return null;return parsed}catch{return null}}function listLaneEvidenceSync(directory,phase){let evidenceDir=path340.join(directory,".swarm","evidence",String(phase),"lean-turbo"),entries2;try{entries2=fs202.readdirSync(evidenceDir)}catch{return[]}entries2.sort();let laneIds=[];for(let entry of entries2){if(!entry.endsWith(".json")||entry==="lean-turbo-phase.json")continue;laneIds.push(entry.slice(0,-5))}return laneIds}var _internals287={listActiveLocks,readPersisted:readPersisted3,readPlanJson:defaultReadPlanJson,readReviewerEvidence:readReviewerEvidenceFromFile,readCriticEvidence:readCriticEvidenceFromFile,listLaneEvidence,listLaneEvidenceSync,verifyLeanTurboPhaseReady};function validatePersistedShape3(persisted){if(typeof persisted!=="object"||persisted===null)return!1;if(Array.isArray(persisted))return!1;if(typeof persisted.sessions!=="object")return!1;if(persisted.sessions===null)return!1;if(Array.isArray(persisted.sessions))return!1;return!0}function validateLanesArray(lanes){if(!Array.isArray(lanes))return!1;for(let lane of lanes){if(typeof lane!=="object"||lane===null)return!1;if(typeof lane.laneId!=="string")return!1;if(typeof lane.status!=="string")return!1}return!0}function validateDegradedTasksArray(degradedTasks){if(!Array.isArray(degradedTasks))return!1;for(let dt of degradedTasks){if(typeof dt!=="object"||dt===null)return!1;if(typeof dt.taskId!=="string")return!1}return!0}function verifyLeanTurboPhaseReady(directory,phase,sessionIDOrConfig,config3){let sessionID=typeof sessionIDOrConfig==="string"?sessionIDOrConfig:void 0,mergedConfig={...DEFAULT_CONFIG4,...typeof sessionIDOrConfig==="object"&&sessionIDOrConfig!==null?sessionIDOrConfig:config3??DEFAULT_CONFIG4},statePath3=path340.join(directory,".swarm","turbo-state.json");if(!fs202.existsSync(statePath3))return{ok:!1,reason:"Lean Turbo state unreadable or missing"};let persisted=_internals287.readPersisted(directory);if(!persisted)return{ok:!1,reason:"Lean Turbo state unreadable or missing"};if(!validatePersistedShape3(persisted))return{ok:!1,reason:"Lean Turbo state unreadable or missing"};let runState=null;for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"&&sessionState.sessionID===sessionID){runState=sessionState;break}if(!runState&&sessionID===void 0){for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"){runState=sessionState;break}}if(!runState)return{ok:!1,reason:sessionID?`No active Lean Turbo session for phase ${phase} and session ${sessionID}`:`No active Lean Turbo session for phase ${phase}`};if(!validateLanesArray(runState.lanes))return{ok:!1,reason:`No active Lean Turbo session for phase ${phase}`};if(!validateDegradedTasksArray(runState.degradedTasks))return{ok:!1,reason:`No active Lean Turbo session for phase ${phase}`};if(runState.lanes.length===0&&(!Array.isArray(runState.serializedTasks)||runState.serializedTasks.length===0)&&(!Array.isArray(runState.degradedTasks)||runState.degradedTasks.length===0))return{ok:!1,reason:`No lane plan or fallback tasks found for phase ${phase}`};let laneIds=runState.lanes.map((l)=>l.laneId);if(runState.lanes.length>0){for(let lane of runState.lanes)if(lane.status!=="completed"&&lane.status!=="failed")return{ok:!1,reason:`Lane ${lane.laneId} is not completed (status: ${lane.status})`}}if(runState.lanes.length>0){let evidenceLaneIds=new Set(_internals287.listLaneEvidenceSync(directory,phase));for(let lane of runState.lanes)if((lane.status==="completed"||lane.status==="failed")&&!evidenceLaneIds.has(lane.laneId))return{ok:!1,reason:`Lane ${lane.laneId} is ${lane.status} but lane evidence file is missing`}}let activeLocks=_internals287.listActiveLocks(directory),phaseLaneIds=new Set(laneIds);for(let lock of activeLocks)if(lock.laneId&&phaseLaneIds.has(lock.laneId))return{ok:!1,reason:`Active locks remain for lane ${lock.laneId}`};let laneTaskIds=new Set;for(let lane of runState.lanes)if(Array.isArray(lane.taskIds))for(let taskId of lane.taskIds)laneTaskIds.add(taskId);let serialDegradedTasks=runState.degradedTasks.filter((dt)=>!laneTaskIds.has(dt.taskId));if(serialDegradedTasks.length>0){let plan=_internals287.readPlanJson(directory);if(!plan)return{ok:!1,reason:"Cannot verify degraded task status: plan.json unreadable or malformed"};for(let dt of serialDegradedTasks){if(!Array.isArray(plan.phases))return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: plan.json malformed (phases is not an array)`};let planPhase=plan.phases.find((p)=>p&&typeof p==="object"&&p!==null&&p.id===phase);if(!planPhase)return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: phase ${phase} not found in plan.json`};if(!Array.isArray(planPhase.tasks))return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: plan.json malformed (phase ${phase} tasks is not an array)`};let task2=planPhase.tasks.find((t)=>t&&typeof t==="object"&&t!==null&&t.id===dt.taskId);if(!task2)return{ok:!1,reason:`Degraded task ${dt.taskId} not found in plan`};if(task2.status!=="completed")return{ok:!1,reason:`Degraded task ${dt.taskId} not yet completed via standard flow`}}}let serializedTasks=runState.serializedTasks;if(Array.isArray(serializedTasks)&&serializedTasks.length>0){let plan=_internals287.readPlanJson(directory);if(!plan)return{ok:!1,reason:"Cannot verify serialized task status: plan.json unreadable or malformed"};if(!Array.isArray(plan.phases))return{ok:!1,reason:"Cannot verify serialized tasks: plan.json malformed (phases is not an array)"};let planPhase=plan.phases.find((p)=>p&&typeof p==="object"&&p!==null&&p.id===phase);if(!planPhase)return{ok:!1,reason:`Cannot verify serialized tasks: phase ${phase} not found in plan.json`};if(!Array.isArray(planPhase.tasks))return{ok:!1,reason:`Cannot verify serialized tasks: plan.json malformed (phase ${phase} tasks is not an array)`};for(let serTaskId of serializedTasks){let task2=planPhase.tasks.find((t)=>t&&typeof t==="object"&&t!==null&&t.id===serTaskId);if(!task2)return{ok:!1,reason:`Serialized task ${serTaskId} not found in plan`};if(task2.status!=="completed")return{ok:!1,reason:`Serialized task ${serTaskId} not yet completed (status: ${task2.status})`}}}if(mergedConfig.integrated_diff_required){let evidencePath=path340.join(directory,".swarm","evidence",String(phase),"lean-turbo","lean-turbo-phase.json"),hasDiff=!1;try{let content=fs202.readFileSync(evidencePath,"utf-8");hasDiff=!!JSON.parse(content).integratedDiffSummary}catch{}if(!hasDiff)return{ok:!1,reason:`Integrated diff summary is required but missing for phase ${phase}`}}let reviewerVerdict=runState.lastReviewerVerdict;if(!reviewerVerdict)reviewerVerdict=_internals287.readReviewerEvidence(directory,phase)?.verdict??void 0;if(mergedConfig.phase_reviewer){if(reviewerVerdict!=="APPROVED")return{ok:!1,reason:"Integrated reviewer approval missing or rejected"}}let criticVerdict=runState.lastCriticVerdict;if(!criticVerdict)criticVerdict=_internals287.readCriticEvidence(directory,phase)?.verdict??void 0;if(mergedConfig.phase_critic){if(criticVerdict!=="APPROVED")return{ok:!1,reason:"Integrated critic approval missing or rejected"}}return{ok:!0,reason:`Phase ${phase} is ready to advance`,evidence:{lanes:laneIds,degradedTasks:runState.degradedTasks.map((dt)=>dt.taskId),reviewerVerdict:reviewerVerdict??runState.lastReviewerVerdict,criticVerdict:criticVerdict??runState.lastCriticVerdict}}}init_logger();init_create_tool();function resolveCouncilFreshnessMaxAgeMs(config3){let hours=config3?.freshnessMaxAgeHours??24;if(!Number.isFinite(hours)||hours<1)return 86400000;return Math.min(hours,720)*60*60*1000}function evaluateCouncilFreshness(input){if(input.timestampMs===null||!Number.isFinite(input.timestampMs))return{ok:!1,reason:"invalid_timestamp",message:"evidence has a missing or invalid timestamp",recovery:"Re-run the council to generate fresh, timestamped evidence."};if(input.timestampMs>input.nowMs)return{ok:!1,reason:"future_timestamp",message:"evidence timestamp is in the future",recovery:"Re-run the council after the host clock is correct, then resubmit."};if(input.nowMs-input.timestampMs>input.maxAgeMs)return{ok:!1,reason:"stale_evidence",message:`evidence is older than the configured freshness window (${Math.round(input.maxAgeMs/3600000)} hours)`,recovery:"Re-run the council for fresh review."};if(input.mustPostdateMs!==void 0&&input.mustPostdateMs!==null&&Number.isFinite(input.mustPostdateMs)){if(input.mustPostdateMs>input.nowMs)return{ok:!1,reason:"invalid_required_input",message:"a later required input (e.g. the phase retrospective) is timestamped in the future — host clock skew suspected",recovery:"Correct the host clock / fix the skewed timestamp, then re-run the council."};if(input.timestampMs<input.mustPostdateMs)return{ok:!1,reason:"predates_required_input",message:"evidence predates a later required input (e.g. the phase retrospective)",recovery:"Re-run the council after the latest required evidence is available."}}return{ok:!0,message:"evidence is fresh",recovery:""}}function parseTimestampMs(value){if(typeof value!=="string")return null;let parsed=new Date(value).getTime();return Number.isNaN(parsed)?null:parsed}function latestRetroTimestampMsFromBundle(bundle,phase){if(!bundle||typeof bundle!=="object")return null;let raw=bundle,entries2=Array.isArray(raw.entries)?raw.entries:[],timestamps=[parseTimestampMs(raw.created_at),parseTimestampMs(raw.updated_at),...entries2.filter((entry)=>typeof entry==="object"&&entry!==null).filter((entry)=>entry.type==="retrospective"&&entry.phase_number===phase).map((entry)=>parseTimestampMs(entry.timestamp))].filter((timestamp)=>timestamp!==null);return timestamps.length>0?Math.max(...timestamps):null}init_store5();async function runArchitectureSupervisorGate(ctx){let{phase,dir,pluginConfig,agentsDispatched,safeWarn}=ctx,asConfig=pluginConfig.architectural_supervision,summarizeFindings=(findings)=>{if(!Array.isArray(findings)||findings.length===0)return"";let details=findings.map((f)=>f&&typeof f==="object"&&typeof f.description==="string"?f.description:void 0).filter((d)=>Boolean(d));return details.length>0?`
7753
+ `)}function aggregateEvidence(cluster,phaseNumber){let refs=new Set;for(let p of cluster)for(let ref of p.evidenceRefs)refs.add(ref);let list=Array.from(refs).slice(0,19);return list.push(`consolidation:phase-${phaseNumber}`),list}async function runConsolidationPass(input,deps){let{phaseNumber,runId,config:config3}=input,consolidation=config3.consolidation,base={skipped:!0,phaseNumber,clusterCount:0,clustersDeferred:0,decisionsEmitted:0,added:0,superseded:0,contradictionsDetected:0,deduped:0,proposed:0,memoriesDecayed:0,errored:0};if(!config3.enabled||!consolidation.enabled||!deps.gateway.isEnabled())return{...base,skipReason:"disabled"};let priorLog=await deps.readLog();if(priorLog.some((r)=>r.phaseNumber===phaseNumber))return{...base,skipReason:"already_consolidated"};let processedBefore=new Set(priorLog.flatMap((r)=>r.processedProposalIds)),startedAt=deps.now().toISOString(),logKey=runId??"unknown";await deps.logEvent({event:"consolidation_started",runId:logKey,phaseNumber,timestamp:startedAt});let pendingProposals=(await deps.gateway.listProposals({status:"pending"})).filter((p)=>p.proposedBy?.agentRole!==CONSOLIDATION_AGENT_ROLE&&!processedBefore.has(p.id)).sort((a,b)=>a.id.localeCompare(b.id)),deadAnchorMemoryIds=deps.readDeadAnchorMemoryIds?.()??new Set,existingMemories=(await deps.gateway.listMemories({})).filter((memory)=>!deadAnchorMemoryIds.has(memory.id)),clusters=clusterByJaccard(pendingProposals,(p)=>p.proposedRecord?.text??p.rationale,consolidation.jaccardThreshold),processable=clusters.slice(0,consolidation.maxClustersPerPass),clustersDeferred=Math.max(0,clusters.length-processable.length);await deps.logEvent({event:"cluster_count",runId:logKey,phaseNumber,clusterCount:clusters.length});let result={...base,skipped:!1,clusterCount:clusters.length,clustersDeferred},processedProposalIds=new Set;if(!deps.llmDelegate){if(result.memoriesDecayed=await applyDecay(existingMemories,input,deps),deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};return await finalize2(input,deps,result,startedAt,processedProposalIds),{...result,skipReason:"no_llm_delegate_decay_only"}}let seenFactTexts=new Set;for(let cluster of processable){if(deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};for(let p of cluster)processedProposalIds.add(p.id);let raw;try{let prompt=buildDistillationPrompt(cluster,existingMemories);raw=await deps.llmDelegate("",prompt,deps.signal)}catch{result.errored++;continue}let facts=parseDistillationOutput(raw),evidenceRefs=aggregateEvidence(cluster,phaseNumber);for(let fact of facts){let normalized=fact.text.replace(/\s+/g," ").trim().toLowerCase();if(seenFactTexts.has(normalized))continue;seenFactTexts.add(normalized);let plan=deriveDecision(fact,existingMemories,{autoApplyMinConfidence:consolidation.autoApplyMinConfidence,jaccardThreshold:consolidation.jaccardThreshold});try{await executePlan(plan,evidenceRefs,input,deps,result)}catch{result.errored++}}}if(deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};if(result.memoriesDecayed=await applyDecay(existingMemories,input,deps),deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};return await finalize2(input,deps,result,startedAt,processedProposalIds),result}async function executePlan(plan,evidenceRefs,input,deps,result){let{phaseNumber}=input;if(plan.type==="skip")return;if(plan.type==="dedup"){result.deduped++;return}let newRecord={kind:plan.fact.kind,text:plan.fact.text,confidence:plan.fact.confidence,stability:"durable",source:sourceForDistilled(evidenceRefs,phaseNumber),metadata:{consolidatedFromPhase:phaseNumber}},rationale=`consolidation phase ${phaseNumber}`;if(((plan.type==="add"||plan.type==="supersede")&&EVIDENCE_REQUIRED_KINDS.has(plan.fact.kind)&&!hasRealEvidence(evidenceRefs)?"proposal":plan.type)==="proposal"){await deps.gateway.propose({operation:plan.type==="supersede"?"supersede":"add",kind:plan.fact.kind,text:plan.fact.text,rationale:plan.type==="proposal"?`${rationale}: ${plan.reason}`:`${rationale}: evidence-required kind lacks real evidence source`,evidenceRefs,...plan.type==="supersede"?{targetMemoryId:plan.oldMemoryId}:{}}),result.proposed++;return}if(plan.type==="supersede"){let proposal2=await deps.gateway.propose({operation:"supersede",kind:plan.fact.kind,text:plan.fact.text,targetMemoryId:plan.oldMemoryId,rationale,evidenceRefs});if(proposal2.status!=="pending"){result.proposed++;return}await deps.gateway.applyCuratorDecision({action:"supersede",proposalId:proposal2.id,oldMemoryId:plan.oldMemoryId,replacement:newRecord,reason:`contradiction superseded during phase ${phaseNumber} consolidation`}),result.superseded++,result.contradictionsDetected++,result.decisionsEmitted++;return}let proposal=await deps.gateway.propose({operation:"add",kind:plan.fact.kind,text:plan.fact.text,rationale,evidenceRefs});if(proposal.status!=="pending"){result.proposed++;return}await deps.gateway.applyCuratorDecision({action:"add",proposalId:proposal.id,memory:newRecord}),result.added++,result.decisionsEmitted++}async function applyDecay(memories,input,deps){let decayed=0,halfLives=input.config.consolidation.decayHalfLifeDays,now2=deps.now();for(let memory of memories){if(deps.signal?.aborted)break;if(memory.metadata.deleted===!0||memory.supersededBy)continue;if(isPastDecayHorizon(memory,halfLives,now2))continue;let nextExpiry=computeDecayExpiry(memory,halfLives,now2);if(!nextExpiry)continue;try{await deps.gateway.upsertCurated({...memory,expiresAt:nextExpiry}),decayed++}catch{}}return decayed}async function finalize2(input,deps,result,startedAt,processedProposalIds){let{phaseNumber,runId}=input,logKey=runId??"unknown",completedAt=deps.now().toISOString();await deps.logEvent({event:"decisions_emitted",runId:logKey,phaseNumber,decisionsEmitted:result.decisionsEmitted}),await deps.logEvent({event:"contradictions_detected",runId:logKey,phaseNumber,contradictionsDetected:result.contradictionsDetected}),await deps.logEvent({event:"memories_decayed",runId:logKey,phaseNumber,memoriesDecayed:result.memoriesDecayed}),await deps.logEvent({event:"consolidation_completed",runId:logKey,phaseNumber,clusterCount:result.clusterCount,decisionsEmitted:result.decisionsEmitted,contradictionsDetected:result.contradictionsDetected,memoriesDecayed:result.memoriesDecayed,timestamp:completedAt}),await deps.appendLog({phaseNumber,runId,startedAt,completedAt,clusterCount:result.clusterCount,clustersDeferred:result.clustersDeferred,decisionsEmitted:result.decisionsEmitted,added:result.added,superseded:result.superseded,contradictionsDetected:result.contradictionsDetected,deduped:result.deduped,proposed:result.proposed,memoriesDecayed:result.memoriesDecayed,errored:result.errored,processedProposalIds:Array.from(processedProposalIds)})}init_consolidation_log();init_gateway();init_reflection_service();init_run_log();init_storage_root();init_canonical_root();var CONSOLIDATION_TIMEOUT_MS=300000,runningByDirectory2=new Map;async function runMemoryConsolidation(req){let key2=canonicalRootKeyFresh(req.directory),existing=runningByDirectory2.get(key2);if(existing)return existing;let run=(async()=>{if(!req.config.enabled||!req.config.consolidation.enabled)return{started:!1,reason:"disabled"};let gateway=createMemoryGateway({directory:req.directory,sessionID:req.sessionId,runId:req.sessionId,agentRole:"curator_consolidation"},{config:req.config}),controller=new AbortController,timer=setTimeout(()=>controller.abort(),CONSOLIDATION_TIMEOUT_MS);timer.unref?.();try{if(!gateway.isEnabled())return{started:!1,reason:"disabled"};let llmDelegate=createCuratorLLMDelegate(req.directory,"consolidation",req.sessionId),result=await runConsolidationPass({directory:req.directory,phaseNumber:req.phase,runId:req.sessionId,config:req.config},{gateway,llmDelegate,now:()=>new Date,logEvent:(event)=>appendMemoryRunLog(req.directory,req.sessionId,event),readLog:()=>readConsolidationLog(resolveVettedMemoryRoot(req.directory,req.config)),appendLog:(record3)=>appendConsolidationLog(resolveVettedMemoryRoot(req.directory,req.config),record3),readDeadAnchorMemoryIds:()=>readDeadAnchorMemoryIds(req.directory),signal:controller.signal});return{started:!result.skipped,reason:result.skipReason,result}}finally{clearTimeout(timer),await gateway.dispose()}})();runningByDirectory2.set(key2,run);try{return await run}finally{if(runningByDirectory2.get(key2)===run)runningByDirectory2.delete(key2)}}function runMemoryConsolidationFireAndForget(req,onComplete,onError){queueMicrotask(()=>{runMemoryConsolidation(req).then(onComplete).catch(onError)})}init_skill_consolidation();init_snapshot_writer();init_state2();init_telemetry();init_state();init_constants();init_file_locks();import*as fs202 from"node:fs";import*as path340 from"node:path";init_state4();var DEFAULT_CONFIG4=Object.freeze({phase_reviewer:DEFAULT_LEAN_TURBO_CONFIG.phase_reviewer,phase_critic:DEFAULT_LEAN_TURBO_CONFIG.phase_critic,integrated_diff_required:DEFAULT_LEAN_TURBO_CONFIG.integrated_diff_required});function defaultReadPlanJson(dir){try{let planPath=path340.join(dir,".swarm","plan.json");if(!fs202.existsSync(planPath))return null;let raw=fs202.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw);if(typeof plan!=="object"||plan===null||!Array.isArray(plan.phases))return null;return plan}catch{return null}}function readReviewerEvidenceFromFile(directory,phase){try{let evidencePath=path340.join(directory,".swarm","evidence",String(phase),"lean-turbo-reviewer.json");if(!fs202.existsSync(evidencePath))return null;let raw=fs202.readFileSync(evidencePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||typeof parsed.verdict!=="string")return null;let verdict=parsed.verdict;if(verdict!=="APPROVED"&&verdict!=="NEEDS_REVISION"&&verdict!=="REJECTED")return null;return parsed}catch{return null}}function readCriticEvidenceFromFile(directory,phase){try{let evidencePath=path340.join(directory,".swarm","evidence",String(phase),"lean-turbo-critic.json");if(!fs202.existsSync(evidencePath))return null;let raw=fs202.readFileSync(evidencePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||typeof parsed.verdict!=="string")return null;let verdict=parsed.verdict;if(verdict!=="APPROVED"&&verdict!=="NEEDS_REVISION"&&verdict!=="REJECTED"&&verdict!=="ESCALATE_TO_HUMAN")return null;return parsed}catch{return null}}function listLaneEvidenceSync(directory,phase){let evidenceDir=path340.join(directory,".swarm","evidence",String(phase),"lean-turbo"),entries2;try{entries2=fs202.readdirSync(evidenceDir)}catch{return[]}entries2.sort();let laneIds=[];for(let entry of entries2){if(!entry.endsWith(".json")||entry==="lean-turbo-phase.json")continue;laneIds.push(entry.slice(0,-5))}return laneIds}var _internals287={listActiveLocks,readPersisted:readPersisted3,readPlanJson:defaultReadPlanJson,readReviewerEvidence:readReviewerEvidenceFromFile,readCriticEvidence:readCriticEvidenceFromFile,listLaneEvidence,listLaneEvidenceSync,verifyLeanTurboPhaseReady};function validatePersistedShape3(persisted){if(typeof persisted!=="object"||persisted===null)return!1;if(Array.isArray(persisted))return!1;if(typeof persisted.sessions!=="object")return!1;if(persisted.sessions===null)return!1;if(Array.isArray(persisted.sessions))return!1;return!0}function validateLanesArray(lanes){if(!Array.isArray(lanes))return!1;for(let lane of lanes){if(typeof lane!=="object"||lane===null)return!1;if(typeof lane.laneId!=="string")return!1;if(typeof lane.status!=="string")return!1}return!0}function validateDegradedTasksArray(degradedTasks){if(!Array.isArray(degradedTasks))return!1;for(let dt of degradedTasks){if(typeof dt!=="object"||dt===null)return!1;if(typeof dt.taskId!=="string")return!1}return!0}function verifyLeanTurboPhaseReady(directory,phase,sessionIDOrConfig,config3){let sessionID=typeof sessionIDOrConfig==="string"?sessionIDOrConfig:void 0,actualConfig=typeof sessionIDOrConfig==="object"&&sessionIDOrConfig!==null?sessionIDOrConfig:config3??DEFAULT_CONFIG4,mergedConfig={phase_reviewer:actualConfig.phase_reviewer??DEFAULT_CONFIG4.phase_reviewer,phase_critic:actualConfig.phase_critic??DEFAULT_CONFIG4.phase_critic,integrated_diff_required:actualConfig.integrated_diff_required??DEFAULT_CONFIG4.integrated_diff_required},statePath3=path340.join(directory,".swarm","turbo-state.json");if(!fs202.existsSync(statePath3))return{ok:!1,reason:"Lean Turbo state unreadable or missing"};let persisted=_internals287.readPersisted(directory);if(!persisted)return{ok:!1,reason:"Lean Turbo state unreadable or missing"};if(!validatePersistedShape3(persisted))return{ok:!1,reason:"Lean Turbo state unreadable or missing"};let runState=null;for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"&&sessionState.sessionID===sessionID){runState=sessionState;break}if(!runState&&sessionID===void 0){for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"){runState=sessionState;break}}if(!runState)return{ok:!1,reason:sessionID?`No active Lean Turbo session for phase ${phase} and session ${sessionID}`:`No active Lean Turbo session for phase ${phase}`};if(!validateLanesArray(runState.lanes))return{ok:!1,reason:`No active Lean Turbo session for phase ${phase}`};if(!validateDegradedTasksArray(runState.degradedTasks))return{ok:!1,reason:`No active Lean Turbo session for phase ${phase}`};if(runState.lanes.length===0&&(!Array.isArray(runState.serializedTasks)||runState.serializedTasks.length===0)&&(!Array.isArray(runState.degradedTasks)||runState.degradedTasks.length===0))return{ok:!1,reason:`No lane plan or fallback tasks found for phase ${phase}`};let laneIds=runState.lanes.map((l)=>l.laneId);if(runState.lanes.length>0){for(let lane of runState.lanes)if(lane.status!=="completed"&&lane.status!=="failed")return{ok:!1,reason:`Lane ${lane.laneId} is not completed (status: ${lane.status})`}}if(runState.lanes.length>0){let evidenceLaneIds=new Set(_internals287.listLaneEvidenceSync(directory,phase));for(let lane of runState.lanes)if((lane.status==="completed"||lane.status==="failed")&&!evidenceLaneIds.has(lane.laneId))return{ok:!1,reason:`Lane ${lane.laneId} is ${lane.status} but lane evidence file is missing`}}let activeLocks=_internals287.listActiveLocks(directory),phaseLaneIds=new Set(laneIds);for(let lock of activeLocks)if(lock.laneId&&phaseLaneIds.has(lock.laneId))return{ok:!1,reason:`Active locks remain for lane ${lock.laneId}`};let laneTaskIds=new Set;for(let lane of runState.lanes)if(Array.isArray(lane.taskIds))for(let taskId of lane.taskIds)laneTaskIds.add(taskId);let serialDegradedTasks=runState.degradedTasks.filter((dt)=>!laneTaskIds.has(dt.taskId));if(serialDegradedTasks.length>0){let plan=_internals287.readPlanJson(directory);if(!plan)return{ok:!1,reason:"Cannot verify degraded task status: plan.json unreadable or malformed"};for(let dt of serialDegradedTasks){if(!Array.isArray(plan.phases))return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: plan.json malformed (phases is not an array)`};let planPhase=plan.phases.find((p)=>p&&typeof p==="object"&&p!==null&&p.id===phase);if(!planPhase)return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: phase ${phase} not found in plan.json`};if(!Array.isArray(planPhase.tasks))return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: plan.json malformed (phase ${phase} tasks is not an array)`};let task2=planPhase.tasks.find((t)=>t&&typeof t==="object"&&t!==null&&t.id===dt.taskId);if(!task2)return{ok:!1,reason:`Degraded task ${dt.taskId} not found in plan`};if(task2.status!=="completed")return{ok:!1,reason:`Degraded task ${dt.taskId} not yet completed via standard flow`}}}let serializedTasks=runState.serializedTasks;if(Array.isArray(serializedTasks)&&serializedTasks.length>0){let plan=_internals287.readPlanJson(directory);if(!plan)return{ok:!1,reason:"Cannot verify serialized task status: plan.json unreadable or malformed"};if(!Array.isArray(plan.phases))return{ok:!1,reason:"Cannot verify serialized tasks: plan.json malformed (phases is not an array)"};let planPhase=plan.phases.find((p)=>p&&typeof p==="object"&&p!==null&&p.id===phase);if(!planPhase)return{ok:!1,reason:`Cannot verify serialized tasks: phase ${phase} not found in plan.json`};if(!Array.isArray(planPhase.tasks))return{ok:!1,reason:`Cannot verify serialized tasks: plan.json malformed (phase ${phase} tasks is not an array)`};for(let serTaskId of serializedTasks){let task2=planPhase.tasks.find((t)=>t&&typeof t==="object"&&t!==null&&t.id===serTaskId);if(!task2)return{ok:!1,reason:`Serialized task ${serTaskId} not found in plan`};if(task2.status!=="completed")return{ok:!1,reason:`Serialized task ${serTaskId} not yet completed (status: ${task2.status})`}}}if(mergedConfig.integrated_diff_required){let evidencePath=path340.join(directory,".swarm","evidence",String(phase),"lean-turbo","lean-turbo-phase.json"),hasDiff=!1;try{let content=fs202.readFileSync(evidencePath,"utf-8");hasDiff=!!JSON.parse(content).integratedDiffSummary}catch{}if(!hasDiff)return{ok:!1,reason:`Integrated diff summary is required but missing for phase ${phase}`}}let reviewerVerdict=runState.lastReviewerVerdict;if(!reviewerVerdict)reviewerVerdict=_internals287.readReviewerEvidence(directory,phase)?.verdict??void 0;if(mergedConfig.phase_reviewer){if(reviewerVerdict!=="APPROVED")return{ok:!1,reason:"Integrated reviewer approval missing or rejected"}}let criticVerdict=runState.lastCriticVerdict;if(!criticVerdict)criticVerdict=_internals287.readCriticEvidence(directory,phase)?.verdict??void 0;if(mergedConfig.phase_critic){if(criticVerdict!=="APPROVED")return{ok:!1,reason:"Integrated critic approval missing or rejected"}}return{ok:!0,reason:`Phase ${phase} is ready to advance`,evidence:{lanes:laneIds,degradedTasks:runState.degradedTasks.map((dt)=>dt.taskId),reviewerVerdict:reviewerVerdict??runState.lastReviewerVerdict,criticVerdict:criticVerdict??runState.lastCriticVerdict}}}init_logger();init_create_tool();function resolveCouncilFreshnessMaxAgeMs(config3){let hours=config3?.freshnessMaxAgeHours??24;if(!Number.isFinite(hours)||hours<1)return 86400000;return Math.min(hours,720)*60*60*1000}function evaluateCouncilFreshness(input){if(input.timestampMs===null||!Number.isFinite(input.timestampMs))return{ok:!1,reason:"invalid_timestamp",message:"evidence has a missing or invalid timestamp",recovery:"Re-run the council to generate fresh, timestamped evidence."};if(input.timestampMs>input.nowMs)return{ok:!1,reason:"future_timestamp",message:"evidence timestamp is in the future",recovery:"Re-run the council after the host clock is correct, then resubmit."};if(input.nowMs-input.timestampMs>input.maxAgeMs)return{ok:!1,reason:"stale_evidence",message:`evidence is older than the configured freshness window (${Math.round(input.maxAgeMs/3600000)} hours)`,recovery:"Re-run the council for fresh review."};if(input.mustPostdateMs!==void 0&&input.mustPostdateMs!==null&&Number.isFinite(input.mustPostdateMs)){if(input.mustPostdateMs>input.nowMs)return{ok:!1,reason:"invalid_required_input",message:"a later required input (e.g. the phase retrospective) is timestamped in the future — host clock skew suspected",recovery:"Correct the host clock / fix the skewed timestamp, then re-run the council."};if(input.timestampMs<input.mustPostdateMs)return{ok:!1,reason:"predates_required_input",message:"evidence predates a later required input (e.g. the phase retrospective)",recovery:"Re-run the council after the latest required evidence is available."}}return{ok:!0,message:"evidence is fresh",recovery:""}}function parseTimestampMs(value){if(typeof value!=="string")return null;let parsed=new Date(value).getTime();return Number.isNaN(parsed)?null:parsed}function latestRetroTimestampMsFromBundle(bundle,phase){if(!bundle||typeof bundle!=="object")return null;let raw=bundle,entries2=Array.isArray(raw.entries)?raw.entries:[],timestamps=[parseTimestampMs(raw.created_at),parseTimestampMs(raw.updated_at),...entries2.filter((entry)=>typeof entry==="object"&&entry!==null).filter((entry)=>entry.type==="retrospective"&&entry.phase_number===phase).map((entry)=>parseTimestampMs(entry.timestamp))].filter((timestamp)=>timestamp!==null);return timestamps.length>0?Math.max(...timestamps):null}init_store5();async function runArchitectureSupervisorGate(ctx){let{phase,dir,pluginConfig,agentsDispatched,safeWarn}=ctx,asConfig=pluginConfig.architectural_supervision,summarizeFindings=(findings)=>{if(!Array.isArray(findings)||findings.length===0)return"";let details=findings.map((f)=>f&&typeof f==="object"&&typeof f.description==="string"?f.description:void 0).filter((d)=>Boolean(d));return details.length>0?`
7754
7754
  Findings: ${details.join("; ")}`:""},asBlocked=(reason,message)=>({blocked:!0,reason,message,agentsDispatched,agentsMissing:[],warnings:[]}),asEntry=null;try{asEntry=readSupervisorReportRaw(dir,phase)}catch(asError2){return asBlocked("ARCH_SUPERVISOR_ERROR",`Phase ${phase} cannot be completed: architecture supervisor gate encountered an error. Error: ${String(asError2)}`)}if(!asEntry)return asBlocked("ARCH_SUPERVISOR_REQUIRED",`Phase ${phase} cannot be completed: architectural_supervision gate mode is enabled and no architecture supervisor evidence was found at .swarm/evidence/${phase}/architecture-supervisor.json. Dispatch critic_architecture_supervisor with the phase + agent summaries, then call write_architecture_supervisor_evidence.`);let freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:asEntry.timestamp?new Date(asEntry.timestamp).getTime():null,maxAgeMs:resolveCouncilFreshnessMaxAgeMs(ctx.pluginConfig.council)});if(!freshness.ok)return asBlocked({invalid_timestamp:"ARCH_SUPERVISOR_INVALID_TIMESTAMP",future_timestamp:"ARCH_SUPERVISOR_FUTURE_TIMESTAMP",stale_evidence:"ARCH_SUPERVISOR_STALE_EVIDENCE",predates_required_input:"ARCH_SUPERVISOR_STALE_EVIDENCE",invalid_required_input:"ARCH_SUPERVISOR_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"ARCH_SUPERVISOR_STALE_EVIDENCE",`Phase ${phase} cannot be completed: architecture supervisor ${freshness.message}. ${freshness.recovery}`);if(typeof asEntry.phase_number!=="number"||asEntry.phase_number!==phase)return asBlocked("ARCH_SUPERVISOR_PHASE_MISMATCH",`Phase ${phase} cannot be completed: architecture supervisor evidence is for phase ${String(asEntry.phase_number)}, not phase ${phase}.`);let gateWarnings=[];if(asConfig?.provenance_verify===!0){let provenance=asEntry.provenance;if(!provenance||!provenance.agent_name&&!provenance.session_id)return asBlocked("ARCH_SUPERVISOR_MISSING_PROVENANCE",`Phase ${phase} cannot be completed: architecture supervisor evidence lacks provenance (agent_name or session_id). Evidence provenance verification is enabled.`)}else if(!asEntry.provenance||!asEntry.provenance.agent_name&&!asEntry.provenance.session_id){let msg=`Architecture supervisor evidence lacks provenance for phase ${phase}. Enable 'provenance_verify' in architectural_supervision config to enforce provenance verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}let asVerdict=asEntry.verdict;if(asVerdict==="REJECT")return asBlocked("ARCH_SUPERVISOR_REJECTED",`Phase ${phase} cannot be completed: architecture supervisor returned verdict 'REJECT'. Address the system-level findings before completing the phase.${summarizeFindings(asEntry.findings)}`);if(asVerdict==="CONCERNS"){if(asConfig?.allow_concerns_to_complete===!1)return asBlocked("ARCH_SUPERVISOR_CONCERNS",`Phase ${phase} cannot be completed: architecture supervisor returned verdict 'CONCERNS' and allow_concerns_to_complete is disabled.${summarizeFindings(asEntry.findings)}`);safeWarn(`[phase_complete] Architecture supervisor returned CONCERNS for phase ${phase} — proceeding (allow_concerns_to_complete is enabled)`,void 0)}else if(asVerdict!=="APPROVE")return asBlocked("ARCH_SUPERVISOR_INVALID",`Phase ${phase} cannot be completed: architecture supervisor evidence contains unrecognized verdict '${String(asVerdict)}'. Expected one of: APPROVE, CONCERNS, REJECT.`);return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}async function runCompletionVerifyGate(ctx){let{phase,dir,agentsDispatched}=ctx;try{let completionResultRaw=await executeCompletionVerify({phase,writeEvidence:!1},dir),completionResult=JSON.parse(completionResultRaw);if(completionResult.status==="blocked")return{blocked:!0,reason:"COMPLETION_INCOMPLETE",message:`Phase ${phase} cannot be completed: ${completionResult.reason}`,agentsDispatched,agentsMissing:[],warnings:completionResult.blockedTasks?[`Blocked tasks: ${completionResult.blockedTasks.map((t)=>t.task_id).join(", ")}`]:[]};return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}catch(completionError){return{blocked:!0,reason:"COMPLETION_VERIFY_ERROR",message:`Phase ${phase} cannot be completed: completion verify gate encountered an error. Error: ${String(completionError)}`,agentsDispatched,agentsMissing:[],warnings:[`COMPLETION_VERIFY_ERROR: ${String(completionError)}`]}}}init_effective_spec();import*as fs203 from"node:fs";import*as path341 from"node:path";init_qa_gate_profile();init_ledger();init_manager();init_utils3();init_state2();async function resolveGatePreamble(dir,sessionID){let plan=await loadPlan(dir);if(!plan)return{resolved:!1};let planId=derivePlanId(plan),planHash=computePlanLedgerHash(plan),lookup=getProfileLookupForIdentity(dir,plan),overrides2=(sessionID?swarmState.agentSessions.get(sessionID):void 0)?.qaGateSessionOverrides??{};if(lookup.kind==="missing"){let hasOverrides=Object.keys(overrides2).length>0;return{resolved:hasOverrides,plan,planId,planHash,effectiveGates:hasOverrides?{...DEFAULT_QA_GATES,...overrides2}:void 0,identityBound:!0}}let profile=lookup.profile,effective=getEffectiveGates(profile,overrides2);return{resolved:!0,plan,planId,planHash,effectiveGates:effective,identityBound:lookup.kind==="bound"}}async function runDriftGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,gateWarnings=[],driftCheckEnabled=!0,driftHasEffectiveSpec=!1;try{driftHasEffectiveSpec=readEffectiveSpecSync(dir)!==null;let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved){if(preamble.identityBound===!1&&preamble.effectiveGates?.drift_check===!0)return{blocked:!0,reason:"DRIFT_VERIFICATION_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: drift_check is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};driftCheckEnabled=preamble.effectiveGates?.drift_check===!0}}catch(gateLoadError){safeWarn("[phase_complete] QA gate profile load error, drift_check defaults to enabled:",gateLoadError)}if(!driftCheckEnabled)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`drift_check gate is disabled. Drift verification was skipped for phase ${phase}.`]};let phaseType;try{let planPath=path341.join(dir,".swarm","plan.json");if(fs203.existsSync(planPath)){let planRaw=fs203.readFileSync(planPath,"utf-8");phaseType=JSON.parse(planRaw).phases?.find((p)=>p.id===phase)?.type}}catch{}if(phaseType==="non-code")return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`Phase ${phase} is annotated as 'non-code'. Drift verification was skipped per phase type annotation.`]};try{let driftEvidencePath=path341.join(dir,".swarm","evidence",String(phase),"drift-verifier.json"),driftVerdictFound=!1,driftVerdictApproved=!1;try{let driftEvidenceContent=fs203.readFileSync(driftEvidencePath,"utf-8"),entries2=JSON.parse(driftEvidenceContent).entries??[];for(let entry of entries2)if(typeof entry.type==="string"&&entry.type.includes("drift")&&typeof entry.verdict==="string"){if(driftVerdictFound=!0,!entry.provenance||!entry.provenance.agent_name&&!entry.provenance.session_id){let msg=`Drift verification evidence lacks provenance for phase ${phase}. Evidence should include agent_name or session_id for verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}if(entry.verdict==="approved")driftVerdictApproved=!0;if(entry.verdict==="rejected"||typeof entry.summary==="string"&&entry.summary.includes("NEEDS_REVISION"))return{blocked:!0,reason:"DRIFT_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: drift verifier returned verdict '${entry.verdict}'. Address the drift issues before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readError){if(readError.code!=="ENOENT")safeWarn("[phase_complete] Drift verifier evidence unreadable:",readError);driftVerdictFound=!1}if(!driftVerdictFound)if(!driftHasEffectiveSpec){let incompleteTaskCount=0,planParseable=!1;try{let planPath=path341.join(dir,".swarm","plan.json");if(fs203.existsSync(planPath)){let planRaw=fs203.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);planParseable=!0;let planPhase=plan.phases?.find((p)=>p.id===phase);if(planPhase?.tasks)incompleteTaskCount=planPhase.tasks.filter((t)=>t.status!=="completed"&&t.status!=="closed").length}}catch{}if(!planParseable)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:["No effective spec found and drift verification evidence missing — consider running critic_drift_verifier before phase completion."]};else if(incompleteTaskCount>0)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`No effective spec found and drift verification evidence missing. Phase ${phase} has ${incompleteTaskCount} incomplete task(s) in plan.json — consider running critic_drift_verifier before phase completion.`]};else return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`No effective spec found. Phase ${phase} tasks are all completed in plan.json. Drift verification was skipped.`]}}else return{blocked:!0,reason:"DRIFT_VERIFICATION_MISSING",message:`Phase ${phase} cannot be completed: drift_check is enabled and drift verifier evidence not found at .swarm/evidence/${phase}/drift-verifier.json. Run drift verification before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!driftVerdictApproved&&driftVerdictFound)return{blocked:!0,reason:"DRIFT_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: drift verifier verdict is not approved.`,agentsDispatched,agentsMissing:[],warnings:[]};return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}catch(driftError){return{blocked:!0,reason:"DRIFT_VERIFICATION_ERROR",message:`Phase ${phase} cannot be completed: drift verification encountered an error: ${driftError instanceof Error?driftError.message:String(driftError)}. This is a hard block — resolve the error before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}import*as fs204 from"node:fs";import*as path342 from"node:path";init_council_review_identity();init_types();init_qa_gate_profile();init_utils3();init_state2();function readLatestRetroTimestampMs(dir,phase){let baseDir=path342.normalize(path342.resolve(dir,".swarm")),retroPath=path342.normalize(path342.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path342.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path342.sep)||retroPath===baseDir))return null;try{let content=fs204.readFileSync(retroPath,"utf-8");return latestRetroTimestampMsFromBundle(JSON.parse(content),phase)}catch{return null}}function sessionHasEnabledFinalCouncil(sessionID){if(!sessionID)return!1;return swarmState.agentSessions.get(sessionID)?.qaGateSessionOverrides?.final_council===!0}async function runFinalCouncilGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,finalCouncilEnabled=!1,gateWarnings=[];try{let preamble=await resolveGatePreamble(dir,sessionID);if(!preamble.resolved||!preamble.plan){if(hasAnyProfileWithEnabledGate(dir,"final_council")||sessionHasEnabledFinalCouncil(sessionID))return{blocked:!0,reason:"FINAL_COUNCIL_PLAN_REQUIRED",message:`Phase ${phase} cannot be completed: final_council is enabled but plan.json is missing or invalid, so the final council gate cannot verify the current plan identity. Restore a valid .swarm/plan.json and re-run the final council.`,agentsDispatched,agentsMissing:[],warnings:[]};let warning="Final council gate: plan.json is missing and no enabled final_council profile was found. If final_council is required, the gate cannot be verified.";return gateWarnings.push(warning),safeWarn(`[phase_complete] ${warning}`,void 0),{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[warning]}}if(preamble.resolved&&preamble.plan){let lastPhaseId=preamble.plan.phases[preamble.plan.phases.length-1]?.id;if(lastPhaseId!==void 0&&phase===lastPhaseId){if(preamble.effectiveGates?.final_council===!0){if(preamble.identityBound===!1)return{blocked:!0,reason:"FINAL_COUNCIL_IDENTITY_UNBOUND",message:`Phase ${phase} (last phase) cannot be completed: final_council is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the project")}`,agentsDispatched,agentsMissing:[],warnings:[]};finalCouncilEnabled=!0;let fcPath=path342.join(dir,".swarm","evidence","final-council.json"),fcVerdictFound=!1,_fcVerdict,identity=computeCouncilReviewIdentity({level:"final",scope:{kind:"final",final:!0},plan:preamble.plan,config:ctx.pluginConfig.council}),completionPolicy=resolveFinalCompletionPolicy(ctx.pluginConfig.council),maxAgeMs=resolveCouncilFreshnessMaxAgeMs(ctx.pluginConfig.council);try{let fcContent=fs204.readFileSync(fcPath,"utf-8"),fcBundle=JSON.parse(fcContent);for(let entry of fcBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="final-council"&&typeof entry.verdict==="string"){fcVerdictFound=!0,_fcVerdict=entry.verdict;let fcTimeMs=parseTimestampMs(entry.timestamp),latestRetroTimestampMs=latestRetroTimestampMsFromBundle(ctx.loadedRetroBundle,phase)??readLatestRetroTimestampMs(dir,phase),freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:fcTimeMs,maxAgeMs,mustPostdateMs:latestRetroTimestampMs});if(!freshness.ok)return{blocked:!0,reason:{invalid_timestamp:"FINAL_COUNCIL_TIMESTAMP_REQUIRED",future_timestamp:"FINAL_COUNCIL_FUTURE_TIMESTAMP",stale_evidence:"FINAL_COUNCIL_STALE_EVIDENCE",predates_required_input:"FINAL_COUNCIL_STALE_EVIDENCE",invalid_required_input:"FINAL_COUNCIL_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"FINAL_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: final council ${freshness.message}. ${freshness.recovery}`,agentsDispatched,agentsMissing:[],warnings:[]};if(preamble.plan){let currentPlanId=preamble.planId;if(entry.plan_id&&entry.plan_id!==currentPlanId)return{blocked:!0,reason:"final_council_plan_mismatch",message:`Final council evidence belongs to a different plan (evidence: ${entry.plan_id}, current: ${currentPlanId}). Re-run the final council.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!entry.plan_id)return{blocked:!0,reason:"FINAL_COUNCIL_PLAN_ID_REQUIRED",message:`Phase ${phase} (last phase) cannot be completed: final council evidence is missing plan_id binding. Re-run the final council to generate evidence with plan identity.`,agentsDispatched,agentsMissing:[],warnings:[]};let currentIdentityHash=derivePlanIdentityHash(preamble.plan);if(entry.plan_identity_hash!==currentIdentityHash)return{blocked:!0,reason:entry.plan_identity_hash?"FINAL_COUNCIL_PLAN_IDENTITY_MISMATCH":"FINAL_COUNCIL_PLAN_IDENTITY_REQUIRED",message:entry.plan_identity_hash?`Phase ${phase} cannot be completed: final council evidence belongs to a different raw plan identity. Re-run the final council.`:`Phase ${phase} cannot be completed: final council evidence is missing plan_identity_hash binding. Re-run the final council to generate collision-resistant plan identity evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.identity_version!==COUNCIL_REVIEW_IDENTITY_VERSION)return{blocked:!0,reason:entry.identity_version?"FINAL_COUNCIL_IDENTITY_MISMATCH":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:entry.identity_version?`Phase ${phase} cannot be completed: final council evidence was produced under a different council identity schema version (${entry.identity_version}, expected ${COUNCIL_REVIEW_IDENTITY_VERSION}). Re-run the final council.`:`Phase ${phase} cannot be completed: final council evidence predates the council review identity cutover and carries no identity proof. Re-run the final council to generate identity-bound evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.review_hash!==identity.reviewHash||!isIdentityDigest(entry.identity_digest)||entry.identity_digest!==identity.identityDigest)return{blocked:!0,reason:entry.review_hash?"FINAL_COUNCIL_STALE_REVIEW_IDENTITY":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: final council evidence does not match the current council review identity (review-relevant plan content or council policy changed since the review). Re-run the final council for the current plan and policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.policy_digest!==identity.policyDigest)return{blocked:!0,reason:entry.policy_digest?"FINAL_COUNCIL_POLICY_MISMATCH":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: final council evidence was produced under a different council policy. Re-run the final council under the current policy.`,agentsDispatched,agentsMissing:[],warnings:[]}}let requiredMembers=completionPolicy.mode==="quorum"?completionPolicy.minimumMembers:COUNCIL_MEMBER_ROLES.length,rawMembersVoted=Array.isArray(entry.membersVoted)?entry.membersVoted.filter((member)=>typeof member==="string"):[],distinctCanonicalVoted=new Set(rawMembersVoted.map((member)=>resolveCouncilMemberRole(member)).filter((role)=>Boolean(role))),membersAbsent=COUNCIL_MEMBER_ROLES.filter((role)=>!distinctCanonicalVoted.has(role)),strictAllMembersPresent=distinctCanonicalVoted.size===COUNCIL_MEMBER_ROLES.length,quorumSatisfied=completionPolicy.mode==="quorum"?distinctCanonicalVoted.size>=requiredMembers:strictAllMembersPresent&&membersAbsent.length===0;if(typeof entry.quorumSize!=="number"||!Number.isFinite(entry.quorumSize)||entry.quorumSize<requiredMembers||!quorumSatisfied)return{blocked:!0,reason:"FINAL_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} (last phase) cannot be completed: final council evidence does not prove the required quorum (policy ${completionPolicy.mode}${completionPolicy.mode==="quorum"?`, minimumMembers: ${completionPolicy.minimumMembers}`:""}; recorded quorumSize: ${typeof entry.quorumSize==="number"?entry.quorumSize:"missing"}; distinct canonical members: ${distinctCanonicalVoted.size} of ${requiredMembers} required; absent: [${membersAbsent.join(", ")}]). Re-run the project-scoped final council and call write_final_council_evidence to generate quorumed evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.verdict==="rejected"||entry.verdict==="REJECTED")return{blocked:!0,reason:"FINAL_COUNCIL_REJECTED",message:`Phase ${phase} (last phase) cannot be completed: final council returned verdict 'REJECTED'. Address the required fixes before completing the project.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.verdict==="concerns"||entry.verdict==="CONCERNS"){let advisoryNotes=Array.isArray(entry.advisoryNotes)?entry.advisoryNotes.filter((note)=>typeof note==="string"):[],warning=advisoryNotes.length>0?`Final council returned CONCERNS (non-blocking): ${advisoryNotes.join("; ")}`:"Final council returned CONCERNS (non-blocking).";gateWarnings.push(warning),safeWarn(`[phase_complete] ${warning}`,void 0)}if(entry.verdict!=="approved"&&entry.verdict!=="APPROVED"&&entry.verdict!=="concerns"&&entry.verdict!=="CONCERNS")return{blocked:!0,reason:"FINAL_COUNCIL_INVALID_VERDICT",message:`Phase ${phase} (last phase) cannot be completed: final council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: approved, concerns, rejected.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Final council evidence unreadable:",readErr);fcVerdictFound=!1}if(!fcVerdictFound)return{blocked:!0,reason:"FINAL_COUNCIL_REQUIRED",final_council_required:!0,message:`Phase ${phase} (last phase) cannot be completed: final_council is enabled and final council evidence not found at .swarm/evidence/final-council.json. Dispatch critic, reviewer, sme, test_engineer, and explorer with project-scoped context, collect their CouncilMemberVerdict JSON, and call write_final_council_evidence before completing the project. Do not use convene_general_council for this gate.`,agentsDispatched,agentsMissing:[],warnings:["Final council required - dispatch the project-scoped council members, then call write_final_council_evidence to persist quorumed evidence."]}}}}}catch(fcError){if(finalCouncilEnabled)return{blocked:!0,reason:"FINAL_COUNCIL_ERROR",message:`Phase ${phase} (last phase) cannot be completed: final council gate encountered an error. Error: ${String(fcError)}`,agentsDispatched,agentsMissing:[],warnings:[`FINAL_COUNCIL_ERROR: ${String(fcError)}`]};else safeWarn("[phase_complete] Final council gate error (non-blocking):",fcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}init_schema();init_manager();init_diff_source();init_evidence2();function pass(ctx,warnings=[]){return{blocked:!1,agentsDispatched:ctx.agentsDispatched,agentsMissing:[],warnings}}function block(ctx,reason,message,recovery={kind:"tool",action:"run_phase_review",args:{phase:ctx.phase,sessionID:ctx.sessionID}}){return{blocked:!0,reason,message,agentsDispatched:ctx.agentsDispatched,agentsMissing:[],warnings:[],recovery}}function evidenceStatusMatchesScope(evidenceStatus,scopeStatus){return scopeStatus==="clean"?evidenceStatus==="clean":evidenceStatus==="completed"}async function runFinalReviewGate(ctx){let config3;try{config3=resolveAutoReviewConfig(ctx.pluginConfig.auto_review??{},{preset:ctx.pluginConfig.preset})}catch(error93){return block(ctx,"FINAL_REVIEW_CONFIG_INVALID",`Phase ${ctx.phase} cannot be completed: ${error93 instanceof Error?error93.message:String(error93)}`,{kind:"tool",action:"swarm_command",args:{command:"doctor",args:["config"]}})}let finalPlanPhase=(await loadPlanJsonOnly(ctx.dir).catch(()=>null))?.phases.at(-1)?.id===ctx.phase,allowedTriggers=new Set;if(config3.final_review.on_phase_complete)allowedTriggers.add("phase_completion");if(finalPlanPhase&&config3.final_review.on_plan_complete)allowedTriggers.add("plan_completion");if(!config3.enabled||config3.final_review.mode!=="gate"||config3.trigger==="task_completion"||allowedTriggers.size===0)return pass(ctx);let evidence2=readAutoReviewEvidenceForPhase(ctx.dir,ctx.phase);if(!evidence2)return block(ctx,"FINAL_REVIEW_EVIDENCE_MISSING",`Phase ${ctx.phase} cannot be completed: .swarm/evidence/${ctx.phase}/auto-review.json is missing or malformed.`);if(evidence2.schema_version!==2||!evidence2.scope.manifest)return block(ctx,"FINAL_REVIEW_LEGACY_RERUN",`Phase ${ctx.phase} cannot be completed: final review evidence uses the legacy schema and must be rerun with run_phase_review before completion.`);if(evidence2.phase!==ctx.phase||!allowedTriggers.has(evidence2.trigger))return block(ctx,"FINAL_REVIEW_EVIDENCE_STALE",`Phase ${ctx.phase} cannot be completed: final review evidence does not match the current review scope.`);let currentScope=await _internals288.collectReviewDiff({directory:ctx.dir,maxBytes:config3.final_review.max_diff_bytes});if(currentScope.status==="error")return block(ctx,"FINAL_REVIEW_SCOPE_COLLECTION_FAILED",`Phase ${ctx.phase} cannot be completed: terminal final-review scope collection failed (${currentScope.reason}).`);let currentManifest=await materializeAutoReviewManifest(ctx.dir,currentScope.manifest,config3);if(currentManifest.hash!==evidence2.scope.manifest.hash||JSON.stringify(currentScope.selector)!==JSON.stringify(evidence2.scope.selector)||JSON.stringify(currentScope.completeness)!==JSON.stringify(evidence2.scope.completeness)||!evidenceStatusMatchesScope(evidence2.review.status,currentScope.status))return block(ctx,"FINAL_REVIEW_EVIDENCE_STALE",`Phase ${ctx.phase} cannot be completed: repository scope, plan requirements, or review policy changed after final review evidence was produced.`);if(evidence2.policy.mode!==config3.final_review.mode||evidence2.policy.min_confidence!==config3.min_confidence||evidence2.policy.structured_findings!==config3.structured_findings||evidence2.policy.validate_findings!==config3.validate_findings||evidence2.policy.digest!==currentManifest.review_policy_digest)return block(ctx,"FINAL_REVIEW_POLICY_STALE",`Phase ${ctx.phase} cannot be completed: final review evidence was produced under a different policy.`);let integrity=validateAutoReviewEvidenceIntegrity(ctx.dir,evidence2,{scopeHash:evidence2.scope.hash,phase:ctx.phase,trigger:evidence2.trigger,policy:{mode:evidence2.policy.mode,min_confidence:evidence2.policy.min_confidence,structured_findings:evidence2.policy.structured_findings,validate_findings:evidence2.policy.validate_findings},scopeContent:currentScope.canonicalText});if(!integrity.ok)return block(ctx,integrity.code==="receipt_missing"?"FINAL_REVIEW_RECEIPT_MISSING":"FINAL_REVIEW_EVIDENCE_INVALID",`Phase ${ctx.phase} cannot be completed: final review evidence integrity check failed (${integrity.reason}).`);if(evidence2.review.status==="error")return block(ctx,"FINAL_REVIEW_FAILED",`Phase ${ctx.phase} cannot be completed: final review dispatch or parsing failed.`);if(!evidence2.scope.completeness.complete)return block(ctx,"FINAL_REVIEW_SCOPE_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: final review scope was truncated or incomplete.`);if(evidence2.review.status==="completed"&&evidence2.review.output_mode!=="structured")return block(ctx,"FINAL_REVIEW_STRUCTURED_EVIDENCE_REQUIRED",`Phase ${ctx.phase} cannot be completed: gate mode requires structured review evidence.`);if(!evidence2.validation_complete)return block(ctx,"FINAL_REVIEW_VALIDATION_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: independent finding validation evidence is incomplete.`);let gateCandidates=evidence2.findings.filter((finding)=>finding.anchored&&(finding.effective_severity==="high"||finding.effective_severity==="critical"));if(gateCandidates.some((finding)=>!finding.validation||finding.validation.finding_id!==finding.finding_id))return block(ctx,"FINAL_REVIEW_VALIDATION_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: gate-eligible findings lack exact-ID validation evidence.`);let confirmedIds=gateCandidates.filter((finding)=>finding.validation?.disposition==="CONFIRMED").map((finding)=>finding.finding_id).sort(),recordedBlockingIds=[...evidence2.blocking_finding_ids].sort();if(confirmedIds.length!==recordedBlockingIds.length||confirmedIds.some((id,index)=>id!==recordedBlockingIds[index]))return block(ctx,"FINAL_REVIEW_EVIDENCE_INVALID",`Phase ${ctx.phase} cannot be completed: blocking finding IDs do not match independently confirmed findings.`);if(evidence2.blocking_finding_ids.length>0)return block(ctx,"FINAL_REVIEW_CONFIRMED_FINDINGS",`Phase ${ctx.phase} cannot be completed: ${evidence2.blocking_finding_ids.length} anchored HIGH/CRITICAL finding(s) were independently CONFIRMED.`);return pass(ctx)}var _internals288={collectReviewDiff};import*as fs205 from"node:fs";import*as path343 from"node:path";async function runHallucinationGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,hallucinationGateEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.hallucination_guard===!0){if(hallucinationGateEnabled=!0,preamble.identityBound===!1)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: hallucination_guard is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};let hgPath=path343.join(dir,".swarm","evidence",String(phase),"hallucination-guard.json"),hgVerdictFound=!1,hgVerdictApproved=!1;try{let hgContent=fs205.readFileSync(hgPath,"utf-8"),hgBundle=JSON.parse(hgContent);for(let entry of hgBundle.entries??[])if(typeof entry.type==="string"&&entry.type.includes("hallucination")&&typeof entry.verdict==="string"){if(hgVerdictFound=!0,entry.verdict==="approved")hgVerdictApproved=!0;if(entry.verdict==="rejected"||typeof entry.summary==="string"&&entry.summary.includes("NEEDS_REVISION"))return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: hallucination verifier returned verdict '${entry.verdict}'. Remove fabricated APIs/signatures and fix broken citations before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Hallucination guard evidence unreadable:",readErr);hgVerdictFound=!1}if(!hgVerdictFound)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_MISSING",message:`Phase ${phase} cannot be completed: hallucination_guard is enabled and evidence not found at .swarm/evidence/${phase}/hallucination-guard.json. Delegate to critic_hallucination_verifier and call write_hallucination_evidence before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!hgVerdictApproved)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: hallucination verifier verdict is not approved.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(hgError){if(hallucinationGateEnabled)return{blocked:!0,reason:"HALLUCINATION_GATE_ERROR",message:`Phase ${phase} cannot be completed: hallucination guard gate encountered an error when hallucination_guard was enabled. Error: ${String(hgError)}`,agentsDispatched,agentsMissing:[],warnings:[`HALLUCINATION_GATE_ERROR: ${String(hgError)}`]};else safeWarn("[phase_complete] Hallucination guard error (non-blocking):",hgError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}import*as fs206 from"node:fs";import*as path344 from"node:path";async function runMutationGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,mutationGateEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.mutation_test===!0){if(mutationGateEnabled=!0,preamble.identityBound===!1)return{blocked:!0,reason:"MUTATION_GATE_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: mutation_test is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};let mgPath=path344.join(dir,".swarm","evidence",String(phase),"mutation-gate.json"),mgVerdictFound=!1,mgVerdict;try{let mgContent=fs206.readFileSync(mgPath,"utf-8"),mgBundle=JSON.parse(mgContent);for(let entry of mgBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="mutation-gate"&&typeof entry.verdict==="string"){if(mgVerdictFound=!0,mgVerdict=entry.verdict,entry.verdict==="fail")return{blocked:!0,reason:"MUTATION_GATE_FAIL",message:`Phase ${phase} cannot be completed: mutation gate returned verdict 'fail'. Resolve surviving mutants or lower the kill-rate threshold before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};else if(!["pass","warn","skip"].includes(entry.verdict))return{blocked:!0,reason:"MUTATION_GATE_FAIL",message:`Phase ${phase} cannot be completed: mutation gate evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: pass, warn, fail, skip.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Mutation gate evidence unreadable:",readErr);mgVerdictFound=!1}if(!mgVerdictFound)return{blocked:!0,reason:"MUTATION_GATE_MISSING",message:`Phase ${phase} cannot be completed: mutation_test is enabled and evidence not found at .swarm/evidence/${phase}/mutation-gate.json. Run mutation_test, then call write_mutation_evidence before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(mgVerdict==="warn")safeWarn(`[phase_complete] Mutation gate verdict is 'warn' for phase ${phase} — proceeding with warning`,void 0)}}catch(mgError){if(mutationGateEnabled)return{blocked:!0,reason:"MUTATION_GATE_ERROR",message:`Phase ${phase} cannot be completed: mutation gate encountered an error when mutation_test was enabled. Error: ${String(mgError)}`,agentsDispatched,agentsMissing:[],warnings:[`MUTATION_GATE_ERROR: ${String(mgError)}`]};else safeWarn("[phase_complete] Mutation gate error (non-blocking):",mgError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}import*as fs207 from"node:fs";import*as path345 from"node:path";init_council_review_identity();function readLatestRetroTimestampMs2(dir,phase){let baseDir=path345.normalize(path345.resolve(dir,".swarm")),retroPath=path345.normalize(path345.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path345.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path345.sep)||retroPath===baseDir))return null;try{return latestRetroTimestampMsFromBundle(JSON.parse(fs207.readFileSync(retroPath,"utf-8")),phase)}catch{return null}}async function runPhaseCouncilGate(ctx){let{phase,dir,sessionID,pluginConfig,agentsDispatched,safeWarn}=ctx,gateWarnings=[],councilModeEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.phase_council===!0&&pluginConfig.council?.enabled===!0){if(preamble.identityBound===!1)return{blocked:!0,reason:"PHASE_COUNCIL_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: phase_council is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};councilModeEnabled=!0;let identity=computeCouncilReviewIdentity({level:"phase",scope:{kind:"phase",phaseNumber:phase},plan:preamble.plan??null,config:pluginConfig.council}),maxAgeMs=resolveCouncilFreshnessMaxAgeMs(pluginConfig.council),pcPath=path345.join(dir,".swarm","evidence",String(phase),"phase-council.json"),pcVerdictFound=!1,_pcVerdict,pcQuorumSize,pcPhaseNumber;try{let pcContent=fs207.readFileSync(pcPath,"utf-8"),pcBundle=JSON.parse(pcContent);for(let entry of pcBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="phase-council"&&typeof entry.verdict==="string"){if(pcVerdictFound=!0,_pcVerdict=entry.verdict,pcQuorumSize=typeof entry.quorumSize==="number"?entry.quorumSize:void 0,pcPhaseNumber=typeof entry.phase_number==="number"?entry.phase_number:typeof entry.phase==="number"?entry.phase:void 0,pcPhaseNumber===void 0||typeof pcPhaseNumber!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_PHASE",message:`Phase ${phase} cannot be completed: phase council evidence is missing phase_number field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcPhaseNumber!==phase)return{blocked:!0,reason:"PHASE_COUNCIL_PHASE_MISMATCH",message:`Phase ${phase} cannot be completed: phase council evidence is for phase ${pcPhaseNumber}, not phase ${phase}. Run council for the correct phase.`,agentsDispatched,agentsMissing:[],warnings:[]};let freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:parseTimestampMs(entry.timestamp),maxAgeMs,mustPostdateMs:latestRetroTimestampMsFromBundle(ctx.loadedRetroBundle,phase)??readLatestRetroTimestampMs2(dir,phase)});if(!freshness.ok)return{blocked:!0,reason:{invalid_timestamp:"PHASE_COUNCIL_INVALID_TIMESTAMP",future_timestamp:"PHASE_COUNCIL_FUTURE_TIMESTAMP",stale_evidence:"PHASE_COUNCIL_STALE_EVIDENCE",predates_required_input:"PHASE_COUNCIL_STALE_EVIDENCE",invalid_required_input:"PHASE_COUNCIL_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"PHASE_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: phase council ${freshness.message}. ${freshness.recovery}`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.identity_version!==COUNCIL_REVIEW_IDENTITY_VERSION)return{blocked:!0,reason:entry.identity_version?"PHASE_COUNCIL_IDENTITY_MISMATCH":"PHASE_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: phase council evidence ${entry.identity_version?`was produced under a different council identity schema version (${entry.identity_version}, expected ${COUNCIL_REVIEW_IDENTITY_VERSION})`:"predates the council review identity cutover and carries no identity proof"}. Re-convene the phase council for the current plan and policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.review_hash!==identity.reviewHash||!isIdentityDigest(entry.identity_digest)||entry.identity_digest!==identity.identityDigest)return{blocked:!0,reason:"PHASE_COUNCIL_STALE_REVIEW_IDENTITY",message:`Phase ${phase} cannot be completed: phase council evidence does not match the current council review identity (review-relevant plan content changed since the review). Re-convene the phase council.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.policy_digest!==identity.policyDigest)return{blocked:!0,reason:entry.policy_digest?"PHASE_COUNCIL_POLICY_MISMATCH":"PHASE_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: phase council evidence was produced under a different council policy. Re-convene the phase council under the current policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!entry.provenance||!entry.provenance.agent_name&&!entry.provenance.session_id){let msg=`Phase council evidence lacks provenance for phase ${phase}. Evidence should include agent_name or session_id for verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}if(entry.verdict==="REJECT"||entry.verdict==="reject"){let requiredFixes=entry.requiredFixes??entry.required_fixes??[],fixesDetail=Array.isArray(requiredFixes)&&requiredFixes.length>0?`
7755
7755
  Required fixes: ${requiredFixes.map((f)=>f.detail??JSON.stringify(f)).join("; ")}`:"";return{blocked:!0,reason:"PHASE_COUNCIL_REJECTED",message:`Phase ${phase} cannot be completed: phase council returned verdict 'REJECT'. Address the required fixes before completing the phase.${fixesDetail}`,agentsDispatched,agentsMissing:[],warnings:[]}}if(entry.verdict==="CONCERNS"||entry.verdict==="concerns"){if(!(pluginConfig.council?.phaseConcernsAllowComplete??!0)){let advisoryNotes=entry.advisoryNotes??entry.advisory_notes??[],notesDetail=Array.isArray(advisoryNotes)&&advisoryNotes.length>0?`
7756
7756
  Advisory notes: ${advisoryNotes.join("; ")}`:"";return{blocked:!0,reason:"PHASE_COUNCIL_CONCERNS",message:`Phase ${phase} cannot be completed: phase council returned verdict 'CONCERNS'.${notesDetail}`,agentsDispatched,agentsMissing:[],warnings:[]}}safeWarn(`[phase_complete] Phase council returned CONCERNS for phase ${phase} — proceeding (phaseConcernsAllowComplete is enabled)`,void 0)}if(entry.verdict!=="APPROVE"&&entry.verdict!=="approve"&&entry.verdict!=="CONCERNS"&&entry.verdict!=="concerns")return{blocked:!0,reason:"PHASE_COUNCIL_INVALID",message:`Phase ${phase} cannot be completed: phase council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: APPROVE, CONCERNS, REJECT.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Phase council evidence unreadable:",readErr);pcVerdictFound=!1}if(!pcVerdictFound)return{blocked:!0,reason:"PHASE_COUNCIL_REQUIRED",phase_council_required:!0,message:`Phase ${phase} cannot be completed: phase_council is enabled and phase council evidence not found at .swarm/evidence/${phase}/phase-council.json. Convene a phase-level council (dispatch 5 members, collect verdicts, call submit_phase_council_verdicts) before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:["Phase council required — convene 5 council members (critic, reviewer, sme, test_engineer, explorer) for holistic phase review. Call submit_phase_council_verdicts to synthesize verdicts and write phase-council.json evidence."]};let effectiveMinimum=pluginConfig.council.requireAllMembers?5:pluginConfig.council.minimumMembers??3;if(pcQuorumSize===void 0||typeof pcQuorumSize!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} cannot be completed: phase council evidence is missing quorumSize field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcQuorumSize<effectiveMinimum)return{blocked:!0,reason:"PHASE_COUNCIL_INSUFFICIENT_QUORUM",message:`Phase ${phase} cannot be completed: phase council quorum (${pcQuorumSize}) is below minimum (${effectiveMinimum}). Re-convene council with sufficient members.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(pcError){if(councilModeEnabled)return{blocked:!0,reason:"PHASE_COUNCIL_ERROR",message:`Phase ${phase} cannot be completed: phase council gate encountered an error when phase_council was enabled. Error: ${String(pcError)}`,agentsDispatched,agentsMissing:[],warnings:[`PHASE_COUNCIL_ERROR: ${String(pcError)}`]};else safeWarn("[phase_complete] Phase council gate error (non-blocking):",pcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}init_gate_evidence();init_manager();async function runTodoGateGate(ctx){let{phase,dir,agentsDispatched,pluginConfig,safeWarn}=ctx,pass2=()=>({blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]});if(pluginConfig.todo_gate?.enabled===!1)return pass2();let taskIds;try{let phaseRecord=(await loadPlan(dir))?.phases.find((p)=>p.id===phase);if(!phaseRecord)return safeWarn(`todo_gate: no plan phase ${phase} found; gate passed without evidence`,void 0),pass2();taskIds=phaseRecord.tasks.map((task2)=>task2.id)}catch(planError){return safeWarn("todo_gate: plan load failed; gate passed without evidence",planError),pass2()}let warnings=[];for(let taskId of taskIds){let evidence2=null;try{evidence2=await readTaskEvidence(dir,taskId)}catch(evidenceError){safeWarn(`todo_gate: task ${taskId} evidence unreadable; skipped`,evidenceError);continue}let verdict=evaluateTodoGate(evidence2?.todo_scan,pluginConfig.todo_gate);if(verdict.status!=="exceeded")continue;if(verdict.blocked)return{blocked:!0,reason:"TODO_GATE_THRESHOLD_EXCEEDED",message:`Phase ${phase} cannot be completed: task ${taskId} todo_gate threshold exceeded. ${verdict.message??""}`,agentsDispatched,agentsMissing:[],warnings:[`todo_gate: task ${taskId} has ${verdict.count} high-priority TODOs (max ${verdict.max})`],recovery:{kind:"tool",action:"todo_extract",args:{task_id:taskId}},recoveryGuidance:"Resolve or remove the high-priority TODO comments listed in the gate message, or adjust the todo_gate config (raise max_high_priority / set enabled: false), then re-run todo_extract with the same task_id to refresh the recorded evidence."};warnings.push(`todo_gate advisory: task ${taskId} — ${verdict.count} high-priority TODOs (FIXME/HACK/XXX) exceed max_high_priority=${verdict.max}. ${verdict.message??""}`)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings}}import{createHash as createHash111}from"node:crypto";var MAX_DETAIL_CHARS=1024,MAX_WARNINGS=32,MAX_ACTORS=64,DEFAULT_GATE_TIMEOUT_MS=1e4,MAX_GATE_TIMEOUT_MS=30000;async function runBoundedGate(check3){let timeoutMs=Math.min(MAX_GATE_TIMEOUT_MS,Math.max(1,check3.timeoutMs??DEFAULT_GATE_TIMEOUT_MS)),timer;try{return await Promise.race([check3.run(),new Promise((_,reject2)=>{timer=setTimeout(()=>reject2(Error(`${check3.id.toUpperCase()}_TIMEOUT: gate read exceeded ${timeoutMs}ms`)),timeoutMs)})])}finally{if(timer)clearTimeout(timer)}}function bounded(value,fallback=""){let text=typeof value==="string"?value:fallback;return text.length<=MAX_DETAIL_CHARS?text:`${text.slice(0,MAX_DETAIL_CHARS-1)}…`}function boundedStrings(value,limit=MAX_ACTORS){if(!Array.isArray(value))return[];return value.filter((item)=>typeof item==="string").slice(0,limit).map((item)=>bounded(item))}function recoveryFrom(result){let raw=result.recovery;if(!raw||typeof raw!=="object"||Array.isArray(raw))return;let candidate2=raw;if(!["tool","command","retry","user_action"].includes(String(candidate2.kind))||typeof candidate2.action!=="string"||candidate2.action.length===0)return;return{kind:candidate2.kind,action:bounded(candidate2.action),...candidate2.args&&typeof candidate2.args==="object"&&!Array.isArray(candidate2.args)?{args:candidate2.args}:{}}}function defaultBlockedRecovery(check3,result){let action2={critical_directives:"knowledge_receipt",retrospective:"write_retro",completion_verify:"completion_verify",drift:"write_drift_evidence",hallucination:"write_hallucination_evidence",mutation:"write_mutation_evidence",final_review:"run_phase_review",lean_turbo_readiness:"lean_turbo_review"}[check3.id];if(action2){if(check3.id==="lean_turbo_readiness"){let blockedOnCritic=/critic/i.test(`${result.message??""} ${result.reason??""}`);return{kind:"tool",action:action2,...blockedOnCritic?{args:{follow_up_tool:"lean_turbo_critic"}}:{}}}return{kind:"tool",action:action2}}if(check3.id==="phase_council"||check3.id==="final_council")return{kind:"user_action",action:"Task",args:{agents:["critic","reviewer","sme","test_engineer","explorer"],follow_up_tool:check3.id==="phase_council"?"submit_phase_council_verdicts":"write_final_council_evidence"}};if(check3.id==="architecture_supervisor")return{kind:"user_action",action:"Task",args:{agents:["critic_architecture_supervisor"],follow_up_tool:"write_architecture_supervisor_evidence"}};if(check3.id==="full_auto_approval")return{kind:"user_action",action:"Task",args:{agents:["critic_oversight"]}};if(check3.id==="required_agents")return{kind:"user_action",action:"Task",args:{agents:boundedStrings(result.agentsMissing)}};return{kind:"retry",action:"phase_complete"}}function retrospectiveGateFrom(result){let raw=result.retrospective_gate;if(!raw||typeof raw!=="object"||Array.isArray(raw))return;let candidate2=raw;if(typeof candidate2.schema_valid!=="boolean"||typeof candidate2.gate_pass!=="boolean")return;return{schema_valid:candidate2.schema_valid,gate_pass:candidate2.gate_pass,...candidate2.verdict==="pass"||candidate2.verdict==="fail"?{verdict:candidate2.verdict}:{}}}function stableReportHash(phase,entries2){return createHash111("sha256").update(JSON.stringify({schemaVersion:1,phase,entries:entries2})).digest("hex")}async function collectPhaseGateReport(input){let entries2=[];for(let check3 of input.checks){if(check3.applicable===!1){entries2.push({id:check3.id,code:"NOT_APPLICABLE",outcome:"not_applicable",detail:bounded(check3.notApplicableDetail,"gate not applicable"),evidenceRefs:[],responsibleActor:check3.responsibleActor,agentsDispatched:[],agentsMissing:[],warnings:[]});continue}try{let result=await runBoundedGate(check3),recovery=recoveryFrom(result)??(result.blocked?defaultBlockedRecovery(check3,result):void 0),retrospectiveGate=retrospectiveGateFrom(result);entries2.push({id:check3.id,code:typeof result.reason==="string"?bounded(result.reason):result.blocked?`${check3.id.toUpperCase()}_BLOCKED`:"PASS",outcome:result.blocked?"block":"pass",...typeof result.message==="string"?{detail:bounded(result.message)}:{},evidenceRefs:boundedStrings(result.evidenceRefs),responsibleActor:check3.responsibleActor,...recovery?{recovery,requiredRecoveryKind:recovery.kind}:{},...retrospectiveGate?{retrospective_gate:retrospectiveGate}:{},agentsDispatched:boundedStrings(result.agentsDispatched),agentsMissing:boundedStrings(result.agentsMissing),warnings:boundedStrings(result.warnings,MAX_WARNINGS),...typeof result.recovery_guidance==="string"?{recoveryGuidance:bounded(result.recovery_guidance)}:{},...result.phase_council_required===!0?{phase_council_required:!0}:{},...result.final_council_required===!0?{final_council_required:!0}:{}})}catch(error93){entries2.push({id:check3.id,code:error93 instanceof Error&&error93.message.startsWith(`${check3.id.toUpperCase()}_TIMEOUT:`)?`${check3.id.toUpperCase()}_TIMEOUT`:`${check3.id.toUpperCase()}_ERROR`,outcome:"error",detail:bounded(error93 instanceof Error?error93.message:String(error93),"unknown gate error"),evidenceRefs:[],responsibleActor:check3.responsibleActor,recovery:{kind:"retry",action:"phase_complete"},requiredRecoveryKind:"retry",agentsDispatched:[],agentsMissing:[],warnings:[]})}}let outcome=entries2.some((entry)=>entry.outcome==="block"||entry.outcome==="error")?"block":"pass";return{schemaVersion:1,phase:input.phase,outcome,reportHash:stableReportHash(input.phase,entries2),entries:entries2}}function formatPhaseGateCompatibility(report){let firstFailure=report.entries.find((entry)=>entry.outcome==="block"||entry.outcome==="error"),retrospectiveEntry=report.entries.find((entry)=>entry.id==="retrospective"&&entry.retrospective_gate),recoveryGuidance=report.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,requiredAgentsEntry=report.entries.find((entry)=>entry.id==="required_agents"),dispatched=new Set,missing=new Set,warnings=[];for(let entry of report.entries){for(let actor of entry.agentsDispatched)dispatched.add(actor);for(let actor of entry.agentsMissing)missing.add(actor);for(let warning of entry.warnings)if(warnings.length<MAX_WARNINGS&&!warnings.includes(warning))warnings.push(warning)}if(requiredAgentsEntry){dispatched.clear();for(let actor of requiredAgentsEntry.agentsDispatched)dispatched.add(actor)}return{success:report.outcome==="pass",phase:report.phase,status:report.outcome==="pass"?"success":firstFailure?.code==="REQUIRED_AGENTS_MISSING"?"incomplete":"blocked",...firstFailure?{reason:firstFailure.code,message:firstFailure.detail}:{},agentsDispatched:[...dispatched].sort(),agentsMissing:[...missing].sort(),warnings,gate_report:report,...recoveryGuidance?{recovery_guidance:recoveryGuidance}:{},...report.entries.some((entry)=>entry.phase_council_required)?{phase_council_required:!0}:{},...report.entries.some((entry)=>entry.final_council_required)?{final_council_required:!0}:{},...retrospectiveEntry?.retrospective_gate?{retrospective_gate:retrospectiveEntry.retrospective_gate}:{}}}import{createHash as createHash112}from"node:crypto";import*as fs208 from"node:fs";import*as path346 from"node:path";var MAX_SNAPSHOT_FILES=512,MAX_SNAPSHOT_ENTRIES=2048,MAX_SNAPSHOT_BYTES=16777216,INPUTS=[".swarm/evidence",".swarm/spec.md",".swarm/knowledge-receipts-v2.jsonl","specs","openspec/specs","openspec/changes"];function compareUtf8(left,right){return Buffer.compare(Buffer.from(left,"utf8"),Buffer.from(right,"utf8"))}function isContained3(root,candidate2){let relative89=path346.relative(root,candidate2);return relative89===""||relative89!==".."&&!relative89.startsWith(`..${path346.sep}`)&&!path346.isAbsolute(relative89)}function computePhaseEvidenceSnapshot(directory){let root=fs208.realpathSync(directory),entries2=[],totalBytes=0,visitedEntries=0,visit=(absolute)=>{if(!isContained3(root,absolute))throw Error("PHASE_SNAPSHOT_PATH_ESCAPE");let stat25;try{stat25=fs208.lstatSync(absolute)}catch(error93){if(error93.code==="ENOENT")return;throw error93}if(stat25.isSymbolicLink())throw Error(`PHASE_SNAPSHOT_UNSAFE_PATH: ${path346.relative(root,absolute)}`);if(stat25.isDirectory()){let names=[],handle=fs208.opendirSync(absolute);try{for(;;){let entry=handle.readSync();if(!entry)break;if(visitedEntries+=1,visitedEntries>MAX_SNAPSHOT_ENTRIES)throw Error("PHASE_SNAPSHOT_ENTRY_LIMIT");names.push(entry.name)}}finally{handle.closeSync()}for(let name of names.sort(compareUtf8))visit(path346.join(absolute,name));return}if(!stat25.isFile())throw Error(`PHASE_SNAPSHOT_NON_REGULAR: ${path346.relative(root,absolute)}`);if(entries2.length>=MAX_SNAPSHOT_FILES)throw Error("PHASE_SNAPSHOT_FILE_LIMIT");if(totalBytes+=stat25.size,totalBytes>MAX_SNAPSHOT_BYTES)throw Error("PHASE_SNAPSHOT_BYTE_LIMIT");let descriptor=fs208.openSync(absolute,fs208.constants.O_RDONLY|(fs208.constants.O_NOFOLLOW??0));try{let opened=fs208.fstatSync(descriptor);if(!opened.isFile()||opened.dev!==stat25.dev||opened.ino!==stat25.ino||opened.size!==stat25.size)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");let bytes=fs208.readFileSync(descriptor),after=fs208.fstatSync(descriptor);if(after.size!==opened.size||after.mtimeMs!==opened.mtimeMs||after.ctimeMs!==opened.ctimeMs)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");entries2.push({path:path346.relative(root,absolute).replaceAll("\\","/"),sha256:createHash112("sha256").update(bytes).digest("hex"),bytes:bytes.byteLength})}finally{fs208.closeSync(descriptor)}};for(let relative89 of INPUTS)visit(path346.join(root,...relative89.split("/")));return entries2.sort((left,right)=>compareUtf8(left.path,right.path)),createHash112("sha256").update(JSON.stringify({schemaVersion:1,entries:entries2})).digest("hex")}init_resolve_working_directory();var phaseCompleteReceiptInternals={recordPhaseCloseIntent,commitPhaseClosed,rebindCursorTaggedReceipts:(...args2)=>rebindCursorTaggedReceipts(...args2)},phaseCompleteCommitInternals={savePlan:(...args2)=>savePlan(...args2)},phaseCompletePreflightInternals={runCompletionVerifyGate,runDriftGate,runHallucinationGate,runMutationGate,runPhaseCouncilGate,runArchitectureSupervisorGate,runFinalReviewGate,runFinalCouncilGate,runTodoGateGate};function buildMissingAgentRecoveryGuidance(input){if(input.missing.length===0)return;let steps=[`Dispatch the missing required role${input.missing.length===1?"":"s"} (${input.missing.join(", ")}) and retry phase_complete after each Task returns a successful, non-empty result.`];if(input.docsAddedByConfig&&input.missing.includes("docs"))steps.push("If this phase genuinely has no documentation obligation, set phase_complete.require_docs to false in opencode-swarm configuration; that setting is independent of the QA gate profile.");if(!input.docsPlanReadable&&input.missing.includes("docs"))steps.push("A readable plan is required to bind durable docs participation. Restore or rebuild .swarm/plan.json/.swarm/plan.md (or recover from .swarm/plan-export/) before re-dispatching docs, then retry phase_complete.");if(input.docsEvidenceStatus==="corrupt")steps.push("The readable docs-participation projection is corrupt; a genuine docs re-dispatch will quarantine the original bytes and rebuild it safely.");else if(input.docsEvidenceStatus==="unreadable"||input.docsEvidenceStatus==="oversized")steps.push("The docs-participation projection needs operator repair or archival before a re-dispatch can persist new proof.");if(input.missing.includes("docs")&&input.docsEvidenceStatus==="missing")steps.push("No prior durable docs-participation receipt was found (this can happen after a plugin upgrade or a cleared evidence store). A fresh docs Task dispatch writes a new durable completion receipt and is the canonical recovery path.");if(input.policy==="warn")steps.push("The configured warn policy allows closure with a warning, but it does not create participation proof.");else steps.push('Last resort: if the missing role obligation genuinely cannot be satisfied in this environment, set phase_complete.policy to "warn" in opencode-swarm configuration. This weakens enforcement for every missing role and does NOT create durable participation proof, so only use it when the obligation cannot be met.');return steps.join(" ")}function safeWarn(message,error93){try{warn(message,error93 instanceof Error?error93.message:String(error93))}catch{}}var MAX_OUTPUT_BYTES7=512000,TASK_GATE_INFERABLE_AGENTS=new Set(["coder","reviewer","test_engineer"]);function canInferMissingAgentsFromTaskGates(agentsMissing){return agentsMissing.every((agent)=>TASK_GATE_INFERABLE_AGENTS.has(agent))}async function allCompletedTasksHavePassedGateEvidence(directory,tasks){for(let task2 of tasks){if(task2.status!=="completed")return!1;if(!await hasPassedAllGates(directory,task2.id,task2.files_touched??null))return!1}return tasks.length>0}function collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,callerSessionId){let agents=new Set,contributorSessionIds=[],callerSession=swarmState.agentSessions.get(callerSessionId);if(callerSession){if(contributorSessionIds.push(callerSessionId),callerSession.phaseAgentsDispatched)for(let agent of callerSession.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(callerSessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}for(let[sessionId,session]of swarmState.agentSessions){if(sessionId===callerSessionId)continue;let hasRecentToolCalls=session.lastToolCallTime>=phaseReferenceTimestamp,hasRecentDelegations=swarmState.delegationChains.get(sessionId)?.some((d)=>d.timestamp>=phaseReferenceTimestamp)??!1,hasRestoredAgents=(session.phaseAgentsDispatched?.size??0)>0&&session.lastPhaseCompleteTimestamp===phaseReferenceTimestamp;if(hasRecentToolCalls||hasRecentDelegations||hasRestoredAgents){if(contributorSessionIds.push(sessionId),session.phaseAgentsDispatched)for(let agent of session.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(sessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}}return{agents,contributorSessionIds}}function _getDelegationsSince(sessionID,sinceTimestamp){let chain=swarmState.delegationChains.get(sessionID);if(!chain)return[];if(sinceTimestamp===0)return chain;return chain.filter((entry)=>entry.timestamp>sinceTimestamp)}function isValidRetroEntry(entry,phase){return entry.type==="retrospective"&&"phase_number"in entry&&entry.phase_number===phase&&"verdict"in entry&&(entry.verdict==="pass"||entry.verdict==="fail")}async function executePhaseComplete(args2,workingDirectory,directory,_runtime={}){let phase=Number(args2.phase),summary=args2.summary,sessionID=args2.sessionID;if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase)||!Number.isInteger(phase))return JSON.stringify({success:!1,phase,status:"blocked",message:"Invalid phase number",agentsDispatched:[],warnings:["Phase must be a positive number"]},null,2);if(!sessionID)return JSON.stringify({success:!1,phase,message:"Session ID is required",agentsDispatched:[],warnings:["sessionID parameter is required for phase completion tracking"]},null,2);let phaseReferenceTimestamp=ensureAgentSession(sessionID).lastPhaseCompleteTimestamp??0,warnings=[];if(hasActiveTurboMode(sessionID))warnings.push(`Turbo mode active — skipped completion-verify, drift-verifier, hallucination-guard, mutation-gate, and phase-council gates for phase ${phase}.`);let crossSessionResult=collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,sessionID),agentsDispatched=Array.from(crossSessionResult.agents).sort(),dir=workingDirectory||directory,{config:config3}=loadPluginConfigWithMeta(dir),phaseCompleteConfig;try{phaseCompleteConfig=PhaseCompleteConfigSchema.parse(config3.phase_complete??{})}catch(parseError){return JSON.stringify({success:!1,phase,status:"incomplete",message:`Invalid phase_complete configuration: ${parseError instanceof Error?parseError.message:"Unknown error"}`,agentsDispatched,agentsMissing:[],warnings:["Configuration validation failed"]},null,2)}if(phaseCompleteConfig.enabled===!1){let disabledReport=await collectPhaseGateReport({phase,checks:["critical_directives","retrospective","completion_verify","drift","hallucination","mutation","phase_council","todo_gate","architecture_supervisor","final_review","final_council","full_auto_approval","lean_turbo_readiness","required_agents","snapshot_identity"].map((id)=>({id,responsibleActor:"architect",applicable:!1,notApplicableDetail:"phase completion enforcement is disabled",run:async()=>({blocked:!1,agentsDispatched:[],agentsMissing:[],warnings:[]})}))});return JSON.stringify({success:!0,phase,status:"disabled",message:`Phase ${phase} complete (enforcement disabled)`,agentsDispatched,agentsMissing:[],warnings:[],gate_report:disabledReport},null,2)}let receiptPlan=await loadPlan(dir).catch(()=>null),receiptPhaseLabel=receiptPlan?extractCurrentPhaseFromPlan(receiptPlan)??`Phase ${receiptPlan.current_phase??phase}`:`Phase ${phase}`,knowledgeEnabled=config3.knowledge?.enabled!==!1,retroFound=!1,retroEntry=null,invalidSchemaErrors=[],loadedRetroTaskId=null,loadedRetroBundle=null,retrospectiveGate={schema_valid:!1,gate_pass:!1},primaryRetroTaskId=`retro-${phase}`,preflightNowMs=Date.now(),gateCtx={phase,dir,sessionID,pluginConfig:config3,agentsDispatched,safeWarn,loadedRetroBundle,loadedRetroTaskId,preflightNowMs},passGate=(extra={})=>({blocked:!1,agentsDispatched,agentsMissing:[],warnings:[],...extra}),preflightChecks=[];preflightChecks.push({id:"critical_directives",responsibleActor:"architect",applicable:knowledgeEnabled,notApplicableDetail:"knowledge directives are disabled",run:async()=>{let requestedAccept=Array.isArray(args2.acceptViolations)?args2.acceptViolations.filter((value)=>typeof value==="string"&&value.length>0):[];if(requestedAccept.length>0){let callerAgent=args2.callerAgent??swarmState.activeAgent.get(sessionID)??"architect";if(stripKnownSwarmPrefix(callerAgent).toLowerCase()!=="architect")return{...passGate(),blocked:!0,reason:"OVERRIDE_DENIED_NON_ARCHITECT",message:"accept_violations is architect-only and cannot be committed by this caller."};let justification=typeof args2.acceptViolationsJustification==="string"?args2.acceptViolationsJustification.trim():"";return{...passGate(),blocked:!0,reason:justification.length>=10?"DIRECTIVE_OVERRIDE_SEPARATE_ACTION_REQUIRED":"OVERRIDE_REQUIRES_JUSTIFICATION",message:justification.length>=10?"Directive overrides are separate audited evidence writes. Record the override, then retry phase_complete without accept_violations.":"accept_violations requires at least 10 characters of substantive justification.",recovery:{kind:"tool",action:"record_directive_override",args:{directive_ids:requestedAccept,justification,phase}}}}let directiveGate=await evaluatePhaseCriticalDirectives({directory:dir,sessionId:sessionID,phaseLabel:receiptPhaseLabel,phaseId:phase});if(!directiveGate.blocked)return passGate();let skew=directiveGate.phaseLabelSkew,skewNote="";if(skew){let queried=skew.queried_label.slice(0,120).replace(/[\r\n]+/g," "),stored=skew.stored_label.slice(0,120).replace(/[\r\n]+/g," ");skewNote=skew.stored_phase_id!==void 0&&skew.stored_phase_id!==skew.phase_id?`
7757
7757
  Phase identity note for phase ${skew.phase_id}: an unresolved obligation was recorded under phase id ${skew.stored_phase_id} (label "${stored}") and matched this phase via its label — base-parity matching keeps it visible here. Resolve it or record its outcome to proceed.`:`
7758
- Phase label skew detected for phase ${skew.phase_id}: gate queried "${queried}" but obligations were recorded under "${stored}". Matching used the stable phase id.`}return{...passGate(),blocked:!0,reason:directiveGate.failedClosed?"DIRECTIVE_GATE_FAILED_CLOSED":"UNRESOLVED_CRITICAL_DIRECTIVES",message:directiveGate.failedClosed?"Critical-directive gate could not read authoritative receipt state; failing closed.":`${formatDirectiveBlockMessage(directiveGate.unresolved)}${skewNote}`,unresolved_directives:directiveGate.unresolved,..."recovery"in directiveGate&&directiveGate.recovery&&typeof directiveGate.recovery==="object"?{recovery:directiveGate.recovery}:{}}}}),preflightChecks.push({id:"retrospective",responsibleActor:"architect",run:async()=>{let retroResult=await loadEvidence(dir,primaryRetroTaskId,{migrate:!1}),candidates=[];if(retroResult.status==="found")candidates.push({taskId:primaryRetroTaskId,bundle:retroResult.bundle});else if(retroResult.status==="invalid_schema")invalidSchemaErrors.push(...retroResult.errors);if(candidates.length===0){let taskIds=(await listEvidenceTaskIds(dir)).filter((id)=>/^retro-\d+$/.test(id)).sort();for(let taskId of taskIds){let candidate2=await loadEvidence(dir,taskId,{migrate:!1});if(candidate2.status==="found")candidates.push({taskId,bundle:candidate2.bundle});else if(candidate2.status==="invalid_schema")invalidSchemaErrors.push(...candidate2.errors)}}for(let candidate2 of candidates){let entry=candidate2.bundle.entries?.find((item)=>isValidRetroEntry(item,phase));if(!entry)continue;if(retroFound=!0,retroEntry=entry,loadedRetroTaskId=candidate2.taskId,loadedRetroBundle=candidate2.bundle,retrospectiveGate={schema_valid:!0,gate_pass:entry.verdict==="pass",verdict:entry.verdict},gateCtx.loadedRetroTaskId=candidate2.taskId,gateCtx.loadedRetroBundle=candidate2.bundle,entry.verdict==="fail")return{...passGate(),blocked:!0,reason:"RETROSPECTIVE_FAILED",message:'The retrospective is schema-valid and truthfully records verdict "fail". Resolve the phase findings and write a new explicit verdict before retrying.',retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro"}};return passGate({retrospective_gate:retrospectiveGate})}let schemaDetail=invalidSchemaErrors.length>0?` Schema validation failed: ${invalidSchemaErrors.slice(0,8).join("; ")}.`:"";return{...passGate(),blocked:!0,reason:invalidSchemaErrors.length>0?"RETROSPECTIVE_SCHEMA_INVALID":"RETROSPECTIVE_MISSING",message:`Phase ${phase} cannot be completed without an explicit retrospective verdict.${schemaDetail}`,retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro",args:{phase}}}}});let turboActive=hasActiveTurboMode(sessionID),standardGateSpecs=[{id:"completion_verify",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runCompletionVerifyGate(gateCtx)},{id:"drift",actor:"critic",run:()=>phaseCompletePreflightInternals.runDriftGate(gateCtx)},{id:"hallucination",actor:"reviewer",run:()=>phaseCompletePreflightInternals.runHallucinationGate(gateCtx)},{id:"mutation",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runMutationGate(gateCtx)},{id:"phase_council",actor:"architect",run:()=>phaseCompletePreflightInternals.runPhaseCouncilGate(gateCtx)},{id:"todo_gate",actor:"coder",run:()=>phaseCompletePreflightInternals.runTodoGateGate(gateCtx)}];for(let spec of standardGateSpecs)preflightChecks.push({id:spec.id,responsibleActor:spec.actor,applicable:!turboActive,notApplicableDetail:"standard gate bypassed by active Turbo policy",run:spec.run});preflightChecks.push({id:"architecture_supervisor",responsibleActor:"architecture_supervisor",applicable:config3.architectural_supervision?.enabled===!0&&config3.architectural_supervision.mode==="gate",notApplicableDetail:"architecture supervision gate is not enabled",run:()=>phaseCompletePreflightInternals.runArchitectureSupervisorGate(gateCtx)}),preflightChecks.push({id:"final_review",responsibleActor:"reviewer",run:()=>phaseCompletePreflightInternals.runFinalReviewGate(gateCtx)}),preflightChecks.push({id:"final_council",responsibleActor:"architect",run:()=>phaseCompletePreflightInternals.runFinalCouncilGate(gateCtx)}),preflightChecks.push({id:"full_auto_approval",responsibleActor:"critic",run:async()=>{let approval=verifyFullAutoPhaseApproval(dir,sessionID,phase,config3);return approval.ok?passGate():{...passGate(),blocked:!0,reason:"FULL_AUTO_APPROVAL_REQUIRED",message:`Phase ${phase} cannot be completed: ${approval.reason??"Full-Auto v2 approval missing"}`,recovery:{kind:"user_action",action:"Task",args:{subagent_type:"critic_oversight",trigger_source:"phase_boundary",phase}}}}});let epicActiveForProject=isEpicModeActiveForProject(dir);preflightChecks.push({id:"lean_turbo_readiness",responsibleActor:"architect",applicable:hasActiveLeanTurbo(sessionID)&&!epicActiveForProject,notApplicableDetail:"Lean Turbo is inactive or Epic Mode owns readiness",run:async()=>{let leanConfig=config3?.turbo?.lean,check3=_internals287.verifyLeanTurboPhaseReady(dir,phase,sessionID,leanConfig?{phase_reviewer:leanConfig.phase_reviewer,phase_critic:leanConfig.phase_critic,integrated_diff_required:leanConfig.integrated_diff_required}:void 0);return check3.ok?passGate():{...passGate(),blocked:!0,reason:"LEAN_TURBO_PHASE_NOT_READY",message:`Phase ${phase} cannot be completed: ${check3.reason}`}}}),preflightChecks.push({id:"required_agents",responsibleActor:"architect",run:async()=>{let participationPlan=null,phaseRequiredAgents;try{participationPlan=await loadPlan(dir),phaseRequiredAgents=participationPlan?.phases.find((item)=>item.id===phase)?.required_agents}catch{participationPlan=null}let configured=[...phaseRequiredAgents??phaseCompleteConfig.required_agents],required3=[...configured];if(phaseCompleteConfig.require_docs&&!required3.includes("docs"))required3.push("docs");let docsStatus=null,durableDocsFound=!1;if(required3.includes("docs")){if(crossSessionResult.agents.delete("docs"),participationPlan){let receipt=await readPhaseParticipation(dir,participationPlan,phase,"docs");if(docsStatus=receipt.status,receipt.found)durableDocsFound=!0,crossSessionResult.agents.add("docs")}}let missing=required3.filter((role)=>!crossSessionResult.agents.has(role)),inferredFromTaskGates=[];if(missing.length>0)try{let target=participationPlan?.phases.find((item)=>item.id===phase);if(target&&target.tasks.length>0&&canInferMissingAgentsFromTaskGates(missing)&&await allCompletedTasksHavePassedGateEvidence(dir,target.tasks))inferredFromTaskGates=[...missing],missing=[]}catch{}let recoveryGuidance=buildMissingAgentRecoveryGuidance({missing,docsAddedByConfig:phaseCompleteConfig.require_docs&&!configured.includes("docs"),docsEvidenceStatus:docsStatus,docsPlanReadable:participationPlan!==null,policy:phaseCompleteConfig.policy}),authoritativeAgents=[...crossSessionResult.agents].sort();return missing.length>0&&phaseCompleteConfig.policy==="enforce"?{...passGate(),blocked:!0,reason:"REQUIRED_AGENTS_MISSING",message:`Phase ${phase} is missing required agents: ${missing.join(", ")}. ${recoveryGuidance}`,agentsMissing:missing,agentsDispatched:authoritativeAgents,recovery_guidance:recoveryGuidance,recovery:{kind:"user_action",action:"Task",args:{agents:missing}}}:passGate({agentsDispatched:durableDocsFound?[...new Set([...authoritativeAgents,"docs"])].sort():authoritativeAgents,recovery_guidance:recoveryGuidance,agentsMissing:missing,warnings:[...durableDocsFound?[`Recovered durable docs participation proof for phase ${phase}.`]:[],...inferredFromTaskGates.length>0?[`Agent dispatch fallback: all completed tasks in phase ${phase} have durable passing gate evidence. Clearing missing agents: ${inferredFromTaskGates.join(", ")}.`]:[],...missing.length>0?[`Warning: phase ${phase} missing required agents: ${missing.join(", ")} (advisory because phase_complete.policy=warn).`]:[]]})}}),preflightChecks.push({id:"snapshot_identity",responsibleActor:"architect",run:async()=>{let plan=await loadPlan(dir),structureHash=plan?computePlanStructureHash(plan):"plan:none",policyHash=createHash113("sha256").update(JSON.stringify(config3)).digest("hex"),evidenceHash=computePhaseEvidenceSnapshot(dir);return passGate({evidenceRefs:[`plan-structure:${structureHash}`,`policy:${policyHash}`,`phase-evidence:${evidenceHash}`]})}});let preflightReport=await collectPhaseGateReport({phase,checks:preflightChecks});if(preflightReport.outcome==="block")return JSON.stringify(formatPhaseGateCompatibility(preflightReport),null,2);for(let entry of preflightReport.entries)warnings.push(...entry.warnings);let acceptedRetro={found:retroFound,entry:retroEntry,taskId:loadedRetroTaskId,bundle:loadedRetroBundle},phaseRecoveryGuidance=preflightReport.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,phaseCommitAgent="phase-complete";for(let[,activeAgent]of swarmState.activeAgent){phaseCommitAgent=activeAgent;break}let planLockTaskId=`phase-complete-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,phasePlanLock;try{phasePlanLock=await tryAcquireLock(dir,"plan.json",phaseCommitAgent,planLockTaskId)}catch(error93){let detail=error93 instanceof Error?error93.message:String(error93);return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCK_ERROR",message:`Failed to acquire the guarded phase commit lock: ${detail}`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Phase commit lock acquisition failed: ${detail}`],recovery_guidance:"Resolve the filesystem or lock-directory error, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}if(!phasePlanLock.acquired){let lockOwner=phasePlanLock.existing?.agent??"another agent";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCKED",message:`Plan write is locked by ${lockOwner}.`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Concurrent plan write detected; lock is held by ${lockOwner}.`],recovery_guidance:"Wait for the current plan writer to finish, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}try{let lockedPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(lockedPreflight.outcome!=="pass"||lockedPreflight.reportHash!==preflightReport.reportHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence, plan identity, or policy changed after preflight. No phase transition or post-commit side effect was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,recovery:{kind:"retry",action:"phase_complete"}});let plan=await loadPlan(dir);if(plan?._ledgerReplayStale===!0){let staleReason=plan._ledgerReplayStaleReason??"unknown reason";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_STALE",message:`Plan write refused: plan.json is stale from a failed ledger replay (${staleReason}). Refusing to complete phase ${phase} against a known-stale plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[`Stale plan from failed ledger replay: ${staleReason}`],recovery_guidance:"The ledger replay failed and no critic-approved snapshot was available, so loadPlan fell back to a stale plan.json. Do NOT retry blindly. Recover first: re-verify the plan (re-run completion verification), reset the session, or restore from the latest checkpoint under .swarm/plan-export/, then retry phase_complete.",_ledgerReplayStaleReason:staleReason})}if(!plan&&await ledgerExists(dir))plan=await replayFromLedger(dir);let phaseObject=plan?plan.phases.find((candidate2)=>candidate2.id===phase):void 0;if(plan){if(!phaseObject)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_NOT_IN_PLAN",message:`Phase ${phase} is not present in the authoritative plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight})}else if(fs210.existsSync(validateSwarmPath(dir,"plan.json")))return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_UNREADABLE",message:"Plan exists but could not be read or rebuilt from the ledger; no phase transition was committed.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight});if(knowledgeEnabled){let closeIntent=await phaseCompleteReceiptInternals.recordPhaseCloseIntent(dir,receiptPhaseLabel,sessionID,void 0,phase);if(!closeIntent.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_CLOSE_INTENT_FAILED",message:"Phase completion blocked: could not persist receipt phase-close intent.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[closeIntent.detail],recovery:{kind:"retry",action:"phase_complete"}})}let commitPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(commitPreflight.outcome!=="pass")return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence or policy changed before the authoritative transition. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});let commitEvidenceRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("phase-evidence:")),commitPolicyRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("policy:")),expectedCommitEvidenceHash=commitEvidenceRef?.slice(15),expectedCommitPolicyHash=commitPolicyRef?.slice(7);if(!expectedCommitEvidenceHash||!expectedCommitPolicyHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"The commit-boundary evidence identity was unavailable. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});if(plan&&phaseObject&&!["complete","completed","closed"].includes(phaseObject.status)){phaseObject.status="complete";try{let saveDurability=await phaseCompleteCommitInternals.savePlan(dir,plan,{preserveCompletedStatuses:!0,planLockAlreadyHeld:!0,preCommitCheck:()=>{let currentPolicyHash=createHash113("sha256").update(JSON.stringify(loadPluginConfigWithMeta(dir).config)).digest("hex");if(computePhaseEvidenceSnapshot(dir)!==expectedCommitEvidenceHash||currentPolicyHash!==expectedCommitPolicyHash)throw Error("PHASE_PREFLIGHT_STALE: evidence changed at the authoritative transition boundary")}});if(saveDurability.durability==="incomplete")warnings.push(`Plan saved with incomplete durability; degraded surfaces: ${saveDurability.degraded_surfaces.join(", ")}`+(saveDurability.md_write_error?` (${saveDurability.md_write_error})`:""))}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("PHASE_PREFLIGHT_STALE:"))return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence changed at the authoritative transition boundary. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});throw error93}await takeSnapshotEvent(dir,plan).catch(()=>{return})}}finally{if(phasePlanLock.lock._release)await phasePlanLock.lock._release().catch((error93)=>{warn("[phase_complete] Plan lock release failed:",error93 instanceof Error?error93.message:String(error93))})}try{let normalizedPlan=await loadPlan(dir).catch(()=>null);if(normalizedPlan){let{rebound}=await phaseCompleteReceiptInternals.rebindCursorTaggedReceipts(dir,normalizedPlan,phase,"docs");if(rebound>0)warnings.push(`Re-stamped ${rebound} docs participation receipt(s) from the plan's stale current_phase cursor to phase ${phase}.`)}}catch(error93){warnings.push(`Docs participation receipt normalization failed: ${error93 instanceof Error?error93.message:String(error93)}.`)}if(knowledgeEnabled){let receiptClose=await phaseCompleteReceiptInternals.commitPhaseClosed(dir,receiptPhaseLabel,sessionID,void 0,phase);if(!receiptClose.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_RECEIPT_CLOSE_PENDING",message:"Plan phase closed, but receipt lifecycle closure is pending reconciliation; retry phase_complete.",agentsDispatched,agentsMissing:[],warnings:[...warnings,receiptClose.detail],gate_report:preflightReport,recovery:{kind:"retry",action:"phase_complete"}})}let requiredAgentsEntry=preflightReport.entries.find((entry)=>entry.id==="required_agents");if(requiredAgentsEntry)agentsDispatched.splice(0,agentsDispatched.length,...requiredAgentsEntry.agentsDispatched);let knowledgeConfig;try{knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch(parseErr){warnings.push(`Knowledge config validation failed: ${String(parseErr)}`),knowledgeConfig=KnowledgeConfigSchema.parse({})}if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)try{let projectName=path348.basename(dir),curationResult=await curateAndStoreSwarm(acceptedRetro.entry.lessons_learned,projectName,{phase_number:phase},dir,knowledgeConfig,{llmDelegate:createCuratorLLMDelegate(dir,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});if(curationResult&&curationResult.stored+curationResult.reinforced+curationResult.quarantined+curationResult.rejected>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[CURATOR] Knowledge curation: ${curationResult.stored} stored, ${curationResult.reinforced} reinforced, ${curationResult.skipped} skipped, ${curationResult.rejected} rejected, ${curationResult.quarantined} quarantined (unactionable).`)}}catch(error93){safeWarn("[phase_complete] Failed to curate lessons from retrospective:",error93)}let complianceWarnings=[];try{let curatorConfig=CuratorConfigSchema.parse(config3.curator??{});if(curatorConfig.enabled&&curatorConfig.phase_enabled){let llmDelegate=createCuratorLLMDelegate(dir,"phase",sessionID??void 0),curatorResult=await runCuratorPhase(dir,phase,agentsDispatched,curatorConfig,{},llmDelegate);{let scopeContent=curatorResult.digest?.summary??`Phase ${phase} curator analysis`,complianceWarnings2=curatorResult.compliance.filter((c)=>c.severity==="warning"),receipt=complianceWarnings2.length>0?buildRejectedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",blockingFindings:complianceWarnings2.map((c)=>({location:`phase-${c.phase}`,summary:c.description,severity:c.type==="missing_reviewer"?"high":"medium"})),evidenceReferences:[],passConditions:["resolve all compliance warnings before phase completion"]}):buildApprovedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",checkedAspects:["phase_compliance","knowledge_recommendations","phase_digest"],validatedClaims:[`phase: ${phase}`,`agents_dispatched: ${agentsDispatched.length}`,`knowledge_recommendations: ${curatorResult.knowledge_recommendations.length}`]});persistReviewReceipt(dir,receipt).catch(()=>{})}let knowledgeResult=await applyCuratorKnowledgeUpdates(dir,curatorResult.knowledge_recommendations,knowledgeConfig),driftAdvisoryPushedThisRun=!1;try{let{runDeterministicDriftCheck:runDeterministicDriftCheck2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift));await runDeterministicDriftCheck2(dir,phase,curatorResult,curatorConfig,(message2)=>{let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,message2),driftAdvisoryPushedThisRun=!0})}catch{}let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let digestSummary=curatorResult.digest?.summary?curatorResult.digest.summary.slice(0,200):"Phase analysis complete",complianceNote=curatorResult.compliance.length>0?` (${curatorResult.compliance.length} compliance observation(s))`:"",analyzeHint=curatorResult.knowledge_recommendations.length>0?" Call curator_analyze with recommendations to apply knowledge updates from this phase.":"";if(digestSummary!=="Phase analysis complete")pushAdvisory(callerSessionState,`[CURATOR] Phase ${phase} digest: ${digestSummary}${complianceNote}. Knowledge: ${knowledgeResult.applied} applied, ${knowledgeResult.skipped} skipped.${analyzeHint}`);try{let{readPriorDriftReports:readPriorDriftReports2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift)),phaseReport=(await readPriorDriftReports2(dir)).filter((r)=>r.phase===phase).pop();if(phaseReport&&phaseReport.drift_score>0&&!driftAdvisoryPushedThisRun)pushAdvisory(callerSessionState,`[CURATOR DRIFT DETECTED (phase ${phase}, score ${phaseReport.drift_score})]: Prior drift report found on disk. Consider running critic_drift_verifier before phase completion to get a proper drift review. Review drift report for phase ${phase} and address spec alignment if applicable.`)}catch{}}if(curatorResult.compliance.length>0&&!curatorConfig.suppress_warnings)complianceWarnings=curatorResult.compliance.map((obs)=>`[${obs.severity.toUpperCase()}] ${obs.description}`).slice(0,5)}}catch(curatorError){safeWarn("[phase_complete] Curator pipeline error (non-blocking):",curatorError)}try{if(config3.design_docs?.enabled===!0){let outDir=config3.design_docs.out_dir??"docs",{runDesignDocDriftCheck:runDesignDocDriftCheck2}=await Promise.resolve().then(() => (init_design_doc_drift(),exports_design_doc_drift)),docReport=await runDesignDocDriftCheck2(dir,phase,outDir);if(docReport?.verdict==="DOC_STALE"){let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let staleIds=docReport.stale_sections.map((s)=>s.section_id).slice(0,8).join(", ");pushAdvisory(callerSessionState,`[DESIGN-DOC DRIFT (phase ${phase})]: ${docReport.stale_sections.length} design-doc section(s) are stale (${staleIds}). Run /swarm design-docs --update to sync ${outDir}/ and append a design-changelog entry. Advisory only — does not block completion.`)}}}}catch(docDriftError){safeWarn("[phase_complete] Design-doc drift check error (non-blocking):",docDriftError)}let floorOptions={floorAction:knowledgeConfig.confidence_floor_action,floorMinOutcomes:knowledgeConfig.confidence_floor_min_outcomes,floorSignalThreshold:knowledgeConfig.confidence_floor_signal_threshold};try{let feedbackResult=await applySkillUsageFeedback(dir,{floorOptions});if(feedbackResult.processed>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Skill usage feedback: ${feedbackResult.processed} skills processed, ${feedbackResult.bumps} confidence updates applied.`)}}catch(skillUsageError){safeWarn("[phase_complete] Skill usage feedback error (non-blocking):",skillUsageError)}try{pruneSkillUsageLog(dir,500)}catch(skillPruneError){safeWarn("[phase_complete] Skill usage log pruning error (non-blocking):",skillPruneError)}try{let verdictMarkerPath=validateSwarmPath(dir,"verdict-feedback-last-processed.json"),verdictSinceTimestamp,verdictSinceEventId;try{let markerData=JSON.parse(fs210.readFileSync(verdictMarkerPath,"utf-8"));verdictSinceTimestamp=markerData.lastProcessedTimestamp,verdictSinceEventId=markerData.lastProcessedEventId}catch{}let{applyKnowledgeVerdictFeedback:applyKnowledgeVerdictFeedback2}=await Promise.resolve().then(() => (init_knowledge_events(),exports_knowledge_events)),verdictResult=await applyKnowledgeVerdictFeedback2(dir,{sinceTimestamp:verdictSinceTimestamp,sinceEventId:verdictSinceEventId,floorOptions});if(verdictResult.lastProcessedTimestamp)try{fs210.writeFileSync(verdictMarkerPath,JSON.stringify({lastProcessedTimestamp:verdictResult.lastProcessedTimestamp,lastProcessedEventId:verdictResult.lastProcessedEventId}),"utf-8")}catch{}if(verdictResult.bumps>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Knowledge verdict feedback: ${verdictResult.processed} entries processed, ${verdictResult.bumps} confidence updates applied.`)}}catch(verdictError){safeWarn("[phase_complete] Knowledge verdict feedback error (non-blocking):",verdictError)}let agentsMissing=[...requiredAgentsEntry?.agentsMissing??[]],VALID_TASK_COMPLEXITY=["trivial","simple","moderate","complex"],firstEntry=acceptedRetro.bundle?.entries?.[0];if(acceptedRetro.taskId!==primaryRetroTaskId&&acceptedRetro.taskId?.startsWith("retro-")&&acceptedRetro.bundle?.schema_version==="1.0.0"&&firstEntry?.task_complexity&&VALID_TASK_COMPLEXITY.includes(firstEntry.task_complexity))warnings.push(`Retrospective data for phase ${phase} may have been automatically migrated to current schema format.`);let success3=!0,status2=agentsMissing.length>0?"warned":"success",safeSummary=summary?.trim().slice(0,500),message=safeSummary?`Phase ${phase} completed: ${safeSummary}`:`Phase ${phase} completed`,result={success:success3,phase,status:status2,message,agentsDispatched,agentsMissing,warnings,gate_report:preflightReport,...phaseRecoveryGuidance?{recovery_guidance:phaseRecoveryGuidance}:{}},hasPlan=!1;try{hasPlan=fs210.existsSync(validateSwarmPath(dir,"plan.json"))}catch{}if(!hasPlan&&!crossSessionResult.agents.has("reviewer")&&!crossSessionResult.agents.has("test_engineer"))warnings.push(`⚠️ Plan-free phase ${phase}: no independent reviewer or test_engineer dispatch detected. Code changes in plan-free sessions should have independent review. Consider dispatching reviewer + test_engineer before completing future plan-free phases.`);if(!hasPlan)warnings.push(`Warning: failed to update plan.json phase status because no authoritative plan was found; phase ${phase} completed in plan-free mode.`);if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)await updateRetrievalOutcome(dir,`Phase ${phase}`,success3).catch(()=>{});if(phaseCompleteConfig.regression_sweep?.enforce)try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs210.readFileSync(planPath,"utf-8"),targetPhase=JSON.parse(planRaw).phases.find((p)=>p.id===phase);if(targetPhase){let sweepFound=!1;for(let task2 of targetPhase.tasks){let taskEvidenceResult=await loadEvidence(dir,task2.id);if(taskEvidenceResult.status==="found"){let entries2=taskEvidenceResult.bundle.entries??[];for(let entry of entries2)if(entry.regression_sweep!==void 0){sweepFound=!0;break}}if(sweepFound)break}if(!sweepFound)warnings.push(`Warning: regression_sweep.enforce=true but no regression-sweep result found for any task in phase ${phase}. Run tests to populate regression-sweep results.`)}}catch{}let now2=Date.now(),durationMs=now2-phaseReferenceTimestamp,event={event:"phase_complete",phase,timestamp:new Date(now2).toISOString(),agents_dispatched:agentsDispatched,agents_missing:agentsMissing,status:status2,summary:safeSummary??null};try{appendCoreEventSync(dir,{...event})}catch(writeError){warnings.push(`Warning: failed to write phase complete event: ${writeError instanceof Error?writeError.message:String(writeError)}`)}if(success3){try{let skillConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{});if(skillConfig.enabled&&skillConfig.trigger==="scheduled")runSkillConsolidationFireAndForget({directory:dir,config:skillConfig,source:"phase_complete",sessionId:sessionID,enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},(consolidationResult)=>{if(!consolidationResult.started)return;let sessionState=swarmState.agentSessions.get(sessionID);if(!sessionState)return;let activatedSlugs=consolidationResult.result?.autoApply?.approved??[],activationSuffix=activatedSlugs.length>0?` and auto-activated ${activatedSlugs.length} skill(s): ${activatedSlugs.join(", ")}.`:" and auto-activated no skills.";pushAdvisory(sessionState,`[SKILL CONSOLIDATION] Scheduled skill_improver consolidation wrote ${consolidationResult.result?.proposalPath??"a proposal"}${activationSuffix}`)},(err)=>{safeWarn("[phase_complete] Scheduled skill consolidation error (non-blocking):",err)})}catch(skillConsolidationError){safeWarn("[phase_complete] Scheduled skill consolidation setup error (non-blocking):",skillConsolidationError)}try{let memoryConfig=config3.memory;if(memoryConfig?.enabled&&memoryConfig.consolidation?.enabled)runMemoryConsolidationFireAndForget({directory:dir,config:memoryConfig,phase,sessionId:sessionID},void 0,(err)=>{safeWarn("[phase_complete] Memory consolidation error (non-blocking):",err)})}catch(memoryConsolidationError){safeWarn("[phase_complete] Memory consolidation setup error (non-blocking):",memoryConsolidationError)}for(let contributorSessionId of crossSessionResult.contributorSessionIds){let contributorSession=swarmState.agentSessions.get(contributorSessionId);if(contributorSession){if(contributorSession.phaseAgentsDispatched.size>0)contributorSession.lastCompletedPhaseAgentsDispatched=new Set(contributorSession.phaseAgentsDispatched);contributorSession.phaseAgentsDispatched=new Set,contributorSession.fullAutoInteractionCount=0,contributorSession.fullAutoDeadlockCount=0,contributorSession.fullAutoLastQuestionHash=null,contributorSession.lastPhaseCompleteTimestamp=now2;let oldPhase=contributorSession.lastPhaseCompletePhase;contributorSession.lastPhaseCompletePhase=phase,telemetry.phaseChanged(contributorSessionId,oldPhase??0,phase)}}try{if(knowledgeConfig.sweep_enabled){let swarmPath3=resolveSwarmKnowledgePath(dir);if(await sweepAgedEntries(swarmPath3,knowledgeConfig.default_max_phases),await sweepStaleTodos(swarmPath3,knowledgeConfig.todo_max_phases),knowledgeConfig.hive_enabled){let hivePath=resolveHiveKnowledgePath2();await sweepAgedEntries(hivePath,knowledgeConfig.default_max_phases),await sweepStaleTodos(hivePath,knowledgeConfig.todo_max_phases)}}}catch(err){let detail=String(err);if(detail.includes("ELOCKED"))detail="lock timeout (stale lock detected)";else if(detail.includes("ENOSPC"))detail="disk full";else if(detail.includes("EACCES"))detail="permission denied";warnings.push(`Knowledge sweep failed for phase ${phase}: ${detail}`)}}if(complianceWarnings.length>0)warnings.push(`Curator compliance: ${complianceWarnings.join("; ")}`);await flushPendingSnapshot(dir),await writeCheckpoint(dir).catch(()=>{});try{let curatorCfg=CuratorConfigSchema.parse(config3.curator??{});if(curatorCfg.enabled&&curatorCfg.postmortem_enabled){let finalPlan=await loadPlan(dir);if(finalPlan?.phases?.length){if(finalPlan.phases.every((p)=>p.status==="complete")){let{runCuratorPostMortem:runCuratorPostMortem2}=await Promise.resolve().then(() => (init_curator_postmortem(),exports_curator_postmortem)),pmResult=await runCuratorPostMortem2(dir,{llmDelegate:createCuratorLLMDelegate(dir,"postmortem",sessionID),scope:"project",sessionID});if(pmResult.success&&pmResult.summary)warnings.push(`[POST-MORTEM] ${pmResult.summary}`);if(pmResult.warnings.length>0)for(let w of pmResult.warnings)warnings.push(`[POST-MORTEM] ${w}`)}}}}catch{}let outputData={...result,timestamp:event.timestamp,duration_ms:durationMs};return _buildOutputJson(outputData)}function _buildOutputJson(outputData){let json3=JSON.stringify(outputData,null,2);if(json3.length>MAX_OUTPUT_BYTES7){let truncated={_truncated:!0,_truncation_reason:`Output exceeded MAX_OUTPUT_BYTES (${MAX_OUTPUT_BYTES7}) limit`,phase:outputData.phase,success:outputData.success,status:outputData.status,message:outputData.message,agentsDispatched:outputData.agentsDispatched?.slice(0,10),agentsMissing:outputData.agentsMissing?.slice(0,10),warnings:["(output truncated — full output exceeded size limit)"],timestamp:outputData.timestamp,duration_ms:outputData.duration_ms};json3=JSON.stringify(truncated,null,2)}return json3}function createPhaseCompleteTool(runtime={}){return createSwarmTool({description:"Mark a phase as complete and track which agents were dispatched. Used for phase completion gating and tracking. Accepts phase number and optional summary. Returns list of agents that were dispatched.",args:{phase:exports_external.number().int().min(1).describe("The phase number being completed — a positive integer (e.g., 1, 2, 3)"),summary:exports_external.string().optional().describe("Optional summary of what was accomplished in this phase"),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."),accept_violations:exports_external.array(exports_external.string()).optional().describe("DEPRECATED COMPATIBILITY INPUT. phase_complete never records directive overrides. When supplied, it fails closed with recovery instructions for the architect-only record_directive_override action."),accept_violations_justification:exports_external.string().optional().describe("Written justification retained only for deprecated compatibility input; use it with record_directive_override instead.")},execute:async(args2,directory,ctx)=>{let phaseCompleteArgs,workingDirInput;try{phaseCompleteArgs={phase:Number(args2.phase),summary:args2.summary!==void 0?String(args2.summary):void 0,sessionID:ctx?.sessionID??(args2.sessionID!==void 0?String(args2.sessionID):void 0),acceptViolations:Array.isArray(args2.accept_violations)?args2.accept_violations.map((s)=>String(s)):void 0,acceptViolationsJustification:args2.accept_violations_justification!==void 0?String(args2.accept_violations_justification):void 0,callerAgent:ctx?.agent!==void 0?String(ctx.agent):void 0},workingDirInput=args2.working_directory!==void 0?String(args2.working_directory):void 0}catch{return JSON.stringify({success:!1,phase:0,message:"Invalid arguments",agentsDispatched:[],warnings:["Failed to parse arguments"]},null,2)}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:phaseCompleteArgs.phase,message:dirResult.message,agentsDispatched:[],warnings:[dirResult.message]},null,2);return executePhaseComplete(phaseCompleteArgs,dirResult.directory,dirResult.directory,runtime)}})}var phase_complete=createPhaseCompleteTool();init_zod();init_discovery();init_utils();init_bun_compat();init_external_tool_runner();init_create_tool();import*as fs211 from"node:fs";import*as path349 from"node:path";var MAX_OUTPUT_BYTES8=52428800,AUDIT_TIMEOUT_MS=120000;function resolveAuditCommandDefault(name){if(process.platform!=="win32")return[name];let resolved=resolveExecutableFromPath([name]);if(!resolved)return[name];let lowered=resolved.toLowerCase();if(lowered.endsWith(".cmd")||lowered.endsWith(".bat")){if(/["&|<>^!%]/.test(resolved))return[name];return["cmd.exe","/d","/s","/c",`call "${resolved}"`]}return[resolved]}var _internals290={bunSpawn,resolveAuditCommand:resolveAuditCommandDefault};function isValidEcosystem(value){return typeof value==="string"&&["auto","npm","pip","cargo","go","dotnet","ruby","dart","composer"].includes(value)}function validateArgs3(args2){if(typeof args2!=="object"||args2===null)return!0;let obj=args2;if(obj.ecosystem!==void 0&&!isValidEcosystem(obj.ecosystem))return!1;return!0}function detectEcosystems(directory){let ecosystems=[],cwd=directory;if(fs211.existsSync(path349.join(cwd,"package.json")))ecosystems.push("npm");if(fs211.existsSync(path349.join(cwd,"pyproject.toml"))||fs211.existsSync(path349.join(cwd,"requirements.txt")))ecosystems.push("pip");if(fs211.existsSync(path349.join(cwd,"Cargo.toml")))ecosystems.push("cargo");if(fs211.existsSync(path349.join(cwd,"go.mod")))ecosystems.push("go");try{if(fs211.readdirSync(cwd).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))ecosystems.push("dotnet")}catch{}if(fs211.existsSync(path349.join(cwd,"Gemfile"))||fs211.existsSync(path349.join(cwd,"Gemfile.lock")))ecosystems.push("ruby");if(fs211.existsSync(path349.join(cwd,"pubspec.yaml")))ecosystems.push("dart");if(fs211.existsSync(path349.join(cwd,"composer.lock")))ecosystems.push("composer");return ecosystems}function auditFailureResult(ecosystem,command,error93,isToolMissing,toolMissingNote,genericNotePrefix){let message=error93 instanceof Error?error93.message:"Unknown error",base={ecosystem,command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0};if(classifySpawnFailure(error93)==="cwd-missing")return{...base,note:`${genericNotePrefix}: ${message}`};if(isToolMissing(message))return{...base,note:toolMissingNote};return{...base,note:`${genericNotePrefix}: ${message}`}}function npmAuditFailure(command,error93){return auditFailureResult("npm",command,error93,(m)=>m.includes("audit")||m.includes("command not found")||m.includes("'npm' is not recognized"),"npm audit not available - npm may not be installed","Error running npm audit")}function cargoAuditFailure(command,error93){return auditFailureResult("cargo",command,error93,(m)=>m.includes("not found")||m.includes("not recognized")||m.includes("cargo-audit"),"cargo-audit not installed. Install with: cargo install cargo-audit","Error running cargo audit")}async function runNpmAudit(directory){let command=[..._internals290.resolveAuditCommand("npm"),"audit","--json"];try{let proc=_internals290.bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`npm audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return npmAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let jsonOutput=stdout,jsonMatch=stdout.match(/\{[\s\S]*\}/)||stderr.match(/\{[\s\S]*\}/);if(jsonMatch)jsonOutput=jsonMatch[0];let response=JSON.parse(jsonOutput),findings=[];if(response.vulnerabilities)for(let[pkgName,vuln]of Object.entries(response.vulnerabilities)){let patchedVersion=null;if(vuln.fixAvailable&&typeof vuln.fixAvailable==="object")patchedVersion=vuln.fixAvailable.version;else if(vuln.fixAvailable===!0)patchedVersion="latest";let severity2=mapNpmSeverity(vuln.severity);findings.push({package:pkgName,installedVersion:vuln.range,patchedVersion,severity:severity2,title:vuln.title||`Vulnerability in ${pkgName}`,cve:vuln.cves&&vuln.cves.length>0?vuln.cves[0]:null,url:vuln.url||null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"npm",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){return npmAuditFailure(command,error93)}}function mapNpmSeverity(severity2){switch(severity2.toLowerCase()){case"critical":return"critical";case"high":return"high";case"moderate":return"moderate";case"low":return"low";default:return"info"}}async function runPipAudit(directory){let command=["pip-audit","--format=json"];try{let proc=bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);if(await proc.exited===0&&!stdout.trim())return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let packages=[];try{let parsed=JSON.parse(stdout);if(Array.isArray(parsed))packages=parsed;else if(parsed.dependencies)packages=parsed.dependencies}catch{if(stderr.includes("not installed")||stdout.includes("not installed")||stderr.includes("command not found"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit output could not be parsed: ${stdout.slice(0,200)}`}}let findings=[];for(let pkg of packages)if(pkg.vulns&&pkg.vulns.length>0)for(let vuln of pkg.vulns){let severity2=vuln.aliases&&vuln.aliases.length>0?"high":"moderate";findings.push({package:pkg.name,installedVersion:pkg.version,patchedVersion:vuln.fix_versions&&vuln.fix_versions.length>0?vuln.fix_versions[0]:null,severity:severity2,title:vuln.id,cve:vuln.aliases&&vuln.aliases.length>0?vuln.aliases[0]:null,url:vuln.id.startsWith("CVE-")?`https://nvd.nist.gov/vuln/detail/${vuln.id}`:null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"pip",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";if(errorMessage3.includes("not found")||errorMessage3.includes("not recognized")||errorMessage3.includes("pip-audit"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running pip-audit: ${errorMessage3}`}}}async function runCargoAudit(directory){let command=[..._internals290.resolveAuditCommand("cargo"),"audit","--json"];try{let proc=_internals290.bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`cargo audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr:_stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return cargoAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let findings=[],lines=stdout.split(`
7758
+ Phase label skew detected for phase ${skew.phase_id}: gate queried "${queried}" but obligations were recorded under "${stored}". Matching used the stable phase id.`}return{...passGate(),blocked:!0,reason:directiveGate.failedClosed?"DIRECTIVE_GATE_FAILED_CLOSED":"UNRESOLVED_CRITICAL_DIRECTIVES",message:directiveGate.failedClosed?"Critical-directive gate could not read authoritative receipt state; failing closed.":`${formatDirectiveBlockMessage(directiveGate.unresolved)}${skewNote}`,unresolved_directives:directiveGate.unresolved,..."recovery"in directiveGate&&directiveGate.recovery&&typeof directiveGate.recovery==="object"?{recovery:directiveGate.recovery}:{}}}}),preflightChecks.push({id:"retrospective",responsibleActor:"architect",run:async()=>{let retroResult=await loadEvidence(dir,primaryRetroTaskId,{migrate:!1}),candidates=[];if(retroResult.status==="found")candidates.push({taskId:primaryRetroTaskId,bundle:retroResult.bundle});else if(retroResult.status==="invalid_schema")invalidSchemaErrors.push(...retroResult.errors);if(candidates.length===0){let taskIds=(await listEvidenceTaskIds(dir)).filter((id)=>/^retro-\d+$/.test(id)).sort();for(let taskId of taskIds){let candidate2=await loadEvidence(dir,taskId,{migrate:!1});if(candidate2.status==="found")candidates.push({taskId,bundle:candidate2.bundle});else if(candidate2.status==="invalid_schema")invalidSchemaErrors.push(...candidate2.errors)}}for(let candidate2 of candidates){let entry=candidate2.bundle.entries?.find((item)=>isValidRetroEntry(item,phase));if(!entry)continue;if(retroFound=!0,retroEntry=entry,loadedRetroTaskId=candidate2.taskId,loadedRetroBundle=candidate2.bundle,retrospectiveGate={schema_valid:!0,gate_pass:entry.verdict==="pass",verdict:entry.verdict},gateCtx.loadedRetroTaskId=candidate2.taskId,gateCtx.loadedRetroBundle=candidate2.bundle,entry.verdict==="fail")return{...passGate(),blocked:!0,reason:"RETROSPECTIVE_FAILED",message:'The retrospective is schema-valid and truthfully records verdict "fail". Resolve the phase findings and write a new explicit verdict before retrying.',retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro"}};return passGate({retrospective_gate:retrospectiveGate})}let schemaDetail=invalidSchemaErrors.length>0?` Schema validation failed: ${invalidSchemaErrors.slice(0,8).join("; ")}.`:"";return{...passGate(),blocked:!0,reason:invalidSchemaErrors.length>0?"RETROSPECTIVE_SCHEMA_INVALID":"RETROSPECTIVE_MISSING",message:`Phase ${phase} cannot be completed without an explicit retrospective verdict.${schemaDetail}`,retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro",args:{phase}}}}});let turboActive=hasActiveTurboMode(sessionID),standardGateSpecs=[{id:"completion_verify",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runCompletionVerifyGate(gateCtx)},{id:"drift",actor:"critic",run:()=>phaseCompletePreflightInternals.runDriftGate(gateCtx)},{id:"hallucination",actor:"reviewer",run:()=>phaseCompletePreflightInternals.runHallucinationGate(gateCtx)},{id:"mutation",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runMutationGate(gateCtx)},{id:"phase_council",actor:"architect",run:()=>phaseCompletePreflightInternals.runPhaseCouncilGate(gateCtx)},{id:"todo_gate",actor:"coder",run:()=>phaseCompletePreflightInternals.runTodoGateGate(gateCtx)}];for(let spec of standardGateSpecs)preflightChecks.push({id:spec.id,responsibleActor:spec.actor,applicable:!turboActive,notApplicableDetail:"standard gate bypassed by active Turbo policy",run:spec.run});preflightChecks.push({id:"architecture_supervisor",responsibleActor:"architecture_supervisor",applicable:config3.architectural_supervision?.enabled===!0&&config3.architectural_supervision.mode==="gate",notApplicableDetail:"architecture supervision gate is not enabled",run:()=>phaseCompletePreflightInternals.runArchitectureSupervisorGate(gateCtx)}),preflightChecks.push({id:"final_review",responsibleActor:"reviewer",run:()=>phaseCompletePreflightInternals.runFinalReviewGate(gateCtx)}),preflightChecks.push({id:"final_council",responsibleActor:"architect",run:()=>phaseCompletePreflightInternals.runFinalCouncilGate(gateCtx)}),preflightChecks.push({id:"full_auto_approval",responsibleActor:"critic",run:async()=>{let approval=verifyFullAutoPhaseApproval(dir,sessionID,phase,config3);return approval.ok?passGate():{...passGate(),blocked:!0,reason:"FULL_AUTO_APPROVAL_REQUIRED",message:`Phase ${phase} cannot be completed: ${approval.reason??"Full-Auto v2 approval missing"}`,recovery:{kind:"user_action",action:"Task",args:{subagent_type:"critic_oversight",trigger_source:"phase_boundary",phase}}}}});let epicActiveForProject=isEpicModeActiveForProject(dir);preflightChecks.push({id:"lean_turbo_readiness",responsibleActor:"architect",applicable:hasActiveLeanTurbo(sessionID)&&!epicActiveForProject,notApplicableDetail:"Lean Turbo is inactive or Epic Mode owns readiness",run:async()=>{let leanConfig=config3?.turbo?.lean,check3=_internals287.verifyLeanTurboPhaseReady(dir,phase,sessionID,leanConfig?{phase_reviewer:leanConfig.phase_reviewer,phase_critic:leanConfig.phase_critic,integrated_diff_required:leanConfig.integrated_diff_required}:void 0);return check3.ok?passGate():{...passGate(),blocked:!0,reason:"LEAN_TURBO_PHASE_NOT_READY",message:`Phase ${phase} cannot be completed: ${check3.reason}`,recovery:{kind:"user_action",action:"config",args:{option:"turbo.lean.integrated_diff_required",opt_out_value:!1,detail:`If the integrated-diff evidence is missing, re-run the phase (mid-phase) or provide ${dir}/.swarm/evidence/${phase}/lean-turbo/lean-turbo-phase.json with a non-empty integratedDiffSummary; to restore the pre-#2954 permissive behavior, set turbo.lean.integrated_diff_required: false in .opencode/opencode-swarm.json.`}}}}}),preflightChecks.push({id:"required_agents",responsibleActor:"architect",run:async()=>{let participationPlan=null,phaseRequiredAgents;try{participationPlan=await loadPlan(dir),phaseRequiredAgents=participationPlan?.phases.find((item)=>item.id===phase)?.required_agents}catch{participationPlan=null}let configured=[...phaseRequiredAgents??phaseCompleteConfig.required_agents],required3=[...configured];if(phaseCompleteConfig.require_docs&&!required3.includes("docs"))required3.push("docs");let docsStatus=null,durableDocsFound=!1;if(required3.includes("docs")){if(crossSessionResult.agents.delete("docs"),participationPlan){let receipt=await readPhaseParticipation(dir,participationPlan,phase,"docs");if(docsStatus=receipt.status,receipt.found)durableDocsFound=!0,crossSessionResult.agents.add("docs")}}let missing=required3.filter((role)=>!crossSessionResult.agents.has(role)),inferredFromTaskGates=[];if(missing.length>0)try{let target=participationPlan?.phases.find((item)=>item.id===phase);if(target&&target.tasks.length>0&&canInferMissingAgentsFromTaskGates(missing)&&await allCompletedTasksHavePassedGateEvidence(dir,target.tasks))inferredFromTaskGates=[...missing],missing=[]}catch{}let recoveryGuidance=buildMissingAgentRecoveryGuidance({missing,docsAddedByConfig:phaseCompleteConfig.require_docs&&!configured.includes("docs"),docsEvidenceStatus:docsStatus,docsPlanReadable:participationPlan!==null,policy:phaseCompleteConfig.policy}),authoritativeAgents=[...crossSessionResult.agents].sort();return missing.length>0&&phaseCompleteConfig.policy==="enforce"?{...passGate(),blocked:!0,reason:"REQUIRED_AGENTS_MISSING",message:`Phase ${phase} is missing required agents: ${missing.join(", ")}. ${recoveryGuidance}`,agentsMissing:missing,agentsDispatched:authoritativeAgents,recovery_guidance:recoveryGuidance,recovery:{kind:"user_action",action:"Task",args:{agents:missing}}}:passGate({agentsDispatched:durableDocsFound?[...new Set([...authoritativeAgents,"docs"])].sort():authoritativeAgents,recovery_guidance:recoveryGuidance,agentsMissing:missing,warnings:[...durableDocsFound?[`Recovered durable docs participation proof for phase ${phase}.`]:[],...inferredFromTaskGates.length>0?[`Agent dispatch fallback: all completed tasks in phase ${phase} have durable passing gate evidence. Clearing missing agents: ${inferredFromTaskGates.join(", ")}.`]:[],...missing.length>0?[`Warning: phase ${phase} missing required agents: ${missing.join(", ")} (advisory because phase_complete.policy=warn).`]:[]]})}}),preflightChecks.push({id:"snapshot_identity",responsibleActor:"architect",run:async()=>{let plan=await loadPlan(dir),structureHash=plan?computePlanStructureHash(plan):"plan:none",policyHash=createHash113("sha256").update(JSON.stringify(config3)).digest("hex"),evidenceHash=computePhaseEvidenceSnapshot(dir);return passGate({evidenceRefs:[`plan-structure:${structureHash}`,`policy:${policyHash}`,`phase-evidence:${evidenceHash}`]})}});let preflightReport=await collectPhaseGateReport({phase,checks:preflightChecks});if(preflightReport.outcome==="block")return JSON.stringify(formatPhaseGateCompatibility(preflightReport),null,2);for(let entry of preflightReport.entries)warnings.push(...entry.warnings);let acceptedRetro={found:retroFound,entry:retroEntry,taskId:loadedRetroTaskId,bundle:loadedRetroBundle},phaseRecoveryGuidance=preflightReport.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,phaseCommitAgent="phase-complete";for(let[,activeAgent]of swarmState.activeAgent){phaseCommitAgent=activeAgent;break}let planLockTaskId=`phase-complete-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,phasePlanLock;try{phasePlanLock=await tryAcquireLock(dir,"plan.json",phaseCommitAgent,planLockTaskId)}catch(error93){let detail=error93 instanceof Error?error93.message:String(error93);return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCK_ERROR",message:`Failed to acquire the guarded phase commit lock: ${detail}`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Phase commit lock acquisition failed: ${detail}`],recovery_guidance:"Resolve the filesystem or lock-directory error, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}if(!phasePlanLock.acquired){let lockOwner=phasePlanLock.existing?.agent??"another agent";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCKED",message:`Plan write is locked by ${lockOwner}.`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Concurrent plan write detected; lock is held by ${lockOwner}.`],recovery_guidance:"Wait for the current plan writer to finish, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}try{let lockedPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(lockedPreflight.outcome!=="pass"||lockedPreflight.reportHash!==preflightReport.reportHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence, plan identity, or policy changed after preflight. No phase transition or post-commit side effect was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,recovery:{kind:"retry",action:"phase_complete"}});let plan=await loadPlan(dir);if(plan?._ledgerReplayStale===!0){let staleReason=plan._ledgerReplayStaleReason??"unknown reason";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_STALE",message:`Plan write refused: plan.json is stale from a failed ledger replay (${staleReason}). Refusing to complete phase ${phase} against a known-stale plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[`Stale plan from failed ledger replay: ${staleReason}`],recovery_guidance:"The ledger replay failed and no critic-approved snapshot was available, so loadPlan fell back to a stale plan.json. Do NOT retry blindly. Recover first: re-verify the plan (re-run completion verification), reset the session, or restore from the latest checkpoint under .swarm/plan-export/, then retry phase_complete.",_ledgerReplayStaleReason:staleReason})}if(!plan&&await ledgerExists(dir))plan=await replayFromLedger(dir);let phaseObject=plan?plan.phases.find((candidate2)=>candidate2.id===phase):void 0;if(plan){if(!phaseObject)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_NOT_IN_PLAN",message:`Phase ${phase} is not present in the authoritative plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight})}else if(fs210.existsSync(validateSwarmPath(dir,"plan.json")))return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_UNREADABLE",message:"Plan exists but could not be read or rebuilt from the ledger; no phase transition was committed.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight});if(knowledgeEnabled){let closeIntent=await phaseCompleteReceiptInternals.recordPhaseCloseIntent(dir,receiptPhaseLabel,sessionID,void 0,phase);if(!closeIntent.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_CLOSE_INTENT_FAILED",message:"Phase completion blocked: could not persist receipt phase-close intent.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[closeIntent.detail],recovery:{kind:"retry",action:"phase_complete"}})}let commitPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(commitPreflight.outcome!=="pass")return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence or policy changed before the authoritative transition. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});let commitEvidenceRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("phase-evidence:")),commitPolicyRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("policy:")),expectedCommitEvidenceHash=commitEvidenceRef?.slice(15),expectedCommitPolicyHash=commitPolicyRef?.slice(7);if(!expectedCommitEvidenceHash||!expectedCommitPolicyHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"The commit-boundary evidence identity was unavailable. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});if(plan&&phaseObject&&!["complete","completed","closed"].includes(phaseObject.status)){phaseObject.status="complete";try{let saveDurability=await phaseCompleteCommitInternals.savePlan(dir,plan,{preserveCompletedStatuses:!0,planLockAlreadyHeld:!0,preCommitCheck:()=>{let currentPolicyHash=createHash113("sha256").update(JSON.stringify(loadPluginConfigWithMeta(dir).config)).digest("hex");if(computePhaseEvidenceSnapshot(dir)!==expectedCommitEvidenceHash||currentPolicyHash!==expectedCommitPolicyHash)throw Error("PHASE_PREFLIGHT_STALE: evidence changed at the authoritative transition boundary")}});if(saveDurability.durability==="incomplete")warnings.push(`Plan saved with incomplete durability; degraded surfaces: ${saveDurability.degraded_surfaces.join(", ")}`+(saveDurability.md_write_error?` (${saveDurability.md_write_error})`:""))}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("PHASE_PREFLIGHT_STALE:"))return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence changed at the authoritative transition boundary. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});throw error93}await takeSnapshotEvent(dir,plan).catch(()=>{return})}}finally{if(phasePlanLock.lock._release)await phasePlanLock.lock._release().catch((error93)=>{warn("[phase_complete] Plan lock release failed:",error93 instanceof Error?error93.message:String(error93))})}try{let normalizedPlan=await loadPlan(dir).catch(()=>null);if(normalizedPlan){let{rebound}=await phaseCompleteReceiptInternals.rebindCursorTaggedReceipts(dir,normalizedPlan,phase,"docs");if(rebound>0)warnings.push(`Re-stamped ${rebound} docs participation receipt(s) from the plan's stale current_phase cursor to phase ${phase}.`)}}catch(error93){warnings.push(`Docs participation receipt normalization failed: ${error93 instanceof Error?error93.message:String(error93)}.`)}if(knowledgeEnabled){let receiptClose=await phaseCompleteReceiptInternals.commitPhaseClosed(dir,receiptPhaseLabel,sessionID,void 0,phase);if(!receiptClose.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_RECEIPT_CLOSE_PENDING",message:"Plan phase closed, but receipt lifecycle closure is pending reconciliation; retry phase_complete.",agentsDispatched,agentsMissing:[],warnings:[...warnings,receiptClose.detail],gate_report:preflightReport,recovery:{kind:"retry",action:"phase_complete"}})}let requiredAgentsEntry=preflightReport.entries.find((entry)=>entry.id==="required_agents");if(requiredAgentsEntry)agentsDispatched.splice(0,agentsDispatched.length,...requiredAgentsEntry.agentsDispatched);let knowledgeConfig;try{knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch(parseErr){warnings.push(`Knowledge config validation failed: ${String(parseErr)}`),knowledgeConfig=KnowledgeConfigSchema.parse({})}if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)try{let projectName=path348.basename(dir),curationResult=await curateAndStoreSwarm(acceptedRetro.entry.lessons_learned,projectName,{phase_number:phase},dir,knowledgeConfig,{llmDelegate:createCuratorLLMDelegate(dir,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});if(curationResult&&curationResult.stored+curationResult.reinforced+curationResult.quarantined+curationResult.rejected>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[CURATOR] Knowledge curation: ${curationResult.stored} stored, ${curationResult.reinforced} reinforced, ${curationResult.skipped} skipped, ${curationResult.rejected} rejected, ${curationResult.quarantined} quarantined (unactionable).`)}}catch(error93){safeWarn("[phase_complete] Failed to curate lessons from retrospective:",error93)}let complianceWarnings=[];try{let curatorConfig=CuratorConfigSchema.parse(config3.curator??{});if(curatorConfig.enabled&&curatorConfig.phase_enabled){let llmDelegate=createCuratorLLMDelegate(dir,"phase",sessionID??void 0),curatorResult=await runCuratorPhase(dir,phase,agentsDispatched,curatorConfig,{},llmDelegate);{let scopeContent=curatorResult.digest?.summary??`Phase ${phase} curator analysis`,complianceWarnings2=curatorResult.compliance.filter((c)=>c.severity==="warning"),receipt=complianceWarnings2.length>0?buildRejectedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",blockingFindings:complianceWarnings2.map((c)=>({location:`phase-${c.phase}`,summary:c.description,severity:c.type==="missing_reviewer"?"high":"medium"})),evidenceReferences:[],passConditions:["resolve all compliance warnings before phase completion"]}):buildApprovedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",checkedAspects:["phase_compliance","knowledge_recommendations","phase_digest"],validatedClaims:[`phase: ${phase}`,`agents_dispatched: ${agentsDispatched.length}`,`knowledge_recommendations: ${curatorResult.knowledge_recommendations.length}`]});persistReviewReceipt(dir,receipt).catch(()=>{})}let knowledgeResult=await applyCuratorKnowledgeUpdates(dir,curatorResult.knowledge_recommendations,knowledgeConfig),driftAdvisoryPushedThisRun=!1;try{let{runDeterministicDriftCheck:runDeterministicDriftCheck2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift));await runDeterministicDriftCheck2(dir,phase,curatorResult,curatorConfig,(message2)=>{let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,message2),driftAdvisoryPushedThisRun=!0})}catch{}let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let digestSummary=curatorResult.digest?.summary?curatorResult.digest.summary.slice(0,200):"Phase analysis complete",complianceNote=curatorResult.compliance.length>0?` (${curatorResult.compliance.length} compliance observation(s))`:"",analyzeHint=curatorResult.knowledge_recommendations.length>0?" Call curator_analyze with recommendations to apply knowledge updates from this phase.":"";if(digestSummary!=="Phase analysis complete")pushAdvisory(callerSessionState,`[CURATOR] Phase ${phase} digest: ${digestSummary}${complianceNote}. Knowledge: ${knowledgeResult.applied} applied, ${knowledgeResult.skipped} skipped.${analyzeHint}`);try{let{readPriorDriftReports:readPriorDriftReports2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift)),phaseReport=(await readPriorDriftReports2(dir)).filter((r)=>r.phase===phase).pop();if(phaseReport&&phaseReport.drift_score>0&&!driftAdvisoryPushedThisRun)pushAdvisory(callerSessionState,`[CURATOR DRIFT DETECTED (phase ${phase}, score ${phaseReport.drift_score})]: Prior drift report found on disk. Consider running critic_drift_verifier before phase completion to get a proper drift review. Review drift report for phase ${phase} and address spec alignment if applicable.`)}catch{}}if(curatorResult.compliance.length>0&&!curatorConfig.suppress_warnings)complianceWarnings=curatorResult.compliance.map((obs)=>`[${obs.severity.toUpperCase()}] ${obs.description}`).slice(0,5)}}catch(curatorError){safeWarn("[phase_complete] Curator pipeline error (non-blocking):",curatorError)}try{if(config3.design_docs?.enabled===!0){let outDir=config3.design_docs.out_dir??"docs",{runDesignDocDriftCheck:runDesignDocDriftCheck2}=await Promise.resolve().then(() => (init_design_doc_drift(),exports_design_doc_drift)),docReport=await runDesignDocDriftCheck2(dir,phase,outDir);if(docReport?.verdict==="DOC_STALE"){let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let staleIds=docReport.stale_sections.map((s)=>s.section_id).slice(0,8).join(", ");pushAdvisory(callerSessionState,`[DESIGN-DOC DRIFT (phase ${phase})]: ${docReport.stale_sections.length} design-doc section(s) are stale (${staleIds}). Run /swarm design-docs --update to sync ${outDir}/ and append a design-changelog entry. Advisory only — does not block completion.`)}}}}catch(docDriftError){safeWarn("[phase_complete] Design-doc drift check error (non-blocking):",docDriftError)}let floorOptions={floorAction:knowledgeConfig.confidence_floor_action,floorMinOutcomes:knowledgeConfig.confidence_floor_min_outcomes,floorSignalThreshold:knowledgeConfig.confidence_floor_signal_threshold};try{let feedbackResult=await applySkillUsageFeedback(dir,{floorOptions});if(feedbackResult.processed>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Skill usage feedback: ${feedbackResult.processed} skills processed, ${feedbackResult.bumps} confidence updates applied.`)}}catch(skillUsageError){safeWarn("[phase_complete] Skill usage feedback error (non-blocking):",skillUsageError)}try{pruneSkillUsageLog(dir,500)}catch(skillPruneError){safeWarn("[phase_complete] Skill usage log pruning error (non-blocking):",skillPruneError)}try{let verdictMarkerPath=validateSwarmPath(dir,"verdict-feedback-last-processed.json"),verdictSinceTimestamp,verdictSinceEventId;try{let markerData=JSON.parse(fs210.readFileSync(verdictMarkerPath,"utf-8"));verdictSinceTimestamp=markerData.lastProcessedTimestamp,verdictSinceEventId=markerData.lastProcessedEventId}catch{}let{applyKnowledgeVerdictFeedback:applyKnowledgeVerdictFeedback2}=await Promise.resolve().then(() => (init_knowledge_events(),exports_knowledge_events)),verdictResult=await applyKnowledgeVerdictFeedback2(dir,{sinceTimestamp:verdictSinceTimestamp,sinceEventId:verdictSinceEventId,floorOptions});if(verdictResult.lastProcessedTimestamp)try{fs210.writeFileSync(verdictMarkerPath,JSON.stringify({lastProcessedTimestamp:verdictResult.lastProcessedTimestamp,lastProcessedEventId:verdictResult.lastProcessedEventId}),"utf-8")}catch{}if(verdictResult.bumps>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Knowledge verdict feedback: ${verdictResult.processed} entries processed, ${verdictResult.bumps} confidence updates applied.`)}}catch(verdictError){safeWarn("[phase_complete] Knowledge verdict feedback error (non-blocking):",verdictError)}let agentsMissing=[...requiredAgentsEntry?.agentsMissing??[]],VALID_TASK_COMPLEXITY=["trivial","simple","moderate","complex"],firstEntry=acceptedRetro.bundle?.entries?.[0];if(acceptedRetro.taskId!==primaryRetroTaskId&&acceptedRetro.taskId?.startsWith("retro-")&&acceptedRetro.bundle?.schema_version==="1.0.0"&&firstEntry?.task_complexity&&VALID_TASK_COMPLEXITY.includes(firstEntry.task_complexity))warnings.push(`Retrospective data for phase ${phase} may have been automatically migrated to current schema format.`);let success3=!0,status2=agentsMissing.length>0?"warned":"success",safeSummary=summary?.trim().slice(0,500),message=safeSummary?`Phase ${phase} completed: ${safeSummary}`:`Phase ${phase} completed`,result={success:success3,phase,status:status2,message,agentsDispatched,agentsMissing,warnings,gate_report:preflightReport,...phaseRecoveryGuidance?{recovery_guidance:phaseRecoveryGuidance}:{}},hasPlan=!1;try{hasPlan=fs210.existsSync(validateSwarmPath(dir,"plan.json"))}catch{}if(!hasPlan&&!crossSessionResult.agents.has("reviewer")&&!crossSessionResult.agents.has("test_engineer"))warnings.push(`⚠️ Plan-free phase ${phase}: no independent reviewer or test_engineer dispatch detected. Code changes in plan-free sessions should have independent review. Consider dispatching reviewer + test_engineer before completing future plan-free phases.`);if(!hasPlan)warnings.push(`Warning: failed to update plan.json phase status because no authoritative plan was found; phase ${phase} completed in plan-free mode.`);if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)await updateRetrievalOutcome(dir,`Phase ${phase}`,success3).catch(()=>{});if(phaseCompleteConfig.regression_sweep?.enforce)try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs210.readFileSync(planPath,"utf-8"),targetPhase=JSON.parse(planRaw).phases.find((p)=>p.id===phase);if(targetPhase){let sweepFound=!1;for(let task2 of targetPhase.tasks){let taskEvidenceResult=await loadEvidence(dir,task2.id);if(taskEvidenceResult.status==="found"){let entries2=taskEvidenceResult.bundle.entries??[];for(let entry of entries2)if(entry.regression_sweep!==void 0){sweepFound=!0;break}}if(sweepFound)break}if(!sweepFound)warnings.push(`Warning: regression_sweep.enforce=true but no regression-sweep result found for any task in phase ${phase}. Run tests to populate regression-sweep results.`)}}catch{}let now2=Date.now(),durationMs=now2-phaseReferenceTimestamp,event={event:"phase_complete",phase,timestamp:new Date(now2).toISOString(),agents_dispatched:agentsDispatched,agents_missing:agentsMissing,status:status2,summary:safeSummary??null};try{appendCoreEventSync(dir,{...event})}catch(writeError){warnings.push(`Warning: failed to write phase complete event: ${writeError instanceof Error?writeError.message:String(writeError)}`)}if(success3){try{let skillConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{});if(skillConfig.enabled&&skillConfig.trigger==="scheduled")runSkillConsolidationFireAndForget({directory:dir,config:skillConfig,source:"phase_complete",sessionId:sessionID,enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},(consolidationResult)=>{if(!consolidationResult.started)return;let sessionState=swarmState.agentSessions.get(sessionID);if(!sessionState)return;let activatedSlugs=consolidationResult.result?.autoApply?.approved??[],activationSuffix=activatedSlugs.length>0?` and auto-activated ${activatedSlugs.length} skill(s): ${activatedSlugs.join(", ")}.`:" and auto-activated no skills.";pushAdvisory(sessionState,`[SKILL CONSOLIDATION] Scheduled skill_improver consolidation wrote ${consolidationResult.result?.proposalPath??"a proposal"}${activationSuffix}`)},(err)=>{safeWarn("[phase_complete] Scheduled skill consolidation error (non-blocking):",err)})}catch(skillConsolidationError){safeWarn("[phase_complete] Scheduled skill consolidation setup error (non-blocking):",skillConsolidationError)}try{let memoryConfig=config3.memory;if(memoryConfig?.enabled&&memoryConfig.consolidation?.enabled)runMemoryConsolidationFireAndForget({directory:dir,config:memoryConfig,phase,sessionId:sessionID},void 0,(err)=>{safeWarn("[phase_complete] Memory consolidation error (non-blocking):",err)})}catch(memoryConsolidationError){safeWarn("[phase_complete] Memory consolidation setup error (non-blocking):",memoryConsolidationError)}for(let contributorSessionId of crossSessionResult.contributorSessionIds){let contributorSession=swarmState.agentSessions.get(contributorSessionId);if(contributorSession){if(contributorSession.phaseAgentsDispatched.size>0)contributorSession.lastCompletedPhaseAgentsDispatched=new Set(contributorSession.phaseAgentsDispatched);contributorSession.phaseAgentsDispatched=new Set,contributorSession.fullAutoInteractionCount=0,contributorSession.fullAutoDeadlockCount=0,contributorSession.fullAutoLastQuestionHash=null,contributorSession.lastPhaseCompleteTimestamp=now2;let oldPhase=contributorSession.lastPhaseCompletePhase;contributorSession.lastPhaseCompletePhase=phase,telemetry.phaseChanged(contributorSessionId,oldPhase??0,phase)}}try{if(knowledgeConfig.sweep_enabled){let swarmPath3=resolveSwarmKnowledgePath(dir);if(await sweepAgedEntries(swarmPath3,knowledgeConfig.default_max_phases),await sweepStaleTodos(swarmPath3,knowledgeConfig.todo_max_phases),knowledgeConfig.hive_enabled){let hivePath=resolveHiveKnowledgePath2();await sweepAgedEntries(hivePath,knowledgeConfig.default_max_phases),await sweepStaleTodos(hivePath,knowledgeConfig.todo_max_phases)}}}catch(err){let detail=String(err);if(detail.includes("ELOCKED"))detail="lock timeout (stale lock detected)";else if(detail.includes("ENOSPC"))detail="disk full";else if(detail.includes("EACCES"))detail="permission denied";warnings.push(`Knowledge sweep failed for phase ${phase}: ${detail}`)}}if(complianceWarnings.length>0)warnings.push(`Curator compliance: ${complianceWarnings.join("; ")}`);await flushPendingSnapshot(dir),await writeCheckpoint(dir).catch(()=>{});try{let curatorCfg=CuratorConfigSchema.parse(config3.curator??{});if(curatorCfg.enabled&&curatorCfg.postmortem_enabled){let finalPlan=await loadPlan(dir);if(finalPlan?.phases?.length){if(finalPlan.phases.every((p)=>p.status==="complete")){let{runCuratorPostMortem:runCuratorPostMortem2}=await Promise.resolve().then(() => (init_curator_postmortem(),exports_curator_postmortem)),pmResult=await runCuratorPostMortem2(dir,{llmDelegate:createCuratorLLMDelegate(dir,"postmortem",sessionID),scope:"project",sessionID});if(pmResult.success&&pmResult.summary)warnings.push(`[POST-MORTEM] ${pmResult.summary}`);if(pmResult.warnings.length>0)for(let w of pmResult.warnings)warnings.push(`[POST-MORTEM] ${w}`)}}}}catch{}let outputData={...result,timestamp:event.timestamp,duration_ms:durationMs};return _buildOutputJson(outputData)}function _buildOutputJson(outputData){let json3=JSON.stringify(outputData,null,2);if(json3.length>MAX_OUTPUT_BYTES7){let truncated={_truncated:!0,_truncation_reason:`Output exceeded MAX_OUTPUT_BYTES (${MAX_OUTPUT_BYTES7}) limit`,phase:outputData.phase,success:outputData.success,status:outputData.status,message:outputData.message,agentsDispatched:outputData.agentsDispatched?.slice(0,10),agentsMissing:outputData.agentsMissing?.slice(0,10),warnings:["(output truncated — full output exceeded size limit)"],timestamp:outputData.timestamp,duration_ms:outputData.duration_ms};json3=JSON.stringify(truncated,null,2)}return json3}function createPhaseCompleteTool(runtime={}){return createSwarmTool({description:"Mark a phase as complete and track which agents were dispatched. Used for phase completion gating and tracking. Accepts phase number and optional summary. Returns list of agents that were dispatched.",args:{phase:exports_external.number().int().min(1).describe("The phase number being completed — a positive integer (e.g., 1, 2, 3)"),summary:exports_external.string().optional().describe("Optional summary of what was accomplished in this phase"),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."),accept_violations:exports_external.array(exports_external.string()).optional().describe("DEPRECATED COMPATIBILITY INPUT. phase_complete never records directive overrides. When supplied, it fails closed with recovery instructions for the architect-only record_directive_override action."),accept_violations_justification:exports_external.string().optional().describe("Written justification retained only for deprecated compatibility input; use it with record_directive_override instead.")},execute:async(args2,directory,ctx)=>{let phaseCompleteArgs,workingDirInput;try{phaseCompleteArgs={phase:Number(args2.phase),summary:args2.summary!==void 0?String(args2.summary):void 0,sessionID:ctx?.sessionID??(args2.sessionID!==void 0?String(args2.sessionID):void 0),acceptViolations:Array.isArray(args2.accept_violations)?args2.accept_violations.map((s)=>String(s)):void 0,acceptViolationsJustification:args2.accept_violations_justification!==void 0?String(args2.accept_violations_justification):void 0,callerAgent:ctx?.agent!==void 0?String(ctx.agent):void 0},workingDirInput=args2.working_directory!==void 0?String(args2.working_directory):void 0}catch{return JSON.stringify({success:!1,phase:0,message:"Invalid arguments",agentsDispatched:[],warnings:["Failed to parse arguments"]},null,2)}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:phaseCompleteArgs.phase,message:dirResult.message,agentsDispatched:[],warnings:[dirResult.message]},null,2);return executePhaseComplete(phaseCompleteArgs,dirResult.directory,dirResult.directory,runtime)}})}var phase_complete=createPhaseCompleteTool();init_zod();init_discovery();init_utils();init_bun_compat();init_external_tool_runner();init_create_tool();import*as fs211 from"node:fs";import*as path349 from"node:path";var MAX_OUTPUT_BYTES8=52428800,AUDIT_TIMEOUT_MS=120000;function resolveAuditCommandDefault(name){if(process.platform!=="win32")return[name];let resolved=resolveExecutableFromPath([name]);if(!resolved)return[name];let lowered=resolved.toLowerCase();if(lowered.endsWith(".cmd")||lowered.endsWith(".bat")){if(/["&|<>^!%]/.test(resolved))return[name];return["cmd.exe","/d","/s","/c",`call "${resolved}"`]}return[resolved]}var _internals290={bunSpawn,resolveAuditCommand:resolveAuditCommandDefault};function isValidEcosystem(value){return typeof value==="string"&&["auto","npm","pip","cargo","go","dotnet","ruby","dart","composer"].includes(value)}function validateArgs3(args2){if(typeof args2!=="object"||args2===null)return!0;let obj=args2;if(obj.ecosystem!==void 0&&!isValidEcosystem(obj.ecosystem))return!1;return!0}function detectEcosystems(directory){let ecosystems=[],cwd=directory;if(fs211.existsSync(path349.join(cwd,"package.json")))ecosystems.push("npm");if(fs211.existsSync(path349.join(cwd,"pyproject.toml"))||fs211.existsSync(path349.join(cwd,"requirements.txt")))ecosystems.push("pip");if(fs211.existsSync(path349.join(cwd,"Cargo.toml")))ecosystems.push("cargo");if(fs211.existsSync(path349.join(cwd,"go.mod")))ecosystems.push("go");try{if(fs211.readdirSync(cwd).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))ecosystems.push("dotnet")}catch{}if(fs211.existsSync(path349.join(cwd,"Gemfile"))||fs211.existsSync(path349.join(cwd,"Gemfile.lock")))ecosystems.push("ruby");if(fs211.existsSync(path349.join(cwd,"pubspec.yaml")))ecosystems.push("dart");if(fs211.existsSync(path349.join(cwd,"composer.lock")))ecosystems.push("composer");return ecosystems}function auditFailureResult(ecosystem,command,error93,isToolMissing,toolMissingNote,genericNotePrefix){let message=error93 instanceof Error?error93.message:"Unknown error",base={ecosystem,command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0};if(classifySpawnFailure(error93)==="cwd-missing")return{...base,note:`${genericNotePrefix}: ${message}`};if(isToolMissing(message))return{...base,note:toolMissingNote};return{...base,note:`${genericNotePrefix}: ${message}`}}function npmAuditFailure(command,error93){return auditFailureResult("npm",command,error93,(m)=>m.includes("audit")||m.includes("command not found")||m.includes("'npm' is not recognized"),"npm audit not available - npm may not be installed","Error running npm audit")}function cargoAuditFailure(command,error93){return auditFailureResult("cargo",command,error93,(m)=>m.includes("not found")||m.includes("not recognized")||m.includes("cargo-audit"),"cargo-audit not installed. Install with: cargo install cargo-audit","Error running cargo audit")}async function runNpmAudit(directory){let command=[..._internals290.resolveAuditCommand("npm"),"audit","--json"];try{let proc=_internals290.bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`npm audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return npmAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let jsonOutput=stdout,jsonMatch=stdout.match(/\{[\s\S]*\}/)||stderr.match(/\{[\s\S]*\}/);if(jsonMatch)jsonOutput=jsonMatch[0];let response=JSON.parse(jsonOutput),findings=[];if(response.vulnerabilities)for(let[pkgName,vuln]of Object.entries(response.vulnerabilities)){let patchedVersion=null;if(vuln.fixAvailable&&typeof vuln.fixAvailable==="object")patchedVersion=vuln.fixAvailable.version;else if(vuln.fixAvailable===!0)patchedVersion="latest";let severity2=mapNpmSeverity(vuln.severity);findings.push({package:pkgName,installedVersion:vuln.range,patchedVersion,severity:severity2,title:vuln.title||`Vulnerability in ${pkgName}`,cve:vuln.cves&&vuln.cves.length>0?vuln.cves[0]:null,url:vuln.url||null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"npm",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){return npmAuditFailure(command,error93)}}function mapNpmSeverity(severity2){switch(severity2.toLowerCase()){case"critical":return"critical";case"high":return"high";case"moderate":return"moderate";case"low":return"low";default:return"info"}}async function runPipAudit(directory){let command=["pip-audit","--format=json"];try{let proc=bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);if(await proc.exited===0&&!stdout.trim())return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let packages=[];try{let parsed=JSON.parse(stdout);if(Array.isArray(parsed))packages=parsed;else if(parsed.dependencies)packages=parsed.dependencies}catch{if(stderr.includes("not installed")||stdout.includes("not installed")||stderr.includes("command not found"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit output could not be parsed: ${stdout.slice(0,200)}`}}let findings=[];for(let pkg of packages)if(pkg.vulns&&pkg.vulns.length>0)for(let vuln of pkg.vulns){let severity2=vuln.aliases&&vuln.aliases.length>0?"high":"moderate";findings.push({package:pkg.name,installedVersion:pkg.version,patchedVersion:vuln.fix_versions&&vuln.fix_versions.length>0?vuln.fix_versions[0]:null,severity:severity2,title:vuln.id,cve:vuln.aliases&&vuln.aliases.length>0?vuln.aliases[0]:null,url:vuln.id.startsWith("CVE-")?`https://nvd.nist.gov/vuln/detail/${vuln.id}`:null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"pip",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";if(errorMessage3.includes("not found")||errorMessage3.includes("not recognized")||errorMessage3.includes("pip-audit"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running pip-audit: ${errorMessage3}`}}}async function runCargoAudit(directory){let command=[..._internals290.resolveAuditCommand("cargo"),"audit","--json"];try{let proc=_internals290.bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`cargo audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr:_stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return cargoAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let findings=[],lines=stdout.split(`
7759
7759
  `).filter((line)=>line.trim());for(let line of lines)try{let obj=JSON.parse(line);if(obj.vulnerabilities?.list)for(let item of obj.vulnerabilities.list){let cvss=item.advisory.cvss||0,severity2=mapCargoSeverity(cvss);findings.push({package:item.advisory.package,installedVersion:item.package.version,patchedVersion:item.versions.patched&&item.versions.patched.length>0?item.versions.patched[0]:null,severity:severity2,title:item.advisory.title,cve:item.advisory.aliases&&item.advisory.aliases.length>0?item.advisory.aliases[0]:item.advisory.id?item.advisory.id:null,url:item.advisory.url||null})}}catch{}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"cargo",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){return cargoAuditFailure(command,error93)}}function mapCargoSeverity(cvss){if(cvss>=9)return"critical";if(cvss>=7)return"high";if(cvss>=4)return"moderate";return"low"}async function runGoAudit(directory){let command=["govulncheck","-json","./..."];if(!isCommandAvailable("govulncheck"))return warn("[pkg-audit] govulncheck not found, skipping Go audit"),{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"govulncheck not installed. Install with: go install golang.org/x/vuln/cmd/govulncheck@latest"};try{let proc=bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`govulncheck timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0&&exitCode!==3)return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`govulncheck exited with code ${exitCode}`};if(exitCode===0)return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let osvMap=new Map,goFindings=[],lines=stdout.split(`
7760
7760
  `).filter((line)=>line.trim());for(let line of lines)try{let obj=JSON.parse(line);if(obj.osv)osvMap.set(obj.osv.id,obj.osv);if(obj.finding)goFindings.push(obj.finding)}catch{}let findings=[];for(let finding of goFindings){let osv=osvMap.get(finding.osv),severity2=osv?.aliases?.some((a)=>a.startsWith("CVE-"))??!1?"high":"moderate",cve=osv?.aliases?.find((a)=>a.startsWith("CVE-"))??null,url3=osv?.references?.find((r)=>r.type==="WEB")?.url??`https://pkg.go.dev/vuln/${finding.osv}`,trace0=finding.trace[0],pkgName=trace0?.module??finding.osv,installedVersion=trace0?.version??"unknown";findings.push({package:pkgName,installedVersion,patchedVersion:finding.fixed_by??null,severity:severity2,title:osv?.summary??finding.osv,cve,url:url3})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"go",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running govulncheck: ${errorMessage3}`}}}async function runDotnetAudit(directory){let command=["dotnet","list","package","--vulnerable","--include-transitive"];if(!isCommandAvailable("dotnet"))return warn("[pkg-audit] dotnet not found, skipping .NET audit"),{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"dotnet CLI not installed. Install from: https://dotnet.microsoft.com/download"};try{let proc=bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`dotnet list package timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0&&!stdout.includes("has the following vulnerable packages"))return{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`dotnet list package exited with code ${exitCode}`};let vulnLinePattern=/^\s*>\s+(\S+)\s+\S+\s+(\S+)\s+(Critical|High|Moderate|Low)\s+(\S+)/i,findings=[],lines=stdout.split(`
7761
7761
  `);for(let line of lines){let match=line.match(vulnLinePattern);if(match){let[,pkgName,resolvedVersion,severityStr,url3]=match,severity2=mapDotnetSeverity(severityStr);findings.push({package:pkgName,installedVersion:resolvedVersion,patchedVersion:null,severity:severity2,title:`Vulnerable package: ${pkgName}`,cve:null,url:url3})}}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"dotnet",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running dotnet list package: ${errorMessage3}`}}}function mapDotnetSeverity(severity2){switch(severity2.toLowerCase()){case"critical":return"critical";case"high":return"high";case"moderate":return"moderate";case"low":return"low";default:return"info"}}async function runBundleAudit(directory){let useBundleExec=!isCommandAvailable("bundle-audit")&&isCommandAvailable("bundle");if(!isCommandAvailable("bundle-audit")&&!isCommandAvailable("bundle"))return warn("[pkg-audit] bundle-audit not found, skipping Ruby audit"),{ecosystem:"ruby",command:["bundle-audit","check","--format","json"],findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"bundle-audit not installed. Install with: gem install bundler-audit"};let command=useBundleExec?["bundle","exec","bundle-audit","check","--format","json"]:["bundle-audit","check","--format","json"];try{let proc=bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`bundle-audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0&&exitCode!==1)return{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`bundle-audit failed with exit code ${exitCode}`};if(exitCode===0)return{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let response;try{response=JSON.parse(stdout)}catch{return{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"bundle-audit JSON output could not be parsed"}}let findings=[];for(let item of response.results??[]){let adv=item.advisory,severity2=mapBundleSeverity(adv);findings.push({package:item.gem.name,installedVersion:item.gem.version,patchedVersion:adv.patched_versions?.[0]??null,severity:severity2,title:adv.title,cve:adv.cve??null,url:adv.url})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"ruby",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error",isNotInstalled=errorMessage3.includes("not recognized")||errorMessage3.includes("not found")||errorMessage3.includes("No such file")||errorMessage3.includes("ENOENT");return{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:isNotInstalled?"bundle-audit not installed. Install with: gem install bundler-audit":`Error running bundle-audit: ${errorMessage3}`}}}function mapBundleSeverity(adv){if(adv.criticality)switch(adv.criticality.toLowerCase()){case"critical":return"critical";case"high":return"high";case"medium":return"moderate";case"low":return"low"}let cvss=adv.cvss_v3??adv.cvss_v2??0;if(cvss>=9)return"critical";if(cvss>=7)return"high";if(cvss>=4)return"moderate";return"low"}async function runDartAudit(directory){let dartBin=isCommandAvailable("dart")?"dart":isCommandAvailable("flutter")?"flutter":null;if(!dartBin)return warn("[pkg-audit] dart/flutter not found, skipping Dart audit"),{ecosystem:"dart",command:["dart","pub","outdated","--json"],findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"dart or flutter not installed. Install from: https://dart.dev/get-dart"};let command=[dartBin,"pub","outdated","--json"];try{let proc=bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"dart",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`dart pub outdated timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0)return{ecosystem:"dart",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`dart pub outdated exited with code ${exitCode}`};let response;try{response=JSON.parse(stdout)}catch{return{ecosystem:"dart",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"dart pub outdated JSON output could not be parsed"}}let findings=[];for(let pkg of response.packages??[]){let current=pkg.current?.version,latest=pkg.latest?.version;if(!current||!latest||current===latest)continue;if(!pkg.upgradable)continue;findings.push({package:pkg.package,installedVersion:current,patchedVersion:pkg.upgradable.version,severity:"info",title:`Outdated package: ${pkg.package} (${current} → ${latest})`,cve:null,url:`https://pub.dev/packages/${pkg.package}`})}return{ecosystem:"dart",command,findings,criticalCount:0,highCount:0,totalCount:findings.length,clean:findings.length===0,note:"dart pub outdated reports outdated packages, not security vulnerabilities"}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return{ecosystem:"dart",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running dart pub outdated: ${errorMessage3}`}}}async function runComposerAudit(directory){let command=["composer","audit","--locked","--format=json"];if(!isCommandAvailable("composer"))return warn("[pkg-audit] composer not found, skipping Composer audit"),{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"composer not installed or not on PATH"};try{let proc=bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`composer audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited,hasVulnerabilities=(exitCode&1)!==0,hasAbandoned=(exitCode&2)!==0;if(exitCode===0)return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};if(hasVulnerabilities&&!stdout.trim())return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!1,incomplete:!0,note:`composer audit returned exit code ${exitCode} indicating vulnerabilities but produced no output`};let parsed;try{parsed=JSON.parse(stdout||"{}")}catch{return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!hasVulnerabilities,incomplete:!0,note:`composer audit returned exit code ${exitCode} but output was not valid JSON`}}if(!hasVulnerabilities&&hasAbandoned){let abandonedList=Object.keys(parsed.abandoned??{});return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:abandonedList.length>0?`Abandoned packages detected: ${abandonedList.join(", ")}`:"composer audit exit 2 (abandoned packages)"}}let findings=[];for(let advisories of Object.values(parsed.advisories??{}))for(let advisory of advisories){let hasCve=Boolean(advisory.cve?.trim());findings.push({package:advisory.packageName,installedVersion:"see composer.lock",patchedVersion:null,severity:hasCve?"high":"moderate",title:advisory.title,cve:advisory.cve||null,url:advisory.link||null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length,abandonedNote=hasAbandoned&&Object.keys(parsed.abandoned??{}).length>0?` Also abandoned: ${Object.keys(parsed.abandoned).join(", ")}`:"";return{ecosystem:"composer",command,findings,criticalCount,highCount,totalCount:findings.length,clean:!1,...abandonedNote?{note:abandonedNote.trim()}:{}}}catch(error93){return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`composer audit error: ${error93 instanceof Error?error93.message:String(error93)}`}}}async function runAutoAudit(directory){let ecosystems=detectEcosystems(directory);if(ecosystems.length===0)return{ecosystems:[],findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let results=[];for(let eco of ecosystems)switch(eco){case"npm":results.push(await runNpmAudit(directory));break;case"pip":results.push(await runPipAudit(directory));break;case"cargo":results.push(await runCargoAudit(directory));break;case"go":results.push(await runGoAudit(directory));break;case"dotnet":results.push(await runDotnetAudit(directory));break;case"ruby":results.push(await runBundleAudit(directory));break;case"dart":results.push(await runDartAudit(directory));break;case"composer":results.push(await runComposerAudit(directory));break}let allFindings=[],totalCritical=0,totalHigh=0,notes=[],ecosystemsIncomplete=[],anyIncomplete=!1;for(let result of results){if(allFindings.push(...result.findings),totalCritical+=result.criticalCount,totalHigh+=result.highCount,result.note)notes.push(result.note);if(result.incomplete)anyIncomplete=!0,ecosystemsIncomplete.push(result.ecosystem)}return{ecosystems,findings:allFindings,criticalCount:totalCritical,highCount:totalHigh,totalCount:allFindings.length,clean:allFindings.length===0&&!anyIncomplete,notes,ecosystemsIncomplete}}var pkg_audit=createSwarmTool({description:'Run package manager security audit (npm, pip, cargo, go, dotnet, ruby, dart) and return structured CVE data. Use ecosystem to specify which package manager, or "auto" to detect from project files.',args:{ecosystem:exports_external.enum(["auto","npm","pip","cargo","go","dotnet","ruby","dart","composer"]).default("auto").describe('Package ecosystem to audit: "auto" (detect from project files), "npm", "pip", "cargo", "go" (govulncheck), "dotnet" (dotnet list package), "ruby" (bundle-audit), "dart" (dart pub outdated), or "composer" (Composer/PHP)')},async execute(args2,directory){if(!validateArgs3(args2))return JSON.stringify({error:'Invalid arguments: ecosystem must be "auto", "npm", "pip", "cargo", "go", "dotnet", "ruby", "dart", or "composer"'},null,2);if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided"},null,2);let ecosystem=args2.ecosystem||"auto",result;switch(ecosystem){case"auto":result=await runAutoAudit(directory);break;case"npm":result=await runNpmAudit(directory);break;case"pip":result=await runPipAudit(directory);break;case"cargo":result=await runCargoAudit(directory);break;case"go":result=await runGoAudit(directory);break;case"dotnet":result=await runDotnetAudit(directory);break;case"ruby":result=await runBundleAudit(directory);break;case"dart":result=await runDartAudit(directory);break;case"composer":result=await runComposerAudit(directory);break}return JSON.stringify(result,null,2)}});init_zod();init_config();init_manager2();init_registry();init_utils();init_path_security();init_create_tool();import*as fs212 from"node:fs";import*as path350 from"node:path";var MAX_FILE_SIZE=1048576,DEFAULT_SENTINEL_ALLOWLIST=["SC-PLACEHOLDER"],DEFAULT_COMMENT_PATTERNS=[{pattern:/\bTODO\b/i,rule_id:"placeholder/comment-todo"},{pattern:/\bFIXME\b/i,rule_id:"placeholder/comment-fixme"},{pattern:/\bTBD\b/i,rule_id:"placeholder/comment-other"},{pattern:/\bXXX\b/,rule_id:"placeholder/comment-other"},{pattern:/\bHACK\b/i,rule_id:"placeholder/comment-other"}],DEFAULT_STRING_PATTERNS=[{pattern:/"[^"]*\bplaceholder\b[^"]*"/i,rule_id:"placeholder/text-placeholder"},{pattern:/"[^"]*\bstub\b[^"]*"/i,rule_id:"placeholder/text-placeholder"},{pattern:/"[^"]*\bwip\b[^"]*"/i,rule_id:"placeholder/text-placeholder"},{pattern:/"[^"]*\bnot implemented\b[^"]*"/i,rule_id:"placeholder/text-placeholder"},{pattern:/'[^']*\bplaceholder\b[^']*'/i,rule_id:"placeholder/text-placeholder"},{pattern:/'[^']*\bstub\b[^']*'/i,rule_id:"placeholder/text-placeholder"},{pattern:/'[^']*\bwip\b[^']*'/i,rule_id:"placeholder/text-placeholder"},{pattern:/`[^`]*\bplaceholder\b[^`]*`/i,rule_id:"placeholder/text-placeholder"},{pattern:/`[^`]*\bstub\b[^`]*`/i,rule_id:"placeholder/text-placeholder"}],FILE_ALLOWLIST=["src/tools/declare-scope.ts","src/tools/placeholder-scan.ts"],DEFAULT_CODE_PATTERNS=[{pattern:/throw\s+new\s+Error\s*\(\s*["'][^"']*\bTODO\b[^"']*["']\s*\)/i,rule_id:"placeholder/code-throw-todo"},{pattern:/throw\s+new\s+Error\s*\(\s*["'][^"']*\bFIXME\b[^"']*["']\s*\)/i,rule_id:"placeholder/code-throw-todo"},{pattern:/return\s+null\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+undefined\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+None\s*$/m,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+0\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+false\s*;/i,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+true\s*;/i,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+""\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+\[\]\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+\{\}\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+nil\s*;/,rule_id:"placeholder/code-stub-return"}],PLAN_PLACEHOLDER_PATTERNS=[{pattern:/\[task\]/gi,rule_id:"placeholder/plan-bracket-task"},{pattern:/\[Project\]/g,rule_id:"placeholder/plan-bracket-project"},{pattern:/\[date\]/g,rule_id:"placeholder/plan-bracket-date"},{pattern:/\[reason\]/g,rule_id:"placeholder/plan-bracket-reason"},{pattern:/\[description\]/gi,rule_id:"placeholder/plan-bracket-description"}],TEST_PATH_PATTERNS=[/\.test\./,/\.spec\./,/\btests?\//,/\b__tests?__\//,/\bmocks?\//,/\b__mocks?__\//,/\bspecs?\//,/\b__specs?__\//],SCAFFOLD_PATH_PATTERNS=[/\bgenerated\//,/\bscaffold\//,/\btemplates?\//,/\b__generated__\//,/\b__scaffold__\//],SCAFFOLD_FILENAME_PATTERNS=[/^gen-/,/^scaffold-/,/^template-/,/\.gen\./,/\.scaffold\./,/\.template\./],SUPPORTED_PARSER_EXTENSIONS=new Set([".js",".jsx",".ts",".tsx",".py",".go",".rs",".java",".c",".cpp",".h",".hpp",".cs",".php",".blade.php",".rb"]);function isTestFile2(filePath){let normalizedPath=filePath.toLowerCase().replace(/\\/g,"/");return TEST_PATH_PATTERNS.some((pattern)=>pattern.test(normalizedPath))}function isScaffoldFile(filePath){let normalizedPath=filePath.toLowerCase().replace(/\\/g,"/");if(SCAFFOLD_PATH_PATTERNS.some((pattern)=>pattern.test(normalizedPath)))return!0;let filename=path350.basename(filePath);if(SCAFFOLD_FILENAME_PATTERNS.some((pattern)=>pattern.test(filename)))return!0;return!1}function isAllowedByGlobs(filePath,allowGlobs){if(!allowGlobs||allowGlobs.length===0)return!1;let normalizedPath=filePath.toLowerCase().replace(/\\/g,"/");for(let glob of allowGlobs)try{let regexPattern=glob.replace(/\*\*/g,"<<<DBL>>>").replace(/\*/g,"([^/]+)").replace(/<<<DBL>>>/g,"(.*)");if(new RegExp(`^${regexPattern}`,"i").test(normalizedPath))return!0;let filename=path350.basename(filePath);if(new RegExp(`^${regexPattern}$`,"i").test(filename))return!0}catch{}return!1}function isParserSupported(filePath){let ext=path350.extname(filePath).toLowerCase();return SUPPORTED_PARSER_EXTENSIONS.has(ext)}var BODY_SHAPE_SUPPORTED_EXTENSIONS=new Set([".js",".jsx",".ts",".tsx",".py"]);function isBodyShapeSupported(filePath){return BODY_SHAPE_SUPPORTED_EXTENSIONS.has(path350.extname(filePath).toLowerCase())}function isPlanFile(filePath){let normalizedPath=filePath.toLowerCase().replace(/\\/g,"/");return normalizedPath.endsWith(".swarm/plan.md")||normalizedPath.includes("/.swarm/plan.md")}function scanPlanFileForPlaceholders(content,filePath,addedLines){let findings=[],lines=content.split(`