opencode-swarm 7.191.2 → 7.191.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/cli/{auto-checkpoint-fdwx53m3.js → auto-checkpoint-mfevgppc.js} +5 -5
- package/dist/cli/{checkpoint-53c1zafe.js → checkpoint-ft7x9hh4.js} +9 -9
- package/dist/cli/{coder-settlement-fyh6tt0j.js → coder-settlement-a8v2w1gw.js} +3 -3
- package/dist/cli/{config-doctor-fgb4e34g.js → config-doctor-5jpt3aj0.js} +7 -7
- package/dist/cli/{core-apkb4h4r.js → core-9sekbwxm.js} +1 -1
- package/dist/cli/{curator-drift-fz1s4mja.js → curator-drift-mqcfwm24.js} +5 -5
- package/dist/cli/{curator-llm-factory-mfnac4ay.js → curator-llm-factory-nm91t6p1.js} +26 -26
- package/dist/cli/{curator-frc99gz3.js → curator-venskykb.js} +26 -26
- package/dist/cli/{doctor-knowledge-receipt-phase-id-jwvzyje6.js → doctor-knowledge-receipt-phase-id-0ewtqwxk.js} +5 -5
- package/dist/cli/{evidence-summary-service-w18gkp8p.js → evidence-summary-service-rr3rb5n2.js} +10 -10
- package/dist/cli/{gate-evidence-36w61c05.js → gate-evidence-sjp73rfv.js} +2 -2
- package/dist/cli/{guardrail-explain-vqgjc2ed.js → guardrail-explain-r5x9khp3.js} +27 -27
- package/dist/cli/{guardrail-log-935f17ge.js → guardrail-log-87qgtbxw.js} +3 -3
- package/dist/cli/{guardrail-reset-xjnvgqah.js → guardrail-reset-z1rhagdh.js} +26 -26
- package/dist/cli/{hive-promoter-xsns8ajv.js → hive-promoter-hy0gm4z7.js} +26 -26
- package/dist/cli/{index-kme2f9w9.js → index-02gmv98q.js} +4 -4
- package/dist/cli/{index-n95ea1jf.js → index-1gv6ja3m.js} +2 -2
- package/dist/cli/{index-aqjn8pax.js → index-1y1fgtd0.js} +91 -66
- package/dist/cli/{index-h2y7bwje.js → index-2afvf0hr.js} +2 -2
- package/dist/cli/{index-tx5vtg1t.js → index-633j6d5z.js} +1 -1
- package/dist/cli/{index-tdwm85ng.js → index-7tkkhbcw.js} +1 -1
- package/dist/cli/{index-xbnb7anq.js → index-8nac5633.js} +2 -2
- package/dist/cli/{index-8mr9p76r.js → index-9nh7fhh9.js} +3 -3
- package/dist/cli/{index-gfterbs7.js → index-9ved57n0.js} +3 -3
- package/dist/cli/{index-jxhf5r26.js → index-bs8yvx1k.js} +1 -1
- package/dist/cli/{index-np6phn34.js → index-ce4skcpr.js} +2 -2
- package/dist/cli/{index-g5acbfgk.js → index-chdc1wv3.js} +1 -1
- package/dist/cli/{index-bd6zxkwg.js → index-d4rm6r3c.js} +1 -1
- package/dist/cli/{index-2rtms4nt.js → index-ez6sczc7.js} +1 -1
- package/dist/cli/{index-j5nhx6e8.js → index-g22dps7x.js} +3 -0
- package/dist/cli/{index-r6xewjr5.js → index-jfk0yzr6.js} +1 -1
- package/dist/cli/{index-xpwcg1rd.js → index-kcx2f95c.js} +6 -6
- package/dist/cli/{index-76086gkg.js → index-knqvkxc4.js} +26 -26
- package/dist/cli/{index-n23cya25.js → index-p4f47xhj.js} +3 -3
- package/dist/cli/{index-m0j9e1gt.js → index-p4vdas8e.js} +1 -1
- package/dist/cli/{index-b36p4kn3.js → index-q0y8e1db.js} +2 -2
- package/dist/cli/{index-hbnrvd8w.js → index-qgzyj2vt.js} +5 -5
- package/dist/cli/{index-nfnrxyvb.js → index-t775as8a.js} +1 -1
- package/dist/cli/{index-qwrbyb3c.js → index-v7bjb1ta.js} +1 -1
- package/dist/cli/{index-55xfbnvy.js → index-w8fbnqhe.js} +1 -1
- package/dist/cli/{index-vwvtmqvw.js → index-xbhs0kp0.js} +1 -1
- package/dist/cli/{index-vn3emgm3.js → index-xgfmzmey.js} +4 -4
- package/dist/cli/{index-6y359eht.js → index-xgy7wakm.js} +28 -28
- package/dist/cli/{index-1xt5gth0.js → index-xrhhjeas.js} +2 -2
- package/dist/cli/{index-99v2k5sy.js → index-y7668dn6.js} +3 -3
- package/dist/cli/{index-tzq81dcp.js → index-ydnfnzdq.js} +1 -1
- package/dist/cli/index.js +27 -27
- package/dist/cli/{knowledge-escalator-p05gp6vc.js → knowledge-escalator-901znnke.js} +8 -8
- package/dist/cli/{knowledge-events-m875rjq2.js → knowledge-events-y2x5c5xe.js} +6 -6
- package/dist/cli/{knowledge-store-4h6pebmp.js → knowledge-store-jkzkgsnw.js} +1 -1
- package/dist/cli/{knowledge-validator-5vyfp4q6.js → knowledge-validator-dar3799k.js} +2 -2
- package/dist/cli/{mcp-xwpwyzx7.js → mcp-7baqvsr2.js} +1 -1
- package/dist/cli/{model-preflight-jgehvs3v.js → model-preflight-gk2dtfw4.js} +26 -26
- package/dist/cli/{pending-delegations-d55bv8sb.js → pending-delegations-aean4z99.js} +2 -2
- package/dist/cli/{pr-subscriptions-f0p41qek.js → pr-subscriptions-zmv0gtv7.js} +1 -1
- package/dist/cli/{pr-workflow-gate-50kkf6y3.js → pr-workflow-gate-50avx71j.js} +26 -26
- package/dist/cli/{scan-cursor-hhsd1pk3.js → scan-cursor-7vnj82v4.js} +2 -2
- package/dist/cli/{schema-8ymp10e6.js → schema-4v7pnknw.js} +1 -1
- package/dist/cli/{scope-persistence-gsn67p3k.js → scope-persistence-xd30y1ym.js} +5 -5
- package/dist/cli/{server-2p7pqctr.js → server-mkvhdc5k.js} +26 -26
- package/dist/cli/{skill-generator-vhdxbs1t.js → skill-generator-mt61qg5f.js} +9 -9
- package/dist/cli/{snapshot-coordination-init-yzqj7px3.js → snapshot-coordination-init-c7r5443q.js} +26 -26
- package/dist/cli/{speckit-checkoff-73nmf206.js → speckit-checkoff-t17g4ej6.js} +3 -3
- package/dist/cli/{worktree-collision-ownership-1ranptpe.js → worktree-collision-ownership-negbpp72.js} +2 -2
- package/dist/cli/{worktree-isolation-heftcwdv.js → worktree-isolation-hhftse76.js} +26 -26
- package/dist/config/evidence-schema.d.ts +9 -0
- package/dist/index.js +8 -8
- package/dist/tools/pre-check-batch.d.ts +64 -1
- package/dist/tools/secretscan.d.ts +15 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.191.2",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"]},pr_review_submission:{description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",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_next_wave:{description:"Epic Mode: the single, idempotent way forward while an epic is open. Closes the active wave once every task is resolved (recording per-task outcomes and declared-vs-actual divergence, which Epic learning uses to plan later waves), keeps phases in order, and issues the next wave of disjoint tasks with dispatch instructions. Returns a status: dispatch | declare-scopes | in-progress | blocked | phase-ready-for-review | epic-complete | refused. Requires `epic.mode.enabled: true` and an epic opened by `/swarm epic start`.",agents:[]},epic_phase_review:{description:"Epic Mode phase readiness: dispatch a read-only phase reviewer, then (only if it APPROVES) a read-only phase critic over the completed phase; parse both verdicts from the agents and record them to .swarm/evidence/{phase}/epic-phase-review.json. Required by phase_complete while an epic is open for the current plan; re-run after any fix (evidence is bound to the plan and phase task evidence).",agents:[]}},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,EPIC_TOOL_NAMES,EPIC_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.191.4",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, 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"]},pr_review_submission:{description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",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_next_wave:{description:"Epic Mode: the single, idempotent way forward while an epic is open. Closes the active wave once every task is resolved (recording per-task outcomes and declared-vs-actual divergence, which Epic learning uses to plan later waves), keeps phases in order, and issues the next wave of disjoint tasks with dispatch instructions. Returns a status: dispatch | declare-scopes | in-progress | blocked | phase-ready-for-review | epic-complete | refused. Requires `epic.mode.enabled: true` and an epic opened by `/swarm epic start`.",agents:[]},epic_phase_review:{description:"Epic Mode phase readiness: dispatch a read-only phase reviewer, then (only if it APPROVES) a read-only phase critic over the completed phase; parse both verdicts from the agents and record them to .swarm/evidence/{phase}/epic-phase-review.json. Required by phase_complete while an epic is open for the current plan; re-run after any fix (evidence is bound to the plan and phase task evidence).",agents:[]}},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,EPIC_TOOL_NAMES,EPIC_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
|
|
|
@@ -109,7 +109,7 @@ Per-task QA (Stage A + Stage B) is NEVER waived in Epic. Audit (no architect nee
|
|
|
109
109
|
|
|
110
110
|
`)}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>
|
|
111
111
|
|
|
112
|
-
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(),ignored_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 resolveEpicConfig(config2){return config2?.epic??config2?.turbo?.epic??void 0}function isEpicModeConfigEnabled(config2){return resolveEpicConfig(config2)?.mode?.enabled===!0}function isEpicCochangeConfigEnabled(config2){return resolveEpicConfig(config2)?.cochange?.enabled===!0}function isPlainRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function mergeWinnerFirst(loser,winner){let out={...loser};for(let[key,value]of Object.entries(winner)){let prior=Object.hasOwn(out,key)?out[key]:void 0;Object.defineProperty(out,key,{value:isPlainRecord(prior)&&isPlainRecord(value)?mergeWinnerFirst(prior,value):value,enumerable:!0,writable:!0,configurable:!0})}return out}function hasLegacyEpicConfig(raw){return isPlainRecord(raw)&&isPlainRecord(raw.turbo)&&Object.hasOwn(raw.turbo,"epic")}function migrateLegacyEpicConfig(raw){if(!hasLegacyEpicConfig(raw))return raw;let{epic:legacy,...turboRest}=raw.turbo,top=raw.epic,epic;if(top===void 0)epic=legacy;else if(isPlainRecord(top)&&isPlainRecord(legacy))epic=mergeWinnerFirst(legacy,top);else epic=top;let{turbo:_turbo,...rest}=raw;return{...rest,...Object.keys(turboRest).length>0?{turbo:turboRest}:{},epic}}function ownPathExists(node,path){let current=node;for(let key of path){if(!isPlainRecord(current)||!Object.hasOwn(current,key))return!1;current=current[key]}return!0}function legacyEpicIssuePath(raw,path){if(path[0]!=="epic"||!hasLegacyEpicConfig(raw)||Object.hasOwn(raw,"epic"))return[...path];return["turbo",...path]}function annotateLegacyEpicKeys(keys,rawFiles){let legacy=rawFiles.filter(hasLegacyEpicConfig);if(legacy.length===0)return keys;let tops=rawFiles.filter((raw)=>isPlainRecord(raw)&&Object.hasOwn(raw,"epic"));return keys.map((key)=>{if(key!=="epic"&&!key.startsWith("epic."))return key;let rel=key==="epic"?[]:key.slice(5).split("."),inLegacy=legacy.some((raw)=>ownPathExists(raw.turbo.epic,rel)),inTop=tops.some((raw)=>ownPathExists(raw.epic,rel));return inLegacy&&!inTop?`${key} (from turbo.epic)`:key})}var LEGACY_EPIC_CONFIG_WARNING;var init_config=__esm(()=>{LEGACY_EPIC_CONFIG_WARNING="[opencode-swarm] turbo.epic is deprecated — move it to top-level epic "+'(`{ "epic": { "mode": { "enabled": true } } }`; no `turbo` block or `turbo.strategy` is needed). The legacy path keeps working: its keys are used where top-level `epic` does not set them. See docs/configuration.md (Epic Mode).'});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,retiredEpicKeyReplacement:()=>retiredEpicKeyReplacement,resolveGuardrailsConfig:()=>resolveGuardrailsConfig,resolveGeneratedAgentRole:()=>resolveGeneratedAgentRole,resolveExternalSkillsConfig:()=>resolveExternalSkillsConfig,resolveAutoReviewConfig:()=>resolveAutoReviewConfig,isKnownCanonicalRole:()=>isKnownCanonicalRole,getCanonicalAgentRole:()=>getCanonicalAgentRole,findRetiredEpicConfigKeys:()=>findRetiredEpicConfigKeys,_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,RETIRED_EPIC_MODE_KEYS:()=>RETIRED_EPIC_MODE_KEYS,RETIRED_EPIC_KEY_REPLACEMENTS:()=>RETIRED_EPIC_KEY_REPLACEMENTS,RETIRED_EPIC_KEYS:()=>RETIRED_EPIC_KEYS,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,LegacyTurboEpicConfigSchema:()=>LegacyTurboEpicConfigSchema,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 isPlainRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function normalizeAutoReviewInput(value,context={}){if(!isPlainRecord2(value))return value;let normalized={...value};if(!Object.hasOwn(value,"enabled"))normalized.enabled=autoReviewEnabledByRelease(context);if(Object.hasOwn(value,"final_review")&&!isPlainRecord2(value.final_review))return normalized;let nested=isPlainRecord2(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 retiredEpicKeyReplacement(dotted2){let relative=dotted2.replace(/^(?:turbo\.)?epic\./,"");return Object.hasOwn(RETIRED_EPIC_KEY_REPLACEMENTS,relative)?RETIRED_EPIC_KEY_REPLACEMENTS[relative]:void 0}function stripKeys(keys){return(value)=>{if(value===null||typeof value!=="object"||Array.isArray(value))return value;let record2=value;if(!keys.some((key)=>Object.hasOwn(record2,key)))return value;let stripped={...record2};for(let key of keys)delete stripped[key];return stripped}}function findRetiredEpicConfigKeys(raw){let at=(node,key)=>node!==null&&typeof node==="object"&&!Array.isArray(node)&&Object.hasOwn(node,key)?node[key]:void 0,found=[];for(let[prefix,epic]of[["epic",at(raw,"epic")],["turbo.epic",at(at(raw,"turbo"),"epic")]]){let mode=at(epic,"mode");found.push(...RETIRED_EPIC_MODE_KEYS.filter((key)=>at(mode,key)!==void 0).map((key)=>`${prefix}.mode.${key}`),...RETIRED_EPIC_KEYS.filter((key)=>at(epic,key)!==void 0).map((key)=>`${prefix}.${key}`))}return found}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,RETIRED_EPIC_MODE_KEYS,RETIRED_EPIC_KEYS,RETIRED_EPIC_KEY_REPLACEMENTS,stripRetiredEpicModeKeys,stripRetiredEpicKeys,EpicConfigSchema,LegacyTurboEpicConfigSchema,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()}),RETIRED_EPIC_MODE_KEYS=["min_commits_for_signal"],RETIRED_EPIC_KEYS=["calibration"],RETIRED_EPIC_KEY_REPLACEMENTS={calibration:"Epic learning replaced it — see epic.learning.* (enabled, decay_per_epic, half_life_days, hot_excess)."};stripRetiredEpicModeKeys=stripKeys(RETIRED_EPIC_MODE_KEYS),stripRetiredEpicKeys=stripKeys(RETIRED_EPIC_KEYS);EpicConfigSchema=exports_external.preprocess(stripRetiredEpicKeys,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.preprocess(stripRetiredEpicModeKeys,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().optional().meta({deprecated:!0,description:"Retired (Epic v2): accepted and ignored with a warning. Remove it."})}).strict()).optional(),calibration:exports_external.record(exports_external.string(),exports_external.unknown()).optional().meta({deprecated:!0,description:"Retired (Epic v2): accepted and ignored with a warning — Epic learning replaced it (epic.learning). Remove it."}),learning:exports_external.object({enabled:exports_external.boolean().default(!0),decay_per_epic:exports_external.number().min(0).max(1).default(0.7),half_life_days:exports_external.number().positive().default(60),hot_excess:exports_external.number().min(0).max(1).default(0.25)}).strict().optional(),sizing:exports_external.object({min_tasks:exports_external.number().int().min(1).default(6),min_scope_coverage:exports_external.number().min(0).max(1).default(0.8),min_effective_speedup:exports_external.number().min(1).default(1.25),coder_fraction:exports_external.number().min(0).max(1).default(0.6)}).strict().optional(),commit_policy:exports_external.enum(["epic-branch","current-branch"]).optional(),retain_refs:exports_external.boolean().optional(),phase_review:exports_external.object({timeout_ms:exports_external.number().int().min(1e4).max(1800000).default(300000)}).strict().optional()}).strict()),LegacyTurboEpicConfigSchema=EpicConfigSchema.optional().meta({deprecated:!0,description:"Deprecated (still accepted): move this block to top-level `epic` — Epic Mode no longer needs a `turbo` block. Within a file, top-level `epic` wins per key when both are set."}),StandardTurboConfigSchema=exports_external.object({strategy:exports_external.literal("standard"),lean:LeanTurboConfigSchema.optional(),epic:LegacyTurboEpicConfigSchema}),LeanTurboStrategyConfigSchema=exports_external.object({strategy:exports_external.literal("lean"),lean:LeanTurboConfigSchema,epic:LegacyTurboEpicConfigSchema}),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."),epic:EpicConfigSchema.optional().describe("Epic Mode block: one plan = one epic delivered in conflict-free parallel waves. Opt in with `mode.enabled: true`, then `/swarm epic start`. Needs no `turbo` block (legacy `turbo.epic` is still accepted and migrated here)."),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 rawEpicFiles=[rawUserConfig,rawProjectConfig],retiredEpicKeys=[...new Set(rawEpicFiles.flatMap((raw)=>findRetiredEpicConfigKeys(raw)))],annotateEpicKeys=(keys)=>annotateLegacyEpicKeys(keys,rawEpicFiles);if(rawEpicFiles.some(hasLegacyEpicConfig)){if(rawUserConfig)rawUserConfig=migrateLegacyEpicConfig(rawUserConfig);if(rawProjectConfig)rawProjectConfig=migrateLegacyEpicConfig(rawProjectConfig);if(!legacyEpicConfigWarned)legacyEpicConfigWarned=!0,advisoryWarn(LEGACY_EPIC_CONFIG_WARNING)}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.`)}if(retiredEpicKeys.length>0){let signature=retiredEpicKeys.join("\x00");if(signature!==lastRetiredEpicKeysSig)lastRetiredEpicKeysSig=signature,advisoryWarn(`[opencode-swarm] Ignored ${retiredEpicKeys.length} retired Epic config key(s): ${retiredEpicKeys.join(", ")}. They have no effect (the rest of the Epic block is kept) — remove them; see docs/configuration.md (Epic Mode).${retiredEpicKeys.map((key)=>retiredEpicKeyReplacement(key)).filter((hint)=>hint!==void 0).map((hint)=>` ${hint}`).join("")}`)}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:strictRemoved}=stripUnrecognizedKeys(mergedRaw,firstResult.error),removed=annotateEpicKeys(strictRemoved);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){let userRemoved=annotateEpicKeys(userStripped.removed);return advisoryWarn(`[opencode-swarm] Project config ignored; also ignored ${userRemoved.length} unrecognized user-config key(s): ${userRemoved.join(", ")}.`),{config:secure(userRecovered.data),recovery:"user_only",removedKeys:[...gatesStripped,...userGatesStripped,...userRemoved],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,...annotateEpicKeys(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=annotateEpicKeys(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,lastRetiredEpicKeysSig=null,legacyEpicConfigWarned=!1}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,lastRetiredEpicKeysSig=null,legacyEpicConfigWarned=!1,gatesAdvisorySignatures,MAX_GATES_ADVISORY_SIGNATURES=64,_internals4;var init_loader=__esm(()=>{init_config();init_warning_buffer();init_git_executable();init_schema();init_merge();init_merge();gatesAdvisorySignatures=new Set;_internals4={resetUnknownTopLevelKeyWarning(){lastUnknownTopLevelSig=null},resetRetiredEpicKeyWarning(){lastRetiredEpicKeysSig=null},resetLegacyEpicConfigWarning(){legacyEpicConfigWarned=!1},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_config2=__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"?`
|
|
112
|
+
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(),ignored_files:exports_external.number().int().min(0).optional(),new_findings_count:exports_external.number().int().min(0).optional(),preexisting_findings_count:exports_external.number().int().min(0).optional(),diff_scoped:exports_external.boolean().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 resolveEpicConfig(config2){return config2?.epic??config2?.turbo?.epic??void 0}function isEpicModeConfigEnabled(config2){return resolveEpicConfig(config2)?.mode?.enabled===!0}function isEpicCochangeConfigEnabled(config2){return resolveEpicConfig(config2)?.cochange?.enabled===!0}function isPlainRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function mergeWinnerFirst(loser,winner){let out={...loser};for(let[key,value]of Object.entries(winner)){let prior=Object.hasOwn(out,key)?out[key]:void 0;Object.defineProperty(out,key,{value:isPlainRecord(prior)&&isPlainRecord(value)?mergeWinnerFirst(prior,value):value,enumerable:!0,writable:!0,configurable:!0})}return out}function hasLegacyEpicConfig(raw){return isPlainRecord(raw)&&isPlainRecord(raw.turbo)&&Object.hasOwn(raw.turbo,"epic")}function migrateLegacyEpicConfig(raw){if(!hasLegacyEpicConfig(raw))return raw;let{epic:legacy,...turboRest}=raw.turbo,top=raw.epic,epic;if(top===void 0)epic=legacy;else if(isPlainRecord(top)&&isPlainRecord(legacy))epic=mergeWinnerFirst(legacy,top);else epic=top;let{turbo:_turbo,...rest}=raw;return{...rest,...Object.keys(turboRest).length>0?{turbo:turboRest}:{},epic}}function ownPathExists(node,path){let current=node;for(let key of path){if(!isPlainRecord(current)||!Object.hasOwn(current,key))return!1;current=current[key]}return!0}function legacyEpicIssuePath(raw,path){if(path[0]!=="epic"||!hasLegacyEpicConfig(raw)||Object.hasOwn(raw,"epic"))return[...path];return["turbo",...path]}function annotateLegacyEpicKeys(keys,rawFiles){let legacy=rawFiles.filter(hasLegacyEpicConfig);if(legacy.length===0)return keys;let tops=rawFiles.filter((raw)=>isPlainRecord(raw)&&Object.hasOwn(raw,"epic"));return keys.map((key)=>{if(key!=="epic"&&!key.startsWith("epic."))return key;let rel=key==="epic"?[]:key.slice(5).split("."),inLegacy=legacy.some((raw)=>ownPathExists(raw.turbo.epic,rel)),inTop=tops.some((raw)=>ownPathExists(raw.epic,rel));return inLegacy&&!inTop?`${key} (from turbo.epic)`:key})}var LEGACY_EPIC_CONFIG_WARNING;var init_config=__esm(()=>{LEGACY_EPIC_CONFIG_WARNING="[opencode-swarm] turbo.epic is deprecated — move it to top-level epic "+'(`{ "epic": { "mode": { "enabled": true } } }`; no `turbo` block or `turbo.strategy` is needed). The legacy path keeps working: its keys are used where top-level `epic` does not set them. See docs/configuration.md (Epic Mode).'});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,retiredEpicKeyReplacement:()=>retiredEpicKeyReplacement,resolveGuardrailsConfig:()=>resolveGuardrailsConfig,resolveGeneratedAgentRole:()=>resolveGeneratedAgentRole,resolveExternalSkillsConfig:()=>resolveExternalSkillsConfig,resolveAutoReviewConfig:()=>resolveAutoReviewConfig,isKnownCanonicalRole:()=>isKnownCanonicalRole,getCanonicalAgentRole:()=>getCanonicalAgentRole,findRetiredEpicConfigKeys:()=>findRetiredEpicConfigKeys,_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,RETIRED_EPIC_MODE_KEYS:()=>RETIRED_EPIC_MODE_KEYS,RETIRED_EPIC_KEY_REPLACEMENTS:()=>RETIRED_EPIC_KEY_REPLACEMENTS,RETIRED_EPIC_KEYS:()=>RETIRED_EPIC_KEYS,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,LegacyTurboEpicConfigSchema:()=>LegacyTurboEpicConfigSchema,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 isPlainRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function normalizeAutoReviewInput(value,context={}){if(!isPlainRecord2(value))return value;let normalized={...value};if(!Object.hasOwn(value,"enabled"))normalized.enabled=autoReviewEnabledByRelease(context);if(Object.hasOwn(value,"final_review")&&!isPlainRecord2(value.final_review))return normalized;let nested=isPlainRecord2(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 retiredEpicKeyReplacement(dotted2){let relative=dotted2.replace(/^(?:turbo\.)?epic\./,"");return Object.hasOwn(RETIRED_EPIC_KEY_REPLACEMENTS,relative)?RETIRED_EPIC_KEY_REPLACEMENTS[relative]:void 0}function stripKeys(keys){return(value)=>{if(value===null||typeof value!=="object"||Array.isArray(value))return value;let record2=value;if(!keys.some((key)=>Object.hasOwn(record2,key)))return value;let stripped={...record2};for(let key of keys)delete stripped[key];return stripped}}function findRetiredEpicConfigKeys(raw){let at=(node,key)=>node!==null&&typeof node==="object"&&!Array.isArray(node)&&Object.hasOwn(node,key)?node[key]:void 0,found=[];for(let[prefix,epic]of[["epic",at(raw,"epic")],["turbo.epic",at(at(raw,"turbo"),"epic")]]){let mode=at(epic,"mode");found.push(...RETIRED_EPIC_MODE_KEYS.filter((key)=>at(mode,key)!==void 0).map((key)=>`${prefix}.mode.${key}`),...RETIRED_EPIC_KEYS.filter((key)=>at(epic,key)!==void 0).map((key)=>`${prefix}.${key}`))}return found}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,RETIRED_EPIC_MODE_KEYS,RETIRED_EPIC_KEYS,RETIRED_EPIC_KEY_REPLACEMENTS,stripRetiredEpicModeKeys,stripRetiredEpicKeys,EpicConfigSchema,LegacyTurboEpicConfigSchema,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()}),RETIRED_EPIC_MODE_KEYS=["min_commits_for_signal"],RETIRED_EPIC_KEYS=["calibration"],RETIRED_EPIC_KEY_REPLACEMENTS={calibration:"Epic learning replaced it — see epic.learning.* (enabled, decay_per_epic, half_life_days, hot_excess)."};stripRetiredEpicModeKeys=stripKeys(RETIRED_EPIC_MODE_KEYS),stripRetiredEpicKeys=stripKeys(RETIRED_EPIC_KEYS);EpicConfigSchema=exports_external.preprocess(stripRetiredEpicKeys,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.preprocess(stripRetiredEpicModeKeys,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().optional().meta({deprecated:!0,description:"Retired (Epic v2): accepted and ignored with a warning. Remove it."})}).strict()).optional(),calibration:exports_external.record(exports_external.string(),exports_external.unknown()).optional().meta({deprecated:!0,description:"Retired (Epic v2): accepted and ignored with a warning — Epic learning replaced it (epic.learning). Remove it."}),learning:exports_external.object({enabled:exports_external.boolean().default(!0),decay_per_epic:exports_external.number().min(0).max(1).default(0.7),half_life_days:exports_external.number().positive().default(60),hot_excess:exports_external.number().min(0).max(1).default(0.25)}).strict().optional(),sizing:exports_external.object({min_tasks:exports_external.number().int().min(1).default(6),min_scope_coverage:exports_external.number().min(0).max(1).default(0.8),min_effective_speedup:exports_external.number().min(1).default(1.25),coder_fraction:exports_external.number().min(0).max(1).default(0.6)}).strict().optional(),commit_policy:exports_external.enum(["epic-branch","current-branch"]).optional(),retain_refs:exports_external.boolean().optional(),phase_review:exports_external.object({timeout_ms:exports_external.number().int().min(1e4).max(1800000).default(300000)}).strict().optional()}).strict()),LegacyTurboEpicConfigSchema=EpicConfigSchema.optional().meta({deprecated:!0,description:"Deprecated (still accepted): move this block to top-level `epic` — Epic Mode no longer needs a `turbo` block. Within a file, top-level `epic` wins per key when both are set."}),StandardTurboConfigSchema=exports_external.object({strategy:exports_external.literal("standard"),lean:LeanTurboConfigSchema.optional(),epic:LegacyTurboEpicConfigSchema}),LeanTurboStrategyConfigSchema=exports_external.object({strategy:exports_external.literal("lean"),lean:LeanTurboConfigSchema,epic:LegacyTurboEpicConfigSchema}),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."),epic:EpicConfigSchema.optional().describe("Epic Mode block: one plan = one epic delivered in conflict-free parallel waves. Opt in with `mode.enabled: true`, then `/swarm epic start`. Needs no `turbo` block (legacy `turbo.epic` is still accepted and migrated here)."),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 rawEpicFiles=[rawUserConfig,rawProjectConfig],retiredEpicKeys=[...new Set(rawEpicFiles.flatMap((raw)=>findRetiredEpicConfigKeys(raw)))],annotateEpicKeys=(keys)=>annotateLegacyEpicKeys(keys,rawEpicFiles);if(rawEpicFiles.some(hasLegacyEpicConfig)){if(rawUserConfig)rawUserConfig=migrateLegacyEpicConfig(rawUserConfig);if(rawProjectConfig)rawProjectConfig=migrateLegacyEpicConfig(rawProjectConfig);if(!legacyEpicConfigWarned)legacyEpicConfigWarned=!0,advisoryWarn(LEGACY_EPIC_CONFIG_WARNING)}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.`)}if(retiredEpicKeys.length>0){let signature=retiredEpicKeys.join("\x00");if(signature!==lastRetiredEpicKeysSig)lastRetiredEpicKeysSig=signature,advisoryWarn(`[opencode-swarm] Ignored ${retiredEpicKeys.length} retired Epic config key(s): ${retiredEpicKeys.join(", ")}. They have no effect (the rest of the Epic block is kept) — remove them; see docs/configuration.md (Epic Mode).${retiredEpicKeys.map((key)=>retiredEpicKeyReplacement(key)).filter((hint)=>hint!==void 0).map((hint)=>` ${hint}`).join("")}`)}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:strictRemoved}=stripUnrecognizedKeys(mergedRaw,firstResult.error),removed=annotateEpicKeys(strictRemoved);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){let userRemoved=annotateEpicKeys(userStripped.removed);return advisoryWarn(`[opencode-swarm] Project config ignored; also ignored ${userRemoved.length} unrecognized user-config key(s): ${userRemoved.join(", ")}.`),{config:secure(userRecovered.data),recovery:"user_only",removedKeys:[...gatesStripped,...userGatesStripped,...userRemoved],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,...annotateEpicKeys(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=annotateEpicKeys(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,lastRetiredEpicKeysSig=null,legacyEpicConfigWarned=!1}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,lastRetiredEpicKeysSig=null,legacyEpicConfigWarned=!1,gatesAdvisorySignatures,MAX_GATES_ADVISORY_SIGNATURES=64,_internals4;var init_loader=__esm(()=>{init_config();init_warning_buffer();init_git_executable();init_schema();init_merge();init_merge();gatesAdvisorySignatures=new Set;_internals4={resetUnknownTopLevelKeyWarning(){lastUnknownTopLevelSig=null},resetRetiredEpicKeyWarning(){lastRetiredEpicKeysSig=null},resetLegacyEpicConfigWarning(){legacyEpicConfigWarned=!1},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_config2=__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"?`
|
|
113
113
|
This runtime resolution supersedes any planning-profile default in the base prompt.`:"";if(resolution.effective==="balanced")return`${header}${precedence}
|
|
114
114
|
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}
|
|
115
115
|
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}
|
|
@@ -1054,7 +1054,7 @@ Do not acknowledge or reference this guidance in your response.
|
|
|
1054
1054
|
`).trim(),exitCode=readExitCode(input.metadata),metadataCode=boundedString(readOwn(input.metadata,"code")),originalCommand=input.correlation?.originalCommand??"";if(!signal&&exitCode===void 0)return null;if(shell&&(metadataCode==="SANDBOX_WRAPPER_FAILURE"||input.correlation?.sandboxWrapped===!0&&/\[sandbox\]\s+BLOCKED:/i.test(signal)))return buildRecord({source:"shell",category:"shell.sandbox_wrapper",retryClass:"operator_action",risk:"high",action:{tool:input.tool,args:input.args},display:"sandbox wrapper failed closed",exitCode,code:metadataCode});if(shell&&(metadataCode==="ParserError"||/\b(?:MissingEndCurlyBrace|ParserError|ParseError|IncompleteParseException)\b/i.test(signal)))return buildRecord({source:"shell",category:input.correlation?.sandboxWrapped?"shell.sandbox_wrapper":"shell.parser",retryClass:input.correlation?.sandboxWrapped?"operator_action":"repair_then_retry",risk:"high",action:{tool:input.tool,args:input.args},display:"shell parser rejected the command",exitCode,code:metadataCode});let structuredCommandUnavailable=/\bCommandNotFoundException\b/i.test(explicitError)||metadataCode==="ENOENT"||/\b(?:spawn|execFile)\s+\S+\s+ENOENT\b/i.test(explicitError)||exitCode===127&&/(?:^|\n)(?:\/bin\/)?(?:ba|da|z|k)?sh(?:\.exe)?:\s+(?:(?:line\s+)?\d+:\s+)?[^:\r\n]+:\s+not found\b/im.test(outputSignal)||exitCode===127&&/(?:^|\n)[^:\r\n]+:\s+command not found\b/im.test(outputSignal);if(shell&&structuredCommandUnavailable)return buildRecord({source:"shell",category:"shell.command_unavailable",retryClass:"repair_then_retry",risk:"medium",action:{tool:input.tool,args:input.args},display:`command unavailable${exitCode!==void 0?` (exit ${exitCode})`:""}`,exitCode,code:metadataCode??(/\bENOENT\b/.test(signal)?"ENOENT":void 0)});if(shell&&exitCode===1&&isNeutralExitOne(originalCommand))return null;if(shell&&exitCode!==void 0&&exitCode!==0)return buildRecord({source:"shell",category:"shell.exit",retryClass:"do_not_retry",risk:"medium",action:{tool:input.tool,args:input.args},display:`shell exited with code ${exitCode}`,exitCode,code:metadataCode});if(!shell&&(explicitError.length>0||exitCode!==void 0))return buildRecord({source:"validation",category:"validation.agent_result",retryClass:"repair_then_retry",risk:"medium",action:{tool:input.tool,args:input.args},display:signal||"tool failure",exitCode,code:metadataCode});return null}var MAX_DISPLAY_BYTES=512,MAX_STRUCTURED_STRING=128,FILL_MAX_RUN=8,FILL,CONTROL_CHAR_RUN,MAX_SANITIZE_INPUT_CHARS,SCREAMING_SUFFIXES,TOLERANT_BEARER_PREFIX,TOLERANT_AUTH_SCHEME_PREFIX,CREDENTIAL_MORPHEMES,CREDENTIAL_KEY_SUFFIX_CHARS="\\p{L}\\p{N}_\\-\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\p{Default_Ignorable_Code_Point}",CREDENTIAL_KEY_IDENTIFIER,CREDENTIAL_KV_PATTERN,CSI_SEQUENCE,BARE_SGR_PARAMETER_RUN,SCREAMING_KEY_HORIZONTAL_FILL_CHARS="\\x00-\\x09\\x0e-\\x1f\\x7f-\\x9f\\p{Zs}\\p{Cf}\\p{Default_Ignorable_Code_Point}",SCREAMING_KV_CANDIDATE_PATTERN;var init_invocation_failure=__esm(()=>{init_provider_error_classification();init_action_identity();FILL=`[\\s"'\\p{Cc}\\p{Cf}\\p{Default_Ignorable_Code_Point}]{0,${FILL_MAX_RUN}}`,CONTROL_CHAR_RUN=/[\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}]+/gu,MAX_SANITIZE_INPUT_CHARS=MAX_DISPLAY_BYTES*8;SCREAMING_SUFFIXES=["TOKEN","KEY","SECRET","PASSWORD","AUTH"],TOLERANT_BEARER_PREFIX=tolerantKeyword("Bearer"),TOLERANT_AUTH_SCHEME_PREFIX=`(?:${["Bearer","Basic","Digest","Negotiate","HOBA","Mutual","ApiKey"].map(tolerantKeyword).join("|")})`,CREDENTIAL_MORPHEMES=["token","secret","password","authorization","credential","bearer","key"].map(tolerantKeyword),CREDENTIAL_KEY_IDENTIFIER=`[\\p{L}\\p{N}_-]{0,24}(?:${CREDENTIAL_MORPHEMES.join("|")})[${CREDENTIAL_KEY_SUFFIX_CHARS}]{0,24}`,CREDENTIAL_KV_PATTERN=new RegExp(`(${CREDENTIAL_KEY_IDENTIFIER})${FILL}[:=]${FILL}(?:${TOLERANT_AUTH_SCHEME_PREFIX}${FILL})?(?:${TOLERANT_BEARER_PREFIX}${FILL})?[^\\s,;]+`,"giu"),CSI_SEQUENCE=/\x1b\[[0-9;:;<=>?]{0,32}[ !-/]{0,4}[@-~]/gu,BARE_SGR_PARAMETER_RUN=/\[[0-9;:]{17,64}m/gu,SCREAMING_KV_CANDIDATE_PATTERN=new RegExp(`\\b([A-Z0-9_${SCREAMING_KEY_HORIZONTAL_FILL_CHARS}]{1,80})${FILL}=${FILL}([^\\s]+)`,"gu")});function hasOwn2(source,key){return typeof source==="object"&&source!==null&&Object.hasOwn(source,key)}function readOwn2(source,key){if(!hasOwn2(source,key))return;try{return source[key]}catch{return}}function signalFrom2(value){if(typeof value==="string")return value;if(value instanceof Error)return`${value.name}: ${value.message}`;if(typeof value==="number"||typeof value==="boolean")return String(value);if(typeof value!=="object"||value===null)return"";let source=value;return["name","message","code","status","statusCode"].map((key)=>signalFrom2(readOwn2(source,key))).filter(Boolean).join(" ")}function getOriginalCommand(input,correlation){if(correlation)return correlation.originalCommand;return typeof input.args?.command==="string"?input.args.command:""}function isShellTool2(tool3){let normalized=tool3.toLowerCase();return normalized==="bash"||normalized==="shell"}function isSimpleCommand2(command){return command.length>0&&!/[;&|<>\r\n]/.test(command)}function isNeutralExitOne2(command){let trimmed=command.trim();if(!isSimpleCommand2(trimmed))return!1;let tokens=trimmed.match(/"[^"]*"|'[^']*'|\S+/g)?.map((token)=>token.replace(/^(["'])(.*)\1$/,"$2"))??[],executable=tokens[0]?.toLowerCase();if(executable==="rg"||executable==="rg.exe")return!0;if(executable!=="git"&&executable!=="git.exe")return!1;let subcommandIndex=1;while(tokens[subcommandIndex]==="-C"&&tokens[subcommandIndex+1])subcommandIndex+=2;return tokens[subcommandIndex]?.toLowerCase()==="diff"&&tokens.slice(subcommandIndex+1).includes("--quiet")}function mapFailureRecordToFatalCategory(record3){switch(record3?.category){case"shell.sandbox_wrapper":return"sandbox_wrapper_failure";case"shell.parser":return"shell_parse_error";case"shell.command_unavailable":return"command_not_found";default:return null}}function classifyToolOutcome(input,output,correlation){let explicitError=signalFrom2(readOwn2(output,"error")),explicitFailure=explicitError.length>0||readOwn2(output,"success")===!1||output.output===null||output.output===void 0,shell=isShellTool2(input.tool),metadata=output.metadata,exitPresent=shell&&(hasOwn2(metadata,"exit")||hasOwn2(metadata,"exitCode")),exit=hasOwn2(metadata,"exit")?readOwn2(metadata,"exit"):readOwn2(metadata,"exitCode"),originalCommand=getOriginalCommand(input,correlation),correlatedWrappedCommand=correlation!==void 0&&typeof input.args?.command==="string"&&input.args.command!==correlation.originalCommand,neutralExitOne=exit===1&&isNeutralExitOne2(originalCommand),outputSignal=typeof output.output==="string"?output.output:"",signal=[explicitError,outputSignal].filter(Boolean).join(`
|
|
1055
1055
|
`),rawShellFailure=exitPresent&&(exit===null||typeof exit!=="number"||!Number.isFinite(exit)||exit!==0),record3=explicitFailure||rawShellFailure?classifyToolInvocationFailure({tool:input.tool,args:input.args,output:outputSignal,error:explicitError,metadata,correlation:correlation?{sandboxWrapped:correlation.sandboxWrapped===!0||correlatedWrappedCommand,originalCommand}:{originalCommand}}):null;if((explicitFailure||rawShellFailure)&&shell){let category=mapFailureRecordToFatalCategory(record3);if(category)return{kind:"fatal",category,signal}}if(explicitFailure||rawShellFailure&&!neutralExitOne)return{kind:"failure",signal:record3?.evidence.display??signal};if(neutralExitOne)return{kind:"neutral",signal};if(shell&&exitPresent&&exit===0)return{kind:"success",signal};if(!shell)return{kind:"success",signal};return{kind:"unknown",signal}}function currentOwner(sessionID){let session=getAgentSession(sessionID);if(!session)return null;return{agent:stripKnownSwarmPrefix(session.agentName),invocationId:session.activeInvocationId??0}}function parseSwarmCommandVerb(args2){let record3=typeof args2==="object"&&args2!==null&&!Array.isArray(args2)?args2:void 0;return(typeof record3?.command==="string"?record3.command:typeof record3?.subcommand==="string"?record3.subcommand:"").trim().toLowerCase().split(/\s+/).filter(Boolean).slice(0,3)}function isAllowedRecoverySwarmCommand(args2){let parts=parseSwarmCommandVerb(args2);if(parts.length===0)return!1;if(parts[0]==="diagnose"||parts[0]==="diagnosis")return!0;if(parts[0]==="handoff")return!0;if(parts[0]==="guardrail"&&parts[1]==="reset")return!0;if(parts[0]!=="full-auto"||parts.length<2)return!1;return new Set(["status","retry-oversight","abort","resume","on","off","exit"]).has(parts[1])}function isRecoveryAllowedTool(tool3,args2){let normalized=normalizeToolNameLowerCase(tool3);if(RECOVERY_READ_ONLY_TOOLS.has(normalized))return!0;if(normalized==="swarm"||normalized==="swarm_command"||normalized==="swarm-command")return isAllowedRecoverySwarmCommand(args2);return!1}function resolveActionIdentity(sessionID,context){let owner=currentOwner(sessionID);if(!owner)return null;let action=createActionIdentity({tool:context?.tool??"unknown-tool",args:context?.args});return{ownerAgent:owner.agent,ownerInvocationId:owner.invocationId,actionDigest:action.digest,actionPattern:action.pattern}}function freshCircuit(ownerAgent,ownerInvocationId){return{ownerAgent,ownerInvocationId,category:null,sameCategoryCount:0,hardStop:!1,lastSignal:null}}function ensureCircuit(sessionID){let owner=currentOwner(sessionID);if(!owner)return null;let session=getAgentSession(sessionID);if(!session)return null;let circuit=session.nonTransientCircuit;if(!circuit||circuit.ownerAgent!==owner.agent||circuit.ownerInvocationId!==owner.invocationId)session.nonTransientCircuit=freshCircuit(owner.agent,owner.invocationId);return session.nonTransientCircuit??null}function ensureCircuitSession(sessionID){if(getAgentSession(sessionID))return;let agent=swarmState.activeAgent.get(sessionID)??"architect";ensureAgentSession(sessionID,agent)}function recordNonTransientFailure(sessionID,category,signal,context){let safeSignal=sanitizeFailureEvidenceDisplay(signal);ensureCircuitSession(sessionID);let actionIdentity2=resolveActionIdentity(sessionID,context),circuit=ensureCircuit(sessionID),session=getAgentSession(sessionID);if(!circuit||!session||!actionIdentity2)return null;let threshold=IMMEDIATE_HARD_STOP_CATEGORIES.has(category)?1:SAME_CATEGORY_HARD_STOP_THRESHOLD;if(context?.armAttempt===!0)armActionCircuitAttempt(sessionID,actionIdentity2.ownerInvocationId,actionIdentity2.actionDigest);let{entry,enteredHardStop,ignoredLateEvent}=noteActionCircuitFailure({sessionID,invocationID:actionIdentity2.ownerInvocationId,actionDigest:actionIdentity2.actionDigest,circuitKind:category,signal:safeSignal,hardStopThreshold:threshold});if(!entry||ignoredLateEvent)return circuit;if(circuit.category=category,circuit.sameCategoryCount=entry.count,circuit.hardStop=entry.hardStop,circuit.lastSignal=safeSignal.slice(0,1000),enteredHardStop)telemetry.loopDetected(sessionID,circuit.ownerAgent,`nontransient:${category}:${actionIdentity2.actionPattern}`),pushAdvisory(session,"NON-TRANSIENT STOP ("+category+", "+circuit.sameCategoryCount+"/"+threshold+"): STOP. Do not retry this failure with another command or tool. Report the blocker and wait for corrected input, environment, or scope.");return circuit}function clearNonTransientCircuit(sessionID,context){let circuit=ensureCircuit(sessionID),actionIdentity2=resolveActionIdentity(sessionID,context);if(!circuit||!actionIdentity2)return;clearActionCircuit(sessionID,actionIdentity2.ownerInvocationId,actionIdentity2.actionDigest,{reason:"success"}),circuit.category=null,circuit.sameCategoryCount=0,circuit.hardStop=!1,circuit.lastSignal=null}function nonTransientRemediation(category){switch(category){case"sandbox_wrapper_failure":return'This is a SANDBOX PROVISIONING failure — the command wrapper itself failed to sandbox the command (see "Last signal" for the wrapper error and mechanism). It is NOT the sub-agent refusing to act. '+"Run /swarm diagnose to check the sandbox mechanism and its availability. "+'A UI "session reset" alone may NOT clear this: the circuit is keyed to the current agent invocation, so only a fresh agent invocation (re-delegation) or a full plugin restart resets it — clearing the .opencode cache does not, because the circuit is in-memory. '+"When the sandbox mechanism is genuinely unavailable the shell runs UNSANDBOXED instead of hard-stopping, so a repeatable hard-stop here means the wrapper is actively failing — repair the sandbox environment before re-dispatching.";case"command_not_found":return'A command/executable was not found (see "Last signal"). Ensure the binary is installed and on PATH, then start a fresh invocation.';case"shell_parse_error":return'The shell could not parse the command (see "Last signal"). Fix the command syntax (quoting/escaping), then start a fresh invocation.';default:return"Start a verified new invocation or reset the session before continuing."}}function nonTransientHardStopMessage(circuit){let category=circuit.category??"fatal",signal=circuit.lastSignal??"(no signal captured)";return"NON-TRANSIENT CIRCUIT BREAKER: "+circuit.sameCategoryCount+" consecutive "+category+` failure(s). STOP tool calls and report the blocker.
|
|
1056
1056
|
Last signal: `+signal+`
|
|
1057
|
-
`+nonTransientRemediation(category)}function toCompatCircuit(entry){return{ownerAgent:"unknown",ownerInvocationId:0,category:entry.circuitKind,sameCategoryCount:entry.count,hardStop:entry.hardStop,lastSignal:null}}function assertNonTransientCircuitAllowsTool(sessionID,context){let actionIdentity2=resolveActionIdentity(sessionID,context);if(!actionIdentity2)return;let exactCircuit=getBlockingActionCircuit(sessionID,actionIdentity2.ownerInvocationId,actionIdentity2.actionDigest);if(exactCircuit?.hardStop){let compat3=toCompatCircuit(exactCircuit);throw compat3.lastSignal=getAgentSession(sessionID)?.nonTransientCircuit?.lastSignal??null,Error(nonTransientHardStopMessage(compat3))}let activeHardStops=listBlockingActionCircuitsForInvocation(sessionID,actionIdentity2.ownerInvocationId),normalizedTool=normalizeToolNameLowerCase(context?.tool??"");if(activeHardStops.some((entry)=>entry.circuitKind==="sandbox_wrapper_failure")&&isShellTool2(normalizedTool)){let firstHardStop=activeHardStops[0];if(!firstHardStop)return;let compat3=toCompatCircuit(firstHardStop);throw compat3.lastSignal=getAgentSession(sessionID)?.nonTransientCircuit?.lastSignal??null,Error(nonTransientHardStopMessage(compat3))}if(activeHardStops.length>0&&(normalizedTool==="swarm"||normalizedTool==="swarm_command"||normalizedTool==="swarm-command")&&!isAllowedRecoverySwarmCommand(context?.args)){let firstHardStop=activeHardStops[0];if(!firstHardStop)return;let compat3=toCompatCircuit(firstHardStop);throw compat3.lastSignal=getAgentSession(sessionID)?.nonTransientCircuit?.lastSignal??null,Error(nonTransientHardStopMessage(compat3))}if(activeHardStops.length>0&&isRecoveryAllowedTool(normalizedTool,context?.args))return;armActionCircuitAttempt(sessionID,actionIdentity2.ownerInvocationId,actionIdentity2.actionDigest)}function rememberToolExecution(sessionID,callID,tool3,originalCommand){if(!isShellTool2(tool3)||originalCommand.length===0)return;ensureCircuitSession(sessionID);let session=getAgentSession(sessionID);if(!session)return;let owner=currentOwner(sessionID);if(!owner)return;if(session.pendingToolExecutions??=new Map,!session.pendingToolExecutions.has(callID)&&session.pendingToolExecutions.size>=MAX_PENDING_EXECUTIONS_PER_SESSION){let oldest=session.pendingToolExecutions.keys().next().value;if(typeof oldest==="string")session.pendingToolExecutions.delete(oldest)}session.pendingToolExecutions.set(callID,{tool:tool3,originalCommand,sandboxWrapped:!1,ownerAgent:owner.agent,ownerInvocationId:owner.invocationId})}function isToolExecutionCurrent(sessionID,execution){let owner=currentOwner(sessionID);return owner!==null&&execution.ownerAgent===owner.agent&&execution.ownerInvocationId===owner.invocationId}function markToolExecutionSandboxWrapped(sessionID,callID){let pending=getAgentSession(sessionID)?.pendingToolExecutions?.get(callID);if(pending)pending.sandboxWrapped=!0}function takeToolExecution(sessionID,callID){let pending=getAgentSession(sessionID)?.pendingToolExecutions,execution=pending?.get(callID);return pending?.delete(callID),execution}function forgetToolExecution(sessionID,callID){getAgentSession(sessionID)?.pendingToolExecutions?.delete(callID)}var SAME_CATEGORY_HARD_STOP_THRESHOLD=3,IMMEDIATE_HARD_STOP_CATEGORIES,MAX_PENDING_EXECUTIONS_PER_SESSION=100,RECOVERY_READ_ONLY_TOOLS;var init_nontransient_circuit=__esm(()=>{init_schema();init_action_circuit();init_action_identity();init_invocation_failure();init_state();init_telemetry();init_normalize_tool_name();IMMEDIATE_HARD_STOP_CATEGORIES=new Set(["shell_parse_error","command_not_found","sandbox_wrapper_failure"]);RECOVERY_READ_ONLY_TOOLS=new Set(["read","grep","glob","ls"])});function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isFiniteDuration(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0}function sastFindingKey(value){if(!isRecord(value)||!isRecord(value.location))return null;let{rule_id,severity,message,location}=value;if(typeof rule_id!=="string"||typeof severity!=="string"||typeof message!=="string"||typeof location.file!=="string"||typeof location.line!=="number"||!Number.isSafeInteger(location.line)||location.line<1||!["critical","high","medium","low"].includes(severity)||location.column!==void 0&&(typeof location.column!=="number"||!Number.isSafeInteger(location.column)||location.column<1))return null;return JSON.stringify([rule_id,severity,message,location.file,location.line,location.column??null])}function everyGateFindingIsPreexisting(result,batchResult){if(!Array.isArray(result.findings)||!Array.isArray(batchResult.sast_preexisting_findings))return!1;if(result.findings.map(sastFindingKey).some((key)=>key===null))return!1;let gateFindingKeys=result.findings.filter((finding)=>isRecord(finding)&&(finding.severity==="high"||finding.severity==="critical")).map(sastFindingKey);if(gateFindingKeys.length===0)return!1;let remainingPreexisting=batchResult.sast_preexisting_findings.map(sastFindingKey);if(remainingPreexisting.some((key)=>key===null))return!1;for(let gateFindingKey of gateFindingKeys){let index=remainingPreexisting.indexOf(gateFindingKey);if(index<0)return!1;remainingPreexisting.splice(index,1)}return!0}function isIntentionalSastSkip(toolResult,batchResult){return batchResult.sast_skipped===!0&&toolResult.ran===!1&&toolResult.duration_ms===0&&toolResult.passed===void 0&&toolResult.result===void 0&&toolResult.error===void 0&&toolResult.result_omitted===void 0}function isExpectedSastDegradation(toolResult,batchResult){if(batchResult.sast_degraded!==!0||toolResult.ran!==!0)return!1;if(batchResult.output_truncated===!0&&toolResult.result_omitted===!0&&toolResult.passed===void 0&&toolResult.result===void 0&&toolResult.error===void 0)return!0;if(toolResult.passed!==void 0||toolResult.error!==void 0||toolResult.result_omitted!==void 0)return!1;let result=toolResult.result;return isRecord(result)&&result.verdict==="fail"&&typeof result.error==="string"&&result.failure_kind==="semgrep_process_exit"&&Array.isArray(result.findings)&&result.findings.length===0&&result.baseline_used!==!0}function hardGateExplicitlyFailed(key,toolResult,batchResult){if(key==="sast_scan"&&isIntentionalSastSkip(toolResult,batchResult))return!1;if(toolResult.ran===!1||toolResult.passed===!1)return!0;if(typeof toolResult.error==="string"&&toolResult.error!=="Detailed tool result omitted because the batch output exceeded its byte limit")return!0;let result=toolResult.result;if(!isRecord(result))return!(result===void 0&&batchResult.output_truncated===!0&&toolResult.result_omitted===!0&&toolResult.error===void 0);if(toolResult.result_omitted!==void 0)return!0;if(key==="sast_scan"&&isExpectedSastDegradation(toolResult,batchResult))return!1;if(result.passed===!1||typeof result.error==="string")return!0;if(key==="secretscan"){if(typeof result.count!=="number"||!Number.isSafeInteger(result.count)||result.count<0||!Array.isArray(result.findings)||typeof result.files_scanned!=="number"||!Number.isSafeInteger(result.files_scanned)||result.files_scanned<0||typeof result.incomplete_files!=="number"||!Number.isSafeInteger(result.incomplete_files)||result.incomplete_files<0||!Array.isArray(result.incomplete_paths))return!0;let vacuousCoverage=result.files_scanned===0&&typeof result.policy_skipped_files==="number"&&Number.isSafeInteger(result.policy_skipped_files)&&result.policy_skipped_files>=0&&typeof result.requested_files==="number"&&Number.isSafeInteger(result.requested_files)&&result.requested_files>0&&result.policy_skipped_files>=result.requested_files&&result.count===0&&result.findings.length===0&&result.incomplete_files===0&&result.incomplete_paths.length===0;return result.count>0||result.findings.length>0||result.incomplete_files>0||result.incomplete_paths.length>0||result.files_scanned===0&&!vacuousCoverage}if(result.verdict==="pass")return!1;if(result.verdict!=="fail")return!0;return result.baseline_used===!0||!everyGateFindingIsPreexisting(result,batchResult)}function decodePreCheckResult(output){if(typeof output!=="string"||Buffer.byteLength(output,"utf8")>512000)return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};let parsed;try{parsed=JSON.parse(output)}catch{return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"}}if(!isRecord(parsed)||typeof parsed.gates_passed!=="boolean")return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(!isFiniteDuration(parsed.total_duration_ms))return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(parsed.output_truncated!==void 0&&typeof parsed.output_truncated!=="boolean")return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(parsed.sast_skipped!==void 0&&typeof parsed.sast_skipped!=="boolean"||parsed.sast_degraded!==void 0&&typeof parsed.sast_degraded!=="boolean")return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};let ranStates=[];for(let key of TOOL_KEYS){let toolResult=parsed[key];if(!isRecord(toolResult)||typeof toolResult.ran!=="boolean"||!isFiniteDuration(toolResult.duration_ms)||toolResult.error!==void 0&&typeof toolResult.error!=="string"||toolResult.result_omitted!==void 0&&typeof toolResult.result_omitted!=="boolean"||toolResult.result_omitted===!0&&(toolResult.result!==void 0||toolResult.error!==void 0))return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};ranStates.push(toolResult.ran)}let allSkipped=ranStates.every((ran)=>ran===!1),anyRan=ranStates.some((ran)=>ran===!0),batchStatus=parsed.batch_status;if(parsed.sast_skipped===!0&&!isIntentionalSastSkip(parsed.sast_scan,parsed))return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(parsed.sast_degraded===!0&&!isExpectedSastDegradation(parsed.sast_scan,parsed))return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(batchStatus!==void 0&&batchStatus!=="completed"&&batchStatus!=="skipped"&&batchStatus!=="invalid")return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(batchStatus==="skipped")return allSkipped&&parsed.gates_passed===!1?{kind:"skip"}:{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(batchStatus==="invalid")return allSkipped&&parsed.gates_passed===!1?{kind:"fail",code:"PRE_CHECK_INPUT_INVALID"}:{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(batchStatus==="completed"&&!anyRan)return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(batchStatus===void 0&&allSkipped)return{kind:"skip"};if(parsed.gates_passed&&HARD_GATE_KEYS.some((key)=>hardGateExplicitlyFailed(key,parsed[key],parsed)))return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};return parsed.gates_passed?{kind:"pass"}:{kind:"fail",code:"PRE_CHECK_FAILED"}}var TOOL_KEYS,HARD_GATE_KEYS;var init_pre_check_result=__esm(()=>{TOOL_KEYS=["lint","secretscan","sast_scan","quality_budget"],HARD_GATE_KEYS=["secretscan","sast_scan"]});function knownCostValue(value){if(value===void 0)return null;if(typeof value!=="number"||!Number.isFinite(value)||value<0)return null;return value}function buildTaskAttemptCost(partial3){let unavailable2=[],record3={latencyMs:null,inputTokens:null,outputTokens:null,cacheReadTokens:null,estimatedCostUsd:null,billedCostUsd:null,unavailable:unavailable2};if(partial3.taskId!==void 0)record3.taskId=partial3.taskId;if(partial3.attemptId!==void 0)record3.attemptId=partial3.attemptId;for(let axis of TASK_ATTEMPT_COST_AXES){let value=knownCostValue(partial3[axis]);if(value===null)unavailable2.push(axis);else record3[axis]=value}return record3}function boundedId(value){if(typeof value!=="string")return;let cleaned=value.replace(/[\r\n\t]/g,"_").trim();if(cleaned==="")return;return cleaned.slice(0,128)}function recordExecutionAttempt(input){if(input===null||typeof input!=="object")return;if(!EXECUTION_ATTEMPT_CLASSES.includes(input.attemptClass)){warn("Execution attempt record rejected: class outside closed vocabulary",{attemptClass:String(input.attemptClass)});return}let sessionId=boundedId(input.sessionId??input.sessionID);if(sessionId===void 0){warn("Execution attempt record rejected: no session identity",{attemptClass:input.attemptClass});return}let callId=boundedId(input.callId??input.callID),taskId=boundedId(input.taskId),invocationId=boundedId(input.invocationId),laneId=boundedId(input.laneId),knowledgeTraceId=boundedId(input.knowledgeTraceId);if(input.attemptClass==="late"){if(typeof input.generation!=="number"||!Number.isInteger(input.generation)||input.generation<0){warn("Execution attempt record rejected: late record carries no generation cursor",{attemptClass:input.attemptClass,taskId});return}}if(input.attemptClass==="duplicate"){if(boundedId(input.duplicateOf)===void 0){warn("Execution attempt record rejected: duplicate record carries no original identity",{attemptClass:input.attemptClass,taskId});return}}let captured=["sessionId"],unknown3=[];for(let[field,held]of[["taskId",taskId],["callId",callId],["invocationId",invocationId],["generation",input.generation],["retryIndex",input.retryIndex],["laneId",laneId],["knowledgeTraceId",knowledgeTraceId]])if(held===void 0)unknown3.push(field);else captured.push(field);let cost=buildTaskAttemptCost(input.cost??{});for(let axis of cost.unavailable)unknown3.push(`cost.${axis}`);for(let axis of TASK_ATTEMPT_COST_AXES)if(cost[axis]!==null)captured.push(`cost.${axis}`);let payload={sessionId,attemptClass:input.attemptClass,outcomeStatus:input.outcomeStatus??"unknown",captured,unknown:unknown3,cost};if(taskId!==void 0)payload.taskId=taskId;if(callId!==void 0)payload.callId=callId;if(invocationId!==void 0)payload.invocationId=invocationId;if(typeof input.generation==="number")payload.generation=input.generation;if(typeof input.retryIndex==="number")payload.retryIndex=input.retryIndex;if(laneId!==void 0)payload.laneId=laneId;if(knowledgeTraceId!==void 0)payload.knowledgeTraceId=knowledgeTraceId;if(input.attemptClass==="duplicate")payload.duplicateOf=boundedId(input.duplicateOf);emit("execution_attempt_recorded",payload)}var EXECUTION_ATTEMPT_CLASSES,TASK_ATTEMPT_COST_AXES;var init_execution_attempt=__esm(()=>{init_telemetry();init_logger();EXECUTION_ATTEMPT_CLASSES=["denial","attempt","result","duplicate","late","cancelled","provider_failed"],TASK_ATTEMPT_COST_AXES=["latencyMs","inputTokens","outputTokens","cacheReadTokens","estimatedCostUsd","billedCostUsd"]});function boundedId2(value){if(typeof value!=="string")return null;let cleaned=value.replace(/[\r\n\t]/g,"_").trim();if(cleaned==="")return null;return cleaned.slice(0,128)}function buildEvent(input){return{type:STAGE_A_ROUTE_EVENT_TYPE,route:input.route,sessionID:boundedId2(input.sessionID),callID:boundedId2(input.callID),taskId:boundedId2(input.taskId),guardrailsEnabled:input.guardrailsEnabled===!0,ts:new Date().toISOString()}}function stageARouteAttemptClass(route){switch(route){case"valid_pass":return"result";case"pre_check_failed":case"invalid_result":case"no_task_correlation":case"attribution_ambiguous":return"denial";case"late_result":return"late";case"duplicate_result":return"duplicate"}}function recordStageAGateRoute(directory,input){if(!STAGE_A_ROUTES.includes(input.route)){warn("Stage A route event rejected: route outside closed vocabulary",{route:String(input.route)});return}try{appendCoreEventSync(directory,buildEvent(input))}catch(error93){warn("Stage A route event append failed",{code:error93 instanceof Error?error93.message.slice(0,80):String(error93),route:input.route})}recordExecutionAttempt({sessionId:input.sessionID??void 0,callId:input.callID??void 0,taskId:input.taskId??void 0,...typeof input.generation==="number"?{generation:input.generation}:{},attemptClass:stageARouteAttemptClass(input.route),outcomeStatus:input.route==="valid_pass"?"success":"unknown"})}var STAGE_A_ROUTES,STAGE_A_ROUTE_EVENT_TYPE="stage_a_gate_route";var init_stage_a_route=__esm(()=>{init_core_events();init_execution_attempt();init_logger();STAGE_A_ROUTES=["valid_pass","pre_check_failed","invalid_result","no_task_correlation","attribution_ambiguous","late_result","duplicate_result"]});function isFullAutoMode(value){return VALID_MODES.includes(value)}function parseFullAutoCommandArgs(args2,options={}){let first=args2[0]?.toLowerCase();if(!first)return options.allowToggle?{kind:"toggle"}:{kind:"invalid",message:"Exact paused grammar: status | retry-oversight | resume | abort | on [assisted|supervised|strict] | off | exit."};if(first==="status")return{kind:"status"};if(first==="retry-oversight")return args2.length===1?{kind:"retry_oversight"}:{kind:"invalid",message:"`retry-oversight` does not accept arguments."};if(first==="resume")return args2.length===1?{kind:"resume"}:{kind:"invalid",message:"`resume` does not accept arguments."};if(first==="abort")return args2.length===1?{kind:"abort"}:{kind:"invalid",message:"`abort` does not accept arguments."};if(first==="off"||first==="exit")return args2.length===1?{kind:"disable"}:{kind:"invalid",message:"`off` / `exit` do not accept arguments."};if(first==="on"){if(args2.length===1)return{kind:"enable"};let modeArg=args2[1]?.toLowerCase();if(args2.length===2&&modeArg&&isFullAutoMode(modeArg))return{kind:"enable",mode:modeArg};return{kind:"invalid",message:"Usage: `on [assisted|supervised|strict]` with no extra arguments."}}if(isFullAutoMode(first))return args2.length===1?{kind:"enable",mode:first}:{kind:"invalid",message:"Bare mode tokens do not accept extra arguments. Use `strict`, `supervised`, or `assisted` alone."};return{kind:"invalid",message:"Exact grammar: status | retry-oversight | resume | abort | on [assisted|supervised|strict] | off | exit."}}function isInfrastructurePauseReason(reason){if(!reason)return!1;let normalized=reason.toLowerCase();return normalized.includes("infrastructure failure")||normalized.includes("dispatcher exception")||normalized.includes("deadline")||normalized.includes("opencodeclient unavailable")}function canRetryOversight(state2){return!!state2&&state2.status==="paused"&&isInfrastructurePauseReason(state2.pauseReason)}function canResumeFromProbe(state2,now=Date.now()){if(!state2||state2.status!=="paused")return!1;if(!isInfrastructurePauseReason(state2.pauseReason))return!1;let probe2=state2.lastRecoveryProbe;if(!probe2)return!1;if(probe2.pauseGeneration!==state2.pauseGeneration)return!1;if(probe2.outcome!=="healthy")return!1;return Date.parse(probe2.expiresAt)>=now}function registerFullAutoRecoveryBlockerEvaluator(evaluator){activeRecoveryBlockerEvaluator=evaluator}function getFullAutoRecoveryBlockers(input){return activeRecoveryBlockerEvaluator(input)}function isAllowedPausedSwarmCommand(command,args2,status){let canonical=command.trim().toLowerCase();if(canonical==="diagnose"||canonical==="diagnosis")return args2.length===0;if(canonical==="handoff")return!0;if(canonical!=="full-auto")return!1;let parsed=parseFullAutoCommandArgs(args2,{allowToggle:!1});if(parsed.kind==="invalid"||parsed.kind==="toggle")return!1;if(status==="terminated")return parsed.kind==="status"||parsed.kind==="enable"||parsed.kind==="disable";return!0}var VALID_MODES,activeRecoveryBlockerEvaluator=()=>[];var init_recovery2=__esm(()=>{VALID_MODES=["assisted","supervised","strict"]});import{createHash as createHash41}from"node:crypto";import*as fs57 from"node:fs";import*as path90 from"node:path";function hasControlCharacter2(value){for(let index=0;index<value.length;index++){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function isSafeRef(ref){return ref.length>0&&ref.length<=MAX_REF_LENGTH&&!ref.startsWith("-")&&/^[A-Za-z0-9][A-Za-z0-9._/@+-]*$/.test(ref)&&!ref.includes("..")&&!ref.includes("//")&&!ref.includes("@{")&&ref!=="@"&&!ref.endsWith(".")&&!ref.endsWith("/")&&!ref.endsWith(".lock")}function parseReviewDiffSelector(argv){let selector,json3=!1,setSelector=(next)=>{if(selector)return{ok:!1,code:"AMBIGUOUS_SELECTOR",reason:"review accepts exactly one diff selector"};selector=next;return};for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--json"){json3=!0;continue}if(arg==="--working-tree"){let error93=setSelector({kind:"working-tree"});if(error93)return error93;continue}if(arg==="--base"){let ref=argv[++index];if(ref===void 0)return{ok:!1,code:"INVALID_ARGUMENT",reason:"--base requires one ref"};if(!isSafeRef(ref))return{ok:!1,code:"INVALID_REF",reason:`unsafe or malformed Git ref: ${ref}`};let error93=setSelector({kind:"base",ref});if(error93)return error93;continue}if(arg==="--range"){let range=argv[++index];if(range===void 0)return{ok:!1,code:"INVALID_ARGUMENT",reason:"--range requires from..to or from...to"};let match=/^(.+?)(\.\.\.?)(.+)$/.exec(range);if(!match||match[2]!==".."&&match[2]!=="..."||!isSafeRef(match[1])||!isSafeRef(match[3]))return{ok:!1,code:"INVALID_REF",reason:`unsafe or malformed Git range: ${range}`};let error93=setSelector({kind:"range",from:match[1],to:match[3],operator:match[2]});if(error93)return error93;continue}return{ok:!1,code:"INVALID_ARGUMENT",reason:`unknown review argument: ${arg}`}}return{ok:!0,selector:selector??{kind:"default"},json:json3}}function normalizeRelativePath(raw){if(raw.length===0||hasControlCharacter2(raw)||raw.startsWith("/")||raw.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(raw))return null;let slashPath=raw.replace(/\\/g,"/").replace(/^(?:\.\/)+/,""),normalized=path90.posix.normalize(slashPath);if(normalized==="."||normalized===".."||normalized.startsWith("../")||normalized.startsWith("/")||hasControlCharacter2(normalized))return null;return normalized}function diffHeaderPath(raw,prefix){let trimmed=raw.trimEnd();if(trimmed==="/dev/null")return null;if(trimmed.startsWith('"'))return null;let withoutPrefix=trimmed.startsWith(prefix)?trimmed.slice(prefix.length):trimmed;return normalizeRelativePath(withoutPrefix)}function addLine(map3,file3,line){if(!Number.isSafeInteger(line)||line<1)return;let ranges=map3.get(file3)??[],previous=ranges.at(-1);if(previous&&previous.end+1===line)previous.end=line;else if(!previous||line>previous.end)ranges.push({start:line,end:line});map3.set(file3,ranges)}function parseUnifiedDiffScope(text){let changedLines=new Map,deletedLines=new Map,files=new Map,warnings=[],oldPath,newPath,renameFrom,renameTo,oldLine,newLine,registerFile=()=>{let key=newPath??oldPath;if(!key)return;let kind=renameFrom||renameTo||oldPath&&newPath&&oldPath!==newPath?"renamed":!oldPath?"added":!newPath?"deleted":"modified";files.set(key,{kind,oldPath,newPath})};for(let line of text.split(`
|
|
1057
|
+
`+nonTransientRemediation(category)}function toCompatCircuit(entry){return{ownerAgent:"unknown",ownerInvocationId:0,category:entry.circuitKind,sameCategoryCount:entry.count,hardStop:entry.hardStop,lastSignal:null}}function assertNonTransientCircuitAllowsTool(sessionID,context){let actionIdentity2=resolveActionIdentity(sessionID,context);if(!actionIdentity2)return;let exactCircuit=getBlockingActionCircuit(sessionID,actionIdentity2.ownerInvocationId,actionIdentity2.actionDigest);if(exactCircuit?.hardStop){let compat3=toCompatCircuit(exactCircuit);throw compat3.lastSignal=getAgentSession(sessionID)?.nonTransientCircuit?.lastSignal??null,Error(nonTransientHardStopMessage(compat3))}let activeHardStops=listBlockingActionCircuitsForInvocation(sessionID,actionIdentity2.ownerInvocationId),normalizedTool=normalizeToolNameLowerCase(context?.tool??"");if(activeHardStops.some((entry)=>entry.circuitKind==="sandbox_wrapper_failure")&&isShellTool2(normalizedTool)){let firstHardStop=activeHardStops[0];if(!firstHardStop)return;let compat3=toCompatCircuit(firstHardStop);throw compat3.lastSignal=getAgentSession(sessionID)?.nonTransientCircuit?.lastSignal??null,Error(nonTransientHardStopMessage(compat3))}if(activeHardStops.length>0&&(normalizedTool==="swarm"||normalizedTool==="swarm_command"||normalizedTool==="swarm-command")&&!isAllowedRecoverySwarmCommand(context?.args)){let firstHardStop=activeHardStops[0];if(!firstHardStop)return;let compat3=toCompatCircuit(firstHardStop);throw compat3.lastSignal=getAgentSession(sessionID)?.nonTransientCircuit?.lastSignal??null,Error(nonTransientHardStopMessage(compat3))}if(activeHardStops.length>0&&isRecoveryAllowedTool(normalizedTool,context?.args))return;armActionCircuitAttempt(sessionID,actionIdentity2.ownerInvocationId,actionIdentity2.actionDigest)}function rememberToolExecution(sessionID,callID,tool3,originalCommand){if(!isShellTool2(tool3)||originalCommand.length===0)return;ensureCircuitSession(sessionID);let session=getAgentSession(sessionID);if(!session)return;let owner=currentOwner(sessionID);if(!owner)return;if(session.pendingToolExecutions??=new Map,!session.pendingToolExecutions.has(callID)&&session.pendingToolExecutions.size>=MAX_PENDING_EXECUTIONS_PER_SESSION){let oldest=session.pendingToolExecutions.keys().next().value;if(typeof oldest==="string")session.pendingToolExecutions.delete(oldest)}session.pendingToolExecutions.set(callID,{tool:tool3,originalCommand,sandboxWrapped:!1,ownerAgent:owner.agent,ownerInvocationId:owner.invocationId})}function isToolExecutionCurrent(sessionID,execution){let owner=currentOwner(sessionID);return owner!==null&&execution.ownerAgent===owner.agent&&execution.ownerInvocationId===owner.invocationId}function markToolExecutionSandboxWrapped(sessionID,callID){let pending=getAgentSession(sessionID)?.pendingToolExecutions?.get(callID);if(pending)pending.sandboxWrapped=!0}function takeToolExecution(sessionID,callID){let pending=getAgentSession(sessionID)?.pendingToolExecutions,execution=pending?.get(callID);return pending?.delete(callID),execution}function forgetToolExecution(sessionID,callID){getAgentSession(sessionID)?.pendingToolExecutions?.delete(callID)}var SAME_CATEGORY_HARD_STOP_THRESHOLD=3,IMMEDIATE_HARD_STOP_CATEGORIES,MAX_PENDING_EXECUTIONS_PER_SESSION=100,RECOVERY_READ_ONLY_TOOLS;var init_nontransient_circuit=__esm(()=>{init_schema();init_action_circuit();init_action_identity();init_invocation_failure();init_state();init_telemetry();init_normalize_tool_name();IMMEDIATE_HARD_STOP_CATEGORIES=new Set(["shell_parse_error","command_not_found","sandbox_wrapper_failure"]);RECOVERY_READ_ONLY_TOOLS=new Set(["read","grep","glob","ls"])});function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isFiniteDuration(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0}function sastFindingKey(value){if(!isRecord(value)||!isRecord(value.location))return null;let{rule_id,severity,message,location}=value;if(typeof rule_id!=="string"||typeof severity!=="string"||typeof message!=="string"||typeof location.file!=="string"||typeof location.line!=="number"||!Number.isSafeInteger(location.line)||location.line<1||!["critical","high","medium","low"].includes(severity)||location.column!==void 0&&(typeof location.column!=="number"||!Number.isSafeInteger(location.column)||location.column<1))return null;return JSON.stringify([rule_id,severity,message,location.file,location.line,location.column??null])}function everyGateFindingIsPreexisting(result,batchResult){if(!Array.isArray(result.findings)||!Array.isArray(batchResult.sast_preexisting_findings))return!1;if(result.findings.map(sastFindingKey).some((key)=>key===null))return!1;let gateFindingKeys=result.findings.filter((finding)=>isRecord(finding)&&(finding.severity==="high"||finding.severity==="critical")).map(sastFindingKey);if(gateFindingKeys.length===0)return!1;let remainingPreexisting=batchResult.sast_preexisting_findings.map(sastFindingKey);if(remainingPreexisting.some((key)=>key===null))return!1;for(let gateFindingKey of gateFindingKeys){let index=remainingPreexisting.indexOf(gateFindingKey);if(index<0)return!1;remainingPreexisting.splice(index,1)}return!0}function isIntentionalSastSkip(toolResult,batchResult){return batchResult.sast_skipped===!0&&toolResult.ran===!1&&toolResult.duration_ms===0&&toolResult.passed===void 0&&toolResult.result===void 0&&toolResult.error===void 0&&toolResult.result_omitted===void 0}function everySecretFindingIsPreexisting(result,batchResult){if(!Array.isArray(result.findings)||!Array.isArray(batchResult.secretscan_preexisting_findings))return!1;let count2=result.count;if(typeof count2!=="number"||!Number.isSafeInteger(count2)||count2!==result.findings.length)return!1;let secretFindingKey=(finding)=>{if(!isRecord(finding))return null;let{path:path90,line,type}=finding;if(typeof path90!=="string"||path90.length===0||typeof line!=="number"||!Number.isSafeInteger(line)||line<1||typeof type!=="string")return null;return JSON.stringify([path90,line,type])},remainingPreexisting=batchResult.secretscan_preexisting_findings.map(secretFindingKey);if(remainingPreexisting.some((key)=>key===null))return!1;for(let finding of result.findings){let key=secretFindingKey(finding);if(key===null)return!1;let index=remainingPreexisting.indexOf(key);if(index<0)return!1;remainingPreexisting.splice(index,1)}if(remainingPreexisting.length!==0)return!1;return!0}function isExpectedSastDegradation(toolResult,batchResult){if(batchResult.sast_degraded!==!0||toolResult.ran!==!0)return!1;if(batchResult.output_truncated===!0&&toolResult.result_omitted===!0&&toolResult.passed===void 0&&toolResult.result===void 0&&toolResult.error===void 0)return!0;if(toolResult.passed!==void 0||toolResult.error!==void 0||toolResult.result_omitted!==void 0)return!1;let result=toolResult.result;return isRecord(result)&&result.verdict==="fail"&&typeof result.error==="string"&&result.failure_kind==="semgrep_process_exit"&&Array.isArray(result.findings)&&result.findings.length===0&&result.baseline_used!==!0}function hardGateExplicitlyFailed(key,toolResult,batchResult){if(key==="sast_scan"&&isIntentionalSastSkip(toolResult,batchResult))return!1;if(toolResult.ran===!1||toolResult.passed===!1)return!0;if(typeof toolResult.error==="string"&&toolResult.error!=="Detailed tool result omitted because the batch output exceeded its byte limit")return!0;let result=toolResult.result;if(!isRecord(result))return!(result===void 0&&batchResult.output_truncated===!0&&toolResult.result_omitted===!0&&toolResult.error===void 0);if(toolResult.result_omitted!==void 0)return!0;if(key==="sast_scan"&&isExpectedSastDegradation(toolResult,batchResult))return!1;if(result.passed===!1||typeof result.error==="string")return!0;if(key==="secretscan"){if(typeof result.count!=="number"||!Number.isSafeInteger(result.count)||result.count<0||!Array.isArray(result.findings)||typeof result.files_scanned!=="number"||!Number.isSafeInteger(result.files_scanned)||result.files_scanned<0||typeof result.incomplete_files!=="number"||!Number.isSafeInteger(result.incomplete_files)||result.incomplete_files<0||!Array.isArray(result.incomplete_paths)||result.truncated!==void 0&&typeof result.truncated!=="boolean")return!0;let vacuousCoverage=result.files_scanned===0&&typeof result.policy_skipped_files==="number"&&Number.isSafeInteger(result.policy_skipped_files)&&result.policy_skipped_files>=0&&typeof result.requested_files==="number"&&Number.isSafeInteger(result.requested_files)&&result.requested_files>0&&result.policy_skipped_files>=result.requested_files&&result.count===0&&result.findings.length===0&&result.incomplete_files===0&&result.incomplete_paths.length===0,preexistingProof=everySecretFindingIsPreexisting(result,batchResult);return result.count>0&&!preexistingProof||result.findings.length>0&&!preexistingProof||result.truncated===!0||result.incomplete_files>0||result.incomplete_paths.length>0||result.files_scanned===0&&!vacuousCoverage}if(result.verdict==="pass")return!1;if(result.verdict!=="fail")return!0;return result.baseline_used===!0||!everyGateFindingIsPreexisting(result,batchResult)}function decodePreCheckResult(output){if(typeof output!=="string"||Buffer.byteLength(output,"utf8")>512000)return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};let parsed;try{parsed=JSON.parse(output)}catch{return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"}}if(!isRecord(parsed)||typeof parsed.gates_passed!=="boolean")return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(!isFiniteDuration(parsed.total_duration_ms))return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(parsed.output_truncated!==void 0&&typeof parsed.output_truncated!=="boolean")return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(parsed.sast_skipped!==void 0&&typeof parsed.sast_skipped!=="boolean"||parsed.sast_degraded!==void 0&&typeof parsed.sast_degraded!=="boolean")return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};let ranStates=[];for(let key of TOOL_KEYS){let toolResult=parsed[key];if(!isRecord(toolResult)||typeof toolResult.ran!=="boolean"||!isFiniteDuration(toolResult.duration_ms)||toolResult.error!==void 0&&typeof toolResult.error!=="string"||toolResult.result_omitted!==void 0&&typeof toolResult.result_omitted!=="boolean"||toolResult.result_omitted===!0&&(toolResult.result!==void 0||toolResult.error!==void 0))return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};ranStates.push(toolResult.ran)}let allSkipped=ranStates.every((ran)=>ran===!1),anyRan=ranStates.some((ran)=>ran===!0),batchStatus=parsed.batch_status;if(parsed.sast_skipped===!0&&!isIntentionalSastSkip(parsed.sast_scan,parsed))return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(parsed.sast_degraded===!0&&!isExpectedSastDegradation(parsed.sast_scan,parsed))return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(batchStatus!==void 0&&batchStatus!=="completed"&&batchStatus!=="skipped"&&batchStatus!=="invalid")return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(batchStatus==="skipped")return allSkipped&&parsed.gates_passed===!1?{kind:"skip"}:{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(batchStatus==="invalid")return allSkipped&&parsed.gates_passed===!1?{kind:"fail",code:"PRE_CHECK_INPUT_INVALID"}:{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(batchStatus==="completed"&&!anyRan)return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};if(batchStatus===void 0&&allSkipped)return{kind:"skip"};if(parsed.gates_passed&&HARD_GATE_KEYS.some((key)=>hardGateExplicitlyFailed(key,parsed[key],parsed)))return{kind:"invalid",code:"PRE_CHECK_RESULT_INVALID"};return parsed.gates_passed?{kind:"pass"}:{kind:"fail",code:"PRE_CHECK_FAILED"}}var TOOL_KEYS,HARD_GATE_KEYS;var init_pre_check_result=__esm(()=>{TOOL_KEYS=["lint","secretscan","sast_scan","quality_budget"],HARD_GATE_KEYS=["secretscan","sast_scan"]});function knownCostValue(value){if(value===void 0)return null;if(typeof value!=="number"||!Number.isFinite(value)||value<0)return null;return value}function buildTaskAttemptCost(partial3){let unavailable2=[],record3={latencyMs:null,inputTokens:null,outputTokens:null,cacheReadTokens:null,estimatedCostUsd:null,billedCostUsd:null,unavailable:unavailable2};if(partial3.taskId!==void 0)record3.taskId=partial3.taskId;if(partial3.attemptId!==void 0)record3.attemptId=partial3.attemptId;for(let axis of TASK_ATTEMPT_COST_AXES){let value=knownCostValue(partial3[axis]);if(value===null)unavailable2.push(axis);else record3[axis]=value}return record3}function boundedId(value){if(typeof value!=="string")return;let cleaned=value.replace(/[\r\n\t]/g,"_").trim();if(cleaned==="")return;return cleaned.slice(0,128)}function recordExecutionAttempt(input){if(input===null||typeof input!=="object")return;if(!EXECUTION_ATTEMPT_CLASSES.includes(input.attemptClass)){warn("Execution attempt record rejected: class outside closed vocabulary",{attemptClass:String(input.attemptClass)});return}let sessionId=boundedId(input.sessionId??input.sessionID);if(sessionId===void 0){warn("Execution attempt record rejected: no session identity",{attemptClass:input.attemptClass});return}let callId=boundedId(input.callId??input.callID),taskId=boundedId(input.taskId),invocationId=boundedId(input.invocationId),laneId=boundedId(input.laneId),knowledgeTraceId=boundedId(input.knowledgeTraceId);if(input.attemptClass==="late"){if(typeof input.generation!=="number"||!Number.isInteger(input.generation)||input.generation<0){warn("Execution attempt record rejected: late record carries no generation cursor",{attemptClass:input.attemptClass,taskId});return}}if(input.attemptClass==="duplicate"){if(boundedId(input.duplicateOf)===void 0){warn("Execution attempt record rejected: duplicate record carries no original identity",{attemptClass:input.attemptClass,taskId});return}}let captured=["sessionId"],unknown3=[];for(let[field,held]of[["taskId",taskId],["callId",callId],["invocationId",invocationId],["generation",input.generation],["retryIndex",input.retryIndex],["laneId",laneId],["knowledgeTraceId",knowledgeTraceId]])if(held===void 0)unknown3.push(field);else captured.push(field);let cost=buildTaskAttemptCost(input.cost??{});for(let axis of cost.unavailable)unknown3.push(`cost.${axis}`);for(let axis of TASK_ATTEMPT_COST_AXES)if(cost[axis]!==null)captured.push(`cost.${axis}`);let payload={sessionId,attemptClass:input.attemptClass,outcomeStatus:input.outcomeStatus??"unknown",captured,unknown:unknown3,cost};if(taskId!==void 0)payload.taskId=taskId;if(callId!==void 0)payload.callId=callId;if(invocationId!==void 0)payload.invocationId=invocationId;if(typeof input.generation==="number")payload.generation=input.generation;if(typeof input.retryIndex==="number")payload.retryIndex=input.retryIndex;if(laneId!==void 0)payload.laneId=laneId;if(knowledgeTraceId!==void 0)payload.knowledgeTraceId=knowledgeTraceId;if(input.attemptClass==="duplicate")payload.duplicateOf=boundedId(input.duplicateOf);emit("execution_attempt_recorded",payload)}var EXECUTION_ATTEMPT_CLASSES,TASK_ATTEMPT_COST_AXES;var init_execution_attempt=__esm(()=>{init_telemetry();init_logger();EXECUTION_ATTEMPT_CLASSES=["denial","attempt","result","duplicate","late","cancelled","provider_failed"],TASK_ATTEMPT_COST_AXES=["latencyMs","inputTokens","outputTokens","cacheReadTokens","estimatedCostUsd","billedCostUsd"]});function boundedId2(value){if(typeof value!=="string")return null;let cleaned=value.replace(/[\r\n\t]/g,"_").trim();if(cleaned==="")return null;return cleaned.slice(0,128)}function buildEvent(input){return{type:STAGE_A_ROUTE_EVENT_TYPE,route:input.route,sessionID:boundedId2(input.sessionID),callID:boundedId2(input.callID),taskId:boundedId2(input.taskId),guardrailsEnabled:input.guardrailsEnabled===!0,ts:new Date().toISOString()}}function stageARouteAttemptClass(route){switch(route){case"valid_pass":return"result";case"pre_check_failed":case"invalid_result":case"no_task_correlation":case"attribution_ambiguous":return"denial";case"late_result":return"late";case"duplicate_result":return"duplicate"}}function recordStageAGateRoute(directory,input){if(!STAGE_A_ROUTES.includes(input.route)){warn("Stage A route event rejected: route outside closed vocabulary",{route:String(input.route)});return}try{appendCoreEventSync(directory,buildEvent(input))}catch(error93){warn("Stage A route event append failed",{code:error93 instanceof Error?error93.message.slice(0,80):String(error93),route:input.route})}recordExecutionAttempt({sessionId:input.sessionID??void 0,callId:input.callID??void 0,taskId:input.taskId??void 0,...typeof input.generation==="number"?{generation:input.generation}:{},attemptClass:stageARouteAttemptClass(input.route),outcomeStatus:input.route==="valid_pass"?"success":"unknown"})}var STAGE_A_ROUTES,STAGE_A_ROUTE_EVENT_TYPE="stage_a_gate_route";var init_stage_a_route=__esm(()=>{init_core_events();init_execution_attempt();init_logger();STAGE_A_ROUTES=["valid_pass","pre_check_failed","invalid_result","no_task_correlation","attribution_ambiguous","late_result","duplicate_result"]});function isFullAutoMode(value){return VALID_MODES.includes(value)}function parseFullAutoCommandArgs(args2,options={}){let first=args2[0]?.toLowerCase();if(!first)return options.allowToggle?{kind:"toggle"}:{kind:"invalid",message:"Exact paused grammar: status | retry-oversight | resume | abort | on [assisted|supervised|strict] | off | exit."};if(first==="status")return{kind:"status"};if(first==="retry-oversight")return args2.length===1?{kind:"retry_oversight"}:{kind:"invalid",message:"`retry-oversight` does not accept arguments."};if(first==="resume")return args2.length===1?{kind:"resume"}:{kind:"invalid",message:"`resume` does not accept arguments."};if(first==="abort")return args2.length===1?{kind:"abort"}:{kind:"invalid",message:"`abort` does not accept arguments."};if(first==="off"||first==="exit")return args2.length===1?{kind:"disable"}:{kind:"invalid",message:"`off` / `exit` do not accept arguments."};if(first==="on"){if(args2.length===1)return{kind:"enable"};let modeArg=args2[1]?.toLowerCase();if(args2.length===2&&modeArg&&isFullAutoMode(modeArg))return{kind:"enable",mode:modeArg};return{kind:"invalid",message:"Usage: `on [assisted|supervised|strict]` with no extra arguments."}}if(isFullAutoMode(first))return args2.length===1?{kind:"enable",mode:first}:{kind:"invalid",message:"Bare mode tokens do not accept extra arguments. Use `strict`, `supervised`, or `assisted` alone."};return{kind:"invalid",message:"Exact grammar: status | retry-oversight | resume | abort | on [assisted|supervised|strict] | off | exit."}}function isInfrastructurePauseReason(reason){if(!reason)return!1;let normalized=reason.toLowerCase();return normalized.includes("infrastructure failure")||normalized.includes("dispatcher exception")||normalized.includes("deadline")||normalized.includes("opencodeclient unavailable")}function canRetryOversight(state2){return!!state2&&state2.status==="paused"&&isInfrastructurePauseReason(state2.pauseReason)}function canResumeFromProbe(state2,now=Date.now()){if(!state2||state2.status!=="paused")return!1;if(!isInfrastructurePauseReason(state2.pauseReason))return!1;let probe2=state2.lastRecoveryProbe;if(!probe2)return!1;if(probe2.pauseGeneration!==state2.pauseGeneration)return!1;if(probe2.outcome!=="healthy")return!1;return Date.parse(probe2.expiresAt)>=now}function registerFullAutoRecoveryBlockerEvaluator(evaluator){activeRecoveryBlockerEvaluator=evaluator}function getFullAutoRecoveryBlockers(input){return activeRecoveryBlockerEvaluator(input)}function isAllowedPausedSwarmCommand(command,args2,status){let canonical=command.trim().toLowerCase();if(canonical==="diagnose"||canonical==="diagnosis")return args2.length===0;if(canonical==="handoff")return!0;if(canonical!=="full-auto")return!1;let parsed=parseFullAutoCommandArgs(args2,{allowToggle:!1});if(parsed.kind==="invalid"||parsed.kind==="toggle")return!1;if(status==="terminated")return parsed.kind==="status"||parsed.kind==="enable"||parsed.kind==="disable";return!0}var VALID_MODES,activeRecoveryBlockerEvaluator=()=>[];var init_recovery2=__esm(()=>{VALID_MODES=["assisted","supervised","strict"]});import{createHash as createHash41}from"node:crypto";import*as fs57 from"node:fs";import*as path90 from"node:path";function hasControlCharacter2(value){for(let index=0;index<value.length;index++){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function isSafeRef(ref){return ref.length>0&&ref.length<=MAX_REF_LENGTH&&!ref.startsWith("-")&&/^[A-Za-z0-9][A-Za-z0-9._/@+-]*$/.test(ref)&&!ref.includes("..")&&!ref.includes("//")&&!ref.includes("@{")&&ref!=="@"&&!ref.endsWith(".")&&!ref.endsWith("/")&&!ref.endsWith(".lock")}function parseReviewDiffSelector(argv){let selector,json3=!1,setSelector=(next)=>{if(selector)return{ok:!1,code:"AMBIGUOUS_SELECTOR",reason:"review accepts exactly one diff selector"};selector=next;return};for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--json"){json3=!0;continue}if(arg==="--working-tree"){let error93=setSelector({kind:"working-tree"});if(error93)return error93;continue}if(arg==="--base"){let ref=argv[++index];if(ref===void 0)return{ok:!1,code:"INVALID_ARGUMENT",reason:"--base requires one ref"};if(!isSafeRef(ref))return{ok:!1,code:"INVALID_REF",reason:`unsafe or malformed Git ref: ${ref}`};let error93=setSelector({kind:"base",ref});if(error93)return error93;continue}if(arg==="--range"){let range=argv[++index];if(range===void 0)return{ok:!1,code:"INVALID_ARGUMENT",reason:"--range requires from..to or from...to"};let match=/^(.+?)(\.\.\.?)(.+)$/.exec(range);if(!match||match[2]!==".."&&match[2]!=="..."||!isSafeRef(match[1])||!isSafeRef(match[3]))return{ok:!1,code:"INVALID_REF",reason:`unsafe or malformed Git range: ${range}`};let error93=setSelector({kind:"range",from:match[1],to:match[3],operator:match[2]});if(error93)return error93;continue}return{ok:!1,code:"INVALID_ARGUMENT",reason:`unknown review argument: ${arg}`}}return{ok:!0,selector:selector??{kind:"default"},json:json3}}function normalizeRelativePath(raw){if(raw.length===0||hasControlCharacter2(raw)||raw.startsWith("/")||raw.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(raw))return null;let slashPath=raw.replace(/\\/g,"/").replace(/^(?:\.\/)+/,""),normalized=path90.posix.normalize(slashPath);if(normalized==="."||normalized===".."||normalized.startsWith("../")||normalized.startsWith("/")||hasControlCharacter2(normalized))return null;return normalized}function diffHeaderPath(raw,prefix){let trimmed=raw.trimEnd();if(trimmed==="/dev/null")return null;if(trimmed.startsWith('"'))return null;let withoutPrefix=trimmed.startsWith(prefix)?trimmed.slice(prefix.length):trimmed;return normalizeRelativePath(withoutPrefix)}function addLine(map3,file3,line){if(!Number.isSafeInteger(line)||line<1)return;let ranges=map3.get(file3)??[],previous=ranges.at(-1);if(previous&&previous.end+1===line)previous.end=line;else if(!previous||line>previous.end)ranges.push({start:line,end:line});map3.set(file3,ranges)}function parseUnifiedDiffScope(text){let changedLines=new Map,deletedLines=new Map,files=new Map,warnings=[],oldPath,newPath,renameFrom,renameTo,oldLine,newLine,registerFile=()=>{let key=newPath??oldPath;if(!key)return;let kind=renameFrom||renameTo||oldPath&&newPath&&oldPath!==newPath?"renamed":!oldPath?"added":!newPath?"deleted":"modified";files.set(key,{kind,oldPath,newPath})};for(let line of text.split(`
|
|
1058
1058
|
`)){if(line.startsWith("diff --git ")){registerFile(),oldPath=void 0,newPath=void 0,renameFrom=void 0,renameTo=void 0,oldLine=void 0,newLine=void 0;continue}let hunk=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);if(hunk){oldLine=Number.parseInt(hunk[1],10),newLine=Number.parseInt(hunk[2],10);continue}if(oldLine!==void 0&&newLine!==void 0){if(line.startsWith("+")){if(newPath)addLine(changedLines,newPath,newLine);newLine++;continue}if(line.startsWith("-")){if(oldPath)addLine(deletedLines,oldPath,oldLine);oldLine++;continue}if(line.startsWith(" ")){oldLine++,newLine++;continue}if(line.startsWith("\\"))continue;oldLine=void 0,newLine=void 0}if(line.startsWith("rename from ")){renameFrom=normalizeRelativePath(line.slice(12))??void 0,oldPath=renameFrom;continue}if(line.startsWith("rename to ")){renameTo=normalizeRelativePath(line.slice(10))??void 0,newPath=renameTo,registerFile();continue}if(line.startsWith("--- ")){let raw=line.slice(4);if(oldPath=raw.trimEnd()==="/dev/null"?void 0:diffHeaderPath(raw,"a/")??void 0,raw.trimEnd()!=="/dev/null"&&!oldPath)warnings.push({code:"UNPARSEABLE_DIFF_PATH",detail:`unparseable old-side diff path: ${raw}`});continue}if(line.startsWith("+++ ")){let raw=line.slice(4);if(newPath=raw.trimEnd()==="/dev/null"?void 0:diffHeaderPath(raw,"b/")??void 0,raw.trimEnd()!=="/dev/null"&&!newPath)warnings.push({code:"UNPARSEABLE_DIFF_PATH",detail:`unparseable new-side diff path: ${raw}`});registerFile()}}return registerFile(),{changedLines,deletedLines,files,warnings}}async function readBoundedStream(stream,maxBytes,onLimit){let reader=stream.getReader(),chunks=[],total=0,truncated=!1;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-total;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.subarray(0,remaining));total+=Math.max(remaining,0),truncated=!0,onLimit(),await reader.cancel().catch(()=>{});break}chunks.push(value),total+=value.byteLength}}finally{if(truncated)await reader.cancel().catch(()=>{})}let combined=new Uint8Array(total),offset=0;for(let chunk of chunks)combined.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(combined),truncated}}async function runGit4(directory,args2,options){let spawnOptions={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:options.timeoutMs},proc;try{let gitExecutable=await _internals85.resolveGitExecutable();proc=_internals85.bunSpawn([gitExecutable,"-c","core.quotepath=false",...args2],spawnOptions)}catch(error93){return{ok:!1,code:"GIT_FAILED",reason:error93 instanceof Error?error93.message:String(error93)}}let timeoutHandle,limited=!1,kill=()=>{limited=!0;try{proc.kill()}catch{}};try{let operation=Promise.all([proc.exited,readBoundedStream(proc.stdout,options.maxStdoutBytes,kill),readBoundedStream(proc.stderr,STDERR_OUTPUT_LIMIT,kill)]),[exitCode,stdout,stderr]=await Promise.race([operation,new Promise((_,reject2)=>{timeoutHandle=setTimeout(()=>reject2(Error("REVIEW_DIFF_GIT_TIMEOUT")),options.timeoutMs)})]);if(stdout.truncated&&!options.allowTruncate)return{ok:!1,code:"GIT_OUTPUT_LIMIT",reason:`Git stdout exceeded ${options.maxStdoutBytes} bytes`};if(stderr.truncated)return{ok:!1,code:"GIT_OUTPUT_LIMIT",reason:`Git stderr exceeded ${STDERR_OUTPUT_LIMIT} bytes`};if(exitCode!==0&&!(stdout.truncated&&options.allowTruncate))return{ok:!1,code:"GIT_FAILED",reason:stderr.text.trim()||`Git exited with code ${exitCode}`};return{ok:!0,stdout:stdout.text,truncated:stdout.truncated}}catch(error93){if(error93 instanceof Error&&error93.message==="REVIEW_DIFF_GIT_TIMEOUT")return{ok:!1,code:"GIT_TIMEOUT",reason:`Git exceeded ${options.timeoutMs}ms`};return{ok:!1,code:limited?"GIT_OUTPUT_LIMIT":"GIT_FAILED",reason:error93 instanceof Error?error93.message:String(error93)}}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);try{proc.kill()}catch{}}}function samePath3(left,right){let a=path90.resolve(left),b=path90.resolve(right);return process.platform==="win32"?a.toLowerCase()===b.toLowerCase():a===b}function sameFileIdentity(left,right){return(left.dev!==0n||left.ino!==0n)&&(right.dev!==0n||right.ino!==0n)&&left.dev===right.dev&&left.ino===right.ino}function sameCanonicalDirectory(left,right){if(samePath3(left,right))return!0;try{let leftStat=_internals85.lstatBigIntSync(left),rightStat=_internals85.lstatBigIntSync(right);return leftStat.isDirectory()&&rightStat.isDirectory()&&!leftStat.isSymbolicLink()&&!rightStat.isSymbolicLink()&&(leftStat.dev!==0n||leftStat.ino!==0n)&&sameFileIdentity(leftStat,rightStat)}catch{return!1}}function sameFileSnapshot(left,right){return sameFileIdentity(left,right)&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function isContained(root,candidate){let relative23=path90.relative(root,candidate);return relative23.length>0&&!relative23.startsWith(`..${path90.sep}`)&&relative23!==".."&&!path90.isAbsolute(relative23)}function selectorKey(selector){switch(selector.kind){case"default":return"default";case"base":return`base:${selector.ref}`;case"range":return`range:${selector.from}${selector.operator}${selector.to}`;case"working-tree":return"working-tree"}}function reviewTargetKind(selector){switch(selector.kind){case"range":return"exact-committed-range";case"working-tree":return"checkout-index-working-tree";default:return"checkout-history-index-working-tree"}}function compareUtf8Bytes(left,right){return Buffer.compare(Buffer.from(left,"utf8"),Buffer.from(right,"utf8"))}function uniqueSkipCodes(skipReasons){return[...new Set(skipReasons.map((item)=>item.code))].sort()}function hashManifestPayload(payload){return createHash41("sha256").update(JSON.stringify(payload),"utf8").digest("hex")}function parseObjectFormat(stdout){let objectFormat=stdout.trim();return objectFormat.length>0&&!hasControlCharacter2(objectFormat)?objectFormat:null}function parseLsTreeBlobId(stdout,expectedPath){let trimmed=stdout.endsWith("\x00")?stdout.slice(0,-1):stdout;if(!trimmed)return null;let tabIndex=trimmed.indexOf("\t");if(tabIndex===-1)return null;let metadata=trimmed.slice(0,tabIndex).trim().split(/\s+/),actualPath=normalizeRelativePath(trimmed.slice(tabIndex+1));if(metadata.length<3||metadata[1]!=="blob"||actualPath!==expectedPath||!SHA_PATTERN.test(metadata[2]??""))return null;return metadata[2]}async function resolveGitObjectFormat(root,timeoutMs){let result=await runGit4(root,["rev-parse","--show-object-format"],{timeoutMs,maxStdoutBytes:METADATA_OUTPUT_LIMIT});return result.ok?parseObjectFormat(result.stdout):null}async function readGitBlobIdentity(root,treeish,relativePath,timeoutMs,objectFormat){let result=await runGit4(root,["ls-tree","-z",treeish,"--",relativePath],{timeoutMs,maxStdoutBytes:METADATA_OUTPUT_LIMIT});if(!result.ok)return null;let blobId=parseLsTreeBlobId(result.stdout,relativePath);if(!blobId)return null;return{algorithm:"git-blob",git_blob_oid:blobId,git_object_format:objectFormat}}function compareStats(left,right){return sameFileIdentity(left,right)&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function hashWorkingTreeIdentity(root,rawPath,budget){let normalized=normalizeRelativePath(rawPath);if(!normalized)return{identity:null};let candidate=path90.resolve(root,...normalized.split("/"));if(!isContained(root,candidate))return{identity:null};let handle,deadlineExceeded=(detail)=>({identity:null,failure:{code:"UNREADABLE_FILE",path:normalized,detail}});try{if(_internals85.now()>budget.deadlineMs)return deadlineExceeded("working-tree content identity deadline expired before file hashing started");let pathStat=_internals85.lstatBigIntSync(candidate);if(!pathStat.isFile()||pathStat.isSymbolicLink())return{identity:null};let canonicalBeforeOpen=_internals85.realpathSync(candidate);if(!isContained(root,canonicalBeforeOpen))return{identity:null};handle=_internals85.openSync(canonicalBeforeOpen,"r");let openedBeforeRead=_internals85.fstatBigIntSync(handle),canonicalAfterOpen=_internals85.realpathSync(candidate);if(!openedBeforeRead.isFile()||!compareStats(pathStat,openedBeforeRead)||!samePath3(canonicalBeforeOpen,canonicalAfterOpen)||!isContained(root,canonicalAfterOpen))return{identity:null};if(openedBeforeRead.size>BigInt(Number.MAX_SAFE_INTEGER))return deadlineExceeded("working-tree content identity byte length exceeds safe integer bounds");if(openedBeforeRead.size>BigInt(WORKTREE_IDENTITY_MAX_FILE_BYTES))return deadlineExceeded(`working-tree content identity exceeded the ${WORKTREE_IDENTITY_MAX_FILE_BYTES}-byte per-file cap`);let fileBytes=Number(openedBeforeRead.size);if(fileBytes>budget.remainingBytes)return deadlineExceeded(`working-tree content identity exceeded the ${WORKTREE_IDENTITY_TOTAL_BYTES}-byte aggregate cap`);let hash4=createHash41("sha256"),buffer=Buffer.alloc(65536),offset=0;while(offset<fileBytes){if(_internals85.now()>budget.deadlineMs)return deadlineExceeded("working-tree content identity deadline expired while hashing file content");let read=_internals85.readSync(handle,buffer,0,Math.min(buffer.byteLength,fileBytes-offset),offset);if(read===0)break;hash4.update(buffer.subarray(0,read)),offset+=read}let openedAfterRead=_internals85.fstatBigIntSync(handle),canonicalAfterRead=_internals85.realpathSync(candidate);if(!compareStats(openedBeforeRead,openedAfterRead)||!samePath3(canonicalBeforeOpen,canonicalAfterRead)||!isContained(root,canonicalAfterRead)||offset!==fileBytes)return{identity:null};return budget.remainingBytes-=fileBytes,{identity:{algorithm:"sha256",sha256:hash4.digest("hex"),byte_length:Number(openedAfterRead.size)}}}catch{return{identity:null}}finally{if(handle!==void 0)try{_internals85.closeSync(handle)}catch{}}}async function buildReviewManifest(root,selector,files,completeness,timeoutMs,revisionContext,contentHash){let objectFormat=await resolveGitObjectFormat(root,timeoutMs)??"sha1",pathRecords=[],identityFailures=[],missingIdentityBindings=new Set,workingTreeBudget=selector.kind==="range"?void 0:{remainingBytes:WORKTREE_IDENTITY_TOTAL_BYTES,deadlineMs:_internals85.now()+Math.min(timeoutMs,WORKTREE_IDENTITY_MAX_DURATION_MS)},orderedScopes=[...files.values()].sort((left,right)=>compareUtf8Bytes(left.newPath??left.oldPath??"",right.newPath??right.oldPath??"")),oldTreeForSelector=selector.kind==="working-tree"?revisionContext.headSha:selector.kind==="range"?selector.operator==="..."?revisionContext.mergeBase:revisionContext.baseSha:revisionContext.mergeBase,newTreeForSelector=selector.kind==="range"?revisionContext.rangeToSha:void 0;for(let scope of orderedScopes){let record3={kind:scope.kind,old_path:scope.oldPath,new_path:scope.newPath};if(scope.kind!=="added"&&scope.oldPath&&oldTreeForSelector)record3.old_identity=await readGitBlobIdentity(root,oldTreeForSelector,scope.oldPath,timeoutMs,objectFormat)??void 0;if(scope.newPath){if(selector.kind==="range"&&newTreeForSelector)record3.new_identity=await readGitBlobIdentity(root,newTreeForSelector,scope.newPath,timeoutMs,objectFormat)??void 0;else if(workingTreeBudget){let hashed=hashWorkingTreeIdentity(root,scope.newPath,workingTreeBudget);if(record3.new_identity=hashed.identity??void 0,hashed.failure)identityFailures.push(hashed.failure),missingIdentityBindings.add(`new:${scope.newPath}`)}}pathRecords.push(record3)}let payload={schema_version:2,content_hash:contentHash,selector,selector_key:selectorKey(selector),review_target_kind:reviewTargetKind(selector),completeness:{complete:completeness.complete,truncated:completeness.truncated,skip_reason_codes:uniqueSkipCodes(completeness.skipReasons)},path_records:pathRecords};return{manifest:{...payload,hash:hashManifestPayload(payload)},identityFailures,missingIdentityBindings}}function boundedPositiveInteger(value,fallback,maximum){if(value===void 0||!Number.isFinite(value))return fallback;return Math.min(maximum,Math.max(1,Math.floor(value)))}function truncateAtLineBoundary(text,maxBytes){let markerBytes=Buffer.byteLength(`
|
|
1059
1059
|
... [review diff truncated: max_bytes]
|
|
1060
1060
|
`);if(maxBytes<=markerBytes)return`
|
|
@@ -2629,7 +2629,7 @@ Flags:
|
|
|
2629
2629
|
--out <dir> output directory (default "docs")
|
|
2630
2630
|
--lang <name> target language for the reference/ docs (default: inferred)
|
|
2631
2631
|
--update sync existing docs to current code/spec instead of generating fresh`;var init_design_docs=__esm(()=>{init_config2();init_warning_buffer();_internals153={loadPluginConfigWithMeta}});import*as fs101 from"node:fs";import*as os23 from"node:os";import*as path186 from"node:path";function getPluginConfigDir(){return path186.join(process.env.XDG_CONFIG_HOME||path186.join(os23.homedir(),".config"),"opencode")}function getHostConfigDir(){let override=process.env.OPENCODE_CONFIG_DIR;if(override&&override.trim()!=="")return override;return getPluginConfigDir()}function getHostDataDir(){let base=process.env.XDG_DATA_HOME||path186.join(os23.homedir(),".local","share");return path186.join(base,"opencode")}function getHostCacheDir(){let base=process.env.XDG_CACHE_HOME||path186.join(os23.homedir(),".cache");return path186.join(base,"opencode")}function getHostSkillCacheDir(){return path186.join(getHostCacheDir(),"skills")}function getPluginCachePaths(){let cacheBase=process.env.XDG_CACHE_HOME||path186.join(os23.homedir(),".cache"),configDir=getPluginConfigDir(),paths=[path186.join(cacheBase,"opencode","node_modules","opencode-swarm"),path186.join(cacheBase,"opencode","packages","opencode-swarm@latest"),path186.join(cacheBase,"opencode","packages","opencode-swarm"),path186.join(configDir,"node_modules","opencode-swarm")];if(process.platform==="darwin"){let libCaches=path186.join(os23.homedir(),"Library","Caches");paths.push(path186.join(libCaches,"opencode","node_modules","opencode-swarm"),path186.join(libCaches,"opencode","packages","opencode-swarm@latest"),path186.join(libCaches,"opencode","packages","opencode-swarm"))}if(process.platform==="win32"){let localAppData=process.env.LOCALAPPDATA||path186.join(os23.homedir(),"AppData","Local"),appData=process.env.APPDATA||path186.join(os23.homedir(),"AppData","Roaming");paths.push(path186.join(localAppData,"opencode","node_modules","opencode-swarm"),path186.join(localAppData,"opencode","packages","opencode-swarm@latest"),path186.join(localAppData,"opencode","packages","opencode-swarm"),path186.join(appData,"opencode","node_modules","opencode-swarm"))}return paths}function discoverVersionPinnedCachePaths(){let cacheBase=process.env.XDG_CACHE_HOME||path186.join(os23.homedir(),".cache"),packagesParents=[path186.join(cacheBase,"opencode","packages")];if(process.platform==="darwin"){let libCaches=path186.join(os23.homedir(),"Library","Caches");packagesParents.push(path186.join(libCaches,"opencode","packages"))}if(process.platform==="win32"){let localAppData=process.env.LOCALAPPDATA||path186.join(os23.homedir(),"AppData","Local");packagesParents.push(path186.join(localAppData,"opencode","packages"))}let found=[];for(let parent of packagesParents){let entries2;try{entries2=fs101.readdirSync(parent,{withFileTypes:!0})}catch{continue}for(let entry of entries2){if(!VERSION_PINNED_LEAF.test(entry.name))continue;if(!entry.isDirectory()&&!entry.isSymbolicLink())continue;found.push(path186.join(parent,entry.name))}}return found}function resolveCachePackageRoot(cachePath){let nestedPackageRoot=path186.join(cachePath,"node_modules","opencode-swarm");return fs101.existsSync(nestedPackageRoot)?nestedPackageRoot:cachePath}var VERSION_PINNED_LEAF;var init_cache_paths=__esm(()=>{VERSION_PINNED_LEAF=/^opencode-swarm@\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/});async function readDurableGateEvidence(directory,taskId){try{return await readTaskEvidence(directory,taskId)}catch{return null}}function getDurableGateEvidenceStatus(evidence2){if(!evidence2?.gates||typeof evidence2.gates!=="object")return{isComplete:!1,missingGates:[],evidenceExists:evidence2!=null,invalid:!1};if(!Array.isArray(evidence2.required_gates))return{isComplete:!1,missingGates:["required_gates"],evidenceExists:!0,invalid:!1};let derivedGates=deriveApplicableGateSet(evidence2);return{isComplete:derivedGates.missingGates.length===0,missingGates:derivedGates.missingGates,evidenceExists:!0,invalid:!1}}async function getDurableGateEvidenceStatusForTask(directory,taskId){if(!isValidTaskId(taskId))return{isComplete:!1,missingGates:[],evidenceExists:!1,invalid:!1};try{return getDurableGateEvidenceStatusWithCurrentScope(readTaskEvidenceRaw(directory,taskId),directory,taskId)}catch{return{isComplete:!1,missingGates:["invalid_gate_evidence"],evidenceExists:!0,invalid:!0}}}function getDurableGateEvidenceStatusWithCurrentScope(evidence2,directory,taskId){if(!evidence2?.gates||typeof evidence2.gates!=="object")return getDurableGateEvidenceStatus(evidence2);if(!Array.isArray(evidence2.required_gates))return getDurableGateEvidenceStatus(evidence2);if(!evidence2.workflow||evidence2.workflow.schema!==TASK_WORKFLOW_SCHEMA_MARKER){if(evidence2.required_gates.length===0)return{isComplete:!1,missingGates:["required_gates"],evidenceExists:!0,invalid:!1};let missingGates=evidence2.required_gates.filter((gate)=>evidence2.gates[gate]==null);return{isComplete:missingGates.length===0,missingGates,evidenceExists:!0,invalid:!1}}let derivedGates=deriveApplicableGateSet(evidence2,{currentDeclaredFiles:readCurrentTaskDeclaredFiles(directory,taskId)});return{isComplete:derivedGates.missingGates.length===0,missingGates:derivedGates.missingGates,evidenceExists:!0,invalid:!1}}function gateEvidenceToEntry(taskId,gate,type,evidence2){let gateRecord=evidence2.gates[gate];if(!gateRecord)return null;let base={task_id:taskId,timestamp:gateRecord.timestamp,agent:gateRecord.agent||gate,verdict:"pass",summary:`Gate evidence recorded by ${gate}`,metadata:{source:"durable_gate_evidence",gate}};if(type==="review")return{...base,type,risk:"low",issues:[]};if(type==="approval")return{...base,type};return{...base,type,tests_passed:0,tests_failed:0,failures:[]}}function mergeDurableGateEntriesFromEvidence(taskId,entries2,evidence2){if(!evidence2?.gates)return entries2;let merged=[...entries2];for(let gate of Object.keys(evidence2.gates).sort()){let type=GATE_EVIDENCE_TYPE_BY_GATE[gate]??"approval";if((type==="review"||type==="test")&&merged.some((entry2)=>entry2.type===type))continue;let entry=gateEvidenceToEntry(taskId,gate,type,evidence2);if(entry)merged.push(entry)}return merged}var GATE_EVIDENCE_TYPE_BY_GATE;var init_gate_bridge=__esm(()=>{init_gate_evidence();GATE_EVIDENCE_TYPE_BY_GATE={reviewer:"review",test_engineer:"test"}});function renderRecoveryInvocationQuickForms(docPath="docs/troubleshooting/recovery-runbook.md"){let labels={host:"host command path",powershell:"PowerShell headless","git-bash":"Git Bash (MSYS) headless",cli:"shell-neutral CLI"},notes={host:"",powershell:"","git-bash":" (leading slash doubled — MSYS rewrites a single leading slash; never set MSYS_NO_PATHCONV=1 for the whole invocation)",cli:""};return[`Shell-correct invocations (see ${docPath}):`,...RECOVERY_INVOCATIONS.map((form)=>`- ${labels[form.surface]}: ${form.invocation}${notes[form.surface]}`)].join(`
|
|
2632
|
-
`)}var RECOVERY_INVOCATIONS;var init_recovery_invocation=__esm(()=>{RECOVERY_INVOCATIONS=[{surface:"host",invocation:"/swarm recover <task_id>",note:"Host command path — type it verbatim in the OpenCode TUI/GUI command line."},{surface:"powershell",invocation:"opencode run --dir <project-dir> '/swarm recover <task_id>'",note:"PowerShell headless — single quotes keep the /swarm message argument literal."},{surface:"git-bash",invocation:'opencode run --dir <project-dir> "//swarm recover <task_id>"',note:"Git Bash (MSYS) headless — the leading slash is doubled because MSYS rewrites a single leading-slash argument to C:/Program Files/Git/swarm …; do NOT set MSYS_NO_PATHCONV=1 globally (it breaks --dir /c/... conversion)."},{surface:"cli",invocation:"bunx opencode-swarm run recover <task_id> [--force]",note:"Shell-neutral CLI — same command in every shell; --force is an operator assertion that no dispatch is genuinely in flight."}]});function applySessionWorkflowView(session,taskId,workflow){session.taskWorkflowStates.set(taskId,workflow.state),session.stageBCompletion?.delete(taskId),session.taskCouncilApproved?.delete(taskId),session.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(session,taskId,workflow)}function isStageARecoveredState(state2){return STAGE_A_RECOVERED_STATES.includes(state2)}function shouldRefreshStageARecoveryView(view,recoveredState){if(view===void 0)return!0;if(view==="rework_required"||view==="blocked")return!0;if(view==="tests_run"||view==="closed"||view==="complete")return!1;return compareTaskWorkflowStateRank(recoveredState,view)>0}var STAGE_A_RECOVERED_STATES;var init_session_view=__esm(()=>{init_gate_evidence();init_state();STAGE_A_RECOVERED_STATES=["pre_check_passed","reviewer_run","tests_run"]});function identitySuffix(status2){let parts=[];if(status2.transitionId)parts.push(`transition ${sanitizeDiagnosticText(status2.transitionId)}`);if(typeof status2.generation==="number")parts.push(`generation ${status2.generation}`);return parts.length>0?` (${parts.join(", ")})`:""}function classifySettlementWalState(entry,workflow){let base={taskId:entry.taskId,transitionId:entry.transitionId,generation:entry.expectedGeneration??(workflow?.authoritative?workflow.generation:void 0)};if(entry.state==="unreadable")return{...base,category:"corrupt",repairAllowed:!1,uncertainExternalEffect:!0,explanation:"settlement WAL is corrupt (unreadable bytes) — recovery refuses corrupt facts instead of rewriting them; the task stays blocked until a human reconciles the file",suggestedNextCommand:"inspect .swarm/coder-settlements/"+entry.taskId+".json and consult docs/troubleshooting/recovery-runbook.md — do not delete or hand-edit the file"};if(entry.ownedByLiveForeignPid)return{...base,category:"ambiguous",repairAllowed:!1,uncertainExternalEffect:!0,explanation:`owned by live foreign process pid ${entry.processId??"?"} (another OpenCode instance) — the dispatch may genuinely be in flight, so this host never interrupts it and the external effect stays uncertain`,suggestedNextCommand:`close that instance (or run /swarm recover ${entry.taskId} there), then re-run diagnose here`};if(entry.ownedInProcess)return{...base,category:"ambiguous",repairAllowed:!1,uncertainExternalEffect:!0,explanation:"in flight, in this process — the dispatch may still complete on its own; releasing it is an operator assertion, not a status claim",suggestedNextCommand:`wait for the dispatch to settle, or re-run /swarm recover ${entry.taskId} --force only if no coder is genuinely running`};if(entry.state==="DISPATCHED"||entry.state==="PREPARED"){let generationConflict=typeof entry.expectedGeneration==="number"&&workflow!==null&&workflow.authoritative&&workflow.generation!==entry.expectedGeneration;return{...base,category:"stale",repairAllowed:!0,uncertainExternalEffect:!1,explanation:`${entry.state.toLowerCase()} settlement whose owning process is gone${generationConflict?` — the WAL's generation fence (${entry.expectedGeneration}) no longer matches the workflow generation (${workflow?.generation}), so the stale receipt cannot be consumed by a normal settle and recovery is the only deterministic path`:""} — blocks dispatches with CODER_DISPATCH_IN_PROGRESS`,suggestedNextCommand:`/swarm recover ${entry.taskId}`}}return{...base,category:"healthy",repairAllowed:!1,uncertainExternalEffect:!1,explanation:`settlement ${entry.state.toLowerCase()}`,suggestedNextCommand:""}}function classifyEvidenceRecoveryTask(taskId,evidence2,greenPreCheck,options){let snapshot=evidence2?.workflow!==void 0&&evidence2.workflow!==null?{...evidence2.workflow,authoritative:!0}:null;if(snapshot===null)return{taskId,category:"missing",repairAllowed:!1,uncertainExternalEffect:!1,explanation:"no durable receipt exists for this task (no settlement WAL, no evidence workflow) — nothing to repair",suggestedNextCommand:"dispatch the task normally, then re-run diagnose; if it was dispatched, see docs/troubleshooting/recovery-runbook.md"};let base={taskId,transitionId:snapshot.lastTransitionId??void 0,generation:snapshot.generation};if(snapshot.state==="coder_delegated"){if(evidence2?.gates?.pre_check===void 0)return{...base,category:"live_wedge",repairAllowed:greenPreCheck===!0,uncertainExternalEffect:!1,explanation:`live-shaped task wedge — workflow at coder_delegated with no pre_check gate proof${greenPreCheck===!0?" and green post-settlement pre-check bundles: the missing Stage A receipt is deterministically repairable without re-running the coder or editing evidence":greenPreCheck===!1?" but pre-check proof is missing or not green: run pre_check_batch first — the repair refuses to mark Stage A passed without proof":""}`,suggestedNextCommand:`/swarm recover ${taskId}`}}if(options?.settlementCommittedAccepted===!0&&(snapshot.state==="idle"||snapshot.state==="blocked"))return{...base,category:"settlement_wedge",repairAllowed:greenPreCheck===!0,uncertainExternalEffect:!1,explanation:`settlement-backed task wedge — workflow at ${snapshot.state} while a COMMITTED accepted coder settlement still justifies Stage A for generation ${snapshot.generation}${greenPreCheck===!0?" and green post-settlement pre-check bundles exist: the missing Stage A record is deterministically repairable without re-running the coder or editing evidence":greenPreCheck===!1?" but pre-check proof is missing or not green: run pre_check_batch first — the repair refuses to mark Stage A passed without proof":""}`,suggestedNextCommand:`/swarm recover ${taskId}`};return{...base,category:"healthy",repairAllowed:!1,uncertainExternalEffect:!1,explanation:`workflow ${snapshot.state}`,suggestedNextCommand:""}}function renderTaskRecoveryLine(status2){if(status2.category==="healthy")return"";let suffix=identitySuffix(status2),command=status2.suggestedNextCommand?` — ${status2.suggestedNextCommand}`:"";return`task ${status2.taskId} [${status2.category}] ${status2.explanation}${suffix}${command}`}var init_task_recovery_status=__esm(()=>{init_path_identity()});import{readdir as readdir11}from"node:fs/promises";async function appendStageARepairEvent(directory,payload){try{return appendCoreEventSync(directory,{type:"stage_a_repair",timestamp:new Date().toISOString(),...payload}),!0}catch(error93){return criticalWarn(`[stage-a-repair] audit event write failed: ${error93 instanceof Error?error93.message:String(error93)}`),!1}}async function hasGreenPostSettlementPreCheck(directory,settledAfterMs){let sawSecretscanGreen=!1,sawSastGreen=!1;for(let evidenceType of["secretscan","sast_scan"]){let result;try{result=await loadEvidence(directory,evidenceType,{migrate:!1})}catch{continue}if(result.status!=="found")continue;let entryTypeTag=evidenceType==="sast_scan"?"sast":evidenceType,typed=result.bundle.entries.filter((entry)=>entry.type===entryTypeTag);if(typed.length===0)continue;let last=typed[typed.length-1],ts=Date.parse(String(last.timestamp??""));if(settledAfterMs!==null&&Number.isFinite(ts)&&ts<settledAfterMs)return{green:!1,reason:"pre_check_failed_or_stale"};if(evidenceType==="secretscan"){if((last.verdict==="pass"||last.verdict==="approved"||last.verdict==="info")&&isSecretscanEvidence(last)){let{policy_skipped_files:policySkipped,requested_files:requestedFiles}=last,vacuousCoverage=(last.files_scanned??0)===0&&typeof policySkipped==="number"&&Number.isSafeInteger(policySkipped)&&policySkipped>=0&&typeof requestedFiles==="number"&&Number.isSafeInteger(requestedFiles)&&requestedFiles>0&&policySkipped>=requestedFiles&&(last.findings_count??0)===0&&(last.incomplete_files??0)===0&&last.incomplete_paths.length===0;if((last.incomplete_files??0)===0&&((last.files_scanned??0)>0||vacuousCoverage)&&(last.findings_count??0)===0){sawSecretscanGreen=!0;continue}}}else if(last.verdict==="pass"||last.verdict==="approved"||last.verdict==="info"){sawSastGreen=!0;continue}if(last.verdict==="fail"||last.verdict==="rejected")return{green:!1,reason:"pre_check_failed_or_stale"}}if(!sawSecretscanGreen||!sawSastGreen)return{green:!1,reason:"no_pre_check_bundles"};return{green:!0}}async function enumerateStageACandidates(directory,requested){let entries2;try{let evidenceDir=validateSwarmPath(directory,"evidence");entries2=await readdir11(evidenceDir)}catch{return{selected:[],truncated:!1}}let candidates=entries2.filter((entry)=>entry.endsWith(".json")&&isStrictTaskId(entry.slice(0,-5))),selected=requested?.length?candidates.filter((entry)=>requested.includes(entry.slice(0,-5))):candidates,truncated=!requested?.length&&candidates.length>MAX_STAGE_A_REPAIR_SCAN;return{selected:selected.sort().slice(0,MAX_STAGE_A_REPAIR_SCAN).map((entry)=>entry.slice(0,-5)),truncated}}function latestCommittedAcceptedSettlementMs(taskId,walStates){let latest=null;for(let state2 of walStates){if(state2.taskId!==taskId)continue;if(state2.state!=="COMMITTED")continue;if(state2.accepted!==!0)continue;if(state2.recordedAt===void 0)continue;let parsed=Date.parse(state2.recordedAt);if(!Number.isFinite(parsed))continue;latest=latest===null?parsed:Math.max(latest,parsed)}return latest}async function scanStageATask(directory,taskId,walStates){let evidence2=await readTaskEvidence(directory,taskId),workflow=getTaskWorkflowSnapshot(evidence2);if(workflow.state==="coder_delegated"){if(!evidence2?.gates?.pre_check){let greenness=await hasGreenPostSettlementPreCheck(directory,liveWedgeSettledAfterMs(taskId,workflow,walStates));if(!greenness.green)return{kind:"not_green",reason:greenness.reason,evidence:evidence2};return{kind:"repairable",mode:"live_wedge",generation:workflow.generation,green:!0,predecessorTransitionId:workflow.lastTransitionId??null,evidence:evidence2}}return{kind:"not_wedged",state:workflow.state,evidence:evidence2}}if(workflow.state==="idle"||workflow.state==="blocked"){let settledAfterMs=latestCommittedAcceptedSettlementMs(taskId,walStates);if(settledAfterMs!==null&&(workflow.state==="blocked"||!evidence2?.gates?.pre_check)){let greenness=await hasGreenPostSettlementPreCheck(directory,settledAfterMs);if(!greenness.green)return{kind:"not_green",reason:greenness.reason,evidence:evidence2};return{kind:"repairable",mode:"settlement_wedge",generation:workflow.generation,green:!0,predecessorTransitionId:workflow.lastTransitionId??null,evidence:evidence2}}return{kind:"not_wedged",state:workflow.state,evidence:evidence2}}return{kind:"not_wedged",state:workflow.state,evidence:evidence2}}function liveWedgeSettledAfterMs(taskId,workflow,walStates){let settledAfterMs=null;for(let state2 of walStates){if(state2.taskId!==taskId)continue;if(state2.state!=="COMMITTED")continue;if(state2.recordedAt===void 0)continue;let parsed=Date.parse(state2.recordedAt);if(!Number.isFinite(parsed))continue;settledAfterMs=settledAfterMs===null?parsed:Math.max(settledAfterMs,parsed)}if(settledAfterMs===null){let fallbackTs=Date.parse(workflow.updatedAt);if(Number.isFinite(fallbackTs))settledAfterMs=fallbackTs}return settledAfterMs}async function scanWedgedStageA(directory,options){let{selected,truncated}=await enumerateStageACandidates(directory,options?.taskIds),{states:walStates}=await listCoderSettlementWalStates(directory),results=[];for(let taskId of selected)try{let verdict=await scanStageATask(directory,taskId,walStates);if(verdict.kind==="repairable")results.push(classifyEvidenceRecoveryTask(taskId,verdict.evidence,verdict.green,{settlementCommittedAccepted:verdict.mode==="settlement_wedge"}));else if(verdict.kind==="not_green")results.push(classifyEvidenceRecoveryTask(taskId,verdict.evidence,!1,{settlementCommittedAccepted:verdict.evidence!==null&&["idle","blocked"].includes(getTaskWorkflowSnapshot(verdict.evidence).state)&&latestCommittedAcceptedSettlementMs(taskId,walStates)!==null}));else results.push(classifyEvidenceRecoveryTask(taskId,verdict.evidence,null))}catch{}return{results,truncated}}async function repairWedgedStageA(directory,options){let requested=options?.taskIds,refreshSession=options?.sessionId?getAgentSession(options.sessionId):void 0,{selected,truncated}=await enumerateStageACandidates(directory,requested),{states:walStates}=await listCoderSettlementWalStates(directory),results=[];for(let taskId of selected)try{let scan=await scanStageATask(directory,taskId,walStates);if(scan.kind==="not_wedged"){if(refreshSession&&isStageARecoveredState(scan.state)){let snapshot=getTaskWorkflowSnapshot(await readTaskEvidence(directory,taskId));if(snapshot.authoritative&&isStageARecoveredState(snapshot.state)&&shouldRefreshStageARecoveryView(refreshSession.taskWorkflowStates.get(taskId),snapshot.state))applySessionWorkflowView(refreshSession,taskId,snapshot)}results.push({taskId,outcome:"skipped_not_wedged",state:scan.state});continue}if(scan.kind==="not_green"){results.push({taskId,outcome:"skipped_not_green",reason:scan.reason});continue}let transitionId=`stage-a-repair:${taskId}:${scan.generation}`,{evidence:updatedEvidence,duplicated}=await transitionTaskWorkflowEvidenceWithStatus(directory,taskId,{type:"stage_a_passed",...scan.mode==="settlement_wedge"?{settlementRecovery:!0}:{},expectedGeneration:scan.generation,transitionId});if(refreshSession){let snapshot=getTaskWorkflowSnapshot(updatedEvidence);if(isStageARecoveredState(snapshot.state)&&shouldRefreshStageARecoveryView(refreshSession.taskWorkflowStates.get(taskId),snapshot.state))applySessionWorkflowView(refreshSession,taskId,snapshot)}if(!duplicated)await appendStageARepairEvent(directory,{action:"repaired",taskId,transitionId,generation:scan.generation,...scan.mode==="settlement_wedge"?{settlementRecovery:!0}:{},via:"swarm-recover",predecessorTransitionId:scan.predecessorTransitionId});results.push({taskId,outcome:"repaired",generation:scan.generation,transitionId})}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);await appendStageARepairEvent(directory,{action:"repair-failed",taskId,message:sanitizeDiagnosticText(message,512)}),results.push({taskId,outcome:"error",message})}return{results,truncated}}var MAX_STAGE_A_REPAIR_SCAN=200;var init_stage_a_repair=__esm(()=>{init_core_events();init_manager2();init_gate_evidence();init_utils2();init_path_identity();init_state();init_logger();init_task_id();init_coder_settlement();init_session_view();init_task_recovery_status()});import{existsSync as existsSync91,mkdirSync as mkdirSync59,readFileSync as readFileSync67,writeFileSync as writeFileSync32}from"node:fs";import{homedir as homedir14}from"node:os";import{join as join136}from"node:path";function isStrictSemver(value){return typeof value==="string"&&STRICT_SEMVER.test(value)}function cacheDir(){let xdg=process.env.XDG_CACHE_HOME,base=xdg&&xdg.length>0?xdg:join136(homedir14(),".cache");return join136(base,"opencode-swarm")}function cacheFile(){return join136(cacheDir(),"version-check.json")}function readVersionCache(){try{let path187=cacheFile();if(!existsSync91(path187))return null;let raw=readFileSync67(path187,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed?.checkedAt!=="number")return null;let npmLatest=typeof parsed.npmLatest==="string"?parsed.npmLatest:null;return{checkedAt:parsed.checkedAt,npmLatest}}catch{return null}}function writeVersionCache(entry){try{let dir=cacheDir();mkdirSync59(dir,{recursive:!0}),writeFileSync32(cacheFile(),JSON.stringify(entry,null,2),"utf-8")}catch{}}function parseVersion(version3){let trimmed=version3.trim(),match=SEMVER_REGEX.exec(trimmed);if(!match)return null;return{major:Number.parseInt(match[1],10),minor:Number.parseInt(match[2],10),patch:Number.parseInt(match[3],10),prerelease:match[4]??null}}function normalizeVersionCandidate(version3){if(typeof version3!=="string")return null;let trimmed=version3.trim();return SEMVER_REGEX.test(trimmed)?trimmed:null}function compareVersions(a,b){let aParsed=parseVersion(a),bParsed=parseVersion(b);if(!aParsed||!bParsed)return 0;if(aParsed.major!==bParsed.major)return aParsed.major>bParsed.major?1:-1;if(aParsed.minor!==bParsed.minor)return aParsed.minor>bParsed.minor?1:-1;if(aParsed.patch!==bParsed.patch)return aParsed.patch>bParsed.patch?1:-1;if(aParsed.prerelease&&!bParsed.prerelease)return-1;if(!aParsed.prerelease&&bParsed.prerelease)return 1;if(aParsed.prerelease&&bParsed.prerelease)return aParsed.prerelease<bParsed.prerelease?-1:aParsed.prerelease>bParsed.prerelease?1:0;return 0}async function fetchLatestVersion(signal){try{let res=await _internals154.fetch(NPM_REGISTRY_URL,{signal,headers:{Accept:"application/json"}});if(!res.ok)return null;if(!(res.headers.get("content-type")??"").toLowerCase().includes("json"))return null;let lengthHeader=res.headers.get("content-length");if(lengthHeader){let advertised=Number.parseInt(lengthHeader,10);if(Number.isFinite(advertised)&&advertised>MAX_RESPONSE_BYTES2)return null}let text=await res.text();if(text.length>MAX_RESPONSE_BYTES2)return null;let body;try{body=JSON.parse(text)}catch{return null}return isStrictSemver(body.version)?body.version:null}catch{return null}}function scheduleVersionCheck(runningVersion,emitWarning,options){if(_checkLatched)return;_checkLatched=!0;let now2=options?.now??(()=>Date.now()),fetchImpl=options?.fetchImpl??fetchLatestVersion;queueMicrotask(()=>{runVersionCheck(runningVersion,emitWarning,now2,fetchImpl).catch(()=>{})})}async function runVersionCheck(runningVersion,emitWarning,now2,fetchImpl){let cached3=readVersionCache(),t=now2();if(cached3&&t-cached3.checkedAt<CHECK_INTERVAL_MS){if(cached3.npmLatest)maybeWarn(runningVersion,cached3.npmLatest,emitWarning);return}let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),FETCH_TIMEOUT_MS),npmLatest=null;try{let fetchedVersion=await fetchImpl(controller.signal);npmLatest=normalizeVersionCandidate(fetchedVersion)}finally{clearTimeout(timeout)}if(writeVersionCache({checkedAt:t,npmLatest}),npmLatest)maybeWarn(runningVersion,npmLatest,emitWarning)}function maybeWarn(runningVersion,npmLatest,emitWarning){if(compareVersions(npmLatest,runningVersion)>0)emitWarning(`[opencode-swarm] Update available: ${runningVersion} → ${npmLatest}. OpenCode caches plugins indefinitely. Run \`bunx opencode-swarm update\` to refresh. Also run \`/swarm config doctor\` to check for available config migrations.`)}var NPM_REGISTRY_URL="https://registry.npmjs.org/opencode-swarm/latest",CHECK_INTERVAL_MS=86400000,FETCH_TIMEOUT_MS=5000,SEMVER_REGEX,MAX_RESPONSE_BYTES2=262144,STRICT_SEMVER,_checkLatched=!1,_internals154;var init_version_check=__esm(()=>{SEMVER_REGEX=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/,STRICT_SEMVER=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;_internals154={fetch:(input,init)=>fetch(input,init)}});import{existsSync as existsSync92,readFileSync as readFileSync68}from"node:fs";import{readFile as readFile40}from"node:fs/promises";import{join as join137}from"node:path";async function readRawLines(filePath){if(!existsSync92(filePath))return{entries:[],corrupt:0};let content=await readFile40(filePath,"utf-8"),entries2=[],corrupt=0;for(let line of content.split(`
|
|
2632
|
+
`)}var RECOVERY_INVOCATIONS;var init_recovery_invocation=__esm(()=>{RECOVERY_INVOCATIONS=[{surface:"host",invocation:"/swarm recover <task_id>",note:"Host command path — type it verbatim in the OpenCode TUI/GUI command line."},{surface:"powershell",invocation:"opencode run --dir <project-dir> '/swarm recover <task_id>'",note:"PowerShell headless — single quotes keep the /swarm message argument literal."},{surface:"git-bash",invocation:'opencode run --dir <project-dir> "//swarm recover <task_id>"',note:"Git Bash (MSYS) headless — the leading slash is doubled because MSYS rewrites a single leading-slash argument to C:/Program Files/Git/swarm …; do NOT set MSYS_NO_PATHCONV=1 globally (it breaks --dir /c/... conversion)."},{surface:"cli",invocation:"bunx opencode-swarm run recover <task_id> [--force]",note:"Shell-neutral CLI — same command in every shell; --force is an operator assertion that no dispatch is genuinely in flight."}]});function applySessionWorkflowView(session,taskId,workflow){session.taskWorkflowStates.set(taskId,workflow.state),session.stageBCompletion?.delete(taskId),session.taskCouncilApproved?.delete(taskId),session.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(session,taskId,workflow)}function isStageARecoveredState(state2){return STAGE_A_RECOVERED_STATES.includes(state2)}function shouldRefreshStageARecoveryView(view,recoveredState){if(view===void 0)return!0;if(view==="rework_required"||view==="blocked")return!0;if(view==="tests_run"||view==="closed"||view==="complete")return!1;return compareTaskWorkflowStateRank(recoveredState,view)>0}var STAGE_A_RECOVERED_STATES;var init_session_view=__esm(()=>{init_gate_evidence();init_state();STAGE_A_RECOVERED_STATES=["pre_check_passed","reviewer_run","tests_run"]});function identitySuffix(status2){let parts=[];if(status2.transitionId)parts.push(`transition ${sanitizeDiagnosticText(status2.transitionId)}`);if(typeof status2.generation==="number")parts.push(`generation ${status2.generation}`);return parts.length>0?` (${parts.join(", ")})`:""}function classifySettlementWalState(entry,workflow){let base={taskId:entry.taskId,transitionId:entry.transitionId,generation:entry.expectedGeneration??(workflow?.authoritative?workflow.generation:void 0)};if(entry.state==="unreadable")return{...base,category:"corrupt",repairAllowed:!1,uncertainExternalEffect:!0,explanation:"settlement WAL is corrupt (unreadable bytes) — recovery refuses corrupt facts instead of rewriting them; the task stays blocked until a human reconciles the file",suggestedNextCommand:"inspect .swarm/coder-settlements/"+entry.taskId+".json and consult docs/troubleshooting/recovery-runbook.md — do not delete or hand-edit the file"};if(entry.ownedByLiveForeignPid)return{...base,category:"ambiguous",repairAllowed:!1,uncertainExternalEffect:!0,explanation:`owned by live foreign process pid ${entry.processId??"?"} (another OpenCode instance) — the dispatch may genuinely be in flight, so this host never interrupts it and the external effect stays uncertain`,suggestedNextCommand:`close that instance (or run /swarm recover ${entry.taskId} there), then re-run diagnose here`};if(entry.ownedInProcess)return{...base,category:"ambiguous",repairAllowed:!1,uncertainExternalEffect:!0,explanation:"in flight, in this process — the dispatch may still complete on its own; releasing it is an operator assertion, not a status claim",suggestedNextCommand:`wait for the dispatch to settle, or re-run /swarm recover ${entry.taskId} --force only if no coder is genuinely running`};if(entry.state==="DISPATCHED"||entry.state==="PREPARED"){let generationConflict=typeof entry.expectedGeneration==="number"&&workflow!==null&&workflow.authoritative&&workflow.generation!==entry.expectedGeneration;return{...base,category:"stale",repairAllowed:!0,uncertainExternalEffect:!1,explanation:`${entry.state.toLowerCase()} settlement whose owning process is gone${generationConflict?` — the WAL's generation fence (${entry.expectedGeneration}) no longer matches the workflow generation (${workflow?.generation}), so the stale receipt cannot be consumed by a normal settle and recovery is the only deterministic path`:""} — blocks dispatches with CODER_DISPATCH_IN_PROGRESS`,suggestedNextCommand:`/swarm recover ${entry.taskId}`}}return{...base,category:"healthy",repairAllowed:!1,uncertainExternalEffect:!1,explanation:`settlement ${entry.state.toLowerCase()}`,suggestedNextCommand:""}}function classifyEvidenceRecoveryTask(taskId,evidence2,greenPreCheck,options){let snapshot=evidence2?.workflow!==void 0&&evidence2.workflow!==null?{...evidence2.workflow,authoritative:!0}:null;if(snapshot===null)return{taskId,category:"missing",repairAllowed:!1,uncertainExternalEffect:!1,explanation:"no durable receipt exists for this task (no settlement WAL, no evidence workflow) — nothing to repair",suggestedNextCommand:"dispatch the task normally, then re-run diagnose; if it was dispatched, see docs/troubleshooting/recovery-runbook.md"};let base={taskId,transitionId:snapshot.lastTransitionId??void 0,generation:snapshot.generation};if(snapshot.state==="coder_delegated"){if(evidence2?.gates?.pre_check===void 0)return{...base,category:"live_wedge",repairAllowed:greenPreCheck===!0,uncertainExternalEffect:!1,explanation:`live-shaped task wedge — workflow at coder_delegated with no pre_check gate proof${greenPreCheck===!0?" and green post-settlement pre-check bundles: the missing Stage A receipt is deterministically repairable without re-running the coder or editing evidence":greenPreCheck===!1?" but pre-check proof is missing or not green: run pre_check_batch first — the repair refuses to mark Stage A passed without proof":""}`,suggestedNextCommand:`/swarm recover ${taskId}`}}if(options?.settlementCommittedAccepted===!0&&(snapshot.state==="idle"||snapshot.state==="blocked"))return{...base,category:"settlement_wedge",repairAllowed:greenPreCheck===!0,uncertainExternalEffect:!1,explanation:`settlement-backed task wedge — workflow at ${snapshot.state} while a COMMITTED accepted coder settlement still justifies Stage A for generation ${snapshot.generation}${greenPreCheck===!0?" and green post-settlement pre-check bundles exist: the missing Stage A record is deterministically repairable without re-running the coder or editing evidence":greenPreCheck===!1?" but pre-check proof is missing or not green: run pre_check_batch first — the repair refuses to mark Stage A passed without proof":""}`,suggestedNextCommand:`/swarm recover ${taskId}`};return{...base,category:"healthy",repairAllowed:!1,uncertainExternalEffect:!1,explanation:`workflow ${snapshot.state}`,suggestedNextCommand:""}}function renderTaskRecoveryLine(status2){if(status2.category==="healthy")return"";let suffix=identitySuffix(status2),command=status2.suggestedNextCommand?` — ${status2.suggestedNextCommand}`:"";return`task ${status2.taskId} [${status2.category}] ${status2.explanation}${suffix}${command}`}var init_task_recovery_status=__esm(()=>{init_path_identity()});import{readdir as readdir11}from"node:fs/promises";async function appendStageARepairEvent(directory,payload){try{return appendCoreEventSync(directory,{type:"stage_a_repair",timestamp:new Date().toISOString(),...payload}),!0}catch(error93){return criticalWarn(`[stage-a-repair] audit event write failed: ${error93 instanceof Error?error93.message:String(error93)}`),!1}}async function hasGreenPostSettlementPreCheck(directory,settledAfterMs){let sawSecretscanGreen=!1,sawSastGreen=!1;for(let evidenceType of["secretscan","sast_scan"]){let result;try{result=await loadEvidence(directory,evidenceType,{migrate:!1})}catch{continue}if(result.status!=="found")continue;let entryTypeTag=evidenceType==="sast_scan"?"sast":evidenceType,typed=result.bundle.entries.filter((entry)=>entry.type===entryTypeTag);if(typed.length===0)continue;let last=typed[typed.length-1],ts=Date.parse(String(last.timestamp??""));if(settledAfterMs!==null&&Number.isFinite(ts)&&ts<settledAfterMs)return{green:!1,reason:"pre_check_failed_or_stale"};if(evidenceType==="secretscan"){if((last.verdict==="pass"||last.verdict==="approved"||last.verdict==="info")&&isSecretscanEvidence(last)){let{policy_skipped_files:policySkipped,requested_files:requestedFiles}=last,vacuousCoverage=(last.files_scanned??0)===0&&typeof policySkipped==="number"&&Number.isSafeInteger(policySkipped)&&policySkipped>=0&&typeof requestedFiles==="number"&&Number.isSafeInteger(requestedFiles)&&requestedFiles>0&&policySkipped>=requestedFiles&&(last.findings_count??0)===0&&(last.incomplete_files??0)===0&&last.incomplete_paths.length===0;if((last.incomplete_files??0)===0&&(last.incomplete_paths?.length??0)===0&&((last.files_scanned??0)>0||vacuousCoverage)&&(()=>{let total=last.findings_count??0,newFindingsRaw=last.new_findings_count,preexistingRaw=last.preexisting_findings_count;if(!(typeof newFindingsRaw==="number"&&Number.isSafeInteger(newFindingsRaw)&&newFindingsRaw>=0))return total===0;if(typeof preexistingRaw==="number"&&Number.isSafeInteger(preexistingRaw)&&preexistingRaw>=0&&newFindingsRaw+preexistingRaw!==total)return total===0;return newFindingsRaw===0})()){sawSecretscanGreen=!0;continue}}}else if(last.verdict==="pass"||last.verdict==="approved"||last.verdict==="info"){sawSastGreen=!0;continue}if(last.verdict==="fail"||last.verdict==="rejected")return{green:!1,reason:"pre_check_failed_or_stale"}}if(!sawSecretscanGreen||!sawSastGreen)return{green:!1,reason:"no_pre_check_bundles"};return{green:!0}}async function enumerateStageACandidates(directory,requested){let entries2;try{let evidenceDir=validateSwarmPath(directory,"evidence");entries2=await readdir11(evidenceDir)}catch{return{selected:[],truncated:!1}}let candidates=entries2.filter((entry)=>entry.endsWith(".json")&&isStrictTaskId(entry.slice(0,-5))),selected=requested?.length?candidates.filter((entry)=>requested.includes(entry.slice(0,-5))):candidates,truncated=!requested?.length&&candidates.length>MAX_STAGE_A_REPAIR_SCAN;return{selected:selected.sort().slice(0,MAX_STAGE_A_REPAIR_SCAN).map((entry)=>entry.slice(0,-5)),truncated}}function latestCommittedAcceptedSettlementMs(taskId,walStates){let latest=null;for(let state2 of walStates){if(state2.taskId!==taskId)continue;if(state2.state!=="COMMITTED")continue;if(state2.accepted!==!0)continue;if(state2.recordedAt===void 0)continue;let parsed=Date.parse(state2.recordedAt);if(!Number.isFinite(parsed))continue;latest=latest===null?parsed:Math.max(latest,parsed)}return latest}async function scanStageATask(directory,taskId,walStates){let evidence2=await readTaskEvidence(directory,taskId),workflow=getTaskWorkflowSnapshot(evidence2);if(workflow.state==="coder_delegated"){if(!evidence2?.gates?.pre_check){let greenness=await hasGreenPostSettlementPreCheck(directory,liveWedgeSettledAfterMs(taskId,workflow,walStates));if(!greenness.green)return{kind:"not_green",reason:greenness.reason,evidence:evidence2};return{kind:"repairable",mode:"live_wedge",generation:workflow.generation,green:!0,predecessorTransitionId:workflow.lastTransitionId??null,evidence:evidence2}}return{kind:"not_wedged",state:workflow.state,evidence:evidence2}}if(workflow.state==="idle"||workflow.state==="blocked"){let settledAfterMs=latestCommittedAcceptedSettlementMs(taskId,walStates);if(settledAfterMs!==null&&(workflow.state==="blocked"||!evidence2?.gates?.pre_check)){let greenness=await hasGreenPostSettlementPreCheck(directory,settledAfterMs);if(!greenness.green)return{kind:"not_green",reason:greenness.reason,evidence:evidence2};return{kind:"repairable",mode:"settlement_wedge",generation:workflow.generation,green:!0,predecessorTransitionId:workflow.lastTransitionId??null,evidence:evidence2}}return{kind:"not_wedged",state:workflow.state,evidence:evidence2}}return{kind:"not_wedged",state:workflow.state,evidence:evidence2}}function liveWedgeSettledAfterMs(taskId,workflow,walStates){let settledAfterMs=null;for(let state2 of walStates){if(state2.taskId!==taskId)continue;if(state2.state!=="COMMITTED")continue;if(state2.recordedAt===void 0)continue;let parsed=Date.parse(state2.recordedAt);if(!Number.isFinite(parsed))continue;settledAfterMs=settledAfterMs===null?parsed:Math.max(settledAfterMs,parsed)}if(settledAfterMs===null){let fallbackTs=Date.parse(workflow.updatedAt);if(Number.isFinite(fallbackTs))settledAfterMs=fallbackTs}return settledAfterMs}async function scanWedgedStageA(directory,options){let{selected,truncated}=await enumerateStageACandidates(directory,options?.taskIds),{states:walStates}=await listCoderSettlementWalStates(directory),results=[];for(let taskId of selected)try{let verdict=await scanStageATask(directory,taskId,walStates);if(verdict.kind==="repairable")results.push(classifyEvidenceRecoveryTask(taskId,verdict.evidence,verdict.green,{settlementCommittedAccepted:verdict.mode==="settlement_wedge"}));else if(verdict.kind==="not_green")results.push(classifyEvidenceRecoveryTask(taskId,verdict.evidence,!1,{settlementCommittedAccepted:verdict.evidence!==null&&["idle","blocked"].includes(getTaskWorkflowSnapshot(verdict.evidence).state)&&latestCommittedAcceptedSettlementMs(taskId,walStates)!==null}));else results.push(classifyEvidenceRecoveryTask(taskId,verdict.evidence,null))}catch{}return{results,truncated}}async function repairWedgedStageA(directory,options){let requested=options?.taskIds,refreshSession=options?.sessionId?getAgentSession(options.sessionId):void 0,{selected,truncated}=await enumerateStageACandidates(directory,requested),{states:walStates}=await listCoderSettlementWalStates(directory),results=[];for(let taskId of selected)try{let scan=await scanStageATask(directory,taskId,walStates);if(scan.kind==="not_wedged"){if(refreshSession&&isStageARecoveredState(scan.state)){let snapshot=getTaskWorkflowSnapshot(await readTaskEvidence(directory,taskId));if(snapshot.authoritative&&isStageARecoveredState(snapshot.state)&&shouldRefreshStageARecoveryView(refreshSession.taskWorkflowStates.get(taskId),snapshot.state))applySessionWorkflowView(refreshSession,taskId,snapshot)}results.push({taskId,outcome:"skipped_not_wedged",state:scan.state});continue}if(scan.kind==="not_green"){results.push({taskId,outcome:"skipped_not_green",reason:scan.reason});continue}let transitionId=`stage-a-repair:${taskId}:${scan.generation}`,{evidence:updatedEvidence,duplicated}=await transitionTaskWorkflowEvidenceWithStatus(directory,taskId,{type:"stage_a_passed",...scan.mode==="settlement_wedge"?{settlementRecovery:!0}:{},expectedGeneration:scan.generation,transitionId});if(refreshSession){let snapshot=getTaskWorkflowSnapshot(updatedEvidence);if(isStageARecoveredState(snapshot.state)&&shouldRefreshStageARecoveryView(refreshSession.taskWorkflowStates.get(taskId),snapshot.state))applySessionWorkflowView(refreshSession,taskId,snapshot)}if(!duplicated)await appendStageARepairEvent(directory,{action:"repaired",taskId,transitionId,generation:scan.generation,...scan.mode==="settlement_wedge"?{settlementRecovery:!0}:{},via:"swarm-recover",predecessorTransitionId:scan.predecessorTransitionId});results.push({taskId,outcome:"repaired",generation:scan.generation,transitionId})}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);await appendStageARepairEvent(directory,{action:"repair-failed",taskId,message:sanitizeDiagnosticText(message,512)}),results.push({taskId,outcome:"error",message})}return{results,truncated}}var MAX_STAGE_A_REPAIR_SCAN=200;var init_stage_a_repair=__esm(()=>{init_core_events();init_manager2();init_gate_evidence();init_utils2();init_path_identity();init_state();init_logger();init_task_id();init_coder_settlement();init_session_view();init_task_recovery_status()});import{existsSync as existsSync91,mkdirSync as mkdirSync59,readFileSync as readFileSync67,writeFileSync as writeFileSync32}from"node:fs";import{homedir as homedir14}from"node:os";import{join as join136}from"node:path";function isStrictSemver(value){return typeof value==="string"&&STRICT_SEMVER.test(value)}function cacheDir(){let xdg=process.env.XDG_CACHE_HOME,base=xdg&&xdg.length>0?xdg:join136(homedir14(),".cache");return join136(base,"opencode-swarm")}function cacheFile(){return join136(cacheDir(),"version-check.json")}function readVersionCache(){try{let path187=cacheFile();if(!existsSync91(path187))return null;let raw=readFileSync67(path187,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed?.checkedAt!=="number")return null;let npmLatest=typeof parsed.npmLatest==="string"?parsed.npmLatest:null;return{checkedAt:parsed.checkedAt,npmLatest}}catch{return null}}function writeVersionCache(entry){try{let dir=cacheDir();mkdirSync59(dir,{recursive:!0}),writeFileSync32(cacheFile(),JSON.stringify(entry,null,2),"utf-8")}catch{}}function parseVersion(version3){let trimmed=version3.trim(),match=SEMVER_REGEX.exec(trimmed);if(!match)return null;return{major:Number.parseInt(match[1],10),minor:Number.parseInt(match[2],10),patch:Number.parseInt(match[3],10),prerelease:match[4]??null}}function normalizeVersionCandidate(version3){if(typeof version3!=="string")return null;let trimmed=version3.trim();return SEMVER_REGEX.test(trimmed)?trimmed:null}function compareVersions(a,b){let aParsed=parseVersion(a),bParsed=parseVersion(b);if(!aParsed||!bParsed)return 0;if(aParsed.major!==bParsed.major)return aParsed.major>bParsed.major?1:-1;if(aParsed.minor!==bParsed.minor)return aParsed.minor>bParsed.minor?1:-1;if(aParsed.patch!==bParsed.patch)return aParsed.patch>bParsed.patch?1:-1;if(aParsed.prerelease&&!bParsed.prerelease)return-1;if(!aParsed.prerelease&&bParsed.prerelease)return 1;if(aParsed.prerelease&&bParsed.prerelease)return aParsed.prerelease<bParsed.prerelease?-1:aParsed.prerelease>bParsed.prerelease?1:0;return 0}async function fetchLatestVersion(signal){try{let res=await _internals154.fetch(NPM_REGISTRY_URL,{signal,headers:{Accept:"application/json"}});if(!res.ok)return null;if(!(res.headers.get("content-type")??"").toLowerCase().includes("json"))return null;let lengthHeader=res.headers.get("content-length");if(lengthHeader){let advertised=Number.parseInt(lengthHeader,10);if(Number.isFinite(advertised)&&advertised>MAX_RESPONSE_BYTES2)return null}let text=await res.text();if(text.length>MAX_RESPONSE_BYTES2)return null;let body;try{body=JSON.parse(text)}catch{return null}return isStrictSemver(body.version)?body.version:null}catch{return null}}function scheduleVersionCheck(runningVersion,emitWarning,options){if(_checkLatched)return;_checkLatched=!0;let now2=options?.now??(()=>Date.now()),fetchImpl=options?.fetchImpl??fetchLatestVersion;queueMicrotask(()=>{runVersionCheck(runningVersion,emitWarning,now2,fetchImpl).catch(()=>{})})}async function runVersionCheck(runningVersion,emitWarning,now2,fetchImpl){let cached3=readVersionCache(),t=now2();if(cached3&&t-cached3.checkedAt<CHECK_INTERVAL_MS){if(cached3.npmLatest)maybeWarn(runningVersion,cached3.npmLatest,emitWarning);return}let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),FETCH_TIMEOUT_MS),npmLatest=null;try{let fetchedVersion=await fetchImpl(controller.signal);npmLatest=normalizeVersionCandidate(fetchedVersion)}finally{clearTimeout(timeout)}if(writeVersionCache({checkedAt:t,npmLatest}),npmLatest)maybeWarn(runningVersion,npmLatest,emitWarning)}function maybeWarn(runningVersion,npmLatest,emitWarning){if(compareVersions(npmLatest,runningVersion)>0)emitWarning(`[opencode-swarm] Update available: ${runningVersion} → ${npmLatest}. OpenCode caches plugins indefinitely. Run \`bunx opencode-swarm update\` to refresh. Also run \`/swarm config doctor\` to check for available config migrations.`)}var NPM_REGISTRY_URL="https://registry.npmjs.org/opencode-swarm/latest",CHECK_INTERVAL_MS=86400000,FETCH_TIMEOUT_MS=5000,SEMVER_REGEX,MAX_RESPONSE_BYTES2=262144,STRICT_SEMVER,_checkLatched=!1,_internals154;var init_version_check=__esm(()=>{SEMVER_REGEX=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/,STRICT_SEMVER=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;_internals154={fetch:(input,init)=>fetch(input,init)}});import{existsSync as existsSync92,readFileSync as readFileSync68}from"node:fs";import{readFile as readFile40}from"node:fs/promises";import{join as join137}from"node:path";async function readRawLines(filePath){if(!existsSync92(filePath))return{entries:[],corrupt:0};let content=await readFile40(filePath,"utf-8"),entries2=[],corrupt=0;for(let line of content.split(`
|
|
2633
2633
|
`)){let trimmed=line.trim();if(!trimmed)continue;try{entries2.push(JSON.parse(trimmed))}catch{corrupt++}}return{entries:entries2,corrupt}}function hasV2Counters(entry){let ro=entry.retrieval_outcomes;if(!ro||typeof ro!=="object")return!1;return typeof ro.shown_count==="number"&&typeof ro.applied_explicit_count==="number"&&typeof ro.ignored_count==="number"}function cacheStatus(){let cache3=readVersionCache();if(!cache3?.npmLatest)return"unknown";return compareVersions(cache3.npmLatest,version3)>0?"stale":"fresh"}async function computeKnowledgeDebug(directory){let swarmPath2=resolveSwarmKnowledgePath(directory),hivePath=resolveHiveKnowledgePath2(),eventsPath=resolveKnowledgeEventsPath(directory),[swarmRaw,hiveRaw]=await Promise.all([readRawLines(swarmPath2),readRawLines(hivePath)]),rawEntries=[...swarmRaw.entries,...hiveRaw.entries],corrupt=swarmRaw.corrupt+hiveRaw.corrupt,schemaVersions={},missingV2=0;for(let e of rawEntries){let sv=String(typeof e.schema_version==="number"?e.schema_version:"unknown");if(schemaVersions[sv]=(schemaVersions[sv]??0)+1,!hasV2Counters(e))missingV2++}let normalizedCount=0,active=0,archived=0,quarantined=0,enforcedDirectives=0,escalatedDirectives=0;try{let swarm=await readKnowledge(swarmPath2),hive=await readKnowledge(hivePath);for(let e of[...swarm,...hive]){if(normalizedCount++,e.status==="archived")archived++;else if(e.status==="quarantined")quarantined++;else active++;if(e.status!=="archived"&&e.status!=="quarantined"){if(e.enforcement_mode==="enforce")enforcedDirectives++;if(Array.isArray(e.escalation_history)&&e.escalation_history.length>0)escalatedDirectives++}}}catch{}let rejected2=0;try{rejected2=(await readRejectedLessons(directory)).length}catch{}let eventCount=0,retrieval7d=0,eventsByType={};try{let events=await readKnowledgeEvents(directory);eventCount=events.length;let cutoff=Date.now()-SEVEN_DAYS_MS2;for(let ev of events){if(eventsByType[ev.type]=(eventsByType[ev.type]??0)+1,ev.type!=="retrieved")continue;let t=Date.parse(ev.timestamp);if(!Number.isNaN(t)&&t>=cutoff)retrieval7d++}}catch{}let unactionableQueueDepth=await safeJsonlCount(resolveUnactionablePathSafe(directory)),insightCandidatesPending=await countInsightCandidatesPendingDiagnostic(directory),synonymPairs=0;try{synonymPairs=Object.keys((await readSynonymMap(directory)).pairs).length}catch{}let cohortLinked=!1,cohortPointerVersion=null,cohortLinkId=null,cohortId=null,cohortIdentitySource=null,cohortDegraded=!1,cohortSharedRoot=null,cohortGeneration=null,cohortLocalOrphaned=!1;try{let pointer=readLinkPointer(directory);if(pointer)cohortLinked=!0,cohortPointerVersion=pointer.version,cohortLinkId=pointer.linkId,cohortId=pointer.cohortId??null,cohortIdentitySource=pointer.identitySource??null,cohortDegraded=pointer.degraded??!1,cohortSharedRoot=resolveLinkDir(pointer.linkId),cohortGeneration=pointer.generation??null,cohortLocalOrphaned=getLinkedLocalKnowledgeStatus(directory).orphaned}catch{}let hiveEntriesWithLineage=0,hiveOverridePromotions=0,hiveOverrideEntries=[];try{let hive=await readKnowledge(hivePath);for(let e of hive)if(e.lineage){if(hiveEntriesWithLineage++,e.lineage.actor==="manual-override"){if(hiveOverridePromotions++,hiveOverrideEntries.length<20)hiveOverrideEntries.push({id:e.id,lesson_excerpt:e.lesson.slice(0,80),override_failed_gates:e.lineage.override_failed_gates,reason:e.lineage.reason,promotion_event_id:e.lineage.promotion_event_id})}}}catch{}return{plugin_version:version3,directory,swarm_path:swarmPath2,hive_path:hivePath,events_path:eventsPath,raw_entry_count:rawEntries.length,normalized_entry_count:normalizedCount,corrupt_line_count:corrupt,schema_versions:schemaVersions,entries_missing_v2_counters:missingV2,status_breakdown:{active,archived,quarantined,rejected:rejected2},event_count:eventCount,retrieval_events_7d:retrieval7d,cache_status:cacheStatus(),learning:{unactionable_queue_depth:unactionableQueueDepth,insight_candidates_pending:insightCandidatesPending,synonym_pairs:synonymPairs,enforced_directives:enforcedDirectives,escalated_directives:escalatedDirectives,events_by_type:eventsByType,shown_vs_applied:{shown:eventsByType.retrieved??0,applied_explicit:eventsByType.applied??0,ignored:eventsByType.ignored??0,contradicted:eventsByType.contradicted??0,violated:eventsByType.violated??0,no_relevant:eventsByType.no_relevant??0,unacknowledged:eventsByType.unacknowledged??0}},cohort:{linked:cohortLinked,pointer_version:cohortPointerVersion,link_id:cohortLinkId,cohort_id:cohortId,identity_source:cohortIdentitySource,degraded:cohortDegraded,shared_root:cohortSharedRoot,generation:cohortGeneration,local_orphaned:cohortLocalOrphaned},hive:{entries_with_lineage:hiveEntriesWithLineage,override_promotions:hiveOverridePromotions,override_entries:hiveOverrideEntries},curation:await computeCurationDiagnostics(directory,swarmRaw.entries),memory:computeMemoryCohortDiagnostics(directory)}}function computeMemoryCohortDiagnostics(directory){try{let pointer=readMemoryLinkPointer(directory),provider=null,configFingerprintMatch=null;try{let{loadPluginConfig:loadPluginConfig2}=(init_loader(),__toCommonJS(exports_loader)),cfg=loadPluginConfig2(directory);if(provider=cfg.memory?.provider??null,pointer&&cfg.memory){let cohortConfigPath=join137(resolveLinkDir(pointer.linkId),"memory","memory-cohort-config.json");if(existsSync92(cohortConfigPath)){let stored=JSON.parse(readFileSync68(cohortConfigPath,"utf-8"));if(classifyStoredFingerprintAlgorithmVersion(stored.algorithm_version).status==="comparable"&&typeof stored.fingerprint==="string"){let expected=computeMemoryCohortFingerprint(buildMemoryCohortFingerprintInput({provider:cfg.memory.provider??"sqlite",redaction:{rejectDurableSecrets:cfg.memory.redaction?.rejectDurableSecrets??!0},embeddings:{model:cfg.memory.embeddings?.model??"Xenova/all-MiniLM-L6-v2",dimension:cfg.memory.embeddings?.dimension??384,version:cfg.memory.embeddings?.version}}));configFingerprintMatch=stored.fingerprint===expected}}}}catch{}if(pointer)return{linked:!0,pointer_version:pointer.version,link_id:pointer.linkId,cohort_id:pointer.cohortId??null,identity_source:pointer.identitySource??null,degraded:pointer.degraded??!1,shared_root:pointer.linkId?resolveLinkDir(pointer.linkId):null,generation:pointer.generation??null,provider,config_fingerprint_match:configFingerprintMatch};return{linked:!1,pointer_version:null,link_id:null,cohort_id:null,identity_source:null,degraded:!1,shared_root:null,generation:null,provider,config_fingerprint_match:null}}catch{return{linked:!1,pointer_version:null,link_id:null,cohort_id:null,identity_source:null,degraded:!1,shared_root:null,generation:null,provider:null,config_fingerprint_match:null}}}async function computeCurationDiagnostics(directory,entries2){let scanGeneration=0,scanCompleted=!1,scanRemaining=0;try{let{getScanStatus:getScanStatus2}=await Promise.resolve().then(() => (init_scan_cursor(),exports_scan_cursor)),status2=await getScanStatus2(directory);scanGeneration=status2.generation,scanCompleted=status2.completed,scanRemaining=status2.remaining_estimate}catch{}let configMatch=null;try{let{isLinked:isLinked2}=await Promise.resolve().then(() => (init_knowledge_link(),exports_knowledge_link));if(isLinked2(directory)){let{KnowledgeConfigSchema:KnowledgeConfigSchema2}=await Promise.resolve().then(() => (init_schema(),exports_schema)),config3;try{let{loadPluginConfigWithMeta:loadPluginConfigWithMeta2}=await Promise.resolve().then(() => (init_config2(),exports_config)),loaded=loadPluginConfigWithMeta2(directory);config3=KnowledgeConfigSchema2.parse(loaded.config.knowledge??{})}catch{config3=KnowledgeConfigSchema2.parse({})}let{cohortConfigFingerprint:cohortConfigFingerprint2}=await Promise.resolve().then(() => (init_config_fingerprint(),exports_config_fingerprint)),{buildConfigFingerprintInput:buildConfigFingerprintInput2,readCohortConfigFingerprint:readCohortConfigFingerprint2}=await Promise.resolve().then(() => (init_curation_policy(),exports_curation_policy)),currentFp=cohortConfigFingerprint2(buildConfigFingerprintInput2(config3)),cohortFp=await readCohortConfigFingerprint2(directory);configMatch=cohortFp===null?null:currentFp===cohortFp}}catch{}let withProvenance=0,unknownOwner=0;for(let e of entries2)if(e.producer!=null)withProvenance++;else unknownOwner++;let pendingProposals=await countPendingProposals(directory);return{scan_generation:scanGeneration,scan_completed:scanCompleted,scan_remaining_estimate:scanRemaining,config_fingerprint_match:configMatch,entries_with_provenance:withProvenance,entries_unknown_owner:unknownOwner,pending_proposals:pendingProposals}}async function countPendingProposals(directory){let proposalsPath;try{proposalsPath=join137(resolveKnowledgeStoreDir(directory),"curation-proposals.jsonl")}catch{return 0}if(!existsSync92(proposalsPath))return 0;try{let records=await readTailJsonl(proposalsPath,{maxEntries:resolveRetentionCap("MAX_CURATION_PROPOSALS",MAX_CURATION_PROPOSALS)}),n=0;for(let parsed of records)if(parsed.status==="pending")n++;return n}catch{return 0}}async function safeJsonlCount(filePath){if(!filePath||!existsSync92(filePath))return 0;try{let content=await readFile40(filePath,"utf-8"),n=0;for(let line of content.split(`
|
|
2634
2634
|
`))if(line.trim())n++;return n}catch{return 0}}function resolveUnactionablePathSafe(directory){try{return resolveUnactionablePath(directory)}catch{return null}}function resolveInsightCandidatesPathSafe(directory){try{return resolveInsightCandidatesPath(directory)}catch{return null}}async function countInsightCandidatesPendingDiagnostic(directory){try{if(projectDbExists(directory))return countPendingInsightCandidatesDb(directory);return await safeJsonlCount(resolveInsightCandidatesPathSafe(directory))}catch{return 0}}async function checkKnowledgeHealth(directory){let debug;try{debug=await computeKnowledgeDebug(directory)}catch{return{name:"Knowledge health",status:"⚠️",detail:"Could not compute knowledge diagnostics"}}let{status_breakdown:sb,learning:lr,cohort:co,hive:hv,curation:cu}=debug,cohortTag=co.linked?` | cohort[linked id=${co.link_id}${co.cohort_id?` cohort=${co.cohort_id}`:""}${co.identity_source?` via=${co.identity_source}`:""}${co.degraded?" DEGRADED":""}${co.local_orphaned?" local-orphan":""}${co.generation!==null?` gen=${co.generation}`:""}]`:" | cohort[local]",hiveTag=hv.entries_with_lineage>0||hv.override_promotions>0?` | hive[lineage=${hv.entries_with_lineage} overrides=${hv.override_promotions}]`:" | hive[local]",scanPart=cu.scan_completed?`scan[gen=${cu.scan_generation} complete]`:`scan[gen=${cu.scan_generation} remaining=${cu.scan_remaining_estimate}]`,fpPart=cu.config_fingerprint_match===null?"fp=n/a":cu.config_fingerprint_match?"fp=match":"fp=MISMATCH",provenanceTotal=cu.entries_with_provenance+cu.entries_unknown_owner,curationTag=` | curation[${scanPart} ${fpPart} provenance=${cu.entries_with_provenance}/${provenanceTotal} proposals=${cu.pending_proposals}]`,summary=`active=${sb.active} archived=${sb.archived} quarantined=${sb.quarantined} rejected=${sb.rejected} | events=${debug.event_count} (retrieved/7d=${debug.retrieval_events_7d}) | learning[enforce=${lr.enforced_directives} escalated=${lr.escalated_directives} synonyms=${lr.synonym_pairs} unactionable=${lr.unactionable_queue_depth} insights_pending=${lr.insight_candidates_pending}] | schema=${JSON.stringify(debug.schema_versions)}`+cohortTag+hiveTag+curationTag,warnings=[];if(co.linked&&co.degraded)warnings.push(`cohort identity is degraded (via ${co.identity_source}): shared store is machine-local, not portable across machines`);if(co.linked&&co.local_orphaned)warnings.push("local .swarm/knowledge.jsonl is orphaned by the link store (benign; resolver ignores it)");if(lr.unactionable_queue_depth>UNACTIONABLE_BACKLOG_WARN)warnings.push(`${lr.unactionable_queue_depth} lessons stuck in the unactionable queue (curator may not be draining)`);if(lr.insight_candidates_pending>INSIGHT_BACKLOG_WARN)warnings.push(`${lr.insight_candidates_pending} micro-reflection insight candidates pending (curator may not be folding them in)`);if(debug.corrupt_line_count>0)warnings.push(`${debug.corrupt_line_count} corrupt JSONL line(s) (raw=${debug.raw_entry_count} vs normalized=${debug.normalized_entry_count})`);if(debug.entries_missing_v2_counters>0)warnings.push(`${debug.entries_missing_v2_counters} entr(y/ies) missing v2 counters (normalized on read)`);if(debug.cache_status==="stale")warnings.push("stale plugin cache — run `bunx opencode-swarm update` (knowledge tools may be running old code)");if(hv.override_promotions>0){let sample=hv.override_entries[0],gates=sample?.override_failed_gates?.join(",")??"?";warnings.push(`${hv.override_promotions} hive entr(y/ies) promoted via --force override (failed gates: ${gates}${sample?.reason?`; reason: "${sample.reason.slice(0,60)}"`:""})`)}if(cu.config_fingerprint_match===!1)warnings.push("cohort config fingerprint mismatch: this worktree curates with different knowledge semantics than the cohort — align knowledge config across linked worktrees");if(cu.pending_proposals>0)warnings.push(`${cu.pending_proposals} pending curation proposal(s) awaiting confirmation (blocked destructive actions recorded in curation-proposals.jsonl)`);if(warnings.length>0)return{name:"Knowledge health",status:"⚠️",detail:`${summary} — ${warnings.join("; ")}`};return{name:"Knowledge health",status:"✅",detail:summary}}var version3,SEVEN_DAYS_MS2=604800000,UNACTIONABLE_BACKLOG_WARN=100,INSIGHT_BACKLOG_WARN=50;var init_knowledge_diagnostics=__esm(()=>{init_package();init_insight_candidate_store();init_project_db();init_knowledge_events();init_knowledge_link();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_curation_policy();init_memory_link();init_redaction();init_caps();init_jsonl_cap();init_synonym_map();init_version_check();({version:version3}=package_default)});import*as child_process8 from"node:child_process";import{existsSync as existsSync93,readdirSync as readdirSync27,readFileSync as readFileSync69,statSync as statSync62}from"node:fs";import*as path187 from"node:path";import{fileURLToPath as fileURLToPath5}from"node:url";function checkSwarmDb(directory){let runtime=process.versions.bun===void 0?"node":"bun",runtimeVersion=process.versions.bun??process.versions.node??"unknown",snapshot=getSwarmDbHealthSnapshot(directory);switch(snapshot.kind){case"absent":return{name:"swarm.db",status:"✅",detail:`not created yet (driver: ${runtime} ${runtimeVersion})`};case"too_large":return{name:"swarm.db",status:"⚠️",detail:`${Math.round(snapshot.sizeBytes/1048576)} MiB exceeds the ${Math.round(SWARM_DB_QUICK_CHECK_MAX_BYTES2/1048576)} MiB inline quick_check cap — run an external integrity check (driver: ${runtime} ${runtimeVersion})`};case"error":return{name:"swarm.db",status:"❌",detail:`unavailable (${snapshot.category}): ${snapshot.message}`};case"open":{let markerNote=snapshot.staleMarker?", stale db-migration-failure.json marker present":"",detail=`quick_check ${snapshot.quickCheck}; ${snapshot.journalMode} mode, ${snapshot.pageCount} pages, ${snapshot.migrationFailures} recorded migration failure(s)${markerNote}; driver: ${runtime} ${runtimeVersion}`;if(snapshot.quickCheck!=="ok")return{name:"swarm.db",status:"❌",detail};if(snapshot.migrationFailures>0||snapshot.staleMarker)return{name:"swarm.db",status:"⚠️",detail};return{name:"swarm.db",status:"✅",detail}}}}function validateTaskDag(plan){let allTaskIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)allTaskIds.add(task.id);let missingDeps=[];for(let phase of plan.phases)for(let task of phase.tasks)for(let dep of task.depends)if(!allTaskIds.has(dep))missingDeps.push(`${task.id} depends on missing ${dep}`);return{valid:missingDeps.length===0,missingDeps}}async function checkEvidenceCompleteness(directory,plan){let completedTaskIds=[];for(let phase of plan.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.push(task.id);if(completedTaskIds.length>0){let evidenceTaskIds=new Set(await listEvidenceTaskIds(directory)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(directory,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}if(missingEvidence.length===0)return{name:"Evidence",status:"✅",detail:`All ${completedTaskIds.length} completed tasks have evidence`};else return{name:"Evidence",status:"❌",detail:`${missingEvidence.length} completed task(s) missing evidence: ${missingEvidence.join(", ")}`}}return{name:"Evidence",status:"✅",detail:"No completed tasks yet"}}async function checkSwarmIdentity(plan){let activeSwarmId=process.env.OPENCODE_SWARM_ID;if(plan&&!activeSwarmId)return{name:"Swarm Identity",status:"❌",detail:"Plan exists but OPENCODE_SWARM_ID not set in environment"};if(!plan&&!activeSwarmId)return{name:"Swarm Identity",status:"✅",detail:"No conflict detected"};if(!plan)return{name:"Swarm Identity",status:"✅",detail:`No plan, but OPENCODE_SWARM_ID is '${activeSwarmId}'`};if(plan&&plan.swarm!==activeSwarmId)return{name:"Swarm Identity",status:"❌",detail:`Swarm identity mismatch: plan says '${plan.swarm}', active is '${activeSwarmId}'`};return{name:"Swarm Identity",status:"✅",detail:`Swarm identity consistent: '${plan.swarm}'`}}async function checkPhaseBoundaries(plan){if(!plan)return{name:"Phase Boundaries",status:"✅",detail:"No plan to validate"};let mismatches=[];for(let phase of plan.phases)for(let task of phase.tasks){let taskPhaseNum=parseInt(task.id.split(".")[0],10);if(Number.isNaN(taskPhaseNum))mismatches.push(`Task ${task.id} has invalid phase number`);else if(taskPhaseNum!==phase.id)mismatches.push(`Task ${task.id} found under Phase ${phase.id}`)}if(mismatches.length===0)return{name:"Phase Boundaries",status:"✅",detail:"All tasks correctly aligned to phases"};return{name:"Phase Boundaries",status:"❌",detail:mismatches.join("; ")}}async function checkOrphanedEvidence(directory,plan){if(!plan)return{name:"Orphaned Evidence",status:"✅",detail:"No plan to cross-reference"};let planTaskIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)planTaskIds.add(task.id);try{let orphaned=(await listEvidenceTaskIds(directory)).filter((id)=>!planTaskIds.has(id)&&!/^retro-/.test(id));if(orphaned.length===0)return{name:"Orphaned Evidence",status:"✅",detail:"All evidence entries reference valid plan tasks"};return{name:"Orphaned Evidence",status:"❌",detail:`Evidence for [${orphaned.join(", ")}] not in plan`}}catch{return{name:"Orphaned Evidence",status:"❌",detail:"Could not read evidence directory"}}}async function checkPlanSync(directory,plan){if(!plan)return{name:"Plan Sync",status:"✅",detail:"No plan.json present"};try{let jsonTaskCount=0;for(let phase of plan.phases)jsonTaskCount+=phase.tasks.length;let planMdContent=await readSwarmFileAsync(directory,"plan.md");if(!planMdContent)return{name:"Plan Sync",status:"✅",detail:"plan.md not present"};let mdTaskCount=(planMdContent.match(/^- \[[ xX~]/gm)||[]).length;if(jsonTaskCount===mdTaskCount)return{name:"Plan Sync",status:"✅",detail:`plan.json and plan.md both have ${jsonTaskCount} tasks`};return{name:"Plan Sync",status:"❌",detail:`plan.json: ${jsonTaskCount} tasks, plan.md: ${mdTaskCount} — run /swarm sync-plan`}}catch{return{name:"Plan Sync",status:"❌",detail:"Could not compare plan files"}}}async function checkConfigBackups(directory){try{let backupCount=readdirSync27(directory).filter((f)=>/\.opencode-swarm\.yaml\.bak/.test(f)).length;if(backupCount<=5)return{name:"Config Backups",status:"✅",detail:`${backupCount} backup file(s) — within acceptable range`};if(backupCount<=19)return{name:"Config Backups",status:"❌",detail:`${backupCount} backup config files found — consider cleanup`};return{name:"Config Backups",status:"❌",detail:`${backupCount} backup config files found — cleanup required`}}catch{return{name:"Config Backups",status:"✅",detail:"Could not check backup files"}}}function isSpawnTimeoutLike(err){if(typeof err!=="object"||err===null)return!1;let e=err;return e.killed===!0||e.signal==="SIGKILL"||e.signal==="SIGTERM"||e.code==="ETIMEDOUT"}async function checkGitRepository(directory){try{if(!existsSync93(directory)||!statSync62(directory).isDirectory())return{name:"Git Repository",status:"❌",detail:"Invalid directory — cannot check git status"};let gitExecutable=await resolveGitExecutableAsync();return _internals155.execFileSync(gitExecutable,["rev-parse","--git-dir"],{cwd:directory,stdio:["ignore","ignore","ignore"],timeout:GIT_REPOSITORY_CHECK_TIMEOUT_MS,killSignal:"SIGKILL",maxBuffer:GIT_REPOSITORY_CHECK_MAX_BUFFER_BYTES,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),{name:"Git Repository",status:"✅",detail:"Git repository detected"}}catch(err){if(isSpawnTimeoutLike(err))return{name:"Git Repository",status:"⬜",detail:`git rev-parse did not answer within ${GIT_REPOSITORY_CHECK_TIMEOUT_MS} ms — git state unknown`};return{name:"Git Repository",status:"❌",detail:"Not a git repository — version control recommended"}}}async function checkSpecStaleness(directory,plan){let specContent=readEffectiveSpecSync(directory)?.content??null;if(!specContent)return{name:"Spec Staleness",status:"✅",detail:"No effective spec present"};if(!plan)return{name:"Spec Staleness",status:"✅",detail:"No plan to compare spec against"};let titleMatch=specContent.match(/^#\s+(.+)$/m);if(!titleMatch)return{name:"Spec Staleness",status:"✅",detail:"Spec title not detectable"};let specTitle=titleMatch[1].trim(),planTitle=plan.title.trim();if(specTitle.toLowerCase()===planTitle.toLowerCase())return{name:"Spec Staleness",status:"✅",detail:"Spec and plan titles are aligned"};return{name:"Spec Staleness",status:"❌",detail:`Spec/plan title mismatch: spec says '${specTitle}', plan says '${planTitle}'`}}async function checkConfigParseability(directory){let configPath=path187.join(directory,".opencode/opencode-swarm.json");if(!existsSync93(configPath))return{name:"Config Parseability",status:"✅",detail:"No project config file present (using defaults)"};try{let content=readFileSync69(configPath,"utf-8");return JSON.parse(content),{name:"Config Parseability",status:"✅",detail:"Project config is valid JSON"}}catch(err){return{name:"Config Parseability",status:"❌",detail:`Project config at .opencode/opencode-swarm.json is not valid JSON: ${err instanceof Error?err.message:"Unknown error"}`}}}function resolveGrammarDir(thisDir){let normalized=thisDir.replace(/\\/g,"/"),isSource=normalized.endsWith("/src/services"),isCliBundle=normalized.endsWith("/cli");return isSource||isCliBundle?path187.join(thisDir,"..","lang","grammars"):path187.join(thisDir,"lang","grammars")}async function checkGrammarWasmFiles(){let grammarFiles=["tree-sitter-javascript.wasm","tree-sitter-typescript.wasm","tree-sitter-tsx.wasm","tree-sitter-python.wasm","tree-sitter-go.wasm","tree-sitter-rust.wasm","tree-sitter-cpp.wasm","tree-sitter-c-sharp.wasm","tree-sitter-css.wasm","tree-sitter-bash.wasm","tree-sitter-ruby.wasm","tree-sitter-php.wasm","tree-sitter-java.wasm","tree-sitter-kotlin.wasm","tree-sitter-swift.wasm","tree-sitter-dart.wasm","tree-sitter-powershell.wasm","tree-sitter-ini.wasm","tree-sitter-regex.wasm"],thisDir=path187.dirname(fileURLToPath5(import.meta.url)),grammarDir=resolveGrammarDir(thisDir),missing=[];if(!existsSync93(path187.join(grammarDir,"tree-sitter.wasm")))missing.push("tree-sitter.wasm (core runtime)");for(let file3 of grammarFiles)if(!existsSync93(path187.join(grammarDir,file3)))missing.push(file3);if(missing.length===0)return{name:"Grammar WASM Files",status:"✅",detail:`Core runtime + all ${grammarFiles.length} grammar WASM files present`};return{name:"Grammar WASM Files",status:"❌",detail:`${missing.length} WASM file(s) missing: ${missing.join(", ")}`}}async function checkCheckpointManifest(directory){let manifestPath2=path187.join(directory,".swarm/checkpoints.json");if(!existsSync93(manifestPath2))return{name:"Checkpoint Manifest",status:"✅",detail:"No checkpoint manifest (no checkpoints saved)"};try{let content=readFileSync69(manifestPath2,"utf-8"),parsed=JSON.parse(content);if(!parsed.checkpoints||!Array.isArray(parsed.checkpoints))return{name:"Checkpoint Manifest",status:"❌",detail:"checkpoints.json missing 'checkpoints' array"};let invalidCount=0;for(let cp2 of parsed.checkpoints)if(typeof cp2.label!=="string"||typeof cp2.sha!=="string"||typeof cp2.timestamp!=="string")invalidCount++;if(invalidCount>0)return{name:"Checkpoint Manifest",status:"❌",detail:`${invalidCount} checkpoint(s) have invalid structure (missing label/sha/timestamp)`};return{name:"Checkpoint Manifest",status:"✅",detail:`Checkpoint manifest valid — ${parsed.checkpoints.length} checkpoint(s)`}}catch(err){if(err instanceof SyntaxError)return{name:"Checkpoint Manifest",status:"❌",detail:"checkpoints.json is not valid JSON"};return{name:"Checkpoint Manifest",status:"❌",detail:"Could not read checkpoint manifest"}}}async function checkEventStreamIntegrity(directory){if(getCoreEventCoverage(directory)==="empty")return{name:"Event Stream",status:"✅",detail:"No events.jsonl present"};try{let window2=readCoreEvents(directory),lines=window2.text.split(`
|
|
2635
2635
|
`).filter((line)=>line.trim()!==""),malformedCount=0;for(let line of lines)try{JSON.parse(line)}catch{malformedCount++}let coverageNote=window2.coverage==="truncated"?" (retained window — compacted history excluded)":"";if(malformedCount===0)return{name:"Event Stream",status:"✅",detail:`events.jsonl is valid — ${lines.length} event(s)${coverageNote}`};return{name:"Event Stream",status:"❌",detail:`events.jsonl has ${malformedCount} malformed line(s) — possible data corruption`}}catch{return{name:"Event Stream",status:"❌",detail:"Could not read events.jsonl"}}}async function checkSteeringDirectives(directory){if(getCoreEventCoverage(directory)==="empty")return{name:"Steering Directives",status:"✅",detail:"No events.jsonl — no steering directives to check"};try{let window2=readCoreEvents(directory),lines=window2.text.split(`
|
|
@@ -4056,7 +4056,7 @@ ${USAGE13}`;let councilFlag=parsed.council?"council=true":"council=false",signal
|
|
|
4056
4056
|
... (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,_internals202;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:()=>_internals202.platform(),comSpec:()=>_internals202.comSpec(),realpathSync:(candidate2)=>_internals202.realpathSync(candidate2),statSync:(candidate2)=>_internals202.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 _internals202.detectResolvedLinter(directory,ctx?.abort);if(resolvedLinter){let result=await _internals202.runResolvedLint(resolvedLinter,mode,directory,ctx?.abort);return JSON.stringify(result,null,2)}let additionalLinter=_internals202.detectAdditionalLinter(cwd);if(additionalLinter){warn(`[lint] Using ${additionalLinter} linter for this project`);let result=await _internals202.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
|
|
4057
4057
|
For Python: pip install ruff
|
|
4058
4058
|
For Rust: rustup component add clippy`},null,2)}}),_internals202={MAX_PACKAGE_MANIFEST_BYTES,MAX_PATH_SHIM_BYTES,arch:()=>process.arch,closeSync:fs129.closeSync,comSpec:()=>process.env.ComSpec,detectAdditionalLinter,detectAvailableLinter,detectResolvedLinter,execPath:()=>process.execPath,existsSync:fs129.existsSync,fstatSync:fs129.fstatSync,isCommandAvailable,openSync:fs129.openSync,pathEnv:()=>process.env.PATH??"",platform:()=>process.platform,readFileSync:fs129.readFileSync,readSync:fs129.readSync,readdirSync:fs129.readdirSync,realpathSync:fs129.realpathSync,resolveLinterCommand,runAdditionalLint,runExternalTool,runLint,runResolvedLint,statSync:fs129.statSync}});import*as fs130 from"node:fs";import*as path244 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 count4 of freq.values()){let p=count4/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=path244.join(scanDir,".secretscanignore");try{if(!fs130.existsSync(ignorePath))return[];let content=fs130.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(path244.matchesGlob(relPath,pattern))return!0;return!1}function isIgnoredExplicitPath(relPath,ignoreExact,ignoreGlobs){let segments=relPath.split("/"),file3=segments[segments.length-1]??"";if(isExcluded(file3,relPath,ignoreExact,ignoreGlobs))return!0;let prefix="";for(let i=0;i<segments.length-1;i++){let segment=segments[i]??"";if(prefix=prefix.length===0?segment:`${prefix}/${segment}`,isExcluded(segment,prefix,ignoreExact,ignoreGlobs))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=path244.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=fs130.constants.O_RDONLY|(O_NOFOLLOW!==void 0?O_NOFOLLOW:0);fd=_internals203.openFile(filePath,flags)}catch{return{status:"incomplete",reason:"read_error"}}let outcome,closeFailed=!1;try{let stat23=_internals203.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 count4=_internals203.readFileChunk(fd,buffer,bytesRead,buffer.length-bytesRead,null);if(count4===0)break;bytesRead+=count4}let postStat=_internals203.fstatFile(fd),postDescriptorIdentity=getStableFileIdentity(postStat),postPathStat=_internals203.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{_internals203.closeFile(fd)}catch{closeFailed=!0}}if(closeFailed)return{status:"incomplete",reason:"read_error"};return outcome}function scanFileForSecrets(filePath,mode){let findings=[];try{let lstat11=_internals203.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(`
|
|
4059
|
-
`);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((resolve97)=>setImmediate(resolve97))}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 relative58=path244.relative(rootDir2,targetPath).replace(/\\/g,"/");if(!relative58||relative58===".")return".";if(relative58.startsWith("..")||path244.isAbsolute(relative58))return path244.basename(targetPath).replace(/\\/g,"/")||".";return relative58}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=fs130.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 _internals203.yieldToEventLoop(),_internals203.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=path244.join(currentDir,entry.name),relPath=path244.relative(scanDir,fullPath).replace(/\\/g,"/");if(isExcluded(entry.name,relPath,excludeExact,excludeGlobs)){stats2.skippedDirs++;continue}let lstat11;try{lstat11=fs130.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=fs130.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=path244.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{_internals203.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 _internals203.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,ignoredFiles=0,requestedFiles=Math.max(0,rawRequestedFiles??files.length),incompletePaths=[],rawRoot=path244.resolve(directory),canonicalRoot=(()=>{try{return fs130.realpathSync(rawRoot)}catch{return rawRoot}})(),rootStat;try{rootStat=fs130.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 ignoreExact=new Set,ignoreGlobs=[];for(let pattern of loadSecretScanIgnore(canonicalRoot)){if(pattern.length===0)continue;if(isGlobOrPathPattern(pattern))ignoreGlobs.push(pattern);else ignoreExact.add(pattern)}let hasIgnorePatterns=ignoreExact.size>0||ignoreGlobs.length>0,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=_internals203.now()+SCAN_TIME_BUDGET_MS;await _internals203.yieldToEventLoop();for(let index=0;index<filesToScan.length;index++){if(_internals203.now()>=deadline){for(let remaining of filesToScan.slice(index)){let remainingPath=path244.isAbsolute(remaining)?path244.resolve(remaining):path244.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=path244.isAbsolute(file3)?path244.resolve(file3):path244.resolve(rawRoot,file3);if(!isPathWithinScope(resolvedPath,rawRoot)){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"scope_escape");continue}let lstat11;try{lstat11=_internals203.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=path244.extname(resolvedPath).toLowerCase();if(DEFAULT_EXCLUDE_EXTENSIONS.has(ext)){if(skippedFiles++,DOCS_SAFE_EXCLUDE_EXTENSIONS.has(ext))policySkippedFiles++;continue}let scanPath=resolvedPath;try{scanPath=_internals203.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}if(hasIgnorePatterns){let relPath=path244.relative(canonicalRoot,scanPath).replace(/\\/g,"/");if(isIgnoredExplicitPath(relPath,ignoreExact,ignoreGlobs)){skippedFiles++,ignoredFiles++;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 _internals203.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,ignored_files:ignoredFiles,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,_internals203;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"?fs130.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=path244.resolve(directory),scanDir=(()=>{try{return fs130.realpathSync(scanDirRaw)}catch{return scanDirRaw}})(),dirStat;try{dirStat=fs130.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=_internals203.now()+SCAN_TIME_BUDGET_MS,discovery={files:[],totalCandidates:0,deadline,deadlineExceeded:!1,cleanupFailed:!1,entriesSinceYield:0,incompletePaths:[],directoriesQueued:1,unexaminedDirectories:0};await _internals203.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(_internals203.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 _internals203.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,ignored_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)}}});_internals203={secretscan,runSecretscan,runSecretscanOnFiles,SECRET_PATTERNS:SECRET_PATTERNS2,now:Date.now,yieldToEventLoop:yieldToEventLoop2,openFile:fs130.openSync,fstatFile:(fd)=>fs130.fstatSync(fd,{bigint:!0}),readFileChunk:fs130.readSync,closeFile:fs130.closeSync,lstatFile:(path245)=>fs130.lstatSync(path245,{bigint:!0}),realpathSync:(path245)=>fs130.realpathSync(path245),closeDirectory:(directory)=>directory.closeSync()}});import*as fs131 from"node:fs";import*as path245 from"node:path";function detectFileExists(dir,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs131.readdirSync(dir),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs131.accessSync(path245.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(fs131.existsSync(path245.join(dir,"gradlew.bat"))){if(args2.some((arg)=>arg.endsWith("\\")))return["gradle",...args2];return resolveContainedWindowsBatchCommand(dir,"gradlew.bat",args2)??["gradle",...args2]}}return fs131.existsSync(path245.join(dir,"gradlew"))?["./gradlew",...args2]:["gradle",...args2]}function buildPhpVendorCommand(dir,name,args2=[]){let proxy=path245.join("vendor","bin",name);if(process.platform!=="win32")return[proxy,...args2];let interpreterFallback=()=>fs131.existsSync(path245.join(dir,proxy))?["php",proxy,...args2]:[proxy,...args2];if(args2.some((arg)=>arg.endsWith("\\")))return interpreterFallback();return resolveContainedWindowsBatchCommand(dir,path245.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)=>fs131.existsSync(path245.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}
|
|
4059
|
+
`);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((resolve97)=>setImmediate(resolve97))}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 relative58=path244.relative(rootDir2,targetPath).replace(/\\/g,"/");if(!relative58||relative58===".")return".";if(relative58.startsWith("..")||path244.isAbsolute(relative58))return path244.basename(targetPath).replace(/\\/g,"/")||".";return relative58}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=fs130.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 _internals203.yieldToEventLoop(),_internals203.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=path244.join(currentDir,entry.name),relPath=path244.relative(scanDir,fullPath).replace(/\\/g,"/");if(isExcluded(entry.name,relPath,excludeExact,excludeGlobs)){stats2.skippedDirs++;continue}let lstat11;try{lstat11=fs130.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=fs130.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=path244.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{_internals203.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 _internals203.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,ignoredFiles=0,resultsTruncated=!1,requestedFiles=Math.max(0,rawRequestedFiles??files.length),incompletePaths=[],rawRoot=path244.resolve(directory),canonicalRoot=(()=>{try{return fs130.realpathSync(rawRoot)}catch{return rawRoot}})(),rootStat;try{rootStat=fs130.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 ignoreExact=new Set,ignoreGlobs=[];for(let pattern of loadSecretScanIgnore(canonicalRoot)){if(pattern.length===0)continue;if(isGlobOrPathPattern(pattern))ignoreGlobs.push(pattern);else ignoreExact.add(pattern)}let hasIgnorePatterns=ignoreExact.size>0||ignoreGlobs.length>0,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=_internals203.now()+SCAN_TIME_BUDGET_MS;await _internals203.yieldToEventLoop();for(let index=0;index<filesToScan.length;index++){if(_internals203.now()>=deadline){for(let remaining of filesToScan.slice(index)){let remainingPath=path244.isAbsolute(remaining)?path244.resolve(remaining):path244.resolve(rawRoot,remaining);recordIncompletePath(incompletePaths,canonicalRoot,remainingPath,"deadline")}incompleteFiles+=filesToScan.length-index;break}if(findings.length>=MAX_FINDINGS2){resultsTruncated=!0,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=path244.isAbsolute(file3)?path244.resolve(file3):path244.resolve(rawRoot,file3);if(!isPathWithinScope(resolvedPath,rawRoot)){skippedFiles++,incompleteFiles++,recordIncompletePath(incompletePaths,canonicalRoot,resolvedPath,"scope_escape");continue}let lstat11;try{lstat11=_internals203.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=path244.extname(resolvedPath).toLowerCase();if(DEFAULT_EXCLUDE_EXTENSIONS.has(ext)){if(skippedFiles++,DOCS_SAFE_EXCLUDE_EXTENSIONS.has(ext))policySkippedFiles++;continue}let scanPath=resolvedPath;try{scanPath=_internals203.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}if(hasIgnorePatterns){let relPath=path244.relative(canonicalRoot,scanPath).replace(/\\/g,"/");if(isIgnoredExplicitPath(relPath,ignoreExact,ignoreGlobs)){skippedFiles++,ignoredFiles++;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,resultsTruncated=!0;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 _internals203.yieldToEventLoop()}findings.sort((a,b)=>{if(a.path<b.path)return-1;if(a.path>b.path)return 1;return a.line-b.line});let disclosureParts=[];if(resultsTruncated)disclosureParts.push(`Results limited to ${MAX_FINDINGS2} findings`);return{scan_dir:directory,findings,count:findings.length,files_scanned:filesScanned,skipped_files:skippedFiles,policy_skipped_files:policySkippedFiles,ignored_files:ignoredFiles,requested_files:requestedFiles,incomplete_files:incompleteFiles,incomplete_paths:incompletePaths,...resultsTruncated&&{truncated:!0,message:`${disclosureParts.join("; ")}.`}}}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,SECRETSCAN_MAX_FINDINGS,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,_internals203;var init_secretscan=__esm(()=>{init_zod();init_path_security();init_create_tool();SECRETSCAN_MAX_FINDINGS=MAX_FINDINGS2,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"?fs130.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=path244.resolve(directory),scanDir=(()=>{try{return fs130.realpathSync(scanDirRaw)}catch{return scanDirRaw}})(),dirStat;try{dirStat=fs130.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=_internals203.now()+SCAN_TIME_BUDGET_MS,discovery={files:[],totalCandidates:0,deadline,deadlineExceeded:!1,cleanupFailed:!1,entriesSinceYield:0,incompletePaths:[],directoriesQueued:1,unexaminedDirectories:0};await _internals203.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(_internals203.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 _internals203.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,ignored_files:0,incomplete_files:incompleteFiles,incomplete_paths:discovery.incompletePaths,...allFindings.length>=MAX_FINDINGS2&&{truncated:!0}},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)}}});_internals203={secretscan,runSecretscan,runSecretscanOnFiles,SECRET_PATTERNS:SECRET_PATTERNS2,now:Date.now,yieldToEventLoop:yieldToEventLoop2,openFile:fs130.openSync,fstatFile:(fd)=>fs130.fstatSync(fd,{bigint:!0}),readFileChunk:fs130.readSync,closeFile:fs130.closeSync,lstatFile:(path245)=>fs130.lstatSync(path245,{bigint:!0}),realpathSync:(path245)=>fs130.realpathSync(path245),closeDirectory:(directory)=>directory.closeSync()}});import*as fs131 from"node:fs";import*as path245 from"node:path";function detectFileExists(dir,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs131.readdirSync(dir),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs131.accessSync(path245.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(fs131.existsSync(path245.join(dir,"gradlew.bat"))){if(args2.some((arg)=>arg.endsWith("\\")))return["gradle",...args2];return resolveContainedWindowsBatchCommand(dir,"gradlew.bat",args2)??["gradle",...args2]}}return fs131.existsSync(path245.join(dir,"gradlew"))?["./gradlew",...args2]:["gradle",...args2]}function buildPhpVendorCommand(dir,name,args2=[]){let proxy=path245.join("vendor","bin",name);if(process.platform!=="win32")return[proxy,...args2];let interpreterFallback=()=>fs131.existsSync(path245.join(dir,proxy))?["php",proxy,...args2]:[proxy,...args2];if(args2.some((arg)=>arg.endsWith("\\")))return interpreterFallback();return resolveContainedWindowsBatchCommand(dir,path245.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)=>fs131.existsSync(path245.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}
|
|
4060
4060
|
${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=path245.extname(sourceFile);if(!profile.extensions.includes(ext))return[];let base=path245.basename(sourceFile,ext),rel=path245.relative(dir,sourceFile),stripSrc=path245.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(path245.join(dir,tDir,stripSrc,`${base}${suffix}${ext}`));let existing=[];for(let c of candidates)try{fs131.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 fs132 from"node:fs";import*as path246 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=fs132.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=path246.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=fs132.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=fs132.readFileSync(full,"utf-8");if(totalBytes+=size,isMainClass(source))results.push(path246.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 fs132.existsSync(path246.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((resolve97)=>setImmediate(resolve97)),scanForMainClasses(dir)}async function selectFramework(dir){let content="";for(let file3 of["pom.xml","build.gradle","build.gradle.kts"])try{content+=`
|
|
4061
4061
|
${fs132.readFileSync(path246.join(dir,file3),"utf-8")}`}catch{}return detectFramework(content)}function isExecutableFile2(filePath){try{let stats2=fs132.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 _internals204.isExecutableFile(path246.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,_internals204;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"]);_internals204={extractImports,isMainClass,detectFramework,wrapperExists,isExecutableFile:isExecutableFile2,resolveMvnwCommand,resolveGradlewCommand,MAX_ENTRY_POINT_ENTRIES}});import*as fs133 from"node:fs";import*as path247 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===`
|
|
4062
4062
|
`||current==="\r")state2="normal",out+=current;else out+=" ";continue}if(state2==="block"){if(current==="*"&&next==="/")out+=" ",index++,state2="normal";else out+=current===`
|
|
@@ -7584,7 +7584,7 @@ ${hint}`}]}return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0
|
|
|
7584
7584
|
Evidence:
|
|
7585
7585
|
${evidence2}`:""}`;if(blockOnThreshold)return{status:"exceeded",blocked:!0,advisory:!1,count:count4,max,message:`${summary}
|
|
7586
7586
|
${repairStep()}`};return{status:"exceeded",blocked:!1,advisory:!0,count:count4,max,message:`${summary}
|
|
7587
|
-
${repairStep()}`}}init_logger();init_task_id();init_create_tool();init_resolve_working_directory();var EVIDENCE_DIR=".swarm/evidence";function isValidTaskId4(taskId){return isStrictTaskId(taskId)}function isPathWithinSwarm(filePath,workspaceRoot){let normalizedWorkspace=path325.resolve(workspaceRoot),swarmPath3=path325.join(normalizedWorkspace,".swarm","evidence");return path325.resolve(filePath).startsWith(swarmPath3)}function readEvidenceFile(evidencePath2){if(!fs188.existsSync(evidencePath2))return null;let content;try{content=fs188.readFileSync(evidencePath2,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(content)}catch{return null}if(parsed&&typeof parsed==="object"&&Array.isArray(parsed.required_gates)&&typeof parsed.gates==="object"&&parsed.gates!==null)return parsed;return null}var check_gate_status=createSwarmTool({description:"Read-only tool to check the gate status of a specific task. Reads .swarm/evidence/{taskId}.json and returns structured JSON describing required, passed, and missing gates.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "1.2.3", "1.2.3.4")').describe('The task ID to check gate status for (e.g., "1.1", "2.3.1")'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/evidence/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let taskIdInput,workingDirInput;try{if(args2&&typeof args2==="object"){let obj=args2;taskIdInput=typeof obj.task_id==="string"?obj.task_id:void 0,workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}}catch{}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={taskId:taskIdInput??"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:dirResult.message,todo_scan:null};return JSON.stringify(errorResult,null,2)}directory=dirResult.directory;let todoGateConfig;try{todoGateConfig=loadPluginConfigWithMeta(directory).config.todo_gate}catch(configError){log("check_gate_status: todo_gate config load threw; TODO gate evaluation skipped",configError)}if(!taskIdInput)return JSON.stringify({taskId:"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid task_id: task_id is required",todo_scan:null},null,2);if(!isValidTaskId4(taskIdInput)){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`Invalid task_id format: "${taskIdInput}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3", "1.2.3.4")`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let evidencePath2=path325.join(directory,EVIDENCE_DIR,`${taskIdInput}.json`);if(!isPathWithinSwarm(evidencePath2,directory))return JSON.stringify({taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid path: evidence path validation failed",todo_scan:null},null,2);let evidenceData=readEvidenceFile(evidencePath2);if(!evidenceData){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`No evidence file found for task "${taskIdInput}" at ${evidencePath2}. Evidence file may be missing or invalid.`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let gatesMap=evidenceData.gates||{},authoritativeWorkflow=evidenceData.workflow?.schema===TASK_WORKFLOW_SCHEMA_MARKER,derivedGates=deriveApplicableGateSet(evidenceData,authoritativeWorkflow?{currentDeclaredFiles:readCurrentTaskDeclaredFiles(directory,taskIdInput)}:void 0),requiredGates=derivedGates.requiredGates,passedGates=derivedGates.satisfiedGates,missingGates=derivedGates.missingGates,readOnlyNoMutation=derivedGates.readOnlyNoMutation,status2=missingGates.length===0&&(readOnlyNoMutation||evidenceData.workflow?.state==="tests_run"||evidenceData.workflow?.state==="complete")?"all_passed":"incomplete",message;if(status2==="all_passed")message=`All required gates have passed for task "${taskIdInput}".`;else if(requiredGates.length===0)message=`Task "${taskIdInput}" is incomplete. No required gates are configured for this task generation.`;else message=`Task "${taskIdInput}" is incomplete. Missing gates: ${missingGates.join(", ")}.`;let secretscanVerdict="not_run";try{let evidenceResult=await loadEvidence(directory,taskIdInput);if(evidenceResult.status==="found"){let secretscanEntries=evidenceResult.bundle.entries.filter((entry)=>entry.type==="secretscan");if(secretscanEntries.length>0){let lastSecretscan=secretscanEntries[secretscanEntries.length-1];if(isSecretscanEvidence(lastSecretscan)){let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=lastSecretscan,findingsCount=lastSecretscan.findings_count??0,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasFindings=findingsCount>0,policySkipped=lastSecretscan.policy_skipped_files,requestedFilesCount=lastSecretscan.requested_files,vacuousCoverage=lastSecretscan.files_scanned===0&&typeof policySkipped==="number"&&Number.isSafeInteger(policySkipped)&&policySkipped>=0&&typeof requestedFilesCount==="number"&&Number.isSafeInteger(requestedFilesCount)&&requestedFilesCount>0&&policySkipped>=requestedFilesCount&&findingsCount===0&&incompleteFiles===0&&incompletePaths.length===0,hasZeroCoverage=lastSecretscan.files_scanned===0&&!vacuousCoverage;if(hasIncompleteCoverage||hasFindings||hasZeroCoverage||lastSecretscan.verdict==="fail"||lastSecretscan.verdict==="rejected")if(secretscanVerdict="fail",hasIncompleteCoverage&&!hasFindings){if(missingGates.push("secretscan (BLOCKED — incomplete coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan incomplete coverage in prior scan. ${message}`}else if(hasFindings&&hasIncompleteCoverage){if(missingGates.push("secretscan (BLOCKED — secrets detected; incomplete coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan found secrets and incomplete coverage in prior scan. ${message}`}else if(hasFindings){if(missingGates.push("secretscan (BLOCKED — secrets detected)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan found secrets in prior scan. ${message}`}else{if(missingGates.push("secretscan (BLOCKED — zero coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan scanned zero files in prior scan. ${message}`}else if(lastSecretscan.verdict==="pass"||lastSecretscan.verdict==="approved"||lastSecretscan.verdict==="info"){if(secretscanVerdict="pass",vacuousCoverage)message+=` Advisory: Secretscan coverage was vacuous (${lastSecretscan.policy_skipped_files} of ${lastSecretscan.requested_files} requested file(s) skipped by scan policy).`}}}else message+=" Advisory: No secretscan evidence found for this task. Consider running secretscan."}else if(evidenceResult.status==="invalid_schema")secretscanVerdict="fail",missingGates.push("secretscan (BLOCKED — invalid evidence)"),status2="incomplete",message=`BLOCKED: Secretscan evidence is invalid and cannot prove complete coverage. ${message}`}catch{}let todoScan=evidenceData.todo_scan,todoVerdict=evaluateTodoGate(todoScan,todoGateConfig);if(todoVerdict.status==="exceeded")if(todoVerdict.blocked){if(missingGates.push(`todo_gate (BLOCKED — ${todoVerdict.count} high-priority TODOs exceed max ${todoVerdict.max})`),status2==="all_passed")status2="incomplete";message=`BLOCKED: TODO gate threshold exceeded. ${todoVerdict.message} ${message}`}else message+=` Advisory: todo_gate threshold exceeded — ${todoVerdict.count} high-priority TODOs (FIXME/HACK/XXX) exceed max_high_priority=${todoVerdict.max}.`;let workflowMeta=evidenceData.workflow&&typeof evidenceData.workflow==="object"&&typeof evidenceData.workflow.state==="string"?{state:evidenceData.workflow.state,generation:typeof evidenceData.workflow.generation==="number"?evidenceData.workflow.generation:0}:null,workflowAttributionHint;if(status2==="incomplete"&&workflowMeta?.state==="coder_delegated"&&!gatesMap.pre_check)workflowAttributionHint="Task is settled at coder_delegated but Stage A (pre_check_batch) was never attributed — "+`reviewer/test_engineer dispatches will be denied with TASK_WORKFLOW_STAGE_A_REQUIRED. Run pre_check_batch on the task's changed files; if it passes without advancing this task, run /swarm recover ${taskIdInput}.`,message+=` ${workflowAttributionHint}`;let result={taskId:taskIdInput,status:status2,required_gates:requiredGates,passed_gates:passedGates,missing_gates:missingGates,gates:gatesMap,message,todo_scan:todoScan??null,secretscan_verdict:secretscanVerdict,workflow:workflowMeta,...workflowAttributionHint?{workflow_attribution_hint:workflowAttributionHint}:{}};return JSON.stringify(result,null,2)}});init_checkpoint();init_co_change_analyzer();init_zod();init_loader();init_pr_workflow_gate();init_create_tool();var CompletePrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),pr_head_sha:exports_external.string().trim().min(1).max(80),report_verdict:exports_external.enum(["APPROVE","REQUEST_CHANGES","INCOMPLETE"]).optional()}).strict().superRefine((value,ctx)=>{if(value.mode==="PR_REVIEW"&&value.report_verdict===void 0)ctx.addIssue({code:"custom",path:["report_verdict"],message:"is required for PR_REVIEW completion (issue #2383 terminal report)"})});async function executeCompletePrWorkflow(args2,directory,context={}){let parsed=CompletePrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow completion: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow completion requires an active sessionID"});let staleDisclosure={},laneLiveness;try{let config3=loadPluginConfig(directory),hooks2=config3.hooks;laneLiveness={laneLivenessWatchdog:config3.lane_liveness_watchdog,backgroundPendingTimeoutMs:hooks2?.background_pending_timeout_minutes!==void 0?hooks2.background_pending_timeout_minutes*60000:void 0}}catch{}try{let settlement=await _internals278.settlePresumedStalePrWorkflowLanes(directory,context.sessionID,laneLiveness);if(settlement.presumedStaleLaneIds.length>0)staleDisclosure={presumed_stale_lanes:settlement.presumedStaleLaneIds,presumed_stale_disclosure:settlement.disclosure};if(settlement.probedAliveLaneIds?.length)staleDisclosure.probe_retained_lanes=settlement.probedAliveLaneIds;if(settlement.probeDegradedReason)staleDisclosure.probe_status=settlement.probeDegradedReason;if(settlement.horizonConflictNote)staleDisclosure.horizon_conflict=settlement.horizonConflictNote}catch{}let amendmentDisclosure={};try{let gateState=await _internals278.readPrWorkflowGateState(directory,context.sessionID);if(gateState?.prFeedbackInventoryAmendments?.length)amendmentDisclosure={inventory_amendments:gateState.prFeedbackInventoryAmendments}}catch{}try{let terminalReport;if(parsed.data.mode==="PR_REVIEW"){let coverage=null;try{coverage=await _internals278.readPrReviewTerminalCoverageForReport(directory,context.sessionID)}catch{}if(coverage){let findingPolicy;try{findingPolicy=await _internals278.readPrReviewFinalFindingPolicyForReport(directory,context.sessionID)}catch{}terminalReport={kind:coverage.kind,covered_dimensions:coverage.coveredDimensions,unresolved_dimensions:coverage.unresolvedDimensions,live_dimensions:coverage.liveDimensions,allowed_verdicts:findingPolicy?.permittedVerdicts??coverage.allowedVerdicts,...findingPolicy?{finding_policy_version:findingPolicy.policyVersion,blocking_finding_ids:findingPolicy.blockingFindingIds}:{},report_verdict:parsed.data.report_verdict}}}let status2=await _internals278.completePrWorkflow(directory,context.sessionID,parsed.data.mode,parsed.data.pr_head_sha,parsed.data.mode==="PR_REVIEW"?{reportVerdict:parsed.data.report_verdict,...laneLiveness?{laneLiveness}:{}}:laneLiveness?{laneLiveness}:void 0),checkoutRestoreRequired=!1,checkoutRestoreReceipts=[];if(status2==="completed")try{checkoutRestoreReceipts=await _internals278.listPendingPrWorkflowCheckoutRestores(directory,context.sessionID),checkoutRestoreRequired=checkoutRestoreReceipts.length>0}catch{checkoutRestoreRequired=!0}return JSON.stringify({success:!0,mode:parsed.data.mode,pr_head_sha:parsed.data.pr_head_sha,status:status2,ready_to_publish:status2==="ready-to-publish",verified_no_change:status2==="verified-no-change",gate_cleared:status2==="completed"||status2==="verified-no-change",checkout_restore_required:checkoutRestoreRequired,checkout_restore_receipts:checkoutRestoreReceipts,...terminalReport?{terminal_report:terminalReport}:{},...staleDisclosure,...amendmentDisclosure})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93),...staleDisclosure,...amendmentDisclosure})}}var complete_pr_workflow=createSwarmTool({description:"Validate terminal PR workflow coverage. After the ordered PR_FEEDBACK gates permit one standalone commit, the first call requires a clean tree and a non-merge direct child of intake HEAD, then binds its structured upstream target; the second clears only after both the local tracking ref and an actual-remote query point to that exact commit. A cleared result reports checkout_restore_required when preserved pre-workflow changes must be restored.",args:{mode:CompletePrWorkflowArgsSchema.shape.mode,pr_head_sha:CompletePrWorkflowArgsSchema.shape.pr_head_sha,report_verdict:CompletePrWorkflowArgsSchema.shape.report_verdict},execute:executeCompletePrWorkflow}),_internals278={completePrWorkflow,listPendingPrWorkflowCheckoutRestores,readPrWorkflowGateState,readPrReviewTerminalCoverageForReport,readPrReviewFinalFindingPolicyForReport,settlePresumedStalePrWorkflowLanes};init_zod();init_utils2();init_state();init_swarm_artifact_cache();init_create_tool();init_resolve_working_directory();import*as fs189 from"node:fs";import*as path326 from"node:path";function extractMatches(regex,text){return Array.from(text.matchAll(regex))}function parseIdentifiers(description){let identifiers=new Set,backtickRegex=/`([^`]+)`/g;for(let match of extractMatches(backtickRegex,description))identifiers.add(match[1]);let camelCaseRegex=/\b([a-z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(camelCaseRegex,description)){let word=match[1];if(word==="the"||word==="and"||word==="for"||word==="have"||word==="this"||word==="with"||word==="from"||word==="they"||word==="been"||word==="will"||word==="your"||word==="also")continue;identifiers.add(word)}let pascalCaseRegex=/\b([A-Z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(pascalCaseRegex,description))identifiers.add(match[1]);let configKeyRegex=/\b([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+)\b/g;for(let match of extractMatches(configKeyRegex,description))identifiers.add(match[1]);let quotedPathRegex=/['"](\.{0,3}(?:src|lib|test)[/\\][^'"]+)['"]/g;for(let match of extractMatches(quotedPathRegex,description))identifiers.add(match[1]);return Array.from(identifiers)}function parseFilePaths(description,filesTouched){if(filesTouched&&Array.isArray(filesTouched)&&filesTouched.length>0)return filesTouched;let filePaths=[],srcPathRegex=/\b(?:src|lib|test|app|packages?)[/\\][a-zA-Z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)\b/g;for(let match of extractMatches(srcPathRegex,description))filePaths.push(match[0]);let genericPathRegex=/\b[a-zA-Z0-9_./-]+[/\\][a-zA-Z0-9_./-]+\.[a-zA-Z0-9]+(?=\s|$|[.,;])/g;for(let match of extractMatches(genericPathRegex,description)){let pathStr=match[0];if(pathStr.includes("src/")||pathStr.includes("src\\")||pathStr.includes("lib/")||pathStr.includes("lib\\")||pathStr.includes("test/")||pathStr.includes("test\\"))filePaths.push(pathStr)}return filePaths}function buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked){if(tasksBlocked>0)return`Blocked: ${tasksBlocked} task(s) with missing identifiers`;let verified=tasksChecked-tasksSkipped;if(tasksSkipped===tasksChecked)return`All ${tasksChecked} completed task(s) skipped — research/inventory tasks`;if(tasksSkipped>0)return`${verified} task(s) verified, ${tasksSkipped} skipped (research tasks)`;return`All ${tasksChecked} completed tasks verified successfully`}async function executeCompletionVerify(args2,directory){let phase=Number(args2.phase);if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase))return JSON.stringify({success:!1,phase,status:"blocked",reason:"Invalid phase number",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);if(hasActiveTurboMode(args2.sessionID))return JSON.stringify({success:!0,phase,status:"passed",reason:"Turbo Mode active — completion verification bypassed",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);let plan;try{let planPath=validateSwarmPath(directory,"plan.json"),planRaw=fs189.readFileSync(planPath,"utf-8");plan=JSON.parse(planRaw)}catch{return JSON.stringify({success:!0,phase,status:"passed",reason:"Cannot verify without plan.json",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let targetPhase=plan.phases.find((p)=>p.id===phase);if(!targetPhase){let result2={success:!1,phase,status:"blocked",reason:`Phase ${phase} not found in plan.json`,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]};return JSON.stringify(result2,null,2)}let tasksChecked=0,tasksSkipped=0,tasksBlocked=0,blockedTasks=[];for(let task2 of targetPhase.tasks){if(task2.status!=="completed")continue;tasksChecked++;let fileTargets=parseFilePaths(task2.description,task2.files_touched),identifiers=parseIdentifiers(task2.description);if(fileTargets.length===0){tasksSkipped++;continue}if(identifiers.length===0){blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers — cannot verify completion without identifiers"}),tasksBlocked++;continue}let foundIdentifiers=new Set,hasFileReadFailure=!1;for(let filePath of fileTargets){let normalizedPath=filePath.replace(/\\/g,"/"),resolvedPath=path326.resolve(directory,normalizedPath),projectRoot=path326.resolve(directory),relative85=path326.relative(projectRoot,resolvedPath);if(!(relative85===""||!relative85.startsWith("..")&&!path326.isAbsolute(relative85))){blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File path '${filePath}' escapes the project directory — cannot verify completion`}),hasFileReadFailure=!0;continue}let fileContent;try{fileContent=fs189.readFileSync(resolvedPath,"utf-8")}catch{blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File '${filePath}' not found — cannot verify completion`}),hasFileReadFailure=!0;continue}for(let identifier of identifiers)if(fileContent.includes(identifier))foundIdentifiers.add(identifier)}let foundCount=foundIdentifiers.size;if(hasFileReadFailure||foundCount===0){if(!hasFileReadFailure)blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers found in target files"});tasksBlocked++}}let now2=new Date().toISOString(),result={success:tasksBlocked===0,phase,status:tasksBlocked===0?"passed":"blocked",reason:tasksBlocked>0?`COMPLETION_INCOMPLETE: ${tasksBlocked} task(s) blocked — missing identifiers or target files`:void 0,tasksChecked,tasksSkipped,tasksBlocked,blockedTasks};if(args2.writeEvidence!==!1)try{let evidenceDir=path326.join(directory,".swarm","evidence",`${phase}`),evidencePath2=path326.join(evidenceDir,"completion-verify.json");fs189.mkdirSync(evidenceDir,{recursive:!0});let evidenceBundle={schema_version:"1.0.0",task_id:"completion-verify",created_at:now2,entries:[{task_id:"completion-verify",type:"completion_verify",timestamp:now2,agent:"completion_verify",verdict:tasksBlocked===0?"pass":"fail",summary:buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked),phase,tasks_checked:tasksChecked,tasks_skipped:tasksSkipped,tasks_blocked:tasksBlocked,blocked_tasks:blockedTasks}]};fs189.writeFileSync(evidencePath2,JSON.stringify(evidenceBundle,null,2),"utf-8"),invalidateCachedArtifact(evidencePath2)}catch{}return JSON.stringify(result,null,2)}var completion_verify=createSwarmTool({description:"Deterministic pre-check verifying that plan task identifiers exist in their target source files before phase completion. Blocks if obviously incomplete.",args:{phase:exports_external.number().describe("The phase number to check"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},execute:async(args2,directory)=>{let parsedArgs;try{if(args2&&typeof args2==="object"){let obj=args2;parsedArgs={phase:typeof obj.phase==="number"?obj.phase:typeof obj.phase==="string"?Number(obj.phase):0,sessionID:typeof obj.sessionID==="string"?obj.sessionID:void 0,working_directory:typeof obj.working_directory==="string"?obj.working_directory:void 0}}else parsedArgs={phase:0}}catch{return JSON.stringify({success:!1,phase:0,status:"blocked",reason:"Invalid arguments",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let dirResult=resolveWorkingDirectory(parsedArgs.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:parsedArgs.phase,status:"blocked",reason:dirResult.message,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);return executeCompletionVerify(parsedArgs,dirResult.directory)}});init_zod();init_metrics();init_bun_compat();init_git_executable();init_create_tool();init_path_security();import{Buffer as Buffer4}from"node:buffer";import*as fs190 from"node:fs";import*as path327 from"node:path";var MAX_FILE_SIZE_BYTES5=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N2=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N2,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}var _internals279={bunSpawn,resolveGitExecutable},GIT_CHURN_TIMEOUT_MS=1e4,GIT_CHURN_MAX_BUFFER_BYTES=5242880;async function getGitChurn(days,directory,abortSignal){let churnMap=new Map,proc=_internals279.bunSpawn([_internals279.resolveGitExecutable(),"log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",stdin:"ignore",cwd:directory,timeout:GIT_CHURN_TIMEOUT_MS,maxBuffer:GIT_CHURN_MAX_BUFFER_BYTES,killProcessTree:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),churnTimeout,churnAbortCleanup,racers=[Promise.all([proc.stdout.text(),proc.exited]).then((churnOutput)=>churnOutput),new Promise((resolve129)=>{churnTimeout=setTimeout(()=>resolve129([null,"timeout"]),GIT_CHURN_TIMEOUT_MS)})];if(abortSignal!==void 0)racers.push(new Promise((resolve129)=>{let settle2=()=>resolve129([null,"aborted"]);if(abortSignal.aborted){settle2();return}let onAbort=()=>settle2();abortSignal.addEventListener("abort",onAbort,{once:!0}),churnAbortCleanup=()=>{abortSignal.removeEventListener("abort",onAbort)}}));try{let[stdout,outcome]=await Promise.race(racers);if(typeof churnTimeout<"u")clearTimeout(churnTimeout);if(outcome==="timeout")throw Error(`git churn analysis failed: git log did not finish within ${GIT_CHURN_TIMEOUT_MS} ms (bounded; child tree killed)`);if(outcome==="aborted")throw Error(`git churn analysis failed: aborted by host cancellation (ctx.abort fired before the ${GIT_CHURN_TIMEOUT_MS} ms deadline; child tree killed)`);if(proc.spawnError)throw Error(`git churn analysis failed: ${proc.spawnError.message}`);if(proc.signalCode)throw Error(`git churn analysis failed: git log was killed by ${proc.signalCode} after exceeding the ${GIT_CHURN_TIMEOUT_MS} ms / ${GIT_CHURN_MAX_BUFFER_BYTES}-byte bound`);if(Buffer4.byteLength(stdout)>=GIT_CHURN_MAX_BUFFER_BYTES)throw Error(`git churn analysis failed: git log output reached the ${GIT_CHURN_MAX_BUFFER_BYTES}-byte buffer limit`);let lines=stdout.split(/\r?\n/);for(let line of lines){let normalizedPath=line.replace(/\\/g,"/");if(!normalizedPath||normalizedPath.trim()==="")continue;if(normalizedPath.includes("node_modules")||normalizedPath.includes("/.git/")||normalizedPath.includes("/dist/")||normalizedPath.includes("/build/")||normalizedPath.includes("__tests__"))continue;if(normalizedPath.includes(".test.")||normalizedPath.includes(".spec."))continue;churnMap.set(normalizedPath,(churnMap.get(normalizedPath)||0)+1)}}finally{if(typeof churnTimeout<"u")clearTimeout(churnTimeout);churnAbortCleanup?.();try{proc.kill()}catch{}}return churnMap}function getComplexityForFile2(filePath){try{if(fs190.statSync(filePath).size>MAX_FILE_SIZE_BYTES5)return null;let content=fs190.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory,abortSignal){let churnMap=await getGitChurn(days,directory,abortSignal),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count4]of churnMap){let ext=path327.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count4)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs190.existsSync(fullPath))fullPath=path327.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory,ctx){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory,ctx?.abort);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config2();init_schema();init_miner();init_miner();init_store4();async function mineAndStoreConsensusV1(options){let priorFingerprints=options.deps.priorFingerprints??await listConsensusProposalFingerprints(options.directory),result=await mineConsensus(options.directory,options.request,{...options.deps,priorFingerprints}),report=await writeConsensusReport(options.directory,result.report);return{...result,report}}init_store4();init_memory();init_recommendation_ledger();init_state();init_logger();init_create_tool();var MAX_FILTER_ENTRIES=200,FilterListSchema=exports_external.array(exports_external.string().min(1).max(512)).max(MAX_FILTER_ENTRIES),MAX_INLINE_ATTRIBUTES=25;function countSummaries(attributes,inlineLimit){let total=0,shown=0;for(let[index,attribute]of attributes.entries()){if(attribute.llmSummary===void 0)continue;if(total+=1,index<inlineLimit)shown+=1}return{total,hidden:total-shown}}function buildMinerRecommendationCandidates(report,sessionId){return report.proposals.map((proposal)=>({kind:"miner",target:proposal.target,statement:proposal.intent,scopeKeys:[],provenance:{mechanism:"consensus_mine",sourceEvidenceRefs:proposal.evidenceRefs,sourceRunIds:proposal.provenance.sourceRunIds,sourceModelIds:proposal.provenance.sourceModelIds,sourceTaskIds:proposal.provenance.sourceTaskIds},origin:{agentRole:"consensus_mine",...sessionId?{sessionId}:{},producedAt:report.generatedAt}}))}var MIRRORED_PROPOSAL_KIND="todo";async function mirrorProposalsToMemory(options){if(options.memoryConfig?.enabled!==!0)return{enabled:!1,attempted:0,proposed:0,rejected:0,failed:0};let proposals=options.report.proposals;if(proposals.length===0)return{enabled:!0,attempted:0,proposed:0,rejected:0,failed:0};let gateway;try{gateway=_internals280.createMemoryGateway({directory:options.directory,...options.sessionId?{sessionID:options.sessionId,runId:options.sessionId}:{},agentRole:"consensus_mine"},{config:options.memoryConfig})}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[consensus_mine] memory mirror unavailable (fail-open): ${message}`),{enabled:!0,attempted:proposals.length,proposed:0,rejected:0,failed:proposals.length,error:message}}let proposed=0,rejected2=0,failed=0,error93;try{for(let proposal of proposals)try{if((await gateway.propose({operation:"add",kind:MIRRORED_PROPOSAL_KIND,text:proposal.intent,rationale:`consensus_mine proposal from report ${options.report.reportId}, attribute ${proposal.sourceAttributeId} (target ${proposal.target}, confidence ${proposal.confidence})`,evidenceRefs:proposal.evidenceRefs})).status==="rejected")rejected2+=1;else proposed+=1}catch(err){failed+=1,error93??=err instanceof Error?err.message:String(err)}}finally{try{await gateway.dispose()}catch(err){warn(`[consensus_mine] memory gateway dispose failed: ${err instanceof Error?err.message:String(err)}`)}}if(error93!==void 0)warn(`[consensus_mine] memory mirror partially failed: ${error93}`);return{enabled:!0,attempted:proposals.length,proposed,rejected:rejected2,failed,...error93?{error:error93}:{}}}var _internals280={createMemoryGateway};var consensus_mine=createSwarmTool({description:"Mine cross-run consensus from existing .swarm evidence — evaluation runs, gate audits, gate "+"ground truth, task trajectories, PRM sessions, skill usage, knowledge outcomes, evidence "+"bundles, and curated failures (nine sources) — and persist an immutable report of "+`agreed-upon attributes plus proposals-only recommendations. It never activates a skill, writes a knowledge entry, admits a durable memory record, edits a project file, or mutates any evidence it reads. It is NOT otherwise write-minimal, so plan for these effects: it DELETES its own older reports past consensus.report_retention (default 50) on every run; it rewrites the shared recommendation dedup ledger whole, with FIFO eviction that can drop another producer's oldest entries; it leaves one never-removed lock sentinel per report id under .swarm/locks/; when memory.enabled is true it mirrors each proposal into a PENDING swarm-memory proposal (curator review still required); and when consensus.llm_summarization_enabled is true (the default) it issues up to ${MAX_LLM_SUMMARIES} session.create plus session.prompt calls. Under a knowledge or memory link the ledger and the memory store resolve to the shared cohort root, outside this project's .swarm/.`,args:{run_ids:FilterListSchema.optional().describe("Restrict mining to these run ids (raw or namespaced). Omit for all runs."),task_categories:FilterListSchema.optional().describe("Restrict to these evaluation task categories. Omit for all categories."),agent_roles:FilterListSchema.optional().describe("Restrict to these agent roles. Omit for all roles."),model_ids:FilterListSchema.optional().describe("Restrict to these model ids. Omit for all models."),min_support:exports_external.number().int().min(1).max(1e4).optional().describe("Distinct runs required to emit an attribute. Defaults to consensus.default_min_support."),min_successful_runs:exports_external.number().int().min(0).max(1e4).optional().describe("Successful runs required. Defaults to consensus.default_min_successful_runs."),max_evidence_items:exports_external.number().int().min(1).max(1e4).optional().describe("Cap on corpus observations read. Defaults to consensus.default_max_evidence_items.")},execute:async(args2,directory,ctx)=>{let input=args2??{},loaded=loadPluginConfigWithMeta(directory),config3=ConsensusConfigSchema.parse(loaded.config.consensus??{});if(!config3.enabled)return JSON.stringify({success:!1,disabled:!0,message:"Consensus mining is disabled (consensus.enabled = false). No report was written."},null,2);let request={...input.run_ids?{runIds:input.run_ids}:{},...input.task_categories?{taskCategories:input.task_categories}:{},...input.agent_roles?{agentRoles:input.agent_roles}:{},...input.model_ids?{modelIds:input.model_ids}:{},minSupport:input.min_support??config3.default_min_support,minSuccessfulRuns:input.min_successful_runs??config3.default_min_successful_runs,maxEvidenceItems:input.max_evidence_items??config3.default_max_evidence_items},client=swarmState.opencodeClient,dispatcher=config3.llm_summarization_enabled&&client?createEvaluationModelDispatcher(client):void 0,result=await mineAndStoreConsensusV1({directory,request,deps:{config:config3,...dispatcher?{dispatcher}:{},...ctx?.sessionID?{sessionId:ctx.sessionID}:{},agentRole:"consensus_mine"}}),report=result.report,ledger=await recordEmittedRecommendations(directory,buildMinerRecommendationCandidates(report,ctx?.sessionID),{producedAt:report.generatedAt});if(ledger.degraded)warn("[consensus_mine] recommendation ledger write degraded; proposals were not recorded for cross-producer dedup");let memoryMirror=await mirrorProposalsToMemory({directory,memoryConfig:loaded.config.memory,report,...ctx?.sessionID?{sessionId:ctx.sessionID}:{}}),pruned=await pruneConsensusReports(directory,config3.report_retention),pruningEnabled=config3.report_retention>0,summaries=countSummaries(report.attributes,MAX_INLINE_ATTRIBUTES);return JSON.stringify({success:!0,report_id:report.reportId,report_path:`.swarm/evolution/consensus/${report.reportId}.json`,generated_at:report.generatedAt,integrity_hash:report.integrityHash,config_hash:report.configHash,redaction_policy_version:report.redactionPolicyVersion,thresholds:{min_support:request.minSupport,min_successful_runs:request.minSuccessfulRuns,max_evidence_items:request.maxEvidenceItems,min_task_diversity:MIN_TASK_DIVERSITY_FOR_PROPOSAL,min_support_for_proposal:MIN_SUPPORT_FOR_PROPOSAL},input_run_count:report.inputIds.length,corpus:report.corpusHashes.map((entry)=>({source:entry.source,observations:entry.observations})),corpus_truncated:result.truncated,truncation:{corpus:report.truncation.corpus,observations_tallied:report.truncation.observations,input_ids_truncated:report.truncation.inputIds,total_input_ids:report.truncation.totalInputIds,attributes_dropped:report.truncation.attributesDropped},unreadable_sources:result.unreadableSources,attribute_count:report.attributes.length,investigation_note_count:result.investigationNoteCount,proposal_count:report.proposals.length,deduped_proposal_count:result.dedupedProposalCount,recommendation_ledger:{recorded:ledger.recorded,duplicate_recommendation_count:ledger.suppressed,evicted:ledger.evicted,degraded:ledger.degraded},memory_mirror:memoryMirror,summarized_count:summaries.total,summarized_but_not_shown:summaries.hidden,restatements_accepted_this_run:result.summarizedCount,...result.summarizationSkippedReason?{summarization_skipped_reason:result.summarizationSkippedReason}:{},attributes:report.attributes.slice(0,MAX_INLINE_ATTRIBUTES).map((attribute)=>({id:attribute.id,statement:attribute.statement,...attribute.llmSummary?{llm_summary:attribute.llmSummary}:{},support:attribute.support,success_support:attribute.successSupport,failure_support:attribute.failureSupport,task_diversity:attribute.taskDiversity,model_diversity:attribute.modelDiversity,confidence:attribute.confidence,proposed_target:attribute.proposedTarget,counterexample_count:attribute.counterexampleRefs.length})),attributes_truncated:report.attributes.length>MAX_INLINE_ATTRIBUTES,retention:pruningEnabled?{configured:config3.report_retention,pruning_enabled:!0,deleted:pruned.deleted.length,retained:pruned.retained.length,failed:pruned.failed.length,corrupt:pruned.corrupt.length}:{configured:config3.report_retention,pruning_enabled:!1,deleted:0,failed:0},guarantees:["proposals only — no skill activation, no knowledge write, no durable memory record, and no mutation of any evidence read",'model_diversity 0 means "not measurable from this corpus", never "measured as none"',`attributes below task diversity ${MIN_TASK_DIVERSITY_FOR_PROPOSAL} or below support ${MIN_SUPPORT_FOR_PROPOSAL} are investigation notes, never proposals`,"an attribute counting failing runs always carries counterexample refs (schema-enforced)","truncation is not biased toward successes, but it is still a cut: it balances per source, and drops whole sources once the budget is spent","statement is deterministic; llm_summary is an optional restatement excluded from integrity_hash","reproducible: identical corpus, request, config_hash, and prior proposals yield the same integrity_hash and report_id; model wording never moves it",'truncation is declared on the report; read failure_support 0 on a truncated report as "none survived the cut"']},null,2)}});init_config2();init_model_limits();init_state();init_create_tool();var _internals281={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={},liveContextLimit,modelIdentity,directory){let{modelID,providerID}=modelIdentity??extractModelInfo(messages),modelLimitResolution=resolveModelLimit(modelID,providerID,modelLimitsConfig,liveContextLimit,directory),modelLimit=modelLimitResolution.limit,usage=computeContextUsage(messages),usagePercent=usage.tokensUsed/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:usage.tokensUsed,usageSource:usage.source,modelLimit,modelLimitSource:modelLimitResolution.source,modelLimitResolution:modelLimitResolution.resolution,fallbackActive:modelLimitResolution.source==="provider_cap"||modelLimitResolution.source==="native"||modelLimitResolution.source==="fallback",usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({allowWorkingDirectoryOverride:!0,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.",args:{},async execute(_args,directory,ctx){let config3=_internals281.loadPluginConfig(directory),warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,modelLimitsConfig=config3.context_budget?.model_limits??{},messages=[];if(ctx?.sessionID){let sessionMessages=await _internals281.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let{modelID,providerID}=getLiveContextModelIdentity(ctx?.sessionID)??extractModelInfo(messages),headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig,getLiveContextWindow(ctx?.sessionID,{modelID,providerID}),{modelID,providerID},directory);return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;pushAdvisory(session,`${header}
|
|
7587
|
+
${repairStep()}`}}init_logger();init_task_id();init_create_tool();init_resolve_working_directory();var EVIDENCE_DIR=".swarm/evidence";function isValidTaskId4(taskId){return isStrictTaskId(taskId)}function isPathWithinSwarm(filePath,workspaceRoot){let normalizedWorkspace=path325.resolve(workspaceRoot),swarmPath3=path325.join(normalizedWorkspace,".swarm","evidence");return path325.resolve(filePath).startsWith(swarmPath3)}function readEvidenceFile(evidencePath2){if(!fs188.existsSync(evidencePath2))return null;let content;try{content=fs188.readFileSync(evidencePath2,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(content)}catch{return null}if(parsed&&typeof parsed==="object"&&Array.isArray(parsed.required_gates)&&typeof parsed.gates==="object"&&parsed.gates!==null)return parsed;return null}var check_gate_status=createSwarmTool({description:"Read-only tool to check the gate status of a specific task. Reads .swarm/evidence/{taskId}.json and returns structured JSON describing required, passed, and missing gates.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "1.2.3", "1.2.3.4")').describe('The task ID to check gate status for (e.g., "1.1", "2.3.1")'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/evidence/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let taskIdInput,workingDirInput;try{if(args2&&typeof args2==="object"){let obj=args2;taskIdInput=typeof obj.task_id==="string"?obj.task_id:void 0,workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}}catch{}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={taskId:taskIdInput??"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:dirResult.message,todo_scan:null};return JSON.stringify(errorResult,null,2)}directory=dirResult.directory;let todoGateConfig;try{todoGateConfig=loadPluginConfigWithMeta(directory).config.todo_gate}catch(configError){log("check_gate_status: todo_gate config load threw; TODO gate evaluation skipped",configError)}if(!taskIdInput)return JSON.stringify({taskId:"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid task_id: task_id is required",todo_scan:null},null,2);if(!isValidTaskId4(taskIdInput)){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`Invalid task_id format: "${taskIdInput}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3", "1.2.3.4")`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let evidencePath2=path325.join(directory,EVIDENCE_DIR,`${taskIdInput}.json`);if(!isPathWithinSwarm(evidencePath2,directory))return JSON.stringify({taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid path: evidence path validation failed",todo_scan:null},null,2);let evidenceData=readEvidenceFile(evidencePath2);if(!evidenceData){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`No evidence file found for task "${taskIdInput}" at ${evidencePath2}. Evidence file may be missing or invalid.`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let gatesMap=evidenceData.gates||{},authoritativeWorkflow=evidenceData.workflow?.schema===TASK_WORKFLOW_SCHEMA_MARKER,derivedGates=deriveApplicableGateSet(evidenceData,authoritativeWorkflow?{currentDeclaredFiles:readCurrentTaskDeclaredFiles(directory,taskIdInput)}:void 0),requiredGates=derivedGates.requiredGates,passedGates=derivedGates.satisfiedGates,missingGates=derivedGates.missingGates,readOnlyNoMutation=derivedGates.readOnlyNoMutation,status2=missingGates.length===0&&(readOnlyNoMutation||evidenceData.workflow?.state==="tests_run"||evidenceData.workflow?.state==="complete")?"all_passed":"incomplete",message;if(status2==="all_passed")message=`All required gates have passed for task "${taskIdInput}".`;else if(requiredGates.length===0)message=`Task "${taskIdInput}" is incomplete. No required gates are configured for this task generation.`;else message=`Task "${taskIdInput}" is incomplete. Missing gates: ${missingGates.join(", ")}.`;let secretscanVerdict="not_run";try{let evidenceResult=await loadEvidence(directory,taskIdInput);if(evidenceResult.status==="found"){let secretscanEntries=evidenceResult.bundle.entries.filter((entry)=>entry.type==="secretscan");if(secretscanEntries.length>0){let lastSecretscan=secretscanEntries[secretscanEntries.length-1];if(isSecretscanEvidence(lastSecretscan)){let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=lastSecretscan,findingsCount=lastSecretscan.findings_count??0,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,newFindingsRaw=lastSecretscan.new_findings_count,preexistingRaw=lastSecretscan.preexisting_findings_count,newFindingsValid=typeof newFindingsRaw==="number"&&Number.isSafeInteger(newFindingsRaw)&&newFindingsRaw>=0,preexistingValid=typeof preexistingRaw==="number"&&Number.isSafeInteger(preexistingRaw)&&preexistingRaw>=0,newFindingsBasis=newFindingsValid?newFindingsRaw:findingsCount;if(newFindingsValid&&preexistingValid&&newFindingsRaw+preexistingRaw!==findingsCount)newFindingsBasis=findingsCount;let hasNewFindings=newFindingsBasis>0,policySkipped=lastSecretscan.policy_skipped_files,requestedFilesCount=lastSecretscan.requested_files,vacuousCoverage=lastSecretscan.files_scanned===0&&typeof policySkipped==="number"&&Number.isSafeInteger(policySkipped)&&policySkipped>=0&&typeof requestedFilesCount==="number"&&Number.isSafeInteger(requestedFilesCount)&&requestedFilesCount>0&&policySkipped>=requestedFilesCount&&findingsCount===0&&incompleteFiles===0&&incompletePaths.length===0,hasZeroCoverage=lastSecretscan.files_scanned===0&&!vacuousCoverage;if(hasIncompleteCoverage||hasNewFindings||hasZeroCoverage||lastSecretscan.verdict==="fail"||lastSecretscan.verdict==="rejected")if(secretscanVerdict="fail",hasIncompleteCoverage&&!hasNewFindings){if(missingGates.push("secretscan (BLOCKED — incomplete coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan incomplete coverage in prior scan. ${message}`}else if(hasNewFindings&&hasIncompleteCoverage){if(missingGates.push("secretscan (BLOCKED — secrets detected; incomplete coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan found secrets and incomplete coverage in prior scan (${newFindingsBasis} new on changed lines). ${message}`}else if(hasNewFindings){if(missingGates.push("secretscan (BLOCKED — secrets detected)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan found secrets in prior scan (${newFindingsBasis} new on changed lines${findingsCount>newFindingsBasis?`, ${findingsCount} total`:""}). ${message}`}else if(hasZeroCoverage){if(missingGates.push("secretscan (BLOCKED — zero coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan scanned zero files in prior scan. ${message}`}else{if(missingGates.push("secretscan (BLOCKED — zero coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan verdict failed without new findings or coverage gaps (possible truncation or tampering). ${message}`}else if(lastSecretscan.verdict==="pass"||lastSecretscan.verdict==="approved"||lastSecretscan.verdict==="info"){if(secretscanVerdict="pass",vacuousCoverage)message+=` Advisory: Secretscan coverage was vacuous (${lastSecretscan.policy_skipped_files} of ${lastSecretscan.requested_files} requested file(s) skipped by scan policy).`;else if(findingsCount>0)message+=` Advisory: ${findingsCount} pre-existing secret finding(s) remain visible (non-gating; secretscan green = zero new secrets on changed lines).`}}}else message+=" Advisory: No secretscan evidence found for this task. Consider running secretscan."}else if(evidenceResult.status==="invalid_schema")secretscanVerdict="fail",missingGates.push("secretscan (BLOCKED — invalid evidence)"),status2="incomplete",message=`BLOCKED: Secretscan evidence is invalid and cannot prove complete coverage. ${message}`}catch{}let todoScan=evidenceData.todo_scan,todoVerdict=evaluateTodoGate(todoScan,todoGateConfig);if(todoVerdict.status==="exceeded")if(todoVerdict.blocked){if(missingGates.push(`todo_gate (BLOCKED — ${todoVerdict.count} high-priority TODOs exceed max ${todoVerdict.max})`),status2==="all_passed")status2="incomplete";message=`BLOCKED: TODO gate threshold exceeded. ${todoVerdict.message} ${message}`}else message+=` Advisory: todo_gate threshold exceeded — ${todoVerdict.count} high-priority TODOs (FIXME/HACK/XXX) exceed max_high_priority=${todoVerdict.max}.`;let workflowMeta=evidenceData.workflow&&typeof evidenceData.workflow==="object"&&typeof evidenceData.workflow.state==="string"?{state:evidenceData.workflow.state,generation:typeof evidenceData.workflow.generation==="number"?evidenceData.workflow.generation:0}:null,workflowAttributionHint;if(status2==="incomplete"&&workflowMeta?.state==="coder_delegated"&&!gatesMap.pre_check)workflowAttributionHint="Task is settled at coder_delegated but Stage A (pre_check_batch) was never attributed — "+`reviewer/test_engineer dispatches will be denied with TASK_WORKFLOW_STAGE_A_REQUIRED. Run pre_check_batch on the task's changed files; if it passes without advancing this task, run /swarm recover ${taskIdInput}.`,message+=` ${workflowAttributionHint}`;let result={taskId:taskIdInput,status:status2,required_gates:requiredGates,passed_gates:passedGates,missing_gates:missingGates,gates:gatesMap,message,todo_scan:todoScan??null,secretscan_verdict:secretscanVerdict,workflow:workflowMeta,...workflowAttributionHint?{workflow_attribution_hint:workflowAttributionHint}:{}};return JSON.stringify(result,null,2)}});init_checkpoint();init_co_change_analyzer();init_zod();init_loader();init_pr_workflow_gate();init_create_tool();var CompletePrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),pr_head_sha:exports_external.string().trim().min(1).max(80),report_verdict:exports_external.enum(["APPROVE","REQUEST_CHANGES","INCOMPLETE"]).optional()}).strict().superRefine((value,ctx)=>{if(value.mode==="PR_REVIEW"&&value.report_verdict===void 0)ctx.addIssue({code:"custom",path:["report_verdict"],message:"is required for PR_REVIEW completion (issue #2383 terminal report)"})});async function executeCompletePrWorkflow(args2,directory,context={}){let parsed=CompletePrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow completion: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow completion requires an active sessionID"});let staleDisclosure={},laneLiveness;try{let config3=loadPluginConfig(directory),hooks2=config3.hooks;laneLiveness={laneLivenessWatchdog:config3.lane_liveness_watchdog,backgroundPendingTimeoutMs:hooks2?.background_pending_timeout_minutes!==void 0?hooks2.background_pending_timeout_minutes*60000:void 0}}catch{}try{let settlement=await _internals278.settlePresumedStalePrWorkflowLanes(directory,context.sessionID,laneLiveness);if(settlement.presumedStaleLaneIds.length>0)staleDisclosure={presumed_stale_lanes:settlement.presumedStaleLaneIds,presumed_stale_disclosure:settlement.disclosure};if(settlement.probedAliveLaneIds?.length)staleDisclosure.probe_retained_lanes=settlement.probedAliveLaneIds;if(settlement.probeDegradedReason)staleDisclosure.probe_status=settlement.probeDegradedReason;if(settlement.horizonConflictNote)staleDisclosure.horizon_conflict=settlement.horizonConflictNote}catch{}let amendmentDisclosure={};try{let gateState=await _internals278.readPrWorkflowGateState(directory,context.sessionID);if(gateState?.prFeedbackInventoryAmendments?.length)amendmentDisclosure={inventory_amendments:gateState.prFeedbackInventoryAmendments}}catch{}try{let terminalReport;if(parsed.data.mode==="PR_REVIEW"){let coverage=null;try{coverage=await _internals278.readPrReviewTerminalCoverageForReport(directory,context.sessionID)}catch{}if(coverage){let findingPolicy;try{findingPolicy=await _internals278.readPrReviewFinalFindingPolicyForReport(directory,context.sessionID)}catch{}terminalReport={kind:coverage.kind,covered_dimensions:coverage.coveredDimensions,unresolved_dimensions:coverage.unresolvedDimensions,live_dimensions:coverage.liveDimensions,allowed_verdicts:findingPolicy?.permittedVerdicts??coverage.allowedVerdicts,...findingPolicy?{finding_policy_version:findingPolicy.policyVersion,blocking_finding_ids:findingPolicy.blockingFindingIds}:{},report_verdict:parsed.data.report_verdict}}}let status2=await _internals278.completePrWorkflow(directory,context.sessionID,parsed.data.mode,parsed.data.pr_head_sha,parsed.data.mode==="PR_REVIEW"?{reportVerdict:parsed.data.report_verdict,...laneLiveness?{laneLiveness}:{}}:laneLiveness?{laneLiveness}:void 0),checkoutRestoreRequired=!1,checkoutRestoreReceipts=[];if(status2==="completed")try{checkoutRestoreReceipts=await _internals278.listPendingPrWorkflowCheckoutRestores(directory,context.sessionID),checkoutRestoreRequired=checkoutRestoreReceipts.length>0}catch{checkoutRestoreRequired=!0}return JSON.stringify({success:!0,mode:parsed.data.mode,pr_head_sha:parsed.data.pr_head_sha,status:status2,ready_to_publish:status2==="ready-to-publish",verified_no_change:status2==="verified-no-change",gate_cleared:status2==="completed"||status2==="verified-no-change",checkout_restore_required:checkoutRestoreRequired,checkout_restore_receipts:checkoutRestoreReceipts,...terminalReport?{terminal_report:terminalReport}:{},...staleDisclosure,...amendmentDisclosure})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93),...staleDisclosure,...amendmentDisclosure})}}var complete_pr_workflow=createSwarmTool({description:"Validate terminal PR workflow coverage. After the ordered PR_FEEDBACK gates permit one standalone commit, the first call requires a clean tree and a non-merge direct child of intake HEAD, then binds its structured upstream target; the second clears only after both the local tracking ref and an actual-remote query point to that exact commit. A cleared result reports checkout_restore_required when preserved pre-workflow changes must be restored.",args:{mode:CompletePrWorkflowArgsSchema.shape.mode,pr_head_sha:CompletePrWorkflowArgsSchema.shape.pr_head_sha,report_verdict:CompletePrWorkflowArgsSchema.shape.report_verdict},execute:executeCompletePrWorkflow}),_internals278={completePrWorkflow,listPendingPrWorkflowCheckoutRestores,readPrWorkflowGateState,readPrReviewTerminalCoverageForReport,readPrReviewFinalFindingPolicyForReport,settlePresumedStalePrWorkflowLanes};init_zod();init_utils2();init_state();init_swarm_artifact_cache();init_create_tool();init_resolve_working_directory();import*as fs189 from"node:fs";import*as path326 from"node:path";function extractMatches(regex,text){return Array.from(text.matchAll(regex))}function parseIdentifiers(description){let identifiers=new Set,backtickRegex=/`([^`]+)`/g;for(let match of extractMatches(backtickRegex,description))identifiers.add(match[1]);let camelCaseRegex=/\b([a-z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(camelCaseRegex,description)){let word=match[1];if(word==="the"||word==="and"||word==="for"||word==="have"||word==="this"||word==="with"||word==="from"||word==="they"||word==="been"||word==="will"||word==="your"||word==="also")continue;identifiers.add(word)}let pascalCaseRegex=/\b([A-Z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(pascalCaseRegex,description))identifiers.add(match[1]);let configKeyRegex=/\b([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+)\b/g;for(let match of extractMatches(configKeyRegex,description))identifiers.add(match[1]);let quotedPathRegex=/['"](\.{0,3}(?:src|lib|test)[/\\][^'"]+)['"]/g;for(let match of extractMatches(quotedPathRegex,description))identifiers.add(match[1]);return Array.from(identifiers)}function parseFilePaths(description,filesTouched){if(filesTouched&&Array.isArray(filesTouched)&&filesTouched.length>0)return filesTouched;let filePaths=[],srcPathRegex=/\b(?:src|lib|test|app|packages?)[/\\][a-zA-Z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)\b/g;for(let match of extractMatches(srcPathRegex,description))filePaths.push(match[0]);let genericPathRegex=/\b[a-zA-Z0-9_./-]+[/\\][a-zA-Z0-9_./-]+\.[a-zA-Z0-9]+(?=\s|$|[.,;])/g;for(let match of extractMatches(genericPathRegex,description)){let pathStr=match[0];if(pathStr.includes("src/")||pathStr.includes("src\\")||pathStr.includes("lib/")||pathStr.includes("lib\\")||pathStr.includes("test/")||pathStr.includes("test\\"))filePaths.push(pathStr)}return filePaths}function buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked){if(tasksBlocked>0)return`Blocked: ${tasksBlocked} task(s) with missing identifiers`;let verified=tasksChecked-tasksSkipped;if(tasksSkipped===tasksChecked)return`All ${tasksChecked} completed task(s) skipped — research/inventory tasks`;if(tasksSkipped>0)return`${verified} task(s) verified, ${tasksSkipped} skipped (research tasks)`;return`All ${tasksChecked} completed tasks verified successfully`}async function executeCompletionVerify(args2,directory){let phase=Number(args2.phase);if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase))return JSON.stringify({success:!1,phase,status:"blocked",reason:"Invalid phase number",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);if(hasActiveTurboMode(args2.sessionID))return JSON.stringify({success:!0,phase,status:"passed",reason:"Turbo Mode active — completion verification bypassed",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);let plan;try{let planPath=validateSwarmPath(directory,"plan.json"),planRaw=fs189.readFileSync(planPath,"utf-8");plan=JSON.parse(planRaw)}catch{return JSON.stringify({success:!0,phase,status:"passed",reason:"Cannot verify without plan.json",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let targetPhase=plan.phases.find((p)=>p.id===phase);if(!targetPhase){let result2={success:!1,phase,status:"blocked",reason:`Phase ${phase} not found in plan.json`,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]};return JSON.stringify(result2,null,2)}let tasksChecked=0,tasksSkipped=0,tasksBlocked=0,blockedTasks=[];for(let task2 of targetPhase.tasks){if(task2.status!=="completed")continue;tasksChecked++;let fileTargets=parseFilePaths(task2.description,task2.files_touched),identifiers=parseIdentifiers(task2.description);if(fileTargets.length===0){tasksSkipped++;continue}if(identifiers.length===0){blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers — cannot verify completion without identifiers"}),tasksBlocked++;continue}let foundIdentifiers=new Set,hasFileReadFailure=!1;for(let filePath of fileTargets){let normalizedPath=filePath.replace(/\\/g,"/"),resolvedPath=path326.resolve(directory,normalizedPath),projectRoot=path326.resolve(directory),relative85=path326.relative(projectRoot,resolvedPath);if(!(relative85===""||!relative85.startsWith("..")&&!path326.isAbsolute(relative85))){blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File path '${filePath}' escapes the project directory — cannot verify completion`}),hasFileReadFailure=!0;continue}let fileContent;try{fileContent=fs189.readFileSync(resolvedPath,"utf-8")}catch{blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File '${filePath}' not found — cannot verify completion`}),hasFileReadFailure=!0;continue}for(let identifier of identifiers)if(fileContent.includes(identifier))foundIdentifiers.add(identifier)}let foundCount=foundIdentifiers.size;if(hasFileReadFailure||foundCount===0){if(!hasFileReadFailure)blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers found in target files"});tasksBlocked++}}let now2=new Date().toISOString(),result={success:tasksBlocked===0,phase,status:tasksBlocked===0?"passed":"blocked",reason:tasksBlocked>0?`COMPLETION_INCOMPLETE: ${tasksBlocked} task(s) blocked — missing identifiers or target files`:void 0,tasksChecked,tasksSkipped,tasksBlocked,blockedTasks};if(args2.writeEvidence!==!1)try{let evidenceDir=path326.join(directory,".swarm","evidence",`${phase}`),evidencePath2=path326.join(evidenceDir,"completion-verify.json");fs189.mkdirSync(evidenceDir,{recursive:!0});let evidenceBundle={schema_version:"1.0.0",task_id:"completion-verify",created_at:now2,entries:[{task_id:"completion-verify",type:"completion_verify",timestamp:now2,agent:"completion_verify",verdict:tasksBlocked===0?"pass":"fail",summary:buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked),phase,tasks_checked:tasksChecked,tasks_skipped:tasksSkipped,tasks_blocked:tasksBlocked,blocked_tasks:blockedTasks}]};fs189.writeFileSync(evidencePath2,JSON.stringify(evidenceBundle,null,2),"utf-8"),invalidateCachedArtifact(evidencePath2)}catch{}return JSON.stringify(result,null,2)}var completion_verify=createSwarmTool({description:"Deterministic pre-check verifying that plan task identifiers exist in their target source files before phase completion. Blocks if obviously incomplete.",args:{phase:exports_external.number().describe("The phase number to check"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},execute:async(args2,directory)=>{let parsedArgs;try{if(args2&&typeof args2==="object"){let obj=args2;parsedArgs={phase:typeof obj.phase==="number"?obj.phase:typeof obj.phase==="string"?Number(obj.phase):0,sessionID:typeof obj.sessionID==="string"?obj.sessionID:void 0,working_directory:typeof obj.working_directory==="string"?obj.working_directory:void 0}}else parsedArgs={phase:0}}catch{return JSON.stringify({success:!1,phase:0,status:"blocked",reason:"Invalid arguments",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let dirResult=resolveWorkingDirectory(parsedArgs.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:parsedArgs.phase,status:"blocked",reason:dirResult.message,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);return executeCompletionVerify(parsedArgs,dirResult.directory)}});init_zod();init_metrics();init_bun_compat();init_git_executable();init_create_tool();init_path_security();import{Buffer as Buffer4}from"node:buffer";import*as fs190 from"node:fs";import*as path327 from"node:path";var MAX_FILE_SIZE_BYTES5=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N2=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N2,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}var _internals279={bunSpawn,resolveGitExecutable},GIT_CHURN_TIMEOUT_MS=1e4,GIT_CHURN_MAX_BUFFER_BYTES=5242880;async function getGitChurn(days,directory,abortSignal){let churnMap=new Map,proc=_internals279.bunSpawn([_internals279.resolveGitExecutable(),"log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",stdin:"ignore",cwd:directory,timeout:GIT_CHURN_TIMEOUT_MS,maxBuffer:GIT_CHURN_MAX_BUFFER_BYTES,killProcessTree:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),churnTimeout,churnAbortCleanup,racers=[Promise.all([proc.stdout.text(),proc.exited]).then((churnOutput)=>churnOutput),new Promise((resolve129)=>{churnTimeout=setTimeout(()=>resolve129([null,"timeout"]),GIT_CHURN_TIMEOUT_MS)})];if(abortSignal!==void 0)racers.push(new Promise((resolve129)=>{let settle2=()=>resolve129([null,"aborted"]);if(abortSignal.aborted){settle2();return}let onAbort=()=>settle2();abortSignal.addEventListener("abort",onAbort,{once:!0}),churnAbortCleanup=()=>{abortSignal.removeEventListener("abort",onAbort)}}));try{let[stdout,outcome]=await Promise.race(racers);if(typeof churnTimeout<"u")clearTimeout(churnTimeout);if(outcome==="timeout")throw Error(`git churn analysis failed: git log did not finish within ${GIT_CHURN_TIMEOUT_MS} ms (bounded; child tree killed)`);if(outcome==="aborted")throw Error(`git churn analysis failed: aborted by host cancellation (ctx.abort fired before the ${GIT_CHURN_TIMEOUT_MS} ms deadline; child tree killed)`);if(proc.spawnError)throw Error(`git churn analysis failed: ${proc.spawnError.message}`);if(proc.signalCode)throw Error(`git churn analysis failed: git log was killed by ${proc.signalCode} after exceeding the ${GIT_CHURN_TIMEOUT_MS} ms / ${GIT_CHURN_MAX_BUFFER_BYTES}-byte bound`);if(Buffer4.byteLength(stdout)>=GIT_CHURN_MAX_BUFFER_BYTES)throw Error(`git churn analysis failed: git log output reached the ${GIT_CHURN_MAX_BUFFER_BYTES}-byte buffer limit`);let lines=stdout.split(/\r?\n/);for(let line of lines){let normalizedPath=line.replace(/\\/g,"/");if(!normalizedPath||normalizedPath.trim()==="")continue;if(normalizedPath.includes("node_modules")||normalizedPath.includes("/.git/")||normalizedPath.includes("/dist/")||normalizedPath.includes("/build/")||normalizedPath.includes("__tests__"))continue;if(normalizedPath.includes(".test.")||normalizedPath.includes(".spec."))continue;churnMap.set(normalizedPath,(churnMap.get(normalizedPath)||0)+1)}}finally{if(typeof churnTimeout<"u")clearTimeout(churnTimeout);churnAbortCleanup?.();try{proc.kill()}catch{}}return churnMap}function getComplexityForFile2(filePath){try{if(fs190.statSync(filePath).size>MAX_FILE_SIZE_BYTES5)return null;let content=fs190.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory,abortSignal){let churnMap=await getGitChurn(days,directory,abortSignal),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count4]of churnMap){let ext=path327.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count4)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs190.existsSync(fullPath))fullPath=path327.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory,ctx){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory,ctx?.abort);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config2();init_schema();init_miner();init_miner();init_store4();async function mineAndStoreConsensusV1(options){let priorFingerprints=options.deps.priorFingerprints??await listConsensusProposalFingerprints(options.directory),result=await mineConsensus(options.directory,options.request,{...options.deps,priorFingerprints}),report=await writeConsensusReport(options.directory,result.report);return{...result,report}}init_store4();init_memory();init_recommendation_ledger();init_state();init_logger();init_create_tool();var MAX_FILTER_ENTRIES=200,FilterListSchema=exports_external.array(exports_external.string().min(1).max(512)).max(MAX_FILTER_ENTRIES),MAX_INLINE_ATTRIBUTES=25;function countSummaries(attributes,inlineLimit){let total=0,shown=0;for(let[index,attribute]of attributes.entries()){if(attribute.llmSummary===void 0)continue;if(total+=1,index<inlineLimit)shown+=1}return{total,hidden:total-shown}}function buildMinerRecommendationCandidates(report,sessionId){return report.proposals.map((proposal)=>({kind:"miner",target:proposal.target,statement:proposal.intent,scopeKeys:[],provenance:{mechanism:"consensus_mine",sourceEvidenceRefs:proposal.evidenceRefs,sourceRunIds:proposal.provenance.sourceRunIds,sourceModelIds:proposal.provenance.sourceModelIds,sourceTaskIds:proposal.provenance.sourceTaskIds},origin:{agentRole:"consensus_mine",...sessionId?{sessionId}:{},producedAt:report.generatedAt}}))}var MIRRORED_PROPOSAL_KIND="todo";async function mirrorProposalsToMemory(options){if(options.memoryConfig?.enabled!==!0)return{enabled:!1,attempted:0,proposed:0,rejected:0,failed:0};let proposals=options.report.proposals;if(proposals.length===0)return{enabled:!0,attempted:0,proposed:0,rejected:0,failed:0};let gateway;try{gateway=_internals280.createMemoryGateway({directory:options.directory,...options.sessionId?{sessionID:options.sessionId,runId:options.sessionId}:{},agentRole:"consensus_mine"},{config:options.memoryConfig})}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[consensus_mine] memory mirror unavailable (fail-open): ${message}`),{enabled:!0,attempted:proposals.length,proposed:0,rejected:0,failed:proposals.length,error:message}}let proposed=0,rejected2=0,failed=0,error93;try{for(let proposal of proposals)try{if((await gateway.propose({operation:"add",kind:MIRRORED_PROPOSAL_KIND,text:proposal.intent,rationale:`consensus_mine proposal from report ${options.report.reportId}, attribute ${proposal.sourceAttributeId} (target ${proposal.target}, confidence ${proposal.confidence})`,evidenceRefs:proposal.evidenceRefs})).status==="rejected")rejected2+=1;else proposed+=1}catch(err){failed+=1,error93??=err instanceof Error?err.message:String(err)}}finally{try{await gateway.dispose()}catch(err){warn(`[consensus_mine] memory gateway dispose failed: ${err instanceof Error?err.message:String(err)}`)}}if(error93!==void 0)warn(`[consensus_mine] memory mirror partially failed: ${error93}`);return{enabled:!0,attempted:proposals.length,proposed,rejected:rejected2,failed,...error93?{error:error93}:{}}}var _internals280={createMemoryGateway};var consensus_mine=createSwarmTool({description:"Mine cross-run consensus from existing .swarm evidence — evaluation runs, gate audits, gate "+"ground truth, task trajectories, PRM sessions, skill usage, knowledge outcomes, evidence "+"bundles, and curated failures (nine sources) — and persist an immutable report of "+`agreed-upon attributes plus proposals-only recommendations. It never activates a skill, writes a knowledge entry, admits a durable memory record, edits a project file, or mutates any evidence it reads. It is NOT otherwise write-minimal, so plan for these effects: it DELETES its own older reports past consensus.report_retention (default 50) on every run; it rewrites the shared recommendation dedup ledger whole, with FIFO eviction that can drop another producer's oldest entries; it leaves one never-removed lock sentinel per report id under .swarm/locks/; when memory.enabled is true it mirrors each proposal into a PENDING swarm-memory proposal (curator review still required); and when consensus.llm_summarization_enabled is true (the default) it issues up to ${MAX_LLM_SUMMARIES} session.create plus session.prompt calls. Under a knowledge or memory link the ledger and the memory store resolve to the shared cohort root, outside this project's .swarm/.`,args:{run_ids:FilterListSchema.optional().describe("Restrict mining to these run ids (raw or namespaced). Omit for all runs."),task_categories:FilterListSchema.optional().describe("Restrict to these evaluation task categories. Omit for all categories."),agent_roles:FilterListSchema.optional().describe("Restrict to these agent roles. Omit for all roles."),model_ids:FilterListSchema.optional().describe("Restrict to these model ids. Omit for all models."),min_support:exports_external.number().int().min(1).max(1e4).optional().describe("Distinct runs required to emit an attribute. Defaults to consensus.default_min_support."),min_successful_runs:exports_external.number().int().min(0).max(1e4).optional().describe("Successful runs required. Defaults to consensus.default_min_successful_runs."),max_evidence_items:exports_external.number().int().min(1).max(1e4).optional().describe("Cap on corpus observations read. Defaults to consensus.default_max_evidence_items.")},execute:async(args2,directory,ctx)=>{let input=args2??{},loaded=loadPluginConfigWithMeta(directory),config3=ConsensusConfigSchema.parse(loaded.config.consensus??{});if(!config3.enabled)return JSON.stringify({success:!1,disabled:!0,message:"Consensus mining is disabled (consensus.enabled = false). No report was written."},null,2);let request={...input.run_ids?{runIds:input.run_ids}:{},...input.task_categories?{taskCategories:input.task_categories}:{},...input.agent_roles?{agentRoles:input.agent_roles}:{},...input.model_ids?{modelIds:input.model_ids}:{},minSupport:input.min_support??config3.default_min_support,minSuccessfulRuns:input.min_successful_runs??config3.default_min_successful_runs,maxEvidenceItems:input.max_evidence_items??config3.default_max_evidence_items},client=swarmState.opencodeClient,dispatcher=config3.llm_summarization_enabled&&client?createEvaluationModelDispatcher(client):void 0,result=await mineAndStoreConsensusV1({directory,request,deps:{config:config3,...dispatcher?{dispatcher}:{},...ctx?.sessionID?{sessionId:ctx.sessionID}:{},agentRole:"consensus_mine"}}),report=result.report,ledger=await recordEmittedRecommendations(directory,buildMinerRecommendationCandidates(report,ctx?.sessionID),{producedAt:report.generatedAt});if(ledger.degraded)warn("[consensus_mine] recommendation ledger write degraded; proposals were not recorded for cross-producer dedup");let memoryMirror=await mirrorProposalsToMemory({directory,memoryConfig:loaded.config.memory,report,...ctx?.sessionID?{sessionId:ctx.sessionID}:{}}),pruned=await pruneConsensusReports(directory,config3.report_retention),pruningEnabled=config3.report_retention>0,summaries=countSummaries(report.attributes,MAX_INLINE_ATTRIBUTES);return JSON.stringify({success:!0,report_id:report.reportId,report_path:`.swarm/evolution/consensus/${report.reportId}.json`,generated_at:report.generatedAt,integrity_hash:report.integrityHash,config_hash:report.configHash,redaction_policy_version:report.redactionPolicyVersion,thresholds:{min_support:request.minSupport,min_successful_runs:request.minSuccessfulRuns,max_evidence_items:request.maxEvidenceItems,min_task_diversity:MIN_TASK_DIVERSITY_FOR_PROPOSAL,min_support_for_proposal:MIN_SUPPORT_FOR_PROPOSAL},input_run_count:report.inputIds.length,corpus:report.corpusHashes.map((entry)=>({source:entry.source,observations:entry.observations})),corpus_truncated:result.truncated,truncation:{corpus:report.truncation.corpus,observations_tallied:report.truncation.observations,input_ids_truncated:report.truncation.inputIds,total_input_ids:report.truncation.totalInputIds,attributes_dropped:report.truncation.attributesDropped},unreadable_sources:result.unreadableSources,attribute_count:report.attributes.length,investigation_note_count:result.investigationNoteCount,proposal_count:report.proposals.length,deduped_proposal_count:result.dedupedProposalCount,recommendation_ledger:{recorded:ledger.recorded,duplicate_recommendation_count:ledger.suppressed,evicted:ledger.evicted,degraded:ledger.degraded},memory_mirror:memoryMirror,summarized_count:summaries.total,summarized_but_not_shown:summaries.hidden,restatements_accepted_this_run:result.summarizedCount,...result.summarizationSkippedReason?{summarization_skipped_reason:result.summarizationSkippedReason}:{},attributes:report.attributes.slice(0,MAX_INLINE_ATTRIBUTES).map((attribute)=>({id:attribute.id,statement:attribute.statement,...attribute.llmSummary?{llm_summary:attribute.llmSummary}:{},support:attribute.support,success_support:attribute.successSupport,failure_support:attribute.failureSupport,task_diversity:attribute.taskDiversity,model_diversity:attribute.modelDiversity,confidence:attribute.confidence,proposed_target:attribute.proposedTarget,counterexample_count:attribute.counterexampleRefs.length})),attributes_truncated:report.attributes.length>MAX_INLINE_ATTRIBUTES,retention:pruningEnabled?{configured:config3.report_retention,pruning_enabled:!0,deleted:pruned.deleted.length,retained:pruned.retained.length,failed:pruned.failed.length,corrupt:pruned.corrupt.length}:{configured:config3.report_retention,pruning_enabled:!1,deleted:0,failed:0},guarantees:["proposals only — no skill activation, no knowledge write, no durable memory record, and no mutation of any evidence read",'model_diversity 0 means "not measurable from this corpus", never "measured as none"',`attributes below task diversity ${MIN_TASK_DIVERSITY_FOR_PROPOSAL} or below support ${MIN_SUPPORT_FOR_PROPOSAL} are investigation notes, never proposals`,"an attribute counting failing runs always carries counterexample refs (schema-enforced)","truncation is not biased toward successes, but it is still a cut: it balances per source, and drops whole sources once the budget is spent","statement is deterministic; llm_summary is an optional restatement excluded from integrity_hash","reproducible: identical corpus, request, config_hash, and prior proposals yield the same integrity_hash and report_id; model wording never moves it",'truncation is declared on the report; read failure_support 0 on a truncated report as "none survived the cut"']},null,2)}});init_config2();init_model_limits();init_state();init_create_tool();var _internals281={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={},liveContextLimit,modelIdentity,directory){let{modelID,providerID}=modelIdentity??extractModelInfo(messages),modelLimitResolution=resolveModelLimit(modelID,providerID,modelLimitsConfig,liveContextLimit,directory),modelLimit=modelLimitResolution.limit,usage=computeContextUsage(messages),usagePercent=usage.tokensUsed/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:usage.tokensUsed,usageSource:usage.source,modelLimit,modelLimitSource:modelLimitResolution.source,modelLimitResolution:modelLimitResolution.resolution,fallbackActive:modelLimitResolution.source==="provider_cap"||modelLimitResolution.source==="native"||modelLimitResolution.source==="fallback",usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({allowWorkingDirectoryOverride:!0,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.",args:{},async execute(_args,directory,ctx){let config3=_internals281.loadPluginConfig(directory),warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,modelLimitsConfig=config3.context_budget?.model_limits??{},messages=[];if(ctx?.sessionID){let sessionMessages=await _internals281.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let{modelID,providerID}=getLiveContextModelIdentity(ctx?.sessionID)??extractModelInfo(messages),headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig,getLiveContextWindow(ctx?.sessionID,{modelID,providerID}),{modelID,providerID},directory);return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;pushAdvisory(session,`${header}
|
|
7588
7588
|
${body}`,{dedupeKey:dedupKey})}init_zod();init_task_file();init_gate_evidence();init_project_boundary();init_council_review_identity();import{existsSync as existsSync167,mkdirSync as mkdirSync91,readFileSync as readFileSync141}from"node:fs";import{join as join259}from"node:path";var EVIDENCE_DIR2=".swarm/evidence",VALID_TASK_ID=/^\d+\.\d+(\.\d+)*$/,COUNCIL_GATE_NAME="council",COUNCIL_AGENT_ID="architect",EvidenceFileSchema=exports_external.record(exports_external.string(),exports_external.unknown()),_internals282={withTaskEvidenceLock},FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);function safeAssignOwnProps(target,source){for(let key2 of Object.keys(source)){if(FORBIDDEN_KEYS.has(key2))continue;let value=source[key2];if(value!==null&&typeof value==="object"&&!Array.isArray(value)){let nested=Object.create(null);safeAssignOwnProps(nested,value),target[key2]=nested}else if(Array.isArray(value))target[key2]=value.map((item)=>{if(item!==null&&typeof item==="object"&&!Array.isArray(item)){let nested=Object.create(null);return safeAssignOwnProps(nested,item),nested}return item});else target[key2]=value}return target}async function writeCouncilEvidence(workingDir,synthesis,attemptId,expectedGeneration,identity){if(!VALID_TASK_ID.test(synthesis.taskId))throw Error(`writeCouncilEvidence: invalid taskId "${synthesis.taskId}" — must match N.M or N.M.P format`);let dir=join259(workingDir,EVIDENCE_DIR2);assertProjectRoot(workingDir),mkdirSync91(dir,{recursive:!0});let filePath=taskEvidencePath(workingDir,synthesis.taskId);await _internals282.withTaskEvidenceLock(workingDir,synthesis.taskId,COUNCIL_AGENT_ID,async()=>{assertTaskEvidenceWriteAllowed(workingDir,synthesis.taskId);let existingRoot=Object.create(null);if(existsSync167(filePath))try{let raw=readFileSync141(filePath,"utf-8");if(expectedGeneration!==void 0){let exactEvidence=parseTaskEvidence(raw,synthesis.taskId),workflow=getTaskWorkflowSnapshot(exactEvidence);if(!workflow.authoritative||workflow.generation!==expectedGeneration||workflow.state!=="pre_check_passed")throw Error(`TASK_COUNCIL_GENERATION_MISMATCH: expected pre_check_passed@${expectedGeneration}, found ${workflow.state}@${workflow.generation}`)}let parsed=EvidenceFileSchema.parse(JSON.parse(raw));safeAssignOwnProps(existingRoot,parsed)}catch(error93){if(expectedGeneration!==void 0)throw error93}else if(expectedGeneration!==void 0)throw Error(`TASK_COUNCIL_GENERATION_MISMATCH: no exact evidence exists for generation ${expectedGeneration}`);let existingGatesRaw=existingRoot.gates,mergedGates=Object.create(null);if(existingGatesRaw&&typeof existingGatesRaw==="object"&&!Array.isArray(existingGatesRaw))safeAssignOwnProps(mergedGates,existingGatesRaw);mergedGates[COUNCIL_GATE_NAME]={sessionId:synthesis.swarmId,timestamp:synthesis.timestamp,agent:COUNCIL_AGENT_ID,verdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,quorumSize:synthesis.quorumSize,...identity?councilIdentityEvidenceFields(identity):{},...expectedGeneration!==void 0?{workflowGeneration:expectedGeneration}:{},...attemptId?{attemptId}:{}};let updated=Object.create(null);if(safeAssignOwnProps(updated,existingRoot),updated.gates=mergedGates,!updated.taskId)updated.taskId=synthesis.taskId;if(!Array.isArray(updated.required_gates))updated.required_gates=[];await atomicWriteFile(filePath,JSON.stringify(updated,null,2))})}function hasCouncilEvidenceAttempt(workingDir,taskId,attemptId,roundNumber){if(!VALID_TASK_ID.test(taskId))return!1;try{let council=EvidenceFileSchema.parse(JSON.parse(readFileSync141(taskEvidencePath(workingDir,taskId),"utf-8"))).gates?.[COUNCIL_GATE_NAME];return council?.attemptId===attemptId&&council.roundNumber===roundNumber}catch{return!1}}init_council_review_identity();init_lock();init_task_file();import{createHash as createHash107,randomUUID as randomUUID43}from"node:crypto";import{closeSync as closeSync40,existsSync as existsSync168,fsyncSync as fsyncSync11,mkdirSync as mkdirSync92,openSync as openSync40,readFileSync as readFileSync142,readSync as readSync28,statSync as statSync103,writeSync as writeSync7}from"node:fs";import{dirname as dirname121,join as join260}from"node:path";init_telemetry();function scopeIdentityPayload(scope){return{level:scope.kind,...scope.kind==="task"&&scope.taskId!==void 0?{taskId:scope.taskId}:{},...scope.kind==="phase"&&scope.phaseNumber!==void 0?{phase:scope.phaseNumber}:{},identityDigest:scope.identityDigest}}function observeCouncilAuditAppend(scope,sessionID,councilRoundId,record3){try{emit("council_attempt",{...sessionID!==void 0?{sessionId:sessionID}:{},councilRoundId,...scopeIdentityPayload(scope),stage:record3.event,attemptId:record3.attemptId,disposition:record3.disposition,authoritativeRound:record3.authoritativeRound,...record3.clientRound!==void 0?{clientRound:record3.clientRound}:{},verdictCount:record3.verdictCount,memberCount:record3.members.length,...record3.quorumSize!==void 0?{quorumSize:record3.quorumSize}:{},...record3.verdict!==void 0?{verdict:record3.verdict}:{},...record3.transition!==void 0?{transition:record3.transition}:{},...record3.gateEffect!==void 0?{gateEffect:record3.gateEffect}:{}});let next=record3.nextState;if(record3.event!=="received"&&(record3.transition==="advance"||record3.transition==="close")&&next!==void 0)emit("council_round_transition",{...sessionID!==void 0?{sessionId:sessionID}:{},councilRoundId,...scopeIdentityPayload(scope),attemptId:record3.attemptId,transition:record3.transition,gateEffect:record3.gateEffect,round:record3.authoritativeRound,nextRound:next.currentRound,roundStatus:next.status,maxRoundsExhausted:next.maxRoundsExhausted,...record3.verdict!==void 0?{verdict:record3.verdict}:{},...record3.quorumSize!==void 0?{quorumSize:record3.quorumSize}:{}})}catch{}}function emitUnscopedCouncilAttemptObservation(sessionID,level,disposition,fingerprint2,attemptId){try{emit("council_attempt_unscoped",{...sessionID!==void 0?{sessionId:sessionID}:{},level,disposition,fingerprint:fingerprint2,attemptId})}catch{}}init_council_review_identity();var VERSION=2,MAX_ROUND=10,MAX_AUDIT_TAIL=262144,STATE_AGENT="council-round-state",EXHAUSTION_EVENT_RELATIVE_PATH="council/events/max-rounds-exhaustion.jsonl";class CouncilRoundStateUncertainError extends Error{constructor(message){super(message);this.name="CouncilRoundStateUncertainError"}}function sha25613(value){return createHash107("sha256").update(value).digest("hex")}var UUID_PATTERN2=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,DIGEST_PATTERN2=/^[a-f0-9]{64}$/;function isUuid2(value){return typeof value==="string"&&UUID_PATTERN2.test(value)}function isDigest(value){return typeof value==="string"&&DIGEST_PATTERN2.test(value)}function isRound(value){return Number.isInteger(value)&&Number(value)>=1&&Number(value)<=MAX_ROUND}function isDisposition(value){return typeof value==="string"&&value.length>0&&value.length<=80}function isEvidenceRef(value){return typeof value==="string"&&value.length>0&&value.length<=240&&value.startsWith(".swarm/")&&!value.includes("..")}function scopeToken(scope){if(scope.kind==="task"){if(!/^\d+\.\d+(\.\d+)*$/.test(scope.taskId))throw Error("invalid task council scope");if(!isIdentityDigest(scope.identityDigest))throw Error("invalid task council scope identity");return`task-${sha25613(JSON.stringify({k:"task",taskId:scope.taskId,id:scope.identityDigest}))}`}if(scope.kind==="phase"){if(!Number.isInteger(scope.phaseNumber)||scope.phaseNumber<1||scope.phaseNumber>1000)throw Error("invalid phase council scope");if(!isIdentityDigest(scope.identityDigest))throw Error("invalid phase council scope identity");return`phase-${sha25613(JSON.stringify({k:"phase",phaseNumber:scope.phaseNumber,id:scope.identityDigest}))}`}if(!isIdentityDigest(scope.identityDigest))throw Error("invalid final council scope identity");return`final-${sha25613(JSON.stringify({k:"final",id:scope.identityDigest}))}`}function auditScope(scope){if(scopeToken(scope),scope.kind==="task")return{kind:"task",scopeHash:sha25613(scope.taskId),identityDigest:scope.identityDigest};if(scope.kind==="phase")return{kind:"phase",phaseNumber:scope.phaseNumber,identityDigest:scope.identityDigest};return{kind:"final",scopeHash:sha25613(scope.identityDigest),identityDigest:scope.identityDigest}}function sameAuditScope(left,right){if(left.kind!==right.kind)return!1;if(left.identityDigest!==right.identityDigest)return!1;if(left.kind==="phase"&&right.kind==="phase")return left.phaseNumber===right.phaseNumber;if(left.kind!=="phase"&&right.kind!=="phase")return left.scopeHash===right.scopeHash;return!1}function councilRoundStatePaths(directory,scope){let token=scopeToken(scope);return{state:join260(directory,".swarm","council","round-state",`${token}.json`),audit:join260(directory,".swarm","council","attempts",`${token}.jsonl`),lock:join260("council","round-state",`${token}.json`)}}function canonicalize3(value){if(Array.isArray(value))return value.map(canonicalize3);if(value&&typeof value==="object"){let result=Object.create(null);for(let key2 of Object.keys(value).sort()){if(key2==="working_directory"||key2==="roundNumber"||key2==="provenanceAgentName"||key2==="provenanceSessionId")continue;result[key2]=canonicalize3(value[key2])}return result}return value}function councilRequestDigest(request,round){return sha25613(JSON.stringify({round,request:canonicalize3(request)}))}function isSnapshot(value){if(!value||typeof value!=="object")return!1;let state2=value;return state2.version===VERSION&&isIdentityDigest(state2.identityDigest)&&isRound(state2.currentRound)&&(state2.status==="open"||state2.status==="closed")&&typeof state2.maxRoundsExhausted==="boolean"&&(state2.lastAttemptId===void 0||isUuid2(state2.lastAttemptId))&&(state2.lastDigest===void 0||isDigest(state2.lastDigest))&&state2.lastAttemptId===void 0===(state2.lastDigest===void 0)}function isTransition(value){return value==="stay"||value==="advance"||value==="close"}function isGateEffect(value){return value==="none"||value==="blocked"||value==="allowed"}function isVerdict(value){return value==="APPROVE"||value==="CONCERNS"||value==="REJECT"}function auditTransitionIsConsistent(record3){if(!record3.nextState||!record3.transition)return!1;if(record3.transition==="close")return record3.nextState.status==="closed"&&record3.nextState.currentRound===record3.authoritativeRound;if(record3.transition==="stay"){if(record3.nextState.status==="closed"&&!["duplicate_submission","council_round_closed","council_round_mismatch"].includes(record3.disposition))return!1;return(record3.nextState.status==="open"||record3.nextState.status==="closed")&&record3.nextState.currentRound===record3.authoritativeRound}return record3.nextState.status==="open"&&(record3.nextState.currentRound===record3.authoritativeRound+1&&record3.nextState.maxRoundsExhausted===!1||record3.nextState.currentRound===record3.authoritativeRound&&record3.nextState.maxRoundsExhausted===!0)}function recoverAuditHistory(tail2,identityDigest){let current=tail2.truncated?void 0:initialState(identityDigest),awaiting,sawTransition=!1;for(let record3 of tail2.records){if(record3.event==="received"){if(awaiting)throw new CouncilRoundStateUncertainError("council audit contains overlapping attempts");if(current&&record3.authoritativeRound!==current.currentRound||!current&&!tail2.truncated&&record3.authoritativeRound!==1)throw new CouncilRoundStateUncertainError("council audit round history is not monotonic");awaiting=record3;continue}if(!record3.nextState||!record3.transition)throw new CouncilRoundStateUncertainError("council audit transition is incomplete");if(awaiting){if(awaiting.attemptId!==record3.attemptId||awaiting.digest!==record3.digest||awaiting.authoritativeRound!==record3.authoritativeRound)throw new CouncilRoundStateUncertainError("council audit attempt pairing is inconsistent");awaiting=void 0}else if(!tail2.truncated||sawTransition)throw new CouncilRoundStateUncertainError("council audit transition has no matching received record");if(current){if(record3.authoritativeRound!==current.currentRound)throw new CouncilRoundStateUncertainError("council audit transition regresses the authoritative round");if(record3.transition==="stay"&&record3.nextState.status!==current.status)throw new CouncilRoundStateUncertainError("council audit stay transition changes scope status");if((record3.transition==="stay"||record3.transition==="close")&&record3.nextState.maxRoundsExhausted!==current.maxRoundsExhausted)throw new CouncilRoundStateUncertainError("council audit changes exhaustion without advancing");if(current.status==="closed"&&(record3.transition!=="stay"||record3.nextState.status!=="closed"))throw new CouncilRoundStateUncertainError("council audit reopens a closed scope")}current=record3.nextState,sawTransition=!0}if(awaiting)throw new CouncilRoundStateUncertainError("council audit ends with an unresolved received attempt");return current}function pendingMatchesParent(state2,pending){if(state2.status!=="open"||pending.round!==state2.currentRound)return!1;if(pending.nextState.lastAttemptId!==pending.attemptId||pending.nextState.lastDigest!==pending.digest)return!1;if(pending.transition==="stay")return pending.nextState.status==="open"&&pending.nextState.currentRound===state2.currentRound&&pending.nextState.maxRoundsExhausted===state2.maxRoundsExhausted;if(pending.transition==="close")return pending.nextState.status==="closed"&&pending.nextState.currentRound===state2.currentRound&&pending.nextState.maxRoundsExhausted===state2.maxRoundsExhausted;return pending.nextState.status==="open"&&(pending.nextState.currentRound===state2.currentRound+1&&pending.nextState.maxRoundsExhausted===!1||pending.nextState.currentRound===state2.currentRound&&pending.nextState.maxRoundsExhausted===!0)}function parseState(raw,expectedIdentityDigest){let value;try{value=JSON.parse(raw)}catch{throw new CouncilRoundStateUncertainError("council round state is corrupt")}if(!isSnapshot(value))throw new CouncilRoundStateUncertainError("council round state is invalid");let state2=value;if(state2.identityDigest!==expectedIdentityDigest)throw new CouncilRoundStateUncertainError("council round state identity does not match the request scope");if(state2.pending){let pending=state2.pending;if(!isUuid2(pending.attemptId)||!isDigest(pending.digest)||!isRound(pending.round)||!isSnapshot(pending.nextState)||!isTransition(pending.transition)||!isDisposition(pending.disposition)||!isGateEffect(pending.gateEffect)||typeof pending.evidenceExpected!=="boolean"||pending.evidenceExpected!==(pending.evidenceRef!==void 0)||pending.evidenceRef!==void 0&&!isEvidenceRef(pending.evidenceRef)||pending.verdict!==void 0&&!isVerdict(pending.verdict)||pending.quorumSize!==void 0&&(!Number.isInteger(pending.quorumSize)||pending.quorumSize<0||pending.quorumSize>5)||pending.verdict===void 0!==(pending.quorumSize===void 0)||!pendingMatchesParent(state2,pending))throw new CouncilRoundStateUncertainError("pending council state is invalid")}return state2}function parseAuditRecord(line,expectedScope){try{let record3=JSON.parse(line);if(record3.version!==VERSION||!["received","finalized","recovered"].includes(record3.event)||!isUuid2(record3.attemptId)||typeof record3.timestamp!=="string"||record3.timestamp.length>40||!Number.isFinite(Date.parse(record3.timestamp))||!sameAuditScope(record3.scope,expectedScope)||record3.clientRound!==void 0&&!isRound(record3.clientRound)||!isRound(record3.authoritativeRound)||!isDigest(record3.digest)||record3.sessionHash!==void 0&&!isDigest(record3.sessionHash)||!isDisposition(record3.disposition)||!Number.isInteger(record3.verdictCount)||record3.verdictCount<0||record3.verdictCount>5||!Array.isArray(record3.members)||record3.members.length>5||record3.members.some((member)=>typeof member!=="string"||member.length===0||member.length>32)||new Set(record3.members).size!==record3.members.length)throw Error("invalid");if(record3.event==="received"){if(record3.disposition!=="received"||record3.transition!==void 0||record3.gateEffect!==void 0||record3.nextState!==void 0||record3.evidenceRef!==void 0)throw Error("invalid")}else if(!isTransition(record3.transition)||!isGateEffect(record3.gateEffect)||!isSnapshot(record3.nextState)||record3.nextState.lastAttemptId!==record3.attemptId||record3.nextState.lastDigest!==record3.digest||!auditTransitionIsConsistent(record3))throw Error("invalid");if(record3.verdict!==void 0&&!isVerdict(record3.verdict))throw Error("invalid");if(record3.quorumSize!==void 0&&(!Number.isInteger(record3.quorumSize)||record3.quorumSize<0||record3.quorumSize>5))throw Error("invalid");if(record3.verdict===void 0!==(record3.quorumSize===void 0))throw Error("invalid");if(record3.evidenceRef!==void 0&&!isEvidenceRef(record3.evidenceRef))throw Error("invalid");return record3}catch{throw new CouncilRoundStateUncertainError("council attempt audit is corrupt")}}function appendAudit2(path328,record3){mkdirSync92(dirname121(path328),{recursive:!0});let descriptor=openSync40(path328,"a");try{writeSync7(descriptor,`${JSON.stringify(record3)}
|
|
7589
7589
|
`,void 0,"utf8"),fsyncSync11(descriptor)}finally{closeSync40(descriptor)}}function appendAuditAndObserve(input,paths,councilRoundId,record3){_internals283.appendAudit(paths.audit,record3),observeCouncilAuditAppend(input.scope,input.sessionID,councilRoundId,record3)}function readAuditTail(path328,scope){if(!existsSync168(path328))return{records:[],truncated:!1};let size=statSync103(path328).size;if(size===0)return{records:[],truncated:!1};let offset=Math.max(0,size-MAX_AUDIT_TAIL),length=size-offset,descriptor=openSync40(path328,"r"),buffer=Buffer.alloc(length);try{readSync28(descriptor,buffer,0,length,offset)}finally{closeSync40(descriptor)}let text=buffer.toString("utf8");if(!text.endsWith(`
|
|
7590
7590
|
`))throw new CouncilRoundStateUncertainError("council attempt audit has a partial tail");if(offset>0){let firstNewline=text.indexOf(`
|
|
@@ -7777,10 +7777,10 @@ ${jsdocContent}`;else if(line.includes("*/"))break;else if(functionKeywords.test
|
|
|
7777
7777
|
`,"utf-8")}catch(error93){return failure("payload-write-failed",`failed to persist the submission payload copy (.swarm/pr-review/${runId}/submission-payload.json): ${error93 instanceof Error?error93.message:String(error93)}`)}let run=await _internals306.runExternalTool({executable,args:["api",`repos/${repoSlug}/pulls/${prNumber}/reviews`,"--method","POST","--input",payloadPath],cwd:directory,timeoutMs:GH_TIMEOUT_MS2,maxStdoutBytes:GH_MAX_STDOUT_BYTES2,maxStderrBytes:GH_MAX_STDERR_BYTES2});if(run.status==="timeout")return failure("transport-failed",`gh api repos/${repoSlug}/pulls/${prNumber}/reviews timed out after ${GH_TIMEOUT_MS2}ms (the review may or may not have been created; dedupe on resubmit; payload preserved at .swarm/pr-review/${runId}/submission-payload.json)`,!0);if(run.status!=="completed")return failure("transport-failed",`gh api repos/${repoSlug}/pulls/${prNumber}/reviews failed to start (${run.message??run.status})`,!0);if(run.exitCode!==0)return failure("transport-failed",`gh api repos/${repoSlug}/pulls/${prNumber}/reviews exited ${run.exitCode}: ${run.stderr.split(`
|
|
7778
7778
|
`)[0]??""}`,!0);let review={};try{review=JSON.parse(run.stdout)}catch{}return JSON.stringify({success:!0,run_id:runId,pr_head_sha:headSha,event,inline_comment_count:rendered.inlineComments.length,skipped_as_posted:rendered.skippedAsPosted.length,truncated_inline_comments:rendered.truncatedInlineComments,dismissed_findings:rendered.dismissedCount,body_truncated:rendered.bodyTruncated,coverage_kind:coverage.kind,posted_review_id:typeof review.id==="number"?review.id:null,review_url:typeof review.html_url==="string"?review.html_url:null,payload_path:`.swarm/pr-review/${runId}/submission-payload.json`},null,2)}var pr_review_submission=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",args:{pr_number:exports_external.number().int().positive().describe("Pull request number to submit the review to"),repo:exports_external.string().trim().regex(REPO_SLUG_PATTERN).describe("owner/name repository slug"),run_id:exports_external.string().trim().regex(RUN_ID_PATTERN).describe("settled PR-review run id under .swarm/pr-review/"),pr_head_sha:exports_external.string().trim().regex(PR_HEAD_SHA_PATTERN).describe("exact PR head sha the run is bound to (commit_id pin)")},execute:executePrReviewSubmission});init_pending_delegations();init_workspace_snapshot();init_pr_workflow_state();init_pr_workflow_auto_wake();init_pr_workflow_gate();import*as fsp12 from"node:fs/promises";import*as path359 from"node:path";init_utils2();init_bun_compat();init_git_executable();init_create_tool();var GIT_TIMEOUT_MS11=5000,GIT_MAX_STDOUT_BYTES=524288,MAX_DIRTY_FILES=50,MAX_REMOTES=20,MAX_REMOTE_URL_LEN=200,MAX_FIELD_LEN=240,MAX_RECOVERY_REASON_CODE_LEN=120,RECEIPT_DIR2="pr-workflow-checkouts",utf8Encoder=new TextEncoder,utf8Decoder=new TextDecoder("utf-8",{fatal:!1});function truncateToByteBudget(value,maxBytes){let encoded=utf8Encoder.encode(value);if(encoded.length<=maxBytes)return value;return utf8Decoder.decode(encoded.subarray(0,maxBytes))}function boundUntrusted(value,maxLen){let cleaned=value.replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim();return cleaned.length>maxLen?`${cleaned.slice(0,maxLen)}…`:cleaned}async function runGitCapture2(directory,args2){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return null}let proc=bunSpawn([gitExecutable,...args2],{cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:GIT_TIMEOUT_MS11});try{let[exitCode,stdout]=await Promise.all([proc.exited,proc.stdout.text()]);if(exitCode!==0)return null;return truncateToByteBudget(stdout,GIT_MAX_STDOUT_BYTES)}catch{return null}finally{try{proc.kill()}catch{}}}async function resolveBranch(directory){let raw=await _internals307.runGitCapture(directory,["rev-parse","--abbrev-ref","HEAD"]);if(raw===null)return{branch:null,detached:null};let value=raw.trim();if(!value||value==="HEAD")return{branch:null,detached:!0};return{branch:boundUntrusted(value,MAX_FIELD_LEN),detached:!1}}function parseDirtyFiles(porcelain){if(!porcelain)return{dirtyFiles:[],dirtyFileCount:0,dirtyFilesTruncated:!1};let lines=porcelain.split(`
|
|
7779
7779
|
`).filter((line)=>line.length>=4),dirtyFiles=[];for(let line of lines){if(dirtyFiles.length>=MAX_DIRTY_FILES)break;let status2=line.slice(0,2).trim()||"??",rawPath=line.slice(3);dirtyFiles.push({status:boundUntrusted(status2,4),path:boundUntrusted(rawPath,MAX_FIELD_LEN)})}return{dirtyFiles,dirtyFileCount:lines.length,dirtyFilesTruncated:lines.length>dirtyFiles.length}}function parseRemotes(remoteOutput){if(!remoteOutput)return{remotes:[],remotesTruncated:!1};let byName=new Map;for(let line of remoteOutput.split(`
|
|
7780
|
-
`)){let trimmed=line.trim();if(!trimmed)continue;let[name,rest]=trimmed.split(/\s+/,2);if(!name||!rest||byName.has(name))continue;let url3=rest.replace(/\s+\((?:fetch|push)\)\s*$/i,"");byName.set(boundUntrusted(name,64),boundUntrusted(url3,MAX_REMOTE_URL_LEN))}let entries2=[...byName.entries()],remotes=entries2.slice(0,MAX_REMOTES).map(([name,url3])=>({name,url:url3}));return{remotes,remotesTruncated:entries2.length>remotes.length}}async function countCheckoutReceiptFiles(directory,sessionID){try{let receiptDirectory=validateSwarmPath(directory,path359.join(RECEIPT_DIR2,prWorkflowSessionFileStem(sessionID)));return(await fsp12.readdir(receiptDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&/^[0-9a-f]{40,64}\.json$/i.test(entry.name)).length}catch(error93){if(error93.code==="ENOENT")return 0;return null}}function describeDelegationRead(directory){try{let outcome=_internals307.readDelegationsDetailed(directory);if(outcome.status==="ok")return{state:"ok"};return{state:"uncertain",reasonCode:boundUntrusted(outcome.reason,MAX_RECOVERY_REASON_CODE_LEN)}}catch{return{state:"uncertain",reasonCode:"reader-threw"}}}function describeRecoveryNextStep(delegationReadState){if(delegationReadState==="uncertain")return"Delegation store read is uncertain: repair the store, then re-run pr_workflow_status; if abandoning the workflow, abort via abort_pr_workflow.";return"Re-run pr_workflow_status after any store repair; if abandoning the workflow, abort via abort_pr_workflow."}function describeNextStep(gate,git2,checkout){if(checkout.kind==="recovery-required"||checkout.kind==="indeterminate")return`Manual Git recovery required. code=${checkout.code} retryable=false required_action=${checkout.requiredAction}`;if(!gate.active){if(gate.reason==="delegation-chain-uncertain")return"PR workflow gate ownership could not be resolved from this session delegation chain (cycle, depth limit, or missing ancestor). Treat the workflow state as unknown and use read-only recovery inspection; do not perform PR-workflow writes.";return"No active PR workflow gate for this session. Activate with `/swarm pr-review <pr-ref>` or `/swarm pr-feedback <pr-ref>` before PR-workflow tool calls are admitted."}if(!gate.prHeadBound)return gate.mode==="PR_FEEDBACK"?"PR_FEEDBACK gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes). Prefer the intended exact tracking checkout, then bind; if this workflow inherited an already-detached exact intake head, bind it directly and the controller will attach the unique exact local/remote tracking ref. Ambiguity or an existing mismatched upstream fails closed.":"PR_REVIEW gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes), then bind the exact detached PR head.";if(git2.isClean===!1)return`${gate.mode} gate active and head bound, but the working tree is dirty. Read-only observation only; the gate keeps writes and non-tracking fetches fail-closed.`;if(git2.isClean===null)return`${gate.mode} gate active and head bound, but this session could not determine whether the working tree is clean (git status failed). Treat the tree state as unknown and verify manually before assuming it is clean; read-only observation only.`;return`${gate.mode} gate active and head bound. Continue read-only review using the admitted observe/validate tools (diff, gh_evidence, repo_map, lint check, etc.).`}function summarizeGate(state2,receiptFiles,salvage){if(!state2)return{active:!1,reason:"no-active-gate"};return{active:!0,...salvage?.salvaged?{stateSalvaged:!0,stateSalvageDisclosure:salvage.disclosure}:{},mode:state2.mode,prHeadBound:Boolean(state2.prHeadSha),prHeadSha:state2.prHeadSha??null,prFeedbackTargetUrl:state2.prFeedbackTargetUrl?boundUntrusted(state2.prFeedbackTargetUrl,MAX_FIELD_LEN):null,prReviewBaseRef:state2.prReviewBaseRef?boundUntrusted(state2.prReviewBaseRef,MAX_FIELD_LEN):null,prReviewBaseSha:state2.prReviewBaseSha??null,prReviewDepthTier:state2.prReviewDepthTier??null,baseDispatchBatches:state2.prReviewBaseDispatches?.length??0,validationBatches:state2.prReviewValidationBatches?.length??0,feedbackVerificationBatches:state2.prFeedbackVerifications?.length??0,...state2.prFeedbackInventoryAmendments?.length?{inventoryAmendments:state2.prFeedbackInventoryAmendments}:{},checkoutReceiptFiles:receiptFiles,activatedAt:state2.activatedAt,updatedAt:state2.updatedAt,revision:state2.revision}}async function resolveWorkflowGate(directory,sessionID){let outcome=await _internals307.resolvePrWorkflowControllerSession({directory,sessionID,readGate:(candidate2)=>_internals307.readPrWorkflowGateStateForRecovery(directory,candidate2)});if(outcome.kind==="gate-owner")return{sessionID:outcome.sessionID,recovery:outcome.gate};if(outcome.kind==="no-gate")return{sessionID:outcome.sessionID,recovery:null};return{sessionID:null,recovery:null}}async function resolveWorkflowGateSession(directory,sessionID){return(await resolveWorkflowGate(directory,sessionID)).sessionID}async function executePrWorkflowStatus(directory,rawSessionID){let sessionID=rawSessionID?.trim()?rawSessionID.trim():null,resolvedGate=sessionID?await resolveWorkflowGate(directory,sessionID):null,gateSessionID=resolvedGate?.sessionID??null,[head2,isClean,branchInfo,porcelain,remoteOutput,liveCheckout]=await Promise.all([_internals307.resolveCurrentGitHeadAsync(directory),_internals307.resolveIsWorkingTreeCleanAsync(directory),resolveBranch(directory),_internals307.runGitCapture(directory,["status","--porcelain=v1","--untracked-files=all"]),_internals307.runGitCapture(directory,["remote","-v"]),_internals307.classifyGitState(directory)]),dirty=parseDirtyFiles(porcelain),{remotes,remotesTruncated}=parseRemotes(remoteOutput),git2={head:head2,branch:branchInfo.branch,detached:branchInfo.detached,isClean,dirtyFileCount:dirty.dirtyFileCount,dirtyFiles:dirty.dirtyFiles,dirtyFilesTruncated:dirty.dirtyFilesTruncated,remotes,remotesTruncated},gate,activeState=null;if(!gateSessionID)gate={active:!1,reason:sessionID?"delegation-chain-uncertain":"no-session-context"};else{let recovery2=resolvedGate?.recovery??null;activeState=recovery2?.state??null;let receiptFiles=activeState?await countCheckoutReceiptFiles(directory,gateSessionID):null;gate=summarizeGate(activeState,receiptFiles,recovery2?{salvaged:recovery2.salvaged,disclosure:recovery2.disclosure}:void 0)}let recovery=activeState?.checkoutRecovery,checkout=recovery?{kind:recovery.code==="GIT_STATE_INDETERMINATE"?"indeterminate":"recovery-required",code:recovery.code,retryable:!1,requiredAction:recovery.requiredAction,evidence:recovery.evidence}:liveCheckout,delegationRead=describeDelegationRead(directory),recoverySection={controllerSessionID:gateSessionID,delegationRead,lastProgress:activeState?{revision:activeState.revision,updatedAt:activeState.updatedAt}:null,wakeSuspension:{suspended:sessionID?_internals307.isPrWorkflowAutoWakeSuppressed(directory,sessionID):!1},actionCircuits:{state:"unavailable"},nextStep:describeRecoveryNextStep(delegationRead.state)},result={success:!0,sessionID,git:git2,checkout,gate,publication:activeState?describePrWorkflowPublicationSection(activeState):null,nextStep:describeNextStep(gate,git2,checkout),recovery:recoverySection};return JSON.stringify(result,null,2)}var pr_workflow_status=createSwarmTool({description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary (mode, bound PR head, base ref/sha, depth tier, dispatch/validation batch counts). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",args:{},execute:async(_args,directory,ctx)=>executePrWorkflowStatus(directory,ctx?.sessionID)}),_internals307={readPrWorkflowGateStateForRecovery,readDelegationsDetailed,isPrWorkflowAutoWakeSuppressed,resolvePrWorkflowControllerSession,resolveCurrentGitHeadAsync,resolveIsWorkingTreeCleanAsync,runGitCapture:runGitCapture2,classifyGitState:classifyPrWorkflowGitState,truncateToByteBudget,resolveWorkflowGateSession};init_p_limit();init_zod();init_config2();init_manager2();init_utils();init_external_tool_runner();init_filesystem_identity();init_git_executable();init_project_boundary();init_create_tool();init_lint();import*as path360 from"node:path";init_quality_budget();init_sast_scan();init_secretscan();var TOOL_TIMEOUT_MS=60000,MAX_COMBINED_BYTES=500000,MAX_COMPACT_ERROR_BYTES=4096,CANCELLATION_SETTLEMENT_GRACE_MS=1000,MAX_CONCURRENT=4,MAX_FILES=100,GIT_TIMEOUT_MS12=1e4,GIT_MAX_OUTPUT_BYTES2=2000000,ALL_LINES_CHANGED=-1,MAX_CHANGED_LINE_ENTRIES=200000,_internals308={qualityBudget,runLintWrapped,runSecretscanWrapped,runSastScanWrapped,runQualityBudgetWrapped,runWithTimeout:runWithTimeout2,getChangedLineRanges,saveEvidence,runExternalTool,detectResolvedLinter,runLintOnFiles,platform:()=>process.platform,serializePreCheckResult,resolveGatePreamble,runPreCheckBatch,loadGateOverrides,MAX_COMBINED_BYTES};function formatIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function evaluateSecretscanGate(toolResult,requestedFiles){if(toolResult.error)return{passed:!1,summary:`Secretscan wrapper error: ${toolResult.error}`,findingsCount:0};if(!toolResult.ran||!toolResult.result)return{passed:!1,summary:"Secretscan did not return a result",findingsCount:0};if("error"in toolResult.result)return{passed:!1,summary:`Secretscan error: ${toolResult.result.error}`,findingsCount:0};let result=toolResult.result;if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{passed:!1,summary:"Secretscan failed: scanner returned incomplete coverage metadata",result,findingsCount:Math.max(result.count,result.findings.length)};let findingsCount=Math.max(result.count,result.findings.length),failures=[],vacuousCoverage=result.files_scanned===0&&typeof result.policy_skipped_files==="number"&&typeof result.requested_files==="number"&&result.requested_files>0&&result.policy_skipped_files>=result.requested_files&&result.count===0&&result.findings.length===0&&result.incomplete_files===0&&result.incomplete_paths.length===0;if(findingsCount>0)failures.push(`${findingsCount} secret finding(s)`);if(result.incomplete_files>0||result.incomplete_paths.length>0){let incompletePaths=result.incomplete_paths.length>0?`; incomplete paths: ${formatIncompletePaths(result.incomplete_paths)}`:"";failures.push(`${result.incomplete_files} incomplete file(s)${incompletePaths}`)}if(result.count!==result.findings.length)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(requestedFiles>0&&result.files_scanned===0&&!vacuousCoverage)failures.push(typeof result.ignored_files==="number"&&result.ignored_files>0?`${result.ignored_files} requested file(s) suppressed by .secretscanignore; no file scanned`:"zero requested files scanned");let statistics=`Secretscan: ${findingsCount} finding(s), ${result.files_scanned} files scanned, ${result.skipped_files} skipped`;if(vacuousCoverage)statistics+=`, all ${result.requested_files} requested file(s) skipped by secretscan scan policy (vacuous coverage)`;return{passed:failures.length===0,summary:failures.length>0?`${statistics}; failed: ${failures.join("; ")}`:statistics,result,findingsCount}}function truncateUtf8(value,maxBytes){if(Buffer.byteLength(value,"utf8")<=maxBytes)return value;let marker="... (truncated)",budget=Math.max(0,maxBytes-Buffer.byteLength(marker,"utf8")),result="",usedBytes=0;for(let character of value){let characterBytes=Buffer.byteLength(character,"utf8");if(usedBytes+characterBytes>budget)break;result+=character,usedBytes+=characterBytes}return`${result}${marker}`}function compactToolResult(toolResult){return{ran:toolResult.ran,duration_ms:toolResult.duration_ms,...toolResult.error!==void 0&&{error:truncateUtf8(toolResult.error,MAX_COMPACT_ERROR_BYTES)},...toolResult.error===void 0&&toolResult.result!==void 0&&{result_omitted:!0}}}function serializePreCheckResult(result){let serialized3=JSON.stringify(result,null,2);if(Buffer.byteLength(serialized3,"utf8")<=MAX_COMBINED_BYTES)return serialized3;let compact={batch_status:result.batch_status,gates_passed:result.gates_passed,...result.sast_degraded!==void 0&&{sast_degraded:result.sast_degraded},...result.sast_skipped!==void 0&&{sast_skipped:result.sast_skipped},lint:compactToolResult(result.lint),secretscan:compactToolResult(result.secretscan),sast_scan:compactToolResult(result.sast_scan),quality_budget:compactToolResult(result.quality_budget),total_duration_ms:result.total_duration_ms,output_truncated:!0};return JSON.stringify(compact,null,2)}function isWindowsAbsolutePath(inputPath){return/^[A-Za-z]:[/\\]/.test(inputPath)}function validatePath(inputPath,baseDir,workspaceDir){if(typeof inputPath!=="string")return"path must be a string";if(!inputPath||inputPath.trim().length===0)return"path is required";let resolved,isWinAbs=isWindowsAbsolutePath(inputPath);if(isWinAbs)resolved=path360.win32.resolve(inputPath);else if(path360.isAbsolute(inputPath))resolved=path360.resolve(inputPath);else resolved=path360.resolve(baseDir,inputPath);let workspaceResolved=isWindowsAbsolutePath(workspaceDir)?path360.win32.resolve(workspaceDir):path360.resolve(workspaceDir),relative95;if(isWinAbs)relative95=path360.win32.relative(workspaceResolved,resolved);else relative95=path360.relative(workspaceResolved,resolved);if(relative95.startsWith(".."))return"path traversal detected";return null}function isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitBoundary,exactPhysicalRoot=!1){if(exactPhysicalRoot)return!0;let pathApi=platform==="win32"?path360.win32:path360,directoryKey=pathApi.resolve(dir).replace(/\\/g,"/"),workspaceKey=pathApi.resolve(workspaceDir).replace(/\\/g,"/"),normalizedDirectoryKey=platform==="win32"?directoryKey.toLowerCase():directoryKey,normalizedWorkspaceKey=platform==="win32"?workspaceKey.toLowerCase():workspaceKey;if(normalizedDirectoryKey===normalizedWorkspaceKey)return!0;let relative95=pathApi.relative(workspaceDir,dir);return relative95!==""&&relative95!==".."&&!relative95.startsWith(`..${pathApi.sep}`)&&!pathApi.isAbsolute(relative95)&&hasExplicitBoundary}function validateDirectory2(dir,workspaceDir){if(!dir||dir.length===0)return"directory is required";if(dir.length>500)return"directory path too long";let exactPhysicalRoot=sameExistingFilesystemPath(dir,workspaceDir);if(!exactPhysicalRoot){let traversalCheck=validatePath(dir,workspaceDir,workspaceDir);if(traversalCheck)return traversalCheck}let platform=_internals308.platform();if(!isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitProjectBoundary(dir),exactPhysicalRoot))return"directory must resolve to the project root";return null}async function runWithTimeout2(operation,timeoutMs,parentSignal,waitForCancellationSettlement=!1){let controller=new AbortController,timeoutHandle,parentAbortListener;if(parentSignal?.aborted)throw Error("Tool execution cancelled");let parentAbortPromise=new Promise((_,reject3)=>{if(!parentSignal)return;if(parentAbortListener=()=>{reject3(Error("Tool execution cancelled")),controller.abort()},parentSignal.addEventListener("abort",parentAbortListener,{once:!0}),parentSignal.aborted)parentAbortListener()});if(controller.signal.aborted)return await parentAbortPromise;let operationPromise=operation(controller.signal);try{let timeoutPromise=new Promise((_,reject3)=>{timeoutHandle=setTimeout(()=>{reject3(Error(`Timeout after ${timeoutMs}ms`)),controller.abort()},timeoutMs)});return await Promise.race([operationPromise,timeoutPromise,parentAbortPromise])}catch(error93){if(controller.signal.aborted&&waitForCancellationSettlement){let settlementTimer;try{await Promise.race([operationPromise.then(()=>{return},()=>{return}),new Promise((resolve141)=>{settlementTimer=setTimeout(resolve141,CANCELLATION_SETTLEMENT_GRACE_MS)})])}finally{if(settlementTimer!==void 0)clearTimeout(settlementTimer)}}throw error93}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(parentAbortListener&&parentSignal)parentSignal.removeEventListener("abort",parentAbortListener)}}async function runLintWrapped(files,directory,_gates,abortSignal){let start=process.hrtime.bigint();try{let resolvedLinter=await _internals308.detectResolvedLinter(directory,abortSignal);if(!resolvedLinter)return{ran:!1,error:"No linter found (biome or eslint)",duration_ms:Number(process.hrtime.bigint()-start)/1e6};if(files&&files.length>0)return{ran:!0,result:await _internals308.runLintOnFiles(resolvedLinter,files,directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await _internals202.runResolvedLint(resolvedLinter,"check",directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runLintOnFiles(resolvedLinter,files,workspaceDir,abortSignal){if(resolvedLinter.source==="legacy-test-probe")return _internals202.runResolvedLint(resolvedLinter,"check",workspaceDir,abortSignal);let validatedFiles=[];for(let file3 of files){if(typeof file3!=="string")continue;let resolvedPath=path360.resolve(file3);if(validatePath(resolvedPath,workspaceDir,workspaceDir))continue;validatedFiles.push(resolvedPath)}if(validatedFiles.length===0)return{success:!1,mode:"check",linter:resolvedLinter.linter,command:[],error:"No valid files after security validation"};let args2;if(resolvedLinter.linter==="biome")args2=[...resolvedLinter.argsPrefix,"check",...validatedFiles];else args2=[...resolvedLinter.argsPrefix,...validatedFiles];let command=[...resolvedLinter.displayPrefix,...args2];try{let execution=await _internals308.runExternalTool({executable:resolvedLinter.executable,args:args2,cwd:workspaceDir,timeoutMs:TOOL_TIMEOUT_MS,maxStdoutBytes:512000,maxStderrBytes:512000,abortSignal});if(execution.status!=="completed")return{success:!1,mode:"check",linter:resolvedLinter.linter,command,error:execution.message??`Execution ${execution.status}`};let exitCode=execution.exitCode??1,output=execution.stdout;if(execution.stderr)output+=(output?`
|
|
7780
|
+
`)){let trimmed=line.trim();if(!trimmed)continue;let[name,rest]=trimmed.split(/\s+/,2);if(!name||!rest||byName.has(name))continue;let url3=rest.replace(/\s+\((?:fetch|push)\)\s*$/i,"");byName.set(boundUntrusted(name,64),boundUntrusted(url3,MAX_REMOTE_URL_LEN))}let entries2=[...byName.entries()],remotes=entries2.slice(0,MAX_REMOTES).map(([name,url3])=>({name,url:url3}));return{remotes,remotesTruncated:entries2.length>remotes.length}}async function countCheckoutReceiptFiles(directory,sessionID){try{let receiptDirectory=validateSwarmPath(directory,path359.join(RECEIPT_DIR2,prWorkflowSessionFileStem(sessionID)));return(await fsp12.readdir(receiptDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&/^[0-9a-f]{40,64}\.json$/i.test(entry.name)).length}catch(error93){if(error93.code==="ENOENT")return 0;return null}}function describeDelegationRead(directory){try{let outcome=_internals307.readDelegationsDetailed(directory);if(outcome.status==="ok")return{state:"ok"};return{state:"uncertain",reasonCode:boundUntrusted(outcome.reason,MAX_RECOVERY_REASON_CODE_LEN)}}catch{return{state:"uncertain",reasonCode:"reader-threw"}}}function describeRecoveryNextStep(delegationReadState){if(delegationReadState==="uncertain")return"Delegation store read is uncertain: repair the store, then re-run pr_workflow_status; if abandoning the workflow, abort via abort_pr_workflow.";return"Re-run pr_workflow_status after any store repair; if abandoning the workflow, abort via abort_pr_workflow."}function describeNextStep(gate,git2,checkout){if(checkout.kind==="recovery-required"||checkout.kind==="indeterminate")return`Manual Git recovery required. code=${checkout.code} retryable=false required_action=${checkout.requiredAction}`;if(!gate.active){if(gate.reason==="delegation-chain-uncertain")return"PR workflow gate ownership could not be resolved from this session delegation chain (cycle, depth limit, or missing ancestor). Treat the workflow state as unknown and use read-only recovery inspection; do not perform PR-workflow writes.";return"No active PR workflow gate for this session. Activate with `/swarm pr-review <pr-ref>` or `/swarm pr-feedback <pr-ref>` before PR-workflow tool calls are admitted."}if(!gate.prHeadBound)return gate.mode==="PR_FEEDBACK"?"PR_FEEDBACK gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes). Prefer the intended exact tracking checkout, then bind; if this workflow inherited an already-detached exact intake head, bind it directly and the controller will attach the unique exact local/remote tracking ref. Ambiguity or an existing mismatched upstream fails closed.":"PR_REVIEW gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes), then bind the exact detached PR head.";if(git2.isClean===!1)return`${gate.mode} gate active and head bound, but the working tree is dirty. Read-only observation only; the gate keeps writes and non-tracking fetches fail-closed.`;if(git2.isClean===null)return`${gate.mode} gate active and head bound, but this session could not determine whether the working tree is clean (git status failed). Treat the tree state as unknown and verify manually before assuming it is clean; read-only observation only.`;return`${gate.mode} gate active and head bound. Continue read-only review using the admitted observe/validate tools (diff, gh_evidence, repo_map, lint check, etc.).`}function summarizeGate(state2,receiptFiles,salvage){if(!state2)return{active:!1,reason:"no-active-gate"};return{active:!0,...salvage?.salvaged?{stateSalvaged:!0,stateSalvageDisclosure:salvage.disclosure}:{},mode:state2.mode,prHeadBound:Boolean(state2.prHeadSha),prHeadSha:state2.prHeadSha??null,prFeedbackTargetUrl:state2.prFeedbackTargetUrl?boundUntrusted(state2.prFeedbackTargetUrl,MAX_FIELD_LEN):null,prReviewBaseRef:state2.prReviewBaseRef?boundUntrusted(state2.prReviewBaseRef,MAX_FIELD_LEN):null,prReviewBaseSha:state2.prReviewBaseSha??null,prReviewDepthTier:state2.prReviewDepthTier??null,baseDispatchBatches:state2.prReviewBaseDispatches?.length??0,validationBatches:state2.prReviewValidationBatches?.length??0,feedbackVerificationBatches:state2.prFeedbackVerifications?.length??0,...state2.prFeedbackInventoryAmendments?.length?{inventoryAmendments:state2.prFeedbackInventoryAmendments}:{},checkoutReceiptFiles:receiptFiles,activatedAt:state2.activatedAt,updatedAt:state2.updatedAt,revision:state2.revision}}async function resolveWorkflowGate(directory,sessionID){let outcome=await _internals307.resolvePrWorkflowControllerSession({directory,sessionID,readGate:(candidate2)=>_internals307.readPrWorkflowGateStateForRecovery(directory,candidate2)});if(outcome.kind==="gate-owner")return{sessionID:outcome.sessionID,recovery:outcome.gate};if(outcome.kind==="no-gate")return{sessionID:outcome.sessionID,recovery:null};return{sessionID:null,recovery:null}}async function resolveWorkflowGateSession(directory,sessionID){return(await resolveWorkflowGate(directory,sessionID)).sessionID}async function executePrWorkflowStatus(directory,rawSessionID){let sessionID=rawSessionID?.trim()?rawSessionID.trim():null,resolvedGate=sessionID?await resolveWorkflowGate(directory,sessionID):null,gateSessionID=resolvedGate?.sessionID??null,[head2,isClean,branchInfo,porcelain,remoteOutput,liveCheckout]=await Promise.all([_internals307.resolveCurrentGitHeadAsync(directory),_internals307.resolveIsWorkingTreeCleanAsync(directory),resolveBranch(directory),_internals307.runGitCapture(directory,["status","--porcelain=v1","--untracked-files=all"]),_internals307.runGitCapture(directory,["remote","-v"]),_internals307.classifyGitState(directory)]),dirty=parseDirtyFiles(porcelain),{remotes,remotesTruncated}=parseRemotes(remoteOutput),git2={head:head2,branch:branchInfo.branch,detached:branchInfo.detached,isClean,dirtyFileCount:dirty.dirtyFileCount,dirtyFiles:dirty.dirtyFiles,dirtyFilesTruncated:dirty.dirtyFilesTruncated,remotes,remotesTruncated},gate,activeState=null;if(!gateSessionID)gate={active:!1,reason:sessionID?"delegation-chain-uncertain":"no-session-context"};else{let recovery2=resolvedGate?.recovery??null;activeState=recovery2?.state??null;let receiptFiles=activeState?await countCheckoutReceiptFiles(directory,gateSessionID):null;gate=summarizeGate(activeState,receiptFiles,recovery2?{salvaged:recovery2.salvaged,disclosure:recovery2.disclosure}:void 0)}let recovery=activeState?.checkoutRecovery,checkout=recovery?{kind:recovery.code==="GIT_STATE_INDETERMINATE"?"indeterminate":"recovery-required",code:recovery.code,retryable:!1,requiredAction:recovery.requiredAction,evidence:recovery.evidence}:liveCheckout,delegationRead=describeDelegationRead(directory),recoverySection={controllerSessionID:gateSessionID,delegationRead,lastProgress:activeState?{revision:activeState.revision,updatedAt:activeState.updatedAt}:null,wakeSuspension:{suspended:sessionID?_internals307.isPrWorkflowAutoWakeSuppressed(directory,sessionID):!1},actionCircuits:{state:"unavailable"},nextStep:describeRecoveryNextStep(delegationRead.state)},result={success:!0,sessionID,git:git2,checkout,gate,publication:activeState?describePrWorkflowPublicationSection(activeState):null,nextStep:describeNextStep(gate,git2,checkout),recovery:recoverySection};return JSON.stringify(result,null,2)}var pr_workflow_status=createSwarmTool({description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary (mode, bound PR head, base ref/sha, depth tier, dispatch/validation batch counts). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",args:{},execute:async(_args,directory,ctx)=>executePrWorkflowStatus(directory,ctx?.sessionID)}),_internals307={readPrWorkflowGateStateForRecovery,readDelegationsDetailed,isPrWorkflowAutoWakeSuppressed,resolvePrWorkflowControllerSession,resolveCurrentGitHeadAsync,resolveIsWorkingTreeCleanAsync,runGitCapture:runGitCapture2,classifyGitState:classifyPrWorkflowGitState,truncateToByteBudget,resolveWorkflowGateSession};init_p_limit();init_zod();init_config2();init_manager2();init_utils();init_external_tool_runner();init_filesystem_identity();init_git_executable();init_project_boundary();init_create_tool();init_lint();import*as path360 from"node:path";init_quality_budget();init_sast_scan();init_secretscan();var TOOL_TIMEOUT_MS=60000,MAX_COMBINED_BYTES=500000,MAX_COMPACT_ERROR_BYTES=4096,CANCELLATION_SETTLEMENT_GRACE_MS=1000,MAX_CONCURRENT=4,MAX_FILES=100,GIT_TIMEOUT_MS12=1e4,GIT_MAX_OUTPUT_BYTES2=2000000,ALL_LINES_CHANGED=-1,MAX_CHANGED_LINE_ENTRIES=200000,_internals308={qualityBudget,runLintWrapped,runSecretscanWrapped,runSastScanWrapped,runQualityBudgetWrapped,runWithTimeout:runWithTimeout2,getChangedLineRanges,getChangedLineAmbiguousFiles,saveEvidence,runExternalTool,detectResolvedLinter,runLintOnFiles,platform:()=>process.platform,serializePreCheckResult,resolveGatePreamble,runPreCheckBatch,loadGateOverrides,MAX_COMBINED_BYTES};function formatIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function evaluateSecretscanGate(toolResult,requestedFiles,classification){if(toolResult.error)return{passed:!1,summary:`Secretscan wrapper error: ${toolResult.error}`,findingsCount:0};if(!toolResult.ran||!toolResult.result)return{passed:!1,summary:"Secretscan did not return a result",findingsCount:0};if("error"in toolResult.result)return{passed:!1,summary:`Secretscan error: ${toolResult.result.error}`,findingsCount:0};let result=toolResult.result;if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{passed:!1,summary:"Secretscan failed: scanner returned incomplete coverage metadata",result,findingsCount:Math.max(result.count,result.findings.length)};let findingsCount=Math.max(result.count,result.findings.length),failures=[],vacuousCoverage=result.files_scanned===0&&typeof result.policy_skipped_files==="number"&&typeof result.requested_files==="number"&&result.requested_files>0&&result.policy_skipped_files>=result.requested_files&&result.count===0&&result.findings.length===0&&result.incomplete_files===0&&result.incomplete_paths.length===0,newFindingsCount=classification?classification.newFindings.length:findingsCount;if(newFindingsCount>0)failures.push(`${newFindingsCount} new secret finding(s) on changed lines`);if(result.truncated===!0)failures.push(`results truncated at ${SECRETSCAN_MAX_FINDINGS} findings`);if(result.incomplete_files>0||result.incomplete_paths.length>0){let incompletePaths=result.incomplete_paths.length>0?`; incomplete paths: ${formatIncompletePaths(result.incomplete_paths)}`:"";failures.push(`${result.incomplete_files} incomplete file(s)${incompletePaths}`)}if(result.count!==result.findings.length)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(requestedFiles>0&&result.files_scanned===0&&!vacuousCoverage)failures.push(typeof result.ignored_files==="number"&&result.ignored_files>0?`${result.ignored_files} requested file(s) suppressed by .secretscanignore; no file scanned`:"zero requested files scanned");let statistics=`Secretscan: ${findingsCount} finding(s), ${result.files_scanned} files scanned, ${result.skipped_files} skipped`;if(classification)statistics+=`, ${classification.newFindings.length} new secret finding(s) on changed lines (${classification.preexistingFindings.length} pre-existing)`;if(vacuousCoverage)statistics+=`, all ${result.requested_files} requested file(s) skipped by secretscan scan policy (vacuous coverage)`;let passedSummary=classification?.diffScoped?`${statistics}; secretscan green = zero new secrets on changed lines`:statistics;return{passed:failures.length===0,summary:failures.length>0?`${statistics}; failed: ${failures.join("; ")}`:passedSummary,result,findingsCount,...classification&&{newFindingsCount:classification.newFindings.length,preexistingFindingsCount:classification.preexistingFindings.length,diffScoped:classification.diffScoped}}}function truncateUtf8(value,maxBytes){if(Buffer.byteLength(value,"utf8")<=maxBytes)return value;let marker="... (truncated)",budget=Math.max(0,maxBytes-Buffer.byteLength(marker,"utf8")),result="",usedBytes=0;for(let character of value){let characterBytes=Buffer.byteLength(character,"utf8");if(usedBytes+characterBytes>budget)break;result+=character,usedBytes+=characterBytes}return`${result}${marker}`}function compactToolResult(toolResult){return{ran:toolResult.ran,duration_ms:toolResult.duration_ms,...toolResult.error!==void 0&&{error:truncateUtf8(toolResult.error,MAX_COMPACT_ERROR_BYTES)},...toolResult.error===void 0&&toolResult.result!==void 0&&{result_omitted:!0}}}function serializePreCheckResult(result){let serialized3=JSON.stringify(result,null,2);if(Buffer.byteLength(serialized3,"utf8")<=MAX_COMBINED_BYTES)return serialized3;let compact={batch_status:result.batch_status,gates_passed:result.gates_passed,...result.sast_degraded!==void 0&&{sast_degraded:result.sast_degraded},...result.sast_skipped!==void 0&&{sast_skipped:result.sast_skipped},lint:compactToolResult(result.lint),secretscan:compactToolResult(result.secretscan),sast_scan:compactToolResult(result.sast_scan),quality_budget:compactToolResult(result.quality_budget),total_duration_ms:result.total_duration_ms,output_truncated:!0};return JSON.stringify(compact,null,2)}function isWindowsAbsolutePath(inputPath){return/^[A-Za-z]:[/\\]/.test(inputPath)}function validatePath(inputPath,baseDir,workspaceDir){if(typeof inputPath!=="string")return"path must be a string";if(!inputPath||inputPath.trim().length===0)return"path is required";let resolved,isWinAbs=isWindowsAbsolutePath(inputPath);if(isWinAbs)resolved=path360.win32.resolve(inputPath);else if(path360.isAbsolute(inputPath))resolved=path360.resolve(inputPath);else resolved=path360.resolve(baseDir,inputPath);let workspaceResolved=isWindowsAbsolutePath(workspaceDir)?path360.win32.resolve(workspaceDir):path360.resolve(workspaceDir),relative95;if(isWinAbs)relative95=path360.win32.relative(workspaceResolved,resolved);else relative95=path360.relative(workspaceResolved,resolved);if(relative95.startsWith(".."))return"path traversal detected";return null}function isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitBoundary,exactPhysicalRoot=!1){if(exactPhysicalRoot)return!0;let pathApi=platform==="win32"?path360.win32:path360,directoryKey=pathApi.resolve(dir).replace(/\\/g,"/"),workspaceKey=pathApi.resolve(workspaceDir).replace(/\\/g,"/"),normalizedDirectoryKey=platform==="win32"?directoryKey.toLowerCase():directoryKey,normalizedWorkspaceKey=platform==="win32"?workspaceKey.toLowerCase():workspaceKey;if(normalizedDirectoryKey===normalizedWorkspaceKey)return!0;let relative95=pathApi.relative(workspaceDir,dir);return relative95!==""&&relative95!==".."&&!relative95.startsWith(`..${pathApi.sep}`)&&!pathApi.isAbsolute(relative95)&&hasExplicitBoundary}function validateDirectory2(dir,workspaceDir){if(!dir||dir.length===0)return"directory is required";if(dir.length>500)return"directory path too long";let exactPhysicalRoot=sameExistingFilesystemPath(dir,workspaceDir);if(!exactPhysicalRoot){let traversalCheck=validatePath(dir,workspaceDir,workspaceDir);if(traversalCheck)return traversalCheck}let platform=_internals308.platform();if(!isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitProjectBoundary(dir),exactPhysicalRoot))return"directory must resolve to the project root";return null}async function runWithTimeout2(operation,timeoutMs,parentSignal,waitForCancellationSettlement=!1){let controller=new AbortController,timeoutHandle,parentAbortListener;if(parentSignal?.aborted)throw Error("Tool execution cancelled");let parentAbortPromise=new Promise((_,reject3)=>{if(!parentSignal)return;if(parentAbortListener=()=>{reject3(Error("Tool execution cancelled")),controller.abort()},parentSignal.addEventListener("abort",parentAbortListener,{once:!0}),parentSignal.aborted)parentAbortListener()});if(controller.signal.aborted)return await parentAbortPromise;let operationPromise=operation(controller.signal);try{let timeoutPromise=new Promise((_,reject3)=>{timeoutHandle=setTimeout(()=>{reject3(Error(`Timeout after ${timeoutMs}ms`)),controller.abort()},timeoutMs)});return await Promise.race([operationPromise,timeoutPromise,parentAbortPromise])}catch(error93){if(controller.signal.aborted&&waitForCancellationSettlement){let settlementTimer;try{await Promise.race([operationPromise.then(()=>{return},()=>{return}),new Promise((resolve141)=>{settlementTimer=setTimeout(resolve141,CANCELLATION_SETTLEMENT_GRACE_MS)})])}finally{if(settlementTimer!==void 0)clearTimeout(settlementTimer)}}throw error93}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(parentAbortListener&&parentSignal)parentSignal.removeEventListener("abort",parentAbortListener)}}async function runLintWrapped(files,directory,_gates,abortSignal){let start=process.hrtime.bigint();try{let resolvedLinter=await _internals308.detectResolvedLinter(directory,abortSignal);if(!resolvedLinter)return{ran:!1,error:"No linter found (biome or eslint)",duration_ms:Number(process.hrtime.bigint()-start)/1e6};if(files&&files.length>0)return{ran:!0,result:await _internals308.runLintOnFiles(resolvedLinter,files,directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await _internals202.runResolvedLint(resolvedLinter,"check",directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runLintOnFiles(resolvedLinter,files,workspaceDir,abortSignal){if(resolvedLinter.source==="legacy-test-probe")return _internals202.runResolvedLint(resolvedLinter,"check",workspaceDir,abortSignal);let validatedFiles=[];for(let file3 of files){if(typeof file3!=="string")continue;let resolvedPath=path360.resolve(file3);if(validatePath(resolvedPath,workspaceDir,workspaceDir))continue;validatedFiles.push(resolvedPath)}if(validatedFiles.length===0)return{success:!1,mode:"check",linter:resolvedLinter.linter,command:[],error:"No valid files after security validation"};let args2;if(resolvedLinter.linter==="biome")args2=[...resolvedLinter.argsPrefix,"check",...validatedFiles];else args2=[...resolvedLinter.argsPrefix,...validatedFiles];let command=[...resolvedLinter.displayPrefix,...args2];try{let execution=await _internals308.runExternalTool({executable:resolvedLinter.executable,args:args2,cwd:workspaceDir,timeoutMs:TOOL_TIMEOUT_MS,maxStdoutBytes:512000,maxStderrBytes:512000,abortSignal});if(execution.status!=="completed")return{success:!1,mode:"check",linter:resolvedLinter.linter,command,error:execution.message??`Execution ${execution.status}`};let exitCode=execution.exitCode??1,output=execution.stdout;if(execution.stderr)output+=(output?`
|
|
7781
7781
|
`:"")+execution.stderr;if(execution.stdoutTruncated||execution.stderrTruncated)output+=`
|
|
7782
7782
|
... (output truncated)`;let result={success:!0,mode:"check",linter:resolvedLinter.linter,command,exitCode,output};if(exitCode===0)result.message=`${resolvedLinter.linter} check completed successfully with no issues`;else if(resolvedLinter.linter==="biome"&&output.includes("No files were processed"))result.message=`${resolvedLinter.linter} check processed no files (all specified paths ignored by biome configuration)`;else result.message=`${resolvedLinter.linter} check found issues (exit code ${exitCode}).`;return result}catch(error93){return{success:!1,mode:"check",linter:resolvedLinter.linter,command,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error"}}}async function runSecretscanWrapped(files,directory,_gates,abortSignal,rawRequestedFiles){let start=process.hrtime.bigint();try{if(files&&files.length>0)return{ran:!0,result:await runWithTimeout2(()=>runSecretscanOnFiles(files,directory,rawRequestedFiles),TOOL_TIMEOUT_MS,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await runWithTimeout2(()=>runSecretscan(directory),TOOL_TIMEOUT_MS,abortSignal,!0),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runSastScanWrapped(changedFiles,directory,severityThreshold,gates,phase,abortSignal){let start=process.hrtime.bigint();try{return{ran:!0,result:await runWithTimeout2((signal2)=>sastScan({changed_files:changedFiles,severity_threshold:severityThreshold,phase,abort_signal:signal2},directory,gates),TOOL_TIMEOUT_MS,abortSignal,!0),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runQualityBudgetWrapped(changedFiles,directory,gates,abortSignal){let start=process.hrtime.bigint();try{return{ran:!0,result:await runWithTimeout2((signal2)=>_internals308.qualityBudget({changed_files:changedFiles,config:gates?.quality_budget},directory,signal2),TOOL_TIMEOUT_MS,abortSignal,!0),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}var GATE_SEVERITIES=new Set(["high","critical"]),SEVERITY_ORDER_PCB={low:0,medium:1,high:2,critical:3};function meetsThresholdForTriage(severity2,threshold){return(SEVERITY_ORDER_PCB[severity2]??0)>=(SEVERITY_ORDER_PCB[threshold]??1)}async function runGit8(args2,directory,abortSignal){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return null}let result=await _internals308.runExternalTool({executable:gitExecutable,args:args2,cwd:directory,timeoutMs:GIT_TIMEOUT_MS12,maxStdoutBytes:GIT_MAX_OUTPUT_BYTES2,maxStderrBytes:64000,abortSignal});if(result.status!=="completed"||result.exitCode!==0||result.stdoutTruncated)return null;return result.stdout}function decodeGitQuotedPath(value){if(!value.startsWith('"'))return value;if(!value.endsWith('"'))return null;let bytes=[],appendText=(text)=>{bytes.push(...Buffer.from(text,"utf8"))};for(let index=1;index<value.length-1;index++){let codePoint=value.codePointAt(index);if(codePoint===void 0)return null;let char=String.fromCodePoint(codePoint);if(char!=="\\"){if(appendText(char),char.length===2)index++;continue}if(index++,index>=value.length-1)return null;let escaped=value[index],simple={"\\":"\\",'"':'"',t:"\t",n:`
|
|
7783
|
-
`,r:"\r",b:"\b",f:"\f",v:"\v"};if(simple[escaped]!==void 0){appendText(simple[escaped]);continue}if(/[0-7]/.test(escaped)){let octal=escaped;for(let count4=0;count4<2;count4++){let next=value[index+1];if(!next||!/[0-7]/.test(next))break;octal+=next,index++}bytes.push(Number.parseInt(octal,8));continue}return null}return Buffer.from(bytes).toString("utf8")}function normalizeRepoPathKey(repoPath){let normalized=repoPath.replace(/\\/g,"/");return _internals308.platform()==="win32"||_internals308.platform()==="darwin"?normalized.toLowerCase():normalized}function normalizeDiffPath(rawPath){let pathToken=rawPath.startsWith('"')?rawPath:rawPath.split("\t",1)[0],decoded=decodeGitQuotedPath(pathToken);if(decoded===null||decoded==="/dev/null"||decoded.trim().length===0)return null;return normalizeRepoPathKey(decoded)}function parseDiffLineRangesChecked(diffOutput,requireGitFileHeaders){let result=new Map,currentFile=null,inGitFile=!1,expectingDestination=!1,destinationSeen=!1,destinationNeedsHunk=!1,collectedLines=0;for(let rawLine of diffOutput.split(/\r?\n/)){let line=rawLine.endsWith("\r")?rawLine.slice(0,-1):rawLine;if(line.startsWith("diff --git ")){if(expectingDestination||destinationNeedsHunk)return null;inGitFile=!0,currentFile=null,expectingDestination=!1,destinationSeen=!1;continue}if(line.startsWith("--- ")&&(inGitFile||!requireGitFileHeaders)){if(expectingDestination||destinationNeedsHunk)return null;expectingDestination=!0;continue}if(line.startsWith("+++ ")){if(requireGitFileHeaders&&(!inGitFile||!expectingDestination))return null;let rawDestination=line.slice(4);if(currentFile=normalizeDiffPath(rawDestination),currentFile===null&&rawDestination.trim()!=="/dev/null")return null;if(expectingDestination=!1,destinationSeen=!0,destinationNeedsHunk=!0,!currentFile)continue;if(!result.has(currentFile))result.set(currentFile,new Set);continue}if(!line.startsWith("@@"))continue;if(expectingDestination||requireGitFileHeaders&&(!inGitFile||!destinationSeen))return null;let match=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);if(!match)return null;let start=Number.parseInt(match[1],10),count4=match[2]!==void 0?Number.parseInt(match[2],10):1;if(!Number.isSafeInteger(start)||!Number.isSafeInteger(count4)||count4<0||count4>0&&start<1||count4>MAX_CHANGED_LINE_ENTRIES||start+count4-1>Number.MAX_SAFE_INTEGER||collectedLines+count4>MAX_CHANGED_LINE_ENTRIES)return null;if(destinationNeedsHunk=!1,!currentFile)continue;let lines=result.get(currentFile);if(!lines)return null;for(let index=0;index<count4;index++)lines.add(start+index);collectedLines+=count4}if(expectingDestination||destinationNeedsHunk)return null;return result}function mergeChangedLines(target,source){for(let[file3,sourceLines]of source){let targetLines=target.get(file3)??new Set;for(let line of sourceLines)targetLines.add(line);target.set(file3,targetLines)}}function parseUntrackedStatus(output){if(output.length>0&&!output.endsWith("\x00"))return null;let untracked=[],records=output.split("\x00");for(let index=0;index<records.length-1;index++){let record3=records[index];if(!record3||record3.length<4||record3[2]!==" ")return null;let status2=record3.slice(0,2),filePath=record3.slice(3);if(!filePath||!isKnownPorcelainStatus(status2))return null;if(status2==="??"||status2==="!!")untracked.push(normalizeRepoPathKey(filePath));if(/[RC]/.test(status2)){let sourcePath=records[++index];if(!sourcePath||looksLikePorcelainStatusRecord(sourcePath))return null}}return untracked}function isKnownPorcelainStatus(status2){if(status2==="??"||status2==="!!")return!0;if(/U/.test(status2))return new Set(["DD","AU","UD","UA","DU","AA","UU"]).has(status2);return status2!==" "&&/^[ MTADRC]{2}$/.test(status2)}function looksLikePorcelainStatusRecord(value){return value.length>=4&&value[2]===" "&&isKnownPorcelainStatus(value.slice(0,2))}async function getChangedLineRanges(directory,abortSignal,requestedFiles=[]){let mergeBase=null;for(let baseBranch of["zaxbyhub/main","upstream/main","origin/main","main","origin/master","master"]){let candidate2=(await runGit8(["merge-base",baseBranch,"HEAD"],directory,abortSignal))?.trim();if(candidate2&&/^[0-9a-f]{40,64}$/i.test(candidate2)){mergeBase=candidate2;break}}if(!mergeBase)return null;let commonDiffArgs=["-c","core.quotePath=false","diff","--no-ext-diff","--no-color","--no-prefix","-U0"],requestedPathspecs=requestedFiles.map((file3)=>path360.relative(directory,file3).replace(/\\/g,"/")).filter((file3)=>file3.length>0&&file3!==".."&&!file3.startsWith("../")),statusArgs=["-c","core.quotePath=false","status","--porcelain=v1","-z","--untracked-files=all",...requestedPathspecs.length>0?["--ignored=matching"]:[],...requestedPathspecs.length>0?["--",...requestedPathspecs]:[]],[committed,staged,unstaged,status2]=await Promise.all([runGit8([...commonDiffArgs,`${mergeBase}..HEAD`,"--"],directory,abortSignal),runGit8([...commonDiffArgs,"--cached","HEAD","--"],directory,abortSignal),runGit8([...commonDiffArgs,"--"],directory,abortSignal),runGit8(statusArgs,directory,abortSignal)]);if(committed===null||staged===null||unstaged===null||status2===null)return null;let committedLines=parseDiffLineRangesChecked(committed,!0),stagedLines=parseDiffLineRangesChecked(staged,!0),unstagedLines=parseDiffLineRangesChecked(unstaged,!0);if(!committedLines||!stagedLines||!unstagedLines)return null;let result=new Map;mergeChangedLines(result,committedLines),mergeChangedLines(result,stagedLines),mergeChangedLines(result,unstagedLines);let untracked=parseUntrackedStatus(status2);if(untracked===null)return null;let requestedKeys=requestedPathspecs.map(normalizeRepoPathKey);for(let file3 of untracked)if(result.set(file3,new Set([ALL_LINES_CHANGED])),file3.endsWith("/")){for(let requestedFile of requestedKeys)if(requestedFile.startsWith(file3))result.set(requestedFile,new Set([ALL_LINES_CHANGED]))}return result}function classifySastFindings(findings,changedLineRanges,directory){if(!changedLineRanges)return{newFindings:findings,preexistingFindings:[]};let newFindings=[],preexistingFindings=[],pathApi=_internals308.platform()==="win32"?path360.win32:path360.posix,resolvedDirectory=pathApi.resolve(directory);for(let finding of findings){let filePath=finding.location.file,normalised;try{if(typeof filePath!=="string"||filePath.length===0||filePath.includes("\x00")){newFindings.push(finding);continue}let resolvedFinding=pathApi.isAbsolute(filePath)?pathApi.resolve(filePath):pathApi.resolve(resolvedDirectory,filePath),relative95=pathApi.relative(resolvedDirectory,resolvedFinding);if(pathApi.isAbsolute(relative95)||relative95===".."||relative95.startsWith(`..${pathApi.sep}`)){newFindings.push(finding);continue}normalised=normalizeRepoPathKey(relative95)}catch{newFindings.push(finding);continue}let changedLines=changedLineRanges.get(normalised);if(changedLines?.has(ALL_LINES_CHANGED)||changedLines?.has(finding.location.line))newFindings.push(finding);else preexistingFindings.push(finding)}return{newFindings,preexistingFindings}}async function runPreCheckBatch(input,workspaceDir,contextDir,abortSignal){let effectiveWorkspaceDir=workspaceDir||input.directory||contextDir,{files,directory,sast_threshold="medium",gates:gatesOverrides,phase,sast_enabled=!0}=input,gates=gatesOverrides??(input.config?.gates?{sast_scan:input.config.gates.sast_scan,quality_budget:input.config.gates.quality_budget}:void 0),dirError=validateDirectory2(directory,effectiveWorkspaceDir);if(dirError)return warn(`pre_check_batch: Invalid directory: ${dirError}`),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0};if(!files||files.length===0)return warn("pre_check_batch: No files provided, skipping all tools (fail-closed)"),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};let changedFiles=[],rawDeclaredCount=files.length;for(let file3 of files){if(typeof file3!=="string"){warn(`pre_check_batch: Non-string file entry rejected: ${String(file3)}`);continue}if(validatePath(file3,directory,effectiveWorkspaceDir)){warn(`pre_check_batch: Invalid file path: ${file3}`);continue}changedFiles.push(path360.resolve(directory,file3))}if(changedFiles.length===0)return warn("pre_check_batch: No valid files after validation, skipping all tools (fail-closed)"),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};try{assertProjectRoot(directory)}catch(error93){let rootError=error93 instanceof Error?error93.message:String(error93);return warn(`pre_check_batch: Project-root validation failed: ${rootError}`),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:rootError,duration_ms:0},secretscan:{ran:!1,error:rootError,duration_ms:0},sast_scan:{ran:!1,error:rootError,duration_ms:0},quality_budget:{ran:!1,error:rootError,duration_ms:0},total_duration_ms:0}}if(changedFiles.length>MAX_FILES)throw Error(`Input exceeds maximum file count: ${changedFiles.length} > ${MAX_FILES}`);let limit=pLimit(MAX_CONCURRENT),sastDisabledByConfig=gates?.sast_scan?.enabled===!1,[lintResult,secretscanResult,sastScanResult,qualityBudgetResult]=await Promise.all([limit(()=>_internals308.runLintWrapped(changedFiles,directory,gates,abortSignal)),limit(()=>_internals308.runSecretscanWrapped(changedFiles,directory,gates,abortSignal,rawDeclaredCount)),sast_enabled&&!sastDisabledByConfig?limit(()=>_internals308.runSastScanWrapped(changedFiles,directory,sast_threshold,gates,phase,abortSignal)):Promise.resolve({ran:!1,duration_ms:0}),limit(()=>_internals308.runQualityBudgetWrapped(changedFiles,directory,gates,abortSignal))]),totalDuration=lintResult.duration_ms+secretscanResult.duration_ms+sastScanResult.duration_ms+qualityBudgetResult.duration_ms,gatesPassed=!0;if(lintResult.ran&&lintResult.result){let lintRes=lintResult.result;if("success"in lintRes&&lintRes.success===!1)warn("pre_check_batch: Lint found issues (informational only)")}else if(lintResult.error)warn(`pre_check_batch: Lint error (informational only): ${lintResult.error}`);let secretscanDecision=evaluateSecretscanGate(secretscanResult,rawDeclaredCount);if(!secretscanDecision.passed)gatesPassed=!1,warn(`pre_check_batch: ${secretscanDecision.summary} - GATE FAILED`);if(secretscanResult.ran||secretscanResult.error)try{let scanResult=secretscanDecision.result,secretscanEvidence={task_id:"secretscan",type:"secretscan",timestamp:new Date().toISOString(),agent:"pre_check_batch",verdict:secretscanDecision.passed?"pass":"fail",summary:secretscanDecision.summary,findings_count:secretscanDecision.findingsCount,scan_directory:scanResult?.scan_dir??directory,files_scanned:scanResult?.files_scanned??0,skipped_files:scanResult?.skipped_files??0,ignored_files:scanResult?.ignored_files??0,policy_skipped_files:scanResult?.policy_skipped_files??0,requested_files:scanResult?.requested_files??rawDeclaredCount,incomplete_files:scanResult?.incomplete_files??changedFiles.length,incomplete_paths:scanResult?.incomplete_paths??[{path:".",reason:"missing_coverage_metadata"}]};await _internals308.saveEvidence(directory,"secretscan",secretscanEvidence,abortSignal)}catch(e){let persistError=`Failed to persist secretscan evidence: ${e instanceof Error?e.message:String(e)}`;secretscanResult.error=persistError,gatesPassed=!1,warn(`pre_check_batch: ${persistError} - GATE FAILED`)}let sastPreexistingFindings,sastDegraded=!1;if(sastScanResult.ran&&sastScanResult.result){let sastResult=sastScanResult.result;if(sastResult.error)if(sastResult.failure_kind==="semgrep_process_exit"&&sastResult.findings.length===0)sastDegraded=!0,warn(`pre_check_batch: SAST coverage degraded (${sastResult.error}) - continuing without a gate failure`);else gatesPassed=!1,warn(`pre_check_batch: SAST scan error (${sastResult.error}) - GATE FAILED`);else if(sastResult.baseline_used){let sastCarryFindings=[...sastResult.pre_existing_findings??[],...sastResult.moved_findings??[]];if(sastCarryFindings.length>0){if(sastPreexistingFindings=sastCarryFindings.filter((f)=>meetsThresholdForTriage(f.severity,sast_threshold)),sastPreexistingFindings.length>0)warn(`pre_check_batch: SAST baseline diff found ${sastPreexistingFindings.length} pre-existing/moved finding(s) - passing to reviewer for triage`)}if(sastResult.verdict==="fail")gatesPassed=!1,warn("pre_check_batch: SAST scan found new findings above threshold - GATE FAILED")}else if(sastResult.verdict==="fail"){let gateFindings=sastResult.findings.filter((f)=>GATE_SEVERITIES.has(f.severity));if(gateFindings.length>0){let changedLineRanges=await _internals308.getChangedLineRanges(directory,abortSignal,changedFiles),{newFindings,preexistingFindings}=classifySastFindings(gateFindings,changedLineRanges,directory);if(newFindings.length>0)gatesPassed=!1,warn(`pre_check_batch: SAST scan found ${newFindings.length} new HIGH/CRITICAL finding(s) on changed lines - GATE FAILED`);else if(preexistingFindings.length>0)sastPreexistingFindings=preexistingFindings,warn(`pre_check_batch: SAST scan found ${preexistingFindings.length} pre-existing HIGH/CRITICAL finding(s) on unchanged lines - passing to reviewer for triage`)}else gatesPassed=!1,warn("pre_check_batch: SAST scan found vulnerabilities - GATE FAILED")}}else if(sastScanResult.error)gatesPassed=!1,warn(`pre_check_batch: SAST scan error - GATE FAILED: ${sastScanResult.error}`);if(qualityBudgetResult.ran&&qualityBudgetResult.result){if(qualityBudgetResult.result.verdict==="fail")warn("pre_check_batch: Quality budget exceeded (informational only)")}else if(qualityBudgetResult.error)warn(`pre_check_batch: Quality budget error (informational only): ${qualityBudgetResult.error}`);return{batch_status:[lintResult,secretscanResult,sastScanResult,qualityBudgetResult].every((toolResult)=>toolResult.ran===!1)?"skipped":"completed",gates_passed:gatesPassed,lint:lintResult,secretscan:secretscanResult,sast_scan:sastScanResult,quality_budget:qualityBudgetResult,total_duration_ms:Math.round(totalDuration),...sastDegraded&&{sast_degraded:!0},...(!sast_enabled||sastDisabledByConfig)&&{sast_skipped:!0},...sastPreexistingFindings&&sastPreexistingFindings.length>0&&{sast_preexisting_findings:sastPreexistingFindings}}}var pre_check_batch=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Run multiple verification tools in parallel: lint, secretscan, SAST scan, and quality budget. Returns unified result with gates_passed status. Security findings and incomplete SAST runs are hard failures; a Semgrep nonzero process exit with zero findings is returned as explicit sast_degraded coverage and does not block.",args:{files:exports_external.array(exports_external.string()).optional().describe("Specific files to check (optional, scans directory if not provided)"),directory:exports_external.string().describe("Project root directory — ordinary workspace subdirectories are rejected; direct .git or .opencode project boundaries are accepted"),sast_threshold:exports_external.enum(["low","medium","high","critical"]).optional().describe("Minimum severity for SAST findings to cause failure (default: medium)"),phase:exports_external.number().int().min(1).optional().describe("Current phase number (positive integer >= 1). When provided, enables SAST baseline diffing: only findings absent from the phase-scoped baseline fail the gate.")},async execute(args2,directory,ctx){if(!args2||typeof args2!=="object")return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"Invalid arguments",duration_ms:0},secretscan:{ran:!1,error:"Invalid arguments",duration_ms:0},sast_scan:{ran:!1,error:"Invalid arguments",duration_ms:0},quality_budget:{ran:!1,error:"Invalid arguments",duration_ms:0},total_duration_ms:0});if(!directory||typeof directory!=="string"||directory.trim()==="")return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},secretscan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},sast_scan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},quality_budget:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},total_duration_ms:0});let typedArgs=args2;if(!typedArgs.directory)return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"directory is required",duration_ms:0},secretscan:{ran:!1,error:"directory is required",duration_ms:0},sast_scan:{ran:!1,error:"directory is required",duration_ms:0},quality_budget:{ran:!1,error:"directory is required",duration_ms:0},total_duration_ms:0});let resolvedDirectory=path360.resolve(typedArgs.directory),workspaceAnchor=path360.resolve(directory);if(isStrictPathDescendant(resolvedDirectory,workspaceAnchor)&&!hasExplicitProjectBoundary(resolvedDirectory)){let subDirError=`directory "${typedArgs.directory}" is a subdirectory of the project root — pre_check_batch requires the project root directory "${workspaceAnchor}"`;return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:subDirError,duration_ms:0},secretscan:{ran:!1,error:subDirError,duration_ms:0},sast_scan:{ran:!1,error:subDirError,duration_ms:0},quality_budget:{ran:!1,error:subDirError,duration_ms:0},total_duration_ms:0})}let dirError=validateDirectory2(resolvedDirectory,workspaceAnchor);if(dirError)return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0});try{let sastEnabled=!0;try{let preamble=await _internals308.resolveGatePreamble(resolvedDirectory,ctx?.sessionID);if(preamble.resolved&&preamble.effectiveGates)sastEnabled=preamble.effectiveGates.sast_enabled}catch{warn("pre_check_batch: QA-gate profile resolution failed; keeping SAST enabled")}let rawPhase=typedArgs.phase,safePhase=typeof rawPhase==="number"&&Number.isInteger(rawPhase)&&rawPhase>=1?rawPhase:void 0,result=await _internals308.runPreCheckBatch({files:typedArgs.files,directory:resolvedDirectory,sast_threshold:typedArgs.sast_threshold,config:typedArgs.config,gates:_internals308.loadGateOverrides(resolvedDirectory),phase:safePhase,sast_enabled:sastEnabled},workspaceAnchor,directory,ctx?.abort);return serializePreCheckResult(result)}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:errorMessage3,duration_ms:0},secretscan:{ran:!1,error:errorMessage3,duration_ms:0},sast_scan:{ran:!1,error:errorMessage3,duration_ms:0},quality_budget:{ran:!1,error:errorMessage3,duration_ms:0},total_duration_ms:0})}}});init_zod();init_guardrails2();init_pr_workflow_gate();init_scope_binding();init_create_tool();var PreparePrFeedbackScopeArgsSchema=exports_external.object({task_id:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/,"task_id must use N.M notation"),files:exports_external.array(exports_external.string().min(1).max(4096)).min(1).max(1e4)}).strict();function failure2(message){return JSON.stringify({success:!1,message},null,2)}async function executePreparePrFeedbackScope(args2,directory,context={}){let parsed=PreparePrFeedbackScopeArgsSchema.safeParse(args2);if(!parsed.success)return failure2(`Invalid PR-feedback scope: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure2("PR-feedback scope requires an active session");let files=normalizeScopeFiles(parsed.data.files);if(!files)return failure2("PR-feedback scope contains an unsafe file path");for(let file3 of files){let symlinkBlock=checkWriteTargetForSymlink(file3,directory);if(symlinkBlock)return failure2(symlinkBlock)}try{await declarePrFeedbackScope(directory,sessionID,parsed.data.task_id,files)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}return JSON.stringify({success:!0,task_id:parsed.data.task_id,files,message:"Scope is bound to the verified PR-feedback revision and will authorize only the next matching coder Task."},null,2)}var prepare_pr_feedback_scope=createSwarmTool({description:"Prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles.",args:{task_id:PreparePrFeedbackScopeArgsSchema.shape.task_id,files:PreparePrFeedbackScopeArgsSchema.shape.files},execute:executePreparePrFeedbackScope});init_quality_budget();init_zod();init_pr_workflow_gate();init_create_tool();var RebindPrFeedbackHeadArgsSchema=exports_external.object({pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{40}$/i)}).strict();async function executeRebindPrFeedbackHead(args2,directory,context={}){let parsed=RebindPrFeedbackHeadArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR feedback rebind: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR feedback rebind requires an active sessionID"});try{let state2=await rebindPrFeedbackHead(directory,context.sessionID,parsed.data.pr_head_sha);return JSON.stringify({success:!0,pr_head_sha:state2.prHeadSha,rebind_count:state2.prFeedbackRebindCount??1,message:"Rebound the PR_FEEDBACK intake head; every Stage A / verification / gate receipt is invalidated — re-run the full mechanical ladder on the new ancestry."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var rebind_pr_feedback_head=createSwarmTool({description:"Rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair (base-sync). Use ONLY when the history genuinely changed to repair base drift or conflicts: it refuses a no-op rebind to the current intake head, refuses while publication is armed (to change approved content after arming use invalidate_pr_feedback_publication), and refuses while lanes are in flight. It invalidates every ancestry-bound receipt (Stage A, verification, ordered gates) so the full mechanical ladder re-runs on the new ancestry. Requires the full 40-char new PR head SHA; the current checkout must equal it.",args:{pr_head_sha:RebindPrFeedbackHeadArgsSchema.shape.pr_head_sha},execute:executeRebindPrFeedbackHead});init_zod();init_utils2();init_atomic_write();init_create_tool();var FreshnessValueSchema=exports_external.string().trim().min(1).max(500).regex(/^(synced|behind:[1-9][0-9]*|fetch-failed:\S+)$/,"must be 'synced', 'behind:<n>', or 'fetch-failed:<reason>' (reason contains no whitespace)"),RecordBranchFreshnessArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),freshness:FreshnessValueSchema,override:exports_external.string().trim().min(1).max(4000).optional()}).strict();async function executeRecordBranchFreshness(args2,directory,context={}){let parsed=RecordBranchFreshnessArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid branch-freshness receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.freshness==="synced"&&data.override)return JSON.stringify({success:!1,message:"An override is only meaningful for a fetch-failed outcome; a synced base needs none."});let receipt={issueNumber:data.issueNumber,freshness:data.freshness,timestamp:new Date().toISOString()};if(data.override)receipt.override=data.override;if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"branch-freshness.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2));let permits=await branchFreshnessReceiptExists(directory,data.issueNumber);return JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/branch-freshness.json",permits,message:permits?`Branch-freshness receipt recorded for issue #${data.issueNumber}; the trace's freshness gate is satisfied.`:`Branch-freshness receipt recorded for issue #${data.issueNumber}, but the outcome (${data.freshness}) does NOT permit the trace — ${data.freshness.startsWith("behind:")?"re-sync with the default branch and re-record as synced.":"a fetch-failed outcome without a recorded user override fails closed."}`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_branch_freshness=createSwarmTool({description:`Record the Phase 0 branch-freshness outcome for the current traced issue (issue #2564): freshness is "synced", "behind:<n>", or "fetch-failed:<reason>" exactly as the fetch recorded it, plus an optional verbatim user override for a failed fetch. The /swarm issue --trace workflow will not transition to PLAN until the recorded outcome permits (synced, or fetch-failed with an override). The response's permits field mirrors the gate reader's verdict on the persisted receipt (advisory for the calling agent — the reducer always recomputes it independently).`,args:{issueNumber:RecordBranchFreshnessArgsSchema.shape.issueNumber,freshness:RecordBranchFreshnessArgsSchema.shape.freshness,override:RecordBranchFreshnessArgsSchema.shape.override},execute:executeRecordBranchFreshness});init_zod();init_schema();init_extractors();init_manager();init_create_tool();var recordDirectiveOverrideInternals={loadPlan,recordDirectiveOverrides};async function executeRecordDirectiveOverride(args2,directory,ctx){if(!ctx?.sessionID?.trim())return{success:!1,code:"DIRECTIVE_OVERRIDE_SESSION_REQUIRED",message:"An exact session identity is required to record an override."};if(stripKnownSwarmPrefix(ctx.agent??"").toLowerCase()!=="architect")return{success:!1,code:"DIRECTIVE_OVERRIDE_ARCHITECT_ONLY",message:"Only the architect may record a critical-directive override."};let plan=await recordDirectiveOverrideInternals.loadPlan(directory),requestedPhase=plan?.phases.find((candidate2)=>candidate2.id===args2.phase);if(!plan||!requestedPhase||plan.current_phase!==args2.phase)return{success:!1,code:"DIRECTIVE_OVERRIDE_PHASE_MISMATCH",message:`Phase ${args2.phase} is not the current authoritative plan phase.`};let phaseLabel=extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase}`;return await recordDirectiveOverrideInternals.recordDirectiveOverrides(directory,[...new Set(args2.directive_ids)],args2.justification,ctx.sessionID,phaseLabel,args2.phase),{success:!0,code:"DIRECTIVE_OVERRIDE_RECORDED",phase:args2.phase,directive_ids:[...new Set(args2.directive_ids)],message:"Recorded the audited override. Retry phase_complete so every gate is re-evaluated from a fresh snapshot."}}var record_directive_override=createSwarmTool({description:"Architect-only audited override for identified critical-directive violations. Requires exact current phase/session identity and substantive justification; it cannot repair or bypass unreadable authority.",args:{directive_ids:exports_external.array(exports_external.string().min(1).max(256)).min(1).max(64),justification:exports_external.string().trim().min(10).max(2000),phase:exports_external.number().int().min(1).max(9999)},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRecordDirectiveOverride(args2,directory,ctx),null,2)});init_zod();init_utils2();init_atomic_write();init_create_tool();var RecordImplementationReviewArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),reviewerVerdict:exports_external.enum(["APPROVE","NEEDS_REVISION","BLOCKED"]),criticVerdict:exports_external.enum(["APPROVE","NEEDS_REVISION","BLOCKED"]),diffBase:exports_external.string().trim().regex(/^[0-9a-f]{7,40}$/i),diffHead:exports_external.string().trim().regex(/^[0-9a-f]{7,40}$/i),notes:exports_external.string().trim().min(8).max(4000)}).strict();async function executeRecordImplementationReview(args2,directory,context={}){let parsed=RecordImplementationReviewArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid implementation review receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.reviewerVerdict!=="APPROVE"||data.criticVerdict!=="APPROVE")return JSON.stringify({success:!1,message:"A satisfying implementation-review receipt requires BOTH the reviewer and the critic to have delivered APPROVE; record non-approving verdicts in the working notes and fix the findings instead."});let receipt={issueNumber:data.issueNumber,reviewerVerdict:data.reviewerVerdict,criticVerdict:data.criticVerdict,diffBase:data.diffBase,diffHead:data.diffHead,notes:data.notes,timestamp:new Date().toISOString()};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"implementation-review.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/implementation-review.json",message:`Implementation review recorded for issue #${data.issueNumber} (reviewer APPROVE + critic APPROVE); the trace may now satisfy its review gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_implementation_review=createSwarmTool({description:"Record the independent implementation review for the current traced issue (issue #2131 residual B): dispatch FRESH-context reviewer and critic passes over the implementation diff (separate contexts from the implementer), and once BOTH approve call this with the issue number, both APPROVE verdicts, the reviewed diff base/head SHAs, and notes. The /swarm issue --trace workflow will not hand off to commit-pr until this receipt exists. Non-approving verdicts cannot be recorded here — fix the findings and re-review.",args:{issueNumber:RecordImplementationReviewArgsSchema.shape.issueNumber,reviewerVerdict:RecordImplementationReviewArgsSchema.shape.reviewerVerdict,criticVerdict:RecordImplementationReviewArgsSchema.shape.criticVerdict,diffBase:RecordImplementationReviewArgsSchema.shape.diffBase,diffHead:RecordImplementationReviewArgsSchema.shape.diffHead,notes:RecordImplementationReviewArgsSchema.shape.notes},execute:executeRecordImplementationReview});init_zod();init_url_security();init_loader();init_utils2();init_forge_provider();init_atomic_write();init_create_tool();function loadConfiguredForgeContext4(directory){try{let config3=loadPluginConfig(directory),remote=detectGitRemote(directory,void 0);return resolveForgeContextFromPluginConfig(config3,remote?[remote]:[])??void 0}catch{return}}var RecordIssuePublicationArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),prNumber:exports_external.number().int().min(1),prUrl:exports_external.string().url(),headSha:exports_external.string().min(1).optional()}).strict();async function executeRecordIssuePublication(args2,directory){let parsed=RecordIssuePublicationArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid publication receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let{issueNumber,prNumber,prUrl,headSha}=parsed.data,sanitizedPrUrl=sanitizeUrl(prUrl);if(!isForgePrUrl(prUrl)){let configured=loadConfiguredForgeContext4(directory);if(!(configured&&isForgePrUrl(prUrl,configured)))return JSON.stringify({success:!1,message:"Invalid publication receipt: prUrl must be a canonical PR URL (GitHub https://github.com/<owner>/<repo>/pull/<number> or GitLab https://<gitlab-host>/<owner>/<repo>/-/merge_requests/<number>)"})}let receipt={published:!0,issueNumber,prNumber,prUrl:sanitizedPrUrl,publishedAt:new Date().toISOString()};if(headSha)receipt.headSha=headSha;let validatedPath;try{validatedPath=validateSwarmPath(directory,"issue-publication.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber,prNumber,prUrl,path:".swarm/issue-publication.json",message:`Publication receipt recorded for issue #${issueNumber} (PR #${prNumber}); the issue-trace workflow will transition to its terminal published state.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_issue_publication=createSwarmTool({description:'Record that the traced issue has been published (PR created/updated) so the /swarm issue --trace workflow can reach its terminal published state. The trace stops at publication_handoff (the commit-pr directive) until this receipt is observed — publication_handoff is NOT "issue resolved". commit-pr calls this after the PR is created/updated. Supply the traced issue number, the exact PR number, the canonical PR URL (GitHub or GitLab), and (optionally) the published HEAD sha. The receipt is issue-bound.',args:{issueNumber:RecordIssuePublicationArgsSchema.shape.issueNumber,prNumber:RecordIssuePublicationArgsSchema.shape.prNumber,prUrl:RecordIssuePublicationArgsSchema.shape.prUrl,headSha:RecordIssuePublicationArgsSchema.shape.headSha},execute:executeRecordIssuePublication});init_zod();init_utils2();init_atomic_write();init_create_tool();var RecordIssueReproductionArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),performed:exports_external.boolean(),commands:exports_external.array(exports_external.string().min(1)).min(1).optional(),output_summary:exports_external.string().min(1).optional()}).strict();async function executeRecordIssueReproduction(args2,directory,context={}){let parsed=RecordIssueReproductionArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid reproduction receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let{issueNumber,performed,commands,output_summary}=parsed.data;if(performed&&(!commands||commands.length===0||!output_summary))return JSON.stringify({success:!1,message:"A performed=true reproduction receipt requires non-empty commands and output_summary."});let receipt={performed,issueNumber,timestamp:new Date().toISOString()};if(commands)receipt.commands=commands;if(output_summary)receipt.output_summary=output_summary;if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"reproduction.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber,performed,path:".swarm/reproduction.json",message:performed?`Reproduction receipt recorded for issue #${issueNumber}; the trace may now transition to PLAN.`:`Reproduction receipt recorded (performed=false) for issue #${issueNumber}; it does NOT satisfy the reproduction gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_issue_reproduction=createSwarmTool({description:"Record the reproduction outcome for the current traced issue. The /swarm issue --trace workflow requires reproduction evidence (or a typed --no-repro waiver) before it can leave localization and transition to PLAN. Call this with performed=true, the exact commands run, and a concrete output_summary after attempting a minimal reproduction; the receipt binds to issueNumber (and records the calling session) and is read by the issue-trace engine. A performed=true receipt MUST include commands and output_summary. A performed=false receipt is recorded but does NOT satisfy the gate.",args:{issueNumber:RecordIssueReproductionArgsSchema.shape.issueNumber,performed:RecordIssueReproductionArgsSchema.shape.performed,commands:RecordIssueReproductionArgsSchema.shape.commands,output_summary:RecordIssueReproductionArgsSchema.shape.output_summary},execute:executeRecordIssueReproduction});init_zod();init_utils2();init_atomic_write();init_create_tool();var HEX40=/^[0-9a-f]{40}$/,RecordMergeApprovalArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),prHeadSha:exports_external.string().regex(HEX40,"must be a 40-hex commit SHA"),finalCriticReviewedCommit:exports_external.string().regex(HEX40,"must be a 40-hex commit SHA"),userApprovalVerbatim:exports_external.string().trim().min(1).max(8000)}).strict();async function executeRecordMergeApproval(args2,directory,context={}){let parsed=RecordMergeApprovalArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid merge-approval receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.prHeadSha!==data.finalCriticReviewedCommit)return JSON.stringify({success:!1,message:"Merge-approval binding failed: prHeadSha must equal finalCriticReviewedCommit (the final critic approval must be bound to the exact PR head)."});let receipt={issueNumber:data.issueNumber,prHeadSha:data.prHeadSha,finalCriticReviewedCommit:data.finalCriticReviewedCommit,userApprovalVerbatim:data.userApprovalVerbatim,timestamp:new Date().toISOString()};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"merge-approval.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/merge-approval.json",message:`Merge approval recorded for issue #${data.issueNumber}, bound to PR head ${data.prHeadSha}. The approval is captured verbatim for audit; the merge itself is human-enforced and this plugin neither drives nor certifies it.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_merge_approval=createSwarmTool({description:"Record the human merge approval for the current traced issue (issue #2564): prHeadSha and finalCriticReviewedCommit must be the same 40-hex SHA (the final critic approval bound to the exact PR head), and userApprovalVerbatim is the user approval quoted verbatim. The receipt is recorded for audit only — the merge stays human-enforced and the plugin never certifies or drives it.",args:{issueNumber:RecordMergeApprovalArgsSchema.shape.issueNumber,prHeadSha:RecordMergeApprovalArgsSchema.shape.prHeadSha,finalCriticReviewedCommit:RecordMergeApprovalArgsSchema.shape.finalCriticReviewedCommit,userApprovalVerbatim:RecordMergeApprovalArgsSchema.shape.userApprovalVerbatim},execute:executeRecordMergeApproval});init_zod();init_utils2();init_atomic_write();init_create_tool();var DispositionSchema=exports_external.object({ref:exports_external.string().trim().min(1).max(500),disposition:exports_external.enum(["FIX","FALSE_POSITIVE","OUT_OF_CLASS","DEFERRED_WITH_USER_APPROVAL"]),note:exports_external.string().trim().max(1000).optional()}).strict(),GuardrailSchema=exports_external.object({kind:exports_external.enum(["lint-static-analysis","type-level","runtime-assertion","ci-check","documented-invariant-plus-regression-test"]),description:exports_external.string().trim().min(8).max(2000),proof:exports_external.string().trim().min(8).max(4000)}).strict(),RelatedProblemSchema=exports_external.object({ref:exports_external.string().trim().min(1).max(500),note:exports_external.string().trim().max(1000).optional()}).strict(),RecordRecurrenceSweepArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),defectClass:exports_external.string().trim().min(1).max(1000),justification:exports_external.string().trim().min(1).max(1000).optional(),predicates:exports_external.array(exports_external.string().trim().min(1).max(500)).min(1).max(32).optional(),dispositions:exports_external.array(DispositionSchema).min(1).max(200).optional(),guardrail:GuardrailSchema.optional(),relatedProblems:exports_external.array(RelatedProblemSchema).min(1).max(200)}).strict();async function executeRecordRecurrenceSweep(args2,directory,context={}){let parsed=RecordRecurrenceSweepArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recurrence sweep receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data,noDefectClass=data.defectClass==="no defect class";if(noDefectClass){if(!data.justification)return JSON.stringify({success:!1,message:'The "no defect class" fast path requires a one-line justification.'})}else if(!data.predicates||data.predicates.length===0||!data.dispositions||data.dispositions.length===0||!data.guardrail)return JSON.stringify({success:!1,message:"A defect-class sweep requires search predicates, a non-empty disposition for every hit (at least one — the original defect site itself, dispositioned FIX), and a guardrail with proof it catches the original defect. An empty dispositions array is indistinguishable from a sweep that never ran."});let receipt={issueNumber:data.issueNumber,defectClass:data.defectClass,timestamp:new Date().toISOString()};if(data.justification)receipt.justification=data.justification;if(data.predicates)receipt.predicates=data.predicates;if(data.dispositions)receipt.dispositions=data.dispositions;if(data.guardrail)receipt.guardrail=data.guardrail;if(receipt.relatedProblems=data.relatedProblems,context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"recurrence-sweep.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/recurrence-sweep.json",message:noDefectClass?`Recurrence sweep recorded for issue #${data.issueNumber} (no defect class fast path).`:`Recurrence sweep recorded for issue #${data.issueNumber}; the trace may now satisfy its recurrence gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_recurrence_sweep=createSwarmTool({description:'Record the recurrence sweep for the current traced issue (issue #2131 residual B; widened in #2564 and #2600). The /swarm issue --trace workflow will not hand off to commit-pr until this receipt exists. Supply relatedProblems (the Phase 1 related-problems sweep results — at least one {ref, note?} entry) plus, for a real defect class: defectClass (one-sentence characterization), predicates (the exact search predicates), dispositions (non-empty — every hit as FIX / FALSE_POSITIVE / OUT_OF_CLASS / DEFERRED_WITH_USER_APPROVAL, including the original defect site), and a guardrail (kind + description + proof it catches the original defect). If the change corrects no incorrect behavior, use the literal defectClass "no defect class" with a one-line justification (relatedProblems still required).',args:{issueNumber:RecordRecurrenceSweepArgsSchema.shape.issueNumber,defectClass:RecordRecurrenceSweepArgsSchema.shape.defectClass,justification:RecordRecurrenceSweepArgsSchema.shape.justification,predicates:RecordRecurrenceSweepArgsSchema.shape.predicates,dispositions:RecordRecurrenceSweepArgsSchema.shape.dispositions,guardrail:RecordRecurrenceSweepArgsSchema.shape.guardrail,relatedProblems:RecordRecurrenceSweepArgsSchema.shape.relatedProblems},execute:executeRecordRecurrenceSweep});init_zod();import*as fs219 from"node:fs";init_utils2();init_file_locks();init_atomic_write();init_create_tool();var HEX402=/^[0-9a-f]{40}$/,TRACE_VALIDATION_PHASES2=["0","1","2","2.5","3","4","4.2","4.5","4.6","5"],ValidationEntrySchema=exports_external.object({phase:exports_external.enum(TRACE_VALIDATION_PHASES2),outcome:exports_external.enum(["pass","fail"]),reviewedCommit:exports_external.string().regex(HEX402,"must be a 40-hex commit SHA"),treeId:exports_external.string().regex(HEX402,"must be a 40-hex tree id")}).strict(),RecordTraceValidationArgsSchema=ValidationEntrySchema.extend({issueNumber:exports_external.number().int().min(1)}).strict();async function executeRecordTraceValidation(args2,directory,context={}){let parsed=RecordTraceValidationArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid trace-validation receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data,validatedPath;try{validatedPath=validateSwarmPath(directory,"trace-validation.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{let lockResult=await tryAcquireLock(directory,"trace-validation.json","trace-validation","trace-validation");if(!lockResult.acquired)return JSON.stringify({success:!1,message:"The trace-validation receipt is locked by another concurrent writer; no write was attempted. Re-run record_trace_validation for this phase once the other writer finishes."});try{let validations=[];try{let raw=await fs219.promises.readFile(validatedPath,"utf-8"),existing=JSON.parse(raw);if(typeof existing==="object"&&existing!==null&&Array.isArray(existing.validations))validations=existing.validations.filter((v)=>typeof v==="object"&&v!==null&&typeof v.phase==="string")}catch{}let entry={phase:data.phase,outcome:data.outcome,reviewedCommit:data.reviewedCommit,treeId:data.treeId,timestamp:new Date().toISOString()},idx=validations.findIndex((v)=>v.phase===data.phase);if(idx===-1)validations.push(entry);else validations[idx]=entry;let receipt={issueNumber:data.issueNumber,timestamp:new Date().toISOString(),validations};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2));let allGreen=await traceValidationReceiptExists(directory,data.issueNumber);return JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/trace-validation.json",allGreen,message:allGreen?`Validator receipt recorded for issue #${data.issueNumber} phase ${data.phase} (${data.outcome}); every recorded phase is green.`:`Validator receipt recorded for issue #${data.issueNumber} phase ${data.phase} (${data.outcome}), but at least one recorded phase is failing — fix and re-record that phase as a pass before handoff.`})}finally{try{await lockResult.lock._release?.()}catch{}}}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_trace_validation=createSwarmTool({description:"Record one per-phase trace-check.sh validator outcome for the current traced issue (issue #2564): the phase (v3 enum 0..5 incl. 2.5/4.2/4.5/4.6), the outcome (pass or fail), and the exact reviewedCommit and treeId the validator reported. Re-running a phase replaces its entry. The /swarm issue --trace workflow will not hand off to commit-pr while any recorded phase is failing or none is recorded. The receipt write is serialized by a per-file receipt lock, and the response's allGreen field mirrors the gate reader's verdict on the persisted receipt (advisory for the calling agent — the reducer always recomputes it independently).",args:{issueNumber:RecordTraceValidationArgsSchema.shape.issueNumber,phase:RecordTraceValidationArgsSchema.shape.phase,outcome:RecordTraceValidationArgsSchema.shape.outcome,reviewedCommit:RecordTraceValidationArgsSchema.shape.reviewedCommit,treeId:RecordTraceValidationArgsSchema.shape.treeId},execute:executeRecordTraceValidation});init_zod();init_schema();init_gate_evidence();init_manager();init_path_identity();init_state();init_stage_a_repair();import*as fs220 from"node:fs";import*as path361 from"node:path";async function forceRecoverReworkTask(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("RECOVER_REWORK_ARCHITECT_REQUIRED: recover_rework_task requires an active architect session. The rework escape hatch is architect-only; a coder/reviewer/test_engineer cannot self-unblock a task.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('RECOVER_REWORK_UNKNOWN_TASK: recover_rework_task requires the exact plan task id (e.g. "1.1").');let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path361.join(directory,".swarm","plan.json");if(fs220.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recovering a rework_required task.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot recover a rework_required "+"task without a plan. Save a plan first.")}if(!new Set(plan.phases.flatMap((phase)=>phase.tasks.map((task2)=>task2.id))).has(taskId))throw Error(`RECOVER_REWORK_UNKNOWN_TASK: task ${taskId} is not in the current plan. Refusing to recover a foreign task id.`);let evidenceRead=await readTaskEvidenceState(directory,taskId);if(evidenceRead.kind==="unparseable")throw Error(`RECOVER_REWORK_EVIDENCE_CORRUPT: the workflow evidence file for task ${taskId} exists but could not be parsed (${evidenceRead.evidencePath}). Repair the evidence first (repair_gate_evidence or /swarm doctor); recovery cannot classify a corrupt evidence state.`);let evidence2=evidenceRead.kind==="ok"?evidenceRead.evidence:null,workflow=getTaskWorkflowSnapshot(evidence2);if(!evidence2||!workflow.authoritative)throw Error(`RECOVER_REWORK_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no rework state to recover.`);if(workflow.state!=="rework_required")throw Error(`RECOVER_REWORK_STATE_REQUIRED: task ${taskId} is at ${workflow.state}, not rework_required. This recovery applies only to a task whose Stage B verdict moved it to rework_required without a code change. From coder_delegated, run pre_check_batch; for a genuine code defect, delegate the coder to repair it first.`);let wedgeMs=Date.parse(workflow.updatedAt);if(!Number.isFinite(wedgeMs))throw Error(`RECOVER_REWORK_GREEN_PRECHECK_REQUIRED: cannot prove pre-check recency (workflow updatedAt "${workflow.updatedAt}" is not a parseable timestamp — the evidence file for task ${taskId} is likely corrupt). Repair the evidence (repair_gate_evidence or /swarm doctor); re-running pre_check_batch cannot fix an unparseable timestamp.`);let greenness=await hasGreenPostSettlementPreCheck(directory,wedgeMs);if(!greenness.green){let sastHint=greenness.reason==="no_pre_check_bundles"?" Note: if gates.sast_scan.enabled is false, no sast_scan bundle is ever persisted and this recovery is unavailable by design — enable gates.sast_scan.enabled and run sast_scan, or use the coder repair loop.":"";throw Error(`RECOVER_REWORK_GREEN_PRECHECK_REQUIRED: refusing to mark Stage A passed without proof (${greenness.reason}). `+"The bar is a green secretscan AND sast_scan evidence pair newer than the failing verdict — normally provided by a fresh pre_check_batch run (bundle proof is global, not correlated to the task's changed files)."+sastHint)}let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?sanitizeDiagnosticText(options.reason.trim(),500):void 0,recordedAt=new Date().toISOString(),transitionId=`rework-recovery:${taskId}:gen${workflow.generation}`,updated=await transitionTaskWorkflowEvidence(directory,taskId,{type:"stage_a_passed",supervisedRecovery:!0,expectedGeneration:workflow.generation,transitionId}),updatedWorkflow=getTaskWorkflowSnapshot(updated),auditEventRecorded=await appendStageARepairEvent(directory,{action:"rework_recovered",taskId,transitionId,generation:workflow.generation,sessionId:sessionID,...sanitizedReason?{reason:sanitizedReason}:{}});return{taskId,generation:updatedWorkflow.generation,state:updatedWorkflow.state,transitionId,recordedAt,auditEventRecorded}}init_create_tool();var RecoverReworkTaskArgsSchema=exports_external.object({task_id:exports_external.string().trim().min(1).max(64).describe('Exact plan task id of the rework_required task (e.g. "1.1"). Must exist in the current plan and have durable workflow evidence at state rework_required.'),reason:exports_external.string().trim().min(1).max(500).describe('Why the Stage B verdict did not require a code change (e.g. "test_engineer returned SKIPPED for a tool-argument error while pytest passes"). Audited to .swarm/events.jsonl.')}).strict();async function executeRecoverReworkTask(args2,directory,context={}){let parsed=RecoverReworkTaskArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recover_rework_task call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"recover_rework_task requires an active sessionID"});try{let summary=await forceRecoverReworkTask(directory,context.sessionID,{taskId:parsed.data.task_id,reason:parsed.data.reason}),auditNote=summary.auditEventRecorded?"The recovery is audited to .swarm/events.jsonl (stage_a_repair action rework_recovered).":"WARNING: the audit event could NOT be appended to .swarm/events.jsonl (see the plugin log); the durable workflow evidence still records the supervised recovery via the rework-recovery: transition id.";return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,transition_id:summary.transitionId,recorded_at:summary.recordedAt,audit_event_recorded:summary.auditEventRecorded,method:"supervised_recovery",message:`Task ${summary.taskId} recovered from rework_required: a supervised stage_a_passed was written at generation ${summary.generation} (transition id `+summary.transitionId+"). Reviewer/test_engineer dispatch is permitted again — re-run the Stage B gates that the failed verdict cleared. "+auditNote+" Use it ONLY when the Stage B verdict did not require a code change; a genuine defect still needs the coder repair loop."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var recover_rework_task=createSwarmTool({description:"Recover a task wedged at rework_required when the Stage B verdict did NOT require a code change (issue #2755): writes a supervised stage_a_passed for the current generation so reviewer/test_engineer can be re-dispatched, without re-running the coder. Requires the exact plan task id, an active architect session, durable workflow state exactly rework_required, and green pre-check proof: green secretscan AND sast_scan evidence bundles newer than the failing verdict (normally from a fresh pre_check_batch run; bundle recency is global, not file-correlated; projects with SAST disabled cannot use this path). Fail-closed otherwise; the mechanical stage_a_passed path still requires an accepted coder mutation. A reason is required and audited to .swarm/events.jsonl (stage_a_repair action rework_recovered). Prefer the coder repair loop when the code actually has a defect.",args:{task_id:RecoverReworkTaskArgsSchema.shape.task_id,reason:RecoverReworkTaskArgsSchema.shape.reason},execute:executeRecoverReworkTask});init_zod();init_schema();init_gate_evidence();init_path_identity();init_state();init_coder_settlement();init_session_view();init_stage_a_repair();async function recoverStageATaskSupervised(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("RECOVER_STAGE_A_ARCHITECT_REQUIRED: recover_stage_a_task requires an active architect session. The settlement-backed Stage A escape hatch is architect-only; a coder/reviewer/test_engineer cannot self-unblock a task.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('RECOVER_STAGE_A_UNKNOWN_TASK: recover_stage_a_task requires the exact task id of the settlement-wedged task (e.g. "1.1").');let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?sanitizeDiagnosticText(options.reason.trim(),500):void 0;if(!sanitizedReason)throw Error("RECOVER_STAGE_A_REASON_REQUIRED: recover_stage_a_task requires a reason describing why the settlement-backed recovery is justified; it is audited to .swarm/events.jsonl.");let evidenceRead=await readTaskEvidenceState(directory,taskId);if(evidenceRead.kind==="unparseable")throw Error(`RECOVER_STAGE_A_EVIDENCE_CORRUPT: the workflow evidence file for task ${taskId} exists but could not be parsed (${evidenceRead.evidencePath}). Repair the evidence first (repair_gate_evidence or /swarm doctor); recovery cannot classify a corrupt evidence state.`);let evidence2=evidenceRead.kind==="ok"?evidenceRead.evidence:null,workflow=getTaskWorkflowSnapshot(evidence2);if(!evidence2||!workflow.authoritative)throw Error(`RECOVER_STAGE_A_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no settlement wedge to recover.`);if(workflow.state==="pre_check_passed"||workflow.state==="reviewer_run"||workflow.state==="tests_run"){if(isStageARecoveredState(workflow.state)&&shouldRefreshStageARecoveryView(session.taskWorkflowStates.get(taskId),workflow.state))applySessionWorkflowView(session,taskId,workflow);return{taskId,generation:workflow.generation,state:workflow.state,transitionId:`stage-a-supervised:${taskId}:noop`,recordedAt:new Date().toISOString(),alreadyRecovered:!0,auditEventRecorded:!1}}if(workflow.state!=="idle"&&workflow.state!=="blocked")throw Error(`RECOVER_STAGE_A_STATE_REQUIRED: task ${taskId} is at ${workflow.state}, not idle/blocked. This recovery applies only to the settlement-backed wedge (a COMMITTED accepted coder settlement while the workflow drifted to idle or blocked). From coder_delegated, run pre_check_batch or /swarm recover; from rework_required without a code change, use recover_rework_task.`);let{states:walStates}=await listCoderSettlementWalStates(directory),settledAfterMs=latestCommittedAcceptedSettlementMs(taskId,walStates);if(settledAfterMs===null)throw Error(`RECOVER_STAGE_A_SETTLEMENT_REQUIRED: refusing to recover task ${taskId} — no COMMITTED accepted coder settlement exists for it. `+"The settlement receipt is what distinguishes this wedge from a not-yet-started or deliberately stopped task; recovery without it would fabricate Stage A justification. Background-dispatched coder tasks never write a settlement WAL and cannot use this path.");let greenness=await hasGreenPostSettlementPreCheck(directory,settledAfterMs);if(!greenness.green){let sastHint=greenness.reason==="no_pre_check_bundles"?" Note: if gates.sast_scan.enabled is false, no sast_scan bundle is ever persisted and this recovery is unavailable by design — enable gates.sast_scan.enabled and run sast_scan, or use the coder repair loop.":"";throw Error(`RECOVER_STAGE_A_GREEN_PRECHECK_REQUIRED: refusing to mark Stage A passed without proof (${greenness.reason}). `+"The bar is a green secretscan AND sast_scan evidence pair newer than the settlement commit — normally provided by a fresh pre_check_batch run (bundle proof is global, not correlated to the task's changed files)."+sastHint)}let recordedAt=new Date().toISOString(),transitionId=`stage-a-supervised:${taskId}:${workflow.generation}`,updated=await transitionTaskWorkflowEvidence(directory,taskId,{type:"stage_a_passed",settlementRecovery:!0,expectedGeneration:workflow.generation,transitionId}),updatedWorkflow=getTaskWorkflowSnapshot(updated);if(isStageARecoveredState(updatedWorkflow.state)){if(shouldRefreshStageARecoveryView(session.taskWorkflowStates.get(taskId),updatedWorkflow.state))applySessionWorkflowView(session,taskId,updatedWorkflow)}let auditEventRecorded=await appendStageARepairEvent(directory,{action:"repaired",via:"recover_stage_a_task",taskId,transitionId,generation:workflow.generation,settlementRecovery:!0,predecessorTransitionId:workflow.lastTransitionId??null,sessionId:sessionID,reason:sanitizedReason});return{taskId,generation:updatedWorkflow.generation,state:updatedWorkflow.state,transitionId,recordedAt,alreadyRecovered:!1,auditEventRecorded}}init_create_tool();var RecoverStageATaskArgsSchema=exports_external.object({task_id:exports_external.string().trim().min(1).max(64).describe('Exact task id of the settlement-wedged task (e.g. "1.1"). Must have durable workflow evidence at state idle or blocked, a COMMITTED accepted coder settlement, and green post-settlement pre-check proof.'),reason:exports_external.string().trim().min(1).max(500).describe('Why the settlement-backed recovery is justified (e.g. "settlement COMMITTED and pre_check_batch green but stage_a_passed never fired; force-repair cleared the proofs"). Audited to .swarm/events.jsonl.')}).strict();async function executeRecoverStageATask(args2,directory,context={}){let parsed=RecoverStageATaskArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recover_stage_a_task call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"recover_stage_a_task requires an active sessionID"});try{let summary=await recoverStageATaskSupervised(directory,context.sessionID,{taskId:parsed.data.task_id,reason:parsed.data.reason});if(summary.alreadyRecovered)return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,already_recovered:!0,message:`Task ${summary.taskId} already has Stage A recorded (state ${summary.state}, generation ${summary.generation}) — nothing to recover.`});let auditNote=summary.auditEventRecorded?"The recovery is audited to .swarm/events.jsonl (stage_a_repair action repaired, via recover_stage_a_task).":"WARNING: the audit event could NOT be appended to .swarm/events.jsonl (see the plugin log); the durable workflow evidence still records the settlement-backed recovery via the stage-a-supervised: transition id and the settlementRecovery marker.";return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,transition_id:summary.transitionId,recorded_at:summary.recordedAt,audit_event_recorded:summary.auditEventRecorded,method:"settlement_recovery",message:`Task ${summary.taskId} recovered from the settlement wedge: a settlement-backed stage_a_passed was written at generation ${summary.generation} (transition id `+summary.transitionId+"). Reviewer/test_engineer dispatch is permitted again — run the Stage B gates the task still needs. "+auditNote+" Use it ONLY when a COMMITTED accepted settlement and green post-settlement pre-check proof already justify Stage A; it never re-runs the coder and never edits gate evidence."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var recover_stage_a_task=createSwarmTool({description:"Recover a task wedged in the settlement-backed Stage A deadlock (issue #2828): workflow at idle or blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof (green secretscan AND sast_scan evidence newer than the settlement commit) still justify Stage A — the shape where stage_a_passed never fired, a force-repair cleared the proofs, and every other recovery path refuses. Writes a settlement-backed stage_a_passed for the current generation so reviewer/test_engineer can be dispatched, without re-running the coder and without editing gate evidence. Requires the exact task id (bound by its durable workflow evidence and settlement WAL — deliberately no plan-membership precondition, mirroring the /swarm recover scan), an active architect session, a reason (audited), and durable workflow evidence at exactly idle/blocked. Fail-closed otherwise (RECOVER_STAGE_A_* errors); the mechanical stage_a_passed path still requires an accepted coder mutation or the #2665 live_wedge scan.",args:{task_id:RecoverStageATaskArgsSchema.shape.task_id,reason:RecoverStageATaskArgsSchema.shape.reason},execute:executeRecoverStageATask});init_zod();init_schema();init_gate_evidence();init_utils2();init_manager();init_state();init_project_boundary();init_swarm_artifact_cache();init_task_id();init_task_file();init_task_gate_requirements();init_gate_evidence();import{createHash as createHash117,randomUUID as randomUUID48}from"node:crypto";import*as fs221 from"node:fs";import*as path362 from"node:path";var TASK_GATE_EVIDENCE_QUARANTINE_DIR=path362.join("evidence","task-gate-quarantine"),MAX_TASK_GATE_EVIDENCE_BYTES=262144,MAX_TASK_GATE_EVIDENCE_QUARANTINE_FILES=32,MAX_TASK_GATE_EVIDENCE_QUARANTINE_BYTES=12582912,MAX_TASK_GATE_EVIDENCE_QUARANTINE_DIRECTORY_ENTRIES=128,MAX_TASK_GATE_EVIDENCE_QUARANTINE_RECORD_BYTES=786432,TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION=1,GENERIC_REPAIR_REASONS=new Set(["fix","repair","test","debug","unknown","n/a","na","none"]);function isQuarantinableTaskEvidenceRead(read){return read.status==="corrupt"||read.status==="valid"}function sha25614(bytes){return createHash117("sha256").update(bytes).digest("hex")}function normalizeRepairReason(reason){let normalized=reason.trim().replace(/\s+/g," ");if(normalized.length<12)throw Error("TASK_GATE_EVIDENCE_REASON_REQUIRED: repair_gate_evidence requires a substantive reason of at least 12 characters.");if(GENERIC_REPAIR_REASONS.has(normalized.toLowerCase()))throw Error("TASK_GATE_EVIDENCE_REASON_REQUIRED: repair_gate_evidence requires a substantive reason, not a placeholder.");return normalized}function canonicalizeRepairRoot(directory){let requestedRoot=path362.resolve(directory),requestedStat=fs221.lstatSync(requestedRoot);if(requestedStat.isSymbolicLink()||!requestedStat.isDirectory())throw Error("TASK_GATE_EVIDENCE_ROOT_UNSAFE: repair_gate_evidence requires a canonical project root directory, not a symlink, junction, reparse point, or non-directory path.");let canonicalRoot2=fs221.realpathSync(requestedRoot);return assertProjectRoot(canonicalRoot2),canonicalRoot2}function assertExistingRegularPath(root,relativePath2){let segments=relativePath2.replace(/\\/g,"/").split("/").filter(Boolean),cursor=root;for(let segment of segments){if(cursor=path362.join(cursor,segment),!fs221.existsSync(cursor))return;if(fs221.lstatSync(cursor).isSymbolicLink())throw Error(`TASK_GATE_EVIDENCE_PATH_UNSAFE: ${relativePath2} contains a symlink, junction, or reparse point.`)}}function taskEvidenceFilePath(directory,taskId){let relativePath2=taskEvidenceRelPath(taskId);return assertExistingRegularPath(directory,".swarm"),assertExistingRegularPath(directory,path362.join(".swarm","evidence")),assertExistingRegularPath(directory,path362.join(".swarm",relativePath2)),validateSwarmPath(directory,relativePath2)}function readTaskEvidenceForRepair(directory,taskId){let filePath=taskEvidenceFilePath(directory,taskId),pathStat;try{pathStat=fs221.lstatSync(filePath)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:error93}}if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:Error("TASK_GATE_EVIDENCE_UNREADABLE: evidence path is not a regular file")};if(pathStat.size>MAX_TASK_GATE_EVIDENCE_BYTES)return{status:"oversized",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:Error(`TASK_GATE_EVIDENCE_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_EVIDENCE_BYTES}`)};let descriptor=fs221.openSync(filePath,fs221.constants.O_RDONLY|(fs221.constants.O_NOFOLLOW??0));try{let openedStat=fs221.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:Error("TASK_GATE_EVIDENCE_UNREADABLE: evidence changed while being opened")};let bytes=fs221.readFileSync(descriptor);if(bytes.byteLength>MAX_TASK_GATE_EVIDENCE_BYTES)return{status:"oversized",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:Error(`TASK_GATE_EVIDENCE_OVERSIZED: ${bytes.byteLength} bytes exceeds ${MAX_TASK_GATE_EVIDENCE_BYTES}`)};let digest5=sha25614(bytes);try{let evidence2=parseTaskEvidence(bytes.toString("utf8"),taskId);return{status:"valid",filePath,bytes,sha256:digest5,evidence:evidence2,generation:evidence2.workflow?.generation}}catch(error93){return{status:"corrupt",filePath,bytes,sha256:digest5,error:error93}}}finally{try{fs221.closeSync(descriptor)}catch{}}}function taskGateEvidenceQuarantinePath(directory,taskId,digest5){return validateSwarmPath(directory,path362.join(TASK_GATE_EVIDENCE_QUARANTINE_DIR,`${taskId}.${digest5}.v${TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION}.json`))}function parseErrorMetadata(error93){if(!error93)return null;return{name:error93.name||"Error",message:error93.message||String(error93),code:typeof error93.code==="string"?error93.code:null}}function parseQuarantineRecord(raw){try{let parsed=JSON.parse(raw);if(parsed?.schemaVersion!==TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION||typeof parsed.taskId!=="string"||typeof parsed.recordedAt!=="string"||typeof parsed.reason!=="string"||typeof parsed.original?.path!=="string"||typeof parsed.original?.sha256!=="string"||typeof parsed.content?.bytes!=="string"||parsed.content?.encoding!=="base64")return null;return parsed}catch{return null}}function buildQuarantineRecord(taskId,read,reason,context,receiptGeneration){let agentName=context?.sessionID!=null?swarmState.activeAgent.get(context.sessionID)??swarmState.agentSessions.get(context.sessionID)?.agentName??null:null;return{schemaVersion:TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION,taskId,recordedAt:new Date().toISOString(),reason,caller:{sessionId:context?.sessionID?.trim()||null,messageId:context?.messageID?.trim()||null,agentName},original:{path:read.filePath,sha256:read.sha256,sizeBytes:read.bytes.byteLength,status:read.status,observedGeneration:read.generation??null,receiptGeneration,requirementsState:read.evidence?.requirements_state??null},parseError:parseErrorMetadata(read.error),content:{encoding:"base64",bytes:read.bytes.toString("base64")}}}async function quarantineTaskEvidenceBytes(directory,taskId,read,reason,context,receiptGeneration){let digest5=read.sha256,quarantineDir=validateSwarmPath(directory,TASK_GATE_EVIDENCE_QUARANTINE_DIR);await fs221.promises.mkdir(quarantineDir,{recursive:!0});let dirStat=await fs221.promises.lstat(quarantineDir);if(dirStat.isSymbolicLink()||!dirStat.isDirectory())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_UNREADABLE: quarantine is not a regular directory");let target=taskGateEvidenceQuarantinePath(directory,taskId,digest5),record3=buildQuarantineRecord(taskId,read,reason,context,receiptGeneration),serialized3=JSON.stringify(record3,null,2),serializedBytes=Buffer.byteLength(serialized3,"utf8");if(serializedBytes>MAX_TASK_GATE_EVIDENCE_QUARANTINE_RECORD_BYTES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: quarantine payload exceeds the bounded record size limit");let reconcileExisting=async()=>{let existingStat;try{existingStat=await fs221.promises.lstat(target)}catch(error93){if(error93.code==="ENOENT")return!1;throw error93}if(existingStat.isSymbolicLink()||!existingStat.isFile())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_MISMATCH: existing quarantine path is not a regular immutable record");let existingRaw=await fs221.promises.readFile(target,"utf8"),existingRecord=parseQuarantineRecord(existingRaw);if(existingRecord&&existingRecord.taskId===taskId&&existingRecord.original.path===read.filePath&&existingRecord.original.sha256===read.sha256&&existingRecord.content.bytes===read.bytes.toString("base64"))return!0;throw Error("TASK_GATE_EVIDENCE_QUARANTINE_MISMATCH: existing quarantine record does not match the repaired evidence source")};if(await reconcileExisting())return{digest:digest5,filePath:target};let count4=0,totalBytes=0,scanned=0,handle=await fs221.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_TASK_GATE_EVIDENCE_QUARANTINE_DIRECTORY_ENTRIES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: too many quarantine entries");if(!entry.isFile()||!/^[0-9.]+\.[a-f0-9]{64}\.v1\.json$/.test(entry.name))continue;count4+=1;let candidate2=path362.join(quarantineDir,entry.name),candidateStat=await fs221.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_UNREADABLE: invalid quarantine artifact");if(totalBytes+=candidateStat.size,count4>=MAX_TASK_GATE_EVIDENCE_QUARANTINE_FILES||totalBytes+serializedBytes>MAX_TASK_GATE_EVIDENCE_QUARANTINE_BYTES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: quarantine retention limit reached")}}finally{try{await handle.close()}catch{}}let tempPath=path362.join(quarantineDir,`.pending.${process.pid}.${randomUUID48()}.json`),fileHandle;try{fileHandle=await fs221.promises.open(tempPath,"wx"),await fileHandle.writeFile(serialized3,"utf8"),await fileHandle.sync(),await fileHandle.close(),fileHandle=void 0,invalidateCachedArtifact(tempPath),await fs221.promises.link(tempPath,target),invalidateCachedArtifact(target)}catch(error93){if(error93.code!=="EEXIST")throw error93;if(await reconcileExisting())return{digest:digest5,filePath:target};throw error93}finally{await fileHandle?.close().catch(()=>{return}),await fs221.promises.unlink(tempPath).catch(()=>{return})}return{digest:digest5,filePath:target}}function buildRepairTransitionId(taskId,source){return`repair_gate_evidence:${taskId}:${source.slice(0,32)}`}function withoutLegacyReconstructionGate(gates){return[...new Set(gates.filter((gate)=>gate!==TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL))].sort()}function hasLegacyReconstructionGate(gates){return gates.includes(TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL)}function buildKnownRepairedEvidence(taskId,receipt,generation,source){let requiredGates=withoutLegacyReconstructionGate(receipt.requiredGates);if(requiredGates.length!==receipt.requiredGates.length)throw Error("TASK_GATE_REQUIREMENTS_RECEIPT_TAINTED: legacy reconstruction markers cannot seed known requirements.");return{taskId,required_gates:requiredGates,gates:{},requirements_state:"known",test_engineer_exempt:receipt.testEngineerExempt??void 0,workflow:{schema:TASK_WORKFLOW_SCHEMA_MARKER,generation,state:"idle",retryCount:0,retryHistory:[],retryEpoch:0,lastOutcome:"repair_idle",lastTransitionId:buildRepairTransitionId(taskId,receipt.chainHash),updatedAt:new Date().toISOString()},repair_provenance:{source_sha256:source.sha256,source_generation:source.generation,requirements_receipt_hash:receipt.chainHash}}}function buildUnknownRepairedEvidence(taskId,requiredGates,seedGeneration,source,receiptHash){return{taskId,required_gates:withoutLegacyReconstructionGate(requiredGates),gates:{},requirements_state:"unknown",workflow:{schema:TASK_WORKFLOW_SCHEMA_MARKER,generation:seedGeneration,state:"idle",retryCount:0,retryHistory:[],retryEpoch:0,lastOutcome:"repair_idle",lastTransitionId:buildRepairTransitionId(taskId,"unknown"),updatedAt:new Date().toISOString()},repair_provenance:{source_sha256:source.sha256,source_generation:source.generation,requirements_receipt_hash:receiptHash}}}function canonicalizeTaskEvidence(taskId,evidence2){let validated=parseTaskEvidence(JSON.stringify({...evidence2,taskId}),taskId);return JSON.stringify(validated,null,2)}function isRepairWorkflowReset(taskId,workflow){return workflow!=null&&workflow.state==="idle"&&workflow.retryCount===0&&workflow.retryEpoch===0&&workflow.retryHistory.length===0&&workflow.lastOutcome==="repair_idle"&&typeof workflow.lastTransitionId==="string"&&workflow.lastTransitionId.startsWith(`repair_gate_evidence:${taskId}:`)}function isReceiptlessLegacySentinelReset(taskId,evidence2){return evidence2!=null&&isRepairWorkflowReset(taskId,evidence2.workflow)&&evidence2.requirements_state==="unknown"&&evidence2.required_gates.length===1&&evidence2.required_gates[0]===TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL&&Object.keys(evidence2.gates).length===0&&evidence2.repair_provenance!=null&&typeof evidence2.repair_provenance.source_sha256==="string"&&(evidence2.repair_provenance.source_generation===null||evidence2.repair_provenance.source_generation<evidence2.workflow.generation)&&evidence2.repair_provenance.requirements_receipt_hash===null}function isAlreadyRepairedEvidence(taskId,evidence2,receipt){if(!evidence2||!isRepairWorkflowReset(taskId,evidence2.workflow))return!1;if(Object.keys(evidence2.gates).length!==0)return!1;if(hasLegacyReconstructionGate(evidence2.required_gates))return!1;let receiptIsTainted=receipt!=null&&hasLegacyReconstructionGate(receipt.requiredGates);if(receipt&&!receiptIsTainted)return evidence2.requirements_state==="known"&&JSON.stringify(evidence2.required_gates)===JSON.stringify(receipt.requiredGates)&&evidence2.workflow.generation>receipt.generation&&(evidence2.test_engineer_exempt??null)===(receipt.testEngineerExempt??null)&&evidence2.repair_provenance?.requirements_receipt_hash===receipt.chainHash;if(!receipt||!receiptIsTainted)return!1;return evidence2.requirements_state==="unknown"&&evidence2.workflow.generation>=1&&evidence2.repair_provenance!=null&&evidence2.repair_provenance.requirements_receipt_hash===receipt.chainHash&&withoutLegacyReconstructionGate(receipt.requiredGates).every((gate)=>evidence2.required_gates.includes(gate))}function repairedEvidenceMatchesCas(evidence2,args2){let provenance=evidence2.repair_provenance;if(!provenance)return args2.expected_sha256==null&&args2.expected_generation==null;return(args2.expected_sha256==null||provenance.source_sha256===args2.expected_sha256)&&(args2.expected_generation==null||provenance.source_generation===args2.expected_generation)}function buildRepairNextActions(taskId,evidence2){if(evidence2.requirements_state==="known")return[`Delegate coder on task ${taskId} to produce a fresh accepted_mutation for the repaired evidence generation ${evidence2.workflow?.generation}.`,`Rerun Stage A for task ${taskId} until pre_check passes for the new generation.`,`Rerun Stage B gates [${evidence2.required_gates.join(", ")}] for task ${taskId} before attempting completion again.`];return[`Delegate coder on task ${taskId} to produce a fresh accepted mutation and regenerate authoritative required gates for a new exact-task generation.`,`Rerun Stage A for task ${taskId} after the new mutation is recorded.`,`Rerun the exact Stage B gates for task ${taskId} only after authoritative required gates are re-recorded; the idle recovery generation cannot complete directly.`]}function invalidateTaskEvidenceSessionFallbacks(taskId){for(let session of swarmState.agentSessions.values()){if(session.currentTaskId===taskId)session.currentTaskId=null;if(session.lastCoderDelegationTaskId===taskId)session.lastCoderDelegationTaskId=null;if(session.taskWorkflowStates?.delete(taskId),session.taskWorkflowCache?.delete(taskId),session.stageBCompletion?.delete(taskId),session.taskCouncilApproved?.delete(taskId),session.taskCouncilWorkflowGeneration?.delete(taskId),session.gateLog?.delete(taskId),session.partialGateWarningsIssuedForTask?.delete(taskId),session.completionGateWarnedForTask?.delete(taskId),session.lastGateFailure?.taskId===taskId)session.lastGateFailure=null}}async function repairTaskGateEvidence(args2,directory,context){assertStrictTaskId(args2.task_id);let normalizedReason=normalizeRepairReason(args2.reason),canonicalDirectory=canonicalizeRepairRoot(directory);if(!(await loadPlan(canonicalDirectory))?.phases.flatMap((phase)=>phase.tasks).find((candidate2)=>candidate2.id===args2.task_id))return{success:!1,message:`TASK_GATE_EVIDENCE_TASK_MISSING: ${args2.task_id} is not present in the loaded plan`,errors:[`Task ${args2.task_id} is not present in .swarm/plan.json.`]};return withTaskEvidenceLock(canonicalDirectory,args2.task_id,"repair_gate_evidence",async()=>{let read=readTaskEvidenceForRepair(canonicalDirectory,args2.task_id),latestReceipt=(await readTaskGateRequirementsReceipts(canonicalDirectory,args2.task_id)).at(-1),evidenceHasLegacyMarker=read.status==="valid"&&read.evidence!=null&&hasLegacyReconstructionGate(read.evidence.required_gates),receiptHasLegacyMarker=latestReceipt!=null&&hasLegacyReconstructionGate(latestReceipt.requiredGates);if(read.status==="valid"&&isAlreadyRepairedEvidence(args2.task_id,read.evidence,latestReceipt)){if(!repairedEvidenceMatchesCas(read.evidence,args2))return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:["TASK_GATE_EVIDENCE_CAS_MISMATCH: the existing repaired generation was created from a different source identity."]};let nextActions2=buildRepairNextActions(args2.task_id,read.evidence);return{success:!0,repaired:!1,task_id:args2.task_id,required_gates:[...read.evidence.required_gates],requirements_state:read.evidence.requirements_state,repaired_generation:read.evidence.workflow?.generation,next_actions:nextActions2,message:`Task gate evidence for ${args2.task_id} is already in repaired fail-closed state.`}}if(read.status==="valid"&&read.evidence?.workflow?.schema===TASK_WORKFLOW_SCHEMA_MARKER&&!evidenceHasLegacyMarker&&latestReceipt!=null&&!receiptHasLegacyMarker)return{success:!1,message:"TASK_GATE_EVIDENCE_REPAIR_NOT_REQUIRED",errors:[`TASK_GATE_EVIDENCE_REPAIR_NOT_REQUIRED: ${args2.task_id} has valid authoritative evidence. Use the normal workflow repair path; this tool only rebuilds corrupt or legacy evidence.`]};if(read.status==="valid"&&read.evidence?.requirements_state==="known"&&!evidenceHasLegacyMarker&&receiptHasLegacyMarker)return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_STALE",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_STALE: ${args2.task_id} has clean accepted-mutation evidence but its latest requirements receipt is legacy-tainted. Repair was refused without modifying evidence; replay the prepared coder settlement so it can publish the exact hash-linked receipt.`]};if(typeof args2.expected_sha256==="string"&&read.status!=="missing"&&read.sha256!==args2.expected_sha256)return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:[`TASK_GATE_EVIDENCE_CAS_MISMATCH: expected sha256 ${args2.expected_sha256}, found ${read.sha256}.`]};if(typeof args2.expected_generation==="number"){let observedGeneration=read.status==="valid"?read.generation:latestReceipt?.generation;if(observedGeneration!==args2.expected_generation)return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:[`TASK_GATE_EVIDENCE_CAS_MISMATCH: expected generation ${args2.expected_generation}, found ${observedGeneration??"unknown"}.`]}}if(read.status==="unreadable"||read.status==="oversized")return{success:!1,message:read.error?.message??"TASK_GATE_EVIDENCE_UNREADABLE: repair requires operator intervention before evidence can be rewritten.",errors:[read.error?.message??`TASK_GATE_EVIDENCE_UNREADABLE: ${args2.task_id} could not be read safely for repair.`]};if(evidenceHasLegacyMarker&&latestReceipt==null&&!isReceiptlessLegacySentinelReset(args2.task_id,read.evidence))return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_MISSING",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_MISSING: ${args2.task_id} is marker-bearing but does not match the exact receipt-less state emitted by the historical repair flow. Repair was refused without modifying evidence or session state.`]};let nextGeneration2=Math.max(read.status==="valid"?read.generation??-1:-1,latestReceipt?.generation??-1)+1,nextEvidence;if(evidenceHasLegacyMarker||receiptHasLegacyMarker){let preservedGates=withoutLegacyReconstructionGate([...read.status==="valid"?read.evidence?.required_gates??[]:[],...latestReceipt?.requiredGates??[]]);nextEvidence=buildUnknownRepairedEvidence(args2.task_id,preservedGates,Math.max(nextGeneration2,1),{sha256:read.status==="missing"?null:read.sha256,generation:read.status==="valid"?read.generation??null:latestReceipt?.generation??null},latestReceipt?.chainHash??null)}else if(latestReceipt)nextEvidence=buildKnownRepairedEvidence(args2.task_id,latestReceipt,nextGeneration2,{sha256:read.status==="missing"?null:read.sha256,generation:read.status==="valid"?read.generation??null:latestReceipt.generation??null});else if(read.status==="missing")return{success:!1,message:"TASK_GATE_EVIDENCE_ABSENT",errors:[`TASK_GATE_EVIDENCE_ABSENT: ${args2.task_id} has no evidence file and no authoritative requirements receipt to rebuild from.`]};else return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_MISSING",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_MISSING: ${args2.task_id} has no authoritative requirements receipt. Receipt-less repair was refused without modifying the original evidence because its required gates cannot be reconstructed safely.`]};let serialized3=canonicalizeTaskEvidence(args2.task_id,nextEvidence),quarantine;if(isQuarantinableTaskEvidenceRead(read))quarantine=await quarantineTaskEvidenceBytes(canonicalDirectory,args2.task_id,read,normalizedReason,context,latestReceipt?.generation??null);assertTaskEvidenceWriteAllowed(canonicalDirectory,args2.task_id),await atomicWriteFile(taskEvidenceFilePath(canonicalDirectory,args2.task_id),serialized3),invalidateTaskEvidenceSessionFallbacks(args2.task_id);let nextActions=buildRepairNextActions(args2.task_id,nextEvidence);return{success:!0,repaired:!0,task_id:args2.task_id,required_gates:[...nextEvidence.required_gates],requirements_state:nextEvidence.requirements_state,quarantine_digest:quarantine?.digest,quarantine_path:quarantine?.filePath,repaired_generation:nextEvidence.workflow?.generation,next_actions:nextActions,message:`Repaired task gate evidence for ${args2.task_id} into a fresh fail-closed generation ${nextEvidence.workflow?.generation}. Next actions: ${nextActions.join(" ")}`}})}init_create_tool();init_resolve_working_directory();async function executeRepairGateEvidence(args2,directory,_ctx){try{if(!_ctx||stripKnownSwarmPrefix(_ctx.agent??"").toLowerCase()!=="architect")return{success:!1,message:"Only the architect may repair task gate evidence.",errors:["TASK_GATE_EVIDENCE_ARCHITECT_ONLY"]};let resolved=resolveWorkingDirectory(args2.working_directory,directory);if(!resolved.success)return{success:!1,message:resolved.message,errors:[resolved.message]};return await repairTaskGateEvidence(args2,resolved.directory,{sessionID:_ctx?.sessionID,messageID:_ctx?.messageID})}catch(error93){return{success:!1,message:"repair_gate_evidence failed",errors:[error93 instanceof Error?error93.message:String(error93)]}}}var repair_gate_evidence=createSwarmTool({description:"Architect-only evidence repair for exact-task gate files. Rebuilds from a durable requirements receipt, recovers receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuses every other receipt-less reconstruction.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format"),reason:exports_external.string().min(1).max(2000),expected_sha256:exports_external.string().regex(/^[a-f0-9]{64}$/).optional(),expected_generation:exports_external.number().int().min(0).optional(),working_directory:exports_external.string().optional()},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRepairGateEvidence(args2,directory,ctx),null,2)});init_zod();init_schema();init_knowledge_receipt_ledger();init_create_tool();init_resolve_working_directory();async function executeRepairKnowledgeReceiptLedger(args2,directory,_ctx){try{if(_ctx&&stripKnownSwarmPrefix(_ctx.agent??"").toLowerCase()!=="architect")return{success:!1,message:"Only the architect may repair the knowledge receipt ledger.",errors:["RECEIPT_REPAIR_ARCHITECT_ONLY"]};if(_ctx?.sessionID&&args2.session_id!==_ctx.sessionID)return{success:!1,message:"repair_knowledge_receipt_ledger session_id must match the invoking tool context.",errors:["RECEIPT_REPAIR_SESSION_MISMATCH"]};let resolved=resolveWorkingDirectory(args2.working_directory,directory);if(!resolved.success)return{success:!1,message:resolved.message,errors:[resolved.message]};if(args2.operation==="backfill_phase_id"){let backfill=await backfillMembershipPhaseIds(resolved.directory);if(!backfill.ok)return{success:!1,message:"repair_knowledge_receipt_ledger backfill_phase_id failed",errors:[backfill.detail],code:backfill.code};return{success:!0,message:`phase_id backfill complete: ${backfill.backfilled} membership(s) backfilled, ${backfill.skipped.length} skipped (unparsable label), ${backfill.journal_records} journal record(s) appended. Stored labels are never rewritten.`,backfilled:backfill.backfilled,skipped:backfill.skipped.slice(0,20),skipped_total:backfill.skipped.length,journal_records:backfill.journal_records}}let result=await repairKnowledgeReceiptLedger(resolved.directory,args2);if(!result.ok)return{success:!1,message:"repair_knowledge_receipt_ledger failed",errors:[result.detail],code:result.code};let reEvaluationArgs=JSON.stringify({repair_id:result.repair_id,phase:args2.phase,...args2.task_id?{task_id:args2.task_id}:{},scope_complete:!0});return{success:!0,message:result.status==="validated_projection"?"knowledge receipt projection validated":result.status==="pending_re_evaluation"?`knowledge receipt ledger still pending re-evaluation; as architect, run knowledge_recall with a comprehensive query and repair_re_evaluation ${reEvaluationArgs}`:`knowledge receipt ledger repaired and blocked pending re-evaluation; as architect, run knowledge_recall with a comprehensive query and repair_re_evaluation ${reEvaluationArgs}`,...result}}catch(error93){return{success:!1,message:"repair_knowledge_receipt_ledger failed",errors:[error93 instanceof Error?error93.message:String(error93)]}}}var repair_knowledge_receipt_ledger=createSwarmTool({description:"Architect-only repair and validation for the authoritative knowledge receipt ledger. Default operation repairs: rebuilds the derived projection when authority is readable, or quarantines a bounded corrupt authority, salvages only the validated prefix, and blocks the exact phase/session until a fresh re-evaluation is committed. operation backfill_phase_id durably stamps the stable numeric phase_id on live memberships that lack one across the WHOLE ledger (phase/session_id are not used to scope the backfill; labels never rewritten).",args:{phase:exports_external.string().min(1),session_id:exports_external.string().min(1),task_id:exports_external.string().min(1).optional(),reason:exports_external.string().min(1).max(2000),operation:exports_external.enum(["repair","backfill_phase_id"]).optional(),grace_days:exports_external.number().int().min(0).optional(),working_directory:exports_external.string().optional()},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRepairKnowledgeReceiptLedger(args2,directory,ctx),null,2)});init_zod();init_loader();init_schema();init_profiles();init_telemetry();init_path_security();init_create_tool();import*as path364 from"node:path";init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs222 from"node:fs";import{createRequire as createRequire7}from"node:module";import*as path363 from"node:path";var require2=createRequire7(import.meta.url),DEFAULT_MAX_RESULTS4=100,DEFAULT_MAX_LINES=200,REGEX_TIMEOUT_MS=5000,MAX_FILE_SIZE_BYTES8=1048576,HARD_CAP_RESULTS4=1e4,HARD_CAP_LINES=1e4,MAX_QUERY_LENGTH=20000,MAX_INCLUDE_PATTERNS=100,MAX_RG_STDOUT_BYTES=8388608,MAX_RG_STDERR_BYTES=65536,FALLBACK_MAX_FILES=20000,FALLBACK_MAX_DIRS=5000,FALLBACK_MAX_DEPTH=40,FALLBACK_MAX_TOTAL_BYTES=67108864,DEFAULT_SKIP_DIRS=new Set([".git",".swarm","node_modules","dist","build","out","coverage",".next",".turbo",".cache"]);function globMatch(pattern,filePath){let normalizedPattern=pattern.replace(/\\/g,"/"),normalizedPath=filePath.replace(/\\/g,"/"),regexPattern=normalizedPattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"{{DOUBLESTAR}}").replace(/\*/g,"[^/]*").replace(/\?/g,".").replace(/\{\{DOUBLESTAR\}\}/g,".*");try{return new RegExp(`^${regexPattern}$`).test(normalizedPath)}catch{return!1}}function matchesGlobs(filePath,globs){if(globs.length===0)return!0;return globs.some((glob)=>globMatch(glob,filePath))}var WINDOWS_RESERVED_NAMES5=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks4(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES5.test(part))return!0;return!1}function resolveWithinWorkspace(filePath,workspace){try{let resolvedPath=path363.resolve(workspace,filePath),realWorkspace=fs222.realpathSync(workspace),realResolvedPath=fs222.realpathSync(resolvedPath),relativePath2=path363.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path363.isAbsolute(relativePath2))return null;return relativePath2}catch{return null}}function isPathInWorkspace3(filePath,workspace){return resolveWithinWorkspace(filePath,workspace)!==null}function validatePathForRead2(filePath,workspace){return isPathInWorkspace3(filePath,workspace)}function splitGlobPatterns2(value){return value?value.split(",").map((p)=>p.trim()).filter(Boolean):[]}var GLOB_METACHARACTERS=/[*?[\]{}]/;function isExactPath(pattern){return!GLOB_METACHARACTERS.test(pattern)}function targetsDotDirectory(pattern){let firstSegment=pattern.split(/[\\/]/)[0];return!!firstSegment&&firstSegment.startsWith(".")&&firstSegment!=="."&&firstSegment!==".."}function hasGitSegment(resolvedRelativePath){return resolvedRelativePath.split(/[\\/]/).some((segment)=>segment.toLowerCase()===".git")}function toWorkspaceRelativePath2(filePath,workspace){try{let resolved=path363.resolve(workspace,filePath),realWorkspace=fs222.realpathSync(workspace),realResolved=fs222.realpathSync(resolved),relative96=path363.relative(realWorkspace,realResolved);if(!relative96||relative96.startsWith("..")||path363.isAbsolute(relative96))return null;return relative96.split(path363.sep).join("/")}catch{return null}}function truncateLine(line,maxLines){let trimmed=line.trimEnd();if(trimmed.length>maxLines)return`${trimmed.substring(0,maxLines)}...`;return trimmed}function resolvePackagedRipgrep(){try{let mod=require2("@vscode/ripgrep");return typeof mod.rgPath==="string"&&mod.rgPath?mod.rgPath:null}catch{return null}}function resolveRipgrepBinary(){return _internals309.resolvePackagedRipgrep()??_internals309.resolveExecutableFromPath(["rg"])}async function ripgrepSearch(opts){let rgPath=_internals309.resolveRipgrepBinary();if(!rgPath)return{error:!0,type:"rg-not-found",message:"ripgrep (rg) not found; using fallback search was not possible"};let args2=["--json","--no-config","-n"],includes=splitGlobPatterns2(opts.include),promotablePaths=[],globIncludes=[];for(let pattern of includes){let resolvedRelative=resolveWithinWorkspace(pattern,opts.workspace);if(isExactPath(pattern)&&targetsDotDirectory(pattern)&&pattern.split(/[\\/]/)[0]?.toLowerCase()!==".git"&&resolvedRelative!==null&&!hasGitSegment(resolvedRelative))promotablePaths.push(pattern);else globIncludes.push(pattern)}let pathOperands;if(promotablePaths.length>0&&globIncludes.length===0)pathOperands=promotablePaths;else{for(let pattern of[...globIncludes,...promotablePaths])args2.push("--glob",pattern);if(includes.some((p)=>targetsDotDirectory(p)&&p.split(/[\\/]/)[0]?.toLowerCase()!==".git"))args2.push("--hidden","--no-ignore"),args2.push("--glob","!.git");pathOperands=["."]}for(let pattern of splitGlobPatterns2(opts.exclude))args2.push("--glob",`!${pattern}`);if(opts.mode!=="regex")args2.push("--fixed-strings");args2.push("--",opts.query,...pathOperands);let run=await _internals309.runExternalTool({executable:rgPath,args:args2,cwd:opts.workspace,timeoutMs:REGEX_TIMEOUT_MS,maxStdoutBytes:MAX_RG_STDOUT_BYTES,maxStderrBytes:MAX_RG_STDERR_BYTES});try{if(run.status==="timeout")return{error:!0,type:"regex-timeout",message:`Search timed out after ${REGEX_TIMEOUT_MS}ms`};if(run.status==="spawn-error")return{error:!0,type:"unknown",message:run.message??"ripgrep failed to start"};if(run.exitCode!==0&&run.stderr){if(run.stderr.includes("Invalid regex")||run.stderr.includes("regex parse error")||run.stderr.includes("SyntaxError"))return{error:!0,type:"invalid-query",message:`Invalid query: ${run.stderr.split(`
|
|
7783
|
+
`,r:"\r",b:"\b",f:"\f",v:"\v"};if(simple[escaped]!==void 0){appendText(simple[escaped]);continue}if(/[0-7]/.test(escaped)){let octal=escaped;for(let count4=0;count4<2;count4++){let next=value[index+1];if(!next||!/[0-7]/.test(next))break;octal+=next,index++}bytes.push(Number.parseInt(octal,8));continue}return null}return Buffer.from(bytes).toString("utf8")}function normalizeRepoPathKey(repoPath){let normalized=repoPath.replace(/\\/g,"/");return _internals308.platform()==="win32"||_internals308.platform()==="darwin"?normalized.toLowerCase():normalized}function normalizeDiffPath(rawPath){let pathToken=rawPath.startsWith('"')?rawPath:rawPath.split("\t",1)[0],decoded=decodeGitQuotedPath(pathToken);if(decoded===null||decoded==="/dev/null"||decoded.trim().length===0)return null;return normalizeRepoPathKey(decoded)}function parseDiffLineRangesChecked(diffOutput,requireGitFileHeaders){let result=new Map,currentFile=null,inGitFile=!1,expectingDestination=!1,destinationSeen=!1,destinationNeedsHunk=!1,collectedLines=0;for(let rawLine of diffOutput.split(/\r?\n/)){let line=rawLine.endsWith("\r")?rawLine.slice(0,-1):rawLine;if(line.startsWith("diff --git ")){if(expectingDestination||destinationNeedsHunk)return null;inGitFile=!0,currentFile=null,expectingDestination=!1,destinationSeen=!1;continue}if(line.startsWith("--- ")&&(inGitFile||!requireGitFileHeaders)){if(expectingDestination||destinationNeedsHunk)return null;expectingDestination=!0;continue}if(line.startsWith("+++ ")){if(requireGitFileHeaders&&(!inGitFile||!expectingDestination))return null;let rawDestination=line.slice(4);if(currentFile=normalizeDiffPath(rawDestination),currentFile===null&&rawDestination.trim()!=="/dev/null")return null;if(expectingDestination=!1,destinationSeen=!0,destinationNeedsHunk=!0,!currentFile)continue;if(!result.has(currentFile))result.set(currentFile,new Set);continue}if(!line.startsWith("@@"))continue;if(expectingDestination||requireGitFileHeaders&&(!inGitFile||!destinationSeen))return null;let match=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);if(!match)return null;let start=Number.parseInt(match[1],10),count4=match[2]!==void 0?Number.parseInt(match[2],10):1;if(!Number.isSafeInteger(start)||!Number.isSafeInteger(count4)||count4<0||count4>0&&start<1||count4>MAX_CHANGED_LINE_ENTRIES||start+count4-1>Number.MAX_SAFE_INTEGER||collectedLines+count4>MAX_CHANGED_LINE_ENTRIES)return null;if(destinationNeedsHunk=!1,!currentFile)continue;let lines=result.get(currentFile);if(!lines)return null;for(let index=0;index<count4;index++)lines.add(start+index);collectedLines+=count4}if(expectingDestination||destinationNeedsHunk)return null;return result}function mergeChangedLines(target,source){for(let[file3,sourceLines]of source){let targetLines=target.get(file3)??new Set;for(let line of sourceLines)targetLines.add(line);target.set(file3,targetLines)}}function parseUntrackedStatus(output){if(output.length>0&&!output.endsWith("\x00"))return null;let untracked=[],records=output.split("\x00");for(let index=0;index<records.length-1;index++){let record3=records[index];if(!record3||record3.length<4||record3[2]!==" ")return null;let status2=record3.slice(0,2),filePath=record3.slice(3);if(!filePath||!isKnownPorcelainStatus(status2))return null;if(status2==="??"||status2==="!!")untracked.push(normalizeRepoPathKey(filePath));if(/[RC]/.test(status2)){let sourcePath=records[++index];if(!sourcePath||looksLikePorcelainStatusRecord(sourcePath))return null}}return untracked}function isKnownPorcelainStatus(status2){if(status2==="??"||status2==="!!")return!0;if(/U/.test(status2))return new Set(["DD","AU","UD","UA","DU","AA","UU"]).has(status2);return status2!==" "&&/^[ MTADRC]{2}$/.test(status2)}function looksLikePorcelainStatusRecord(value){return value.length>=4&&value[2]===" "&&isKnownPorcelainStatus(value.slice(0,2))}async function getChangedLineAmbiguousFiles(directory,abortSignal,requestedFiles=[]){let mergeBase=null;for(let baseBranch of["zaxbyhub/main","upstream/main","origin/main","main","origin/master","master"]){let candidate2=(await runGit8(["merge-base",baseBranch,"HEAD"],directory,abortSignal))?.trim();if(candidate2&&/^[0-9a-f]{40,64}$/i.test(candidate2)){mergeBase=candidate2;break}}if(!mergeBase)return null;let headSha=(await runGit8(["rev-parse","HEAD"],directory,abortSignal))?.trim();if(typeof headSha==="string"&&/^[0-9a-f]{40,64}$/i.test(headSha)&&headSha.toLowerCase()===mergeBase.toLowerCase())return null;let literalPathspecs=requestedFiles.map((file3)=>path360.relative(directory,file3).replace(/\\/g,"/")).filter((file3)=>file3.length>0&&file3!==".."&&!file3.startsWith("../")).map((file3)=>`:(literal)${file3}`),statusArgs=["-c","core.quotePath=false","status","--porcelain=v1","-z","--untracked-files=all",...literalPathspecs.length>0?["--",...literalPathspecs]:[]],[committedNames,status2]=await Promise.all([runGit8(["-c","core.quotePath=false","diff","--name-only","--no-ext-diff","--no-color","--no-prefix","-z",`${mergeBase}..HEAD`,"--",...literalPathspecs.length>0?literalPathspecs:[]],directory,abortSignal),runGit8(statusArgs,directory,abortSignal)]);if(committedNames===null||status2===null)return null;let committed=new Set(committedNames.split("\x00").filter(Boolean).map(normalizeRepoPathKey)),staged=new Set,unstaged=new Set;if(status2.length>0&&!status2.endsWith("\x00"))return null;let records=status2.split("\x00");for(let index=0;index<records.length-1;index++){let record3=records[index];if(!record3||record3.length<4||record3[2]!==" ")return null;let statusCode=record3.slice(0,2),filePath=record3.slice(3);if(!filePath||!isKnownPorcelainStatus(statusCode))return null;if(statusCode!=="??"&&statusCode!=="!!"){let key2=normalizeRepoPathKey(filePath);if(/[MADRCU]/.test(statusCode[0]))staged.add(key2);if(/[MADRCU]/.test(statusCode[1]))unstaged.add(key2)}if(/[RC]/.test(statusCode)){let sourcePath=records[++index];if(!sourcePath||looksLikePorcelainStatusRecord(sourcePath))return null}}let ambiguous=new Set;for(let key2 of committed)if(staged.has(key2)||unstaged.has(key2))ambiguous.add(key2);for(let key2 of staged)if(unstaged.has(key2))ambiguous.add(key2);return ambiguous}async function getChangedLineRanges(directory,abortSignal,requestedFiles=[]){let mergeBase=null;for(let baseBranch of["zaxbyhub/main","upstream/main","origin/main","main","origin/master","master"]){let candidate2=(await runGit8(["merge-base",baseBranch,"HEAD"],directory,abortSignal))?.trim();if(candidate2&&/^[0-9a-f]{40,64}$/i.test(candidate2)){mergeBase=candidate2;break}}if(!mergeBase)return null;let commonDiffArgs=["-c","core.quotePath=false","diff","--no-ext-diff","--no-color","--no-prefix","-U0"],requestedPathspecs=requestedFiles.map((file3)=>path360.relative(directory,file3).replace(/\\/g,"/")).filter((file3)=>file3.length>0&&file3!==".."&&!file3.startsWith("../")),statusArgs=["-c","core.quotePath=false","status","--porcelain=v1","-z","--untracked-files=all",...requestedPathspecs.length>0?["--ignored=matching"]:[],...requestedPathspecs.length>0?["--",...requestedPathspecs]:[]],[committed,staged,unstaged,status2]=await Promise.all([runGit8([...commonDiffArgs,`${mergeBase}..HEAD`,"--"],directory,abortSignal),runGit8([...commonDiffArgs,"--cached","HEAD","--"],directory,abortSignal),runGit8([...commonDiffArgs,"--"],directory,abortSignal),runGit8(statusArgs,directory,abortSignal)]);if(committed===null||staged===null||unstaged===null||status2===null)return null;let committedLines=parseDiffLineRangesChecked(committed,!0),stagedLines=parseDiffLineRangesChecked(staged,!0),unstagedLines=parseDiffLineRangesChecked(unstaged,!0);if(!committedLines||!stagedLines||!unstagedLines)return null;let result=new Map;mergeChangedLines(result,committedLines),mergeChangedLines(result,stagedLines),mergeChangedLines(result,unstagedLines);let untracked=parseUntrackedStatus(status2);if(untracked===null)return null;let requestedKeys=requestedPathspecs.map(normalizeRepoPathKey);for(let file3 of untracked)if(result.set(file3,new Set([ALL_LINES_CHANGED])),file3.endsWith("/")){for(let requestedFile of requestedKeys)if(requestedFile.startsWith(file3))result.set(requestedFile,new Set([ALL_LINES_CHANGED]))}return result}function classifySastFindings(findings,changedLineRanges,directory){if(!changedLineRanges)return{newFindings:findings,preexistingFindings:[]};let newFindings=[],preexistingFindings=[],pathApi=_internals308.platform()==="win32"?path360.win32:path360.posix,resolvedDirectory=pathApi.resolve(directory);for(let finding of findings){let filePath=finding.location.file,normalised;try{if(typeof filePath!=="string"||filePath.length===0||filePath.includes("\x00")){newFindings.push(finding);continue}let resolvedFinding=pathApi.isAbsolute(filePath)?pathApi.resolve(filePath):pathApi.resolve(resolvedDirectory,filePath),relative95=pathApi.relative(resolvedDirectory,resolvedFinding);if(pathApi.isAbsolute(relative95)||relative95===".."||relative95.startsWith(`..${pathApi.sep}`)){newFindings.push(finding);continue}normalised=normalizeRepoPathKey(relative95)}catch{newFindings.push(finding);continue}let changedLines=changedLineRanges.get(normalised);if(changedLines?.has(ALL_LINES_CHANGED)||changedLines?.has(finding.location.line))newFindings.push(finding);else preexistingFindings.push(finding)}return{newFindings,preexistingFindings}}function classifySecretFindings(findings,changedLineRanges,directory,ambiguousFiles){if(!changedLineRanges)return{newFindings:findings,preexistingFindings:[]};let newFindings=[],preexistingFindings=[],pathApi=_internals308.platform()==="win32"?path360.win32:path360.posix,resolvedDirectory=pathApi.resolve(directory);for(let finding of findings){let{path:filePath,line}=finding;if(typeof filePath!=="string"||filePath.length===0||filePath.includes("\x00")||typeof line!=="number"||!Number.isSafeInteger(line)||line<1){newFindings.push(finding);continue}let changedLines;try{let resolvedFinding=pathApi.isAbsolute(filePath)?pathApi.resolve(filePath):pathApi.resolve(resolvedDirectory,filePath),relative95=pathApi.relative(resolvedDirectory,resolvedFinding);if(pathApi.isAbsolute(relative95)||relative95===".."||relative95.startsWith(`..${pathApi.sep}`)){newFindings.push(finding);continue}let normalised=normalizeRepoPathKey(relative95);if(ambiguousFiles?.has(normalised)){newFindings.push(finding);continue}changedLines=changedLineRanges.get(normalised)}catch{newFindings.push(finding);continue}if(changedLines!==void 0&&changedLines.size>0&&!changedLines.has(ALL_LINES_CHANGED)&&!changedLines.has(line))preexistingFindings.push(finding);else newFindings.push(finding)}return{newFindings,preexistingFindings}}async function runPreCheckBatch(input,workspaceDir,contextDir,abortSignal){let effectiveWorkspaceDir=workspaceDir||input.directory||contextDir,{files,directory,sast_threshold="medium",gates:gatesOverrides,phase,sast_enabled=!0}=input,gates=gatesOverrides??(input.config?.gates?{sast_scan:input.config.gates.sast_scan,quality_budget:input.config.gates.quality_budget}:void 0),dirError=validateDirectory2(directory,effectiveWorkspaceDir);if(dirError)return warn(`pre_check_batch: Invalid directory: ${dirError}`),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0};if(!files||files.length===0)return warn("pre_check_batch: No files provided, skipping all tools (fail-closed)"),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};let changedFiles=[],rawDeclaredCount=files.length;for(let file3 of files){if(typeof file3!=="string"){warn(`pre_check_batch: Non-string file entry rejected: ${String(file3)}`);continue}if(validatePath(file3,directory,effectiveWorkspaceDir)){warn(`pre_check_batch: Invalid file path: ${file3}`);continue}changedFiles.push(path360.resolve(directory,file3))}if(changedFiles.length===0)return warn("pre_check_batch: No valid files after validation, skipping all tools (fail-closed)"),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};try{assertProjectRoot(directory)}catch(error93){let rootError=error93 instanceof Error?error93.message:String(error93);return warn(`pre_check_batch: Project-root validation failed: ${rootError}`),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:rootError,duration_ms:0},secretscan:{ran:!1,error:rootError,duration_ms:0},sast_scan:{ran:!1,error:rootError,duration_ms:0},quality_budget:{ran:!1,error:rootError,duration_ms:0},total_duration_ms:0}}if(changedFiles.length>MAX_FILES)throw Error(`Input exceeds maximum file count: ${changedFiles.length} > ${MAX_FILES}`);let limit=pLimit(MAX_CONCURRENT),sastDisabledByConfig=gates?.sast_scan?.enabled===!1,[lintResult,secretscanResult,sastScanResult,qualityBudgetResult]=await Promise.all([limit(()=>_internals308.runLintWrapped(changedFiles,directory,gates,abortSignal)),limit(()=>_internals308.runSecretscanWrapped(changedFiles,directory,gates,abortSignal,rawDeclaredCount)),sast_enabled&&!sastDisabledByConfig?limit(()=>_internals308.runSastScanWrapped(changedFiles,directory,sast_threshold,gates,phase,abortSignal)):Promise.resolve({ran:!1,duration_ms:0}),limit(()=>_internals308.runQualityBudgetWrapped(changedFiles,directory,gates,abortSignal))]),totalDuration=lintResult.duration_ms+secretscanResult.duration_ms+sastScanResult.duration_ms+qualityBudgetResult.duration_ms,gatesPassed=!0;if(lintResult.ran&&lintResult.result){let lintRes=lintResult.result;if("success"in lintRes&&lintRes.success===!1)warn("pre_check_batch: Lint found issues (informational only)")}else if(lintResult.error)warn(`pre_check_batch: Lint error (informational only): ${lintResult.error}`);let changedLineRangesMemo,getChangedLineRangesMemoized=async()=>{if(changedLineRangesMemo===void 0)changedLineRangesMemo=await _internals308.getChangedLineRanges(directory,abortSignal,changedFiles);return changedLineRangesMemo},secretscanClassification,secretscanPreexistingFindings,secretscanScanFindings=secretscanResult.ran&&secretscanResult.result&&!("error"in secretscanResult.result)?secretscanResult.result.findings:[];if(secretscanScanFindings.length>0){let changedLineRanges=await getChangedLineRangesMemoized(),ambiguousFiles=await _internals308.getChangedLineAmbiguousFiles(directory,abortSignal,changedFiles);if(ambiguousFiles===null)secretscanClassification={newFindings:secretscanScanFindings,preexistingFindings:[],diffScoped:!1};else{let{newFindings,preexistingFindings}=classifySecretFindings(secretscanScanFindings,changedLineRanges,directory,ambiguousFiles);if(secretscanClassification={newFindings,preexistingFindings,diffScoped:changedLineRanges!==null},preexistingFindings.length>0)secretscanPreexistingFindings=preexistingFindings,warn(`pre_check_batch: Secretscan found ${preexistingFindings.length} pre-existing secret finding(s) on unchanged lines - visible, non-gating, passed to reviewer for triage`)}}let secretscanDecision=evaluateSecretscanGate(secretscanResult,rawDeclaredCount,secretscanClassification);if(!secretscanDecision.passed)gatesPassed=!1,warn(`pre_check_batch: ${secretscanDecision.summary} - GATE FAILED`);if(secretscanResult.ran||secretscanResult.error)try{let scanResult=secretscanDecision.result,secretscanEvidence={task_id:"secretscan",type:"secretscan",timestamp:new Date().toISOString(),agent:"pre_check_batch",verdict:secretscanDecision.passed?"pass":"fail",summary:secretscanDecision.summary,findings_count:secretscanDecision.findingsCount,scan_directory:scanResult?.scan_dir??directory,files_scanned:scanResult?.files_scanned??0,skipped_files:scanResult?.skipped_files??0,ignored_files:scanResult?.ignored_files??0,policy_skipped_files:scanResult?.policy_skipped_files??0,requested_files:scanResult?.requested_files??rawDeclaredCount,new_findings_count:secretscanDecision.newFindingsCount??0,preexisting_findings_count:secretscanDecision.preexistingFindingsCount??0,diff_scoped:secretscanDecision.diffScoped??!1,incomplete_files:scanResult?.incomplete_files??changedFiles.length,incomplete_paths:scanResult?.incomplete_paths??[{path:".",reason:"missing_coverage_metadata"}]};await _internals308.saveEvidence(directory,"secretscan",secretscanEvidence,abortSignal)}catch(e){let persistError=`Failed to persist secretscan evidence: ${e instanceof Error?e.message:String(e)}`;secretscanResult.error=persistError,gatesPassed=!1,warn(`pre_check_batch: ${persistError} - GATE FAILED`)}let sastPreexistingFindings,sastDegraded=!1;if(sastScanResult.ran&&sastScanResult.result){let sastResult=sastScanResult.result;if(sastResult.error)if(sastResult.failure_kind==="semgrep_process_exit"&&sastResult.findings.length===0)sastDegraded=!0,warn(`pre_check_batch: SAST coverage degraded (${sastResult.error}) - continuing without a gate failure`);else gatesPassed=!1,warn(`pre_check_batch: SAST scan error (${sastResult.error}) - GATE FAILED`);else if(sastResult.baseline_used){let sastCarryFindings=[...sastResult.pre_existing_findings??[],...sastResult.moved_findings??[]];if(sastCarryFindings.length>0){if(sastPreexistingFindings=sastCarryFindings.filter((f)=>meetsThresholdForTriage(f.severity,sast_threshold)),sastPreexistingFindings.length>0)warn(`pre_check_batch: SAST baseline diff found ${sastPreexistingFindings.length} pre-existing/moved finding(s) - passing to reviewer for triage`)}if(sastResult.verdict==="fail")gatesPassed=!1,warn("pre_check_batch: SAST scan found new findings above threshold - GATE FAILED")}else if(sastResult.verdict==="fail"){let gateFindings=sastResult.findings.filter((f)=>GATE_SEVERITIES.has(f.severity));if(gateFindings.length>0){let changedLineRanges=await getChangedLineRangesMemoized(),{newFindings,preexistingFindings}=classifySastFindings(gateFindings,changedLineRanges,directory);if(newFindings.length>0)gatesPassed=!1,warn(`pre_check_batch: SAST scan found ${newFindings.length} new HIGH/CRITICAL finding(s) on changed lines - GATE FAILED`);else if(preexistingFindings.length>0)sastPreexistingFindings=preexistingFindings,warn(`pre_check_batch: SAST scan found ${preexistingFindings.length} pre-existing HIGH/CRITICAL finding(s) on unchanged lines - passing to reviewer for triage`)}else gatesPassed=!1,warn("pre_check_batch: SAST scan found vulnerabilities - GATE FAILED")}}else if(sastScanResult.error)gatesPassed=!1,warn(`pre_check_batch: SAST scan error - GATE FAILED: ${sastScanResult.error}`);if(qualityBudgetResult.ran&&qualityBudgetResult.result){if(qualityBudgetResult.result.verdict==="fail")warn("pre_check_batch: Quality budget exceeded (informational only)")}else if(qualityBudgetResult.error)warn(`pre_check_batch: Quality budget error (informational only): ${qualityBudgetResult.error}`);return{batch_status:[lintResult,secretscanResult,sastScanResult,qualityBudgetResult].every((toolResult)=>toolResult.ran===!1)?"skipped":"completed",gates_passed:gatesPassed,lint:lintResult,secretscan:secretscanResult,sast_scan:sastScanResult,quality_budget:qualityBudgetResult,total_duration_ms:Math.round(totalDuration),...sastDegraded&&{sast_degraded:!0},...(!sast_enabled||sastDisabledByConfig)&&{sast_skipped:!0},...sastPreexistingFindings&&sastPreexistingFindings.length>0&&{sast_preexisting_findings:sastPreexistingFindings},...secretscanPreexistingFindings&&secretscanPreexistingFindings.length>0&&{secretscan_preexisting_findings:secretscanPreexistingFindings}}}var pre_check_batch=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Run multiple verification tools in parallel: lint, secretscan, SAST scan, and quality budget. Returns unified result with gates_passed status. Security findings and incomplete SAST runs are hard failures; a Semgrep nonzero process exit with zero findings is returned as explicit sast_degraded coverage and does not block.",args:{files:exports_external.array(exports_external.string()).optional().describe("Specific files to check (optional, scans directory if not provided)"),directory:exports_external.string().describe("Project root directory — ordinary workspace subdirectories are rejected; direct .git or .opencode project boundaries are accepted"),sast_threshold:exports_external.enum(["low","medium","high","critical"]).optional().describe("Minimum severity for SAST findings to cause failure (default: medium)"),phase:exports_external.number().int().min(1).optional().describe("Current phase number (positive integer >= 1). When provided, enables SAST baseline diffing: only findings absent from the phase-scoped baseline fail the gate.")},async execute(args2,directory,ctx){if(!args2||typeof args2!=="object")return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"Invalid arguments",duration_ms:0},secretscan:{ran:!1,error:"Invalid arguments",duration_ms:0},sast_scan:{ran:!1,error:"Invalid arguments",duration_ms:0},quality_budget:{ran:!1,error:"Invalid arguments",duration_ms:0},total_duration_ms:0});if(!directory||typeof directory!=="string"||directory.trim()==="")return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},secretscan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},sast_scan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},quality_budget:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},total_duration_ms:0});let typedArgs=args2;if(!typedArgs.directory)return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"directory is required",duration_ms:0},secretscan:{ran:!1,error:"directory is required",duration_ms:0},sast_scan:{ran:!1,error:"directory is required",duration_ms:0},quality_budget:{ran:!1,error:"directory is required",duration_ms:0},total_duration_ms:0});let resolvedDirectory=path360.resolve(typedArgs.directory),workspaceAnchor=path360.resolve(directory);if(isStrictPathDescendant(resolvedDirectory,workspaceAnchor)&&!hasExplicitProjectBoundary(resolvedDirectory)){let subDirError=`directory "${typedArgs.directory}" is a subdirectory of the project root — pre_check_batch requires the project root directory "${workspaceAnchor}"`;return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:subDirError,duration_ms:0},secretscan:{ran:!1,error:subDirError,duration_ms:0},sast_scan:{ran:!1,error:subDirError,duration_ms:0},quality_budget:{ran:!1,error:subDirError,duration_ms:0},total_duration_ms:0})}let dirError=validateDirectory2(resolvedDirectory,workspaceAnchor);if(dirError)return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0});try{let sastEnabled=!0;try{let preamble=await _internals308.resolveGatePreamble(resolvedDirectory,ctx?.sessionID);if(preamble.resolved&&preamble.effectiveGates)sastEnabled=preamble.effectiveGates.sast_enabled}catch{warn("pre_check_batch: QA-gate profile resolution failed; keeping SAST enabled")}let rawPhase=typedArgs.phase,safePhase=typeof rawPhase==="number"&&Number.isInteger(rawPhase)&&rawPhase>=1?rawPhase:void 0,result=await _internals308.runPreCheckBatch({files:typedArgs.files,directory:resolvedDirectory,sast_threshold:typedArgs.sast_threshold,config:typedArgs.config,gates:_internals308.loadGateOverrides(resolvedDirectory),phase:safePhase,sast_enabled:sastEnabled},workspaceAnchor,directory,ctx?.abort);return serializePreCheckResult(result)}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:errorMessage3,duration_ms:0},secretscan:{ran:!1,error:errorMessage3,duration_ms:0},sast_scan:{ran:!1,error:errorMessage3,duration_ms:0},quality_budget:{ran:!1,error:errorMessage3,duration_ms:0},total_duration_ms:0})}}});init_zod();init_guardrails2();init_pr_workflow_gate();init_scope_binding();init_create_tool();var PreparePrFeedbackScopeArgsSchema=exports_external.object({task_id:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/,"task_id must use N.M notation"),files:exports_external.array(exports_external.string().min(1).max(4096)).min(1).max(1e4)}).strict();function failure2(message){return JSON.stringify({success:!1,message},null,2)}async function executePreparePrFeedbackScope(args2,directory,context={}){let parsed=PreparePrFeedbackScopeArgsSchema.safeParse(args2);if(!parsed.success)return failure2(`Invalid PR-feedback scope: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure2("PR-feedback scope requires an active session");let files=normalizeScopeFiles(parsed.data.files);if(!files)return failure2("PR-feedback scope contains an unsafe file path");for(let file3 of files){let symlinkBlock=checkWriteTargetForSymlink(file3,directory);if(symlinkBlock)return failure2(symlinkBlock)}try{await declarePrFeedbackScope(directory,sessionID,parsed.data.task_id,files)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}return JSON.stringify({success:!0,task_id:parsed.data.task_id,files,message:"Scope is bound to the verified PR-feedback revision and will authorize only the next matching coder Task."},null,2)}var prepare_pr_feedback_scope=createSwarmTool({description:"Prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles.",args:{task_id:PreparePrFeedbackScopeArgsSchema.shape.task_id,files:PreparePrFeedbackScopeArgsSchema.shape.files},execute:executePreparePrFeedbackScope});init_quality_budget();init_zod();init_pr_workflow_gate();init_create_tool();var RebindPrFeedbackHeadArgsSchema=exports_external.object({pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{40}$/i)}).strict();async function executeRebindPrFeedbackHead(args2,directory,context={}){let parsed=RebindPrFeedbackHeadArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR feedback rebind: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR feedback rebind requires an active sessionID"});try{let state2=await rebindPrFeedbackHead(directory,context.sessionID,parsed.data.pr_head_sha);return JSON.stringify({success:!0,pr_head_sha:state2.prHeadSha,rebind_count:state2.prFeedbackRebindCount??1,message:"Rebound the PR_FEEDBACK intake head; every Stage A / verification / gate receipt is invalidated — re-run the full mechanical ladder on the new ancestry."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var rebind_pr_feedback_head=createSwarmTool({description:"Rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair (base-sync). Use ONLY when the history genuinely changed to repair base drift or conflicts: it refuses a no-op rebind to the current intake head, refuses while publication is armed (to change approved content after arming use invalidate_pr_feedback_publication), and refuses while lanes are in flight. It invalidates every ancestry-bound receipt (Stage A, verification, ordered gates) so the full mechanical ladder re-runs on the new ancestry. Requires the full 40-char new PR head SHA; the current checkout must equal it.",args:{pr_head_sha:RebindPrFeedbackHeadArgsSchema.shape.pr_head_sha},execute:executeRebindPrFeedbackHead});init_zod();init_utils2();init_atomic_write();init_create_tool();var FreshnessValueSchema=exports_external.string().trim().min(1).max(500).regex(/^(synced|behind:[1-9][0-9]*|fetch-failed:\S+)$/,"must be 'synced', 'behind:<n>', or 'fetch-failed:<reason>' (reason contains no whitespace)"),RecordBranchFreshnessArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),freshness:FreshnessValueSchema,override:exports_external.string().trim().min(1).max(4000).optional()}).strict();async function executeRecordBranchFreshness(args2,directory,context={}){let parsed=RecordBranchFreshnessArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid branch-freshness receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.freshness==="synced"&&data.override)return JSON.stringify({success:!1,message:"An override is only meaningful for a fetch-failed outcome; a synced base needs none."});let receipt={issueNumber:data.issueNumber,freshness:data.freshness,timestamp:new Date().toISOString()};if(data.override)receipt.override=data.override;if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"branch-freshness.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2));let permits=await branchFreshnessReceiptExists(directory,data.issueNumber);return JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/branch-freshness.json",permits,message:permits?`Branch-freshness receipt recorded for issue #${data.issueNumber}; the trace's freshness gate is satisfied.`:`Branch-freshness receipt recorded for issue #${data.issueNumber}, but the outcome (${data.freshness}) does NOT permit the trace — ${data.freshness.startsWith("behind:")?"re-sync with the default branch and re-record as synced.":"a fetch-failed outcome without a recorded user override fails closed."}`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_branch_freshness=createSwarmTool({description:`Record the Phase 0 branch-freshness outcome for the current traced issue (issue #2564): freshness is "synced", "behind:<n>", or "fetch-failed:<reason>" exactly as the fetch recorded it, plus an optional verbatim user override for a failed fetch. The /swarm issue --trace workflow will not transition to PLAN until the recorded outcome permits (synced, or fetch-failed with an override). The response's permits field mirrors the gate reader's verdict on the persisted receipt (advisory for the calling agent — the reducer always recomputes it independently).`,args:{issueNumber:RecordBranchFreshnessArgsSchema.shape.issueNumber,freshness:RecordBranchFreshnessArgsSchema.shape.freshness,override:RecordBranchFreshnessArgsSchema.shape.override},execute:executeRecordBranchFreshness});init_zod();init_schema();init_extractors();init_manager();init_create_tool();var recordDirectiveOverrideInternals={loadPlan,recordDirectiveOverrides};async function executeRecordDirectiveOverride(args2,directory,ctx){if(!ctx?.sessionID?.trim())return{success:!1,code:"DIRECTIVE_OVERRIDE_SESSION_REQUIRED",message:"An exact session identity is required to record an override."};if(stripKnownSwarmPrefix(ctx.agent??"").toLowerCase()!=="architect")return{success:!1,code:"DIRECTIVE_OVERRIDE_ARCHITECT_ONLY",message:"Only the architect may record a critical-directive override."};let plan=await recordDirectiveOverrideInternals.loadPlan(directory),requestedPhase=plan?.phases.find((candidate2)=>candidate2.id===args2.phase);if(!plan||!requestedPhase||plan.current_phase!==args2.phase)return{success:!1,code:"DIRECTIVE_OVERRIDE_PHASE_MISMATCH",message:`Phase ${args2.phase} is not the current authoritative plan phase.`};let phaseLabel=extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase}`;return await recordDirectiveOverrideInternals.recordDirectiveOverrides(directory,[...new Set(args2.directive_ids)],args2.justification,ctx.sessionID,phaseLabel,args2.phase),{success:!0,code:"DIRECTIVE_OVERRIDE_RECORDED",phase:args2.phase,directive_ids:[...new Set(args2.directive_ids)],message:"Recorded the audited override. Retry phase_complete so every gate is re-evaluated from a fresh snapshot."}}var record_directive_override=createSwarmTool({description:"Architect-only audited override for identified critical-directive violations. Requires exact current phase/session identity and substantive justification; it cannot repair or bypass unreadable authority.",args:{directive_ids:exports_external.array(exports_external.string().min(1).max(256)).min(1).max(64),justification:exports_external.string().trim().min(10).max(2000),phase:exports_external.number().int().min(1).max(9999)},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRecordDirectiveOverride(args2,directory,ctx),null,2)});init_zod();init_utils2();init_atomic_write();init_create_tool();var RecordImplementationReviewArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),reviewerVerdict:exports_external.enum(["APPROVE","NEEDS_REVISION","BLOCKED"]),criticVerdict:exports_external.enum(["APPROVE","NEEDS_REVISION","BLOCKED"]),diffBase:exports_external.string().trim().regex(/^[0-9a-f]{7,40}$/i),diffHead:exports_external.string().trim().regex(/^[0-9a-f]{7,40}$/i),notes:exports_external.string().trim().min(8).max(4000)}).strict();async function executeRecordImplementationReview(args2,directory,context={}){let parsed=RecordImplementationReviewArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid implementation review receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.reviewerVerdict!=="APPROVE"||data.criticVerdict!=="APPROVE")return JSON.stringify({success:!1,message:"A satisfying implementation-review receipt requires BOTH the reviewer and the critic to have delivered APPROVE; record non-approving verdicts in the working notes and fix the findings instead."});let receipt={issueNumber:data.issueNumber,reviewerVerdict:data.reviewerVerdict,criticVerdict:data.criticVerdict,diffBase:data.diffBase,diffHead:data.diffHead,notes:data.notes,timestamp:new Date().toISOString()};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"implementation-review.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/implementation-review.json",message:`Implementation review recorded for issue #${data.issueNumber} (reviewer APPROVE + critic APPROVE); the trace may now satisfy its review gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_implementation_review=createSwarmTool({description:"Record the independent implementation review for the current traced issue (issue #2131 residual B): dispatch FRESH-context reviewer and critic passes over the implementation diff (separate contexts from the implementer), and once BOTH approve call this with the issue number, both APPROVE verdicts, the reviewed diff base/head SHAs, and notes. The /swarm issue --trace workflow will not hand off to commit-pr until this receipt exists. Non-approving verdicts cannot be recorded here — fix the findings and re-review.",args:{issueNumber:RecordImplementationReviewArgsSchema.shape.issueNumber,reviewerVerdict:RecordImplementationReviewArgsSchema.shape.reviewerVerdict,criticVerdict:RecordImplementationReviewArgsSchema.shape.criticVerdict,diffBase:RecordImplementationReviewArgsSchema.shape.diffBase,diffHead:RecordImplementationReviewArgsSchema.shape.diffHead,notes:RecordImplementationReviewArgsSchema.shape.notes},execute:executeRecordImplementationReview});init_zod();init_url_security();init_loader();init_utils2();init_forge_provider();init_atomic_write();init_create_tool();function loadConfiguredForgeContext4(directory){try{let config3=loadPluginConfig(directory),remote=detectGitRemote(directory,void 0);return resolveForgeContextFromPluginConfig(config3,remote?[remote]:[])??void 0}catch{return}}var RecordIssuePublicationArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),prNumber:exports_external.number().int().min(1),prUrl:exports_external.string().url(),headSha:exports_external.string().min(1).optional()}).strict();async function executeRecordIssuePublication(args2,directory){let parsed=RecordIssuePublicationArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid publication receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let{issueNumber,prNumber,prUrl,headSha}=parsed.data,sanitizedPrUrl=sanitizeUrl(prUrl);if(!isForgePrUrl(prUrl)){let configured=loadConfiguredForgeContext4(directory);if(!(configured&&isForgePrUrl(prUrl,configured)))return JSON.stringify({success:!1,message:"Invalid publication receipt: prUrl must be a canonical PR URL (GitHub https://github.com/<owner>/<repo>/pull/<number> or GitLab https://<gitlab-host>/<owner>/<repo>/-/merge_requests/<number>)"})}let receipt={published:!0,issueNumber,prNumber,prUrl:sanitizedPrUrl,publishedAt:new Date().toISOString()};if(headSha)receipt.headSha=headSha;let validatedPath;try{validatedPath=validateSwarmPath(directory,"issue-publication.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber,prNumber,prUrl,path:".swarm/issue-publication.json",message:`Publication receipt recorded for issue #${issueNumber} (PR #${prNumber}); the issue-trace workflow will transition to its terminal published state.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_issue_publication=createSwarmTool({description:'Record that the traced issue has been published (PR created/updated) so the /swarm issue --trace workflow can reach its terminal published state. The trace stops at publication_handoff (the commit-pr directive) until this receipt is observed — publication_handoff is NOT "issue resolved". commit-pr calls this after the PR is created/updated. Supply the traced issue number, the exact PR number, the canonical PR URL (GitHub or GitLab), and (optionally) the published HEAD sha. The receipt is issue-bound.',args:{issueNumber:RecordIssuePublicationArgsSchema.shape.issueNumber,prNumber:RecordIssuePublicationArgsSchema.shape.prNumber,prUrl:RecordIssuePublicationArgsSchema.shape.prUrl,headSha:RecordIssuePublicationArgsSchema.shape.headSha},execute:executeRecordIssuePublication});init_zod();init_utils2();init_atomic_write();init_create_tool();var RecordIssueReproductionArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),performed:exports_external.boolean(),commands:exports_external.array(exports_external.string().min(1)).min(1).optional(),output_summary:exports_external.string().min(1).optional()}).strict();async function executeRecordIssueReproduction(args2,directory,context={}){let parsed=RecordIssueReproductionArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid reproduction receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let{issueNumber,performed,commands,output_summary}=parsed.data;if(performed&&(!commands||commands.length===0||!output_summary))return JSON.stringify({success:!1,message:"A performed=true reproduction receipt requires non-empty commands and output_summary."});let receipt={performed,issueNumber,timestamp:new Date().toISOString()};if(commands)receipt.commands=commands;if(output_summary)receipt.output_summary=output_summary;if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"reproduction.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber,performed,path:".swarm/reproduction.json",message:performed?`Reproduction receipt recorded for issue #${issueNumber}; the trace may now transition to PLAN.`:`Reproduction receipt recorded (performed=false) for issue #${issueNumber}; it does NOT satisfy the reproduction gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_issue_reproduction=createSwarmTool({description:"Record the reproduction outcome for the current traced issue. The /swarm issue --trace workflow requires reproduction evidence (or a typed --no-repro waiver) before it can leave localization and transition to PLAN. Call this with performed=true, the exact commands run, and a concrete output_summary after attempting a minimal reproduction; the receipt binds to issueNumber (and records the calling session) and is read by the issue-trace engine. A performed=true receipt MUST include commands and output_summary. A performed=false receipt is recorded but does NOT satisfy the gate.",args:{issueNumber:RecordIssueReproductionArgsSchema.shape.issueNumber,performed:RecordIssueReproductionArgsSchema.shape.performed,commands:RecordIssueReproductionArgsSchema.shape.commands,output_summary:RecordIssueReproductionArgsSchema.shape.output_summary},execute:executeRecordIssueReproduction});init_zod();init_utils2();init_atomic_write();init_create_tool();var HEX40=/^[0-9a-f]{40}$/,RecordMergeApprovalArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),prHeadSha:exports_external.string().regex(HEX40,"must be a 40-hex commit SHA"),finalCriticReviewedCommit:exports_external.string().regex(HEX40,"must be a 40-hex commit SHA"),userApprovalVerbatim:exports_external.string().trim().min(1).max(8000)}).strict();async function executeRecordMergeApproval(args2,directory,context={}){let parsed=RecordMergeApprovalArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid merge-approval receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.prHeadSha!==data.finalCriticReviewedCommit)return JSON.stringify({success:!1,message:"Merge-approval binding failed: prHeadSha must equal finalCriticReviewedCommit (the final critic approval must be bound to the exact PR head)."});let receipt={issueNumber:data.issueNumber,prHeadSha:data.prHeadSha,finalCriticReviewedCommit:data.finalCriticReviewedCommit,userApprovalVerbatim:data.userApprovalVerbatim,timestamp:new Date().toISOString()};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"merge-approval.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/merge-approval.json",message:`Merge approval recorded for issue #${data.issueNumber}, bound to PR head ${data.prHeadSha}. The approval is captured verbatim for audit; the merge itself is human-enforced and this plugin neither drives nor certifies it.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_merge_approval=createSwarmTool({description:"Record the human merge approval for the current traced issue (issue #2564): prHeadSha and finalCriticReviewedCommit must be the same 40-hex SHA (the final critic approval bound to the exact PR head), and userApprovalVerbatim is the user approval quoted verbatim. The receipt is recorded for audit only — the merge stays human-enforced and the plugin never certifies or drives it.",args:{issueNumber:RecordMergeApprovalArgsSchema.shape.issueNumber,prHeadSha:RecordMergeApprovalArgsSchema.shape.prHeadSha,finalCriticReviewedCommit:RecordMergeApprovalArgsSchema.shape.finalCriticReviewedCommit,userApprovalVerbatim:RecordMergeApprovalArgsSchema.shape.userApprovalVerbatim},execute:executeRecordMergeApproval});init_zod();init_utils2();init_atomic_write();init_create_tool();var DispositionSchema=exports_external.object({ref:exports_external.string().trim().min(1).max(500),disposition:exports_external.enum(["FIX","FALSE_POSITIVE","OUT_OF_CLASS","DEFERRED_WITH_USER_APPROVAL"]),note:exports_external.string().trim().max(1000).optional()}).strict(),GuardrailSchema=exports_external.object({kind:exports_external.enum(["lint-static-analysis","type-level","runtime-assertion","ci-check","documented-invariant-plus-regression-test"]),description:exports_external.string().trim().min(8).max(2000),proof:exports_external.string().trim().min(8).max(4000)}).strict(),RelatedProblemSchema=exports_external.object({ref:exports_external.string().trim().min(1).max(500),note:exports_external.string().trim().max(1000).optional()}).strict(),RecordRecurrenceSweepArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),defectClass:exports_external.string().trim().min(1).max(1000),justification:exports_external.string().trim().min(1).max(1000).optional(),predicates:exports_external.array(exports_external.string().trim().min(1).max(500)).min(1).max(32).optional(),dispositions:exports_external.array(DispositionSchema).min(1).max(200).optional(),guardrail:GuardrailSchema.optional(),relatedProblems:exports_external.array(RelatedProblemSchema).min(1).max(200)}).strict();async function executeRecordRecurrenceSweep(args2,directory,context={}){let parsed=RecordRecurrenceSweepArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recurrence sweep receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data,noDefectClass=data.defectClass==="no defect class";if(noDefectClass){if(!data.justification)return JSON.stringify({success:!1,message:'The "no defect class" fast path requires a one-line justification.'})}else if(!data.predicates||data.predicates.length===0||!data.dispositions||data.dispositions.length===0||!data.guardrail)return JSON.stringify({success:!1,message:"A defect-class sweep requires search predicates, a non-empty disposition for every hit (at least one — the original defect site itself, dispositioned FIX), and a guardrail with proof it catches the original defect. An empty dispositions array is indistinguishable from a sweep that never ran."});let receipt={issueNumber:data.issueNumber,defectClass:data.defectClass,timestamp:new Date().toISOString()};if(data.justification)receipt.justification=data.justification;if(data.predicates)receipt.predicates=data.predicates;if(data.dispositions)receipt.dispositions=data.dispositions;if(data.guardrail)receipt.guardrail=data.guardrail;if(receipt.relatedProblems=data.relatedProblems,context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"recurrence-sweep.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/recurrence-sweep.json",message:noDefectClass?`Recurrence sweep recorded for issue #${data.issueNumber} (no defect class fast path).`:`Recurrence sweep recorded for issue #${data.issueNumber}; the trace may now satisfy its recurrence gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_recurrence_sweep=createSwarmTool({description:'Record the recurrence sweep for the current traced issue (issue #2131 residual B; widened in #2564 and #2600). The /swarm issue --trace workflow will not hand off to commit-pr until this receipt exists. Supply relatedProblems (the Phase 1 related-problems sweep results — at least one {ref, note?} entry) plus, for a real defect class: defectClass (one-sentence characterization), predicates (the exact search predicates), dispositions (non-empty — every hit as FIX / FALSE_POSITIVE / OUT_OF_CLASS / DEFERRED_WITH_USER_APPROVAL, including the original defect site), and a guardrail (kind + description + proof it catches the original defect). If the change corrects no incorrect behavior, use the literal defectClass "no defect class" with a one-line justification (relatedProblems still required).',args:{issueNumber:RecordRecurrenceSweepArgsSchema.shape.issueNumber,defectClass:RecordRecurrenceSweepArgsSchema.shape.defectClass,justification:RecordRecurrenceSweepArgsSchema.shape.justification,predicates:RecordRecurrenceSweepArgsSchema.shape.predicates,dispositions:RecordRecurrenceSweepArgsSchema.shape.dispositions,guardrail:RecordRecurrenceSweepArgsSchema.shape.guardrail,relatedProblems:RecordRecurrenceSweepArgsSchema.shape.relatedProblems},execute:executeRecordRecurrenceSweep});init_zod();import*as fs219 from"node:fs";init_utils2();init_file_locks();init_atomic_write();init_create_tool();var HEX402=/^[0-9a-f]{40}$/,TRACE_VALIDATION_PHASES2=["0","1","2","2.5","3","4","4.2","4.5","4.6","5"],ValidationEntrySchema=exports_external.object({phase:exports_external.enum(TRACE_VALIDATION_PHASES2),outcome:exports_external.enum(["pass","fail"]),reviewedCommit:exports_external.string().regex(HEX402,"must be a 40-hex commit SHA"),treeId:exports_external.string().regex(HEX402,"must be a 40-hex tree id")}).strict(),RecordTraceValidationArgsSchema=ValidationEntrySchema.extend({issueNumber:exports_external.number().int().min(1)}).strict();async function executeRecordTraceValidation(args2,directory,context={}){let parsed=RecordTraceValidationArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid trace-validation receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data,validatedPath;try{validatedPath=validateSwarmPath(directory,"trace-validation.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{let lockResult=await tryAcquireLock(directory,"trace-validation.json","trace-validation","trace-validation");if(!lockResult.acquired)return JSON.stringify({success:!1,message:"The trace-validation receipt is locked by another concurrent writer; no write was attempted. Re-run record_trace_validation for this phase once the other writer finishes."});try{let validations=[];try{let raw=await fs219.promises.readFile(validatedPath,"utf-8"),existing=JSON.parse(raw);if(typeof existing==="object"&&existing!==null&&Array.isArray(existing.validations))validations=existing.validations.filter((v)=>typeof v==="object"&&v!==null&&typeof v.phase==="string")}catch{}let entry={phase:data.phase,outcome:data.outcome,reviewedCommit:data.reviewedCommit,treeId:data.treeId,timestamp:new Date().toISOString()},idx=validations.findIndex((v)=>v.phase===data.phase);if(idx===-1)validations.push(entry);else validations[idx]=entry;let receipt={issueNumber:data.issueNumber,timestamp:new Date().toISOString(),validations};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2));let allGreen=await traceValidationReceiptExists(directory,data.issueNumber);return JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/trace-validation.json",allGreen,message:allGreen?`Validator receipt recorded for issue #${data.issueNumber} phase ${data.phase} (${data.outcome}); every recorded phase is green.`:`Validator receipt recorded for issue #${data.issueNumber} phase ${data.phase} (${data.outcome}), but at least one recorded phase is failing — fix and re-record that phase as a pass before handoff.`})}finally{try{await lockResult.lock._release?.()}catch{}}}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_trace_validation=createSwarmTool({description:"Record one per-phase trace-check.sh validator outcome for the current traced issue (issue #2564): the phase (v3 enum 0..5 incl. 2.5/4.2/4.5/4.6), the outcome (pass or fail), and the exact reviewedCommit and treeId the validator reported. Re-running a phase replaces its entry. The /swarm issue --trace workflow will not hand off to commit-pr while any recorded phase is failing or none is recorded. The receipt write is serialized by a per-file receipt lock, and the response's allGreen field mirrors the gate reader's verdict on the persisted receipt (advisory for the calling agent — the reducer always recomputes it independently).",args:{issueNumber:RecordTraceValidationArgsSchema.shape.issueNumber,phase:RecordTraceValidationArgsSchema.shape.phase,outcome:RecordTraceValidationArgsSchema.shape.outcome,reviewedCommit:RecordTraceValidationArgsSchema.shape.reviewedCommit,treeId:RecordTraceValidationArgsSchema.shape.treeId},execute:executeRecordTraceValidation});init_zod();init_schema();init_gate_evidence();init_manager();init_path_identity();init_state();init_stage_a_repair();import*as fs220 from"node:fs";import*as path361 from"node:path";async function forceRecoverReworkTask(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("RECOVER_REWORK_ARCHITECT_REQUIRED: recover_rework_task requires an active architect session. The rework escape hatch is architect-only; a coder/reviewer/test_engineer cannot self-unblock a task.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('RECOVER_REWORK_UNKNOWN_TASK: recover_rework_task requires the exact plan task id (e.g. "1.1").');let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path361.join(directory,".swarm","plan.json");if(fs220.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recovering a rework_required task.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot recover a rework_required "+"task without a plan. Save a plan first.")}if(!new Set(plan.phases.flatMap((phase)=>phase.tasks.map((task2)=>task2.id))).has(taskId))throw Error(`RECOVER_REWORK_UNKNOWN_TASK: task ${taskId} is not in the current plan. Refusing to recover a foreign task id.`);let evidenceRead=await readTaskEvidenceState(directory,taskId);if(evidenceRead.kind==="unparseable")throw Error(`RECOVER_REWORK_EVIDENCE_CORRUPT: the workflow evidence file for task ${taskId} exists but could not be parsed (${evidenceRead.evidencePath}). Repair the evidence first (repair_gate_evidence or /swarm doctor); recovery cannot classify a corrupt evidence state.`);let evidence2=evidenceRead.kind==="ok"?evidenceRead.evidence:null,workflow=getTaskWorkflowSnapshot(evidence2);if(!evidence2||!workflow.authoritative)throw Error(`RECOVER_REWORK_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no rework state to recover.`);if(workflow.state!=="rework_required")throw Error(`RECOVER_REWORK_STATE_REQUIRED: task ${taskId} is at ${workflow.state}, not rework_required. This recovery applies only to a task whose Stage B verdict moved it to rework_required without a code change. From coder_delegated, run pre_check_batch; for a genuine code defect, delegate the coder to repair it first.`);let wedgeMs=Date.parse(workflow.updatedAt);if(!Number.isFinite(wedgeMs))throw Error(`RECOVER_REWORK_GREEN_PRECHECK_REQUIRED: cannot prove pre-check recency (workflow updatedAt "${workflow.updatedAt}" is not a parseable timestamp — the evidence file for task ${taskId} is likely corrupt). Repair the evidence (repair_gate_evidence or /swarm doctor); re-running pre_check_batch cannot fix an unparseable timestamp.`);let greenness=await hasGreenPostSettlementPreCheck(directory,wedgeMs);if(!greenness.green){let sastHint=greenness.reason==="no_pre_check_bundles"?" Note: if gates.sast_scan.enabled is false, no sast_scan bundle is ever persisted and this recovery is unavailable by design — enable gates.sast_scan.enabled and run sast_scan, or use the coder repair loop.":"";throw Error(`RECOVER_REWORK_GREEN_PRECHECK_REQUIRED: refusing to mark Stage A passed without proof (${greenness.reason}). `+"The bar is a green secretscan AND sast_scan evidence pair newer than the failing verdict — normally provided by a fresh pre_check_batch run (bundle proof is global, not correlated to the task's changed files)."+sastHint)}let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?sanitizeDiagnosticText(options.reason.trim(),500):void 0,recordedAt=new Date().toISOString(),transitionId=`rework-recovery:${taskId}:gen${workflow.generation}`,updated=await transitionTaskWorkflowEvidence(directory,taskId,{type:"stage_a_passed",supervisedRecovery:!0,expectedGeneration:workflow.generation,transitionId}),updatedWorkflow=getTaskWorkflowSnapshot(updated),auditEventRecorded=await appendStageARepairEvent(directory,{action:"rework_recovered",taskId,transitionId,generation:workflow.generation,sessionId:sessionID,...sanitizedReason?{reason:sanitizedReason}:{}});return{taskId,generation:updatedWorkflow.generation,state:updatedWorkflow.state,transitionId,recordedAt,auditEventRecorded}}init_create_tool();var RecoverReworkTaskArgsSchema=exports_external.object({task_id:exports_external.string().trim().min(1).max(64).describe('Exact plan task id of the rework_required task (e.g. "1.1"). Must exist in the current plan and have durable workflow evidence at state rework_required.'),reason:exports_external.string().trim().min(1).max(500).describe('Why the Stage B verdict did not require a code change (e.g. "test_engineer returned SKIPPED for a tool-argument error while pytest passes"). Audited to .swarm/events.jsonl.')}).strict();async function executeRecoverReworkTask(args2,directory,context={}){let parsed=RecoverReworkTaskArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recover_rework_task call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"recover_rework_task requires an active sessionID"});try{let summary=await forceRecoverReworkTask(directory,context.sessionID,{taskId:parsed.data.task_id,reason:parsed.data.reason}),auditNote=summary.auditEventRecorded?"The recovery is audited to .swarm/events.jsonl (stage_a_repair action rework_recovered).":"WARNING: the audit event could NOT be appended to .swarm/events.jsonl (see the plugin log); the durable workflow evidence still records the supervised recovery via the rework-recovery: transition id.";return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,transition_id:summary.transitionId,recorded_at:summary.recordedAt,audit_event_recorded:summary.auditEventRecorded,method:"supervised_recovery",message:`Task ${summary.taskId} recovered from rework_required: a supervised stage_a_passed was written at generation ${summary.generation} (transition id `+summary.transitionId+"). Reviewer/test_engineer dispatch is permitted again — re-run the Stage B gates that the failed verdict cleared. "+auditNote+" Use it ONLY when the Stage B verdict did not require a code change; a genuine defect still needs the coder repair loop."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var recover_rework_task=createSwarmTool({description:"Recover a task wedged at rework_required when the Stage B verdict did NOT require a code change (issue #2755): writes a supervised stage_a_passed for the current generation so reviewer/test_engineer can be re-dispatched, without re-running the coder. Requires the exact plan task id, an active architect session, durable workflow state exactly rework_required, and green pre-check proof: green secretscan AND sast_scan evidence bundles newer than the failing verdict (normally from a fresh pre_check_batch run; bundle recency is global, not file-correlated; projects with SAST disabled cannot use this path). Fail-closed otherwise; the mechanical stage_a_passed path still requires an accepted coder mutation. A reason is required and audited to .swarm/events.jsonl (stage_a_repair action rework_recovered). Prefer the coder repair loop when the code actually has a defect.",args:{task_id:RecoverReworkTaskArgsSchema.shape.task_id,reason:RecoverReworkTaskArgsSchema.shape.reason},execute:executeRecoverReworkTask});init_zod();init_schema();init_gate_evidence();init_path_identity();init_state();init_coder_settlement();init_session_view();init_stage_a_repair();async function recoverStageATaskSupervised(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("RECOVER_STAGE_A_ARCHITECT_REQUIRED: recover_stage_a_task requires an active architect session. The settlement-backed Stage A escape hatch is architect-only; a coder/reviewer/test_engineer cannot self-unblock a task.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('RECOVER_STAGE_A_UNKNOWN_TASK: recover_stage_a_task requires the exact task id of the settlement-wedged task (e.g. "1.1").');let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?sanitizeDiagnosticText(options.reason.trim(),500):void 0;if(!sanitizedReason)throw Error("RECOVER_STAGE_A_REASON_REQUIRED: recover_stage_a_task requires a reason describing why the settlement-backed recovery is justified; it is audited to .swarm/events.jsonl.");let evidenceRead=await readTaskEvidenceState(directory,taskId);if(evidenceRead.kind==="unparseable")throw Error(`RECOVER_STAGE_A_EVIDENCE_CORRUPT: the workflow evidence file for task ${taskId} exists but could not be parsed (${evidenceRead.evidencePath}). Repair the evidence first (repair_gate_evidence or /swarm doctor); recovery cannot classify a corrupt evidence state.`);let evidence2=evidenceRead.kind==="ok"?evidenceRead.evidence:null,workflow=getTaskWorkflowSnapshot(evidence2);if(!evidence2||!workflow.authoritative)throw Error(`RECOVER_STAGE_A_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no settlement wedge to recover.`);if(workflow.state==="pre_check_passed"||workflow.state==="reviewer_run"||workflow.state==="tests_run"){if(isStageARecoveredState(workflow.state)&&shouldRefreshStageARecoveryView(session.taskWorkflowStates.get(taskId),workflow.state))applySessionWorkflowView(session,taskId,workflow);return{taskId,generation:workflow.generation,state:workflow.state,transitionId:`stage-a-supervised:${taskId}:noop`,recordedAt:new Date().toISOString(),alreadyRecovered:!0,auditEventRecorded:!1}}if(workflow.state!=="idle"&&workflow.state!=="blocked")throw Error(`RECOVER_STAGE_A_STATE_REQUIRED: task ${taskId} is at ${workflow.state}, not idle/blocked. This recovery applies only to the settlement-backed wedge (a COMMITTED accepted coder settlement while the workflow drifted to idle or blocked). From coder_delegated, run pre_check_batch or /swarm recover; from rework_required without a code change, use recover_rework_task.`);let{states:walStates}=await listCoderSettlementWalStates(directory),settledAfterMs=latestCommittedAcceptedSettlementMs(taskId,walStates);if(settledAfterMs===null)throw Error(`RECOVER_STAGE_A_SETTLEMENT_REQUIRED: refusing to recover task ${taskId} — no COMMITTED accepted coder settlement exists for it. `+"The settlement receipt is what distinguishes this wedge from a not-yet-started or deliberately stopped task; recovery without it would fabricate Stage A justification. Background-dispatched coder tasks never write a settlement WAL and cannot use this path.");let greenness=await hasGreenPostSettlementPreCheck(directory,settledAfterMs);if(!greenness.green){let sastHint=greenness.reason==="no_pre_check_bundles"?" Note: if gates.sast_scan.enabled is false, no sast_scan bundle is ever persisted and this recovery is unavailable by design — enable gates.sast_scan.enabled and run sast_scan, or use the coder repair loop.":"";throw Error(`RECOVER_STAGE_A_GREEN_PRECHECK_REQUIRED: refusing to mark Stage A passed without proof (${greenness.reason}). `+"The bar is a green secretscan AND sast_scan evidence pair newer than the settlement commit — normally provided by a fresh pre_check_batch run (bundle proof is global, not correlated to the task's changed files)."+sastHint)}let recordedAt=new Date().toISOString(),transitionId=`stage-a-supervised:${taskId}:${workflow.generation}`,updated=await transitionTaskWorkflowEvidence(directory,taskId,{type:"stage_a_passed",settlementRecovery:!0,expectedGeneration:workflow.generation,transitionId}),updatedWorkflow=getTaskWorkflowSnapshot(updated);if(isStageARecoveredState(updatedWorkflow.state)){if(shouldRefreshStageARecoveryView(session.taskWorkflowStates.get(taskId),updatedWorkflow.state))applySessionWorkflowView(session,taskId,updatedWorkflow)}let auditEventRecorded=await appendStageARepairEvent(directory,{action:"repaired",via:"recover_stage_a_task",taskId,transitionId,generation:workflow.generation,settlementRecovery:!0,predecessorTransitionId:workflow.lastTransitionId??null,sessionId:sessionID,reason:sanitizedReason});return{taskId,generation:updatedWorkflow.generation,state:updatedWorkflow.state,transitionId,recordedAt,alreadyRecovered:!1,auditEventRecorded}}init_create_tool();var RecoverStageATaskArgsSchema=exports_external.object({task_id:exports_external.string().trim().min(1).max(64).describe('Exact task id of the settlement-wedged task (e.g. "1.1"). Must have durable workflow evidence at state idle or blocked, a COMMITTED accepted coder settlement, and green post-settlement pre-check proof.'),reason:exports_external.string().trim().min(1).max(500).describe('Why the settlement-backed recovery is justified (e.g. "settlement COMMITTED and pre_check_batch green but stage_a_passed never fired; force-repair cleared the proofs"). Audited to .swarm/events.jsonl.')}).strict();async function executeRecoverStageATask(args2,directory,context={}){let parsed=RecoverStageATaskArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recover_stage_a_task call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"recover_stage_a_task requires an active sessionID"});try{let summary=await recoverStageATaskSupervised(directory,context.sessionID,{taskId:parsed.data.task_id,reason:parsed.data.reason});if(summary.alreadyRecovered)return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,already_recovered:!0,message:`Task ${summary.taskId} already has Stage A recorded (state ${summary.state}, generation ${summary.generation}) — nothing to recover.`});let auditNote=summary.auditEventRecorded?"The recovery is audited to .swarm/events.jsonl (stage_a_repair action repaired, via recover_stage_a_task).":"WARNING: the audit event could NOT be appended to .swarm/events.jsonl (see the plugin log); the durable workflow evidence still records the settlement-backed recovery via the stage-a-supervised: transition id and the settlementRecovery marker.";return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,transition_id:summary.transitionId,recorded_at:summary.recordedAt,audit_event_recorded:summary.auditEventRecorded,method:"settlement_recovery",message:`Task ${summary.taskId} recovered from the settlement wedge: a settlement-backed stage_a_passed was written at generation ${summary.generation} (transition id `+summary.transitionId+"). Reviewer/test_engineer dispatch is permitted again — run the Stage B gates the task still needs. "+auditNote+" Use it ONLY when a COMMITTED accepted settlement and green post-settlement pre-check proof already justify Stage A; it never re-runs the coder and never edits gate evidence."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var recover_stage_a_task=createSwarmTool({description:"Recover a task wedged in the settlement-backed Stage A deadlock (issue #2828): workflow at idle or blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof (green secretscan AND sast_scan evidence newer than the settlement commit) still justify Stage A — the shape where stage_a_passed never fired, a force-repair cleared the proofs, and every other recovery path refuses. Writes a settlement-backed stage_a_passed for the current generation so reviewer/test_engineer can be dispatched, without re-running the coder and without editing gate evidence. Requires the exact task id (bound by its durable workflow evidence and settlement WAL — deliberately no plan-membership precondition, mirroring the /swarm recover scan), an active architect session, a reason (audited), and durable workflow evidence at exactly idle/blocked. Fail-closed otherwise (RECOVER_STAGE_A_* errors); the mechanical stage_a_passed path still requires an accepted coder mutation or the #2665 live_wedge scan.",args:{task_id:RecoverStageATaskArgsSchema.shape.task_id,reason:RecoverStageATaskArgsSchema.shape.reason},execute:executeRecoverStageATask});init_zod();init_schema();init_gate_evidence();init_utils2();init_manager();init_state();init_project_boundary();init_swarm_artifact_cache();init_task_id();init_task_file();init_task_gate_requirements();init_gate_evidence();import{createHash as createHash117,randomUUID as randomUUID48}from"node:crypto";import*as fs221 from"node:fs";import*as path362 from"node:path";var TASK_GATE_EVIDENCE_QUARANTINE_DIR=path362.join("evidence","task-gate-quarantine"),MAX_TASK_GATE_EVIDENCE_BYTES=262144,MAX_TASK_GATE_EVIDENCE_QUARANTINE_FILES=32,MAX_TASK_GATE_EVIDENCE_QUARANTINE_BYTES=12582912,MAX_TASK_GATE_EVIDENCE_QUARANTINE_DIRECTORY_ENTRIES=128,MAX_TASK_GATE_EVIDENCE_QUARANTINE_RECORD_BYTES=786432,TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION=1,GENERIC_REPAIR_REASONS=new Set(["fix","repair","test","debug","unknown","n/a","na","none"]);function isQuarantinableTaskEvidenceRead(read){return read.status==="corrupt"||read.status==="valid"}function sha25614(bytes){return createHash117("sha256").update(bytes).digest("hex")}function normalizeRepairReason(reason){let normalized=reason.trim().replace(/\s+/g," ");if(normalized.length<12)throw Error("TASK_GATE_EVIDENCE_REASON_REQUIRED: repair_gate_evidence requires a substantive reason of at least 12 characters.");if(GENERIC_REPAIR_REASONS.has(normalized.toLowerCase()))throw Error("TASK_GATE_EVIDENCE_REASON_REQUIRED: repair_gate_evidence requires a substantive reason, not a placeholder.");return normalized}function canonicalizeRepairRoot(directory){let requestedRoot=path362.resolve(directory),requestedStat=fs221.lstatSync(requestedRoot);if(requestedStat.isSymbolicLink()||!requestedStat.isDirectory())throw Error("TASK_GATE_EVIDENCE_ROOT_UNSAFE: repair_gate_evidence requires a canonical project root directory, not a symlink, junction, reparse point, or non-directory path.");let canonicalRoot2=fs221.realpathSync(requestedRoot);return assertProjectRoot(canonicalRoot2),canonicalRoot2}function assertExistingRegularPath(root,relativePath2){let segments=relativePath2.replace(/\\/g,"/").split("/").filter(Boolean),cursor=root;for(let segment of segments){if(cursor=path362.join(cursor,segment),!fs221.existsSync(cursor))return;if(fs221.lstatSync(cursor).isSymbolicLink())throw Error(`TASK_GATE_EVIDENCE_PATH_UNSAFE: ${relativePath2} contains a symlink, junction, or reparse point.`)}}function taskEvidenceFilePath(directory,taskId){let relativePath2=taskEvidenceRelPath(taskId);return assertExistingRegularPath(directory,".swarm"),assertExistingRegularPath(directory,path362.join(".swarm","evidence")),assertExistingRegularPath(directory,path362.join(".swarm",relativePath2)),validateSwarmPath(directory,relativePath2)}function readTaskEvidenceForRepair(directory,taskId){let filePath=taskEvidenceFilePath(directory,taskId),pathStat;try{pathStat=fs221.lstatSync(filePath)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:error93}}if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:Error("TASK_GATE_EVIDENCE_UNREADABLE: evidence path is not a regular file")};if(pathStat.size>MAX_TASK_GATE_EVIDENCE_BYTES)return{status:"oversized",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:Error(`TASK_GATE_EVIDENCE_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_EVIDENCE_BYTES}`)};let descriptor=fs221.openSync(filePath,fs221.constants.O_RDONLY|(fs221.constants.O_NOFOLLOW??0));try{let openedStat=fs221.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:Error("TASK_GATE_EVIDENCE_UNREADABLE: evidence changed while being opened")};let bytes=fs221.readFileSync(descriptor);if(bytes.byteLength>MAX_TASK_GATE_EVIDENCE_BYTES)return{status:"oversized",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:Error(`TASK_GATE_EVIDENCE_OVERSIZED: ${bytes.byteLength} bytes exceeds ${MAX_TASK_GATE_EVIDENCE_BYTES}`)};let digest5=sha25614(bytes);try{let evidence2=parseTaskEvidence(bytes.toString("utf8"),taskId);return{status:"valid",filePath,bytes,sha256:digest5,evidence:evidence2,generation:evidence2.workflow?.generation}}catch(error93){return{status:"corrupt",filePath,bytes,sha256:digest5,error:error93}}}finally{try{fs221.closeSync(descriptor)}catch{}}}function taskGateEvidenceQuarantinePath(directory,taskId,digest5){return validateSwarmPath(directory,path362.join(TASK_GATE_EVIDENCE_QUARANTINE_DIR,`${taskId}.${digest5}.v${TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION}.json`))}function parseErrorMetadata(error93){if(!error93)return null;return{name:error93.name||"Error",message:error93.message||String(error93),code:typeof error93.code==="string"?error93.code:null}}function parseQuarantineRecord(raw){try{let parsed=JSON.parse(raw);if(parsed?.schemaVersion!==TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION||typeof parsed.taskId!=="string"||typeof parsed.recordedAt!=="string"||typeof parsed.reason!=="string"||typeof parsed.original?.path!=="string"||typeof parsed.original?.sha256!=="string"||typeof parsed.content?.bytes!=="string"||parsed.content?.encoding!=="base64")return null;return parsed}catch{return null}}function buildQuarantineRecord(taskId,read,reason,context,receiptGeneration){let agentName=context?.sessionID!=null?swarmState.activeAgent.get(context.sessionID)??swarmState.agentSessions.get(context.sessionID)?.agentName??null:null;return{schemaVersion:TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION,taskId,recordedAt:new Date().toISOString(),reason,caller:{sessionId:context?.sessionID?.trim()||null,messageId:context?.messageID?.trim()||null,agentName},original:{path:read.filePath,sha256:read.sha256,sizeBytes:read.bytes.byteLength,status:read.status,observedGeneration:read.generation??null,receiptGeneration,requirementsState:read.evidence?.requirements_state??null},parseError:parseErrorMetadata(read.error),content:{encoding:"base64",bytes:read.bytes.toString("base64")}}}async function quarantineTaskEvidenceBytes(directory,taskId,read,reason,context,receiptGeneration){let digest5=read.sha256,quarantineDir=validateSwarmPath(directory,TASK_GATE_EVIDENCE_QUARANTINE_DIR);await fs221.promises.mkdir(quarantineDir,{recursive:!0});let dirStat=await fs221.promises.lstat(quarantineDir);if(dirStat.isSymbolicLink()||!dirStat.isDirectory())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_UNREADABLE: quarantine is not a regular directory");let target=taskGateEvidenceQuarantinePath(directory,taskId,digest5),record3=buildQuarantineRecord(taskId,read,reason,context,receiptGeneration),serialized3=JSON.stringify(record3,null,2),serializedBytes=Buffer.byteLength(serialized3,"utf8");if(serializedBytes>MAX_TASK_GATE_EVIDENCE_QUARANTINE_RECORD_BYTES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: quarantine payload exceeds the bounded record size limit");let reconcileExisting=async()=>{let existingStat;try{existingStat=await fs221.promises.lstat(target)}catch(error93){if(error93.code==="ENOENT")return!1;throw error93}if(existingStat.isSymbolicLink()||!existingStat.isFile())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_MISMATCH: existing quarantine path is not a regular immutable record");let existingRaw=await fs221.promises.readFile(target,"utf8"),existingRecord=parseQuarantineRecord(existingRaw);if(existingRecord&&existingRecord.taskId===taskId&&existingRecord.original.path===read.filePath&&existingRecord.original.sha256===read.sha256&&existingRecord.content.bytes===read.bytes.toString("base64"))return!0;throw Error("TASK_GATE_EVIDENCE_QUARANTINE_MISMATCH: existing quarantine record does not match the repaired evidence source")};if(await reconcileExisting())return{digest:digest5,filePath:target};let count4=0,totalBytes=0,scanned=0,handle=await fs221.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_TASK_GATE_EVIDENCE_QUARANTINE_DIRECTORY_ENTRIES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: too many quarantine entries");if(!entry.isFile()||!/^[0-9.]+\.[a-f0-9]{64}\.v1\.json$/.test(entry.name))continue;count4+=1;let candidate2=path362.join(quarantineDir,entry.name),candidateStat=await fs221.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_UNREADABLE: invalid quarantine artifact");if(totalBytes+=candidateStat.size,count4>=MAX_TASK_GATE_EVIDENCE_QUARANTINE_FILES||totalBytes+serializedBytes>MAX_TASK_GATE_EVIDENCE_QUARANTINE_BYTES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: quarantine retention limit reached")}}finally{try{await handle.close()}catch{}}let tempPath=path362.join(quarantineDir,`.pending.${process.pid}.${randomUUID48()}.json`),fileHandle;try{fileHandle=await fs221.promises.open(tempPath,"wx"),await fileHandle.writeFile(serialized3,"utf8"),await fileHandle.sync(),await fileHandle.close(),fileHandle=void 0,invalidateCachedArtifact(tempPath),await fs221.promises.link(tempPath,target),invalidateCachedArtifact(target)}catch(error93){if(error93.code!=="EEXIST")throw error93;if(await reconcileExisting())return{digest:digest5,filePath:target};throw error93}finally{await fileHandle?.close().catch(()=>{return}),await fs221.promises.unlink(tempPath).catch(()=>{return})}return{digest:digest5,filePath:target}}function buildRepairTransitionId(taskId,source){return`repair_gate_evidence:${taskId}:${source.slice(0,32)}`}function withoutLegacyReconstructionGate(gates){return[...new Set(gates.filter((gate)=>gate!==TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL))].sort()}function hasLegacyReconstructionGate(gates){return gates.includes(TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL)}function buildKnownRepairedEvidence(taskId,receipt,generation,source){let requiredGates=withoutLegacyReconstructionGate(receipt.requiredGates);if(requiredGates.length!==receipt.requiredGates.length)throw Error("TASK_GATE_REQUIREMENTS_RECEIPT_TAINTED: legacy reconstruction markers cannot seed known requirements.");return{taskId,required_gates:requiredGates,gates:{},requirements_state:"known",test_engineer_exempt:receipt.testEngineerExempt??void 0,workflow:{schema:TASK_WORKFLOW_SCHEMA_MARKER,generation,state:"idle",retryCount:0,retryHistory:[],retryEpoch:0,lastOutcome:"repair_idle",lastTransitionId:buildRepairTransitionId(taskId,receipt.chainHash),updatedAt:new Date().toISOString()},repair_provenance:{source_sha256:source.sha256,source_generation:source.generation,requirements_receipt_hash:receipt.chainHash}}}function buildUnknownRepairedEvidence(taskId,requiredGates,seedGeneration,source,receiptHash){return{taskId,required_gates:withoutLegacyReconstructionGate(requiredGates),gates:{},requirements_state:"unknown",workflow:{schema:TASK_WORKFLOW_SCHEMA_MARKER,generation:seedGeneration,state:"idle",retryCount:0,retryHistory:[],retryEpoch:0,lastOutcome:"repair_idle",lastTransitionId:buildRepairTransitionId(taskId,"unknown"),updatedAt:new Date().toISOString()},repair_provenance:{source_sha256:source.sha256,source_generation:source.generation,requirements_receipt_hash:receiptHash}}}function canonicalizeTaskEvidence(taskId,evidence2){let validated=parseTaskEvidence(JSON.stringify({...evidence2,taskId}),taskId);return JSON.stringify(validated,null,2)}function isRepairWorkflowReset(taskId,workflow){return workflow!=null&&workflow.state==="idle"&&workflow.retryCount===0&&workflow.retryEpoch===0&&workflow.retryHistory.length===0&&workflow.lastOutcome==="repair_idle"&&typeof workflow.lastTransitionId==="string"&&workflow.lastTransitionId.startsWith(`repair_gate_evidence:${taskId}:`)}function isReceiptlessLegacySentinelReset(taskId,evidence2){return evidence2!=null&&isRepairWorkflowReset(taskId,evidence2.workflow)&&evidence2.requirements_state==="unknown"&&evidence2.required_gates.length===1&&evidence2.required_gates[0]===TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL&&Object.keys(evidence2.gates).length===0&&evidence2.repair_provenance!=null&&typeof evidence2.repair_provenance.source_sha256==="string"&&(evidence2.repair_provenance.source_generation===null||evidence2.repair_provenance.source_generation<evidence2.workflow.generation)&&evidence2.repair_provenance.requirements_receipt_hash===null}function isAlreadyRepairedEvidence(taskId,evidence2,receipt){if(!evidence2||!isRepairWorkflowReset(taskId,evidence2.workflow))return!1;if(Object.keys(evidence2.gates).length!==0)return!1;if(hasLegacyReconstructionGate(evidence2.required_gates))return!1;let receiptIsTainted=receipt!=null&&hasLegacyReconstructionGate(receipt.requiredGates);if(receipt&&!receiptIsTainted)return evidence2.requirements_state==="known"&&JSON.stringify(evidence2.required_gates)===JSON.stringify(receipt.requiredGates)&&evidence2.workflow.generation>receipt.generation&&(evidence2.test_engineer_exempt??null)===(receipt.testEngineerExempt??null)&&evidence2.repair_provenance?.requirements_receipt_hash===receipt.chainHash;if(!receipt||!receiptIsTainted)return!1;return evidence2.requirements_state==="unknown"&&evidence2.workflow.generation>=1&&evidence2.repair_provenance!=null&&evidence2.repair_provenance.requirements_receipt_hash===receipt.chainHash&&withoutLegacyReconstructionGate(receipt.requiredGates).every((gate)=>evidence2.required_gates.includes(gate))}function repairedEvidenceMatchesCas(evidence2,args2){let provenance=evidence2.repair_provenance;if(!provenance)return args2.expected_sha256==null&&args2.expected_generation==null;return(args2.expected_sha256==null||provenance.source_sha256===args2.expected_sha256)&&(args2.expected_generation==null||provenance.source_generation===args2.expected_generation)}function buildRepairNextActions(taskId,evidence2){if(evidence2.requirements_state==="known")return[`Delegate coder on task ${taskId} to produce a fresh accepted_mutation for the repaired evidence generation ${evidence2.workflow?.generation}.`,`Rerun Stage A for task ${taskId} until pre_check passes for the new generation.`,`Rerun Stage B gates [${evidence2.required_gates.join(", ")}] for task ${taskId} before attempting completion again.`];return[`Delegate coder on task ${taskId} to produce a fresh accepted mutation and regenerate authoritative required gates for a new exact-task generation.`,`Rerun Stage A for task ${taskId} after the new mutation is recorded.`,`Rerun the exact Stage B gates for task ${taskId} only after authoritative required gates are re-recorded; the idle recovery generation cannot complete directly.`]}function invalidateTaskEvidenceSessionFallbacks(taskId){for(let session of swarmState.agentSessions.values()){if(session.currentTaskId===taskId)session.currentTaskId=null;if(session.lastCoderDelegationTaskId===taskId)session.lastCoderDelegationTaskId=null;if(session.taskWorkflowStates?.delete(taskId),session.taskWorkflowCache?.delete(taskId),session.stageBCompletion?.delete(taskId),session.taskCouncilApproved?.delete(taskId),session.taskCouncilWorkflowGeneration?.delete(taskId),session.gateLog?.delete(taskId),session.partialGateWarningsIssuedForTask?.delete(taskId),session.completionGateWarnedForTask?.delete(taskId),session.lastGateFailure?.taskId===taskId)session.lastGateFailure=null}}async function repairTaskGateEvidence(args2,directory,context){assertStrictTaskId(args2.task_id);let normalizedReason=normalizeRepairReason(args2.reason),canonicalDirectory=canonicalizeRepairRoot(directory);if(!(await loadPlan(canonicalDirectory))?.phases.flatMap((phase)=>phase.tasks).find((candidate2)=>candidate2.id===args2.task_id))return{success:!1,message:`TASK_GATE_EVIDENCE_TASK_MISSING: ${args2.task_id} is not present in the loaded plan`,errors:[`Task ${args2.task_id} is not present in .swarm/plan.json.`]};return withTaskEvidenceLock(canonicalDirectory,args2.task_id,"repair_gate_evidence",async()=>{let read=readTaskEvidenceForRepair(canonicalDirectory,args2.task_id),latestReceipt=(await readTaskGateRequirementsReceipts(canonicalDirectory,args2.task_id)).at(-1),evidenceHasLegacyMarker=read.status==="valid"&&read.evidence!=null&&hasLegacyReconstructionGate(read.evidence.required_gates),receiptHasLegacyMarker=latestReceipt!=null&&hasLegacyReconstructionGate(latestReceipt.requiredGates);if(read.status==="valid"&&isAlreadyRepairedEvidence(args2.task_id,read.evidence,latestReceipt)){if(!repairedEvidenceMatchesCas(read.evidence,args2))return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:["TASK_GATE_EVIDENCE_CAS_MISMATCH: the existing repaired generation was created from a different source identity."]};let nextActions2=buildRepairNextActions(args2.task_id,read.evidence);return{success:!0,repaired:!1,task_id:args2.task_id,required_gates:[...read.evidence.required_gates],requirements_state:read.evidence.requirements_state,repaired_generation:read.evidence.workflow?.generation,next_actions:nextActions2,message:`Task gate evidence for ${args2.task_id} is already in repaired fail-closed state.`}}if(read.status==="valid"&&read.evidence?.workflow?.schema===TASK_WORKFLOW_SCHEMA_MARKER&&!evidenceHasLegacyMarker&&latestReceipt!=null&&!receiptHasLegacyMarker)return{success:!1,message:"TASK_GATE_EVIDENCE_REPAIR_NOT_REQUIRED",errors:[`TASK_GATE_EVIDENCE_REPAIR_NOT_REQUIRED: ${args2.task_id} has valid authoritative evidence. Use the normal workflow repair path; this tool only rebuilds corrupt or legacy evidence.`]};if(read.status==="valid"&&read.evidence?.requirements_state==="known"&&!evidenceHasLegacyMarker&&receiptHasLegacyMarker)return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_STALE",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_STALE: ${args2.task_id} has clean accepted-mutation evidence but its latest requirements receipt is legacy-tainted. Repair was refused without modifying evidence; replay the prepared coder settlement so it can publish the exact hash-linked receipt.`]};if(typeof args2.expected_sha256==="string"&&read.status!=="missing"&&read.sha256!==args2.expected_sha256)return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:[`TASK_GATE_EVIDENCE_CAS_MISMATCH: expected sha256 ${args2.expected_sha256}, found ${read.sha256}.`]};if(typeof args2.expected_generation==="number"){let observedGeneration=read.status==="valid"?read.generation:latestReceipt?.generation;if(observedGeneration!==args2.expected_generation)return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:[`TASK_GATE_EVIDENCE_CAS_MISMATCH: expected generation ${args2.expected_generation}, found ${observedGeneration??"unknown"}.`]}}if(read.status==="unreadable"||read.status==="oversized")return{success:!1,message:read.error?.message??"TASK_GATE_EVIDENCE_UNREADABLE: repair requires operator intervention before evidence can be rewritten.",errors:[read.error?.message??`TASK_GATE_EVIDENCE_UNREADABLE: ${args2.task_id} could not be read safely for repair.`]};if(evidenceHasLegacyMarker&&latestReceipt==null&&!isReceiptlessLegacySentinelReset(args2.task_id,read.evidence))return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_MISSING",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_MISSING: ${args2.task_id} is marker-bearing but does not match the exact receipt-less state emitted by the historical repair flow. Repair was refused without modifying evidence or session state.`]};let nextGeneration2=Math.max(read.status==="valid"?read.generation??-1:-1,latestReceipt?.generation??-1)+1,nextEvidence;if(evidenceHasLegacyMarker||receiptHasLegacyMarker){let preservedGates=withoutLegacyReconstructionGate([...read.status==="valid"?read.evidence?.required_gates??[]:[],...latestReceipt?.requiredGates??[]]);nextEvidence=buildUnknownRepairedEvidence(args2.task_id,preservedGates,Math.max(nextGeneration2,1),{sha256:read.status==="missing"?null:read.sha256,generation:read.status==="valid"?read.generation??null:latestReceipt?.generation??null},latestReceipt?.chainHash??null)}else if(latestReceipt)nextEvidence=buildKnownRepairedEvidence(args2.task_id,latestReceipt,nextGeneration2,{sha256:read.status==="missing"?null:read.sha256,generation:read.status==="valid"?read.generation??null:latestReceipt.generation??null});else if(read.status==="missing")return{success:!1,message:"TASK_GATE_EVIDENCE_ABSENT",errors:[`TASK_GATE_EVIDENCE_ABSENT: ${args2.task_id} has no evidence file and no authoritative requirements receipt to rebuild from.`]};else return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_MISSING",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_MISSING: ${args2.task_id} has no authoritative requirements receipt. Receipt-less repair was refused without modifying the original evidence because its required gates cannot be reconstructed safely.`]};let serialized3=canonicalizeTaskEvidence(args2.task_id,nextEvidence),quarantine;if(isQuarantinableTaskEvidenceRead(read))quarantine=await quarantineTaskEvidenceBytes(canonicalDirectory,args2.task_id,read,normalizedReason,context,latestReceipt?.generation??null);assertTaskEvidenceWriteAllowed(canonicalDirectory,args2.task_id),await atomicWriteFile(taskEvidenceFilePath(canonicalDirectory,args2.task_id),serialized3),invalidateTaskEvidenceSessionFallbacks(args2.task_id);let nextActions=buildRepairNextActions(args2.task_id,nextEvidence);return{success:!0,repaired:!0,task_id:args2.task_id,required_gates:[...nextEvidence.required_gates],requirements_state:nextEvidence.requirements_state,quarantine_digest:quarantine?.digest,quarantine_path:quarantine?.filePath,repaired_generation:nextEvidence.workflow?.generation,next_actions:nextActions,message:`Repaired task gate evidence for ${args2.task_id} into a fresh fail-closed generation ${nextEvidence.workflow?.generation}. Next actions: ${nextActions.join(" ")}`}})}init_create_tool();init_resolve_working_directory();async function executeRepairGateEvidence(args2,directory,_ctx){try{if(!_ctx||stripKnownSwarmPrefix(_ctx.agent??"").toLowerCase()!=="architect")return{success:!1,message:"Only the architect may repair task gate evidence.",errors:["TASK_GATE_EVIDENCE_ARCHITECT_ONLY"]};let resolved=resolveWorkingDirectory(args2.working_directory,directory);if(!resolved.success)return{success:!1,message:resolved.message,errors:[resolved.message]};return await repairTaskGateEvidence(args2,resolved.directory,{sessionID:_ctx?.sessionID,messageID:_ctx?.messageID})}catch(error93){return{success:!1,message:"repair_gate_evidence failed",errors:[error93 instanceof Error?error93.message:String(error93)]}}}var repair_gate_evidence=createSwarmTool({description:"Architect-only evidence repair for exact-task gate files. Rebuilds from a durable requirements receipt, recovers receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuses every other receipt-less reconstruction.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format"),reason:exports_external.string().min(1).max(2000),expected_sha256:exports_external.string().regex(/^[a-f0-9]{64}$/).optional(),expected_generation:exports_external.number().int().min(0).optional(),working_directory:exports_external.string().optional()},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRepairGateEvidence(args2,directory,ctx),null,2)});init_zod();init_schema();init_knowledge_receipt_ledger();init_create_tool();init_resolve_working_directory();async function executeRepairKnowledgeReceiptLedger(args2,directory,_ctx){try{if(_ctx&&stripKnownSwarmPrefix(_ctx.agent??"").toLowerCase()!=="architect")return{success:!1,message:"Only the architect may repair the knowledge receipt ledger.",errors:["RECEIPT_REPAIR_ARCHITECT_ONLY"]};if(_ctx?.sessionID&&args2.session_id!==_ctx.sessionID)return{success:!1,message:"repair_knowledge_receipt_ledger session_id must match the invoking tool context.",errors:["RECEIPT_REPAIR_SESSION_MISMATCH"]};let resolved=resolveWorkingDirectory(args2.working_directory,directory);if(!resolved.success)return{success:!1,message:resolved.message,errors:[resolved.message]};if(args2.operation==="backfill_phase_id"){let backfill=await backfillMembershipPhaseIds(resolved.directory);if(!backfill.ok)return{success:!1,message:"repair_knowledge_receipt_ledger backfill_phase_id failed",errors:[backfill.detail],code:backfill.code};return{success:!0,message:`phase_id backfill complete: ${backfill.backfilled} membership(s) backfilled, ${backfill.skipped.length} skipped (unparsable label), ${backfill.journal_records} journal record(s) appended. Stored labels are never rewritten.`,backfilled:backfill.backfilled,skipped:backfill.skipped.slice(0,20),skipped_total:backfill.skipped.length,journal_records:backfill.journal_records}}let result=await repairKnowledgeReceiptLedger(resolved.directory,args2);if(!result.ok)return{success:!1,message:"repair_knowledge_receipt_ledger failed",errors:[result.detail],code:result.code};let reEvaluationArgs=JSON.stringify({repair_id:result.repair_id,phase:args2.phase,...args2.task_id?{task_id:args2.task_id}:{},scope_complete:!0});return{success:!0,message:result.status==="validated_projection"?"knowledge receipt projection validated":result.status==="pending_re_evaluation"?`knowledge receipt ledger still pending re-evaluation; as architect, run knowledge_recall with a comprehensive query and repair_re_evaluation ${reEvaluationArgs}`:`knowledge receipt ledger repaired and blocked pending re-evaluation; as architect, run knowledge_recall with a comprehensive query and repair_re_evaluation ${reEvaluationArgs}`,...result}}catch(error93){return{success:!1,message:"repair_knowledge_receipt_ledger failed",errors:[error93 instanceof Error?error93.message:String(error93)]}}}var repair_knowledge_receipt_ledger=createSwarmTool({description:"Architect-only repair and validation for the authoritative knowledge receipt ledger. Default operation repairs: rebuilds the derived projection when authority is readable, or quarantines a bounded corrupt authority, salvages only the validated prefix, and blocks the exact phase/session until a fresh re-evaluation is committed. operation backfill_phase_id durably stamps the stable numeric phase_id on live memberships that lack one across the WHOLE ledger (phase/session_id are not used to scope the backfill; labels never rewritten).",args:{phase:exports_external.string().min(1),session_id:exports_external.string().min(1),task_id:exports_external.string().min(1).optional(),reason:exports_external.string().min(1).max(2000),operation:exports_external.enum(["repair","backfill_phase_id"]).optional(),grace_days:exports_external.number().int().min(0).optional(),working_directory:exports_external.string().optional()},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRepairKnowledgeReceiptLedger(args2,directory,ctx),null,2)});init_zod();init_loader();init_schema();init_profiles();init_telemetry();init_path_security();init_create_tool();import*as path364 from"node:path";init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs222 from"node:fs";import{createRequire as createRequire7}from"node:module";import*as path363 from"node:path";var require2=createRequire7(import.meta.url),DEFAULT_MAX_RESULTS4=100,DEFAULT_MAX_LINES=200,REGEX_TIMEOUT_MS=5000,MAX_FILE_SIZE_BYTES8=1048576,HARD_CAP_RESULTS4=1e4,HARD_CAP_LINES=1e4,MAX_QUERY_LENGTH=20000,MAX_INCLUDE_PATTERNS=100,MAX_RG_STDOUT_BYTES=8388608,MAX_RG_STDERR_BYTES=65536,FALLBACK_MAX_FILES=20000,FALLBACK_MAX_DIRS=5000,FALLBACK_MAX_DEPTH=40,FALLBACK_MAX_TOTAL_BYTES=67108864,DEFAULT_SKIP_DIRS=new Set([".git",".swarm","node_modules","dist","build","out","coverage",".next",".turbo",".cache"]);function globMatch(pattern,filePath){let normalizedPattern=pattern.replace(/\\/g,"/"),normalizedPath=filePath.replace(/\\/g,"/"),regexPattern=normalizedPattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"{{DOUBLESTAR}}").replace(/\*/g,"[^/]*").replace(/\?/g,".").replace(/\{\{DOUBLESTAR\}\}/g,".*");try{return new RegExp(`^${regexPattern}$`).test(normalizedPath)}catch{return!1}}function matchesGlobs(filePath,globs){if(globs.length===0)return!0;return globs.some((glob)=>globMatch(glob,filePath))}var WINDOWS_RESERVED_NAMES5=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks4(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES5.test(part))return!0;return!1}function resolveWithinWorkspace(filePath,workspace){try{let resolvedPath=path363.resolve(workspace,filePath),realWorkspace=fs222.realpathSync(workspace),realResolvedPath=fs222.realpathSync(resolvedPath),relativePath2=path363.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path363.isAbsolute(relativePath2))return null;return relativePath2}catch{return null}}function isPathInWorkspace3(filePath,workspace){return resolveWithinWorkspace(filePath,workspace)!==null}function validatePathForRead2(filePath,workspace){return isPathInWorkspace3(filePath,workspace)}function splitGlobPatterns2(value){return value?value.split(",").map((p)=>p.trim()).filter(Boolean):[]}var GLOB_METACHARACTERS=/[*?[\]{}]/;function isExactPath(pattern){return!GLOB_METACHARACTERS.test(pattern)}function targetsDotDirectory(pattern){let firstSegment=pattern.split(/[\\/]/)[0];return!!firstSegment&&firstSegment.startsWith(".")&&firstSegment!=="."&&firstSegment!==".."}function hasGitSegment(resolvedRelativePath){return resolvedRelativePath.split(/[\\/]/).some((segment)=>segment.toLowerCase()===".git")}function toWorkspaceRelativePath2(filePath,workspace){try{let resolved=path363.resolve(workspace,filePath),realWorkspace=fs222.realpathSync(workspace),realResolved=fs222.realpathSync(resolved),relative96=path363.relative(realWorkspace,realResolved);if(!relative96||relative96.startsWith("..")||path363.isAbsolute(relative96))return null;return relative96.split(path363.sep).join("/")}catch{return null}}function truncateLine(line,maxLines){let trimmed=line.trimEnd();if(trimmed.length>maxLines)return`${trimmed.substring(0,maxLines)}...`;return trimmed}function resolvePackagedRipgrep(){try{let mod=require2("@vscode/ripgrep");return typeof mod.rgPath==="string"&&mod.rgPath?mod.rgPath:null}catch{return null}}function resolveRipgrepBinary(){return _internals309.resolvePackagedRipgrep()??_internals309.resolveExecutableFromPath(["rg"])}async function ripgrepSearch(opts){let rgPath=_internals309.resolveRipgrepBinary();if(!rgPath)return{error:!0,type:"rg-not-found",message:"ripgrep (rg) not found; using fallback search was not possible"};let args2=["--json","--no-config","-n"],includes=splitGlobPatterns2(opts.include),promotablePaths=[],globIncludes=[];for(let pattern of includes){let resolvedRelative=resolveWithinWorkspace(pattern,opts.workspace);if(isExactPath(pattern)&&targetsDotDirectory(pattern)&&pattern.split(/[\\/]/)[0]?.toLowerCase()!==".git"&&resolvedRelative!==null&&!hasGitSegment(resolvedRelative))promotablePaths.push(pattern);else globIncludes.push(pattern)}let pathOperands;if(promotablePaths.length>0&&globIncludes.length===0)pathOperands=promotablePaths;else{for(let pattern of[...globIncludes,...promotablePaths])args2.push("--glob",pattern);if(includes.some((p)=>targetsDotDirectory(p)&&p.split(/[\\/]/)[0]?.toLowerCase()!==".git"))args2.push("--hidden","--no-ignore"),args2.push("--glob","!.git");pathOperands=["."]}for(let pattern of splitGlobPatterns2(opts.exclude))args2.push("--glob",`!${pattern}`);if(opts.mode!=="regex")args2.push("--fixed-strings");args2.push("--",opts.query,...pathOperands);let run=await _internals309.runExternalTool({executable:rgPath,args:args2,cwd:opts.workspace,timeoutMs:REGEX_TIMEOUT_MS,maxStdoutBytes:MAX_RG_STDOUT_BYTES,maxStderrBytes:MAX_RG_STDERR_BYTES});try{if(run.status==="timeout")return{error:!0,type:"regex-timeout",message:`Search timed out after ${REGEX_TIMEOUT_MS}ms`};if(run.status==="spawn-error")return{error:!0,type:"unknown",message:run.message??"ripgrep failed to start"};if(run.exitCode!==0&&run.stderr){if(run.stderr.includes("Invalid regex")||run.stderr.includes("regex parse error")||run.stderr.includes("SyntaxError"))return{error:!0,type:"invalid-query",message:`Invalid query: ${run.stderr.split(`
|
|
7784
7784
|
`)[0]}`};if(run.exitCode===2)return{error:!0,type:"unknown",message:`ripgrep error: ${run.stderr.split(`
|
|
7785
7785
|
`)[0]}`}}let matches=[],total=0;for(let line of run.stdout.split(`
|
|
7786
7786
|
`)){if(!line.trim())continue;try{let entry=JSON.parse(line);if(entry.type==="match"){let rawPath=entry.data?.path?.text??entry.data?.path,relativePath2=typeof rawPath==="string"?toWorkspaceRelativePath2(rawPath,opts.workspace):null;if(!relativePath2)continue;if(total++,matches.length<opts.maxResults){let match={file:relativePath2,lineNumber:entry.data.line_number,lineText:truncateLine(entry.data.lines.text,opts.maxLines)};matches.push(match)}}}catch{}}return{matches,truncated:total>opts.maxResults||run.stdoutTruncated||run.stderrTruncated,total,query:opts.query,mode:opts.mode,maxResults:opts.maxResults,engine:"ripgrep",outputTruncated:run.stdoutTruncated||run.stderrTruncated}}catch(err){return{error:!0,type:"unknown",message:err instanceof Error?err.message:String(err)}}}function escapeRegex4(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function collectFiles(dir,workspace,includeGlobs,excludeGlobs,state2,depth=0){if(depth>FALLBACK_MAX_DEPTH||state2.files.length>=FALLBACK_MAX_FILES||state2.dirCount>=FALLBACK_MAX_DIRS)return state2.truncated=!0,state2.files;try{let realDir=fs222.realpathSync(dir);if(state2.seenRealPaths.has(realDir))return state2.files;state2.seenRealPaths.add(realDir),state2.dirCount++}catch{return state2.files}if(!validatePathForRead2(dir,workspace))return state2.files;try{let entries2=fs222.readdirSync(dir,{withFileTypes:!0});for(let entry of entries2){if(state2.files.length>=FALLBACK_MAX_FILES||state2.dirCount>=FALLBACK_MAX_DIRS){state2.truncated=!0;break}let fullPath=path363.join(dir,entry.name),relativePath2=path363.relative(workspace,fullPath);if(!validatePathForRead2(fullPath,workspace))continue;if(entry.isDirectory()){if(entry.name.toLowerCase()===".git"||DEFAULT_SKIP_DIRS.has(entry.name)&&!includeGlobs.some((g)=>g.split(/[\\/]/)[0]===entry.name))continue;collectFiles(fullPath,workspace,includeGlobs,excludeGlobs,state2,depth+1)}else if(entry.isFile()){if(includeGlobs.length>0&&!matchesGlobs(relativePath2,includeGlobs))continue;if(excludeGlobs.length>0&&matchesGlobs(relativePath2,excludeGlobs))continue;let normalized=toWorkspaceRelativePath2(fullPath,workspace);if(!normalized)continue;state2.files.push(normalized)}}}catch{}return state2.files}async function searchWorkspaceLiteral(opts){let includeGlobs=opts.include?opts.include.split(",").map((p)=>p.trim()).filter(Boolean):[],excludeGlobs=opts.exclude?opts.exclude.split(",").map((p)=>p.trim()).filter(Boolean):[],collectState={files:[],seenRealPaths:new Set,dirCount:0,truncated:!1},files=collectFiles(opts.workspace,opts.workspace,includeGlobs,excludeGlobs,collectState),regex;try{if(opts.mode==="regex")regex=new RegExp(opts.query);else regex=new RegExp(escapeRegex4(opts.query))}catch(err){return{error:!0,type:"invalid-query",message:err instanceof Error?err.message:"Invalid regex pattern"}}let matches=[],total=0,totalBytesRead=0,truncated=collectState.truncated;for(let file3 of files){let fullPath=path363.join(opts.workspace,file3);if(!validatePathForRead2(fullPath,opts.workspace))continue;let stats2;try{if(stats2=fs222.statSync(fullPath),stats2.size>MAX_FILE_SIZE_BYTES8)continue;if(totalBytesRead+stats2.size>FALLBACK_MAX_TOTAL_BYTES){truncated=!0;break}totalBytesRead+=stats2.size}catch{continue}let content;try{let bytes=fs222.readFileSync(fullPath);if(bytes.includes(0))continue;content=bytes.toString("utf-8")}catch{continue}let lines=content.split(`
|