opencode-swarm 7.103.2 → 7.104.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/cli/{config-doctor-4rxjsg22.js → config-doctor-5m8z8jeg.js} +2 -2
  2. package/dist/cli/{guardrail-explain-4pnnjmyb.js → guardrail-explain-2zat1bxh.js} +5 -5
  3. package/dist/cli/{guardrail-log-vg0atkrx.js → guardrail-log-zhshjbpk.js} +3 -3
  4. package/dist/cli/{index-9zb70qfe.js → index-0derejrq.js} +1 -1
  5. package/dist/cli/{index-h0h4qjmc.js → index-5tywmqeh.js} +1 -1
  6. package/dist/cli/{index-4fnw0ebs.js → index-e7nhwa9k.js} +8 -6
  7. package/dist/cli/{index-5xy6kv7p.js → index-fk8ta8zw.js} +2 -2
  8. package/dist/cli/{index-m9keg83x.js → index-kcbcy6wq.js} +1 -1
  9. package/dist/cli/{index-3ahcme4e.js → index-n3ys2eny.js} +655 -55
  10. package/dist/cli/{index-ga7et2xw.js → index-t1vfvtg9.js} +21 -0
  11. package/dist/cli/index.js +4 -4
  12. package/dist/cli/{schema-az0hgfv0.js → schema-yxkdx5g5.js} +1 -1
  13. package/dist/commands/index.d.ts +1 -1
  14. package/dist/commands/memory.d.ts +1 -0
  15. package/dist/commands/registry.d.ts +8 -0
  16. package/dist/config/schema.d.ts +22 -0
  17. package/dist/council/types.d.ts +9 -0
  18. package/dist/graph/import-extractor.d.ts +1 -1
  19. package/dist/hooks/knowledge-application.d.ts +2 -2
  20. package/dist/hooks/knowledge-events.d.ts +3 -0
  21. package/dist/index.js +79 -44
  22. package/dist/lang/symbol-visibility.d.ts +2 -0
  23. package/dist/memory/config.d.ts +20 -0
  24. package/dist/memory/gateway.d.ts +1 -0
  25. package/dist/memory/index.d.ts +2 -1
  26. package/dist/memory/maintenance.d.ts +4 -1
  27. package/dist/memory/provider-pool.d.ts +23 -0
  28. package/dist/memory/provider.d.ts +53 -0
  29. package/dist/memory/reward.d.ts +39 -0
  30. package/dist/memory/schema.d.ts +2 -0
  31. package/dist/memory/scoring.d.ts +2 -0
  32. package/dist/memory/sqlite-provider.d.ts +53 -1
  33. package/dist/memory/types.d.ts +5 -0
  34. package/dist/state.d.ts +2 -2
  35. package/dist/tools/convene-council.d.ts +2 -0
  36. package/dist/tools/repo-graph/builder.d.ts +4 -2
  37. package/dist/tools/submit-phase-council-verdicts.d.ts +1 -0
  38. package/dist/tools/symbols.d.ts +2 -0
  39. 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.103.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"},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",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm-pr-feedback",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","drift:check":"bun run scripts/drift-check.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs"},dependencies:{"@opencode-ai/plugin":"^1.1.53","@opencode-ai/sdk":"^1.1.53","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_oversight","coder","test_engineer"]},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"]},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"]},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"]},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"]},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"]},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"]},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer"]},quality_budget:{description:"code quality budget check",agents:["architect"]},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"]},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"]},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","test_engineer"]},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"]},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","explorer","architect"]},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"]},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"]},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["architect","sme","docs","docs_design","designer","spec_writer","reviewer","explorer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"]},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"]},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"]},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic","critic_oversight","explorer","coder"]},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","coder"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES),TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.104.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm-pr-feedback",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","drift:check":"bun run scripts/drift-check.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs"},dependencies:{"@opencode-ai/plugin":"^1.1.53","@opencode-ai/sdk":"^1.1.53","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_oversight","coder","test_engineer"]},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"]},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"]},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"]},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"]},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"]},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"]},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer"]},quality_budget:{description:"code quality budget check",agents:["architect"]},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"]},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"]},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","test_engineer"]},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"]},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","explorer","architect"]},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"]},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"]},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["architect","sme","docs","docs_design","designer","spec_writer","reviewer","explorer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"]},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"]},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"]},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic","critic_oversight","explorer","coder"]},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","coder"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES),TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -155,7 +155,7 @@ Audit (no architect needed): \`/swarm epic status | last | decide | calibration\
155
155
 
156
156
  `)}doc.write("payload.value = newResult;"),doc.write("return payload;");let fn2=doc.compile();return(payload,ctx)=>fn2(shape,payload,ctx)},fastpass,isObject2=isObject,jit=!globalConfig.jitless,fastEnabled=jit&&allowsEval.value,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject2(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;if(jit&&fastEnabled&&ctx?.async===!1&&ctx.jitless!==!0){if(!fastpass)fastpass=generateFastpass(def.shape);if(payload=fastpass(payload,ctx),!catchall)return payload;return handleCatchall([],input,payload,ctx,value,inst)}return superParse(payload,ctx)}});$ZodUnion=$constructor("$ZodUnion",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),defineLazy(inst._zod,"optout",()=>def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),defineLazy(inst._zod,"values",()=>{if(def.options.every((o)=>o._zod.values))return new Set(def.options.flatMap((option)=>Array.from(option._zod.values)));return}),defineLazy(inst._zod,"pattern",()=>{if(def.options.every((o)=>o._zod.pattern)){let patterns=def.options.map((o)=>o._zod.pattern);return new RegExp(`^(${patterns.map((p)=>cleanRegex(p.source)).join("|")})$`)}return});let single=def.options.length===1,first=def.options[0]._zod.run;inst._zod.parse=(payload,ctx)=>{if(single)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else{if(result.issues.length===0)return result;results.push(result)}}if(!async)return handleUnionResults(results,payload,inst,ctx);return Promise.all(results).then((results2)=>{return handleUnionResults(results2,payload,inst,ctx)})}});$ZodXor=$constructor("$ZodXor",(inst,def)=>{$ZodUnion.init(inst,def),def.inclusive=!1;let single=def.options.length===1,first=def.options[0]._zod.run;inst._zod.parse=(payload,ctx)=>{if(single)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else results.push(result)}if(!async)return handleExclusiveUnionResults(results,payload,inst,ctx);return Promise.all(results).then((results2)=>{return handleExclusiveUnionResults(results2,payload,inst,ctx)})}}),$ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(inst,def)=>{def.inclusive=!1,$ZodUnion.init(inst,def);let _super=inst._zod.parse;defineLazy(inst._zod,"propValues",()=>{let propValues={};for(let option of def.options){let pv=option._zod.propValues;if(!pv||Object.keys(pv).length===0)throw Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(let[k,v]of Object.entries(pv)){if(!propValues[k])propValues[k]=new Set;for(let val of v)propValues[k].add(val)}}return propValues});let disc=cached(()=>{let opts=def.options,map=new Map;for(let o of opts){let values=o._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);for(let v of values){if(map.has(v))throw Error(`Duplicate discriminator value "${String(v)}"`);map.set(v,o)}}return map});inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isObject(input))return payload.issues.push({code:"invalid_type",expected:"object",input,inst}),payload;let opt=disc.value.get(input?.[def.discriminator]);if(opt)return opt._zod.run(payload,ctx);if(def.unionFallback)return _super(payload,ctx);return payload.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:def.discriminator,input,path:[def.discriminator],inst}),payload}}),$ZodIntersection=$constructor("$ZodIntersection",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value,left=def.left._zod.run({value:input,issues:[]},ctx),right=def.right._zod.run({value:input,issues:[]},ctx);if(left instanceof Promise||right instanceof Promise)return Promise.all([left,right]).then(([left2,right2])=>{return handleIntersectionResults(payload,left2,right2)});return handleIntersectionResults(payload,left,right)}});$ZodTuple=$constructor("$ZodTuple",(inst,def)=>{$ZodType.init(inst,def);let items=def.items;inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({input,inst,expected:"tuple",code:"invalid_type"}),payload;payload.value=[];let proms=[],reversedIndex=[...items].reverse().findIndex((item)=>item._zod.optin!=="optional"),optStart=reversedIndex===-1?0:items.length-reversedIndex;if(!def.rest){let tooBig=input.length>items.length,tooSmall=input.length<optStart-1;if(tooBig||tooSmall)return payload.issues.push({...tooBig?{code:"too_big",maximum:items.length,inclusive:!0}:{code:"too_small",minimum:items.length},input,inst,origin:"array"}),payload}let i=-1;for(let item of items){if(i++,i>=input.length){if(i>=optStart)continue}let result=item._zod.run({value:input[i],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleTupleResult(result2,payload,i)));else handleTupleResult(result,payload,i)}if(def.rest){let rest=input.slice(items.length);for(let el of rest){i++;let result=def.rest._zod.run({value:el,issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleTupleResult(result2,payload,i)));else handleTupleResult(result,payload,i)}}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodRecord=$constructor("$ZodRecord",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isPlainObject(input))return payload.issues.push({expected:"record",code:"invalid_type",input,inst}),payload;let proms=[],values=def.keyType._zod.values;if(values){payload.value={};let recordKeys=new Set;for(let key of values)if(typeof key==="string"||typeof key==="number"||typeof key==="symbol"){recordKeys.add(typeof key==="number"?key.toString():key);let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>{if(result2.issues.length)payload.issues.push(...prefixIssues(key,result2.issues));payload.value[key]=result2.value}));else{if(result.issues.length)payload.issues.push(...prefixIssues(key,result.issues));payload.value[key]=result.value}}let unrecognized;for(let key in input)if(!recordKeys.has(key))unrecognized=unrecognized??[],unrecognized.push(key);if(unrecognized&&unrecognized.length>0)payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized})}else{payload.value={};for(let key of Reflect.ownKeys(input)){if(key==="__proto__")continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof key==="string"&&number.test(key)&&keyResult.issues.length){let retryResult=def.keyType._zod.run({value:Number(key),issues:[]},ctx);if(retryResult instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(retryResult.issues.length===0)keyResult=retryResult}if(keyResult.issues.length){if(def.mode==="loose")payload.value[key]=input[key];else payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map((iss)=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>{if(result2.issues.length)payload.issues.push(...prefixIssues(key,result2.issues));payload.value[keyResult.value]=result2.value}));else{if(result.issues.length)payload.issues.push(...prefixIssues(key,result.issues));payload.value[keyResult.value]=result.value}}}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}}),$ZodMap=$constructor("$ZodMap",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!(input instanceof Map))return payload.issues.push({expected:"map",code:"invalid_type",input,inst}),payload;let proms=[];payload.value=new Map;for(let[key,value]of input){let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx),valueResult=def.valueType._zod.run({value,issues:[]},ctx);if(keyResult instanceof Promise||valueResult instanceof Promise)proms.push(Promise.all([keyResult,valueResult]).then(([keyResult2,valueResult2])=>{handleMapResult(keyResult2,valueResult2,payload,key,input,inst,ctx)}));else handleMapResult(keyResult,valueResult,payload,key,input,inst,ctx)}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodSet=$constructor("$ZodSet",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!(input instanceof Set))return payload.issues.push({input,inst,expected:"set",code:"invalid_type"}),payload;let proms=[];payload.value=new Set;for(let item of input){let result=def.valueType._zod.run({value:item,issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleSetResult(result2,payload)));else handleSetResult(result,payload)}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodEnum=$constructor("$ZodEnum",(inst,def)=>{$ZodType.init(inst,def);let values=getEnumValues(def.entries),valuesSet=new Set(values);inst._zod.values=valuesSet,inst._zod.pattern=new RegExp(`^(${values.filter((k)=>propertyKeyTypes.has(typeof k)).map((o)=>typeof o==="string"?escapeRegex(o):o.toString()).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(valuesSet.has(input))return payload;return payload.issues.push({code:"invalid_value",values,input,inst}),payload}}),$ZodLiteral=$constructor("$ZodLiteral",(inst,def)=>{if($ZodType.init(inst,def),def.values.length===0)throw Error("Cannot create literal schema with no valid values");let values=new Set(def.values);inst._zod.values=values,inst._zod.pattern=new RegExp(`^(${def.values.map((o)=>typeof o==="string"?escapeRegex(o):o?escapeRegex(o.toString()):String(o)).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(values.has(input))return payload;return payload.issues.push({code:"invalid_value",values:def.values,input,inst}),payload}}),$ZodFile=$constructor("$ZodFile",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(input instanceof File)return payload;return payload.issues.push({expected:"file",code:"invalid_type",input,inst}),payload}}),$ZodTransform=$constructor("$ZodTransform",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);let _out=def.transform(payload.value,payload);if(ctx.async)return(_out instanceof Promise?_out:Promise.resolve(_out)).then((output2)=>{return payload.value=output2,payload});if(_out instanceof Promise)throw new $ZodAsyncError;return payload.value=_out,payload}});$ZodOptional=$constructor("$ZodOptional",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",inst._zod.optout="optional",defineLazy(inst._zod,"values",()=>{return def.innerType._zod.values?new Set([...def.innerType._zod.values,void 0]):void 0}),defineLazy(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)})?$`):void 0}),inst._zod.parse=(payload,ctx)=>{if(def.innerType._zod.optin==="optional"){let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((r)=>handleOptionalResult(r,payload.value));return handleOptionalResult(result,payload.value)}if(payload.value===void 0)return payload;return def.innerType._zod.run(payload,ctx)}}),$ZodExactOptional=$constructor("$ZodExactOptional",(inst,def)=>{$ZodOptional.init(inst,def),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),defineLazy(inst._zod,"pattern",()=>def.innerType._zod.pattern),inst._zod.parse=(payload,ctx)=>{return def.innerType._zod.run(payload,ctx)}}),$ZodNullable=$constructor("$ZodNullable",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.innerType._zod.optin),defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)}|null)$`):void 0}),defineLazy(inst._zod,"values",()=>{return def.innerType._zod.values?new Set([...def.innerType._zod.values,null]):void 0}),inst._zod.parse=(payload,ctx)=>{if(payload.value===null)return payload;return def.innerType._zod.run(payload,ctx)}}),$ZodDefault=$constructor("$ZodDefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)return payload.value=def.defaultValue,payload;let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>handleDefaultResult(result2,def));return handleDefaultResult(result,def)}});$ZodPrefault=$constructor("$ZodPrefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)payload.value=def.defaultValue;return def.innerType._zod.run(payload,ctx)}}),$ZodNonOptional=$constructor("$ZodNonOptional",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>{let v=def.innerType._zod.values;return v?new Set([...v].filter((x)=>x!==void 0)):void 0}),inst._zod.parse=(payload,ctx)=>{let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>handleNonOptionalResult(result2,inst));return handleNonOptionalResult(result,inst)}});$ZodSuccess=$constructor("$ZodSuccess",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError("ZodSuccess");let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>{return payload.value=result2.issues.length===0,payload});return payload.value=result.issues.length===0,payload}}),$ZodCatch=$constructor("$ZodCatch",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.innerType._zod.optin),defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>{if(payload.value=result2.value,result2.issues.length)payload.value=def.catchValue({...payload,error:{issues:result2.issues.map((iss)=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[];return payload});if(payload.value=result.value,result.issues.length)payload.value=def.catchValue({...payload,error:{issues:result.issues.map((iss)=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[];return payload}}),$ZodNaN=$constructor("$ZodNaN",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="number"||!Number.isNaN(payload.value))return payload.issues.push({input:payload.value,inst,expected:"nan",code:"invalid_type"}),payload;return payload}}),$ZodPipe=$constructor("$ZodPipe",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>def.in._zod.values),defineLazy(inst._zod,"optin",()=>def.in._zod.optin),defineLazy(inst._zod,"optout",()=>def.out._zod.optout),defineLazy(inst._zod,"propValues",()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){let right=def.out._zod.run(payload,ctx);if(right instanceof Promise)return right.then((right2)=>handlePipeResult(right2,def.in,ctx));return handlePipeResult(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);if(left instanceof Promise)return left.then((left2)=>handlePipeResult(left2,def.out,ctx));return handlePipeResult(left,def.out,ctx)}});$ZodCodec=$constructor("$ZodCodec",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>def.in._zod.values),defineLazy(inst._zod,"optin",()=>def.in._zod.optin),defineLazy(inst._zod,"optout",()=>def.out._zod.optout),defineLazy(inst._zod,"propValues",()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if((ctx.direction||"forward")==="forward"){let left=def.in._zod.run(payload,ctx);if(left instanceof Promise)return left.then((left2)=>handleCodecAResult(left2,def,ctx));return handleCodecAResult(left,def,ctx)}else{let right=def.out._zod.run(payload,ctx);if(right instanceof Promise)return right.then((right2)=>handleCodecAResult(right2,def,ctx));return handleCodecAResult(right,def,ctx)}}});$ZodReadonly=$constructor("$ZodReadonly",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"propValues",()=>def.innerType._zod.propValues),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),defineLazy(inst._zod,"optin",()=>def.innerType?._zod?.optin),defineLazy(inst._zod,"optout",()=>def.innerType?._zod?.optout),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then(handleReadonlyResult);return handleReadonlyResult(result)}});$ZodTemplateLiteral=$constructor("$ZodTemplateLiteral",(inst,def)=>{$ZodType.init(inst,def);let regexParts=[];for(let part of def.parts)if(typeof part==="object"&&part!==null){if(!part._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);let source=part._zod.pattern instanceof RegExp?part._zod.pattern.source:part._zod.pattern;if(!source)throw Error(`Invalid template literal part: ${part._zod.traits}`);let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;regexParts.push(source.slice(start,end))}else if(part===null||primitiveTypes.has(typeof part))regexParts.push(escapeRegex(`${part}`));else throw Error(`Invalid template literal part: ${part}`);inst._zod.pattern=new RegExp(`^${regexParts.join("")}$`),inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="string")return payload.issues.push({input:payload.value,inst,expected:"string",code:"invalid_type"}),payload;if(inst._zod.pattern.lastIndex=0,!inst._zod.pattern.test(payload.value))return payload.issues.push({input:payload.value,inst,code:"invalid_format",format:def.format??"template_literal",pattern:inst._zod.pattern.source}),payload;return payload}}),$ZodFunction=$constructor("$ZodFunction",(inst,def)=>{return $ZodType.init(inst,def),inst._def=def,inst._zod.def=def,inst.implement=(func)=>{if(typeof func!=="function")throw Error("implement() must be called with a function");return function(...args2){let parsedArgs=inst._def.input?parse(inst._def.input,args2):args2,result=Reflect.apply(func,this,parsedArgs);if(inst._def.output)return parse(inst._def.output,result);return result}},inst.implementAsync=(func)=>{if(typeof func!=="function")throw Error("implementAsync() must be called with a function");return async function(...args2){let parsedArgs=inst._def.input?await parseAsync(inst._def.input,args2):args2,result=await Reflect.apply(func,this,parsedArgs);if(inst._def.output)return await parseAsync(inst._def.output,result);return result}},inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="function")return payload.issues.push({code:"invalid_type",expected:"function",input:payload.value,inst}),payload;if(inst._def.output&&inst._def.output._zod.def.type==="promise")payload.value=inst.implementAsync(payload.value);else payload.value=inst.implement(payload.value);return payload},inst.input=(...args2)=>{let F=inst.constructor;if(Array.isArray(args2[0]))return new F({type:"function",input:new $ZodTuple({type:"tuple",items:args2[0],rest:args2[1]}),output:inst._def.output});return new F({type:"function",input:args2[0],output:inst._def.output})},inst.output=(output)=>{return new inst.constructor({type:"function",input:inst._def.input,output})},inst}),$ZodPromise=$constructor("$ZodPromise",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{return Promise.resolve(payload.value).then((inner)=>def.innerType._zod.run({value:inner,issues:[]},ctx))}}),$ZodLazy=$constructor("$ZodLazy",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"innerType",()=>def.getter()),defineLazy(inst._zod,"pattern",()=>inst._zod.innerType?._zod?.pattern),defineLazy(inst._zod,"propValues",()=>inst._zod.innerType?._zod?.propValues),defineLazy(inst._zod,"optin",()=>inst._zod.innerType?._zod?.optin??void 0),defineLazy(inst._zod,"optout",()=>inst._zod.innerType?._zod?.optout??void 0),inst._zod.parse=(payload,ctx)=>{return inst._zod.innerType._zod.run(payload,ctx)}}),$ZodCustom=$constructor("$ZodCustom",(inst,def)=>{$ZodCheck.init(inst,def),$ZodType.init(inst,def),inst._zod.parse=(payload,_)=>{return payload},inst._zod.check=(payload)=>{let input=payload.value,r=def.fn(input);if(r instanceof Promise)return r.then((r2)=>handleRefineResult(r2,payload,input,inst));handleRefineResult(r,payload,input,inst);return}})});function ar_default(){return{localeError:error()}}var error=()=>{let Sizable={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${issue2.expected}، ولكن تم إدخال ${received}`;return`مدخلات غير مقبولة: يفترض إدخال ${expected}، ولكن تم إدخال ${received}`}case"invalid_value":if(issue2.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive(issue2.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return` أكبر من اللازم: يفترض أن تكون ${issue2.origin??"القيمة"} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${issue2.origin??"القيمة"} ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`أصغر من اللازم: يفترض لـ ${issue2.origin} أن يكون ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`أصغر من اللازم: يفترض لـ ${issue2.origin} أن يكون ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${issue2.prefix}"`;if(_issue.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`;if(_issue.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`;if(_issue.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${issue2.divisor}`;case"unrecognized_keys":return`معرف${issue2.keys.length>1?"ات":""} غريب${issue2.keys.length>1?"ة":""}: ${joinValues(issue2.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${issue2.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${issue2.origin}`;default:return"مدخل غير مقبول"}}};var init_ar=__esm(()=>{init_util()});function az_default(){return{localeError:error2()}}var error2=()=>{let Sizable={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Yanlış dəyər: gözlənilən instanceof ${issue2.expected}, daxil olan ${received}`;return`Yanlış dəyər: gözlənilən ${expected}, daxil olan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Yanlış dəyər: gözlənilən ${stringifyPrimitive(issue2.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Çox böyük: gözlənilən ${issue2.origin??"dəyər"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"element"}`;return`Çox böyük: gözlənilən ${issue2.origin??"dəyər"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Çox kiçik: gözlənilən ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Çox kiçik: gözlənilən ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`;if(_issue.format==="ends_with")return`Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`;if(_issue.format==="includes")return`Yanlış mətn: "${_issue.includes}" daxil olmalıdır`;if(_issue.format==="regex")return`Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Yanlış ədəd: ${issue2.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${issue2.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};var init_az=__esm(()=>{init_util()});function getBelarusianPlural(count,one,few,many){let absCount=Math.abs(count),lastDigit=absCount%10,lastTwoDigits=absCount%100;if(lastTwoDigits>=11&&lastTwoDigits<=19)return many;if(lastDigit===1)return one;if(lastDigit>=2&&lastDigit<=4)return few;return many}function be_default(){return{localeError:error3()}}var error3=()=>{let Sizable={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},TypeDictionary={nan:"NaN",number:"лік",array:"масіў"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Няправільны ўвод: чакаўся instanceof ${issue2.expected}, атрымана ${received}`;return`Няправільны ўвод: чакаўся ${expected}, атрымана ${received}`}case"invalid_value":if(issue2.values.length===1)return`Няправільны ўвод: чакалася ${stringifyPrimitive(issue2.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing){let maxValue=Number(issue2.maximum),unit=getBelarusianPlural(maxValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Занадта вялікі: чакалася, што ${issue2.origin??"значэнне"} павінна ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`}return`Занадта вялікі: чакалася, што ${issue2.origin??"значэнне"} павінна быць ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing){let minValue=Number(issue2.minimum),unit=getBelarusianPlural(minValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Занадта малы: чакалася, што ${issue2.origin} павінна ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`}return`Занадта малы: чакалася, што ${issue2.origin} павінна быць ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`;if(_issue.format==="includes")return`Няправільны радок: павінен змяшчаць "${_issue.includes}"`;if(_issue.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`;return`Няправільны ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${issue2.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${issue2.keys.length>1?"ключы":"ключ"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${issue2.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${issue2.origin}`;default:return"Няправільны ўвод"}}};var init_be=__esm(()=>{init_util()});function bg_default(){return{localeError:error4()}}var error4=()=>{let Sizable={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},TypeDictionary={nan:"NaN",number:"число",array:"масив"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Невалиден вход: очакван instanceof ${issue2.expected}, получен ${received}`;return`Невалиден вход: очакван ${expected}, получен ${received}`}case"invalid_value":if(issue2.values.length===1)return`Невалиден вход: очакван ${stringifyPrimitive(issue2.values[0])}`;return`Невалидна опция: очаквано едно от ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Твърде голямо: очаква се ${issue2.origin??"стойност"} да съдържа ${adj}${issue2.maximum.toString()} ${sizing.unit??"елемента"}`;return`Твърде голямо: очаква се ${issue2.origin??"стойност"} да бъде ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Твърде малко: очаква се ${issue2.origin} да съдържа ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Твърде малко: очаква се ${issue2.origin} да бъде ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Невалиден низ: трябва да започва с "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Невалиден низ: трябва да завършва с "${_issue.suffix}"`;if(_issue.format==="includes")return`Невалиден низ: трябва да включва "${_issue.includes}"`;if(_issue.format==="regex")return`Невалиден низ: трябва да съвпада с ${_issue.pattern}`;let invalid_adj="Невалиден";if(_issue.format==="emoji")invalid_adj="Невалидно";if(_issue.format==="datetime")invalid_adj="Невалидно";if(_issue.format==="date")invalid_adj="Невалидна";if(_issue.format==="time")invalid_adj="Невалидно";if(_issue.format==="duration")invalid_adj="Невалидна";return`${invalid_adj} ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${issue2.divisor}`;case"unrecognized_keys":return`Неразпознат${issue2.keys.length>1?"и":""} ключ${issue2.keys.length>1?"ове":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${issue2.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${issue2.origin}`;default:return"Невалиден вход"}}};var init_bg=__esm(()=>{init_util()});function ca_default(){return{localeError:error5()}}var error5=()=>{let Sizable={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Tipus invàlid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`;return`Tipus invàlid: s'esperava ${expected}, s'ha rebut ${received}`}case"invalid_value":if(issue2.values.length===1)return`Valor invàlid: s'esperava ${stringifyPrimitive(issue2.values[0])}`;return`Opció invàlida: s'esperava una de ${joinValues(issue2.values," o ")}`;case"too_big":{let adj=issue2.inclusive?"com a màxim":"menys de",sizing=getSizing(issue2.origin);if(sizing)return`Massa gran: s'esperava que ${issue2.origin??"el valor"} contingués ${adj} ${issue2.maximum.toString()} ${sizing.unit??"elements"}`;return`Massa gran: s'esperava que ${issue2.origin??"el valor"} fos ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?"com a mínim":"més de",sizing=getSizing(issue2.origin);if(sizing)return`Massa petit: s'esperava que ${issue2.origin} contingués ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Format invàlid: ha de començar amb "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Format invàlid: ha d'acabar amb "${_issue.suffix}"`;if(_issue.format==="includes")return`Format invàlid: ha d'incloure "${_issue.includes}"`;if(_issue.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`;return`Format invàlid per a ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${issue2.divisor}`;case"unrecognized_keys":return`Clau${issue2.keys.length>1?"s":""} no reconeguda${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${issue2.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${issue2.origin}`;default:return"Entrada invàlida"}}};var init_ca=__esm(()=>{init_util()});function cs_default(){return{localeError:error6()}}var error6=()=>{let Sizable={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},TypeDictionary={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Neplatný vstup: očekáváno instanceof ${issue2.expected}, obdrženo ${received}`;return`Neplatný vstup: očekáváno ${expected}, obdrženo ${received}`}case"invalid_value":if(issue2.values.length===1)return`Neplatný vstup: očekáváno ${stringifyPrimitive(issue2.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Hodnota je příliš velká: ${issue2.origin??"hodnota"} musí mít ${adj}${issue2.maximum.toString()} ${sizing.unit??"prvků"}`;return`Hodnota je příliš velká: ${issue2.origin??"hodnota"} musí být ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Hodnota je příliš malá: ${issue2.origin??"hodnota"} musí mít ${adj}${issue2.minimum.toString()} ${sizing.unit??"prvků"}`;return`Hodnota je příliš malá: ${issue2.origin??"hodnota"} musí být ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Neplatný řetězec: musí začínat na "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Neplatný řetězec: musí končit na "${_issue.suffix}"`;if(_issue.format==="includes")return`Neplatný řetězec: musí obsahovat "${_issue.includes}"`;if(_issue.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`;return`Neplatný formát ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${issue2.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${issue2.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${issue2.origin}`;default:return"Neplatný vstup"}}};var init_cs=__esm(()=>{init_util()});function da_default(){return{localeError:error7()}}var error7=()=>{let Sizable={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`;return`Ugyldigt input: forventede ${expected}, fik ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ugyldig værdi: forventede ${stringifyPrimitive(issue2.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`For stor: forventede ${origin??"value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"elementer"}`;return`For stor: forventede ${origin??"value"} havde ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ugyldig streng: skal starte med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ugyldig streng: skal ende med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ugyldig streng: skal indeholde "${_issue.includes}"`;if(_issue.format==="regex")return`Ugyldig streng: skal matche mønsteret ${_issue.pattern}`;return`Ugyldig ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${issue2.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${issue2.origin}`;default:return"Ugyldigt input"}}};var init_da=__esm(()=>{init_util()});function de_default(){return{localeError:error8()}}var error8=()=>{let Sizable={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},TypeDictionary={nan:"NaN",number:"Zahl",array:"Array"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ungültige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`;return`Ungültige Eingabe: erwartet ${expected}, erhalten ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ungültige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`;return`Ungültige Option: erwartet eine von ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Zu groß: erwartet, dass ${issue2.origin??"Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${issue2.origin??"Wert"} ${adj}${issue2.maximum.toString()} ist`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`;return`Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ungültiger String: muss mit "${_issue.prefix}" beginnen`;if(_issue.format==="ends_with")return`Ungültiger String: muss mit "${_issue.suffix}" enden`;if(_issue.format==="includes")return`Ungültiger String: muss "${_issue.includes}" enthalten`;if(_issue.format==="regex")return`Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`;return`Ungültig: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;case"unrecognized_keys":return`${issue2.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${issue2.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${issue2.origin}`;default:return"Ungültige Eingabe"}}};var init_de=__esm(()=>{init_util()});function en_default(){return{localeError:error9()}}var error9=()=>{let Sizable={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return`Invalid input: expected ${expected}, received ${received}`}case"invalid_value":if(issue2.values.length===1)return`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;return`Invalid option: expected one of ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Too big: expected ${issue2.origin??"value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"}`;return`Too big: expected ${issue2.origin??"value"} to be ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Invalid string: must start with "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Invalid string: must end with "${_issue.suffix}"`;if(_issue.format==="includes")return`Invalid string: must include "${_issue.includes}"`;if(_issue.format==="regex")return`Invalid string: must match pattern ${_issue.pattern}`;return`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${issue2.divisor}`;case"unrecognized_keys":return`Unrecognized key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Invalid key in ${issue2.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${issue2.origin}`;default:return"Invalid input"}}};var init_en=__esm(()=>{init_util()});function eo_default(){return{localeError:error10()}}var error10=()=>{let Sizable={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},TypeDictionary={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Nevalida enigo: atendiĝis instanceof ${issue2.expected}, riceviĝis ${received}`;return`Nevalida enigo: atendiĝis ${expected}, riceviĝis ${received}`}case"invalid_value":if(issue2.values.length===1)return`Nevalida enigo: atendiĝis ${stringifyPrimitive(issue2.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Tro granda: atendiĝis ke ${issue2.origin??"valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${issue2.origin??"valoro"} havu ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Tro malgranda: atendiĝis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Tro malgranda: atendiĝis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${_issue.suffix}"`;if(_issue.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;if(_issue.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;return`Nevalida ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${issue2.divisor}`;case"unrecognized_keys":return`Nekonata${issue2.keys.length>1?"j":""} ŝlosilo${issue2.keys.length>1?"j":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${issue2.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${issue2.origin}`;default:return"Nevalida enigo"}}};var init_eo=__esm(()=>{init_util()});function es_default(){return{localeError:error11()}}var error11=()=>{let Sizable={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},TypeDictionary={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Entrada inválida: se esperaba instanceof ${issue2.expected}, recibido ${received}`;return`Entrada inválida: se esperaba ${expected}, recibido ${received}`}case"invalid_value":if(issue2.values.length===1)return`Entrada inválida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;return`Opción inválida: se esperaba una de ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`Demasiado grande: se esperaba que ${origin??"valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${origin??"valor"} fuera ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`Demasiado pequeño: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Demasiado pequeño: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Cadena inválida: debe comenzar con "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Cadena inválida: debe terminar en "${_issue.suffix}"`;if(_issue.format==="includes")return`Cadena inválida: debe incluir "${_issue.includes}"`;if(_issue.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`;return`Inválido ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${issue2.divisor}`;case"unrecognized_keys":return`Llave${issue2.keys.length>1?"s":""} desconocida${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Llave inválida en ${TypeDictionary[issue2.origin]??issue2.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${TypeDictionary[issue2.origin]??issue2.origin}`;default:return"Entrada inválida"}}};var init_es=__esm(()=>{init_util()});function fa_default(){return{localeError:error12()}}var error12=()=>{let Sizable={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},TypeDictionary={nan:"NaN",number:"عدد",array:"آرایه"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`ورودی نامعتبر: می‌بایست instanceof ${issue2.expected} می‌بود، ${received} دریافت شد`;return`ورودی نامعتبر: می‌بایست ${expected} می‌بود، ${received} دریافت شد`}case"invalid_value":if(issue2.values.length===1)return`ورودی نامعتبر: می‌بایست ${stringifyPrimitive(issue2.values[0])} می‌بود`;return`گزینه نامعتبر: می‌بایست یکی از ${joinValues(issue2.values,"|")} می‌بود`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`خیلی بزرگ: ${issue2.origin??"مقدار"} باید ${adj}${issue2.maximum.toString()} ${sizing.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${issue2.origin??"مقدار"} باید ${adj}${issue2.maximum.toString()} باشد`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`خیلی کوچک: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} ${sizing.unit} باشد`;return`خیلی کوچک: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} باشد`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`;if(_issue.format==="ends_with")return`رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`;if(_issue.format==="includes")return`رشته نامعتبر: باید شامل "${_issue.includes}" باشد`;if(_issue.format==="regex")return`رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`;return`${FormatDictionary[_issue.format]??issue2.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${issue2.divisor} باشد`;case"unrecognized_keys":return`کلید${issue2.keys.length>1?"های":""} ناشناس: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${issue2.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${issue2.origin}`;default:return"ورودی نامعتبر"}}};var init_fa=__esm(()=>{init_util()});function fi_default(){return{localeError:error13()}}var error13=()=>{let Sizable={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`;return`Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`}case"invalid_value":if(issue2.values.length===1)return`Virheellinen syöte: täytyy olla ${stringifyPrimitive(issue2.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim();return`Liian suuri: arvon täytyy olla ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim();return`Liian pieni: arvon täytyy olla ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${_issue.suffix}"`;if(_issue.format==="includes")return`Virheellinen syöte: täytyy sisältää "${_issue.includes}"`;if(_issue.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`;return`Virheellinen ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${issue2.divisor} monikerta`;case"unrecognized_keys":return`${issue2.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};var init_fi=__esm(()=>{init_util()});function fr_default(){return{localeError:error14()}}var error14=()=>{let Sizable={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},TypeDictionary={nan:"NaN",number:"nombre",array:"tableau"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Entrée invalide : instanceof ${issue2.expected} attendu, ${received} reçu`;return`Entrée invalide : ${expected} attendu, ${received} reçu`}case"invalid_value":if(issue2.values.length===1)return`Entrée invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;return`Option invalide : une valeur parmi ${joinValues(issue2.values,"|")} attendue`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Trop grand : ${issue2.origin??"valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"élément(s)"}`;return`Trop grand : ${issue2.origin??"valeur"} doit être ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Trop petit : ${issue2.origin} doit être ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Chaîne invalide : doit commencer par "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chaîne invalide : doit se terminer par "${_issue.suffix}"`;if(_issue.format==="includes")return`Chaîne invalide : doit inclure "${_issue.includes}"`;if(_issue.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${issue2.divisor}`;case"unrecognized_keys":return`Clé${issue2.keys.length>1?"s":""} non reconnue${issue2.keys.length>1?"s":""} : ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${issue2.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${issue2.origin}`;default:return"Entrée invalide"}}};var init_fr=__esm(()=>{init_util()});function fr_CA_default(){return{localeError:error15()}}var error15=()=>{let Sizable={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Entrée invalide : attendu instanceof ${issue2.expected}, reçu ${received}`;return`Entrée invalide : attendu ${expected}, reçu ${received}`}case"invalid_value":if(issue2.values.length===1)return`Entrée invalide : attendu ${stringifyPrimitive(issue2.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"≤":"<",sizing=getSizing(issue2.origin);if(sizing)return`Trop grand : attendu que ${issue2.origin??"la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`;return`Trop grand : attendu que ${issue2.origin??"la valeur"} soit ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?"≥":">",sizing=getSizing(issue2.origin);if(sizing)return`Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Chaîne invalide : doit commencer par "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chaîne invalide : doit se terminer par "${_issue.suffix}"`;if(_issue.format==="includes")return`Chaîne invalide : doit inclure "${_issue.includes}"`;if(_issue.format==="regex")return`Chaîne invalide : doit correspondre au motif ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${issue2.divisor}`;case"unrecognized_keys":return`Clé${issue2.keys.length>1?"s":""} non reconnue${issue2.keys.length>1?"s":""} : ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${issue2.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${issue2.origin}`;default:return"Entrée invalide"}}};var init_fr_CA=__esm(()=>{init_util()});function he_default(){return{localeError:error16()}}var error16=()=>{let TypeNames={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},Sizable={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},typeEntry=(t)=>t?TypeNames[t]:void 0,typeLabel=(t)=>{let e=typeEntry(t);if(e)return e.label;return t??TypeNames.unknown.label},withDefinite=(t)=>`ה${typeLabel(t)}`,verbFor=(t)=>{return(typeEntry(t)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},getSizing=(origin)=>{if(!origin)return null;return Sizable[origin]??null},FormatDictionary={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expectedKey=issue2.expected,expected=TypeDictionary[expectedKey??""]??typeLabel(expectedKey),receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??TypeNames[receivedType]?.label??receivedType;if(/^[A-Z]/.test(issue2.expected))return`קלט לא תקין: צריך להיות instanceof ${issue2.expected}, התקבל ${received}`;return`קלט לא תקין: צריך להיות ${expected}, התקבל ${received}`}case"invalid_value":{if(issue2.values.length===1)return`ערך לא תקין: הערך חייב להיות ${stringifyPrimitive(issue2.values[0])}`;let stringified=issue2.values.map((v)=>stringifyPrimitive(v));if(issue2.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${stringified[0]} או ${stringified[1]}`;let lastValue=stringified[stringified.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${stringified.slice(0,-1).join(", ")} או ${lastValue}`}case"too_big":{let sizing=getSizing(issue2.origin),subject=withDefinite(issue2.origin??"value");if(issue2.origin==="string")return`${sizing?.longLabel??"ארוך"} מדי: ${subject} צריכה להכיל ${issue2.maximum.toString()} ${sizing?.unit??""} ${issue2.inclusive?"או פחות":"לכל היותר"}`.trim();if(issue2.origin==="number"){let comparison=issue2.inclusive?`קטן או שווה ל-${issue2.maximum}`:`קטן מ-${issue2.maximum}`;return`גדול מדי: ${subject} צריך להיות ${comparison}`}if(issue2.origin==="array"||issue2.origin==="set"){let verb=issue2.origin==="set"?"צריכה":"צריך",comparison=issue2.inclusive?`${issue2.maximum} ${sizing?.unit??""} או פחות`:`פחות מ-${issue2.maximum} ${sizing?.unit??""}`;return`גדול מדי: ${subject} ${verb} להכיל ${comparison}`.trim()}let adj=issue2.inclusive?"<=":"<",be=verbFor(issue2.origin??"value");if(sizing?.unit)return`${sizing.longLabel} מדי: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;return`${sizing?.longLabel??"גדול"} מדי: ${subject} ${be} ${adj}${issue2.maximum.toString()}`}case"too_small":{let sizing=getSizing(issue2.origin),subject=withDefinite(issue2.origin??"value");if(issue2.origin==="string")return`${sizing?.shortLabel??"קצר"} מדי: ${subject} צריכה להכיל ${issue2.minimum.toString()} ${sizing?.unit??""} ${issue2.inclusive?"או יותר":"לפחות"}`.trim();if(issue2.origin==="number"){let comparison=issue2.inclusive?`גדול או שווה ל-${issue2.minimum}`:`גדול מ-${issue2.minimum}`;return`קטן מדי: ${subject} צריך להיות ${comparison}`}if(issue2.origin==="array"||issue2.origin==="set"){let verb=issue2.origin==="set"?"צריכה":"צריך";if(issue2.minimum===1&&issue2.inclusive){let singularPhrase=issue2.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${subject} ${verb} להכיל ${singularPhrase}`}let comparison=issue2.inclusive?`${issue2.minimum} ${sizing?.unit??""} או יותר`:`יותר מ-${issue2.minimum} ${sizing?.unit??""}`;return`קטן מדי: ${subject} ${verb} להכיל ${comparison}`.trim()}let adj=issue2.inclusive?">=":">",be=verbFor(issue2.origin??"value");if(sizing?.unit)return`${sizing.shortLabel} מדי: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`${sizing?.shortLabel??"קטן"} מדי: ${subject} ${be} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${_issue.prefix}"`;if(_issue.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${_issue.suffix}"`;if(_issue.format==="includes")return`המחרוזת חייבת לכלול "${_issue.includes}"`;if(_issue.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${_issue.pattern}`;let nounEntry=FormatDictionary[_issue.format],noun=nounEntry?.label??_issue.format,adjective=(nounEntry?.gender??"m")==="f"?"תקינה":"תקין";return`${noun} לא ${adjective}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${issue2.divisor}`;case"unrecognized_keys":return`מפתח${issue2.keys.length>1?"ות":""} לא מזוה${issue2.keys.length>1?"ים":"ה"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${withDefinite(issue2.origin??"array")}`;default:return"קלט לא תקין"}}};var init_he=__esm(()=>{init_util()});function hu_default(){return{localeError:error17()}}var error17=()=>{let Sizable={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},TypeDictionary={nan:"NaN",number:"szám",array:"tömb"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Érvénytelen bemenet: a várt érték instanceof ${issue2.expected}, a kapott érték ${received}`;return`Érvénytelen bemenet: a várt érték ${expected}, a kapott érték ${received}`}case"invalid_value":if(issue2.values.length===1)return`Érvénytelen bemenet: a várt érték ${stringifyPrimitive(issue2.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Túl nagy: ${issue2.origin??"érték"} mérete túl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${issue2.origin??"érték"} túl nagy: ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Túl kicsi: a bemeneti érték ${issue2.origin} mérete túl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Túl kicsi: a bemeneti érték ${issue2.origin} túl kicsi ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`;if(_issue.format==="ends_with")return`Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`;if(_issue.format==="includes")return`Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`;if(_issue.format==="regex")return`Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`;return`Érvénytelen ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Érvénytelen szám: ${issue2.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${issue2.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${issue2.origin}`;default:return"Érvénytelen bemenet"}}};var init_hu=__esm(()=>{init_util()});function getArmenianPlural(count,one,many){return Math.abs(count)===1?one:many}function withDefiniteArticle(word){if(!word)return"";let vowels=["ա","ե","ը","ի","ո","ու","օ"],lastChar=word[word.length-1];return word+(vowels.includes(lastChar)?"ն":"ը")}function hy_default(){return{localeError:error18()}}var error18=()=>{let Sizable={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},TypeDictionary={nan:"NaN",number:"թիվ",array:"զանգված"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${issue2.expected}, ստացվել է ${received}`;return`Սխալ մուտքագրում․ սպասվում էր ${expected}, ստացվել է ${received}`}case"invalid_value":if(issue2.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${stringifyPrimitive(issue2.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing){let maxValue=Number(issue2.maximum),unit=getArmenianPlural(maxValue,sizing.unit.one,sizing.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin??"արժեք")} կունենա ${adj}${issue2.maximum.toString()} ${unit}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin??"արժեք")} լինի ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing){let minValue=Number(issue2.minimum),unit=getArmenianPlural(minValue,sizing.unit.one,sizing.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin)} կունենա ${adj}${issue2.minimum.toString()} ${unit}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin)} լինի ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${_issue.prefix}"-ով`;if(_issue.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${_issue.suffix}"-ով`;if(_issue.format==="includes")return`Սխալ տող․ պետք է պարունակի "${_issue.includes}"`;if(_issue.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${_issue.pattern} ձևաչափին`;return`Սխալ ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${issue2.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${issue2.keys.length>1?"ներ":""}. ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${withDefiniteArticle(issue2.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${withDefiniteArticle(issue2.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};var init_hy=__esm(()=>{init_util()});function id_default(){return{localeError:error19()}}var error19=()=>{let Sizable={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`;return`Input tidak valid: diharapkan ${expected}, diterima ${received}`}case"invalid_value":if(issue2.values.length===1)return`Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Terlalu besar: diharapkan ${issue2.origin??"value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemen"}`;return`Terlalu besar: diharapkan ${issue2.origin??"value"} menjadi ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`String tidak valid: harus dimulai dengan "${_issue.prefix}"`;if(_issue.format==="ends_with")return`String tidak valid: harus berakhir dengan "${_issue.suffix}"`;if(_issue.format==="includes")return`String tidak valid: harus menyertakan "${_issue.includes}"`;if(_issue.format==="regex")return`String tidak valid: harus sesuai pola ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${issue2.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${issue2.origin}`;default:return"Input tidak valid"}}};var init_id=__esm(()=>{init_util()});function is_default(){return{localeError:error20()}}var error20=()=>{let Sizable={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},TypeDictionary={nan:"NaN",number:"númer",array:"fylki"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Rangt gildi: Þú slóst inn ${received} þar sem á að vera instanceof ${issue2.expected}`;return`Rangt gildi: Þú slóst inn ${received} þar sem á að vera ${expected}`}case"invalid_value":if(issue2.values.length===1)return`Rangt gildi: gert ráð fyrir ${stringifyPrimitive(issue2.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Of stórt: gert er ráð fyrir að ${issue2.origin??"gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${issue2.origin??"gildi"} sé ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Of lítið: gert er ráð fyrir að ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Of lítið: gert er ráð fyrir að ${issue2.origin} sé ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ógildur strengur: verður að byrja á "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ógildur strengur: verður að enda á "${_issue.suffix}"`;if(_issue.format==="includes")return`Ógildur strengur: verður að innihalda "${_issue.includes}"`;if(_issue.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${_issue.pattern}`;return`Rangt ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${issue2.divisor}`;case"unrecognized_keys":return`Óþekkt ${issue2.keys.length>1?"ir lyklar":"ur lykill"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${issue2.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${issue2.origin}`;default:return"Rangt gildi"}}};var init_is=__esm(()=>{init_util()});function it_default(){return{localeError:error21()}}var error21=()=>{let Sizable={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"numero",array:"vettore"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`;return`Input non valido: atteso ${expected}, ricevuto ${received}`}case"invalid_value":if(issue2.values.length===1)return`Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`;return`Opzione non valida: atteso uno tra ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Troppo grande: ${issue2.origin??"valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementi"}`;return`Troppo grande: ${issue2.origin??"valore"} deve essere ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Stringa non valida: deve iniziare con "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Stringa non valida: deve terminare con "${_issue.suffix}"`;if(_issue.format==="includes")return`Stringa non valida: deve includere "${_issue.includes}"`;if(_issue.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;return`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${issue2.divisor}`;case"unrecognized_keys":return`Chiav${issue2.keys.length>1?"i":"e"} non riconosciut${issue2.keys.length>1?"e":"a"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${issue2.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${issue2.origin}`;default:return"Input non valido"}}};var init_it=__esm(()=>{init_util()});function ja_default(){return{localeError:error22()}}var error22=()=>{let Sizable={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},TypeDictionary={nan:"NaN",number:"数値",array:"配列"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`無効な入力: instanceof ${issue2.expected}が期待されましたが、${received}が入力されました`;return`無効な入力: ${expected}が期待されましたが、${received}が入力されました`}case"invalid_value":if(issue2.values.length===1)return`無効な入力: ${stringifyPrimitive(issue2.values[0])}が期待されました`;return`無効な選択: ${joinValues(issue2.values,"、")}のいずれかである必要があります`;case"too_big":{let adj=issue2.inclusive?"以下である":"より小さい",sizing=getSizing(issue2.origin);if(sizing)return`大きすぎる値: ${issue2.origin??"値"}は${issue2.maximum.toString()}${sizing.unit??"要素"}${adj}必要があります`;return`大きすぎる値: ${issue2.origin??"値"}は${issue2.maximum.toString()}${adj}必要があります`}case"too_small":{let adj=issue2.inclusive?"以上である":"より大きい",sizing=getSizing(issue2.origin);if(sizing)return`小さすぎる値: ${issue2.origin}は${issue2.minimum.toString()}${sizing.unit}${adj}必要があります`;return`小さすぎる値: ${issue2.origin}は${issue2.minimum.toString()}${adj}必要があります`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`無効な文字列: "${_issue.prefix}"で始まる必要があります`;if(_issue.format==="ends_with")return`無効な文字列: "${_issue.suffix}"で終わる必要があります`;if(_issue.format==="includes")return`無効な文字列: "${_issue.includes}"を含む必要があります`;if(_issue.format==="regex")return`無効な文字列: パターン${_issue.pattern}に一致する必要があります`;return`無効な${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`無効な数値: ${issue2.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${issue2.keys.length>1?"群":""}: ${joinValues(issue2.keys,"、")}`;case"invalid_key":return`${issue2.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${issue2.origin}内の無効な値`;default:return"無効な入力"}}};var init_ja=__esm(()=>{init_util()});function ka_default(){return{localeError:error23()}}var error23=()=>{let Sizable={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული სტრინგი",base64url:"base64url-კოდირებული სტრინგი",json_string:"JSON სტრინგი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},TypeDictionary={nan:"NaN",number:"რიცხვი",string:"სტრინგი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${issue2.expected}, მიღებული ${received}`;return`არასწორი შეყვანა: მოსალოდნელი ${expected}, მიღებული ${received}`}case"invalid_value":if(issue2.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${stringifyPrimitive(issue2.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${joinValues(issue2.values,"|")}-დან`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`ზედმეტად დიდი: მოსალოდნელი ${issue2.origin??"მნიშვნელობა"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${issue2.origin??"მნიშვნელობა"} იყოს ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`ზედმეტად პატარა: მოსალოდნელი ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${issue2.origin} იყოს ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`არასწორი სტრინგი: უნდა იწყებოდეს "${_issue.prefix}"-ით`;if(_issue.format==="ends_with")return`არასწორი სტრინგი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`;if(_issue.format==="includes")return`არასწორი სტრინგი: უნდა შეიცავდეს "${_issue.includes}"-ს`;if(_issue.format==="regex")return`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`;return`არასწორი ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${issue2.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${issue2.keys.length>1?"ები":"ი"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${issue2.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${issue2.origin}-ში`;default:return"არასწორი შეყვანა"}}};var init_ka=__esm(()=>{init_util()});function km_default(){return{localeError:error24()}}var error24=()=>{let Sizable={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},TypeDictionary={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${issue2.expected} ប៉ុន្តែទទួលបាន ${received}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${expected} ប៉ុន្តែទទួលបាន ${received}`}case"invalid_value":if(issue2.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive(issue2.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`ធំពេក៖ ត្រូវការ ${issue2.origin??"តម្លៃ"} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${issue2.origin??"តម្លៃ"} ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`តូចពេក៖ ត្រូវការ ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`តូចពេក៖ ត្រូវការ ${issue2.origin} ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`;if(_issue.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`;if(_issue.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`;if(_issue.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`;return`មិនត្រឹមត្រូវ៖ ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue2.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${issue2.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue2.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};var init_km=__esm(()=>{init_util()});function kh_default(){return km_default()}var init_kh=__esm(()=>{init_km()});function ko_default(){return{localeError:error25()}}var error25=()=>{let Sizable={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`잘못된 입력: 예상 타입은 instanceof ${issue2.expected}, 받은 타입은 ${received}입니다`;return`잘못된 입력: 예상 타입은 ${expected}, 받은 타입은 ${received}입니다`}case"invalid_value":if(issue2.values.length===1)return`잘못된 입력: 값은 ${stringifyPrimitive(issue2.values[0])} 이어야 합니다`;return`잘못된 옵션: ${joinValues(issue2.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let adj=issue2.inclusive?"이하":"미만",suffix=adj==="미만"?"이어야 합니다":"여야 합니다",sizing=getSizing(issue2.origin),unit=sizing?.unit??"요소";if(sizing)return`${issue2.origin??"값"}이 너무 큽니다: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`;return`${issue2.origin??"값"}이 너무 큽니다: ${issue2.maximum.toString()} ${adj}${suffix}`}case"too_small":{let adj=issue2.inclusive?"이상":"초과",suffix=adj==="이상"?"이어야 합니다":"여야 합니다",sizing=getSizing(issue2.origin),unit=sizing?.unit??"요소";if(sizing)return`${issue2.origin??"값"}이 너무 작습니다: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`;return`${issue2.origin??"값"}이 너무 작습니다: ${issue2.minimum.toString()} ${adj}${suffix}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`;if(_issue.format==="ends_with")return`잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`;if(_issue.format==="includes")return`잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`;if(_issue.format==="regex")return`잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`잘못된 숫자: ${issue2.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`잘못된 키: ${issue2.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${issue2.origin}`;default:return"잘못된 입력"}}};var init_ko=__esm(()=>{init_util()});function getUnitTypeFromNumber(number2){let abs=Math.abs(number2),last=abs%10,last2=abs%100;if(last2>=11&&last2<=19||last===0)return"many";if(last===1)return"one";return"few"}function lt_default(){return{localeError:error26()}}var capitalizeFirstCharacter=(text)=>{return text.charAt(0).toUpperCase()+text.slice(1)},error26=()=>{let Sizable={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function getSizing(origin,unitType,inclusive,targetShouldBe){let result=Sizable[origin]??null;if(result===null)return result;return{unit:result.unit[unitType],verb:result.verb[targetShouldBe][inclusive?"inclusive":"notInclusive"]}}let FormatDictionary={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},TypeDictionary={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Gautas tipas ${received}, o tikėtasi - instanceof ${issue2.expected}`;return`Gautas tipas ${received}, o tikėtasi - ${expected}`}case"invalid_value":if(issue2.values.length===1)return`Privalo būti ${stringifyPrimitive(issue2.values[0])}`;return`Privalo būti vienas iš ${joinValues(issue2.values,"|")} pasirinkimų`;case"too_big":{let origin=TypeDictionary[issue2.origin]??issue2.origin,sizing=getSizing(issue2.origin,getUnitTypeFromNumber(Number(issue2.maximum)),issue2.inclusive??!1,"smaller");if(sizing?.verb)return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit??"elementų"}`;let adj=issue2.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} turi būti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`}case"too_small":{let origin=TypeDictionary[issue2.origin]??issue2.origin,sizing=getSizing(issue2.origin,getUnitTypeFromNumber(Number(issue2.minimum)),issue2.inclusive??!1,"bigger");if(sizing?.verb)return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit??"elementų"}`;let adj=issue2.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} turi būti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Eilutė privalo prasidėti "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Eilutė privalo pasibaigti "${_issue.suffix}"`;if(_issue.format==="includes")return`Eilutė privalo įtraukti "${_issue.includes}"`;if(_issue.format==="regex")return`Eilutė privalo atitikti ${_issue.pattern}`;return`Neteisingas ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Skaičius privalo būti ${issue2.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${issue2.keys.length>1?"i":"as"} rakt${issue2.keys.length>1?"ai":"as"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let origin=TypeDictionary[issue2.origin]??issue2.origin;return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};var init_lt=__esm(()=>{init_util()});function mk_default(){return{localeError:error27()}}var error27=()=>{let Sizable={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},TypeDictionary={nan:"NaN",number:"број",array:"низа"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Грешен внес: се очекува instanceof ${issue2.expected}, примено ${received}`;return`Грешен внес: се очекува ${expected}, примено ${received}`}case"invalid_value":if(issue2.values.length===1)return`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;return`Грешана опција: се очекува една ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Премногу голем: се очекува ${issue2.origin??"вредноста"} да има ${adj}${issue2.maximum.toString()} ${sizing.unit??"елементи"}`;return`Премногу голем: се очекува ${issue2.origin??"вредноста"} да биде ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Премногу мал: се очекува ${issue2.origin} да има ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Премногу мал: се очекува ${issue2.origin} да биде ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Неважечка низа: мора да започнува со "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Неважечка низа: мора да завршува со "${_issue.suffix}"`;if(_issue.format==="includes")return`Неважечка низа: мора да вклучува "${_issue.includes}"`;if(_issue.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`;return`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${issue2.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${issue2.origin}`;default:return"Грешен внес"}}};var init_mk=__esm(()=>{init_util()});function ms_default(){return{localeError:error28()}}var error28=()=>{let Sizable={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"nombor"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`;return`Input tidak sah: dijangka ${expected}, diterima ${received}`}case"invalid_value":if(issue2.values.length===1)return`Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Terlalu besar: dijangka ${issue2.origin??"nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemen"}`;return`Terlalu besar: dijangka ${issue2.origin??"nilai"} adalah ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`String tidak sah: mesti bermula dengan "${_issue.prefix}"`;if(_issue.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;if(_issue.format==="includes")return`String tidak sah: mesti mengandungi "${_issue.includes}"`;if(_issue.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${issue2.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${issue2.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${issue2.origin}`;default:return"Input tidak sah"}}};var init_ms=__esm(()=>{init_util()});function nl_default(){return{localeError:error29()}}var error29=()=>{let Sizable={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},TypeDictionary={nan:"NaN",number:"getal"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`;return`Ongeldige invoer: verwacht ${expected}, ontving ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;return`Ongeldige optie: verwacht één van ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),longName=issue2.origin==="date"?"laat":issue2.origin==="string"?"lang":"groot";if(sizing)return`Te ${longName}: verwacht dat ${issue2.origin??"waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementen"} ${sizing.verb}`;return`Te ${longName}: verwacht dat ${issue2.origin??"waarde"} ${adj}${issue2.maximum.toString()} is`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),shortName=issue2.origin==="date"?"vroeg":issue2.origin==="string"?"kort":"klein";if(sizing)return`Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;return`Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;if(_issue.format==="ends_with")return`Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;if(_issue.format==="includes")return`Ongeldige tekst: moet "${_issue.includes}" bevatten`;if(_issue.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;return`Ongeldig: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${issue2.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${issue2.origin}`;default:return"Ongeldige invoer"}}};var init_nl=__esm(()=>{init_util()});function no_default(){return{localeError:error30()}}var error30=()=>{let Sizable={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"tall",array:"liste"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`;return`Ugyldig input: forventet ${expected}, fikk ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`;return`Ugyldig valg: forventet en av ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`For stor(t): forventet ${issue2.origin??"value"} til å ha ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementer"}`;return`For stor(t): forventet ${issue2.origin??"value"} til å ha ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`For lite(n): forventet ${issue2.origin} til å ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`For lite(n): forventet ${issue2.origin} til å ha ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ugyldig streng: må starte med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ugyldig streng: må ende med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ugyldig streng: må inneholde "${_issue.includes}"`;if(_issue.format==="regex")return`Ugyldig streng: må matche mønsteret ${_issue.pattern}`;return`Ugyldig ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${issue2.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${issue2.origin}`;default:return"Ugyldig input"}}};var init_no=__esm(()=>{init_util()});function ota_default(){return{localeError:error31()}}var error31=()=>{let Sizable={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},TypeDictionary={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Fâsit giren: umulan instanceof ${issue2.expected}, alınan ${received}`;return`Fâsit giren: umulan ${expected}, alınan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Fâsit giren: umulan ${stringifyPrimitive(issue2.values[0])}`;return`Fâsit tercih: mûteberler ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Fazla büyük: ${issue2.origin??"value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${issue2.origin??"value"}, ${adj}${issue2.maximum.toString()} olmalıydı.`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Fazla küçük: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmalıydı.`;return`Fazla küçük: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmalıydı.`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Fâsit metin: "${_issue.prefix}" ile başlamalı.`;if(_issue.format==="ends_with")return`Fâsit metin: "${_issue.suffix}" ile bitmeli.`;if(_issue.format==="includes")return`Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`;if(_issue.format==="regex")return`Fâsit metin: ${_issue.pattern} nakşına uymalı.`;return`Fâsit ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Fâsit sayı: ${issue2.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${issue2.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};var init_ota=__esm(()=>{init_util()});function ps_default(){return{localeError:error32()}}var error32=()=>{let Sizable={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},TypeDictionary={nan:"NaN",number:"عدد",array:"ارې"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`ناسم ورودي: باید instanceof ${issue2.expected} وای, مګر ${received} ترلاسه شو`;return`ناسم ورودي: باید ${expected} وای, مګر ${received} ترلاسه شو`}case"invalid_value":if(issue2.values.length===1)return`ناسم ورودي: باید ${stringifyPrimitive(issue2.values[0])} وای`;return`ناسم انتخاب: باید یو له ${joinValues(issue2.values,"|")} څخه وای`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`ډیر لوی: ${issue2.origin??"ارزښت"} باید ${adj}${issue2.maximum.toString()} ${sizing.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${issue2.origin??"ارزښت"} باید ${adj}${issue2.maximum.toString()} وي`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`ډیر کوچنی: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} ${sizing.unit} ولري`;return`ډیر کوچنی: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} وي`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`ناسم متن: باید د "${_issue.prefix}" سره پیل شي`;if(_issue.format==="ends_with")return`ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`;if(_issue.format==="includes")return`ناسم متن: باید "${_issue.includes}" ولري`;if(_issue.format==="regex")return`ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`;return`${FormatDictionary[_issue.format]??issue2.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${issue2.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${issue2.keys.length>1?"کلیډونه":"کلیډ"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${issue2.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${issue2.origin} کې`;default:return"ناسمه ورودي"}}};var init_ps=__esm(()=>{init_util()});function pl_default(){return{localeError:error33()}}var error33=()=>{let Sizable={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},TypeDictionary={nan:"NaN",number:"liczba",array:"tablica"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${expected}, otrzymano ${received}`}case"invalid_value":if(issue2.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Za duża wartość: oczekiwano, że ${issue2.origin??"wartość"} będzie mieć ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${issue2.origin??"wartość"} będzie wynosić ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Za mała wartość: oczekiwano, że ${issue2.origin??"wartość"} będzie mieć ${adj}${issue2.minimum.toString()} ${sizing.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${issue2.origin??"wartość"} będzie wynosić ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`;if(_issue.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`;if(_issue.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`;return`Nieprawidłow(y/a/e) ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${issue2.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${issue2.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${issue2.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};var init_pl=__esm(()=>{init_util()});function pt_default(){return{localeError:error34()}}var error34=()=>{let Sizable={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},TypeDictionary={nan:"NaN",number:"número",null:"nulo"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Tipo inválido: esperado instanceof ${issue2.expected}, recebido ${received}`;return`Tipo inválido: esperado ${expected}, recebido ${received}`}case"invalid_value":if(issue2.values.length===1)return`Entrada inválida: esperado ${stringifyPrimitive(issue2.values[0])}`;return`Opção inválida: esperada uma das ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Muito grande: esperado que ${issue2.origin??"valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementos"}`;return`Muito grande: esperado que ${issue2.origin??"valor"} fosse ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Texto inválido: deve começar com "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Texto inválido: deve terminar com "${_issue.suffix}"`;if(_issue.format==="includes")return`Texto inválido: deve incluir "${_issue.includes}"`;if(_issue.format==="regex")return`Texto inválido: deve corresponder ao padrão ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${issue2.divisor}`;case"unrecognized_keys":return`Chave${issue2.keys.length>1?"s":""} desconhecida${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Chave inválida em ${issue2.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${issue2.origin}`;default:return"Campo inválido"}}};var init_pt=__esm(()=>{init_util()});function getRussianPlural(count,one,few,many){let absCount=Math.abs(count),lastDigit=absCount%10,lastTwoDigits=absCount%100;if(lastTwoDigits>=11&&lastTwoDigits<=19)return many;if(lastDigit===1)return one;if(lastDigit>=2&&lastDigit<=4)return few;return many}function ru_default(){return{localeError:error35()}}var error35=()=>{let Sizable={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},TypeDictionary={nan:"NaN",number:"число",array:"массив"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Неверный ввод: ожидалось instanceof ${issue2.expected}, получено ${received}`;return`Неверный ввод: ожидалось ${expected}, получено ${received}`}case"invalid_value":if(issue2.values.length===1)return`Неверный ввод: ожидалось ${stringifyPrimitive(issue2.values[0])}`;return`Неверный вариант: ожидалось одно из ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing){let maxValue=Number(issue2.maximum),unit=getRussianPlural(maxValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Слишком большое значение: ожидалось, что ${issue2.origin??"значение"} будет иметь ${adj}${issue2.maximum.toString()} ${unit}`}return`Слишком большое значение: ожидалось, что ${issue2.origin??"значение"} будет ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing){let minValue=Number(issue2.minimum),unit=getRussianPlural(minValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Слишком маленькое значение: ожидалось, что ${issue2.origin} будет иметь ${adj}${issue2.minimum.toString()} ${unit}`}return`Слишком маленькое значение: ожидалось, что ${issue2.origin} будет ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Неверная строка: должна начинаться с "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Неверная строка: должна заканчиваться на "${_issue.suffix}"`;if(_issue.format==="includes")return`Неверная строка: должна содержать "${_issue.includes}"`;if(_issue.format==="regex")return`Неверная строка: должна соответствовать шаблону ${_issue.pattern}`;return`Неверный ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${issue2.divisor}`;case"unrecognized_keys":return`Нераспознанн${issue2.keys.length>1?"ые":"ый"} ключ${issue2.keys.length>1?"и":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${issue2.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${issue2.origin}`;default:return"Неверные входные данные"}}};var init_ru=__esm(()=>{init_util()});function sl_default(){return{localeError:error36()}}var error36=()=>{let Sizable={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},TypeDictionary={nan:"NaN",number:"število",array:"tabela"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Neveljaven vnos: pričakovano instanceof ${issue2.expected}, prejeto ${received}`;return`Neveljaven vnos: pričakovano ${expected}, prejeto ${received}`}case"invalid_value":if(issue2.values.length===1)return`Neveljaven vnos: pričakovano ${stringifyPrimitive(issue2.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Preveliko: pričakovano, da bo ${issue2.origin??"vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${issue2.origin??"vrednost"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Premajhno: pričakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Premajhno: pričakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Neveljaven niz: mora se začeti z "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Neveljaven niz: mora se končati z "${_issue.suffix}"`;if(_issue.format==="includes")return`Neveljaven niz: mora vsebovati "${_issue.includes}"`;if(_issue.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;return`Neveljaven ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${issue2.divisor}`;case"unrecognized_keys":return`Neprepoznan${issue2.keys.length>1?"i ključi":" ključ"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${issue2.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${issue2.origin}`;default:return"Neveljaven vnos"}}};var init_sl=__esm(()=>{init_util()});function sv_default(){return{localeError:error37()}}var error37=()=>{let Sizable={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},TypeDictionary={nan:"NaN",number:"antal",array:"lista"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ogiltig inmatning: förväntat instanceof ${issue2.expected}, fick ${received}`;return`Ogiltig inmatning: förväntat ${expected}, fick ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ogiltig inmatning: förväntat ${stringifyPrimitive(issue2.values[0])}`;return`Ogiltigt val: förväntade en av ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`För stor(t): förväntade ${issue2.origin??"värdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit??"element"}`;return`För stor(t): förväntat ${issue2.origin??"värdet"} att ha ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`För lite(t): förväntade ${issue2.origin??"värdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`För lite(t): förväntade ${issue2.origin??"värdet"} att ha ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ogiltig sträng: måste börja med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ogiltig sträng: måste sluta med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ogiltig sträng: måste innehålla "${_issue.includes}"`;if(_issue.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`;return`Ogiltig(t) ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${issue2.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${issue2.origin??"värdet"}`;default:return"Ogiltig input"}}};var init_sv=__esm(()=>{init_util()});function ta_default(){return{localeError:error38()}}var error38=()=>{let Sizable={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${issue2.expected}, பெறப்பட்டது ${received}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${expected}, பெறப்பட்டது ${received}`}case"invalid_value":if(issue2.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive(issue2.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues(issue2.values,"|")} இல் ஒன்று`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue2.origin??"மதிப்பு"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue2.origin??"மதிப்பு"} ${adj}${issue2.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue2.origin} ${adj}${issue2.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`;if(_issue.format==="ends_with")return`தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`;if(_issue.format==="includes")return`தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`;if(_issue.format==="regex")return`தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`தவறான எண்: ${issue2.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${issue2.keys.length>1?"கள்":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${issue2.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};var init_ta=__esm(()=>{init_util()});function th_default(){return{localeError:error39()}}var error39=()=>{let Sizable={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},TypeDictionary={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${issue2.expected} แต่ได้รับ ${received}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${expected} แต่ได้รับ ${received}`}case"invalid_value":if(issue2.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive(issue2.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"ไม่เกิน":"น้อยกว่า",sizing=getSizing(issue2.origin);if(sizing)return`เกินกำหนด: ${issue2.origin??"ค่า"} ควรมี${adj} ${issue2.maximum.toString()} ${sizing.unit??"รายการ"}`;return`เกินกำหนด: ${issue2.origin??"ค่า"} ควรมี${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?"อย่างน้อย":"มากกว่า",sizing=getSizing(issue2.origin);if(sizing)return`น้อยกว่ากำหนด: ${issue2.origin} ควรมี${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`น้อยกว่ากำหนด: ${issue2.origin} ควรมี${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`;if(_issue.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`;if(_issue.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`;if(_issue.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`;return`รูปแบบไม่ถูกต้อง: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue2.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${issue2.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${issue2.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};var init_th=__esm(()=>{init_util()});function tr_default(){return{localeError:error40()}}var error40=()=>{let Sizable={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Geçersiz değer: beklenen instanceof ${issue2.expected}, alınan ${received}`;return`Geçersiz değer: beklenen ${expected}, alınan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Geçersiz değer: beklenen ${stringifyPrimitive(issue2.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Çok büyük: beklenen ${issue2.origin??"değer"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"öğe"}`;return`Çok büyük: beklenen ${issue2.origin??"değer"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Çok küçük: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Çok küçük: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Geçersiz metin: "${_issue.prefix}" ile başlamalı`;if(_issue.format==="ends_with")return`Geçersiz metin: "${_issue.suffix}" ile bitmeli`;if(_issue.format==="includes")return`Geçersiz metin: "${_issue.includes}" içermeli`;if(_issue.format==="regex")return`Geçersiz metin: ${_issue.pattern} desenine uymalı`;return`Geçersiz ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Geçersiz sayı: ${issue2.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${issue2.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};var init_tr=__esm(()=>{init_util()});function uk_default(){return{localeError:error41()}}var error41=()=>{let Sizable={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},TypeDictionary={nan:"NaN",number:"число",array:"масив"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Неправильні вхідні дані: очікується instanceof ${issue2.expected}, отримано ${received}`;return`Неправильні вхідні дані: очікується ${expected}, отримано ${received}`}case"invalid_value":if(issue2.values.length===1)return`Неправильні вхідні дані: очікується ${stringifyPrimitive(issue2.values[0])}`;return`Неправильна опція: очікується одне з ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Занадто велике: очікується, що ${issue2.origin??"значення"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"елементів"}`;return`Занадто велике: очікується, що ${issue2.origin??"значення"} буде ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Занадто мале: очікується, що ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Занадто мале: очікується, що ${issue2.origin} буде ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Неправильний рядок: повинен починатися з "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`;if(_issue.format==="includes")return`Неправильний рядок: повинен містити "${_issue.includes}"`;if(_issue.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`;return`Неправильний ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${issue2.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${issue2.keys.length>1?"і":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${issue2.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${issue2.origin}`;default:return"Неправильні вхідні дані"}}};var init_uk=__esm(()=>{init_util()});function ua_default(){return uk_default()}var init_ua=__esm(()=>{init_uk()});function ur_default(){return{localeError:error42()}}var error42=()=>{let Sizable={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},TypeDictionary={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`غلط ان پٹ: instanceof ${issue2.expected} متوقع تھا، ${received} موصول ہوا`;return`غلط ان پٹ: ${expected} متوقع تھا، ${received} موصول ہوا`}case"invalid_value":if(issue2.values.length===1)return`غلط ان پٹ: ${stringifyPrimitive(issue2.values[0])} متوقع تھا`;return`غلط آپشن: ${joinValues(issue2.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`بہت بڑا: ${issue2.origin??"ویلیو"} کے ${adj}${issue2.maximum.toString()} ${sizing.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${issue2.origin??"ویلیو"} کا ${adj}${issue2.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`بہت چھوٹا: ${issue2.origin} کے ${adj}${issue2.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${issue2.origin} کا ${adj}${issue2.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`;if(_issue.format==="ends_with")return`غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`;if(_issue.format==="includes")return`غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`;if(_issue.format==="regex")return`غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`;return`غلط ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`غلط نمبر: ${issue2.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${issue2.keys.length>1?"ز":""}: ${joinValues(issue2.keys,"، ")}`;case"invalid_key":return`${issue2.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${issue2.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};var init_ur=__esm(()=>{init_util()});function uz_default(){return{localeError:error43()}}var error43=()=>{let Sizable={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},TypeDictionary={nan:"NaN",number:"raqam",array:"massiv"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`;return`Noto‘g‘ri kirish: kutilgan ${expected}, qabul qilingan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Juda katta: kutilgan ${issue2.origin??"qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`;return`Juda katta: kutilgan ${issue2.origin??"qiymat"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;return`Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Noto‘g‘ri satr: "${_issue.prefix}" bilan boshlanishi kerak`;if(_issue.format==="ends_with")return`Noto‘g‘ri satr: "${_issue.suffix}" bilan tugashi kerak`;if(_issue.format==="includes")return`Noto‘g‘ri satr: "${_issue.includes}" ni o‘z ichiga olishi kerak`;if(_issue.format==="regex")return`Noto‘g‘ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${issue2.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${issue2.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};var init_uz=__esm(()=>{init_util()});function vi_default(){return{localeError:error44()}}var error44=()=>{let Sizable={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},TypeDictionary={nan:"NaN",number:"số",array:"mảng"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${issue2.expected}, nhận được ${received}`;return`Đầu vào không hợp lệ: mong đợi ${expected}, nhận được ${received}`}case"invalid_value":if(issue2.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive(issue2.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Quá lớn: mong đợi ${issue2.origin??"giá trị"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"phần tử"}`;return`Quá lớn: mong đợi ${issue2.origin??"giá trị"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Quá nhỏ: mong đợi ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Quá nhỏ: mong đợi ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`;if(_issue.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`;if(_issue.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${issue2.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${issue2.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${issue2.origin}`;default:return"Đầu vào không hợp lệ"}}};var init_vi=__esm(()=>{init_util()});function zh_CN_default(){return{localeError:error45()}}var error45=()=>{let Sizable={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},TypeDictionary={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`无效输入:期望 instanceof ${issue2.expected},实际接收 ${received}`;return`无效输入:期望 ${expected},实际接收 ${received}`}case"invalid_value":if(issue2.values.length===1)return`无效输入:期望 ${stringifyPrimitive(issue2.values[0])}`;return`无效选项:期望以下之一 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`数值过大:期望 ${issue2.origin??"值"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"个元素"}`;return`数值过大:期望 ${issue2.origin??"值"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`数值过小:期望 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`数值过小:期望 ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`无效字符串:必须以 "${_issue.prefix}" 开头`;if(_issue.format==="ends_with")return`无效字符串:必须以 "${_issue.suffix}" 结尾`;if(_issue.format==="includes")return`无效字符串:必须包含 "${_issue.includes}"`;if(_issue.format==="regex")return`无效字符串:必须满足正则表达式 ${_issue.pattern}`;return`无效${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`无效数字:必须是 ${issue2.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${issue2.origin} 中包含无效值(value)`;default:return"无效输入"}}};var init_zh_CN=__esm(()=>{init_util()});function zh_TW_default(){return{localeError:error46()}}var error46=()=>{let Sizable={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`無效的輸入值:預期為 instanceof ${issue2.expected},但收到 ${received}`;return`無效的輸入值:預期為 ${expected},但收到 ${received}`}case"invalid_value":if(issue2.values.length===1)return`無效的輸入值:預期為 ${stringifyPrimitive(issue2.values[0])}`;return`無效的選項:預期為以下其中之一 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`數值過大:預期 ${issue2.origin??"值"} 應為 ${adj}${issue2.maximum.toString()} ${sizing.unit??"個元素"}`;return`數值過大:預期 ${issue2.origin??"值"} 應為 ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`數值過小:預期 ${issue2.origin} 應為 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`數值過小:預期 ${issue2.origin} 應為 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`無效的字串:必須以 "${_issue.prefix}" 開頭`;if(_issue.format==="ends_with")return`無效的字串:必須以 "${_issue.suffix}" 結尾`;if(_issue.format==="includes")return`無效的字串:必須包含 "${_issue.includes}"`;if(_issue.format==="regex")return`無效的字串:必須符合格式 ${_issue.pattern}`;return`無效的 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`無效的數字:必須為 ${issue2.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${issue2.keys.length>1?"們":""}:${joinValues(issue2.keys,"、")}`;case"invalid_key":return`${issue2.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${issue2.origin} 中有無效的值`;default:return"無效的輸入值"}}};var init_zh_TW=__esm(()=>{init_util()});function yo_default(){return{localeError:error47()}}var error47=()=>{let Sizable={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},TypeDictionary={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${issue2.expected}, àmọ̀ a rí ${received}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${expected}, àmọ̀ a rí ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${stringifyPrimitive(issue2.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${issue2.origin??"iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${adj}${issue2.maximum}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Kéré ju: a ní láti jẹ́ pé ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`;return`Kéré ju: a ní láti jẹ́ ${adj}${issue2.minimum}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${_issue.suffix}"`;if(_issue.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${_issue.includes}"`;if(_issue.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${_issue.pattern}`;return`Aṣìṣe: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${issue2.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${issue2.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${issue2.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};var init_yo=__esm(()=>{init_util()});var exports_locales={};__export(exports_locales,{zhTW:()=>zh_TW_default,zhCN:()=>zh_CN_default,yo:()=>yo_default,vi:()=>vi_default,uz:()=>uz_default,ur:()=>ur_default,uk:()=>uk_default,ua:()=>ua_default,tr:()=>tr_default,th:()=>th_default,ta:()=>ta_default,sv:()=>sv_default,sl:()=>sl_default,ru:()=>ru_default,pt:()=>pt_default,ps:()=>ps_default,pl:()=>pl_default,ota:()=>ota_default,no:()=>no_default,nl:()=>nl_default,ms:()=>ms_default,mk:()=>mk_default,lt:()=>lt_default,ko:()=>ko_default,km:()=>km_default,kh:()=>kh_default,ka:()=>ka_default,ja:()=>ja_default,it:()=>it_default,is:()=>is_default,id:()=>id_default,hy:()=>hy_default,hu:()=>hu_default,he:()=>he_default,frCA:()=>fr_CA_default,fr:()=>fr_default,fi:()=>fi_default,fa:()=>fa_default,es:()=>es_default,eo:()=>eo_default,en:()=>en_default,de:()=>de_default,da:()=>da_default,cs:()=>cs_default,ca:()=>ca_default,bg:()=>bg_default,be:()=>be_default,az:()=>az_default,ar:()=>ar_default});var init_locales=__esm(()=>{init_ar();init_az();init_be();init_bg();init_ca();init_cs();init_da();init_de();init_en();init_eo();init_es();init_fa();init_fi();init_fr();init_fr_CA();init_he();init_hu();init_hy();init_id();init_is();init_it();init_ja();init_ka();init_kh();init_km();init_ko();init_lt();init_mk();init_ms();init_nl();init_no();init_ota();init_ps();init_pl();init_pt();init_ru();init_sl();init_sv();init_ta();init_th();init_tr();init_ua();init_uk();init_ur();init_uz();init_vi();init_zh_CN();init_zh_TW();init_yo()});class $ZodRegistry{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema,..._meta){let meta=_meta[0];if(this._map.set(schema,meta),meta&&typeof meta==="object"&&"id"in meta)this._idmap.set(meta.id,schema);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema){let meta=this._map.get(schema);if(meta&&typeof meta==="object"&&"id"in meta)this._idmap.delete(meta.id);return this._map.delete(schema),this}get(schema){let p=schema._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f={...pm,...this._map.get(schema)};return Object.keys(f).length?f:void 0}return this._map.get(schema)}has(schema){return this._map.has(schema)}}function registry(){return new $ZodRegistry}var _a,$output,$input,globalRegistry;var init_registries=__esm(()=>{$output=Symbol("ZodOutput"),$input=Symbol("ZodInput");(_a=globalThis).__zod_globalRegistry??(_a.__zod_globalRegistry=registry());globalRegistry=globalThis.__zod_globalRegistry});function _string(Class2,params){return new Class2({type:"string",...normalizeParams(params)})}function _coercedString(Class2,params){return new Class2({type:"string",coerce:!0,...normalizeParams(params)})}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _mac(Class2,params){return new Class2({type:"string",format:"mac",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(params)})}function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2({type:"number",checks:[],...normalizeParams(params)})}function _coercedNumber(Class2,params){return new Class2({type:"number",coerce:!0,checks:[],...normalizeParams(params)})}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(params)})}function _float32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float32",...normalizeParams(params)})}function _float64(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float64",...normalizeParams(params)})}function _int32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"int32",...normalizeParams(params)})}function _uint32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"uint32",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class2,params){return new Class2({type:"boolean",coerce:!0,...normalizeParams(params)})}function _bigint(Class2,params){return new Class2({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class2,params){return new Class2({type:"bigint",coerce:!0,...normalizeParams(params)})}function _int64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...normalizeParams(params)})}function _uint64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...normalizeParams(params)})}function _symbol(Class2,params){return new Class2({type:"symbol",...normalizeParams(params)})}function _undefined2(Class2,params){return new Class2({type:"undefined",...normalizeParams(params)})}function _null2(Class2,params){return new Class2({type:"null",...normalizeParams(params)})}function _any(Class2){return new Class2({type:"any"})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _void(Class2,params){return new Class2({type:"void",...normalizeParams(params)})}function _date(Class2,params){return new Class2({type:"date",...normalizeParams(params)})}function _coercedDate(Class2,params){return new Class2({type:"date",coerce:!0,...normalizeParams(params)})}function _nan(Class2,params){return new Class2({type:"nan",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!1})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!0})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!1})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!0})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite((input)=>input.normalize(form))}function _trim(){return _overwrite((input)=>input.trim())}function _toLowerCase(){return _overwrite((input)=>input.toLowerCase())}function _toUpperCase(){return _overwrite((input)=>input.toUpperCase())}function _slugify(){return _overwrite((input)=>slugify(input))}function _array(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _union(Class2,options,params){return new Class2({type:"union",options,...normalizeParams(params)})}function _xor(Class2,options,params){return new Class2({type:"union",options,inclusive:!1,...normalizeParams(params)})}function _discriminatedUnion(Class2,discriminator,options,params){return new Class2({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class2,left,right){return new Class2({type:"intersection",left,right})}function _tuple(Class2,items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType;return new Class2({type:"tuple",items,rest:hasRest?_paramsOrRest:null,...normalizeParams(hasRest?_params:_paramsOrRest)})}function _record(Class2,keyType,valueType,params){return new Class2({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class2,keyType,valueType,params){return new Class2({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class2,valueType,params){return new Class2({type:"set",valueType,...normalizeParams(params)})}function _enum(Class2,values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new Class2({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class2,entries,params){return new Class2({type:"enum",entries,...normalizeParams(params)})}function _literal(Class2,value,params){return new Class2({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function _file(Class2,params){return new Class2({type:"file",...normalizeParams(params)})}function _transform(Class2,fn2){return new Class2({type:"transform",transform:fn2})}function _optional(Class2,innerType){return new Class2({type:"optional",innerType})}function _nullable(Class2,innerType){return new Class2({type:"nullable",innerType})}function _default(Class2,innerType,defaultValue){return new Class2({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class2,innerType,params){return new Class2({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class2,innerType){return new Class2({type:"success",innerType})}function _catch(Class2,innerType,catchValue){return new Class2({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function _pipe(Class2,in_,out){return new Class2({type:"pipe",in:in_,out})}function _readonly(Class2,innerType){return new Class2({type:"readonly",innerType})}function _templateLiteral(Class2,parts,params){return new Class2({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class2,getter){return new Class2({type:"lazy",getter})}function _promise(Class2,innerType){return new Class2({type:"promise",innerType})}function _custom(Class2,fn2,_params){let norm=normalizeParams(_params);return norm.abort??(norm.abort=!0),new Class2({type:"custom",check:"custom",fn:fn2,...norm})}function _refine(Class2,fn2,_params){return new Class2({type:"custom",check:"custom",fn:fn2,...normalizeParams(_params)})}function _superRefine(fn2){let ch=_check((payload)=>{return payload.addIssue=(issue2)=>{if(typeof issue2==="string")payload.issues.push(issue(issue2,payload.value,ch._zod.def));else{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=ch),_issue.continue??(_issue.continue=!ch._zod.def.abort),payload.issues.push(issue(_issue))}},fn2(payload.value,payload)});return ch}function _check(fn2,params){let ch=new $ZodCheck({check:"custom",...normalizeParams(params)});return ch._zod.check=fn2,ch}function describe(description){let ch=new $ZodCheck({check:"describe"});return ch._zod.onattach=[(inst)=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}],ch._zod.check=()=>{},ch}function meta(metadata){let ch=new $ZodCheck({check:"meta"});return ch._zod.onattach=[(inst)=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}],ch._zod.check=()=>{},ch}function _stringbool(Classes,_params){let params=normalizeParams(_params),truthyArray=params.truthy??["true","1","yes","on","y","enabled"],falsyArray=params.falsy??["false","0","no","off","n","disabled"];if(params.case!=="sensitive")truthyArray=truthyArray.map((v)=>typeof v==="string"?v.toLowerCase():v),falsyArray=falsyArray.map((v)=>typeof v==="string"?v.toLowerCase():v);let truthySet=new Set(truthyArray),falsySet=new Set(falsyArray),_Codec=Classes.Codec??$ZodCodec,_Boolean=Classes.Boolean??$ZodBoolean,stringSchema=new(Classes.String??$ZodString)({type:"string",error:params.error}),booleanSchema=new _Boolean({type:"boolean",error:params.error}),codec=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:(input,payload)=>{let data=input;if(params.case!=="sensitive")data=data.toLowerCase();if(truthySet.has(data))return!0;else if(falsySet.has(data))return!1;else return payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec,continue:!1}),{}},reverseTransform:(input,_payload)=>{if(input===!0)return truthyArray[0]||"true";else return falsyArray[0]||"false"},error:params.error});return codec}function _stringFormat(Class2,format,fnOrRegex,_params={}){let params=normalizeParams(_params),def={...normalizeParams(_params),check:"string_format",type:"string",format,fn:typeof fnOrRegex==="function"?fnOrRegex:(val)=>fnOrRegex.test(val),...params};if(fnOrRegex instanceof RegExp)def.pattern=fnOrRegex;return new Class2(def)}var TimePrecision;var init_api=__esm(()=>{init_checks();init_registries();init_schemas();init_util();TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function initializeContext(params){let target=params?.target??"draft-2020-12";if(target==="draft-4")target="draft-04";if(target==="draft-7")target="draft-07";return{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,cycles:params?.cycles??"ref",reused:params?.reused??"inline",external:params?.external??void 0}}function process2(schema,ctx,_params={path:[],schemaPath:[]}){var _a2;let def=schema._zod.def,seen=ctx.seen.get(schema);if(seen){if(seen.count++,_params.schemaPath.includes(schema))seen.cycle=_params.path;return seen.schema}let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result);let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema)schema._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema,ctx,_json,params)}let parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;process2(parent,ctx,params),ctx.seen.get(parent).isParent=!0}}let meta2=ctx.metadataRegistry.get(schema);if(meta2)Object.assign(result.schema,meta2);if(ctx.io==="input"&&isTransforming(schema))delete result.schema.examples,delete result.schema.default;if(ctx.io==="input"&&result.schema._prefault)(_a2=result.schema).default??(_a2.default=result.schema._prefault);return delete result.schema._prefault,ctx.seen.get(schema).schema}function extractDefs(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry[0])throw Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id,entry[0])}}let makeURI=(entry)=>{let defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??((id2)=>id2);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${id}`}}if(entry[1]===root)return{ref:"#"};let defUriPrefix=`${"#"}/${defsSegment}/`,defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+defId}},extractToDef=(entry)=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);if(seen.def={...seen.schema},defId)seen.defId=defId;let schema2=seen.schema;for(let key in schema2)delete schema2[key];schema2.$ref=ref};if(ctx.cycles==="throw")for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
157
157
 
158
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry);continue}}}}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=(zodSchema)=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"))schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema);else Object.assign(schema2,refSchema);if(Object.assign(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached))delete schema2[key]}if(refSchema.$ref&&refSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key]))delete schema2[key]}}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){if(schema2.$ref=parentSeen.schema.$ref,parentSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key]))delete schema2[key]}}}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);let result={};if(ctx.target==="draft-2020-12")result.$schema="https://json-schema.org/draft/2020-12/schema";else if(ctx.target==="draft-07")result.$schema="http://json-schema.org/draft-07/schema#";else if(ctx.target==="draft-04")result.$schema="http://json-schema.org/draft-04/schema#";else if(ctx.target==="openapi-3.0");if(ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);let defs=ctx.external?.defs??{};for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.def&&seen.defId)defs[seen.defId]=seen.def}if(ctx.external);else if(Object.keys(defs).length>0)if(ctx.target==="draft-2020-12")result.$defs=defs;else result.definitions=defs;try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch(_err){throw Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;if(def.rest&&isTransforming(def.rest,ctx))return!0;return!1}return!1}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{let ctx=initializeContext({...params,processors});return process2(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return process2(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var init_to_json_schema=__esm(()=>{init_registries()});function toJSONSchema(input,params){if("_idmap"in input){let registry2=input,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema]=entry;process2(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema]=entry;extractDefs(ctx2,schema),schemas[key]=finalize(ctx2,schema)}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return process2(input,ctx),extractDefs(ctx,input),finalize(ctx,input)}var formatMap,stringProcessor=(schema,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){if(json.format=formatMap[format]??format,json.format==="")delete json.format;if(format==="time")delete json.format}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){let regexes=[...patterns];if(regexes.length===1)json.pattern=regexes[0].source;else if(regexes.length>1)json.allOf=[...regexes.map((regex)=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}},numberProcessor=(schema,ctx,_json,_params)=>{let json=_json,{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema._zod.bag;if(typeof format==="string"&&format.includes("int"))json.type="integer";else json.type="number";if(typeof exclusiveMinimum==="number")if(ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0;else json.exclusiveMinimum=exclusiveMinimum;if(typeof minimum==="number"){if(json.minimum=minimum,typeof exclusiveMinimum==="number"&&ctx.target!=="draft-04")if(exclusiveMinimum>=minimum)delete json.minimum;else delete json.exclusiveMinimum}if(typeof exclusiveMaximum==="number")if(ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0;else json.exclusiveMaximum=exclusiveMaximum;if(typeof maximum==="number"){if(json.maximum=maximum,typeof exclusiveMaximum==="number"&&ctx.target!=="draft-04")if(exclusiveMaximum<=maximum)delete json.maximum;else delete json.exclusiveMaximum}if(typeof multipleOf==="number")json.multipleOf=multipleOf},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0")json.type="string",json.nullable=!0,json.enum=[null];else json.type="null"},undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json,_params)=>{let def=schema._zod.def,values=getEnumValues(def.entries);if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values},literalProcessor=(schema,ctx,json,_params)=>{let def=schema._zod.def,vals=[];for(let val of def.values)if(val===void 0){if(ctx.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof val==="bigint")if(ctx.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else vals.push(Number(val));else vals.push(val);if(vals.length===0);else if(vals.length===1){let val=vals[0];if(json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.enum=[val];else json.const=val}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}},nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json,_params)=>{let _json=json,pattern=schema._zod.pattern;if(!pattern)throw Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json,_params)=>{let _json=json,file={type:"string",format:"binary",contentEncoding:"binary"},{minimum,maximum,mime}=schema._zod.bag;if(minimum!==void 0)file.minLength=minimum;if(maximum!==void 0)file.maxLength=maximum;if(mime)if(mime.length===1)file.contentMediaType=mime[0],Object.assign(_json,file);else Object.assign(_json,file),_json.anyOf=mime.map((m)=>({contentMediaType:m}));else Object.assign(_json,file)},successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array",json.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})},objectProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object",json.properties={};let shape=def.shape;for(let key in shape)json.properties[key]=process2(shape[key],ctx,{...params,path:[...params.path,"properties",key]});let allKeys=new Set(Object.keys(shape)),requiredKeys=new Set([...allKeys].filter((key)=>{let v=def.shape[key]._zod;if(ctx.io==="input")return v.optin===void 0;else return v.optout===void 0}));if(requiredKeys.size>0)json.required=Array.from(requiredKeys);if(def.catchall?._zod.def.type==="never")json.additionalProperties=!1;else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=!1}else if(def.catchall)json.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive)json.oneOf=options;else json.anyOf=options},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf},tupleProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?process2(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;if(ctx.target==="draft-2020-12"){if(json.prefixItems=prefixItems,rest)json.items=rest}else if(ctx.target==="openapi-3.0"){if(json.items={anyOf:prefixItems},rest)json.items.anyOf.push(rest);if(json.minItems=prefixItems.length,!rest)json.maxItems=prefixItems.length}else if(json.items=prefixItems,rest)json.additionalItems=rest;let{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum},recordProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object";let keyType=def.keyType,patterns=keyType._zod.bag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let pattern of patterns)json.patternProperties[pattern.source]=valueSchema}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12")json.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});json.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values;if(keyValues){let validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0)json.required=validKeyValues}},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=process2(def.innerType,ctx,params),seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0")seen.ref=def.innerType,json.nullable=!0;else json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.default=JSON.parse(JSON.stringify(def.defaultValue))},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io==="input")json._prefault=JSON.parse(JSON.stringify(def.defaultValue))},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,innerType=ctx.io==="input"?def.in._zod.def.type==="transform"?def.out:def.in:def.out;process2(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;process2(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors;var init_json_schema_processors=__esm(()=>{init_to_json_schema();init_util();formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}});class JSONSchemaGenerator{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return process2(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_,...plainResult}=result;return plainResult}}var init_json_schema_generator=__esm(()=>{init_json_schema_processors();init_to_json_schema()});var exports_json_schema={};var init_json_schema=()=>{};var exports_core2={};__export(exports_core2,{version:()=>version,util:()=>exports_util,treeifyError:()=>treeifyError,toJSONSchema:()=>toJSONSchema,toDotPath:()=>toDotPath,safeParseAsync:()=>safeParseAsync,safeParse:()=>safeParse,safeEncodeAsync:()=>safeEncodeAsync,safeEncode:()=>safeEncode,safeDecodeAsync:()=>safeDecodeAsync,safeDecode:()=>safeDecode,registry:()=>registry,regexes:()=>exports_regexes,process:()=>process2,prettifyError:()=>prettifyError,parseAsync:()=>parseAsync,parse:()=>parse,meta:()=>meta,locales:()=>exports_locales,isValidJWT:()=>isValidJWT,isValidBase64URL:()=>isValidBase64URL,isValidBase64:()=>isValidBase64,initializeContext:()=>initializeContext,globalRegistry:()=>globalRegistry,globalConfig:()=>globalConfig,formatError:()=>formatError,flattenError:()=>flattenError,finalize:()=>finalize,extractDefs:()=>extractDefs,encodeAsync:()=>encodeAsync,encode:()=>encode,describe:()=>describe,decodeAsync:()=>decodeAsync,decode:()=>decode,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,config:()=>config,clone:()=>clone,_xor:()=>_xor,_xid:()=>_xid,_void:()=>_void,_uuidv7:()=>_uuidv7,_uuidv6:()=>_uuidv6,_uuidv4:()=>_uuidv4,_uuid:()=>_uuid,_url:()=>_url,_uppercase:()=>_uppercase,_unknown:()=>_unknown,_union:()=>_union,_undefined:()=>_undefined2,_ulid:()=>_ulid,_uint64:()=>_uint64,_uint32:()=>_uint32,_tuple:()=>_tuple,_trim:()=>_trim,_transform:()=>_transform,_toUpperCase:()=>_toUpperCase,_toLowerCase:()=>_toLowerCase,_templateLiteral:()=>_templateLiteral,_symbol:()=>_symbol,_superRefine:()=>_superRefine,_success:()=>_success,_stringbool:()=>_stringbool,_stringFormat:()=>_stringFormat,_string:()=>_string,_startsWith:()=>_startsWith,_slugify:()=>_slugify,_size:()=>_size,_set:()=>_set,_safeParseAsync:()=>_safeParseAsync,_safeParse:()=>_safeParse,_safeEncodeAsync:()=>_safeEncodeAsync,_safeEncode:()=>_safeEncode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeDecode:()=>_safeDecode,_regex:()=>_regex,_refine:()=>_refine,_record:()=>_record,_readonly:()=>_readonly,_property:()=>_property,_promise:()=>_promise,_positive:()=>_positive,_pipe:()=>_pipe,_parseAsync:()=>_parseAsync,_parse:()=>_parse,_overwrite:()=>_overwrite,_optional:()=>_optional,_number:()=>_number,_nullable:()=>_nullable,_null:()=>_null2,_normalize:()=>_normalize,_nonpositive:()=>_nonpositive,_nonoptional:()=>_nonoptional,_nonnegative:()=>_nonnegative,_never:()=>_never,_negative:()=>_negative,_nativeEnum:()=>_nativeEnum,_nanoid:()=>_nanoid,_nan:()=>_nan,_multipleOf:()=>_multipleOf,_minSize:()=>_minSize,_minLength:()=>_minLength,_min:()=>_gte,_mime:()=>_mime,_maxSize:()=>_maxSize,_maxLength:()=>_maxLength,_max:()=>_lte,_map:()=>_map,_mac:()=>_mac,_lte:()=>_lte,_lt:()=>_lt,_lowercase:()=>_lowercase,_literal:()=>_literal,_length:()=>_length,_lazy:()=>_lazy,_ksuid:()=>_ksuid,_jwt:()=>_jwt,_isoTime:()=>_isoTime,_isoDuration:()=>_isoDuration,_isoDateTime:()=>_isoDateTime,_isoDate:()=>_isoDate,_ipv6:()=>_ipv6,_ipv4:()=>_ipv4,_intersection:()=>_intersection,_int64:()=>_int64,_int32:()=>_int32,_int:()=>_int,_includes:()=>_includes,_guid:()=>_guid,_gte:()=>_gte,_gt:()=>_gt,_float64:()=>_float64,_float32:()=>_float32,_file:()=>_file,_enum:()=>_enum,_endsWith:()=>_endsWith,_encodeAsync:()=>_encodeAsync,_encode:()=>_encode,_emoji:()=>_emoji2,_email:()=>_email,_e164:()=>_e164,_discriminatedUnion:()=>_discriminatedUnion,_default:()=>_default,_decodeAsync:()=>_decodeAsync,_decode:()=>_decode,_date:()=>_date,_custom:()=>_custom,_cuid2:()=>_cuid2,_cuid:()=>_cuid,_coercedString:()=>_coercedString,_coercedNumber:()=>_coercedNumber,_coercedDate:()=>_coercedDate,_coercedBoolean:()=>_coercedBoolean,_coercedBigint:()=>_coercedBigint,_cidrv6:()=>_cidrv6,_cidrv4:()=>_cidrv4,_check:()=>_check,_catch:()=>_catch,_boolean:()=>_boolean,_bigint:()=>_bigint,_base64url:()=>_base64url,_base64:()=>_base64,_array:()=>_array,_any:()=>_any,TimePrecision:()=>TimePrecision,NEVER:()=>NEVER,JSONSchemaGenerator:()=>JSONSchemaGenerator,JSONSchema:()=>exports_json_schema,Doc:()=>Doc,$output:()=>$output,$input:()=>$input,$constructor:()=>$constructor,$brand:()=>$brand,$ZodXor:()=>$ZodXor,$ZodXID:()=>$ZodXID,$ZodVoid:()=>$ZodVoid,$ZodUnknown:()=>$ZodUnknown,$ZodUnion:()=>$ZodUnion,$ZodUndefined:()=>$ZodUndefined,$ZodUUID:()=>$ZodUUID,$ZodURL:()=>$ZodURL,$ZodULID:()=>$ZodULID,$ZodType:()=>$ZodType,$ZodTuple:()=>$ZodTuple,$ZodTransform:()=>$ZodTransform,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodSymbol:()=>$ZodSymbol,$ZodSuccess:()=>$ZodSuccess,$ZodStringFormat:()=>$ZodStringFormat,$ZodString:()=>$ZodString,$ZodSet:()=>$ZodSet,$ZodRegistry:()=>$ZodRegistry,$ZodRecord:()=>$ZodRecord,$ZodRealError:()=>$ZodRealError,$ZodReadonly:()=>$ZodReadonly,$ZodPromise:()=>$ZodPromise,$ZodPrefault:()=>$ZodPrefault,$ZodPipe:()=>$ZodPipe,$ZodOptional:()=>$ZodOptional,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodObject:()=>$ZodObject,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodNumber:()=>$ZodNumber,$ZodNullable:()=>$ZodNullable,$ZodNull:()=>$ZodNull,$ZodNonOptional:()=>$ZodNonOptional,$ZodNever:()=>$ZodNever,$ZodNanoID:()=>$ZodNanoID,$ZodNaN:()=>$ZodNaN,$ZodMap:()=>$ZodMap,$ZodMAC:()=>$ZodMAC,$ZodLiteral:()=>$ZodLiteral,$ZodLazy:()=>$ZodLazy,$ZodKSUID:()=>$ZodKSUID,$ZodJWT:()=>$ZodJWT,$ZodIntersection:()=>$ZodIntersection,$ZodISOTime:()=>$ZodISOTime,$ZodISODuration:()=>$ZodISODuration,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODate:()=>$ZodISODate,$ZodIPv6:()=>$ZodIPv6,$ZodIPv4:()=>$ZodIPv4,$ZodGUID:()=>$ZodGUID,$ZodFunction:()=>$ZodFunction,$ZodFile:()=>$ZodFile,$ZodExactOptional:()=>$ZodExactOptional,$ZodError:()=>$ZodError,$ZodEnum:()=>$ZodEnum,$ZodEncodeError:()=>$ZodEncodeError,$ZodEmoji:()=>$ZodEmoji,$ZodEmail:()=>$ZodEmail,$ZodE164:()=>$ZodE164,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodDefault:()=>$ZodDefault,$ZodDate:()=>$ZodDate,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodCustom:()=>$ZodCustom,$ZodCodec:()=>$ZodCodec,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheck:()=>$ZodCheck,$ZodCatch:()=>$ZodCatch,$ZodCUID2:()=>$ZodCUID2,$ZodCUID:()=>$ZodCUID,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodBoolean:()=>$ZodBoolean,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBigInt:()=>$ZodBigInt,$ZodBase64URL:()=>$ZodBase64URL,$ZodBase64:()=>$ZodBase64,$ZodAsyncError:()=>$ZodAsyncError,$ZodArray:()=>$ZodArray,$ZodAny:()=>$ZodAny});var init_core2=__esm(()=>{init_util();init_regexes();init_locales();init_json_schema_processors();init_json_schema_generator();init_json_schema();init_core();init_parse();init_errors();init_schemas();init_checks();init_versions();init_registries();init_api();init_to_json_schema()});var exports_checks2={};__export(exports_checks2,{uppercase:()=>_uppercase,trim:()=>_trim,toUpperCase:()=>_toUpperCase,toLowerCase:()=>_toLowerCase,startsWith:()=>_startsWith,slugify:()=>_slugify,size:()=>_size,regex:()=>_regex,property:()=>_property,positive:()=>_positive,overwrite:()=>_overwrite,normalize:()=>_normalize,nonpositive:()=>_nonpositive,nonnegative:()=>_nonnegative,negative:()=>_negative,multipleOf:()=>_multipleOf,minSize:()=>_minSize,minLength:()=>_minLength,mime:()=>_mime,maxSize:()=>_maxSize,maxLength:()=>_maxLength,lte:()=>_lte,lt:()=>_lt,lowercase:()=>_lowercase,length:()=>_length,includes:()=>_includes,gte:()=>_gte,gt:()=>_gt,endsWith:()=>_endsWith});var init_checks2=__esm(()=>{init_core2()});var exports_iso={};__export(exports_iso,{time:()=>time2,duration:()=>duration2,datetime:()=>datetime2,date:()=>date2,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration;var init_iso=__esm(()=>{init_core2();init_schemas2();ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)})});var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:(mapper)=>formatError(inst,mapper)},flatten:{value:(mapper)=>flattenError(inst,mapper)},addIssue:{value:(issue2)=>{inst.issues.push(issue2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:(issues2)=>{inst.issues.push(...issues2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})},ZodError,ZodRealError;var init_errors2=__esm(()=>{init_core2();init_core2();init_util();ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,{Parent:Error})});var parse3,parseAsync2,safeParse2,safeParseAsync2,encode2,decode2,encodeAsync2,decodeAsync2,safeEncode2,safeDecode2,safeEncodeAsync2,safeDecodeAsync2;var init_parse2=__esm(()=>{init_core2();init_errors2();parse3=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError)});var exports_schemas2={};__export(exports_schemas2,{xor:()=>xor,xid:()=>xid2,void:()=>_void2,uuidv7:()=>uuidv7,uuidv6:()=>uuidv6,uuidv4:()=>uuidv4,uuid:()=>uuid2,url:()=>url,unknown:()=>unknown,union:()=>union,undefined:()=>_undefined3,ulid:()=>ulid2,uint64:()=>uint64,uint32:()=>uint32,tuple:()=>tuple,transform:()=>transform,templateLiteral:()=>templateLiteral,symbol:()=>symbol,superRefine:()=>superRefine,success:()=>success,stringbool:()=>stringbool,stringFormat:()=>stringFormat,string:()=>string2,strictObject:()=>strictObject,set:()=>set,refine:()=>refine,record:()=>record,readonly:()=>readonly,promise:()=>promise,preprocess:()=>preprocess,prefault:()=>prefault,pipe:()=>pipe,partialRecord:()=>partialRecord,optional:()=>optional,object:()=>object,number:()=>number2,nullish:()=>nullish2,nullable:()=>nullable,null:()=>_null3,nonoptional:()=>nonoptional,never:()=>never,nativeEnum:()=>nativeEnum,nanoid:()=>nanoid2,nan:()=>nan,meta:()=>meta2,map:()=>map,mac:()=>mac2,looseRecord:()=>looseRecord,looseObject:()=>looseObject,literal:()=>literal,lazy:()=>lazy,ksuid:()=>ksuid2,keyof:()=>keyof,jwt:()=>jwt,json:()=>json,ipv6:()=>ipv62,ipv4:()=>ipv42,intersection:()=>intersection,int64:()=>int64,int32:()=>int32,int:()=>int,instanceof:()=>_instanceof,httpUrl:()=>httpUrl,hostname:()=>hostname2,hex:()=>hex2,hash:()=>hash,guid:()=>guid2,function:()=>_function,float64:()=>float64,float32:()=>float32,file:()=>file,exactOptional:()=>exactOptional,enum:()=>_enum2,emoji:()=>emoji2,email:()=>email2,e164:()=>e1642,discriminatedUnion:()=>discriminatedUnion,describe:()=>describe2,date:()=>date3,custom:()=>custom,cuid2:()=>cuid22,cuid:()=>cuid3,codec:()=>codec,cidrv6:()=>cidrv62,cidrv4:()=>cidrv42,check:()=>check,catch:()=>_catch2,boolean:()=>boolean2,bigint:()=>bigint2,base64url:()=>base64url2,base64:()=>base642,array:()=>array,any:()=>any,_function:()=>_function,_default:()=>_default2,_ZodString:()=>_ZodString,ZodXor:()=>ZodXor,ZodXID:()=>ZodXID,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodUUID:()=>ZodUUID,ZodURL:()=>ZodURL,ZodULID:()=>ZodULID,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransform:()=>ZodTransform,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodSymbol:()=>ZodSymbol,ZodSuccess:()=>ZodSuccess,ZodStringFormat:()=>ZodStringFormat,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodRecord:()=>ZodRecord,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPrefault:()=>ZodPrefault,ZodPipe:()=>ZodPipe,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumberFormat:()=>ZodNumberFormat,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNonOptional:()=>ZodNonOptional,ZodNever:()=>ZodNever,ZodNanoID:()=>ZodNanoID,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodMAC:()=>ZodMAC,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodKSUID:()=>ZodKSUID,ZodJWT:()=>ZodJWT,ZodIntersection:()=>ZodIntersection,ZodIPv6:()=>ZodIPv6,ZodIPv4:()=>ZodIPv4,ZodGUID:()=>ZodGUID,ZodFunction:()=>ZodFunction,ZodFile:()=>ZodFile,ZodExactOptional:()=>ZodExactOptional,ZodEnum:()=>ZodEnum,ZodEmoji:()=>ZodEmoji,ZodEmail:()=>ZodEmail,ZodE164:()=>ZodE164,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodCustom:()=>ZodCustom,ZodCodec:()=>ZodCodec,ZodCatch:()=>ZodCatch,ZodCUID2:()=>ZodCUID2,ZodCUID:()=>ZodCUID,ZodCIDRv6:()=>ZodCIDRv6,ZodCIDRv4:()=>ZodCIDRv4,ZodBoolean:()=>ZodBoolean,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBigInt:()=>ZodBigInt,ZodBase64URL:()=>ZodBase64URL,ZodBase64:()=>ZodBase64,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny});function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function guid2(params){return _guid(ZodGUID,params)}function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:/^https?$/,hostname:exports_regexes.domain,...exports_util.normalizeParams(params)})}function emoji2(params){return _emoji2(ZodEmoji,params)}function nanoid2(params){return _nanoid(ZodNanoID,params)}function cuid3(params){return _cuid(ZodCUID,params)}function cuid22(params){return _cuid2(ZodCUID2,params)}function ulid2(params){return _ulid(ZodULID,params)}function xid2(params){return _xid(ZodXID,params)}function ksuid2(params){return _ksuid(ZodKSUID,params)}function ipv42(params){return _ipv4(ZodIPv4,params)}function mac2(params){return _mac(ZodMAC,params)}function ipv62(params){return _ipv6(ZodIPv6,params)}function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}function base642(params){return _base64(ZodBase64,params)}function base64url2(params){return _base64url(ZodBase64URL,params)}function e1642(params){return _e164(ZodE164,params)}function jwt(params){return _jwt(ZodJWT,params)}function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",exports_regexes.hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",exports_regexes.hex,_params)}function hash(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=exports_regexes[format];if(!regex)throw Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function bigint2(params){return _bigint(ZodBigInt,params)}function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}function symbol(params){return _symbol(ZodSymbol,params)}function _undefined3(params){return _undefined2(ZodUndefined,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function _void2(params){return _void(ZodVoid,params)}function date3(params){return _date(ZodDate,params)}function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}function object(shape,params){let def={type:"object",shape:shape??{},...exports_util.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...exports_util.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...exports_util.normalizeParams(params)})}function union(options,params){return new ZodUnion({type:"union",options,...exports_util.normalizeParams(params)})}function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...exports_util.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...exports_util.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest;return new ZodTuple({type:"tuple",items,rest:hasRest?_paramsOrRest:null,...exports_util.normalizeParams(params)})}function record(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...exports_util.normalizeParams(params)})}function partialRecord(keyType,valueType,params){let k=clone(keyType);return k._zod.values=void 0,new ZodRecord({type:"record",keyType:k,valueType,...exports_util.normalizeParams(params)})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...exports_util.normalizeParams(params)})}function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...exports_util.normalizeParams(params)})}function set(valueType,params){return new ZodSet({type:"set",valueType,...exports_util.normalizeParams(params)})}function _enum2(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...exports_util.normalizeParams(params)})}function file(params){return _file(ZodFile,params)}function transform(fn2){return new ZodTransform({type:"transform",transform:fn2})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...exports_util.normalizeParams(params)})}function success(innerType){return new ZodSuccess({type:"success",innerType})}function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function nan(params){return _nan(ZodNaN,params)}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...exports_util.normalizeParams(params)})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function promise(innerType){return new ZodPromise({type:"promise",innerType})}function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}function check(fn2){let ch=new $ZodCheck({check:"custom"});return ch._zod.check=fn2,ch}function custom(fn2,_params){return _custom(ZodCustom,fn2??(()=>!0),_params)}function refine(fn2,_params={}){return _refine(ZodCustom,fn2,_params)}function superRefine(fn2){return _superRefine(fn2)}function _instanceof(cls,params={}){let inst=new ZodCustom({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:!0,...exports_util.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=(payload)=>{if(!(payload.value instanceof cls))payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}function json(params){let jsonSchema=lazy(()=>{return union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn2,schema){return pipe(transform(fn2),schema)}var ZodType,_ZodString,ZodString,ZodStringFormat,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodMAC,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodJWT,ZodCustomStringFormat,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodBigIntFormat,ZodSymbol,ZodUndefined,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodVoid,ZodDate,ZodArray,ZodObject,ZodUnion,ZodXor,ZodDiscriminatedUnion,ZodIntersection,ZodTuple,ZodRecord,ZodMap,ZodSet,ZodEnum,ZodLiteral,ZodFile,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodSuccess,ZodCatch,ZodNaN,ZodPipe,ZodCodec,ZodReadonly,ZodTemplateLiteral,ZodLazy,ZodPromise,ZodFunction,ZodCustom,describe2,meta2,stringbool=(...args2)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args2);var init_schemas2=__esm(()=>{init_core2();init_core2();init_json_schema_processors();init_to_json_schema();init_checks2();init_iso();init_parse2();ZodType=$constructor("ZodType",(inst,def)=>{return $ZodType.init(inst,def),Object.assign(inst["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,"input"),output:createStandardJSONSchemaMethod(inst,"output")}}),inst.toJSONSchema=createToJSONSchemaMethod(inst,{}),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.check=(...checks2)=>{return inst.clone(exports_util.mergeDefs(def,{checks:[...def.checks??[],...checks2.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},inst.with=inst.check,inst.clone=(def2,params)=>clone(inst,def2,params),inst.brand=()=>inst,inst.register=(reg,meta2)=>{return reg.add(inst,meta2),inst},inst.parse=(data,params)=>parse3(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse2(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync2(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync2(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode2(inst,data,params),inst.decode=(data,params)=>decode2(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync2(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync2(inst,data,params),inst.safeEncode=(data,params)=>safeEncode2(inst,data,params),inst.safeDecode=(data,params)=>safeDecode2(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync2(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync2(inst,data,params),inst.refine=(check,params)=>inst.check(refine(check,params)),inst.superRefine=(refinement)=>inst.check(superRefine(refinement)),inst.overwrite=(fn2)=>inst.check(_overwrite(fn2)),inst.optional=()=>optional(inst),inst.exactOptional=()=>exactOptional(inst),inst.nullable=()=>nullable(inst),inst.nullish=()=>optional(nullable(inst)),inst.nonoptional=(params)=>nonoptional(inst,params),inst.array=()=>array(inst),inst.or=(arg)=>union([inst,arg]),inst.and=(arg)=>intersection(inst,arg),inst.transform=(tx)=>pipe(inst,transform(tx)),inst.default=(def2)=>_default2(inst,def2),inst.prefault=(def2)=>prefault(inst,def2),inst.catch=(params)=>_catch2(inst,params),inst.pipe=(target)=>pipe(inst,target),inst.readonly=()=>readonly(inst),inst.describe=(description)=>{let cl=inst.clone();return globalRegistry.add(cl,{description}),cl},Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst.meta=(...args2)=>{if(args2.length===0)return globalRegistry.get(inst);let cl=inst.clone();return globalRegistry.add(cl,args2[0]),cl},inst.isOptional=()=>inst.safeParse(void 0).success,inst.isNullable=()=>inst.safeParse(null).success,inst.apply=(fn2)=>fn2(inst),inst}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,inst.regex=(...args2)=>inst.check(_regex(...args2)),inst.includes=(...args2)=>inst.check(_includes(...args2)),inst.startsWith=(...args2)=>inst.check(_startsWith(...args2)),inst.endsWith=(...args2)=>inst.check(_endsWith(...args2)),inst.min=(...args2)=>inst.check(_minLength(...args2)),inst.max=(...args2)=>inst.check(_maxLength(...args2)),inst.length=(...args2)=>inst.check(_length(...args2)),inst.nonempty=(...args2)=>inst.check(_minLength(1,...args2)),inst.lowercase=(params)=>inst.check(_lowercase(params)),inst.uppercase=(params)=>inst.check(_uppercase(params)),inst.trim=()=>inst.check(_trim()),inst.normalize=(...args2)=>inst.check(_normalize(...args2)),inst.toLowerCase=()=>inst.check(_toLowerCase()),inst.toUpperCase=()=>inst.check(_toUpperCase()),inst.slugify=()=>inst.check(_slugify())}),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=(params)=>inst.check(_email(ZodEmail,params)),inst.url=(params)=>inst.check(_url(ZodURL,params)),inst.jwt=(params)=>inst.check(_jwt(ZodJWT,params)),inst.emoji=(params)=>inst.check(_emoji2(ZodEmoji,params)),inst.guid=(params)=>inst.check(_guid(ZodGUID,params)),inst.uuid=(params)=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=(params)=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=(params)=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=(params)=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=(params)=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=(params)=>inst.check(_guid(ZodGUID,params)),inst.cuid=(params)=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=(params)=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=(params)=>inst.check(_ulid(ZodULID,params)),inst.base64=(params)=>inst.check(_base64(ZodBase64,params)),inst.base64url=(params)=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=(params)=>inst.check(_xid(ZodXID,params)),inst.ksuid=(params)=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=(params)=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=(params)=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=(params)=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=(params)=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=(params)=>inst.check(_e164(ZodE164,params)),inst.datetime=(params)=>inst.check(datetime2(params)),inst.date=(params)=>inst.check(date2(params)),inst.time=(params)=>inst.check(time2(params)),inst.duration=(params)=>inst.check(duration2(params))});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.int=(params)=>inst.check(int(params)),inst.safe=(params)=>inst.check(int(params)),inst.positive=(params)=>inst.check(_gt(0,params)),inst.nonnegative=(params)=>inst.check(_gte(0,params)),inst.negative=(params)=>inst.check(_lt(0,params)),inst.nonpositive=(params)=>inst.check(_lte(0,params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params)),inst.step=(value,params)=>inst.check(_multipleOf(value,params)),inst.finite=()=>inst;let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??0.5),inst.isFinite=!0,inst.format=bag.format??null});ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>bigintProcessor(inst,ctx,json,params),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.positive=(params)=>inst.check(_gt(BigInt(0),params)),inst.negative=(params)=>inst.check(_lt(BigInt(0),params)),inst.nonpositive=(params)=>inst.check(_lte(BigInt(0),params)),inst.nonnegative=(params)=>inst.check(_gte(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null});ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>symbolProcessor(inst,ctx,json,params)});ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>undefinedProcessor(inst,ctx,json,params)});ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>anyProcessor(inst,ctx,json,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>voidProcessor(inst,ctx,json,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>dateProcessor(inst,ctx,json,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null});ZodArray=$constructor("ZodArray",(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element,inst.min=(minLength,params)=>inst.check(_minLength(minLength,params)),inst.nonempty=(params)=>inst.check(_minLength(1,params)),inst.max=(maxLength,params)=>inst.check(_maxLength(maxLength,params)),inst.length=(len,params)=>inst.check(_length(len,params)),inst.unwrap=()=>inst.element});ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),exports_util.defineLazy(inst,"shape",()=>{return def.shape}),inst.keyof=()=>_enum2(Object.keys(inst._zod.def.shape)),inst.catchall=(catchall)=>inst.clone({...inst._zod.def,catchall}),inst.passthrough=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.loose=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.strict=()=>inst.clone({...inst._zod.def,catchall:never()}),inst.strip=()=>inst.clone({...inst._zod.def,catchall:void 0}),inst.extend=(incoming)=>{return exports_util.extend(inst,incoming)},inst.safeExtend=(incoming)=>{return exports_util.safeExtend(inst,incoming)},inst.merge=(other)=>exports_util.merge(inst,other),inst.pick=(mask)=>exports_util.pick(inst,mask),inst.omit=(mask)=>exports_util.omit(inst,mask),inst.partial=(...args2)=>exports_util.partial(ZodOptional,inst,args2[0]),inst.required=(...args2)=>exports_util.required(ZodNonOptional,inst,args2[0])});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});ZodTuple=$constructor("ZodTuple",(inst,def)=>{$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>tupleProcessor(inst,ctx,json,params),inst.rest=(rest)=>inst.clone({...inst._zod.def,rest})});ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodMap=$constructor("ZodMap",(inst,def)=>{$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>mapProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args2)=>inst.check(_minSize(...args2)),inst.nonempty=(params)=>inst.check(_minSize(1,params)),inst.max=(...args2)=>inst.check(_maxSize(...args2)),inst.size=(...args2)=>inst.check(_size(...args2))});ZodSet=$constructor("ZodSet",(inst,def)=>{$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>setProcessor(inst,ctx,json,params),inst.min=(...args2)=>inst.check(_minSize(...args2)),inst.nonempty=(params)=>inst.check(_minSize(1,params)),inst.max=(...args2)=>inst.check(_maxSize(...args2)),inst.size=(...args2)=>inst.check(_size(...args2))});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>fileProcessor(inst,ctx,json,params),inst.min=(size,params)=>inst.check(_minSize(size,params)),inst.max=(size,params)=>inst.check(_maxSize(size,params)),inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});ZodTransform=$constructor("ZodTransform",(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=(issue2)=>{if(typeof issue2==="string")payload.issues.push(exports_util.issue(issue2,payload.value,def));else{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(exports_util.issue(_issue))}};let output=def.transform(payload.value,payload);if(output instanceof Promise)return output.then((output2)=>{return payload.value=output2,payload});return payload.value=output,payload}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>successProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nanProcessor(inst,ctx,json,params)});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>templateLiteralProcessor(inst,ctx,json,params)});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>lazyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.getter()});ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>promiseProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>functionProcessor(inst,ctx,json,params)});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});describe2=describe,meta2=meta});function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodIssueCode,ZodFirstPartyTypeKind;var init_compat=__esm(()=>{init_core2();ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(ZodFirstPartyTypeKind2){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}))});function detectVersion(schema,defaultTarget){let $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if($schema==="http://json-schema.org/draft-07/schema#")return"draft-7";if($schema==="http://json-schema.org/draft-04/schema#")return"draft-4";return defaultTarget??"draft-2020-12"}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let path=ref.slice(1).split("/").filter(Boolean);if(path.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){let key=path[1];if(!key||!ctx.defs[key])throw Error(`Reference not found: ${ref}`);return ctx.defs[key]}throw Error(`Reference not found: ${ref}`)}function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0)return z.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z.lazy(()=>{if(!ctx.refs.has(refPath))throw Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z.null();if(enumValues.length===0)return z.never();if(enumValues.length===1)return z.literal(enumValues[0]);if(enumValues.every((v)=>typeof v==="string"))return z.enum(enumValues);let literalSchemas=enumValues.map((v)=>z.literal(v));if(literalSchemas.length<2)return literalSchemas[0];return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z.literal(schema.const);let type=schema.type;if(Array.isArray(type)){let typeSchemas=type.map((t)=>{let typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0)return z.never();if(typeSchemas.length===1)return typeSchemas[0];return z.union(typeSchemas)}if(!type)return z.any();let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){let format=schema.format;if(format==="email")stringSchema=stringSchema.check(z.email());else if(format==="uri"||format==="uri-reference")stringSchema=stringSchema.check(z.url());else if(format==="uuid"||format==="guid")stringSchema=stringSchema.check(z.uuid());else if(format==="date-time")stringSchema=stringSchema.check(z.iso.datetime());else if(format==="date")stringSchema=stringSchema.check(z.iso.date());else if(format==="time")stringSchema=stringSchema.check(z.iso.time());else if(format==="duration")stringSchema=stringSchema.check(z.iso.duration());else if(format==="ipv4")stringSchema=stringSchema.check(z.ipv4());else if(format==="ipv6")stringSchema=stringSchema.check(z.ipv6());else if(format==="mac")stringSchema=stringSchema.check(z.mac());else if(format==="cidr")stringSchema=stringSchema.check(z.cidrv4());else if(format==="cidr-v6")stringSchema=stringSchema.check(z.cidrv6());else if(format==="base64")stringSchema=stringSchema.check(z.base64());else if(format==="base64url")stringSchema=stringSchema.check(z.base64url());else if(format==="e164")stringSchema=stringSchema.check(z.e164());else if(format==="jwt")stringSchema=stringSchema.check(z.jwt());else if(format==="emoji")stringSchema=stringSchema.check(z.emoji());else if(format==="nanoid")stringSchema=stringSchema.check(z.nanoid());else if(format==="cuid")stringSchema=stringSchema.check(z.cuid());else if(format==="cuid2")stringSchema=stringSchema.check(z.cuid2());else if(format==="ulid")stringSchema=stringSchema.check(z.ulid());else if(format==="xid")stringSchema=stringSchema.check(z.xid());else if(format==="ksuid")stringSchema=stringSchema.check(z.ksuid())}if(typeof schema.minLength==="number")stringSchema=stringSchema.min(schema.minLength);if(typeof schema.maxLength==="number")stringSchema=stringSchema.max(schema.maxLength);if(schema.pattern)stringSchema=stringSchema.regex(new RegExp(schema.pattern));zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number")numberSchema=numberSchema.min(schema.minimum);if(typeof schema.maximum==="number")numberSchema=numberSchema.max(schema.maximum);if(typeof schema.exclusiveMinimum==="number")numberSchema=numberSchema.gt(schema.exclusiveMinimum);else if(schema.exclusiveMinimum===!0&&typeof schema.minimum==="number")numberSchema=numberSchema.gt(schema.minimum);if(typeof schema.exclusiveMaximum==="number")numberSchema=numberSchema.lt(schema.exclusiveMaximum);else if(schema.exclusiveMaximum===!0&&typeof schema.maximum==="number")numberSchema=numberSchema.lt(schema.maximum);if(typeof schema.multipleOf==="number")numberSchema=numberSchema.multipleOf(schema.multipleOf);zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{let shape={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]);for(let[key,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);shape[key]=requiredSet.has(key)?propZodSchema:propZodSchema.optional()}if(schema.propertyNames){let keySchema=convertSchema(schema.propertyNames,ctx),valueSchema=schema.additionalProperties&&typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):z.any();if(Object.keys(shape).length===0){zodSchema=z.record(keySchema,valueSchema);break}let objectSchema2=z.object(shape).passthrough(),recordSchema=z.looseRecord(keySchema,valueSchema);zodSchema=z.intersection(objectSchema2,recordSchema);break}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape).length>0)schemasToIntersect.push(z.object(shape).passthrough());if(schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++)result=z.intersection(result,schemasToIntersect[i]);zodSchema=result}break}let objectSchema=z.object(shape);if(schema.additionalProperties===!1)zodSchema=objectSchema.strict();else if(typeof schema.additionalProperties==="object")zodSchema=objectSchema.catchall(convertSchema(schema.additionalProperties,ctx));else zodSchema=objectSchema.passthrough();break}case"array":{let{prefixItems,items}=schema;if(prefixItems&&Array.isArray(prefixItems)){let tupleItems=prefixItems.map((item)=>convertSchema(item,ctx)),rest=items&&typeof items==="object"&&!Array.isArray(items)?convertSchema(items,ctx):void 0;if(rest)zodSchema=z.tuple(tupleItems).rest(rest);else zodSchema=z.tuple(tupleItems);if(typeof schema.minItems==="number")zodSchema=zodSchema.check(z.minLength(schema.minItems));if(typeof schema.maxItems==="number")zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}else if(Array.isArray(items)){let tupleItems=items.map((item)=>convertSchema(item,ctx)),rest=schema.additionalItems&&typeof schema.additionalItems==="object"?convertSchema(schema.additionalItems,ctx):void 0;if(rest)zodSchema=z.tuple(tupleItems).rest(rest);else zodSchema=z.tuple(tupleItems);if(typeof schema.minItems==="number")zodSchema=zodSchema.check(z.minLength(schema.minItems));if(typeof schema.maxItems==="number")zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z.array(element);if(typeof schema.minItems==="number")arraySchema=arraySchema.min(schema.minItems);if(typeof schema.maxItems==="number")arraySchema=arraySchema.max(schema.maxItems);zodSchema=arraySchema}else zodSchema=z.array(z.any());break}default:throw Error(`Unsupported type: ${type}`)}if(schema.description)zodSchema=zodSchema.describe(schema.description);if(schema.default!==void 0)zodSchema=zodSchema.default(schema.default);return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean")return schema?z.any():z.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map((s)=>convertSchema(s,ctx)),anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map((s)=>convertSchema(s,ctx)),oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++)result=z.intersection(result,convertSchema(schema.allOf[i],ctx));baseSchema=result}if(schema.nullable===!0&&ctx.version==="openapi-3.0")baseSchema=z.nullable(baseSchema);if(schema.readOnly===!0)baseSchema=z.readonly(baseSchema);let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key of coreMetadataKeys)if(key in schema)extraMeta[key]=schema[key];let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key of contentMetadataKeys)if(key in schema)extraMeta[key]=schema[key];for(let key of Object.keys(schema))if(!RECOGNIZED_KEYS.has(key))extraMeta[key]=schema[key];if(Object.keys(extraMeta).length>0)ctx.registry.add(baseSchema,extraMeta);return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean")return schema?z.any():z.never();let version2=detectVersion(schema,params?.defaultTarget),defs=schema.$defs||schema.definitions||{},ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:schema,registry:params?.registry??globalRegistry};return convertSchema(schema,ctx)}var z,RECOGNIZED_KEYS;var init_from_json_schema=__esm(()=>{init_registries();init_checks2();init_iso();init_schemas2();z={...exports_schemas2,...exports_checks2,iso:exports_iso},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var exports_coerce={};__export(exports_coerce,{string:()=>string3,number:()=>number3,date:()=>date4,boolean:()=>boolean3,bigint:()=>bigint3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm(()=>{init_core2();init_schemas2()});var exports_external={};__export(exports_external,{xor:()=>xor,xid:()=>xid2,void:()=>_void2,uuidv7:()=>uuidv7,uuidv6:()=>uuidv6,uuidv4:()=>uuidv4,uuid:()=>uuid2,util:()=>exports_util,url:()=>url,uppercase:()=>_uppercase,unknown:()=>unknown,union:()=>union,undefined:()=>_undefined3,ulid:()=>ulid2,uint64:()=>uint64,uint32:()=>uint32,tuple:()=>tuple,trim:()=>_trim,treeifyError:()=>treeifyError,transform:()=>transform,toUpperCase:()=>_toUpperCase,toLowerCase:()=>_toLowerCase,toJSONSchema:()=>toJSONSchema,templateLiteral:()=>templateLiteral,symbol:()=>symbol,superRefine:()=>superRefine,success:()=>success,stringbool:()=>stringbool,stringFormat:()=>stringFormat,string:()=>string2,strictObject:()=>strictObject,startsWith:()=>_startsWith,slugify:()=>_slugify,size:()=>_size,setErrorMap:()=>setErrorMap,set:()=>set,safeParseAsync:()=>safeParseAsync2,safeParse:()=>safeParse2,safeEncodeAsync:()=>safeEncodeAsync2,safeEncode:()=>safeEncode2,safeDecodeAsync:()=>safeDecodeAsync2,safeDecode:()=>safeDecode2,registry:()=>registry,regexes:()=>exports_regexes,regex:()=>_regex,refine:()=>refine,record:()=>record,readonly:()=>readonly,property:()=>_property,promise:()=>promise,prettifyError:()=>prettifyError,preprocess:()=>preprocess,prefault:()=>prefault,positive:()=>_positive,pipe:()=>pipe,partialRecord:()=>partialRecord,parseAsync:()=>parseAsync2,parse:()=>parse3,overwrite:()=>_overwrite,optional:()=>optional,object:()=>object,number:()=>number2,nullish:()=>nullish2,nullable:()=>nullable,null:()=>_null3,normalize:()=>_normalize,nonpositive:()=>_nonpositive,nonoptional:()=>nonoptional,nonnegative:()=>_nonnegative,never:()=>never,negative:()=>_negative,nativeEnum:()=>nativeEnum,nanoid:()=>nanoid2,nan:()=>nan,multipleOf:()=>_multipleOf,minSize:()=>_minSize,minLength:()=>_minLength,mime:()=>_mime,meta:()=>meta2,maxSize:()=>_maxSize,maxLength:()=>_maxLength,map:()=>map,mac:()=>mac2,lte:()=>_lte,lt:()=>_lt,lowercase:()=>_lowercase,looseRecord:()=>looseRecord,looseObject:()=>looseObject,locales:()=>exports_locales,literal:()=>literal,length:()=>_length,lazy:()=>lazy,ksuid:()=>ksuid2,keyof:()=>keyof,jwt:()=>jwt,json:()=>json,iso:()=>exports_iso,ipv6:()=>ipv62,ipv4:()=>ipv42,intersection:()=>intersection,int64:()=>int64,int32:()=>int32,int:()=>int,instanceof:()=>_instanceof,includes:()=>_includes,httpUrl:()=>httpUrl,hostname:()=>hostname2,hex:()=>hex2,hash:()=>hash,guid:()=>guid2,gte:()=>_gte,gt:()=>_gt,globalRegistry:()=>globalRegistry,getErrorMap:()=>getErrorMap,function:()=>_function,fromJSONSchema:()=>fromJSONSchema,formatError:()=>formatError,float64:()=>float64,float32:()=>float32,flattenError:()=>flattenError,file:()=>file,exactOptional:()=>exactOptional,enum:()=>_enum2,endsWith:()=>_endsWith,encodeAsync:()=>encodeAsync2,encode:()=>encode2,emoji:()=>emoji2,email:()=>email2,e164:()=>e1642,discriminatedUnion:()=>discriminatedUnion,describe:()=>describe2,decodeAsync:()=>decodeAsync2,decode:()=>decode2,date:()=>date3,custom:()=>custom,cuid2:()=>cuid22,cuid:()=>cuid3,core:()=>exports_core2,config:()=>config,coerce:()=>exports_coerce,codec:()=>codec,clone:()=>clone,cidrv6:()=>cidrv62,cidrv4:()=>cidrv42,check:()=>check,catch:()=>_catch2,boolean:()=>boolean2,bigint:()=>bigint2,base64url:()=>base64url2,base64:()=>base642,array:()=>array,any:()=>any,_function:()=>_function,_default:()=>_default2,_ZodString:()=>_ZodString,ZodXor:()=>ZodXor,ZodXID:()=>ZodXID,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodUUID:()=>ZodUUID,ZodURL:()=>ZodURL,ZodULID:()=>ZodULID,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransform:()=>ZodTransform,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodSymbol:()=>ZodSymbol,ZodSuccess:()=>ZodSuccess,ZodStringFormat:()=>ZodStringFormat,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodRecord:()=>ZodRecord,ZodRealError:()=>ZodRealError,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPrefault:()=>ZodPrefault,ZodPipe:()=>ZodPipe,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumberFormat:()=>ZodNumberFormat,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNonOptional:()=>ZodNonOptional,ZodNever:()=>ZodNever,ZodNanoID:()=>ZodNanoID,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodMAC:()=>ZodMAC,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodKSUID:()=>ZodKSUID,ZodJWT:()=>ZodJWT,ZodIssueCode:()=>ZodIssueCode,ZodIntersection:()=>ZodIntersection,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate,ZodIPv6:()=>ZodIPv6,ZodIPv4:()=>ZodIPv4,ZodGUID:()=>ZodGUID,ZodFunction:()=>ZodFunction,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFile:()=>ZodFile,ZodExactOptional:()=>ZodExactOptional,ZodError:()=>ZodError,ZodEnum:()=>ZodEnum,ZodEmoji:()=>ZodEmoji,ZodEmail:()=>ZodEmail,ZodE164:()=>ZodE164,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodCustom:()=>ZodCustom,ZodCodec:()=>ZodCodec,ZodCatch:()=>ZodCatch,ZodCUID2:()=>ZodCUID2,ZodCUID:()=>ZodCUID,ZodCIDRv6:()=>ZodCIDRv6,ZodCIDRv4:()=>ZodCIDRv4,ZodBoolean:()=>ZodBoolean,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBigInt:()=>ZodBigInt,ZodBase64URL:()=>ZodBase64URL,ZodBase64:()=>ZodBase64,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny,TimePrecision:()=>TimePrecision,NEVER:()=>NEVER,$output:()=>$output,$input:()=>$input,$brand:()=>$brand});var init_external=__esm(()=>{init_core2();init_core2();init_en();init_core2();init_json_schema_processors();init_from_json_schema();init_locales();init_iso();init_iso();init_coerce();init_schemas2();init_checks2();init_errors2();init_parse2();init_compat();config(en_default())});var init_zod=__esm(()=>{init_external();init_external()});var EVIDENCE_MAX_JSON_BYTES=512000,EVIDENCE_MAX_PATCH_BYTES=5242880,EVIDENCE_MAX_TASK_BYTES=20971520,EvidenceTypeSchema,EvidenceVerdictSchema,BaseEvidenceSchema,ReviewEvidenceSchema,TestEvidenceSchema,DiffEvidenceSchema,ApprovalEvidenceSchema,NoteEvidenceSchema,RetrospectiveEvidenceSchema,SyntaxEvidenceSchema,PlaceholderEvidenceSchema,SastFindingSchema,SastEvidenceSchema,SbomEvidenceSchema,BuildEvidenceSchema,QualityBudgetEvidenceSchema,SecretscanEvidenceSchema,GateEvidenceBaseSchema,MutationGateEvidenceSchema,DriftVerificationEvidenceSchema,HallucinationVerificationEvidenceSchema,EvidenceSchema,EvidenceBundleSchema;var init_evidence_schema=__esm(()=>{init_zod();EvidenceTypeSchema=exports_external.enum(["review","test","diff","approval","note","retrospective","syntax","placeholder","sast","sbom","build","quality_budget","secretscan","mutation-gate","drift-verification","hallucination-verification"]),EvidenceVerdictSchema=exports_external.enum(["pass","fail","warn","skip","approved","rejected","info"]),BaseEvidenceSchema=exports_external.object({task_id:exports_external.string().min(1),type:EvidenceTypeSchema,timestamp:exports_external.string().datetime(),agent:exports_external.string().min(1),verdict:EvidenceVerdictSchema,summary:exports_external.string().min(1),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}),ReviewEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("review"),risk:exports_external.enum(["low","medium","high","critical"]),issues:exports_external.array(exports_external.object({severity:exports_external.enum(["error","warning","info"]),message:exports_external.string().min(1),file:exports_external.string().optional(),line:exports_external.number().int().optional()})).default([])}),TestEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("test"),tests_passed:exports_external.number().int().min(0),tests_failed:exports_external.number().int().min(0),test_file:exports_external.string().optional(),failures:exports_external.array(exports_external.object({name:exports_external.string().min(1),message:exports_external.string().min(1)})).default([])}),DiffEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("diff"),files_changed:exports_external.array(exports_external.string()).default([]),additions:exports_external.number().int().min(0).default(0),deletions:exports_external.number().int().min(0).default(0),patch_path:exports_external.string().optional()}),ApprovalEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("approval")}),NoteEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("note")}),RetrospectiveEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("retrospective"),phase_number:exports_external.number().int().min(1).max(99),total_tool_calls:exports_external.number().int().min(0).max(9999),coder_revisions:exports_external.number().int().min(0).max(999),reviewer_rejections:exports_external.number().int().min(0).max(999),loop_detections:exports_external.number().int().min(0).max(9999).optional(),circuit_breaker_trips:exports_external.number().int().min(0).max(9999).optional(),test_failures:exports_external.number().int().min(0).max(9999),security_findings:exports_external.number().int().min(0).max(999),integration_issues:exports_external.number().int().min(0).max(999),task_count:exports_external.number().int().min(1).max(9999),task_complexity:exports_external.enum(["trivial","simple","moderate","complex"]),top_rejection_reasons:exports_external.array(exports_external.string()).default([]),lessons_learned:exports_external.array(exports_external.string()).max(5).default([]),user_directives:exports_external.array(exports_external.object({directive:exports_external.string().min(1),category:exports_external.enum(["tooling","code_style","architecture","process","other"]),scope:exports_external.enum(["session","project","global"])})).default([]),approaches_tried:exports_external.array(exports_external.object({approach:exports_external.string().min(1),result:exports_external.enum(["success","failure","partial"]),abandoned_reason:exports_external.string().optional()})).max(10).default([]),error_taxonomy:exports_external.array(exports_external.enum(["planning_error","interface_mismatch","logic_error","scope_creep","gate_evasion"])).default([])}),SyntaxEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("syntax"),files_checked:exports_external.number().int(),files_failed:exports_external.number().int(),skipped_count:exports_external.number().int().default(0),files:exports_external.array(exports_external.object({path:exports_external.string(),language:exports_external.string(),ok:exports_external.boolean(),errors:exports_external.array(exports_external.object({line:exports_external.number().int(),column:exports_external.number().int(),message:exports_external.string()})).default([]),skipped_reason:exports_external.string().optional()})).default([])}),PlaceholderEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("placeholder"),findings:exports_external.array(exports_external.object({path:exports_external.string(),line:exports_external.number().int(),kind:exports_external.enum(["comment","string","function_body","other"]),excerpt:exports_external.string(),rule_id:exports_external.string()})).default([]),files_scanned:exports_external.number().int(),files_with_findings:exports_external.number().int(),findings_count:exports_external.number().int()}),SastFindingSchema=exports_external.object({rule_id:exports_external.string(),severity:exports_external.enum(["critical","high","medium","low"]),message:exports_external.string(),location:exports_external.object({file:exports_external.string(),line:exports_external.number().int(),column:exports_external.number().int().optional()}),remediation:exports_external.string().optional()}),SastEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("sast"),findings:exports_external.array(SastFindingSchema).default([]),engine:exports_external.enum(["tier_a","tier_a+tier_b"]),files_scanned:exports_external.number().int(),findings_count:exports_external.number().int(),findings_by_severity:exports_external.object({critical:exports_external.number().int(),high:exports_external.number().int(),medium:exports_external.number().int(),low:exports_external.number().int()}),new_findings:exports_external.array(SastFindingSchema).optional(),pre_existing_findings:exports_external.array(SastFindingSchema).optional(),baseline_used:exports_external.boolean().optional()}),SbomEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("sbom"),components:exports_external.array(exports_external.object({name:exports_external.string(),version:exports_external.string(),type:exports_external.enum(["library","framework","application"]),purl:exports_external.string().optional(),license:exports_external.string().optional()})).default([]),metadata:exports_external.object({timestamp:exports_external.string().datetime(),tool:exports_external.string(),tool_version:exports_external.string()}),files:exports_external.array(exports_external.string()),components_count:exports_external.number().int(),output_path:exports_external.string()}),BuildEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("build"),runs:exports_external.array(exports_external.object({kind:exports_external.enum(["build","typecheck","test"]),command:exports_external.string(),cwd:exports_external.string(),exit_code:exports_external.number().int(),duration_ms:exports_external.number().int(),stdout_tail:exports_external.string(),stderr_tail:exports_external.string()})).default([]),files_scanned:exports_external.number().int(),runs_count:exports_external.number().int(),failed_count:exports_external.number().int(),skipped_reason:exports_external.string().optional()}),QualityBudgetEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("quality_budget"),metrics:exports_external.object({complexity_delta:exports_external.number(),public_api_delta:exports_external.number(),duplication_ratio:exports_external.number(),test_to_code_ratio:exports_external.number()}),thresholds:exports_external.object({max_complexity_delta:exports_external.number(),max_public_api_delta:exports_external.number(),max_duplication_ratio:exports_external.number(),min_test_to_code_ratio:exports_external.number()}),violations:exports_external.array(exports_external.object({type:exports_external.enum(["complexity","api","duplication","test_ratio"]),message:exports_external.string(),severity:exports_external.enum(["error","warning"]),files:exports_external.array(exports_external.string())})).default([]),files_analyzed:exports_external.array(exports_external.string())}),SecretscanEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("secretscan"),findings_count:exports_external.number().int().min(0).default(0),scan_directory:exports_external.string().optional(),files_scanned:exports_external.number().int().min(0).default(0),skipped_files:exports_external.number().int().min(0).default(0)}),GateEvidenceBaseSchema=exports_external.object({task_id:exports_external.string().optional(),agent:exports_external.string().optional(),timestamp:exports_external.string().datetime(),summary:exports_external.string().min(1),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}),MutationGateEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("mutation-gate"),verdict:exports_external.enum(["pass","warn","fail","skip"]),killRate:exports_external.number().min(0).max(1).optional(),adjustedKillRate:exports_external.number().min(0).max(1).optional(),survivedMutants:exports_external.string().optional()}),DriftVerificationEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("drift-verification"),verdict:exports_external.enum(["approved","rejected"]),requirementCoverage:exports_external.string().optional()}),HallucinationVerificationEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("hallucination-verification"),verdict:exports_external.enum(["approved","rejected"]),findings:exports_external.string().optional()}),EvidenceSchema=exports_external.discriminatedUnion("type",[ReviewEvidenceSchema,TestEvidenceSchema,DiffEvidenceSchema,ApprovalEvidenceSchema,NoteEvidenceSchema,RetrospectiveEvidenceSchema,SyntaxEvidenceSchema,PlaceholderEvidenceSchema,SastEvidenceSchema,SbomEvidenceSchema,BuildEvidenceSchema,QualityBudgetEvidenceSchema,SecretscanEvidenceSchema,MutationGateEvidenceSchema,DriftVerificationEvidenceSchema,HallucinationVerificationEvidenceSchema]),EvidenceBundleSchema=exports_external.object({schema_version:exports_external.literal("1.0.0"),task_id:exports_external.string().min(1),entries:exports_external.array(EvidenceSchema).default([]),created_at:exports_external.string().datetime(),updated_at:exports_external.string().datetime()})});var exports_schema={};__export(exports_schema,{stripKnownSwarmPrefix:()=>stripKnownSwarmPrefix,resolveGuardrailsConfig:()=>resolveGuardrailsConfig,resolveGeneratedAgentRole:()=>resolveGeneratedAgentRole,resolveExternalSkillsConfig:()=>resolveExternalSkillsConfig,isKnownCanonicalRole:()=>isKnownCanonicalRole,getCanonicalAgentRole:()=>getCanonicalAgentRole,_internals:()=>_internals,WorktreeIsolationConfigSchema:()=>WorktreeIsolationConfigSchema,WatchdogConfigSchema:()=>WatchdogConfigSchema,UIReviewConfigSchema:()=>UIReviewConfigSchema,TurboConfigSchema:()=>TurboConfigSchema,ToolFilterConfigSchema:()=>ToolFilterConfigSchema,TokenRatiosSchema:()=>TokenRatiosSchema,SwarmConfigSchema:()=>SwarmConfigSchema,SummaryConfigSchema:()=>SummaryConfigSchema,StandardTurboConfigSchema:()=>StandardTurboConfigSchema,SpecWriterConfigSchema:()=>SpecWriterConfigSchema,SlopDetectorConfigSchema:()=>SlopDetectorConfigSchema,SkillsConfigSchema:()=>SkillsConfigSchema,SkillPropagationConfigSchema:()=>SkillPropagationConfigSchema,SkillImproverConfigSchema:()=>SkillImproverConfigSchema,SelfReviewConfigSchema:()=>SelfReviewConfigSchema,SecretscanConfigSchema:()=>SecretscanConfigSchema,ScoringWeightsSchema:()=>ScoringWeightsSchema,ScoringConfigSchema:()=>ScoringConfigSchema,ReviewPassesConfigSchema:()=>ReviewPassesConfigSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QualityBudgetConfigSchema:()=>QualityBudgetConfigSchema,PrmConfigSchema:()=>PrmConfigSchema,PricingConfigSchema:()=>PricingConfigSchema,PrMonitorConfigSchema:()=>PrMonitorConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanCursorConfigSchema:()=>PlanCursorConfigSchema,PlaceholderScanConfigSchema:()=>PlaceholderScanConfigSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,ParallelizationConfigSchema:()=>ParallelizationConfigSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LintConfigSchema:()=>LintConfigSchema,LeanTurboStrategyConfigSchema:()=>LeanTurboStrategyConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,KnowledgeConfigSchema:()=>KnowledgeConfigSchema,KnowledgeApplicationConfigSchema:()=>KnowledgeApplicationConfigSchema,IntegrationAnalysisConfigSchema:()=>IntegrationAnalysisConfigSchema,IncrementalVerifyConfigSchema:()=>IncrementalVerifyConfigSchema,HooksConfigSchema:()=>HooksConfigSchema,GuardrailsProfileSchema:()=>GuardrailsProfileSchema,GuardrailsConfigSchema:()=>GuardrailsConfigSchema,GeneralCouncilConfigSchema:()=>GeneralCouncilConfigSchema,GateFeatureSchema:()=>GateFeatureSchema,GateConfigSchema:()=>GateConfigSchema,ExternalSkillsConfigSchema:()=>ExternalSkillsConfigSchema,ExternalSkillCandidateSourceTypeSchema:()=>ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateSchema:()=>ExternalSkillCandidateSchema,ExternalSkillCandidateEvaluationVerdictSchema:()=>ExternalSkillCandidateEvaluationVerdictSchema,EvidenceConfigSchema:()=>EvidenceConfigSchema,EpicConfigSchema:()=>EpicConfigSchema,DocsConfigSchema:()=>DocsConfigSchema,DiscoverySourceSchema:()=>DiscoverySourceSchema,DesignDocsConfigSchema:()=>DesignDocsConfigSchema,DecisionDecaySchema:()=>DecisionDecaySchema,DEFAULT_SKILLS_CONFIG:()=>DEFAULT_SKILLS_CONFIG,DEFAULT_EXTERNAL_SKILLS_CONFIG:()=>DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_ARCHITECT_PROFILE:()=>DEFAULT_ARCHITECT_PROFILE,DEFAULT_AGENT_PROFILES:()=>DEFAULT_AGENT_PROFILES,CuratorConfigSchema:()=>CuratorConfigSchema,CouncilConfigSchema:()=>CouncilConfigSchema,ContextMapConfigSchema:()=>ContextMapConfigSchema,ContextBudgetConfigSchema:()=>ContextBudgetConfigSchema,CompactionConfigSchema:()=>CompactionConfigSchema,CompactionAdvisoryConfigSchema:()=>CompactionAdvisoryConfigSchema,CheckpointConfigSchema:()=>CheckpointConfigSchema,AutomationModeSchema:()=>AutomationModeSchema,AutomationConfigSchema:()=>AutomationConfigSchema,AutomationCapabilitiesSchema:()=>AutomationCapabilitiesSchema,AutoReviewConfigSchema:()=>AutoReviewConfigSchema,AuthorityConfigSchema:()=>AuthorityConfigSchema,ArchitecturalSupervisionConfigSchema:()=>ArchitecturalSupervisionConfigSchema,AgentThinkingConfigSchema:()=>AgentThinkingConfigSchema,AgentReasoningConfigSchema:()=>AgentReasoningConfigSchema,AgentOverrideConfigSchema:()=>AgentOverrideConfigSchema,AgentAuthorityRuleSchema:()=>AgentAuthorityRuleSchema,AdversarialTestingConfigSchema:()=>AdversarialTestingConfigSchema,AdversarialDetectionConfigSchema:()=>AdversarialDetectionConfigSchema});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.endsWith(suffix))return role}return agentName}function resolveGeneratedAgentRole(agentName,generatedAgentNames){return _internals.getCanonicalAgentRole(agentName,generatedAgentNames)}function stripKnownSwarmPrefix(agentName){return getCanonicalAgentRole(agentName)}function resolveGuardrailsConfig(config2,agentName){if(!agentName)return config2;let canonicalName=_internals.stripKnownSwarmPrefix(agentName),hasBuiltInProfile=canonicalName in DEFAULT_AGENT_PROFILES,userProfile=config2.profiles?.[agentName]??config2.profiles?.[canonicalName];if(!hasBuiltInProfile){if(userProfile)return{...config2,...userProfile};return config2}let builtInProfile=DEFAULT_AGENT_PROFILES[canonicalName];return{...config2,...builtInProfile,...userProfile||{}}}function resolveExternalSkillsConfig(input){if(input===void 0||input===null||typeof input!=="object"||Array.isArray(input))return{...DEFAULT_EXTERNAL_SKILLS_CONFIG};let config2=input;return{curation_enabled:config2.curation_enabled??DEFAULT_EXTERNAL_SKILLS_CONFIG.curation_enabled,max_candidates:config2.max_candidates??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_candidates,max_bytes_per_candidate:config2.max_bytes_per_candidate??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_bytes_per_candidate,eviction_policy:config2.eviction_policy??DEFAULT_EXTERNAL_SKILLS_CONFIG.eviction_policy,ttl_days:config2.ttl_days??DEFAULT_EXTERNAL_SKILLS_CONFIG.ttl_days,evaluation_enabled:config2.evaluation_enabled??DEFAULT_EXTERNAL_SKILLS_CONFIG.evaluation_enabled,sources:Array.isArray(config2.sources)?config2.sources:[],max_candidates_per_discovery:config2.max_candidates_per_discovery??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_candidates_per_discovery,max_concurrent_fetches:config2.max_concurrent_fetches??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_concurrent_fetches,fetch_timeout_ms:config2.fetch_timeout_ms??DEFAULT_EXTERNAL_SKILLS_CONFIG.fetch_timeout_ms}}var _internals,SEPARATORS,CANONICAL_ROLES_LONGEST_FIRST,CANONICAL_ROLES_SET,AgentReasoningConfigSchema,AgentThinkingConfigSchema,AgentOverrideConfigSchema,SwarmConfigSchema,ModelPricingConfigSchema,PricingConfigSchema,HooksConfigSchema,ScoringWeightsSchema,DecisionDecaySchema,TokenRatiosSchema,ScoringConfigSchema,ContextBudgetConfigSchema,EvidenceConfigSchema,GateFeatureSchema,PlaceholderScanConfigSchema,QualityBudgetConfigSchema,GateConfigSchema,PipelineConfigSchema,PhaseCompleteConfigSchema,SummaryConfigSchema,ReviewPassesConfigSchema,AutoReviewConfigSchema,AdversarialDetectionConfigSchema,AdversarialTestingConfigSchemaBase,AdversarialTestingConfigSchema,IntegrationAnalysisConfigSchema,DocsConfigSchema,DesignDocsConfigSchema,UIReviewConfigSchema,CompactionAdvisoryConfigSchema,LintConfigSchema,SecretscanConfigSchema,GuardrailsProfileSchema,DEFAULT_AGENT_PROFILES,DEFAULT_ARCHITECT_PROFILE,GuardrailsConfigSchema,WatchdogConfigSchema,SelfReviewConfigSchema,ToolFilterConfigSchema,PlanCursorConfigSchema,ContextMapConfigSchema,RepoGraphConfigSchema,CheckpointConfigSchema,AutomationModeSchema,AutomationCapabilitiesSchema,AutomationConfigSchemaBase,AutomationConfigSchema,KnowledgeConfigSchema,MemoryConfigSchema,CuratorConfigSchema,ArchitecturalSupervisionConfigSchema,KnowledgeApplicationConfigSchema,SkillPropagationConfigSchema,SkillImproverConfigSchema,SkillsConfigSchema,SpecWriterConfigSchema,SlopDetectorConfigSchema,IncrementalVerifyConfigSchema,CompactionConfigSchema,PrmConfigSchema,AgentAuthorityRuleSchema,AuthorityConfigSchema,GeneralCouncilMemberConfigSchema,GeneralCouncilConfigSchema,CouncilConfigSchema,PrMonitorConfigSchema,ParallelizationConfigSchema,WorktreeIsolationConfigSchema,LeanTurboConfigSchema,EpicConfigSchema,StandardTurboConfigSchema,LeanTurboStrategyConfigSchema,TurboConfigSchema,ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateEvaluationVerdictSchema,DiscoverySourceSchema,ExternalSkillCandidateSchema,ExternalSkillsConfigSchema,DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_SKILLS_CONFIG,PluginConfigSchema;var init_schema=__esm(()=>{init_zod();init_constants();_internals={stripKnownSwarmPrefix,getCanonicalAgentRole,resolveGuardrailsConfig},SEPARATORS=["_","-"," "],CANONICAL_ROLES_LONGEST_FIRST=[...ALL_AGENT_NAMES].sort((a,b)=>b.length-a.length),CANONICAL_ROLES_SET=new Set(ALL_AGENT_NAMES);AgentReasoningConfigSchema=exports_external.object({effort:exports_external.enum(["low","medium","high","max"]).optional()}),AgentThinkingConfigSchema=exports_external.object({type:exports_external.enum(["enabled","disabled"]).optional(),budget_tokens:exports_external.number().int().positive().optional()}),AgentOverrideConfigSchema=exports_external.object({model:exports_external.string().optional(),variant:exports_external.string().min(1).optional(),temperature:exports_external.number().min(0).max(2).optional(),disabled:exports_external.boolean().optional(),fallback_models:exports_external.array(exports_external.string()).max(3).optional(),reasoning:AgentReasoningConfigSchema.optional(),thinking:AgentThinkingConfigSchema.optional()}),SwarmConfigSchema=exports_external.object({name:exports_external.string().optional(),agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional()}),ModelPricingConfigSchema=exports_external.object({input_per_million:exports_external.number().min(0),output_per_million:exports_external.number().min(0),reasoning_per_million:exports_external.number().min(0).optional(),cache_per_million:exports_external.number().min(0).optional()}),PricingConfigSchema=exports_external.object({models:exports_external.record(exports_external.string().min(1),ModelPricingConfigSchema).optional().default({})}),HooksConfigSchema=exports_external.object({system_enhancer:exports_external.boolean().default(!0),compaction:exports_external.boolean().default(!0),agent_activity:exports_external.boolean().default(!0),delegation_tracker:exports_external.boolean().default(!1),agent_awareness_max_chars:exports_external.number().min(50).max(2000).default(300),delegation_gate:exports_external.boolean().default(!0),delegation_max_chars:exports_external.number().min(500).max(20000).default(4000),background_subagents:exports_external.boolean().default(!1),background_pending_timeout_minutes:exports_external.number().int().min(1).max(1440).default(30)}),ScoringWeightsSchema=exports_external.object({phase:exports_external.number().min(0).max(5).default(1),current_task:exports_external.number().min(0).max(5).default(2),blocked_task:exports_external.number().min(0).max(5).default(1.5),recent_failure:exports_external.number().min(0).max(5).default(2.5),recent_success:exports_external.number().min(0).max(5).default(0.5),evidence_presence:exports_external.number().min(0).max(5).default(1),decision_recency:exports_external.number().min(0).max(5).default(1.5),dependency_proximity:exports_external.number().min(0).max(5).default(1)}),DecisionDecaySchema=exports_external.object({mode:exports_external.enum(["linear","exponential"]).default("exponential"),half_life_hours:exports_external.number().min(1).max(168).default(24)}),TokenRatiosSchema=exports_external.object({prose:exports_external.number().min(0.1).max(1).default(0.25),code:exports_external.number().min(0.1).max(1).default(0.4),markdown:exports_external.number().min(0.1).max(1).default(0.3),json:exports_external.number().min(0.1).max(1).default(0.35)}),ScoringConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),max_candidates:exports_external.number().min(10).max(500).default(100),weights:ScoringWeightsSchema.optional(),decision_decay:DecisionDecaySchema.optional(),token_ratios:TokenRatiosSchema.optional()}),ContextBudgetConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),warn_threshold:exports_external.number().min(0).max(1).default(0.7),critical_threshold:exports_external.number().min(0).max(1).default(0.9),model_limits:exports_external.record(exports_external.string(),exports_external.number().min(1000)).default({default:128000}),max_injection_tokens:exports_external.number().min(100).max(50000).default(4000),unified_injection_tokens:exports_external.number().min(100).max(50000).optional(),tracked_agents:exports_external.array(exports_external.string()).default(["architect"]),scoring:ScoringConfigSchema.optional(),enforce:exports_external.boolean().default(!0),prune_target:exports_external.number().min(0).max(1).default(0.7),preserve_last_n_turns:exports_external.number().min(0).max(100).default(4),recent_window:exports_external.number().min(1).max(100).default(10),enforce_on_agent_switch:exports_external.boolean().default(!0),tool_output_mask_threshold:exports_external.number().min(100).max(1e5).default(2000)}),EvidenceConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_age_days:exports_external.number().min(1).max(365).default(90),max_bundles:exports_external.number().min(10).max(1e4).default(1000),auto_archive:exports_external.boolean().default(!1)}),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)}),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.*"])}),GateConfigSchema=exports_external.object({syntax_check:GateFeatureSchema.default({enabled:!0}),placeholder_scan:PlaceholderScanConfigSchema.default({enabled:!0,deny_patterns:["TODO","FIXME","TBD","XXX","placeholder","stub","wip","not implemented"],allow_globs:["docs/**","examples/**","tests/**","**/*.test.*","**/*.spec.*","**/mocks/**","**/__tests__/**"],max_allowed_findings:0}),sast_scan:GateFeatureSchema.default({enabled:!0}),sbom_generate:GateFeatureSchema.default({enabled:!0}),build_check:GateFeatureSchema.default({enabled:!0}),quality_budget:QualityBudgetConfigSchema}),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(["retrieve_summary","retrieve_lane_output","task","read"])}),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/**"])}),AutoReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),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)}),AdversarialDetectionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),policy:exports_external.enum(["warn","gate","ignore"]).default("warn"),pairs:exports_external.array(exports_external.tuple([exports_external.string(),exports_external.string()])).default([["coder","reviewer"]])}),AdversarialTestingConfigSchemaBase=exports_external.object({enabled:exports_external.boolean().default(!0),scope:exports_external.enum(["all","security-only"]).default("all")}),AdversarialTestingConfigSchema=AdversarialTestingConfigSchemaBase.default(()=>({enabled:!0,scope:"all"})),IntegrationAnalysisConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0)}),DocsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),doc_patterns:exports_external.array(exports_external.string()).default(["README.md","CONTRIBUTING.md","docs/**/*.md","docs/**/*.rst","**/CHANGELOG.md"])}),DesignDocsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),out_dir:exports_external.string().default("docs").refine((v)=>v.length>0&&v!=="."&&!v.includes("..")&&!v.startsWith("/")&&!v.startsWith("\\")&&!/^[A-Za-z]:/.test(v),{message:'design_docs.out_dir must be a non-empty project-relative path with no "..", leading slash, or drive letter'}),language:exports_external.string().optional()}),UIReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),trigger_paths:exports_external.array(exports_external.string()).default(["**/pages/**","**/components/**","**/views/**","**/screens/**","**/ui/**","**/layouts/**"]),trigger_keywords:exports_external.array(exports_external.string()).default(["new page","new screen","new component","redesign","layout change","form","modal","dialog","dropdown","sidebar","navbar","dashboard","landing page","signup","login form","settings page","profile page"])}),CompactionAdvisoryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),thresholds:exports_external.array(exports_external.number().int().min(10).max(500)).default([50,75,100,125,150]),message:exports_external.string().default("[SWARM HINT] Session has ${totalToolCalls} tool calls. Consider compacting at next phase boundary to maintain context quality.")}),LintConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),mode:exports_external.enum(["check","fix"]).default("check"),linter:exports_external.enum(["biome","eslint","auto"]).default("auto"),patterns:exports_external.array(exports_external.string()).default(["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/biome.json","**/biome.jsonc"]),exclude:exports_external.array(exports_external.string()).default(["**/node_modules/**","**/dist/**","**/.git/**","**/coverage/**","**/*.min.js"])}),SecretscanConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),patterns:exports_external.array(exports_external.string()).default(["**/*.{env,properties,yml,yaml,json,js,ts}","**/.env*","**/secrets/**","**/credentials/**","**/config/**/*.ts","**/config/**/*.js"]),exclude:exports_external.array(exports_external.string()).default(["**/node_modules/**","**/dist/**","**/.git/**","**/coverage/**","**/test/**","**/tests/**","**/__tests__/**","**/*.test.ts","**/*.test.js","**/*.spec.ts","**/*.spec.js"]),extensions:exports_external.array(exports_external.string()).default([".env",".properties",".yml",".yaml",".json",".js",".ts",".py",".rb",".go",".java",".cs",".php"])}),GuardrailsProfileSchema=exports_external.object({max_tool_calls:exports_external.number().min(0).max(1000).optional(),max_duration_minutes:exports_external.number().min(0).max(480).optional(),max_repetitions:exports_external.number().min(3).max(50).optional(),max_consecutive_errors:exports_external.number().min(2).max(20).optional(),warning_threshold:exports_external.number().min(0.1).max(0.9).optional(),idle_timeout_minutes:exports_external.number().min(5).max(240).optional(),max_transient_retries:exports_external.number().min(0).max(20).optional()}),DEFAULT_AGENT_PROFILES={architect:{max_tool_calls:0,max_duration_minutes:0,max_consecutive_errors:8,warning_threshold:0.75},coder:{max_tool_calls:400,max_duration_minutes:45,max_consecutive_errors:8,warning_threshold:0.85},test_engineer:{max_tool_calls:400,max_duration_minutes:45,max_consecutive_errors:8,warning_threshold:0.85},explorer:{max_tool_calls:150,max_duration_minutes:20,max_consecutive_errors:8,warning_threshold:0.75},reviewer:{max_tool_calls:200,max_duration_minutes:30,max_consecutive_errors:8,warning_threshold:0.65},critic:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.65},sme:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.65},docs:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.75},designer:{max_tool_calls:150,max_duration_minutes:20,warning_threshold:0.75}},DEFAULT_ARCHITECT_PROFILE=DEFAULT_AGENT_PROFILES.architect,GuardrailsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_tool_calls:exports_external.number().min(0).max(1000).default(200),max_duration_minutes:exports_external.number().min(0).max(480).default(30),max_repetitions:exports_external.number().min(3).max(50).default(10),max_consecutive_errors:exports_external.number().min(2).max(20).default(5),max_transient_retries:exports_external.number().min(0).max(20).default(5),warning_threshold:exports_external.number().min(0.1).max(0.9).default(0.75),idle_timeout_minutes:exports_external.number().min(5).max(240).default(60),no_op_warning_threshold:exports_external.number().min(1).max(100).default(15),max_coder_revisions:exports_external.number().int().min(1).max(20).default(5),runaway_output_max_turns:exports_external.number().int().min(1).max(20).default(5),qa_gates:exports_external.object({required_tools:exports_external.array(exports_external.string().min(1)).default(["diff","syntax_check","placeholder_scan","lint","pre_check_batch"]),require_reviewer_test_engineer:exports_external.boolean().default(!0)}).optional(),profiles:exports_external.record(exports_external.string(),GuardrailsProfileSchema).optional(),block_destructive_commands:exports_external.boolean().default(!0),interpreter_allowed_agents:exports_external.array(exports_external.string().min(1)).optional(),shell_audit_log:exports_external.boolean().default(!0)}),WatchdogConfigSchema=exports_external.object({scope_guard:exports_external.boolean().default(!0),skip_in_turbo:exports_external.boolean().default(!1),delegation_ledger:exports_external.boolean().default(!0)}),SelfReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),skip_in_turbo:exports_external.boolean().default(!0)});ToolFilterConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),overrides:exports_external.record(exports_external.string(),exports_external.array(exports_external.string())).default({})}),PlanCursorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_tokens:exports_external.number().min(500).max(4000).default(1500),lookahead_tasks:exports_external.number().min(0).max(5).default(2)}),ContextMapConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),mode:exports_external.enum(["conservative","balanced","aggressive"]).default("balanced"),max_capsule_tokens:exports_external.number().int().positive().default(2000),invalidate_on_hash_change:exports_external.boolean().default(!0),agent_profiles:exports_external.record(exports_external.string(),exports_external.string()).default({})}),RepoGraphConfigSchema=exports_external.object({exclude_dirs:exports_external.array(exports_external.string().trim().min(1)).default([])}),CheckpointConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),auto_checkpoint_threshold:exports_external.number().int().min(1).max(20).default(3),allow_empty_commits:exports_external.boolean().default(!1)}).strict(),AutomationModeSchema=exports_external.enum(["manual","hybrid","auto"]),AutomationCapabilitiesSchema=exports_external.object({plan_sync:exports_external.boolean().default(!0),phase_preflight:exports_external.boolean().default(!1),config_doctor_on_startup:exports_external.boolean().default(!1),config_doctor_autofix:exports_external.boolean().default(!1),evidence_auto_summaries:exports_external.boolean().default(!0),decision_drift_detection:exports_external.boolean().default(!0)}),AutomationConfigSchemaBase=exports_external.object({mode:AutomationModeSchema.default("manual"),capabilities:AutomationCapabilitiesSchema.default({plan_sync:!0,phase_preflight:!1,config_doctor_on_startup:!1,config_doctor_autofix:!1,evidence_auto_summaries:!0,decision_drift_detection:!0})}),AutomationConfigSchema=AutomationConfigSchemaBase,KnowledgeConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),swarm_max_entries:exports_external.number().min(1).max(1e4).default(100),hive_max_entries:exports_external.number().min(1).max(1e5).default(200),auto_promote_days:exports_external.number().min(1).max(3650).default(90),max_inject_count:exports_external.number().min(0).max(50).default(5),delegate_max_inject_count:exports_external.number().min(0).max(50).default(8),inject_char_budget:exports_external.number().min(200).max(1e4).default(2000),context_budget_threshold:exports_external.number().int().positive().optional(),max_lesson_display_chars:exports_external.number().min(40).max(280).default(120),dedup_threshold:exports_external.number().min(0).max(1).default(0.6),scope_filter:exports_external.array(exports_external.string()).default(["global"]),hive_enabled:exports_external.boolean().default(!0),rejected_max_entries:exports_external.number().min(1).max(1000).default(20),validation_enabled:exports_external.boolean().default(!0),evergreen_confidence:exports_external.number().min(0).max(1).default(0.9),evergreen_utility:exports_external.number().min(0).max(1).default(0.8),low_utility_threshold:exports_external.number().min(0).max(1).default(0.3),min_retrievals_for_utility:exports_external.number().min(1).max(100).default(3),schema_version:exports_external.number().int().min(1).default(1),directive_min_confidence:exports_external.number().min(0).max(1).default(0.75),same_project_weight:exports_external.number().min(0).max(5).default(1),cross_project_weight:exports_external.number().min(0).max(5).default(0.5),min_encounter_score:exports_external.number().min(0).max(1).default(0.1),initial_encounter_score:exports_external.number().min(0).max(5).default(1),encounter_increment:exports_external.number().min(0).max(1).default(0.1),max_encounter_score:exports_external.number().min(1).max(20).default(10),default_max_phases:exports_external.number().int().positive().default(10),todo_max_phases:exports_external.number().int().positive().default(3),sweep_enabled:exports_external.boolean().default(!0),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"})}),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}),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}}),writes:exports_external.object({mode:exports_external.literal("propose").default("propose")}).default({mode:"propose"}),redaction:exports_external.object({rejectDurableSecrets:exports_external.boolean().default(!0)}).default({rejectDurableSecrets:!0}),maintenance:exports_external.object({lowUtilityMaxConfidence:exports_external.number().min(0).max(1).default(0.45),lowUtilityMinAgeDays:exports_external.number().int().min(1).max(3650).default(30),importance:exports_external.object({wRecency:exports_external.number().min(0).max(1).default(0.2),wFrequency:exports_external.number().min(0).max(1).default(0.2),wFreshness:exports_external.number().min(0).max(1).default(0.15),wConfidence:exports_external.number().min(0).max(1).default(0.25),lambda:exports_external.number().min(0).max(10).default(0.05),mu:exports_external.number().min(0).max(10).default(0.01),n:exports_external.number().int().min(1).max(1e5).default(50),threshold:exports_external.number().min(0).max(1).default(0.2)}).default({wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2})}).default({lowUtilityMaxConfidence:0.45,lowUtilityMinAgeDays:30,importance:{wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2}}),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"])}),SkillPropagationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),enforce:exports_external.boolean().default(!1)}),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)}),SpecWriterConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),model:exports_external.string().nullable().default(null),fallback_models:exports_external.array(exports_external.string()).default([]),allow_spec_write:exports_external.boolean().default(!0)}),SlopDetectorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),classThreshold:exports_external.number().int().min(1).default(3),commentStripThreshold:exports_external.number().int().min(1).default(5),diffLineThreshold:exports_external.number().int().min(10).default(200),importHygieneThreshold:exports_external.number().int().min(1).default(2)}),IncrementalVerifyConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),command:exports_external.union([exports_external.string(),exports_external.array(exports_external.string())]).nullable().default(null),timeoutMs:exports_external.number().int().min(1000).max(300000).default(30000),triggerAgents:exports_external.array(exports_external.string()).default(["coder"])}),CompactionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),observationThreshold:exports_external.number().min(1).max(99).default(40),reflectionThreshold:exports_external.number().min(1).max(99).default(60),emergencyThreshold:exports_external.number().min(1).max(99).default(80),preserveLastNTurns:exports_external.number().int().min(1).default(5)}),PrmConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),pattern_thresholds:exports_external.object({repetition_loop:exports_external.number().min(1).default(2),ping_pong:exports_external.number().min(1).default(2),expansion_drift:exports_external.number().min(1).default(3),stuck_on_test:exports_external.number().min(1).default(3),context_thrash:exports_external.number().min(1).default(3)}).default(()=>({repetition_loop:2,ping_pong:2,expansion_drift:3,stuck_on_test:3,context_thrash:3})),max_trajectory_lines:exports_external.number().min(10).default(1000),escalation_enabled:exports_external.boolean().default(!0),detection_timeout_ms:exports_external.number().min(10).default(100)}),AgentAuthorityRuleSchema=exports_external.object({readOnly:exports_external.boolean().optional(),blockedExact:exports_external.array(exports_external.string()).optional(),allowedExact:exports_external.array(exports_external.string()).optional(),blockedPrefix:exports_external.array(exports_external.string()).optional(),allowedPrefix:exports_external.array(exports_external.string()).optional(),blockedZones:exports_external.array(exports_external.enum(["production","test","config","generated","docs","build"])).optional(),blockedGlobs:exports_external.array(exports_external.string()).optional(),allowedGlobs:exports_external.array(exports_external.string()).optional(),allowedCaseSensitiveGlobs:exports_external.array(exports_external.string()).optional()}),AuthorityConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),rules:exports_external.record(exports_external.string(),AgentAuthorityRuleSchema).default({}),universal_deny_prefixes:exports_external.array(exports_external.string().min(1)).default([]),verifier_config_paths:exports_external.array(exports_external.string()).optional().describe("Additional glob patterns for verifier config files that are merged into the architect agent's blockedGlobs at plugin init. Writes to matching files are blocked by the authority layer.")}),GeneralCouncilMemberConfigSchema=exports_external.object({memberId:exports_external.string().min(1),model:exports_external.string().min(1),role:exports_external.enum(["generalist","skeptic","domain_expert","devil_advocate","synthesizer"]),persona:exports_external.string().optional()}).strict(),GeneralCouncilConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),searchProvider:exports_external.enum(["tavily","brave"]).default("tavily"),searchApiKey:exports_external.string().optional(),members:exports_external.array(GeneralCouncilMemberConfigSchema).default([]),presets:exports_external.record(exports_external.string(),exports_external.array(GeneralCouncilMemberConfigSchema)).default({}),deliberate:exports_external.boolean().default(!0),moderator:exports_external.boolean().default(!0),moderatorModel:exports_external.string().optional(),maxSourcesPerMember:exports_external.number().int().min(1).max(20).default(5)}).strict(),CouncilConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),maxRounds:exports_external.number().int().min(1).max(10).default(3),parallelTimeoutMs:exports_external.number().int().min(5000).max(120000).default(30000),vetoPriority:exports_external.boolean().default(!0),requireAllMembers:exports_external.boolean().default(!1).describe("When true, submit_council_verdicts rejects if fewer than 5 member verdicts are provided. Equivalent to minimumMembers: 5."),minimumMembers:exports_external.number().int().min(1).max(5).default(3).describe("Minimum distinct council member verdicts required for synthesis. Default 3. Set to 1 to disable quorum enforcement. requireAllMembers: true overrides this to 5 (stricter constraint wins)."),escalateOnMaxRounds:exports_external.string().optional().describe("Optional webhook URL or handler name invoked when maxRounds is reached without APPROVE. Declared for forward compatibility; no behavior is implemented yet."),phaseConcernsAllowComplete:exports_external.boolean().default(!0).describe("When true, a phase-level council CONCERNS verdict with only MEDIUM/LOW findings does NOT block phase completion — the advisory notes are logged as warnings and the phase proceeds. When false, CONCERNS blocks like REJECT. Note: HIGH/CRITICAL findings from CONCERNS members are always promoted to requiredFixes and block at the tool level regardless of this setting. Default: true."),general:GeneralCouncilConfigSchema.optional()}).strict(),PrMonitorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),poll_interval_seconds:exports_external.number().int().min(30).max(300).default(60),max_subscriptions:exports_external.number().int().min(1).max(100).default(20),max_prs_per_cycle:exports_external.number().int().min(1).max(20).default(5),max_concurrent_pr_polls:exports_external.number().int().min(1).max(10).default(3),poll_timeout_ms:exports_external.number().int().min(5000).max(120000).default(30000),failure_threshold:exports_external.number().int().min(1).max(20).default(5),cooldown_seconds:exports_external.number().int().min(5).max(600).default(30),max_cooldown_seconds:exports_external.number().int().min(30).max(3600).default(300),cleanup_ttl_days:exports_external.number().int().min(1).max(90).default(7),auto_unsubscribe_on_merge:exports_external.boolean().default(!0),auto_unsubscribe_on_close:exports_external.boolean().default(!0),notify_ci_failure:exports_external.boolean().default(!0),notify_new_comments:exports_external.boolean().default(!0),notify_merge_conflict:exports_external.boolean().default(!0),auto_pr_feedback:exports_external.boolean().default(!1)}).strict(),ParallelizationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),maxConcurrentTasks:exports_external.number().int().min(1).max(64).default(1),evidenceLockTimeoutMs:exports_external.number().int().min(1000).max(300000).default(60000),max_coders:exports_external.number().int().min(1).max(16).default(3),max_reviewers:exports_external.number().int().min(1).max(16).default(2)}),WorktreeIsolationConfigSchema=exports_external.object({policy:exports_external.enum(["auto","required","disabled"]).default("auto"),merge_strategy:exports_external.enum(["merge","rebase","cherry-pick"]).default("merge"),worktree_dir:exports_external.string().optional(),deps_strategy:exports_external.enum(["skip","copy","link"]).default("skip")}),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(!1),merge_strategy:exports_external.enum(["merge","rebase","cherry-pick"]).default("merge").optional(),worktree_dir:exports_external.string().optional()}),EpicConfigSchema=exports_external.object({cochange:exports_external.object({enabled:exports_external.boolean().default(!1),threshold:exports_external.number().min(-1).max(1).default(0.6),min_co_changes:exports_external.number().int().min(1).default(5)}).strict().optional(),mode:exports_external.object({enabled:exports_external.boolean().default(!1),activation_threshold:exports_external.number().min(0).max(1).default(0.3),min_commits_for_signal:exports_external.number().int().min(1).default(20)}).strict().optional(),calibration:exports_external.object({enabled:exports_external.boolean().default(!0),floor_threshold:exports_external.number().min(0).max(1).default(0.05),tighten_step:exports_external.number().min(0).max(1).default(0.02),loosen_step:exports_external.number().min(0).max(1).default(0.01),loosen_window:exports_external.number().int().min(1).default(10)}).strict().optional()}).strict(),StandardTurboConfigSchema=exports_external.object({strategy:exports_external.literal("standard"),lean:LeanTurboConfigSchema.optional(),epic:EpicConfigSchema.optional()}),LeanTurboStrategyConfigSchema=exports_external.object({strategy:exports_external.literal("lean"),lean:LeanTurboConfigSchema,epic:EpicConfigSchema.optional()}),TurboConfigSchema=exports_external.discriminatedUnion("strategy",[StandardTurboConfigSchema,LeanTurboStrategyConfigSchema]),ExternalSkillCandidateSourceTypeSchema=exports_external.enum(["github","url","collection","manual_import"]),ExternalSkillCandidateEvaluationVerdictSchema=exports_external.enum(["pending","in_review","quarantined","passed","rejected","promoted","revoked"]),DiscoverySourceSchema=exports_external.object({type:ExternalSkillCandidateSourceTypeSchema,location:exports_external.string().min(1),enabled:exports_external.boolean().default(!0),trust_level:exports_external.enum(["low","medium","high"]).default("low").optional()}),ExternalSkillCandidateSchema=exports_external.object({id:exports_external.string().uuid(),source_url:exports_external.string().url(),source_type:ExternalSkillCandidateSourceTypeSchema,publisher:exports_external.string().min(1),sha256:exports_external.string().regex(/^[a-f0-9]{64}$/),fetched_at:exports_external.string().datetime(),skill_name:exports_external.string().optional(),skill_description:exports_external.string().optional(),skill_body:exports_external.string(),risk_flags:exports_external.array(exports_external.string()).default([]),evaluation_verdict:ExternalSkillCandidateEvaluationVerdictSchema.default("pending"),evaluation_history:exports_external.array(exports_external.object({verdict:ExternalSkillCandidateEvaluationVerdictSchema,timestamp:exports_external.string().datetime(),actor:exports_external.string(),reason:exports_external.string().optional(),candidate_id:exports_external.string().optional(),original_verdict:ExternalSkillCandidateEvaluationVerdictSchema.optional(),gate_results:exports_external.array(exports_external.object({gate:exports_external.string(),verdict:exports_external.string()})).optional(),risk_assessment:exports_external.object({total_flags:exports_external.number().int().nonnegative(),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["error","warning"]),category:exports_external.string()}))}).optional(),risk_flags_count:exports_external.number().int().nonnegative().optional(),provenance_snapshot:exports_external.object({sha256:exports_external.string(),source_url:exports_external.string(),publisher:exports_external.string(),fetched_at:exports_external.string().datetime().optional()}).optional(),target_path:exports_external.string().optional(),promoted_content_hash:exports_external.string().regex(/^[a-f0-9]{64}$/).optional(),original_evaluation:exports_external.record(exports_external.string(),exports_external.unknown()).optional()})).default([])}),ExternalSkillsConfigSchema=exports_external.object({curation_enabled:exports_external.boolean().default(!1),max_candidates:exports_external.number().int().min(1).max(1e4).default(500),max_bytes_per_candidate:exports_external.number().int().min(1024).max(10485760).default(1048576),eviction_policy:exports_external.enum(["fifo"]).default("fifo"),ttl_days:exports_external.number().int().min(1).max(3650).default(90),evaluation_enabled:exports_external.boolean().default(!1),sources:exports_external.array(DiscoverySourceSchema).default([]),max_candidates_per_discovery:exports_external.number().int().min(1).max(1000).default(50),max_concurrent_fetches:exports_external.number().int().min(1).max(20).default(5),fetch_timeout_ms:exports_external.number().int().min(1000).max(300000).default(30000)}),DEFAULT_EXTERNAL_SKILLS_CONFIG={curation_enabled:!1,max_candidates:500,max_bytes_per_candidate:1048576,eviction_policy:"fifo",ttl_days:90,evaluation_enabled:!1,sources:[],max_candidates_per_discovery:50,max_concurrent_fetches:5,fetch_timeout_ms:30000},DEFAULT_SKILLS_CONFIG={enabled:!1};PluginConfigSchema=exports_external.object({agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional(),default_agent:exports_external.string().optional().transform((v)=>{if(v===void 0)return;let trimmed=v.trim();return trimmed===""?void 0:trimmed}),auto_select_architect:exports_external.union([exports_external.boolean(),exports_external.string()]).optional().transform((v)=>{if(v===void 0)return;if(typeof v==="boolean")return v;let trimmed=v.trim();return trimmed===""?!1:trimmed}),swarms:exports_external.record(exports_external.string().regex(/^[^_]+$/,"Swarm ID must not contain underscores"),SwarmConfigSchema).optional(),max_iterations:exports_external.number().min(1).max(10).default(5),pipeline:PipelineConfigSchema.optional(),phase_complete:PhaseCompleteConfigSchema.optional(),qa_retry_limit:exports_external.number().min(1).max(10).default(3),execution_mode:exports_external.enum(["strict","balanced","fast"]).default("balanced"),inject_phase_reminders:exports_external.boolean().default(!0),hooks:HooksConfigSchema.optional(),gates:GateConfigSchema.optional(),context_budget:ContextBudgetConfigSchema.optional(),pricing:PricingConfigSchema.optional(),guardrails:GuardrailsConfigSchema.optional(),watchdog:WatchdogConfigSchema.optional(),self_review:SelfReviewConfigSchema.optional(),auto_review:AutoReviewConfigSchema.optional(),tool_filter:ToolFilterConfigSchema.optional(),authority:AuthorityConfigSchema.optional(),plan_cursor:PlanCursorConfigSchema.optional(),context_map:ContextMapConfigSchema.optional(),repo_graph:RepoGraphConfigSchema.optional(),evidence:EvidenceConfigSchema.optional(),summaries:SummaryConfigSchema.optional(),review_passes:ReviewPassesConfigSchema.optional(),adversarial_detection:AdversarialDetectionConfigSchema.optional(),adversarial_testing:AdversarialTestingConfigSchema.optional(),integration_analysis:IntegrationAnalysisConfigSchema.optional(),docs:DocsConfigSchema.optional(),design_docs:DesignDocsConfigSchema.optional(),ui_review:UIReviewConfigSchema.optional(),compaction_advisory:CompactionAdvisoryConfigSchema.optional(),lint:LintConfigSchema.optional(),secretscan:SecretscanConfigSchema.optional(),checkpoint:CheckpointConfigSchema.optional(),automation:AutomationConfigSchema.optional(),knowledge:KnowledgeConfigSchema.optional(),memory:MemoryConfigSchema.optional(),curator:CuratorConfigSchema.optional(),architectural_supervision:ArchitecturalSupervisionConfigSchema.optional(),knowledge_application:KnowledgeApplicationConfigSchema.optional(),skillPropagation:SkillPropagationConfigSchema.optional(),skill_improver:SkillImproverConfigSchema.optional(),spec_writer:SpecWriterConfigSchema.optional(),tool_output:exports_external.object({truncation_enabled:exports_external.boolean().default(!0),max_lines:exports_external.number().min(10).max(500).default(150),per_tool:exports_external.record(exports_external.string(),exports_external.number()).optional(),truncation_tools:exports_external.array(exports_external.string()).optional().describe("Tools to apply output truncation to. Defaults to diff, symbols, bash, shell, test_runner, lint, pre_check_batch, complexity_hotspots, pkg_audit, sbom_generate, schema_drift.")}).optional(),slop_detector:SlopDetectorConfigSchema.optional(),todo_gate:exports_external.object({enabled:exports_external.boolean().default(!0),max_high_priority:exports_external.number().int().min(-1).default(0).describe("Max new high-priority TODOs (FIXME/HACK/XXX) before warning. 0 = warn on any. Set to -1 to disable."),block_on_threshold:exports_external.boolean().default(!1).describe("If true, block phase completion when threshold exceeded. Default: advisory only.")}).optional(),incremental_verify:IncrementalVerifyConfigSchema.optional(),compaction_service:CompactionConfigSchema.optional(),prm:PrmConfigSchema.optional(),council:CouncilConfigSchema.optional(),parallelization:ParallelizationConfigSchema.optional(),worktree:WorktreeIsolationConfigSchema.optional(),turbo:TurboConfigSchema.optional(),turbo_mode:exports_external.boolean().default(!1).optional(),quiet:exports_external.boolean().default(!0).optional(),version_check:exports_external.boolean().default(!0).optional(),full_auto:exports_external.object({enabled:exports_external.boolean().default(!1),locked:exports_external.boolean().default(!1),critic_model:exports_external.string().optional(),max_interactions_per_phase:exports_external.number().int().min(5).max(200).default(50),deadlock_threshold:exports_external.number().int().min(2).max(10).default(3),escalation_mode:exports_external.enum(["pause","terminate"]).default("pause"),mode:exports_external.enum(["assisted","supervised","strict"]).default("supervised"),fail_closed:exports_external.boolean().default(!0),permission_policy:exports_external.object({enabled:exports_external.boolean().default(!0),trusted_roots:exports_external.array(exports_external.string()).default(["."]),trusted_domains:exports_external.array(exports_external.string()).default([]),protected_paths:exports_external.array(exports_external.string()).default([".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"]),allow_defaults:exports_external.boolean().default(!0)}).default(()=>({enabled:!0,trusted_roots:["."],trusted_domains:[],protected_paths:[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"],allow_defaults:!0})),denials:exports_external.object({max_consecutive:exports_external.number().int().min(1).max(50).default(3),max_total:exports_external.number().int().min(1).max(500).default(20),on_limit:exports_external.enum(["pause","terminate"]).default("pause")}).default(()=>({max_consecutive:3,max_total:20,on_limit:"pause"})),oversight:exports_external.object({on_plan_change:exports_external.boolean().default(!0),on_task_completion:exports_external.boolean().default(!1),on_phase_boundary:exports_external.boolean().default(!0),on_high_risk_action:exports_external.boolean().default(!0),on_subagent_return_warning:exports_external.boolean().default(!0),every_tool_calls:exports_external.number().int().min(0).max(1e4).default(25),every_architect_turns:exports_external.number().int().min(0).max(1000).default(5),every_minutes:exports_external.number().int().min(0).max(1440).default(20)}).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}))}).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}})),pr_monitor:PrMonitorConfigSchema.optional(),external_skills:ExternalSkillsConfigSchema.optional(),skills:SkillsConfigSchema.optional()})});import*as fs from"node:fs";import*as fsPromises from"node:fs/promises";import*as os from"node:os";import*as path from"node:path";function getUserConfigDir(){return process.env.XDG_CONFIG_HOME||path.join(os.homedir(),".config")}function loadRawConfigFromPath(configPath){try{if(fs.statSync(configPath).size>MAX_CONFIG_FILE_BYTES)return console.warn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),console.warn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let content=fs.readFileSync(configPath,"utf-8");if(content.length>MAX_CONFIG_FILE_BYTES)return console.warn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),console.warn("[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 console.warn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),console.warn("[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(error48){if(!(error48 instanceof Error&&("code"in error48)&&error48.code==="ENOENT")){let errorMessage=error48 instanceof Error?error48.message:String(error48);return console.warn(`[opencode-swarm] ⚠️ CONFIG LOAD FAILURE — config exists at ${configPath} but could not be loaded: ${errorMessage}`),console.warn("[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,console.warn("[opencode-swarm] Migrated v6.12 presets config to agents format. Consider updating your opencode-swarm.json."),migrated}}return raw}function sanitizeExternalSkillsConfig(raw){if(!("external_skills"in raw)||raw.external_skills===void 0)return raw;let esResult=ExternalSkillsConfigSchema.safeParse(raw.external_skills);if(esResult.success)return{...raw,external_skills:resolveExternalSkillsConfig(esResult.data)};console.warn("[opencode-swarm] external_skills config validation failed:"),console.warn(esResult.error.format()),console.warn("[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,cleaned}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 loadPluginConfig(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),userResult=loadRawConfigFromPath(userConfigPath),projectResult=loadRawConfigFromPath(projectConfigPath),rawUserConfig=userResult.config,rawProjectConfig=projectResult.config,loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError,mergedRaw=rawUserConfig??{};if(rawProjectConfig)mergedRaw=deepMerge(mergedRaw,rawProjectConfig);if(rawFullAutoLocked(rawUserConfig)||rawFullAutoLocked(rawProjectConfig)){let fullAutoRaw=mergedRaw.full_auto&&typeof mergedRaw.full_auto==="object"&&!Array.isArray(mergedRaw.full_auto)?mergedRaw.full_auto:{};mergedRaw={...mergedRaw,full_auto:{...fullAutoRaw,locked:!0}}}mergedRaw=migratePresetsConfig(mergedRaw),mergedRaw=sanitizeExternalSkillsConfig(mergedRaw);let result=PluginConfigSchema.safeParse(mergedRaw);if(!result.success){if(rawUserConfig){let userParseResult=PluginConfigSchema.safeParse(sanitizeExternalSkillsConfig(rawUserConfig??{}));if(userParseResult.success)return console.warn("[opencode-swarm] Project config ignored due to validation errors. Using user config."),userParseResult.data}return console.warn("[opencode-swarm] Merged config validation failed:"),console.warn(result.error.format()),console.warn("[opencode-swarm] ⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."),PluginConfigSchema.parse({guardrails:{enabled:!0}})}if(loadedFromFile&&configHadErrors)return PluginConfigSchema.parse({...mergedRaw,guardrails:{enabled:!0}});return result.data}function loadPluginConfigWithMeta(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),userResult=loadRawConfigFromPath(userConfigPath),projectResult=loadRawConfigFromPath(projectConfigPath),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError;return{config:loadPluginConfig(directory),loadedFromFile,configHadErrors}}async function loadRawConfigFromPathAsync(configPath){try{if((await fsPromises.stat(configPath)).size>MAX_CONFIG_FILE_BYTES)return console.warn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),console.warn("[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 console.warn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),console.warn("[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 console.warn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),console.warn("[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(error48){if(error48.code==="ENOENT")return{config:null,fileExisted:!1,hadError:!1};return console.warn(`[opencode-swarm] Failed to load config from ${configPath}:`,error48 instanceof Error?error48.message:String(error48)),{config:null,fileExisted:!0,hadError:!0}}}function reduceParsedConfig(rawUserConfig,rawProjectConfig,loadedFromFile,configHadErrors){let mergedRaw=rawUserConfig??{};if(rawProjectConfig)mergedRaw=deepMerge(mergedRaw,rawProjectConfig);mergedRaw=migratePresetsConfig(mergedRaw),mergedRaw=sanitizeExternalSkillsConfig(mergedRaw);let result=PluginConfigSchema.safeParse(mergedRaw);if(!result.success){if(rawUserConfig){let userParseResult=PluginConfigSchema.safeParse(sanitizeExternalSkillsConfig(rawUserConfig??{}));if(userParseResult.success)return console.warn("[opencode-swarm] Project config ignored due to validation errors. Using user config."),userParseResult.data}return console.warn("[opencode-swarm] Merged config validation failed:"),console.warn(result.error.format()),console.warn("[opencode-swarm] ⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."),PluginConfigSchema.parse({guardrails:{enabled:!0}})}if(loadedFromFile&&configHadErrors)return PluginConfigSchema.parse({...mergedRaw,guardrails:{enabled:!0}});return result.data}async function loadPluginConfigWithMetaAsync(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),[userResult,projectResult]=await Promise.all([loadRawConfigFromPathAsync(userConfigPath),loadRawConfigFromPathAsync(projectConfigPath)]),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError;return{config:reduceParsedConfig(userResult.config,projectResult.config,loadedFromFile,configHadErrors),loadedFromFile,configHadErrors}}function loadAgentPrompt(agentName){let promptsDir=path.join(getUserConfigDir(),"opencode",PROMPTS_DIR_NAME),result={},promptPath=path.join(promptsDir,`${agentName}.md`);if(fs.existsSync(promptPath))try{result.prompt=fs.readFileSync(promptPath,"utf-8")}catch(error48){console.warn(`[opencode-swarm] Error reading prompt file ${promptPath}:`,error48 instanceof Error?error48.message:String(error48))}let appendPromptPath=path.join(promptsDir,`${agentName}_append.md`);if(fs.existsSync(appendPromptPath))try{result.appendPrompt=fs.readFileSync(appendPromptPath,"utf-8")}catch(error48){console.warn(`[opencode-swarm] Error reading append prompt ${appendPromptPath}:`,error48 instanceof Error?error48.message:String(error48))}return result}var CONFIG_FILENAME="opencode-swarm.json",PROMPTS_DIR_NAME="opencode-swarm",MAX_CONFIG_FILE_BYTES=102400;var init_loader=__esm(()=>{init_schema()});var ExecutionProfileSchema,TaskStatusSchema,TaskSizeSchema,PhaseStatusSchema,MigrationStatusSchema,TaskSchema,PhaseSchema,PlanSchema;var init_plan_schema=__esm(()=>{init_zod();ExecutionProfileSchema=exports_external.object({parallelization_enabled:exports_external.boolean().default(!1),max_concurrent_tasks:exports_external.number().int().min(1).max(64).default(10),council_parallel:exports_external.boolean().default(!0),locked:exports_external.boolean().default(!1),auto_proceed:exports_external.boolean().default(!1)}),TaskStatusSchema=exports_external.enum(["pending","in_progress","completed","blocked","closed"]),TaskSizeSchema=exports_external.enum(["small","medium","large"]),PhaseStatusSchema=exports_external.enum(["pending","in_progress","complete","completed","blocked","closed"]),MigrationStatusSchema=exports_external.enum(["native","migrated","migration_failed"]),TaskSchema=exports_external.object({id:exports_external.string(),phase:exports_external.number().int().min(1),status:TaskStatusSchema.default("pending"),size:TaskSizeSchema.default("small"),description:exports_external.string().min(1),depends:exports_external.array(exports_external.string()).default([]),acceptance:exports_external.string().optional(),files_touched:exports_external.array(exports_external.string()).default([]),evidence_path:exports_external.string().optional(),blocked_reason:exports_external.string().optional()}),PhaseSchema=exports_external.object({id:exports_external.number().int().min(1),name:exports_external.string().min(1),status:PhaseStatusSchema.default("pending"),tasks:exports_external.array(TaskSchema).default([]),type:exports_external.enum(["code","non-code"]).optional(),required_agents:exports_external.array(exports_external.string()).optional()}),PlanSchema=exports_external.object({schema_version:exports_external.literal("1.0.0"),title:exports_external.string().min(1),swarm:exports_external.string().min(1),current_phase:exports_external.number().int().min(1).optional(),phases:exports_external.array(PhaseSchema).min(1),migration_status:MigrationStatusSchema.optional(),specMtime:exports_external.string().optional(),specHash:exports_external.string().optional(),execution_profile:ExecutionProfileSchema.optional()})});function stripCodeBlocks(content){return content.replace(FENCED_BLOCK_PATTERN,"").replace(INLINE_CODE_PATTERN,"")}function getLineNumber(content,position){return(content.substring(0,position).match(/\n/g)||[]).length+1}function validateSpecContent(content){let issues=[];if(!content||content.trim().length===0)return{valid:!1,issues:[{line:1,message:"Content is empty"}]};let strippedContent=stripCodeBlocks(content),frMatches=strippedContent.match(FR_ID_PATTERN);if(!frMatches||frMatches.length===0)issues.push({line:1,message:"No FR-### requirement IDs found in spec content"});let obligationMatches=strippedContent.match(OBLIGATION_PATTERN);if(!obligationMatches||obligationMatches.length===0)issues.push({line:1,message:"No obligation keywords (MUST, SHALL, SHOULD, MAY) found in spec content"});let sectionMatches=strippedContent.match(SECTION_HEADER_PATTERN);if(!sectionMatches||sectionMatches.length===0)issues.push({line:1,message:"No section headers (## Section Name) found in spec content"});let idMatches=strippedContent.matchAll(/\bFR-(\d{3})\b/g);for(let idMatch of idMatches)if(parseInt(idMatch[1],10)===0){let pos=idMatch.index;issues.push({line:getLineNumber(strippedContent,pos),message:`Invalid FR-ID "${idMatch[0]}" — number must be 001-999`})}return{valid:issues.length===0,issues}}var ObligationSchema,SpecRequirementSchema,SpecScenarioSchema,SpecSectionSchema,SwarmSpecSchema,SpecDeltaSchema,DeltaSpecSchema,FENCED_BLOCK_PATTERN,INLINE_CODE_PATTERN,FR_ID_PATTERN,OBLIGATION_PATTERN,SECTION_HEADER_PATTERN;var init_spec_schema=__esm(()=>{init_zod();ObligationSchema=exports_external.enum(["MUST","SHALL","SHOULD","MAY"]),SpecRequirementSchema=exports_external.object({id:exports_external.string().regex(/^FR-(?!000)\d{3}$/,"Requirement ID must match FR-### pattern (e.g., FR-001)"),obligation:ObligationSchema,text:exports_external.string().min(1)}),SpecScenarioSchema=exports_external.object({name:exports_external.string().min(1),given:exports_external.array(exports_external.string()).optional().default([]),when:exports_external.array(exports_external.string()).min(1,'Scenario must have at least one "when" clause'),thenClauses:exports_external.array(exports_external.string()).min(1,'Scenario must have at least one "then" clause')}),SpecSectionSchema=exports_external.object({name:exports_external.string().min(1),requirements:exports_external.array(SpecRequirementSchema).default([])}),SwarmSpecSchema=exports_external.object({title:exports_external.string().min(1),purpose:exports_external.string().min(1),sections:exports_external.array(SpecSectionSchema).min(1,"Spec must have at least one section")}),SpecDeltaSchema=exports_external.object({added:exports_external.array(SpecRequirementSchema).default([]),modified:exports_external.array(SpecRequirementSchema).default([]),removed:exports_external.array(SpecRequirementSchema).default([])}),DeltaSpecSchema=exports_external.union([SwarmSpecSchema,SpecDeltaSchema]),FENCED_BLOCK_PATTERN=/```[\s\S]*?```/g,INLINE_CODE_PATTERN=/`[^`]*`/g,FR_ID_PATTERN=/\bFR-\d{3}\b/g,OBLIGATION_PATTERN=/\b(MUST|SHALL|SHOULD|MAY)\b/g,SECTION_HEADER_PATTERN=/^##\s+.+$/gm});var exports_config={};__export(exports_config,{validateSpecContent:()=>validateSpecContent,loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadAgentPrompt:()=>loadAgentPrompt,isSubagent:()=>isSubagent,isQAAgent:()=>isQAAgent,_internals:()=>_internals2,WorktreeIsolationConfigSchema:()=>WorktreeIsolationConfigSchema,TurboConfigSchema:()=>TurboConfigSchema,TestEvidenceSchema:()=>TestEvidenceSchema,TaskStatusSchema:()=>TaskStatusSchema,TaskSizeSchema:()=>TaskSizeSchema,TaskSchema:()=>TaskSchema,SwarmSpecSchema:()=>SwarmSpecSchema,SwarmConfigSchema:()=>SwarmConfigSchema,SpecSectionSchema:()=>SpecSectionSchema,SpecScenarioSchema:()=>SpecScenarioSchema,SpecRequirementSchema:()=>SpecRequirementSchema,SpecDeltaSchema:()=>SpecDeltaSchema,SkillPropagationConfigSchema:()=>SkillPropagationConfigSchema,ReviewEvidenceSchema:()=>ReviewEvidenceSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QA_AGENTS:()=>QA_AGENTS,PricingConfigSchema:()=>PricingConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanSchema:()=>PlanSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseStatusSchema:()=>PhaseStatusSchema,PhaseSchema:()=>PhaseSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,PIPELINE_AGENTS:()=>PIPELINE_AGENTS,ObligationSchema:()=>ObligationSchema,ORCHESTRATOR_NAME:()=>ORCHESTRATOR_NAME,NoteEvidenceSchema:()=>NoteEvidenceSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MigrationStatusSchema:()=>MigrationStatusSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,EvidenceVerdictSchema:()=>EvidenceVerdictSchema,EvidenceTypeSchema:()=>EvidenceTypeSchema,EvidenceSchema:()=>EvidenceSchema,EvidenceBundleSchema:()=>EvidenceBundleSchema,EVIDENCE_MAX_TASK_BYTES:()=>EVIDENCE_MAX_TASK_BYTES,EVIDENCE_MAX_PATCH_BYTES:()=>EVIDENCE_MAX_PATCH_BYTES,EVIDENCE_MAX_JSON_BYTES:()=>EVIDENCE_MAX_JSON_BYTES,DiffEvidenceSchema:()=>DiffEvidenceSchema,DeltaSpecSchema:()=>DeltaSpecSchema,DEFAULT_MODELS:()=>DEFAULT_MODELS,BaseEvidenceSchema:()=>BaseEvidenceSchema,AutomationModeSchema:()=>AutomationModeSchema,AutomationConfigSchema:()=>AutomationConfigSchema,AutomationCapabilitiesSchema:()=>AutomationCapabilitiesSchema,ApprovalEvidenceSchema:()=>ApprovalEvidenceSchema,AgentOverrideConfigSchema:()=>AgentOverrideConfigSchema,ALL_SUBAGENT_NAMES:()=>ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES:()=>ALL_AGENT_NAMES});var _internals2;var init_config=__esm(()=>{init_constants();init_evidence_schema();init_loader();init_loader();init_plan_schema();init_schema();init_spec_schema();_internals2={loadPluginConfigWithMeta}});function addDeferredWarning(warning){if(deferredWarnings.length<50)deferredWarnings.push(warning)}function getDeferredWarnings(){return[...deferredWarnings]}function clearDeferredWarnings(){deferredWarnings.length=0}var deferredWarnings;var init_warning_buffer=__esm(()=>{deferredWarnings=[]});function resolvePrompt(base,custom2,append){if(custom2)return custom2;if(append)return`${base}
158
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry);continue}}}}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=(zodSchema)=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"))schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema);else Object.assign(schema2,refSchema);if(Object.assign(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached))delete schema2[key]}if(refSchema.$ref&&refSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key]))delete schema2[key]}}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){if(schema2.$ref=parentSeen.schema.$ref,parentSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key]))delete schema2[key]}}}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);let result={};if(ctx.target==="draft-2020-12")result.$schema="https://json-schema.org/draft/2020-12/schema";else if(ctx.target==="draft-07")result.$schema="http://json-schema.org/draft-07/schema#";else if(ctx.target==="draft-04")result.$schema="http://json-schema.org/draft-04/schema#";else if(ctx.target==="openapi-3.0");if(ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);let defs=ctx.external?.defs??{};for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.def&&seen.defId)defs[seen.defId]=seen.def}if(ctx.external);else if(Object.keys(defs).length>0)if(ctx.target==="draft-2020-12")result.$defs=defs;else result.definitions=defs;try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch(_err){throw Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;if(def.rest&&isTransforming(def.rest,ctx))return!0;return!1}return!1}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{let ctx=initializeContext({...params,processors});return process2(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return process2(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var init_to_json_schema=__esm(()=>{init_registries()});function toJSONSchema(input,params){if("_idmap"in input){let registry2=input,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema]=entry;process2(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema]=entry;extractDefs(ctx2,schema),schemas[key]=finalize(ctx2,schema)}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return process2(input,ctx),extractDefs(ctx,input),finalize(ctx,input)}var formatMap,stringProcessor=(schema,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){if(json.format=formatMap[format]??format,json.format==="")delete json.format;if(format==="time")delete json.format}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){let regexes=[...patterns];if(regexes.length===1)json.pattern=regexes[0].source;else if(regexes.length>1)json.allOf=[...regexes.map((regex)=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}},numberProcessor=(schema,ctx,_json,_params)=>{let json=_json,{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema._zod.bag;if(typeof format==="string"&&format.includes("int"))json.type="integer";else json.type="number";if(typeof exclusiveMinimum==="number")if(ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0;else json.exclusiveMinimum=exclusiveMinimum;if(typeof minimum==="number"){if(json.minimum=minimum,typeof exclusiveMinimum==="number"&&ctx.target!=="draft-04")if(exclusiveMinimum>=minimum)delete json.minimum;else delete json.exclusiveMinimum}if(typeof exclusiveMaximum==="number")if(ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0;else json.exclusiveMaximum=exclusiveMaximum;if(typeof maximum==="number"){if(json.maximum=maximum,typeof exclusiveMaximum==="number"&&ctx.target!=="draft-04")if(exclusiveMaximum<=maximum)delete json.maximum;else delete json.exclusiveMaximum}if(typeof multipleOf==="number")json.multipleOf=multipleOf},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0")json.type="string",json.nullable=!0,json.enum=[null];else json.type="null"},undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json,_params)=>{let def=schema._zod.def,values=getEnumValues(def.entries);if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values},literalProcessor=(schema,ctx,json,_params)=>{let def=schema._zod.def,vals=[];for(let val of def.values)if(val===void 0){if(ctx.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof val==="bigint")if(ctx.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else vals.push(Number(val));else vals.push(val);if(vals.length===0);else if(vals.length===1){let val=vals[0];if(json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.enum=[val];else json.const=val}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}},nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json,_params)=>{let _json=json,pattern=schema._zod.pattern;if(!pattern)throw Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json,_params)=>{let _json=json,file={type:"string",format:"binary",contentEncoding:"binary"},{minimum,maximum,mime}=schema._zod.bag;if(minimum!==void 0)file.minLength=minimum;if(maximum!==void 0)file.maxLength=maximum;if(mime)if(mime.length===1)file.contentMediaType=mime[0],Object.assign(_json,file);else Object.assign(_json,file),_json.anyOf=mime.map((m)=>({contentMediaType:m}));else Object.assign(_json,file)},successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array",json.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})},objectProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object",json.properties={};let shape=def.shape;for(let key in shape)json.properties[key]=process2(shape[key],ctx,{...params,path:[...params.path,"properties",key]});let allKeys=new Set(Object.keys(shape)),requiredKeys=new Set([...allKeys].filter((key)=>{let v=def.shape[key]._zod;if(ctx.io==="input")return v.optin===void 0;else return v.optout===void 0}));if(requiredKeys.size>0)json.required=Array.from(requiredKeys);if(def.catchall?._zod.def.type==="never")json.additionalProperties=!1;else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=!1}else if(def.catchall)json.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive)json.oneOf=options;else json.anyOf=options},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf},tupleProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?process2(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;if(ctx.target==="draft-2020-12"){if(json.prefixItems=prefixItems,rest)json.items=rest}else if(ctx.target==="openapi-3.0"){if(json.items={anyOf:prefixItems},rest)json.items.anyOf.push(rest);if(json.minItems=prefixItems.length,!rest)json.maxItems=prefixItems.length}else if(json.items=prefixItems,rest)json.additionalItems=rest;let{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum},recordProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object";let keyType=def.keyType,patterns=keyType._zod.bag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let pattern of patterns)json.patternProperties[pattern.source]=valueSchema}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12")json.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});json.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values;if(keyValues){let validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0)json.required=validKeyValues}},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=process2(def.innerType,ctx,params),seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0")seen.ref=def.innerType,json.nullable=!0;else json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.default=JSON.parse(JSON.stringify(def.defaultValue))},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io==="input")json._prefault=JSON.parse(JSON.stringify(def.defaultValue))},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,innerType=ctx.io==="input"?def.in._zod.def.type==="transform"?def.out:def.in:def.out;process2(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;process2(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors;var init_json_schema_processors=__esm(()=>{init_to_json_schema();init_util();formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}});class JSONSchemaGenerator{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return process2(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_,...plainResult}=result;return plainResult}}var init_json_schema_generator=__esm(()=>{init_json_schema_processors();init_to_json_schema()});var exports_json_schema={};var init_json_schema=()=>{};var exports_core2={};__export(exports_core2,{version:()=>version,util:()=>exports_util,treeifyError:()=>treeifyError,toJSONSchema:()=>toJSONSchema,toDotPath:()=>toDotPath,safeParseAsync:()=>safeParseAsync,safeParse:()=>safeParse,safeEncodeAsync:()=>safeEncodeAsync,safeEncode:()=>safeEncode,safeDecodeAsync:()=>safeDecodeAsync,safeDecode:()=>safeDecode,registry:()=>registry,regexes:()=>exports_regexes,process:()=>process2,prettifyError:()=>prettifyError,parseAsync:()=>parseAsync,parse:()=>parse,meta:()=>meta,locales:()=>exports_locales,isValidJWT:()=>isValidJWT,isValidBase64URL:()=>isValidBase64URL,isValidBase64:()=>isValidBase64,initializeContext:()=>initializeContext,globalRegistry:()=>globalRegistry,globalConfig:()=>globalConfig,formatError:()=>formatError,flattenError:()=>flattenError,finalize:()=>finalize,extractDefs:()=>extractDefs,encodeAsync:()=>encodeAsync,encode:()=>encode,describe:()=>describe,decodeAsync:()=>decodeAsync,decode:()=>decode,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,config:()=>config,clone:()=>clone,_xor:()=>_xor,_xid:()=>_xid,_void:()=>_void,_uuidv7:()=>_uuidv7,_uuidv6:()=>_uuidv6,_uuidv4:()=>_uuidv4,_uuid:()=>_uuid,_url:()=>_url,_uppercase:()=>_uppercase,_unknown:()=>_unknown,_union:()=>_union,_undefined:()=>_undefined2,_ulid:()=>_ulid,_uint64:()=>_uint64,_uint32:()=>_uint32,_tuple:()=>_tuple,_trim:()=>_trim,_transform:()=>_transform,_toUpperCase:()=>_toUpperCase,_toLowerCase:()=>_toLowerCase,_templateLiteral:()=>_templateLiteral,_symbol:()=>_symbol,_superRefine:()=>_superRefine,_success:()=>_success,_stringbool:()=>_stringbool,_stringFormat:()=>_stringFormat,_string:()=>_string,_startsWith:()=>_startsWith,_slugify:()=>_slugify,_size:()=>_size,_set:()=>_set,_safeParseAsync:()=>_safeParseAsync,_safeParse:()=>_safeParse,_safeEncodeAsync:()=>_safeEncodeAsync,_safeEncode:()=>_safeEncode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeDecode:()=>_safeDecode,_regex:()=>_regex,_refine:()=>_refine,_record:()=>_record,_readonly:()=>_readonly,_property:()=>_property,_promise:()=>_promise,_positive:()=>_positive,_pipe:()=>_pipe,_parseAsync:()=>_parseAsync,_parse:()=>_parse,_overwrite:()=>_overwrite,_optional:()=>_optional,_number:()=>_number,_nullable:()=>_nullable,_null:()=>_null2,_normalize:()=>_normalize,_nonpositive:()=>_nonpositive,_nonoptional:()=>_nonoptional,_nonnegative:()=>_nonnegative,_never:()=>_never,_negative:()=>_negative,_nativeEnum:()=>_nativeEnum,_nanoid:()=>_nanoid,_nan:()=>_nan,_multipleOf:()=>_multipleOf,_minSize:()=>_minSize,_minLength:()=>_minLength,_min:()=>_gte,_mime:()=>_mime,_maxSize:()=>_maxSize,_maxLength:()=>_maxLength,_max:()=>_lte,_map:()=>_map,_mac:()=>_mac,_lte:()=>_lte,_lt:()=>_lt,_lowercase:()=>_lowercase,_literal:()=>_literal,_length:()=>_length,_lazy:()=>_lazy,_ksuid:()=>_ksuid,_jwt:()=>_jwt,_isoTime:()=>_isoTime,_isoDuration:()=>_isoDuration,_isoDateTime:()=>_isoDateTime,_isoDate:()=>_isoDate,_ipv6:()=>_ipv6,_ipv4:()=>_ipv4,_intersection:()=>_intersection,_int64:()=>_int64,_int32:()=>_int32,_int:()=>_int,_includes:()=>_includes,_guid:()=>_guid,_gte:()=>_gte,_gt:()=>_gt,_float64:()=>_float64,_float32:()=>_float32,_file:()=>_file,_enum:()=>_enum,_endsWith:()=>_endsWith,_encodeAsync:()=>_encodeAsync,_encode:()=>_encode,_emoji:()=>_emoji2,_email:()=>_email,_e164:()=>_e164,_discriminatedUnion:()=>_discriminatedUnion,_default:()=>_default,_decodeAsync:()=>_decodeAsync,_decode:()=>_decode,_date:()=>_date,_custom:()=>_custom,_cuid2:()=>_cuid2,_cuid:()=>_cuid,_coercedString:()=>_coercedString,_coercedNumber:()=>_coercedNumber,_coercedDate:()=>_coercedDate,_coercedBoolean:()=>_coercedBoolean,_coercedBigint:()=>_coercedBigint,_cidrv6:()=>_cidrv6,_cidrv4:()=>_cidrv4,_check:()=>_check,_catch:()=>_catch,_boolean:()=>_boolean,_bigint:()=>_bigint,_base64url:()=>_base64url,_base64:()=>_base64,_array:()=>_array,_any:()=>_any,TimePrecision:()=>TimePrecision,NEVER:()=>NEVER,JSONSchemaGenerator:()=>JSONSchemaGenerator,JSONSchema:()=>exports_json_schema,Doc:()=>Doc,$output:()=>$output,$input:()=>$input,$constructor:()=>$constructor,$brand:()=>$brand,$ZodXor:()=>$ZodXor,$ZodXID:()=>$ZodXID,$ZodVoid:()=>$ZodVoid,$ZodUnknown:()=>$ZodUnknown,$ZodUnion:()=>$ZodUnion,$ZodUndefined:()=>$ZodUndefined,$ZodUUID:()=>$ZodUUID,$ZodURL:()=>$ZodURL,$ZodULID:()=>$ZodULID,$ZodType:()=>$ZodType,$ZodTuple:()=>$ZodTuple,$ZodTransform:()=>$ZodTransform,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodSymbol:()=>$ZodSymbol,$ZodSuccess:()=>$ZodSuccess,$ZodStringFormat:()=>$ZodStringFormat,$ZodString:()=>$ZodString,$ZodSet:()=>$ZodSet,$ZodRegistry:()=>$ZodRegistry,$ZodRecord:()=>$ZodRecord,$ZodRealError:()=>$ZodRealError,$ZodReadonly:()=>$ZodReadonly,$ZodPromise:()=>$ZodPromise,$ZodPrefault:()=>$ZodPrefault,$ZodPipe:()=>$ZodPipe,$ZodOptional:()=>$ZodOptional,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodObject:()=>$ZodObject,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodNumber:()=>$ZodNumber,$ZodNullable:()=>$ZodNullable,$ZodNull:()=>$ZodNull,$ZodNonOptional:()=>$ZodNonOptional,$ZodNever:()=>$ZodNever,$ZodNanoID:()=>$ZodNanoID,$ZodNaN:()=>$ZodNaN,$ZodMap:()=>$ZodMap,$ZodMAC:()=>$ZodMAC,$ZodLiteral:()=>$ZodLiteral,$ZodLazy:()=>$ZodLazy,$ZodKSUID:()=>$ZodKSUID,$ZodJWT:()=>$ZodJWT,$ZodIntersection:()=>$ZodIntersection,$ZodISOTime:()=>$ZodISOTime,$ZodISODuration:()=>$ZodISODuration,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODate:()=>$ZodISODate,$ZodIPv6:()=>$ZodIPv6,$ZodIPv4:()=>$ZodIPv4,$ZodGUID:()=>$ZodGUID,$ZodFunction:()=>$ZodFunction,$ZodFile:()=>$ZodFile,$ZodExactOptional:()=>$ZodExactOptional,$ZodError:()=>$ZodError,$ZodEnum:()=>$ZodEnum,$ZodEncodeError:()=>$ZodEncodeError,$ZodEmoji:()=>$ZodEmoji,$ZodEmail:()=>$ZodEmail,$ZodE164:()=>$ZodE164,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodDefault:()=>$ZodDefault,$ZodDate:()=>$ZodDate,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodCustom:()=>$ZodCustom,$ZodCodec:()=>$ZodCodec,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheck:()=>$ZodCheck,$ZodCatch:()=>$ZodCatch,$ZodCUID2:()=>$ZodCUID2,$ZodCUID:()=>$ZodCUID,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodBoolean:()=>$ZodBoolean,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBigInt:()=>$ZodBigInt,$ZodBase64URL:()=>$ZodBase64URL,$ZodBase64:()=>$ZodBase64,$ZodAsyncError:()=>$ZodAsyncError,$ZodArray:()=>$ZodArray,$ZodAny:()=>$ZodAny});var init_core2=__esm(()=>{init_util();init_regexes();init_locales();init_json_schema_processors();init_json_schema_generator();init_json_schema();init_core();init_parse();init_errors();init_schemas();init_checks();init_versions();init_registries();init_api();init_to_json_schema()});var exports_checks2={};__export(exports_checks2,{uppercase:()=>_uppercase,trim:()=>_trim,toUpperCase:()=>_toUpperCase,toLowerCase:()=>_toLowerCase,startsWith:()=>_startsWith,slugify:()=>_slugify,size:()=>_size,regex:()=>_regex,property:()=>_property,positive:()=>_positive,overwrite:()=>_overwrite,normalize:()=>_normalize,nonpositive:()=>_nonpositive,nonnegative:()=>_nonnegative,negative:()=>_negative,multipleOf:()=>_multipleOf,minSize:()=>_minSize,minLength:()=>_minLength,mime:()=>_mime,maxSize:()=>_maxSize,maxLength:()=>_maxLength,lte:()=>_lte,lt:()=>_lt,lowercase:()=>_lowercase,length:()=>_length,includes:()=>_includes,gte:()=>_gte,gt:()=>_gt,endsWith:()=>_endsWith});var init_checks2=__esm(()=>{init_core2()});var exports_iso={};__export(exports_iso,{time:()=>time2,duration:()=>duration2,datetime:()=>datetime2,date:()=>date2,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration;var init_iso=__esm(()=>{init_core2();init_schemas2();ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)})});var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:(mapper)=>formatError(inst,mapper)},flatten:{value:(mapper)=>flattenError(inst,mapper)},addIssue:{value:(issue2)=>{inst.issues.push(issue2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:(issues2)=>{inst.issues.push(...issues2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})},ZodError,ZodRealError;var init_errors2=__esm(()=>{init_core2();init_core2();init_util();ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,{Parent:Error})});var parse3,parseAsync2,safeParse2,safeParseAsync2,encode2,decode2,encodeAsync2,decodeAsync2,safeEncode2,safeDecode2,safeEncodeAsync2,safeDecodeAsync2;var init_parse2=__esm(()=>{init_core2();init_errors2();parse3=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError)});var exports_schemas2={};__export(exports_schemas2,{xor:()=>xor,xid:()=>xid2,void:()=>_void2,uuidv7:()=>uuidv7,uuidv6:()=>uuidv6,uuidv4:()=>uuidv4,uuid:()=>uuid2,url:()=>url,unknown:()=>unknown,union:()=>union,undefined:()=>_undefined3,ulid:()=>ulid2,uint64:()=>uint64,uint32:()=>uint32,tuple:()=>tuple,transform:()=>transform,templateLiteral:()=>templateLiteral,symbol:()=>symbol,superRefine:()=>superRefine,success:()=>success,stringbool:()=>stringbool,stringFormat:()=>stringFormat,string:()=>string2,strictObject:()=>strictObject,set:()=>set,refine:()=>refine,record:()=>record,readonly:()=>readonly,promise:()=>promise,preprocess:()=>preprocess,prefault:()=>prefault,pipe:()=>pipe,partialRecord:()=>partialRecord,optional:()=>optional,object:()=>object,number:()=>number2,nullish:()=>nullish2,nullable:()=>nullable,null:()=>_null3,nonoptional:()=>nonoptional,never:()=>never,nativeEnum:()=>nativeEnum,nanoid:()=>nanoid2,nan:()=>nan,meta:()=>meta2,map:()=>map,mac:()=>mac2,looseRecord:()=>looseRecord,looseObject:()=>looseObject,literal:()=>literal,lazy:()=>lazy,ksuid:()=>ksuid2,keyof:()=>keyof,jwt:()=>jwt,json:()=>json,ipv6:()=>ipv62,ipv4:()=>ipv42,intersection:()=>intersection,int64:()=>int64,int32:()=>int32,int:()=>int,instanceof:()=>_instanceof,httpUrl:()=>httpUrl,hostname:()=>hostname2,hex:()=>hex2,hash:()=>hash,guid:()=>guid2,function:()=>_function,float64:()=>float64,float32:()=>float32,file:()=>file,exactOptional:()=>exactOptional,enum:()=>_enum2,emoji:()=>emoji2,email:()=>email2,e164:()=>e1642,discriminatedUnion:()=>discriminatedUnion,describe:()=>describe2,date:()=>date3,custom:()=>custom,cuid2:()=>cuid22,cuid:()=>cuid3,codec:()=>codec,cidrv6:()=>cidrv62,cidrv4:()=>cidrv42,check:()=>check,catch:()=>_catch2,boolean:()=>boolean2,bigint:()=>bigint2,base64url:()=>base64url2,base64:()=>base642,array:()=>array,any:()=>any,_function:()=>_function,_default:()=>_default2,_ZodString:()=>_ZodString,ZodXor:()=>ZodXor,ZodXID:()=>ZodXID,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodUUID:()=>ZodUUID,ZodURL:()=>ZodURL,ZodULID:()=>ZodULID,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransform:()=>ZodTransform,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodSymbol:()=>ZodSymbol,ZodSuccess:()=>ZodSuccess,ZodStringFormat:()=>ZodStringFormat,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodRecord:()=>ZodRecord,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPrefault:()=>ZodPrefault,ZodPipe:()=>ZodPipe,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumberFormat:()=>ZodNumberFormat,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNonOptional:()=>ZodNonOptional,ZodNever:()=>ZodNever,ZodNanoID:()=>ZodNanoID,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodMAC:()=>ZodMAC,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodKSUID:()=>ZodKSUID,ZodJWT:()=>ZodJWT,ZodIntersection:()=>ZodIntersection,ZodIPv6:()=>ZodIPv6,ZodIPv4:()=>ZodIPv4,ZodGUID:()=>ZodGUID,ZodFunction:()=>ZodFunction,ZodFile:()=>ZodFile,ZodExactOptional:()=>ZodExactOptional,ZodEnum:()=>ZodEnum,ZodEmoji:()=>ZodEmoji,ZodEmail:()=>ZodEmail,ZodE164:()=>ZodE164,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodCustom:()=>ZodCustom,ZodCodec:()=>ZodCodec,ZodCatch:()=>ZodCatch,ZodCUID2:()=>ZodCUID2,ZodCUID:()=>ZodCUID,ZodCIDRv6:()=>ZodCIDRv6,ZodCIDRv4:()=>ZodCIDRv4,ZodBoolean:()=>ZodBoolean,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBigInt:()=>ZodBigInt,ZodBase64URL:()=>ZodBase64URL,ZodBase64:()=>ZodBase64,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny});function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function guid2(params){return _guid(ZodGUID,params)}function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:/^https?$/,hostname:exports_regexes.domain,...exports_util.normalizeParams(params)})}function emoji2(params){return _emoji2(ZodEmoji,params)}function nanoid2(params){return _nanoid(ZodNanoID,params)}function cuid3(params){return _cuid(ZodCUID,params)}function cuid22(params){return _cuid2(ZodCUID2,params)}function ulid2(params){return _ulid(ZodULID,params)}function xid2(params){return _xid(ZodXID,params)}function ksuid2(params){return _ksuid(ZodKSUID,params)}function ipv42(params){return _ipv4(ZodIPv4,params)}function mac2(params){return _mac(ZodMAC,params)}function ipv62(params){return _ipv6(ZodIPv6,params)}function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}function base642(params){return _base64(ZodBase64,params)}function base64url2(params){return _base64url(ZodBase64URL,params)}function e1642(params){return _e164(ZodE164,params)}function jwt(params){return _jwt(ZodJWT,params)}function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",exports_regexes.hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",exports_regexes.hex,_params)}function hash(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=exports_regexes[format];if(!regex)throw Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function bigint2(params){return _bigint(ZodBigInt,params)}function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}function symbol(params){return _symbol(ZodSymbol,params)}function _undefined3(params){return _undefined2(ZodUndefined,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function _void2(params){return _void(ZodVoid,params)}function date3(params){return _date(ZodDate,params)}function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}function object(shape,params){let def={type:"object",shape:shape??{},...exports_util.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...exports_util.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...exports_util.normalizeParams(params)})}function union(options,params){return new ZodUnion({type:"union",options,...exports_util.normalizeParams(params)})}function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...exports_util.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...exports_util.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest;return new ZodTuple({type:"tuple",items,rest:hasRest?_paramsOrRest:null,...exports_util.normalizeParams(params)})}function record(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...exports_util.normalizeParams(params)})}function partialRecord(keyType,valueType,params){let k=clone(keyType);return k._zod.values=void 0,new ZodRecord({type:"record",keyType:k,valueType,...exports_util.normalizeParams(params)})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...exports_util.normalizeParams(params)})}function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...exports_util.normalizeParams(params)})}function set(valueType,params){return new ZodSet({type:"set",valueType,...exports_util.normalizeParams(params)})}function _enum2(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...exports_util.normalizeParams(params)})}function file(params){return _file(ZodFile,params)}function transform(fn2){return new ZodTransform({type:"transform",transform:fn2})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...exports_util.normalizeParams(params)})}function success(innerType){return new ZodSuccess({type:"success",innerType})}function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function nan(params){return _nan(ZodNaN,params)}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...exports_util.normalizeParams(params)})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function promise(innerType){return new ZodPromise({type:"promise",innerType})}function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}function check(fn2){let ch=new $ZodCheck({check:"custom"});return ch._zod.check=fn2,ch}function custom(fn2,_params){return _custom(ZodCustom,fn2??(()=>!0),_params)}function refine(fn2,_params={}){return _refine(ZodCustom,fn2,_params)}function superRefine(fn2){return _superRefine(fn2)}function _instanceof(cls,params={}){let inst=new ZodCustom({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:!0,...exports_util.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=(payload)=>{if(!(payload.value instanceof cls))payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}function json(params){let jsonSchema=lazy(()=>{return union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn2,schema){return pipe(transform(fn2),schema)}var ZodType,_ZodString,ZodString,ZodStringFormat,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodMAC,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodJWT,ZodCustomStringFormat,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodBigIntFormat,ZodSymbol,ZodUndefined,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodVoid,ZodDate,ZodArray,ZodObject,ZodUnion,ZodXor,ZodDiscriminatedUnion,ZodIntersection,ZodTuple,ZodRecord,ZodMap,ZodSet,ZodEnum,ZodLiteral,ZodFile,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodSuccess,ZodCatch,ZodNaN,ZodPipe,ZodCodec,ZodReadonly,ZodTemplateLiteral,ZodLazy,ZodPromise,ZodFunction,ZodCustom,describe2,meta2,stringbool=(...args2)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args2);var init_schemas2=__esm(()=>{init_core2();init_core2();init_json_schema_processors();init_to_json_schema();init_checks2();init_iso();init_parse2();ZodType=$constructor("ZodType",(inst,def)=>{return $ZodType.init(inst,def),Object.assign(inst["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,"input"),output:createStandardJSONSchemaMethod(inst,"output")}}),inst.toJSONSchema=createToJSONSchemaMethod(inst,{}),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.check=(...checks2)=>{return inst.clone(exports_util.mergeDefs(def,{checks:[...def.checks??[],...checks2.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},inst.with=inst.check,inst.clone=(def2,params)=>clone(inst,def2,params),inst.brand=()=>inst,inst.register=(reg,meta2)=>{return reg.add(inst,meta2),inst},inst.parse=(data,params)=>parse3(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse2(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync2(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync2(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode2(inst,data,params),inst.decode=(data,params)=>decode2(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync2(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync2(inst,data,params),inst.safeEncode=(data,params)=>safeEncode2(inst,data,params),inst.safeDecode=(data,params)=>safeDecode2(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync2(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync2(inst,data,params),inst.refine=(check,params)=>inst.check(refine(check,params)),inst.superRefine=(refinement)=>inst.check(superRefine(refinement)),inst.overwrite=(fn2)=>inst.check(_overwrite(fn2)),inst.optional=()=>optional(inst),inst.exactOptional=()=>exactOptional(inst),inst.nullable=()=>nullable(inst),inst.nullish=()=>optional(nullable(inst)),inst.nonoptional=(params)=>nonoptional(inst,params),inst.array=()=>array(inst),inst.or=(arg)=>union([inst,arg]),inst.and=(arg)=>intersection(inst,arg),inst.transform=(tx)=>pipe(inst,transform(tx)),inst.default=(def2)=>_default2(inst,def2),inst.prefault=(def2)=>prefault(inst,def2),inst.catch=(params)=>_catch2(inst,params),inst.pipe=(target)=>pipe(inst,target),inst.readonly=()=>readonly(inst),inst.describe=(description)=>{let cl=inst.clone();return globalRegistry.add(cl,{description}),cl},Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst.meta=(...args2)=>{if(args2.length===0)return globalRegistry.get(inst);let cl=inst.clone();return globalRegistry.add(cl,args2[0]),cl},inst.isOptional=()=>inst.safeParse(void 0).success,inst.isNullable=()=>inst.safeParse(null).success,inst.apply=(fn2)=>fn2(inst),inst}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,inst.regex=(...args2)=>inst.check(_regex(...args2)),inst.includes=(...args2)=>inst.check(_includes(...args2)),inst.startsWith=(...args2)=>inst.check(_startsWith(...args2)),inst.endsWith=(...args2)=>inst.check(_endsWith(...args2)),inst.min=(...args2)=>inst.check(_minLength(...args2)),inst.max=(...args2)=>inst.check(_maxLength(...args2)),inst.length=(...args2)=>inst.check(_length(...args2)),inst.nonempty=(...args2)=>inst.check(_minLength(1,...args2)),inst.lowercase=(params)=>inst.check(_lowercase(params)),inst.uppercase=(params)=>inst.check(_uppercase(params)),inst.trim=()=>inst.check(_trim()),inst.normalize=(...args2)=>inst.check(_normalize(...args2)),inst.toLowerCase=()=>inst.check(_toLowerCase()),inst.toUpperCase=()=>inst.check(_toUpperCase()),inst.slugify=()=>inst.check(_slugify())}),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=(params)=>inst.check(_email(ZodEmail,params)),inst.url=(params)=>inst.check(_url(ZodURL,params)),inst.jwt=(params)=>inst.check(_jwt(ZodJWT,params)),inst.emoji=(params)=>inst.check(_emoji2(ZodEmoji,params)),inst.guid=(params)=>inst.check(_guid(ZodGUID,params)),inst.uuid=(params)=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=(params)=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=(params)=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=(params)=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=(params)=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=(params)=>inst.check(_guid(ZodGUID,params)),inst.cuid=(params)=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=(params)=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=(params)=>inst.check(_ulid(ZodULID,params)),inst.base64=(params)=>inst.check(_base64(ZodBase64,params)),inst.base64url=(params)=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=(params)=>inst.check(_xid(ZodXID,params)),inst.ksuid=(params)=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=(params)=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=(params)=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=(params)=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=(params)=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=(params)=>inst.check(_e164(ZodE164,params)),inst.datetime=(params)=>inst.check(datetime2(params)),inst.date=(params)=>inst.check(date2(params)),inst.time=(params)=>inst.check(time2(params)),inst.duration=(params)=>inst.check(duration2(params))});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.int=(params)=>inst.check(int(params)),inst.safe=(params)=>inst.check(int(params)),inst.positive=(params)=>inst.check(_gt(0,params)),inst.nonnegative=(params)=>inst.check(_gte(0,params)),inst.negative=(params)=>inst.check(_lt(0,params)),inst.nonpositive=(params)=>inst.check(_lte(0,params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params)),inst.step=(value,params)=>inst.check(_multipleOf(value,params)),inst.finite=()=>inst;let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??0.5),inst.isFinite=!0,inst.format=bag.format??null});ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>bigintProcessor(inst,ctx,json,params),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.positive=(params)=>inst.check(_gt(BigInt(0),params)),inst.negative=(params)=>inst.check(_lt(BigInt(0),params)),inst.nonpositive=(params)=>inst.check(_lte(BigInt(0),params)),inst.nonnegative=(params)=>inst.check(_gte(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null});ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>symbolProcessor(inst,ctx,json,params)});ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>undefinedProcessor(inst,ctx,json,params)});ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>anyProcessor(inst,ctx,json,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>voidProcessor(inst,ctx,json,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>dateProcessor(inst,ctx,json,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null});ZodArray=$constructor("ZodArray",(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element,inst.min=(minLength,params)=>inst.check(_minLength(minLength,params)),inst.nonempty=(params)=>inst.check(_minLength(1,params)),inst.max=(maxLength,params)=>inst.check(_maxLength(maxLength,params)),inst.length=(len,params)=>inst.check(_length(len,params)),inst.unwrap=()=>inst.element});ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),exports_util.defineLazy(inst,"shape",()=>{return def.shape}),inst.keyof=()=>_enum2(Object.keys(inst._zod.def.shape)),inst.catchall=(catchall)=>inst.clone({...inst._zod.def,catchall}),inst.passthrough=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.loose=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.strict=()=>inst.clone({...inst._zod.def,catchall:never()}),inst.strip=()=>inst.clone({...inst._zod.def,catchall:void 0}),inst.extend=(incoming)=>{return exports_util.extend(inst,incoming)},inst.safeExtend=(incoming)=>{return exports_util.safeExtend(inst,incoming)},inst.merge=(other)=>exports_util.merge(inst,other),inst.pick=(mask)=>exports_util.pick(inst,mask),inst.omit=(mask)=>exports_util.omit(inst,mask),inst.partial=(...args2)=>exports_util.partial(ZodOptional,inst,args2[0]),inst.required=(...args2)=>exports_util.required(ZodNonOptional,inst,args2[0])});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});ZodTuple=$constructor("ZodTuple",(inst,def)=>{$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>tupleProcessor(inst,ctx,json,params),inst.rest=(rest)=>inst.clone({...inst._zod.def,rest})});ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodMap=$constructor("ZodMap",(inst,def)=>{$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>mapProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args2)=>inst.check(_minSize(...args2)),inst.nonempty=(params)=>inst.check(_minSize(1,params)),inst.max=(...args2)=>inst.check(_maxSize(...args2)),inst.size=(...args2)=>inst.check(_size(...args2))});ZodSet=$constructor("ZodSet",(inst,def)=>{$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>setProcessor(inst,ctx,json,params),inst.min=(...args2)=>inst.check(_minSize(...args2)),inst.nonempty=(params)=>inst.check(_minSize(1,params)),inst.max=(...args2)=>inst.check(_maxSize(...args2)),inst.size=(...args2)=>inst.check(_size(...args2))});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>fileProcessor(inst,ctx,json,params),inst.min=(size,params)=>inst.check(_minSize(size,params)),inst.max=(size,params)=>inst.check(_maxSize(size,params)),inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});ZodTransform=$constructor("ZodTransform",(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=(issue2)=>{if(typeof issue2==="string")payload.issues.push(exports_util.issue(issue2,payload.value,def));else{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(exports_util.issue(_issue))}};let output=def.transform(payload.value,payload);if(output instanceof Promise)return output.then((output2)=>{return payload.value=output2,payload});return payload.value=output,payload}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>successProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nanProcessor(inst,ctx,json,params)});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>templateLiteralProcessor(inst,ctx,json,params)});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>lazyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.getter()});ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>promiseProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>functionProcessor(inst,ctx,json,params)});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});describe2=describe,meta2=meta});function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodIssueCode,ZodFirstPartyTypeKind;var init_compat=__esm(()=>{init_core2();ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(ZodFirstPartyTypeKind2){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}))});function detectVersion(schema,defaultTarget){let $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if($schema==="http://json-schema.org/draft-07/schema#")return"draft-7";if($schema==="http://json-schema.org/draft-04/schema#")return"draft-4";return defaultTarget??"draft-2020-12"}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let path=ref.slice(1).split("/").filter(Boolean);if(path.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){let key=path[1];if(!key||!ctx.defs[key])throw Error(`Reference not found: ${ref}`);return ctx.defs[key]}throw Error(`Reference not found: ${ref}`)}function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0)return z.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z.lazy(()=>{if(!ctx.refs.has(refPath))throw Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z.null();if(enumValues.length===0)return z.never();if(enumValues.length===1)return z.literal(enumValues[0]);if(enumValues.every((v)=>typeof v==="string"))return z.enum(enumValues);let literalSchemas=enumValues.map((v)=>z.literal(v));if(literalSchemas.length<2)return literalSchemas[0];return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z.literal(schema.const);let type=schema.type;if(Array.isArray(type)){let typeSchemas=type.map((t)=>{let typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0)return z.never();if(typeSchemas.length===1)return typeSchemas[0];return z.union(typeSchemas)}if(!type)return z.any();let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){let format=schema.format;if(format==="email")stringSchema=stringSchema.check(z.email());else if(format==="uri"||format==="uri-reference")stringSchema=stringSchema.check(z.url());else if(format==="uuid"||format==="guid")stringSchema=stringSchema.check(z.uuid());else if(format==="date-time")stringSchema=stringSchema.check(z.iso.datetime());else if(format==="date")stringSchema=stringSchema.check(z.iso.date());else if(format==="time")stringSchema=stringSchema.check(z.iso.time());else if(format==="duration")stringSchema=stringSchema.check(z.iso.duration());else if(format==="ipv4")stringSchema=stringSchema.check(z.ipv4());else if(format==="ipv6")stringSchema=stringSchema.check(z.ipv6());else if(format==="mac")stringSchema=stringSchema.check(z.mac());else if(format==="cidr")stringSchema=stringSchema.check(z.cidrv4());else if(format==="cidr-v6")stringSchema=stringSchema.check(z.cidrv6());else if(format==="base64")stringSchema=stringSchema.check(z.base64());else if(format==="base64url")stringSchema=stringSchema.check(z.base64url());else if(format==="e164")stringSchema=stringSchema.check(z.e164());else if(format==="jwt")stringSchema=stringSchema.check(z.jwt());else if(format==="emoji")stringSchema=stringSchema.check(z.emoji());else if(format==="nanoid")stringSchema=stringSchema.check(z.nanoid());else if(format==="cuid")stringSchema=stringSchema.check(z.cuid());else if(format==="cuid2")stringSchema=stringSchema.check(z.cuid2());else if(format==="ulid")stringSchema=stringSchema.check(z.ulid());else if(format==="xid")stringSchema=stringSchema.check(z.xid());else if(format==="ksuid")stringSchema=stringSchema.check(z.ksuid())}if(typeof schema.minLength==="number")stringSchema=stringSchema.min(schema.minLength);if(typeof schema.maxLength==="number")stringSchema=stringSchema.max(schema.maxLength);if(schema.pattern)stringSchema=stringSchema.regex(new RegExp(schema.pattern));zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number")numberSchema=numberSchema.min(schema.minimum);if(typeof schema.maximum==="number")numberSchema=numberSchema.max(schema.maximum);if(typeof schema.exclusiveMinimum==="number")numberSchema=numberSchema.gt(schema.exclusiveMinimum);else if(schema.exclusiveMinimum===!0&&typeof schema.minimum==="number")numberSchema=numberSchema.gt(schema.minimum);if(typeof schema.exclusiveMaximum==="number")numberSchema=numberSchema.lt(schema.exclusiveMaximum);else if(schema.exclusiveMaximum===!0&&typeof schema.maximum==="number")numberSchema=numberSchema.lt(schema.maximum);if(typeof schema.multipleOf==="number")numberSchema=numberSchema.multipleOf(schema.multipleOf);zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{let shape={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]);for(let[key,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);shape[key]=requiredSet.has(key)?propZodSchema:propZodSchema.optional()}if(schema.propertyNames){let keySchema=convertSchema(schema.propertyNames,ctx),valueSchema=schema.additionalProperties&&typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):z.any();if(Object.keys(shape).length===0){zodSchema=z.record(keySchema,valueSchema);break}let objectSchema2=z.object(shape).passthrough(),recordSchema=z.looseRecord(keySchema,valueSchema);zodSchema=z.intersection(objectSchema2,recordSchema);break}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape).length>0)schemasToIntersect.push(z.object(shape).passthrough());if(schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++)result=z.intersection(result,schemasToIntersect[i]);zodSchema=result}break}let objectSchema=z.object(shape);if(schema.additionalProperties===!1)zodSchema=objectSchema.strict();else if(typeof schema.additionalProperties==="object")zodSchema=objectSchema.catchall(convertSchema(schema.additionalProperties,ctx));else zodSchema=objectSchema.passthrough();break}case"array":{let{prefixItems,items}=schema;if(prefixItems&&Array.isArray(prefixItems)){let tupleItems=prefixItems.map((item)=>convertSchema(item,ctx)),rest=items&&typeof items==="object"&&!Array.isArray(items)?convertSchema(items,ctx):void 0;if(rest)zodSchema=z.tuple(tupleItems).rest(rest);else zodSchema=z.tuple(tupleItems);if(typeof schema.minItems==="number")zodSchema=zodSchema.check(z.minLength(schema.minItems));if(typeof schema.maxItems==="number")zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}else if(Array.isArray(items)){let tupleItems=items.map((item)=>convertSchema(item,ctx)),rest=schema.additionalItems&&typeof schema.additionalItems==="object"?convertSchema(schema.additionalItems,ctx):void 0;if(rest)zodSchema=z.tuple(tupleItems).rest(rest);else zodSchema=z.tuple(tupleItems);if(typeof schema.minItems==="number")zodSchema=zodSchema.check(z.minLength(schema.minItems));if(typeof schema.maxItems==="number")zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z.array(element);if(typeof schema.minItems==="number")arraySchema=arraySchema.min(schema.minItems);if(typeof schema.maxItems==="number")arraySchema=arraySchema.max(schema.maxItems);zodSchema=arraySchema}else zodSchema=z.array(z.any());break}default:throw Error(`Unsupported type: ${type}`)}if(schema.description)zodSchema=zodSchema.describe(schema.description);if(schema.default!==void 0)zodSchema=zodSchema.default(schema.default);return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean")return schema?z.any():z.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map((s)=>convertSchema(s,ctx)),anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map((s)=>convertSchema(s,ctx)),oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++)result=z.intersection(result,convertSchema(schema.allOf[i],ctx));baseSchema=result}if(schema.nullable===!0&&ctx.version==="openapi-3.0")baseSchema=z.nullable(baseSchema);if(schema.readOnly===!0)baseSchema=z.readonly(baseSchema);let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key of coreMetadataKeys)if(key in schema)extraMeta[key]=schema[key];let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key of contentMetadataKeys)if(key in schema)extraMeta[key]=schema[key];for(let key of Object.keys(schema))if(!RECOGNIZED_KEYS.has(key))extraMeta[key]=schema[key];if(Object.keys(extraMeta).length>0)ctx.registry.add(baseSchema,extraMeta);return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean")return schema?z.any():z.never();let version2=detectVersion(schema,params?.defaultTarget),defs=schema.$defs||schema.definitions||{},ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:schema,registry:params?.registry??globalRegistry};return convertSchema(schema,ctx)}var z,RECOGNIZED_KEYS;var init_from_json_schema=__esm(()=>{init_registries();init_checks2();init_iso();init_schemas2();z={...exports_schemas2,...exports_checks2,iso:exports_iso},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var exports_coerce={};__export(exports_coerce,{string:()=>string3,number:()=>number3,date:()=>date4,boolean:()=>boolean3,bigint:()=>bigint3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm(()=>{init_core2();init_schemas2()});var exports_external={};__export(exports_external,{xor:()=>xor,xid:()=>xid2,void:()=>_void2,uuidv7:()=>uuidv7,uuidv6:()=>uuidv6,uuidv4:()=>uuidv4,uuid:()=>uuid2,util:()=>exports_util,url:()=>url,uppercase:()=>_uppercase,unknown:()=>unknown,union:()=>union,undefined:()=>_undefined3,ulid:()=>ulid2,uint64:()=>uint64,uint32:()=>uint32,tuple:()=>tuple,trim:()=>_trim,treeifyError:()=>treeifyError,transform:()=>transform,toUpperCase:()=>_toUpperCase,toLowerCase:()=>_toLowerCase,toJSONSchema:()=>toJSONSchema,templateLiteral:()=>templateLiteral,symbol:()=>symbol,superRefine:()=>superRefine,success:()=>success,stringbool:()=>stringbool,stringFormat:()=>stringFormat,string:()=>string2,strictObject:()=>strictObject,startsWith:()=>_startsWith,slugify:()=>_slugify,size:()=>_size,setErrorMap:()=>setErrorMap,set:()=>set,safeParseAsync:()=>safeParseAsync2,safeParse:()=>safeParse2,safeEncodeAsync:()=>safeEncodeAsync2,safeEncode:()=>safeEncode2,safeDecodeAsync:()=>safeDecodeAsync2,safeDecode:()=>safeDecode2,registry:()=>registry,regexes:()=>exports_regexes,regex:()=>_regex,refine:()=>refine,record:()=>record,readonly:()=>readonly,property:()=>_property,promise:()=>promise,prettifyError:()=>prettifyError,preprocess:()=>preprocess,prefault:()=>prefault,positive:()=>_positive,pipe:()=>pipe,partialRecord:()=>partialRecord,parseAsync:()=>parseAsync2,parse:()=>parse3,overwrite:()=>_overwrite,optional:()=>optional,object:()=>object,number:()=>number2,nullish:()=>nullish2,nullable:()=>nullable,null:()=>_null3,normalize:()=>_normalize,nonpositive:()=>_nonpositive,nonoptional:()=>nonoptional,nonnegative:()=>_nonnegative,never:()=>never,negative:()=>_negative,nativeEnum:()=>nativeEnum,nanoid:()=>nanoid2,nan:()=>nan,multipleOf:()=>_multipleOf,minSize:()=>_minSize,minLength:()=>_minLength,mime:()=>_mime,meta:()=>meta2,maxSize:()=>_maxSize,maxLength:()=>_maxLength,map:()=>map,mac:()=>mac2,lte:()=>_lte,lt:()=>_lt,lowercase:()=>_lowercase,looseRecord:()=>looseRecord,looseObject:()=>looseObject,locales:()=>exports_locales,literal:()=>literal,length:()=>_length,lazy:()=>lazy,ksuid:()=>ksuid2,keyof:()=>keyof,jwt:()=>jwt,json:()=>json,iso:()=>exports_iso,ipv6:()=>ipv62,ipv4:()=>ipv42,intersection:()=>intersection,int64:()=>int64,int32:()=>int32,int:()=>int,instanceof:()=>_instanceof,includes:()=>_includes,httpUrl:()=>httpUrl,hostname:()=>hostname2,hex:()=>hex2,hash:()=>hash,guid:()=>guid2,gte:()=>_gte,gt:()=>_gt,globalRegistry:()=>globalRegistry,getErrorMap:()=>getErrorMap,function:()=>_function,fromJSONSchema:()=>fromJSONSchema,formatError:()=>formatError,float64:()=>float64,float32:()=>float32,flattenError:()=>flattenError,file:()=>file,exactOptional:()=>exactOptional,enum:()=>_enum2,endsWith:()=>_endsWith,encodeAsync:()=>encodeAsync2,encode:()=>encode2,emoji:()=>emoji2,email:()=>email2,e164:()=>e1642,discriminatedUnion:()=>discriminatedUnion,describe:()=>describe2,decodeAsync:()=>decodeAsync2,decode:()=>decode2,date:()=>date3,custom:()=>custom,cuid2:()=>cuid22,cuid:()=>cuid3,core:()=>exports_core2,config:()=>config,coerce:()=>exports_coerce,codec:()=>codec,clone:()=>clone,cidrv6:()=>cidrv62,cidrv4:()=>cidrv42,check:()=>check,catch:()=>_catch2,boolean:()=>boolean2,bigint:()=>bigint2,base64url:()=>base64url2,base64:()=>base642,array:()=>array,any:()=>any,_function:()=>_function,_default:()=>_default2,_ZodString:()=>_ZodString,ZodXor:()=>ZodXor,ZodXID:()=>ZodXID,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodUUID:()=>ZodUUID,ZodURL:()=>ZodURL,ZodULID:()=>ZodULID,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransform:()=>ZodTransform,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodSymbol:()=>ZodSymbol,ZodSuccess:()=>ZodSuccess,ZodStringFormat:()=>ZodStringFormat,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodRecord:()=>ZodRecord,ZodRealError:()=>ZodRealError,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPrefault:()=>ZodPrefault,ZodPipe:()=>ZodPipe,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumberFormat:()=>ZodNumberFormat,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNonOptional:()=>ZodNonOptional,ZodNever:()=>ZodNever,ZodNanoID:()=>ZodNanoID,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodMAC:()=>ZodMAC,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodKSUID:()=>ZodKSUID,ZodJWT:()=>ZodJWT,ZodIssueCode:()=>ZodIssueCode,ZodIntersection:()=>ZodIntersection,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate,ZodIPv6:()=>ZodIPv6,ZodIPv4:()=>ZodIPv4,ZodGUID:()=>ZodGUID,ZodFunction:()=>ZodFunction,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFile:()=>ZodFile,ZodExactOptional:()=>ZodExactOptional,ZodError:()=>ZodError,ZodEnum:()=>ZodEnum,ZodEmoji:()=>ZodEmoji,ZodEmail:()=>ZodEmail,ZodE164:()=>ZodE164,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodCustom:()=>ZodCustom,ZodCodec:()=>ZodCodec,ZodCatch:()=>ZodCatch,ZodCUID2:()=>ZodCUID2,ZodCUID:()=>ZodCUID,ZodCIDRv6:()=>ZodCIDRv6,ZodCIDRv4:()=>ZodCIDRv4,ZodBoolean:()=>ZodBoolean,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBigInt:()=>ZodBigInt,ZodBase64URL:()=>ZodBase64URL,ZodBase64:()=>ZodBase64,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny,TimePrecision:()=>TimePrecision,NEVER:()=>NEVER,$output:()=>$output,$input:()=>$input,$brand:()=>$brand});var init_external=__esm(()=>{init_core2();init_core2();init_en();init_core2();init_json_schema_processors();init_from_json_schema();init_locales();init_iso();init_iso();init_coerce();init_schemas2();init_checks2();init_errors2();init_parse2();init_compat();config(en_default())});var init_zod=__esm(()=>{init_external();init_external()});var EVIDENCE_MAX_JSON_BYTES=512000,EVIDENCE_MAX_PATCH_BYTES=5242880,EVIDENCE_MAX_TASK_BYTES=20971520,EvidenceTypeSchema,EvidenceVerdictSchema,BaseEvidenceSchema,ReviewEvidenceSchema,TestEvidenceSchema,DiffEvidenceSchema,ApprovalEvidenceSchema,NoteEvidenceSchema,RetrospectiveEvidenceSchema,SyntaxEvidenceSchema,PlaceholderEvidenceSchema,SastFindingSchema,SastEvidenceSchema,SbomEvidenceSchema,BuildEvidenceSchema,QualityBudgetEvidenceSchema,SecretscanEvidenceSchema,GateEvidenceBaseSchema,MutationGateEvidenceSchema,DriftVerificationEvidenceSchema,HallucinationVerificationEvidenceSchema,EvidenceSchema,EvidenceBundleSchema;var init_evidence_schema=__esm(()=>{init_zod();EvidenceTypeSchema=exports_external.enum(["review","test","diff","approval","note","retrospective","syntax","placeholder","sast","sbom","build","quality_budget","secretscan","mutation-gate","drift-verification","hallucination-verification"]),EvidenceVerdictSchema=exports_external.enum(["pass","fail","warn","skip","approved","rejected","info"]),BaseEvidenceSchema=exports_external.object({task_id:exports_external.string().min(1),type:EvidenceTypeSchema,timestamp:exports_external.string().datetime(),agent:exports_external.string().min(1),verdict:EvidenceVerdictSchema,summary:exports_external.string().min(1),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}),ReviewEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("review"),risk:exports_external.enum(["low","medium","high","critical"]),issues:exports_external.array(exports_external.object({severity:exports_external.enum(["error","warning","info"]),message:exports_external.string().min(1),file:exports_external.string().optional(),line:exports_external.number().int().optional()})).default([])}),TestEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("test"),tests_passed:exports_external.number().int().min(0),tests_failed:exports_external.number().int().min(0),test_file:exports_external.string().optional(),failures:exports_external.array(exports_external.object({name:exports_external.string().min(1),message:exports_external.string().min(1)})).default([])}),DiffEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("diff"),files_changed:exports_external.array(exports_external.string()).default([]),additions:exports_external.number().int().min(0).default(0),deletions:exports_external.number().int().min(0).default(0),patch_path:exports_external.string().optional()}),ApprovalEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("approval")}),NoteEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("note")}),RetrospectiveEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("retrospective"),phase_number:exports_external.number().int().min(1).max(99),total_tool_calls:exports_external.number().int().min(0).max(9999),coder_revisions:exports_external.number().int().min(0).max(999),reviewer_rejections:exports_external.number().int().min(0).max(999),loop_detections:exports_external.number().int().min(0).max(9999).optional(),circuit_breaker_trips:exports_external.number().int().min(0).max(9999).optional(),test_failures:exports_external.number().int().min(0).max(9999),security_findings:exports_external.number().int().min(0).max(999),integration_issues:exports_external.number().int().min(0).max(999),task_count:exports_external.number().int().min(1).max(9999),task_complexity:exports_external.enum(["trivial","simple","moderate","complex"]),top_rejection_reasons:exports_external.array(exports_external.string()).default([]),lessons_learned:exports_external.array(exports_external.string()).max(5).default([]),user_directives:exports_external.array(exports_external.object({directive:exports_external.string().min(1),category:exports_external.enum(["tooling","code_style","architecture","process","other"]),scope:exports_external.enum(["session","project","global"])})).default([]),approaches_tried:exports_external.array(exports_external.object({approach:exports_external.string().min(1),result:exports_external.enum(["success","failure","partial"]),abandoned_reason:exports_external.string().optional()})).max(10).default([]),error_taxonomy:exports_external.array(exports_external.enum(["planning_error","interface_mismatch","logic_error","scope_creep","gate_evasion"])).default([])}),SyntaxEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("syntax"),files_checked:exports_external.number().int(),files_failed:exports_external.number().int(),skipped_count:exports_external.number().int().default(0),files:exports_external.array(exports_external.object({path:exports_external.string(),language:exports_external.string(),ok:exports_external.boolean(),errors:exports_external.array(exports_external.object({line:exports_external.number().int(),column:exports_external.number().int(),message:exports_external.string()})).default([]),skipped_reason:exports_external.string().optional()})).default([])}),PlaceholderEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("placeholder"),findings:exports_external.array(exports_external.object({path:exports_external.string(),line:exports_external.number().int(),kind:exports_external.enum(["comment","string","function_body","other"]),excerpt:exports_external.string(),rule_id:exports_external.string()})).default([]),files_scanned:exports_external.number().int(),files_with_findings:exports_external.number().int(),findings_count:exports_external.number().int()}),SastFindingSchema=exports_external.object({rule_id:exports_external.string(),severity:exports_external.enum(["critical","high","medium","low"]),message:exports_external.string(),location:exports_external.object({file:exports_external.string(),line:exports_external.number().int(),column:exports_external.number().int().optional()}),remediation:exports_external.string().optional()}),SastEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("sast"),findings:exports_external.array(SastFindingSchema).default([]),engine:exports_external.enum(["tier_a","tier_a+tier_b"]),files_scanned:exports_external.number().int(),findings_count:exports_external.number().int(),findings_by_severity:exports_external.object({critical:exports_external.number().int(),high:exports_external.number().int(),medium:exports_external.number().int(),low:exports_external.number().int()}),new_findings:exports_external.array(SastFindingSchema).optional(),pre_existing_findings:exports_external.array(SastFindingSchema).optional(),baseline_used:exports_external.boolean().optional()}),SbomEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("sbom"),components:exports_external.array(exports_external.object({name:exports_external.string(),version:exports_external.string(),type:exports_external.enum(["library","framework","application"]),purl:exports_external.string().optional(),license:exports_external.string().optional()})).default([]),metadata:exports_external.object({timestamp:exports_external.string().datetime(),tool:exports_external.string(),tool_version:exports_external.string()}),files:exports_external.array(exports_external.string()),components_count:exports_external.number().int(),output_path:exports_external.string()}),BuildEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("build"),runs:exports_external.array(exports_external.object({kind:exports_external.enum(["build","typecheck","test"]),command:exports_external.string(),cwd:exports_external.string(),exit_code:exports_external.number().int(),duration_ms:exports_external.number().int(),stdout_tail:exports_external.string(),stderr_tail:exports_external.string()})).default([]),files_scanned:exports_external.number().int(),runs_count:exports_external.number().int(),failed_count:exports_external.number().int(),skipped_reason:exports_external.string().optional()}),QualityBudgetEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("quality_budget"),metrics:exports_external.object({complexity_delta:exports_external.number(),public_api_delta:exports_external.number(),duplication_ratio:exports_external.number(),test_to_code_ratio:exports_external.number()}),thresholds:exports_external.object({max_complexity_delta:exports_external.number(),max_public_api_delta:exports_external.number(),max_duplication_ratio:exports_external.number(),min_test_to_code_ratio:exports_external.number()}),violations:exports_external.array(exports_external.object({type:exports_external.enum(["complexity","api","duplication","test_ratio"]),message:exports_external.string(),severity:exports_external.enum(["error","warning"]),files:exports_external.array(exports_external.string())})).default([]),files_analyzed:exports_external.array(exports_external.string())}),SecretscanEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("secretscan"),findings_count:exports_external.number().int().min(0).default(0),scan_directory:exports_external.string().optional(),files_scanned:exports_external.number().int().min(0).default(0),skipped_files:exports_external.number().int().min(0).default(0)}),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()})});var exports_schema={};__export(exports_schema,{stripKnownSwarmPrefix:()=>stripKnownSwarmPrefix,resolveGuardrailsConfig:()=>resolveGuardrailsConfig,resolveGeneratedAgentRole:()=>resolveGeneratedAgentRole,resolveExternalSkillsConfig:()=>resolveExternalSkillsConfig,isKnownCanonicalRole:()=>isKnownCanonicalRole,getCanonicalAgentRole:()=>getCanonicalAgentRole,_internals:()=>_internals,WorktreeIsolationConfigSchema:()=>WorktreeIsolationConfigSchema,WatchdogConfigSchema:()=>WatchdogConfigSchema,UIReviewConfigSchema:()=>UIReviewConfigSchema,TurboConfigSchema:()=>TurboConfigSchema,ToolFilterConfigSchema:()=>ToolFilterConfigSchema,TokenRatiosSchema:()=>TokenRatiosSchema,SwarmConfigSchema:()=>SwarmConfigSchema,SummaryConfigSchema:()=>SummaryConfigSchema,StandardTurboConfigSchema:()=>StandardTurboConfigSchema,SpecWriterConfigSchema:()=>SpecWriterConfigSchema,SlopDetectorConfigSchema:()=>SlopDetectorConfigSchema,SkillsConfigSchema:()=>SkillsConfigSchema,SkillPropagationConfigSchema:()=>SkillPropagationConfigSchema,SkillImproverConfigSchema:()=>SkillImproverConfigSchema,SelfReviewConfigSchema:()=>SelfReviewConfigSchema,SecretscanConfigSchema:()=>SecretscanConfigSchema,ScoringWeightsSchema:()=>ScoringWeightsSchema,ScoringConfigSchema:()=>ScoringConfigSchema,ReviewPassesConfigSchema:()=>ReviewPassesConfigSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QualityBudgetConfigSchema:()=>QualityBudgetConfigSchema,PrmConfigSchema:()=>PrmConfigSchema,PricingConfigSchema:()=>PricingConfigSchema,PrMonitorConfigSchema:()=>PrMonitorConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanCursorConfigSchema:()=>PlanCursorConfigSchema,PlaceholderScanConfigSchema:()=>PlaceholderScanConfigSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,ParallelizationConfigSchema:()=>ParallelizationConfigSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LintConfigSchema:()=>LintConfigSchema,LeanTurboStrategyConfigSchema:()=>LeanTurboStrategyConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,KnowledgeConfigSchema:()=>KnowledgeConfigSchema,KnowledgeApplicationConfigSchema:()=>KnowledgeApplicationConfigSchema,IntegrationAnalysisConfigSchema:()=>IntegrationAnalysisConfigSchema,IncrementalVerifyConfigSchema:()=>IncrementalVerifyConfigSchema,HooksConfigSchema:()=>HooksConfigSchema,GuardrailsProfileSchema:()=>GuardrailsProfileSchema,GuardrailsConfigSchema:()=>GuardrailsConfigSchema,GeneralCouncilConfigSchema:()=>GeneralCouncilConfigSchema,GateFeatureSchema:()=>GateFeatureSchema,GateConfigSchema:()=>GateConfigSchema,ExternalSkillsConfigSchema:()=>ExternalSkillsConfigSchema,ExternalSkillCandidateSourceTypeSchema:()=>ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateSchema:()=>ExternalSkillCandidateSchema,ExternalSkillCandidateEvaluationVerdictSchema:()=>ExternalSkillCandidateEvaluationVerdictSchema,EvidenceConfigSchema:()=>EvidenceConfigSchema,EpicConfigSchema:()=>EpicConfigSchema,DocsConfigSchema:()=>DocsConfigSchema,DiscoverySourceSchema:()=>DiscoverySourceSchema,DesignDocsConfigSchema:()=>DesignDocsConfigSchema,DecisionDecaySchema:()=>DecisionDecaySchema,DEFAULT_SKILLS_CONFIG:()=>DEFAULT_SKILLS_CONFIG,DEFAULT_EXTERNAL_SKILLS_CONFIG:()=>DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_ARCHITECT_PROFILE:()=>DEFAULT_ARCHITECT_PROFILE,DEFAULT_AGENT_PROFILES:()=>DEFAULT_AGENT_PROFILES,CuratorConfigSchema:()=>CuratorConfigSchema,CouncilConfigSchema:()=>CouncilConfigSchema,ContextMapConfigSchema:()=>ContextMapConfigSchema,ContextBudgetConfigSchema:()=>ContextBudgetConfigSchema,CompactionConfigSchema:()=>CompactionConfigSchema,CompactionAdvisoryConfigSchema:()=>CompactionAdvisoryConfigSchema,CheckpointConfigSchema:()=>CheckpointConfigSchema,AutomationModeSchema:()=>AutomationModeSchema,AutomationConfigSchema:()=>AutomationConfigSchema,AutomationCapabilitiesSchema:()=>AutomationCapabilitiesSchema,AutoReviewConfigSchema:()=>AutoReviewConfigSchema,AuthorityConfigSchema:()=>AuthorityConfigSchema,ArchitecturalSupervisionConfigSchema:()=>ArchitecturalSupervisionConfigSchema,AgentThinkingConfigSchema:()=>AgentThinkingConfigSchema,AgentReasoningConfigSchema:()=>AgentReasoningConfigSchema,AgentOverrideConfigSchema:()=>AgentOverrideConfigSchema,AgentAuthorityRuleSchema:()=>AgentAuthorityRuleSchema,AdversarialTestingConfigSchema:()=>AdversarialTestingConfigSchema,AdversarialDetectionConfigSchema:()=>AdversarialDetectionConfigSchema});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.endsWith(suffix))return role}return agentName}function resolveGeneratedAgentRole(agentName,generatedAgentNames){return _internals.getCanonicalAgentRole(agentName,generatedAgentNames)}function stripKnownSwarmPrefix(agentName){return getCanonicalAgentRole(agentName)}function resolveGuardrailsConfig(config2,agentName){if(!agentName)return config2;let canonicalName=_internals.stripKnownSwarmPrefix(agentName),hasBuiltInProfile=canonicalName in DEFAULT_AGENT_PROFILES,userProfile=config2.profiles?.[agentName]??config2.profiles?.[canonicalName];if(!hasBuiltInProfile){if(userProfile)return{...config2,...userProfile};return config2}let builtInProfile=DEFAULT_AGENT_PROFILES[canonicalName];return{...config2,...builtInProfile,...userProfile||{}}}function resolveExternalSkillsConfig(input){if(input===void 0||input===null||typeof input!=="object"||Array.isArray(input))return{...DEFAULT_EXTERNAL_SKILLS_CONFIG};let config2=input;return{curation_enabled:config2.curation_enabled??DEFAULT_EXTERNAL_SKILLS_CONFIG.curation_enabled,max_candidates:config2.max_candidates??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_candidates,max_bytes_per_candidate:config2.max_bytes_per_candidate??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_bytes_per_candidate,eviction_policy:config2.eviction_policy??DEFAULT_EXTERNAL_SKILLS_CONFIG.eviction_policy,ttl_days:config2.ttl_days??DEFAULT_EXTERNAL_SKILLS_CONFIG.ttl_days,evaluation_enabled:config2.evaluation_enabled??DEFAULT_EXTERNAL_SKILLS_CONFIG.evaluation_enabled,sources:Array.isArray(config2.sources)?config2.sources:[],max_candidates_per_discovery:config2.max_candidates_per_discovery??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_candidates_per_discovery,max_concurrent_fetches:config2.max_concurrent_fetches??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_concurrent_fetches,fetch_timeout_ms:config2.fetch_timeout_ms??DEFAULT_EXTERNAL_SKILLS_CONFIG.fetch_timeout_ms}}var _internals,SEPARATORS,CANONICAL_ROLES_LONGEST_FIRST,CANONICAL_ROLES_SET,AgentReasoningConfigSchema,AgentThinkingConfigSchema,AgentOverrideConfigSchema,SwarmConfigSchema,ModelPricingConfigSchema,PricingConfigSchema,HooksConfigSchema,ScoringWeightsSchema,DecisionDecaySchema,TokenRatiosSchema,ScoringConfigSchema,ContextBudgetConfigSchema,EvidenceConfigSchema,GateFeatureSchema,PlaceholderScanConfigSchema,QualityBudgetConfigSchema,GateConfigSchema,PipelineConfigSchema,PhaseCompleteConfigSchema,SummaryConfigSchema,ReviewPassesConfigSchema,AutoReviewConfigSchema,AdversarialDetectionConfigSchema,AdversarialTestingConfigSchemaBase,AdversarialTestingConfigSchema,IntegrationAnalysisConfigSchema,DocsConfigSchema,DesignDocsConfigSchema,UIReviewConfigSchema,CompactionAdvisoryConfigSchema,LintConfigSchema,SecretscanConfigSchema,GuardrailsProfileSchema,DEFAULT_AGENT_PROFILES,DEFAULT_ARCHITECT_PROFILE,GuardrailsConfigSchema,WatchdogConfigSchema,SelfReviewConfigSchema,ToolFilterConfigSchema,PlanCursorConfigSchema,ContextMapConfigSchema,RepoGraphConfigSchema,CheckpointConfigSchema,AutomationModeSchema,AutomationCapabilitiesSchema,AutomationConfigSchemaBase,AutomationConfigSchema,KnowledgeConfigSchema,MemoryConfigSchema,CuratorConfigSchema,ArchitecturalSupervisionConfigSchema,KnowledgeApplicationConfigSchema,SkillPropagationConfigSchema,SkillImproverConfigSchema,SkillsConfigSchema,SpecWriterConfigSchema,SlopDetectorConfigSchema,IncrementalVerifyConfigSchema,CompactionConfigSchema,PrmConfigSchema,AgentAuthorityRuleSchema,AuthorityConfigSchema,GeneralCouncilMemberConfigSchema,GeneralCouncilConfigSchema,CouncilConfigSchema,PrMonitorConfigSchema,ParallelizationConfigSchema,WorktreeIsolationConfigSchema,LeanTurboConfigSchema,EpicConfigSchema,StandardTurboConfigSchema,LeanTurboStrategyConfigSchema,TurboConfigSchema,ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateEvaluationVerdictSchema,DiscoverySourceSchema,ExternalSkillCandidateSchema,ExternalSkillsConfigSchema,DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_SKILLS_CONFIG,PluginConfigSchema;var init_schema=__esm(()=>{init_zod();init_constants();_internals={stripKnownSwarmPrefix,getCanonicalAgentRole,resolveGuardrailsConfig},SEPARATORS=["_","-"," "],CANONICAL_ROLES_LONGEST_FIRST=[...ALL_AGENT_NAMES].sort((a,b)=>b.length-a.length),CANONICAL_ROLES_SET=new Set(ALL_AGENT_NAMES);AgentReasoningConfigSchema=exports_external.object({effort:exports_external.enum(["low","medium","high","max"]).optional()}),AgentThinkingConfigSchema=exports_external.object({type:exports_external.enum(["enabled","disabled"]).optional(),budget_tokens:exports_external.number().int().positive().optional()}),AgentOverrideConfigSchema=exports_external.object({model:exports_external.string().optional(),variant:exports_external.string().min(1).optional(),temperature:exports_external.number().min(0).max(2).optional(),disabled:exports_external.boolean().optional(),fallback_models:exports_external.array(exports_external.string()).max(3).optional(),reasoning:AgentReasoningConfigSchema.optional(),thinking:AgentThinkingConfigSchema.optional()}),SwarmConfigSchema=exports_external.object({name:exports_external.string().optional(),agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional()}),ModelPricingConfigSchema=exports_external.object({input_per_million:exports_external.number().min(0),output_per_million:exports_external.number().min(0),reasoning_per_million:exports_external.number().min(0).optional(),cache_per_million:exports_external.number().min(0).optional()}),PricingConfigSchema=exports_external.object({models:exports_external.record(exports_external.string().min(1),ModelPricingConfigSchema).optional().default({})}),HooksConfigSchema=exports_external.object({system_enhancer:exports_external.boolean().default(!0),compaction:exports_external.boolean().default(!0),agent_activity:exports_external.boolean().default(!0),delegation_tracker:exports_external.boolean().default(!1),agent_awareness_max_chars:exports_external.number().min(50).max(2000).default(300),delegation_gate:exports_external.boolean().default(!0),delegation_max_chars:exports_external.number().min(500).max(20000).default(4000),background_subagents:exports_external.boolean().default(!1),background_pending_timeout_minutes:exports_external.number().int().min(1).max(1440).default(30)}),ScoringWeightsSchema=exports_external.object({phase:exports_external.number().min(0).max(5).default(1),current_task:exports_external.number().min(0).max(5).default(2),blocked_task:exports_external.number().min(0).max(5).default(1.5),recent_failure:exports_external.number().min(0).max(5).default(2.5),recent_success:exports_external.number().min(0).max(5).default(0.5),evidence_presence:exports_external.number().min(0).max(5).default(1),decision_recency:exports_external.number().min(0).max(5).default(1.5),dependency_proximity:exports_external.number().min(0).max(5).default(1)}),DecisionDecaySchema=exports_external.object({mode:exports_external.enum(["linear","exponential"]).default("exponential"),half_life_hours:exports_external.number().min(1).max(168).default(24)}),TokenRatiosSchema=exports_external.object({prose:exports_external.number().min(0.1).max(1).default(0.25),code:exports_external.number().min(0.1).max(1).default(0.4),markdown:exports_external.number().min(0.1).max(1).default(0.3),json:exports_external.number().min(0.1).max(1).default(0.35)}),ScoringConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),max_candidates:exports_external.number().min(10).max(500).default(100),weights:ScoringWeightsSchema.optional(),decision_decay:DecisionDecaySchema.optional(),token_ratios:TokenRatiosSchema.optional()}),ContextBudgetConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),warn_threshold:exports_external.number().min(0).max(1).default(0.7),critical_threshold:exports_external.number().min(0).max(1).default(0.9),model_limits:exports_external.record(exports_external.string(),exports_external.number().min(1000)).default({default:128000}),max_injection_tokens:exports_external.number().min(100).max(50000).default(4000),unified_injection_tokens:exports_external.number().min(100).max(50000).optional(),tracked_agents:exports_external.array(exports_external.string()).default(["architect"]),scoring:ScoringConfigSchema.optional(),enforce:exports_external.boolean().default(!0),prune_target:exports_external.number().min(0).max(1).default(0.7),preserve_last_n_turns:exports_external.number().min(0).max(100).default(4),recent_window:exports_external.number().min(1).max(100).default(10),enforce_on_agent_switch:exports_external.boolean().default(!0),tool_output_mask_threshold:exports_external.number().min(100).max(1e5).default(2000)}),EvidenceConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_age_days:exports_external.number().min(1).max(365).default(90),max_bundles:exports_external.number().min(10).max(1e4).default(1000),auto_archive:exports_external.boolean().default(!1)}),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)}),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.*"])}),GateConfigSchema=exports_external.object({syntax_check:GateFeatureSchema.default({enabled:!0}),placeholder_scan:PlaceholderScanConfigSchema.default({enabled:!0,deny_patterns:["TODO","FIXME","TBD","XXX","placeholder","stub","wip","not implemented"],allow_globs:["docs/**","examples/**","tests/**","**/*.test.*","**/*.spec.*","**/mocks/**","**/__tests__/**"],max_allowed_findings:0}),sast_scan:GateFeatureSchema.default({enabled:!0}),sbom_generate:GateFeatureSchema.default({enabled:!0}),build_check:GateFeatureSchema.default({enabled:!0}),quality_budget:QualityBudgetConfigSchema}),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(["retrieve_summary","retrieve_lane_output","task","read"])}),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/**"])}),AutoReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),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)}),AdversarialDetectionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),policy:exports_external.enum(["warn","gate","ignore"]).default("warn"),pairs:exports_external.array(exports_external.tuple([exports_external.string(),exports_external.string()])).default([["coder","reviewer"]])}),AdversarialTestingConfigSchemaBase=exports_external.object({enabled:exports_external.boolean().default(!0),scope:exports_external.enum(["all","security-only"]).default("all")}),AdversarialTestingConfigSchema=AdversarialTestingConfigSchemaBase.default(()=>({enabled:!0,scope:"all"})),IntegrationAnalysisConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0)}),DocsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),doc_patterns:exports_external.array(exports_external.string()).default(["README.md","CONTRIBUTING.md","docs/**/*.md","docs/**/*.rst","**/CHANGELOG.md"])}),DesignDocsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),out_dir:exports_external.string().default("docs").refine((v)=>v.length>0&&v!=="."&&!v.includes("..")&&!v.startsWith("/")&&!v.startsWith("\\")&&!/^[A-Za-z]:/.test(v),{message:'design_docs.out_dir must be a non-empty project-relative path with no "..", leading slash, or drive letter'}),language:exports_external.string().optional()}),UIReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),trigger_paths:exports_external.array(exports_external.string()).default(["**/pages/**","**/components/**","**/views/**","**/screens/**","**/ui/**","**/layouts/**"]),trigger_keywords:exports_external.array(exports_external.string()).default(["new page","new screen","new component","redesign","layout change","form","modal","dialog","dropdown","sidebar","navbar","dashboard","landing page","signup","login form","settings page","profile page"])}),CompactionAdvisoryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),thresholds:exports_external.array(exports_external.number().int().min(10).max(500)).default([50,75,100,125,150]),message:exports_external.string().default("[SWARM HINT] Session has ${totalToolCalls} tool calls. Consider compacting at next phase boundary to maintain context quality.")}),LintConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),mode:exports_external.enum(["check","fix"]).default("check"),linter:exports_external.enum(["biome","eslint","auto"]).default("auto"),patterns:exports_external.array(exports_external.string()).default(["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/biome.json","**/biome.jsonc"]),exclude:exports_external.array(exports_external.string()).default(["**/node_modules/**","**/dist/**","**/.git/**","**/coverage/**","**/*.min.js"])}),SecretscanConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),patterns:exports_external.array(exports_external.string()).default(["**/*.{env,properties,yml,yaml,json,js,ts}","**/.env*","**/secrets/**","**/credentials/**","**/config/**/*.ts","**/config/**/*.js"]),exclude:exports_external.array(exports_external.string()).default(["**/node_modules/**","**/dist/**","**/.git/**","**/coverage/**","**/test/**","**/tests/**","**/__tests__/**","**/*.test.ts","**/*.test.js","**/*.spec.ts","**/*.spec.js"]),extensions:exports_external.array(exports_external.string()).default([".env",".properties",".yml",".yaml",".json",".js",".ts",".py",".rb",".go",".java",".cs",".php"])}),GuardrailsProfileSchema=exports_external.object({max_tool_calls:exports_external.number().min(0).max(1000).optional(),max_duration_minutes:exports_external.number().min(0).max(480).optional(),max_repetitions:exports_external.number().min(3).max(50).optional(),max_consecutive_errors:exports_external.number().min(2).max(20).optional(),warning_threshold:exports_external.number().min(0.1).max(0.9).optional(),idle_timeout_minutes:exports_external.number().min(5).max(240).optional(),max_transient_retries:exports_external.number().min(0).max(20).optional()}),DEFAULT_AGENT_PROFILES={architect:{max_tool_calls:0,max_duration_minutes:0,max_consecutive_errors:8,warning_threshold:0.75},coder:{max_tool_calls:400,max_duration_minutes:45,max_consecutive_errors:8,warning_threshold:0.85},test_engineer:{max_tool_calls:400,max_duration_minutes:45,max_consecutive_errors:8,warning_threshold:0.85},explorer:{max_tool_calls:150,max_duration_minutes:20,max_consecutive_errors:8,warning_threshold:0.75},reviewer:{max_tool_calls:200,max_duration_minutes:30,max_consecutive_errors:8,warning_threshold:0.65},critic:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.65},sme:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.65},docs:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.75},designer:{max_tool_calls:150,max_duration_minutes:20,warning_threshold:0.75}},DEFAULT_ARCHITECT_PROFILE=DEFAULT_AGENT_PROFILES.architect,GuardrailsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_tool_calls:exports_external.number().min(0).max(1000).default(200),max_duration_minutes:exports_external.number().min(0).max(480).default(30),max_repetitions:exports_external.number().min(3).max(50).default(10),max_consecutive_errors:exports_external.number().min(2).max(20).default(5),max_transient_retries:exports_external.number().min(0).max(20).default(5),warning_threshold:exports_external.number().min(0.1).max(0.9).default(0.75),idle_timeout_minutes:exports_external.number().min(5).max(240).default(60),no_op_warning_threshold:exports_external.number().min(1).max(100).default(15),max_coder_revisions:exports_external.number().int().min(1).max(20).default(5),runaway_output_max_turns:exports_external.number().int().min(1).max(20).default(5),qa_gates:exports_external.object({required_tools:exports_external.array(exports_external.string().min(1)).default(["diff","syntax_check","placeholder_scan","lint","pre_check_batch"]),require_reviewer_test_engineer:exports_external.boolean().default(!0)}).optional(),profiles:exports_external.record(exports_external.string(),GuardrailsProfileSchema).optional(),block_destructive_commands:exports_external.boolean().default(!0),interpreter_allowed_agents:exports_external.array(exports_external.string().min(1)).optional(),shell_audit_log:exports_external.boolean().default(!0)}),WatchdogConfigSchema=exports_external.object({scope_guard:exports_external.boolean().default(!0),skip_in_turbo:exports_external.boolean().default(!1),delegation_ledger:exports_external.boolean().default(!0)}),SelfReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),skip_in_turbo:exports_external.boolean().default(!0)});ToolFilterConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),overrides:exports_external.record(exports_external.string(),exports_external.array(exports_external.string())).default({})}),PlanCursorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_tokens:exports_external.number().min(500).max(4000).default(1500),lookahead_tasks:exports_external.number().min(0).max(5).default(2)}),ContextMapConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),mode:exports_external.enum(["conservative","balanced","aggressive"]).default("balanced"),max_capsule_tokens:exports_external.number().int().positive().default(2000),invalidate_on_hash_change:exports_external.boolean().default(!0),agent_profiles:exports_external.record(exports_external.string(),exports_external.string()).default({})}),RepoGraphConfigSchema=exports_external.object({exclude_dirs:exports_external.array(exports_external.string().trim().min(1)).default([])}),CheckpointConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),auto_checkpoint_threshold:exports_external.number().int().min(1).max(20).default(3),allow_empty_commits:exports_external.boolean().default(!1)}).strict(),AutomationModeSchema=exports_external.enum(["manual","hybrid","auto"]),AutomationCapabilitiesSchema=exports_external.object({plan_sync:exports_external.boolean().default(!0),phase_preflight:exports_external.boolean().default(!1),config_doctor_on_startup:exports_external.boolean().default(!1),config_doctor_autofix:exports_external.boolean().default(!1),evidence_auto_summaries:exports_external.boolean().default(!0),decision_drift_detection:exports_external.boolean().default(!0)}),AutomationConfigSchemaBase=exports_external.object({mode:AutomationModeSchema.default("manual"),capabilities:AutomationCapabilitiesSchema.default({plan_sync:!0,phase_preflight:!1,config_doctor_on_startup:!1,config_doctor_autofix:!1,evidence_auto_summaries:!0,decision_drift_detection:!0})}),AutomationConfigSchema=AutomationConfigSchemaBase,KnowledgeConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),swarm_max_entries:exports_external.number().min(1).max(1e4).default(100),hive_max_entries:exports_external.number().min(1).max(1e5).default(200),auto_promote_days:exports_external.number().min(1).max(3650).default(90),max_inject_count:exports_external.number().min(0).max(50).default(5),delegate_max_inject_count:exports_external.number().min(0).max(50).default(8),inject_char_budget:exports_external.number().min(200).max(1e4).default(2000),context_budget_threshold:exports_external.number().int().positive().optional(),max_lesson_display_chars:exports_external.number().min(40).max(280).default(120),dedup_threshold:exports_external.number().min(0).max(1).default(0.6),scope_filter:exports_external.array(exports_external.string()).default(["global"]),hive_enabled:exports_external.boolean().default(!0),rejected_max_entries:exports_external.number().min(1).max(1000).default(20),validation_enabled:exports_external.boolean().default(!0),evergreen_confidence:exports_external.number().min(0).max(1).default(0.9),evergreen_utility:exports_external.number().min(0).max(1).default(0.8),low_utility_threshold:exports_external.number().min(0).max(1).default(0.3),min_retrievals_for_utility:exports_external.number().min(1).max(100).default(3),schema_version:exports_external.number().int().min(1).default(1),directive_min_confidence:exports_external.number().min(0).max(1).default(0.75),same_project_weight:exports_external.number().min(0).max(5).default(1),cross_project_weight:exports_external.number().min(0).max(5).default(0.5),min_encounter_score:exports_external.number().min(0).max(1).default(0.1),initial_encounter_score:exports_external.number().min(0).max(5).default(1),encounter_increment:exports_external.number().min(0).max(1).default(0.1),max_encounter_score:exports_external.number().min(1).max(20).default(10),default_max_phases:exports_external.number().int().positive().default(10),todo_max_phases:exports_external.number().int().positive().default(3),sweep_enabled:exports_external.boolean().default(!0),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"})}),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}),recall:exports_external.object({defaultMaxItems:exports_external.number().int().min(1).max(20).default(8),defaultTokenBudget:exports_external.number().int().min(100).max(5000).default(1200),minScore:exports_external.number().min(0).max(1).default(0.05),injection:exports_external.object({enabled:exports_external.boolean().default(!0),minScore:exports_external.number().min(0).max(1).default(0.25),requireQuerySignal:exports_external.boolean().default(!0),maxItems:exports_external.number().int().min(1).max(20).default(6),tokenBudget:exports_external.number().int().min(100).max(5000).default(1000)}).default({enabled:!0,minScore:0.25,requireQuerySignal:!0,maxItems:6,tokenBudget:1000})}).default({defaultMaxItems:8,defaultTokenBudget:1200,minScore:0.05,injection:{enabled:!0,minScore:0.25,requireQuerySignal:!0,maxItems:6,tokenBudget:1000}}),learning:exports_external.object({learningRate:exports_external.number().min(0).max(1).default(0.1),propagationFactor:exports_external.number().min(0).max(1).default(0.3),qValueBoostWeight:exports_external.number().min(0).max(1).default(0.1),suppressionThreshold:exports_external.number().min(0).max(1).default(0.15),promotionThreshold:exports_external.number().min(0).max(1).default(0.85),propagationTokenOverlapThreshold:exports_external.number().min(0).max(1).default(0.4),propagationEmbeddingCosineThreshold:exports_external.number().min(0).max(1).default(0.7),propagationFanout:exports_external.number().int().min(0).max(1000).default(20),propagationLookbackDays:exports_external.number().int().min(1).max(3650).default(30)}).default({learningRate:0.1,propagationFactor:0.3,qValueBoostWeight:0.1,suppressionThreshold:0.15,promotionThreshold:0.85,propagationTokenOverlapThreshold:0.4,propagationEmbeddingCosineThreshold:0.7,propagationFanout:20,propagationLookbackDays:30}),writes:exports_external.object({mode:exports_external.literal("propose").default("propose")}).default({mode:"propose"}),redaction:exports_external.object({rejectDurableSecrets:exports_external.boolean().default(!0)}).default({rejectDurableSecrets:!0}),maintenance:exports_external.object({lowUtilityMaxConfidence:exports_external.number().min(0).max(1).default(0.45),lowUtilityMinAgeDays:exports_external.number().int().min(1).max(3650).default(30),importance:exports_external.object({wRecency:exports_external.number().min(0).max(1).default(0.2),wFrequency:exports_external.number().min(0).max(1).default(0.2),wFreshness:exports_external.number().min(0).max(1).default(0.15),wConfidence:exports_external.number().min(0).max(1).default(0.25),lambda:exports_external.number().min(0).max(10).default(0.05),mu:exports_external.number().min(0).max(10).default(0.01),n:exports_external.number().int().min(1).max(1e5).default(50),threshold:exports_external.number().min(0).max(1).default(0.2)}).default({wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2})}).default({lowUtilityMaxConfidence:0.45,lowUtilityMinAgeDays:30,importance:{wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2}}),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"])}),SkillPropagationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),enforce:exports_external.boolean().default(!1)}),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)}),SpecWriterConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),model:exports_external.string().nullable().default(null),fallback_models:exports_external.array(exports_external.string()).default([]),allow_spec_write:exports_external.boolean().default(!0)}),SlopDetectorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),classThreshold:exports_external.number().int().min(1).default(3),commentStripThreshold:exports_external.number().int().min(1).default(5),diffLineThreshold:exports_external.number().int().min(10).default(200),importHygieneThreshold:exports_external.number().int().min(1).default(2)}),IncrementalVerifyConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),command:exports_external.union([exports_external.string(),exports_external.array(exports_external.string())]).nullable().default(null),timeoutMs:exports_external.number().int().min(1000).max(300000).default(30000),triggerAgents:exports_external.array(exports_external.string()).default(["coder"])}),CompactionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),observationThreshold:exports_external.number().min(1).max(99).default(40),reflectionThreshold:exports_external.number().min(1).max(99).default(60),emergencyThreshold:exports_external.number().min(1).max(99).default(80),preserveLastNTurns:exports_external.number().int().min(1).default(5)}),PrmConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),pattern_thresholds:exports_external.object({repetition_loop:exports_external.number().min(1).default(2),ping_pong:exports_external.number().min(1).default(2),expansion_drift:exports_external.number().min(1).default(3),stuck_on_test:exports_external.number().min(1).default(3),context_thrash:exports_external.number().min(1).default(3)}).default(()=>({repetition_loop:2,ping_pong:2,expansion_drift:3,stuck_on_test:3,context_thrash:3})),max_trajectory_lines:exports_external.number().min(10).default(1000),escalation_enabled:exports_external.boolean().default(!0),detection_timeout_ms:exports_external.number().min(10).default(100)}),AgentAuthorityRuleSchema=exports_external.object({readOnly:exports_external.boolean().optional(),blockedExact:exports_external.array(exports_external.string()).optional(),allowedExact:exports_external.array(exports_external.string()).optional(),blockedPrefix:exports_external.array(exports_external.string()).optional(),allowedPrefix:exports_external.array(exports_external.string()).optional(),blockedZones:exports_external.array(exports_external.enum(["production","test","config","generated","docs","build"])).optional(),blockedGlobs:exports_external.array(exports_external.string()).optional(),allowedGlobs:exports_external.array(exports_external.string()).optional(),allowedCaseSensitiveGlobs:exports_external.array(exports_external.string()).optional()}),AuthorityConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),rules:exports_external.record(exports_external.string(),AgentAuthorityRuleSchema).default({}),universal_deny_prefixes:exports_external.array(exports_external.string().min(1)).default([]),verifier_config_paths:exports_external.array(exports_external.string()).optional().describe("Additional glob patterns for verifier config files that are merged into the architect agent's blockedGlobs at plugin init. Writes to matching files are blocked by the authority layer.")}),GeneralCouncilMemberConfigSchema=exports_external.object({memberId:exports_external.string().min(1),model:exports_external.string().min(1),role:exports_external.enum(["generalist","skeptic","domain_expert","devil_advocate","synthesizer"]),persona:exports_external.string().optional()}).strict(),GeneralCouncilConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),searchProvider:exports_external.enum(["tavily","brave"]).default("tavily"),searchApiKey:exports_external.string().optional(),members:exports_external.array(GeneralCouncilMemberConfigSchema).default([]),presets:exports_external.record(exports_external.string(),exports_external.array(GeneralCouncilMemberConfigSchema)).default({}),deliberate:exports_external.boolean().default(!0),moderator:exports_external.boolean().default(!0),moderatorModel:exports_external.string().optional(),maxSourcesPerMember:exports_external.number().int().min(1).max(20).default(5)}).strict(),CouncilConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),maxRounds:exports_external.number().int().min(1).max(10).default(3),parallelTimeoutMs:exports_external.number().int().min(5000).max(120000).default(30000),vetoPriority:exports_external.boolean().default(!0),requireAllMembers:exports_external.boolean().default(!1).describe("When true, submit_council_verdicts rejects if fewer than 5 member verdicts are provided. Equivalent to minimumMembers: 5."),minimumMembers:exports_external.number().int().min(1).max(5).default(3).describe("Minimum distinct council member verdicts required for synthesis. Default 3. Set to 1 to disable quorum enforcement. requireAllMembers: true overrides this to 5 (stricter constraint wins)."),escalateOnMaxRounds:exports_external.string().optional().describe("Optional webhook URL or handler name invoked when maxRounds is reached without APPROVE. Declared for forward compatibility; no behavior is implemented yet."),phaseConcernsAllowComplete:exports_external.boolean().default(!0).describe("When true, a phase-level council CONCERNS verdict with only MEDIUM/LOW findings does NOT block phase completion — the advisory notes are logged as warnings and the phase proceeds. When false, CONCERNS blocks like REJECT. Note: HIGH/CRITICAL findings from CONCERNS members are always promoted to requiredFixes and block at the tool level regardless of this setting. Default: true."),general:GeneralCouncilConfigSchema.optional()}).strict(),PrMonitorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),poll_interval_seconds:exports_external.number().int().min(30).max(300).default(60),max_subscriptions:exports_external.number().int().min(1).max(100).default(20),max_prs_per_cycle:exports_external.number().int().min(1).max(20).default(5),max_concurrent_pr_polls:exports_external.number().int().min(1).max(10).default(3),poll_timeout_ms:exports_external.number().int().min(5000).max(120000).default(30000),failure_threshold:exports_external.number().int().min(1).max(20).default(5),cooldown_seconds:exports_external.number().int().min(5).max(600).default(30),max_cooldown_seconds:exports_external.number().int().min(30).max(3600).default(300),cleanup_ttl_days:exports_external.number().int().min(1).max(90).default(7),auto_unsubscribe_on_merge:exports_external.boolean().default(!0),auto_unsubscribe_on_close:exports_external.boolean().default(!0),notify_ci_failure:exports_external.boolean().default(!0),notify_new_comments:exports_external.boolean().default(!0),notify_merge_conflict:exports_external.boolean().default(!0),auto_pr_feedback:exports_external.boolean().default(!1)}).strict(),ParallelizationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),maxConcurrentTasks:exports_external.number().int().min(1).max(64).default(1),evidenceLockTimeoutMs:exports_external.number().int().min(1000).max(300000).default(60000),max_coders:exports_external.number().int().min(1).max(16).default(3),max_reviewers:exports_external.number().int().min(1).max(16).default(2)}),WorktreeIsolationConfigSchema=exports_external.object({policy:exports_external.enum(["auto","required","disabled"]).default("auto"),merge_strategy:exports_external.enum(["merge","rebase","cherry-pick"]).default("merge"),worktree_dir:exports_external.string().optional(),deps_strategy:exports_external.enum(["skip","copy","link"]).default("skip")}),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(!1),merge_strategy:exports_external.enum(["merge","rebase","cherry-pick"]).default("merge").optional(),worktree_dir:exports_external.string().optional()}),EpicConfigSchema=exports_external.object({cochange:exports_external.object({enabled:exports_external.boolean().default(!1),threshold:exports_external.number().min(-1).max(1).default(0.6),min_co_changes:exports_external.number().int().min(1).default(5)}).strict().optional(),mode:exports_external.object({enabled:exports_external.boolean().default(!1),activation_threshold:exports_external.number().min(0).max(1).default(0.3),min_commits_for_signal:exports_external.number().int().min(1).default(20)}).strict().optional(),calibration:exports_external.object({enabled:exports_external.boolean().default(!0),floor_threshold:exports_external.number().min(0).max(1).default(0.05),tighten_step:exports_external.number().min(0).max(1).default(0.02),loosen_step:exports_external.number().min(0).max(1).default(0.01),loosen_window:exports_external.number().int().min(1).default(10)}).strict().optional()}).strict(),StandardTurboConfigSchema=exports_external.object({strategy:exports_external.literal("standard"),lean:LeanTurboConfigSchema.optional(),epic:EpicConfigSchema.optional()}),LeanTurboStrategyConfigSchema=exports_external.object({strategy:exports_external.literal("lean"),lean:LeanTurboConfigSchema,epic:EpicConfigSchema.optional()}),TurboConfigSchema=exports_external.discriminatedUnion("strategy",[StandardTurboConfigSchema,LeanTurboStrategyConfigSchema]),ExternalSkillCandidateSourceTypeSchema=exports_external.enum(["github","url","collection","manual_import"]),ExternalSkillCandidateEvaluationVerdictSchema=exports_external.enum(["pending","in_review","quarantined","passed","rejected","promoted","revoked"]),DiscoverySourceSchema=exports_external.object({type:ExternalSkillCandidateSourceTypeSchema,location:exports_external.string().min(1),enabled:exports_external.boolean().default(!0),trust_level:exports_external.enum(["low","medium","high"]).default("low").optional()}),ExternalSkillCandidateSchema=exports_external.object({id:exports_external.string().uuid(),source_url:exports_external.string().url(),source_type:ExternalSkillCandidateSourceTypeSchema,publisher:exports_external.string().min(1),sha256:exports_external.string().regex(/^[a-f0-9]{64}$/),fetched_at:exports_external.string().datetime(),skill_name:exports_external.string().optional(),skill_description:exports_external.string().optional(),skill_body:exports_external.string(),risk_flags:exports_external.array(exports_external.string()).default([]),evaluation_verdict:ExternalSkillCandidateEvaluationVerdictSchema.default("pending"),evaluation_history:exports_external.array(exports_external.object({verdict:ExternalSkillCandidateEvaluationVerdictSchema,timestamp:exports_external.string().datetime(),actor:exports_external.string(),reason:exports_external.string().optional(),candidate_id:exports_external.string().optional(),original_verdict:ExternalSkillCandidateEvaluationVerdictSchema.optional(),gate_results:exports_external.array(exports_external.object({gate:exports_external.string(),verdict:exports_external.string()})).optional(),risk_assessment:exports_external.object({total_flags:exports_external.number().int().nonnegative(),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["error","warning"]),category:exports_external.string()}))}).optional(),risk_flags_count:exports_external.number().int().nonnegative().optional(),provenance_snapshot:exports_external.object({sha256:exports_external.string(),source_url:exports_external.string(),publisher:exports_external.string(),fetched_at:exports_external.string().datetime().optional()}).optional(),target_path:exports_external.string().optional(),promoted_content_hash:exports_external.string().regex(/^[a-f0-9]{64}$/).optional(),original_evaluation:exports_external.record(exports_external.string(),exports_external.unknown()).optional()})).default([])}),ExternalSkillsConfigSchema=exports_external.object({curation_enabled:exports_external.boolean().default(!1),max_candidates:exports_external.number().int().min(1).max(1e4).default(500),max_bytes_per_candidate:exports_external.number().int().min(1024).max(10485760).default(1048576),eviction_policy:exports_external.enum(["fifo"]).default("fifo"),ttl_days:exports_external.number().int().min(1).max(3650).default(90),evaluation_enabled:exports_external.boolean().default(!1),sources:exports_external.array(DiscoverySourceSchema).default([]),max_candidates_per_discovery:exports_external.number().int().min(1).max(1000).default(50),max_concurrent_fetches:exports_external.number().int().min(1).max(20).default(5),fetch_timeout_ms:exports_external.number().int().min(1000).max(300000).default(30000)}),DEFAULT_EXTERNAL_SKILLS_CONFIG={curation_enabled:!1,max_candidates:500,max_bytes_per_candidate:1048576,eviction_policy:"fifo",ttl_days:90,evaluation_enabled:!1,sources:[],max_candidates_per_discovery:50,max_concurrent_fetches:5,fetch_timeout_ms:30000},DEFAULT_SKILLS_CONFIG={enabled:!1};PluginConfigSchema=exports_external.object({agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional(),default_agent:exports_external.string().optional().transform((v)=>{if(v===void 0)return;let trimmed=v.trim();return trimmed===""?void 0:trimmed}),auto_select_architect:exports_external.union([exports_external.boolean(),exports_external.string()]).optional().transform((v)=>{if(v===void 0)return;if(typeof v==="boolean")return v;let trimmed=v.trim();return trimmed===""?!1:trimmed}),swarms:exports_external.record(exports_external.string().regex(/^[^_]+$/,"Swarm ID must not contain underscores"),SwarmConfigSchema).optional(),max_iterations:exports_external.number().min(1).max(10).default(5),pipeline:PipelineConfigSchema.optional(),phase_complete:PhaseCompleteConfigSchema.optional(),qa_retry_limit:exports_external.number().min(1).max(10).default(3),execution_mode:exports_external.enum(["strict","balanced","fast"]).default("balanced"),inject_phase_reminders:exports_external.boolean().default(!0),hooks:HooksConfigSchema.optional(),gates:GateConfigSchema.optional(),context_budget:ContextBudgetConfigSchema.optional(),pricing:PricingConfigSchema.optional(),guardrails:GuardrailsConfigSchema.optional(),watchdog:WatchdogConfigSchema.optional(),self_review:SelfReviewConfigSchema.optional(),auto_review:AutoReviewConfigSchema.optional(),tool_filter:ToolFilterConfigSchema.optional(),authority:AuthorityConfigSchema.optional(),plan_cursor:PlanCursorConfigSchema.optional(),context_map:ContextMapConfigSchema.optional(),repo_graph:RepoGraphConfigSchema.optional(),evidence:EvidenceConfigSchema.optional(),summaries:SummaryConfigSchema.optional(),review_passes:ReviewPassesConfigSchema.optional(),adversarial_detection:AdversarialDetectionConfigSchema.optional(),adversarial_testing:AdversarialTestingConfigSchema.optional(),integration_analysis:IntegrationAnalysisConfigSchema.optional(),docs:DocsConfigSchema.optional(),design_docs:DesignDocsConfigSchema.optional(),ui_review:UIReviewConfigSchema.optional(),compaction_advisory:CompactionAdvisoryConfigSchema.optional(),lint:LintConfigSchema.optional(),secretscan:SecretscanConfigSchema.optional(),checkpoint:CheckpointConfigSchema.optional(),automation:AutomationConfigSchema.optional(),knowledge:KnowledgeConfigSchema.optional(),memory:MemoryConfigSchema.optional(),curator:CuratorConfigSchema.optional(),architectural_supervision:ArchitecturalSupervisionConfigSchema.optional(),knowledge_application:KnowledgeApplicationConfigSchema.optional(),skillPropagation:SkillPropagationConfigSchema.optional(),skill_improver:SkillImproverConfigSchema.optional(),spec_writer:SpecWriterConfigSchema.optional(),tool_output:exports_external.object({truncation_enabled:exports_external.boolean().default(!0),max_lines:exports_external.number().min(10).max(500).default(150),per_tool:exports_external.record(exports_external.string(),exports_external.number()).optional(),truncation_tools:exports_external.array(exports_external.string()).optional().describe("Tools to apply output truncation to. Defaults to diff, symbols, bash, shell, test_runner, lint, pre_check_batch, complexity_hotspots, pkg_audit, sbom_generate, schema_drift.")}).optional(),slop_detector:SlopDetectorConfigSchema.optional(),todo_gate:exports_external.object({enabled:exports_external.boolean().default(!0),max_high_priority:exports_external.number().int().min(-1).default(0).describe("Max new high-priority TODOs (FIXME/HACK/XXX) before warning. 0 = warn on any. Set to -1 to disable."),block_on_threshold:exports_external.boolean().default(!1).describe("If true, block phase completion when threshold exceeded. Default: advisory only.")}).optional(),incremental_verify:IncrementalVerifyConfigSchema.optional(),compaction_service:CompactionConfigSchema.optional(),prm:PrmConfigSchema.optional(),council:CouncilConfigSchema.optional(),parallelization:ParallelizationConfigSchema.optional(),worktree:WorktreeIsolationConfigSchema.optional(),turbo:TurboConfigSchema.optional(),turbo_mode:exports_external.boolean().default(!1).optional(),quiet:exports_external.boolean().default(!0).optional(),version_check:exports_external.boolean().default(!0).optional(),full_auto:exports_external.object({enabled:exports_external.boolean().default(!1),locked:exports_external.boolean().default(!1),critic_model:exports_external.string().optional(),max_interactions_per_phase:exports_external.number().int().min(5).max(200).default(50),deadlock_threshold:exports_external.number().int().min(2).max(10).default(3),escalation_mode:exports_external.enum(["pause","terminate"]).default("pause"),mode:exports_external.enum(["assisted","supervised","strict"]).default("supervised"),fail_closed:exports_external.boolean().default(!0),permission_policy:exports_external.object({enabled:exports_external.boolean().default(!0),trusted_roots:exports_external.array(exports_external.string()).default(["."]),trusted_domains:exports_external.array(exports_external.string()).default([]),protected_paths:exports_external.array(exports_external.string()).default([".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"]),allow_defaults:exports_external.boolean().default(!0)}).default(()=>({enabled:!0,trusted_roots:["."],trusted_domains:[],protected_paths:[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"],allow_defaults:!0})),denials:exports_external.object({max_consecutive:exports_external.number().int().min(1).max(50).default(3),max_total:exports_external.number().int().min(1).max(500).default(20),on_limit:exports_external.enum(["pause","terminate"]).default("pause")}).default(()=>({max_consecutive:3,max_total:20,on_limit:"pause"})),oversight:exports_external.object({on_plan_change:exports_external.boolean().default(!0),on_task_completion:exports_external.boolean().default(!1),on_phase_boundary:exports_external.boolean().default(!0),on_high_risk_action:exports_external.boolean().default(!0),on_subagent_return_warning:exports_external.boolean().default(!0),every_tool_calls:exports_external.number().int().min(0).max(1e4).default(25),every_architect_turns:exports_external.number().int().min(0).max(1000).default(5),every_minutes:exports_external.number().int().min(0).max(1440).default(20)}).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}))}).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}})),pr_monitor:PrMonitorConfigSchema.optional(),external_skills:ExternalSkillsConfigSchema.optional(),skills:SkillsConfigSchema.optional()})});import*as fs from"node:fs";import*as fsPromises from"node:fs/promises";import*as os from"node:os";import*as path from"node:path";function getUserConfigDir(){return process.env.XDG_CONFIG_HOME||path.join(os.homedir(),".config")}function loadRawConfigFromPath(configPath){try{if(fs.statSync(configPath).size>MAX_CONFIG_FILE_BYTES)return console.warn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),console.warn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let content=fs.readFileSync(configPath,"utf-8");if(content.length>MAX_CONFIG_FILE_BYTES)return console.warn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),console.warn("[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 console.warn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),console.warn("[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(error48){if(!(error48 instanceof Error&&("code"in error48)&&error48.code==="ENOENT")){let errorMessage=error48 instanceof Error?error48.message:String(error48);return console.warn(`[opencode-swarm] ⚠️ CONFIG LOAD FAILURE — config exists at ${configPath} but could not be loaded: ${errorMessage}`),console.warn("[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,console.warn("[opencode-swarm] Migrated v6.12 presets config to agents format. Consider updating your opencode-swarm.json."),migrated}}return raw}function sanitizeExternalSkillsConfig(raw){if(!("external_skills"in raw)||raw.external_skills===void 0)return raw;let esResult=ExternalSkillsConfigSchema.safeParse(raw.external_skills);if(esResult.success)return{...raw,external_skills:resolveExternalSkillsConfig(esResult.data)};console.warn("[opencode-swarm] external_skills config validation failed:"),console.warn(esResult.error.format()),console.warn("[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,cleaned}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 loadPluginConfig(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),userResult=loadRawConfigFromPath(userConfigPath),projectResult=loadRawConfigFromPath(projectConfigPath),rawUserConfig=userResult.config,rawProjectConfig=projectResult.config,loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError,mergedRaw=rawUserConfig??{};if(rawProjectConfig)mergedRaw=deepMerge(mergedRaw,rawProjectConfig);if(rawFullAutoLocked(rawUserConfig)||rawFullAutoLocked(rawProjectConfig)){let fullAutoRaw=mergedRaw.full_auto&&typeof mergedRaw.full_auto==="object"&&!Array.isArray(mergedRaw.full_auto)?mergedRaw.full_auto:{};mergedRaw={...mergedRaw,full_auto:{...fullAutoRaw,locked:!0}}}mergedRaw=migratePresetsConfig(mergedRaw),mergedRaw=sanitizeExternalSkillsConfig(mergedRaw);let result=PluginConfigSchema.safeParse(mergedRaw);if(!result.success){if(rawUserConfig){let userParseResult=PluginConfigSchema.safeParse(sanitizeExternalSkillsConfig(rawUserConfig??{}));if(userParseResult.success)return console.warn("[opencode-swarm] Project config ignored due to validation errors. Using user config."),userParseResult.data}return console.warn("[opencode-swarm] Merged config validation failed:"),console.warn(result.error.format()),console.warn("[opencode-swarm] ⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."),PluginConfigSchema.parse({guardrails:{enabled:!0}})}if(loadedFromFile&&configHadErrors)return PluginConfigSchema.parse({...mergedRaw,guardrails:{enabled:!0}});return result.data}function loadPluginConfigWithMeta(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),userResult=loadRawConfigFromPath(userConfigPath),projectResult=loadRawConfigFromPath(projectConfigPath),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError;return{config:loadPluginConfig(directory),loadedFromFile,configHadErrors}}async function loadRawConfigFromPathAsync(configPath){try{if((await fsPromises.stat(configPath)).size>MAX_CONFIG_FILE_BYTES)return console.warn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),console.warn("[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 console.warn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),console.warn("[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 console.warn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),console.warn("[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(error48){if(error48.code==="ENOENT")return{config:null,fileExisted:!1,hadError:!1};return console.warn(`[opencode-swarm] Failed to load config from ${configPath}:`,error48 instanceof Error?error48.message:String(error48)),{config:null,fileExisted:!0,hadError:!0}}}function reduceParsedConfig(rawUserConfig,rawProjectConfig,loadedFromFile,configHadErrors){let mergedRaw=rawUserConfig??{};if(rawProjectConfig)mergedRaw=deepMerge(mergedRaw,rawProjectConfig);mergedRaw=migratePresetsConfig(mergedRaw),mergedRaw=sanitizeExternalSkillsConfig(mergedRaw);let result=PluginConfigSchema.safeParse(mergedRaw);if(!result.success){if(rawUserConfig){let userParseResult=PluginConfigSchema.safeParse(sanitizeExternalSkillsConfig(rawUserConfig??{}));if(userParseResult.success)return console.warn("[opencode-swarm] Project config ignored due to validation errors. Using user config."),userParseResult.data}return console.warn("[opencode-swarm] Merged config validation failed:"),console.warn(result.error.format()),console.warn("[opencode-swarm] ⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."),PluginConfigSchema.parse({guardrails:{enabled:!0}})}if(loadedFromFile&&configHadErrors)return PluginConfigSchema.parse({...mergedRaw,guardrails:{enabled:!0}});return result.data}async function loadPluginConfigWithMetaAsync(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),[userResult,projectResult]=await Promise.all([loadRawConfigFromPathAsync(userConfigPath),loadRawConfigFromPathAsync(projectConfigPath)]),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError;return{config:reduceParsedConfig(userResult.config,projectResult.config,loadedFromFile,configHadErrors),loadedFromFile,configHadErrors}}function loadAgentPrompt(agentName){let promptsDir=path.join(getUserConfigDir(),"opencode",PROMPTS_DIR_NAME),result={},promptPath=path.join(promptsDir,`${agentName}.md`);if(fs.existsSync(promptPath))try{result.prompt=fs.readFileSync(promptPath,"utf-8")}catch(error48){console.warn(`[opencode-swarm] Error reading prompt file ${promptPath}:`,error48 instanceof Error?error48.message:String(error48))}let appendPromptPath=path.join(promptsDir,`${agentName}_append.md`);if(fs.existsSync(appendPromptPath))try{result.appendPrompt=fs.readFileSync(appendPromptPath,"utf-8")}catch(error48){console.warn(`[opencode-swarm] Error reading append prompt ${appendPromptPath}:`,error48 instanceof Error?error48.message:String(error48))}return result}var CONFIG_FILENAME="opencode-swarm.json",PROMPTS_DIR_NAME="opencode-swarm",MAX_CONFIG_FILE_BYTES=102400;var init_loader=__esm(()=>{init_schema()});var ExecutionProfileSchema,TaskStatusSchema,TaskSizeSchema,PhaseStatusSchema,MigrationStatusSchema,TaskSchema,PhaseSchema,PlanSchema;var init_plan_schema=__esm(()=>{init_zod();ExecutionProfileSchema=exports_external.object({parallelization_enabled:exports_external.boolean().default(!1),max_concurrent_tasks:exports_external.number().int().min(1).max(64).default(10),council_parallel:exports_external.boolean().default(!0),locked:exports_external.boolean().default(!1),auto_proceed:exports_external.boolean().default(!1)}),TaskStatusSchema=exports_external.enum(["pending","in_progress","completed","blocked","closed"]),TaskSizeSchema=exports_external.enum(["small","medium","large"]),PhaseStatusSchema=exports_external.enum(["pending","in_progress","complete","completed","blocked","closed"]),MigrationStatusSchema=exports_external.enum(["native","migrated","migration_failed"]),TaskSchema=exports_external.object({id:exports_external.string(),phase:exports_external.number().int().min(1),status:TaskStatusSchema.default("pending"),size:TaskSizeSchema.default("small"),description:exports_external.string().min(1),depends:exports_external.array(exports_external.string()).default([]),acceptance:exports_external.string().optional(),files_touched:exports_external.array(exports_external.string()).default([]),evidence_path:exports_external.string().optional(),blocked_reason:exports_external.string().optional()}),PhaseSchema=exports_external.object({id:exports_external.number().int().min(1),name:exports_external.string().min(1),status:PhaseStatusSchema.default("pending"),tasks:exports_external.array(TaskSchema).default([]),type:exports_external.enum(["code","non-code"]).optional(),required_agents:exports_external.array(exports_external.string()).optional()}),PlanSchema=exports_external.object({schema_version:exports_external.literal("1.0.0"),title:exports_external.string().min(1),swarm:exports_external.string().min(1),current_phase:exports_external.number().int().min(1).optional(),phases:exports_external.array(PhaseSchema).min(1),migration_status:MigrationStatusSchema.optional(),specMtime:exports_external.string().optional(),specHash:exports_external.string().optional(),execution_profile:ExecutionProfileSchema.optional()})});function stripCodeBlocks(content){return content.replace(FENCED_BLOCK_PATTERN,"").replace(INLINE_CODE_PATTERN,"")}function getLineNumber(content,position){return(content.substring(0,position).match(/\n/g)||[]).length+1}function validateSpecContent(content){let issues=[];if(!content||content.trim().length===0)return{valid:!1,issues:[{line:1,message:"Content is empty"}]};let strippedContent=stripCodeBlocks(content),frMatches=strippedContent.match(FR_ID_PATTERN);if(!frMatches||frMatches.length===0)issues.push({line:1,message:"No FR-### requirement IDs found in spec content"});let obligationMatches=strippedContent.match(OBLIGATION_PATTERN);if(!obligationMatches||obligationMatches.length===0)issues.push({line:1,message:"No obligation keywords (MUST, SHALL, SHOULD, MAY) found in spec content"});let sectionMatches=strippedContent.match(SECTION_HEADER_PATTERN);if(!sectionMatches||sectionMatches.length===0)issues.push({line:1,message:"No section headers (## Section Name) found in spec content"});let idMatches=strippedContent.matchAll(/\bFR-(\d{3})\b/g);for(let idMatch of idMatches)if(parseInt(idMatch[1],10)===0){let pos=idMatch.index;issues.push({line:getLineNumber(strippedContent,pos),message:`Invalid FR-ID "${idMatch[0]}" — number must be 001-999`})}return{valid:issues.length===0,issues}}var ObligationSchema,SpecRequirementSchema,SpecScenarioSchema,SpecSectionSchema,SwarmSpecSchema,SpecDeltaSchema,DeltaSpecSchema,FENCED_BLOCK_PATTERN,INLINE_CODE_PATTERN,FR_ID_PATTERN,OBLIGATION_PATTERN,SECTION_HEADER_PATTERN;var init_spec_schema=__esm(()=>{init_zod();ObligationSchema=exports_external.enum(["MUST","SHALL","SHOULD","MAY"]),SpecRequirementSchema=exports_external.object({id:exports_external.string().regex(/^FR-(?!000)\d{3}$/,"Requirement ID must match FR-### pattern (e.g., FR-001)"),obligation:ObligationSchema,text:exports_external.string().min(1)}),SpecScenarioSchema=exports_external.object({name:exports_external.string().min(1),given:exports_external.array(exports_external.string()).optional().default([]),when:exports_external.array(exports_external.string()).min(1,'Scenario must have at least one "when" clause'),thenClauses:exports_external.array(exports_external.string()).min(1,'Scenario must have at least one "then" clause')}),SpecSectionSchema=exports_external.object({name:exports_external.string().min(1),requirements:exports_external.array(SpecRequirementSchema).default([])}),SwarmSpecSchema=exports_external.object({title:exports_external.string().min(1),purpose:exports_external.string().min(1),sections:exports_external.array(SpecSectionSchema).min(1,"Spec must have at least one section")}),SpecDeltaSchema=exports_external.object({added:exports_external.array(SpecRequirementSchema).default([]),modified:exports_external.array(SpecRequirementSchema).default([]),removed:exports_external.array(SpecRequirementSchema).default([])}),DeltaSpecSchema=exports_external.union([SwarmSpecSchema,SpecDeltaSchema]),FENCED_BLOCK_PATTERN=/```[\s\S]*?```/g,INLINE_CODE_PATTERN=/`[^`]*`/g,FR_ID_PATTERN=/\bFR-\d{3}\b/g,OBLIGATION_PATTERN=/\b(MUST|SHALL|SHOULD|MAY)\b/g,SECTION_HEADER_PATTERN=/^##\s+.+$/gm});var exports_config={};__export(exports_config,{validateSpecContent:()=>validateSpecContent,loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadAgentPrompt:()=>loadAgentPrompt,isSubagent:()=>isSubagent,isQAAgent:()=>isQAAgent,_internals:()=>_internals2,WorktreeIsolationConfigSchema:()=>WorktreeIsolationConfigSchema,TurboConfigSchema:()=>TurboConfigSchema,TestEvidenceSchema:()=>TestEvidenceSchema,TaskStatusSchema:()=>TaskStatusSchema,TaskSizeSchema:()=>TaskSizeSchema,TaskSchema:()=>TaskSchema,SwarmSpecSchema:()=>SwarmSpecSchema,SwarmConfigSchema:()=>SwarmConfigSchema,SpecSectionSchema:()=>SpecSectionSchema,SpecScenarioSchema:()=>SpecScenarioSchema,SpecRequirementSchema:()=>SpecRequirementSchema,SpecDeltaSchema:()=>SpecDeltaSchema,SkillPropagationConfigSchema:()=>SkillPropagationConfigSchema,ReviewEvidenceSchema:()=>ReviewEvidenceSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QA_AGENTS:()=>QA_AGENTS,PricingConfigSchema:()=>PricingConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanSchema:()=>PlanSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseStatusSchema:()=>PhaseStatusSchema,PhaseSchema:()=>PhaseSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,PIPELINE_AGENTS:()=>PIPELINE_AGENTS,ObligationSchema:()=>ObligationSchema,ORCHESTRATOR_NAME:()=>ORCHESTRATOR_NAME,NoteEvidenceSchema:()=>NoteEvidenceSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MigrationStatusSchema:()=>MigrationStatusSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,EvidenceVerdictSchema:()=>EvidenceVerdictSchema,EvidenceTypeSchema:()=>EvidenceTypeSchema,EvidenceSchema:()=>EvidenceSchema,EvidenceBundleSchema:()=>EvidenceBundleSchema,EVIDENCE_MAX_TASK_BYTES:()=>EVIDENCE_MAX_TASK_BYTES,EVIDENCE_MAX_PATCH_BYTES:()=>EVIDENCE_MAX_PATCH_BYTES,EVIDENCE_MAX_JSON_BYTES:()=>EVIDENCE_MAX_JSON_BYTES,DiffEvidenceSchema:()=>DiffEvidenceSchema,DeltaSpecSchema:()=>DeltaSpecSchema,DEFAULT_MODELS:()=>DEFAULT_MODELS,BaseEvidenceSchema:()=>BaseEvidenceSchema,AutomationModeSchema:()=>AutomationModeSchema,AutomationConfigSchema:()=>AutomationConfigSchema,AutomationCapabilitiesSchema:()=>AutomationCapabilitiesSchema,ApprovalEvidenceSchema:()=>ApprovalEvidenceSchema,AgentOverrideConfigSchema:()=>AgentOverrideConfigSchema,ALL_SUBAGENT_NAMES:()=>ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES:()=>ALL_AGENT_NAMES});var _internals2;var init_config=__esm(()=>{init_constants();init_evidence_schema();init_loader();init_loader();init_plan_schema();init_schema();init_spec_schema();_internals2={loadPluginConfigWithMeta}});function addDeferredWarning(warning){if(deferredWarnings.length<50)deferredWarnings.push(warning)}function getDeferredWarnings(){return[...deferredWarnings]}function clearDeferredWarnings(){deferredWarnings.length=0}var deferredWarnings;var init_warning_buffer=__esm(()=>{deferredWarnings=[]});function resolvePrompt(base,custom2,append){if(custom2)return custom2;if(append)return`${base}
159
159
 
160
160
  ${append}`;return base}import*as fs2 from"node:fs";import*as fsp from"node:fs/promises";import*as path2 from"node:path";function getSyncCacheKey(projectDirectory,packageRoot){return`${path2.resolve(projectDirectory)}\x00${path2.resolve(packageRoot)}`}function warnBundledSkillSyncFailure(err){let message=err instanceof Error?err.message:String(err);console.warn(`[opencode-swarm] Could not install bundled project skills; continuing without sync: ${message}`)}async function isSymbolicLinkAsync(p){try{return(await fsp.lstat(p)).isSymbolicLink()}catch{return!1}}async function ensureNotSymlinkedDirectoryAsync(p){try{let stat3=await fsp.lstat(p);return stat3.isDirectory()&&!stat3.isSymbolicLink()}catch(err){return err.code==="ENOENT"}}async function pathExistsAsync(p){try{return await fsp.access(p),!0}catch{return!1}}async function collectBundledSkillFilesBoundedAsync(sourceDir,state,relativeDir=""){let currentSource=path2.join(sourceDir,relativeDir),entries=await fsp.readdir(currentSource,{withFileTypes:!0}),files=[];for(let entry of entries){let relativeEntry=path2.join(relativeDir,entry.name),sourcePath=path2.join(sourceDir,relativeEntry);if(entry.isSymbolicLink()||await isSymbolicLinkAsync(sourcePath))continue;if(entry.isDirectory()){files.push(...await collectBundledSkillFilesBoundedAsync(sourceDir,state,relativeEntry));continue}if(!entry.isFile())continue;let stat3=await fsp.stat(sourcePath),nextFiles=state.files+1,nextBytes=state.bytes+stat3.size;if(nextFiles>MAX_SKILL_FILES||nextBytes>MAX_SKILL_BYTES)throw Error("bundled skill package exceeds copy bounds");state.files=nextFiles,state.bytes=nextBytes,files.push({relativePath:relativeEntry})}return files}async function rollbackCopiedFilesAsync(copiedFiles,destDir){let safeDestDir=path2.resolve(destDir),dirs=new Set;for(let copiedFile of copiedFiles){let resolvedFile=path2.resolve(copiedFile),relative2=path2.relative(safeDestDir,resolvedFile);if(relative2.startsWith("..")||path2.isAbsolute(relative2))continue;try{await fsp.rm(resolvedFile,{force:!0})}catch{}dirs.add(path2.dirname(resolvedFile))}for(let dir of[...dirs].sort((a,b)=>b.length-a.length)){let relative2=path2.relative(safeDestDir,path2.resolve(dir));if(relative2.startsWith("..")||path2.isAbsolute(relative2))continue;try{await fsp.rmdir(dir)}catch{}}}async function copyBundledDirectoryBoundedAsync(sourceDir,destDir){let files=await collectBundledSkillFilesBoundedAsync(sourceDir,{files:0,bytes:0}),copiedFiles=[];try{for(let file2 of files){let sourcePath=path2.join(sourceDir,file2.relativePath),destPath=path2.join(destDir,file2.relativePath);await fsp.mkdir(path2.dirname(destPath),{recursive:!0});try{await fsp.copyFile(sourcePath,destPath,fs2.constants.COPYFILE_EXCL),copiedFiles.push(destPath)}catch(err){if(err.code!=="EEXIST")throw err}}}catch(err){throw await rollbackCopiedFilesAsync(copiedFiles,destDir),err}}async function syncBundledProjectSkillsIfMissingAsync(projectDirectory,packageRoot,quiet=!1){try{let cacheKey=getSyncCacheKey(projectDirectory,packageRoot);if(syncedProjectSkillTargets.has(cacheKey))return;let sourceRoot=path2.join(packageRoot,".opencode","skills"),opencodeDir=path2.join(projectDirectory,".opencode"),skillsDir=path2.join(opencodeDir,"skills"),sawBundledSource=!1;if(!await ensureNotSymlinkedDirectoryAsync(opencodeDir))return;if(!await ensureNotSymlinkedDirectoryAsync(skillsDir))return;for(let slug of BUNDLED_PROJECT_SKILLS){let sourceDir=path2.join(sourceRoot,slug),sourceSkill=path2.join(sourceDir,"SKILL.md"),destDir=path2.join(skillsDir,slug),destSkill=path2.join(destDir,"SKILL.md");if(!await pathExistsAsync(sourceSkill))continue;if(sawBundledSource=!0,await pathExistsAsync(destSkill))continue;if(!await ensureNotSymlinkedDirectoryAsync(destDir))continue;if(await copyBundledDirectoryBoundedAsync(sourceDir,destDir),!quiet)console.warn(`[opencode-swarm] Installed bundled skill .opencode/skills/${slug}/SKILL.md for first-class /swarm command support`)}if(sawBundledSource)syncedProjectSkillTargets.add(cacheKey)}catch(err){if(!quiet)warnBundledSkillSyncFailure(err)}}var BUNDLED_PROJECT_SKILLS,MAX_SKILL_FILES=64,MAX_SKILL_BYTES=512000,syncedProjectSkillTargets;var init_bundled_skills=__esm(()=>{BUNDLED_PROJECT_SKILLS=["brainstorm","specify","clarify-spec","resume","clarify","discover","consult","pre-phase-briefing","council","deep-dive","deep-research","codebase-review-swarm","design-docs","swarm-pr-review","swarm-pr-feedback","issue-ingest","plan","critic-gate","execute","phase-wrap","loop","writing-tests","running-tests","engineering-conventions","commit-pr"],syncedProjectSkillTargets=new Set});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=()=>{};var SwarmError;var init_errors3=__esm(()=>{SwarmError=class SwarmError extends Error{code;guidance;constructor(message,code,guidance){super(message);this.name="SwarmError",this.code=code,this.guidance=guidance}}});function escapeRegex2(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function simpleGlobToRegex(pattern,flags="i"){let escaped=pattern.split("*").map((starSegment)=>starSegment.split("?").map(escapeRegex2).join(".")).join(".*");return new RegExp(`^${escaped}$`,flags)}var init_utils=__esm(()=>{init_errors3();init_logger()});import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import*as fsSync from"node:fs";import*as fsPromises2 from"node:fs/promises";import*as path3 from"node:path";function getBun(){return globalThis.Bun}function bunFile(filePath){let bun=getBun();if(bun?.file)return bun.file(filePath);let cachedSize;return{async text(){return fsPromises2.readFile(filePath,"utf-8")},async arrayBuffer(){let buf=await fsPromises2.readFile(filePath),ab=new ArrayBuffer(buf.byteLength);return new Uint8Array(ab).set(buf),ab},async exists(){try{return await fsPromises2.access(filePath,fsSync.constants.F_OK),!0}catch{return!1}},get size(){if(cachedSize!==void 0)return cachedSize;try{cachedSize=fsSync.statSync(filePath).size}catch{cachedSize=0}return cachedSize}}}async function bunWrite(filePath,data){let bun=getBun();if(bun?.write)return bun.write(filePath,data);let dir=path3.dirname(filePath),tempName=`.${path3.basename(filePath)}.${process.pid}.${Date.now()}.${tempCounter++}.${Math.random().toString(36).slice(2,10)}.tmp`,tempPath=path3.join(dir,tempName),buffer;if(typeof data==="string")buffer=data;else if(data instanceof ArrayBuffer)buffer=new Uint8Array(data);else if(ArrayBuffer.isView(data))buffer=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else buffer=new Uint8Array(0);try{await fsPromises2.mkdir(dir,{recursive:!0})}catch{}await fsPromises2.writeFile(tempPath,buffer);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES;attempt++)try{await fsPromises2.rename(tempPath,filePath),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;await new Promise((r)=>setTimeout(r,WINDOWS_RENAME_RETRY_DELAY_MS))}if(lastError){try{await fsPromises2.unlink(tempPath)}catch{}throw lastError}try{let dirFd=await fsPromises2.open(dir,"r");try{await dirFd.sync()}finally{await dirFd.close()}}catch{}return(await fsPromises2.stat(filePath)).size}function bunHash(input){let bun=getBun();if(bun?.hash){let r=bun.hash(input);return typeof r==="bigint"?r:BigInt(r)}let bytes;if(typeof input==="string")bytes=new TextEncoder().encode(input);else if(input instanceof ArrayBuffer)bytes=new Uint8Array(input);else bytes=new Uint8Array(input.buffer,input.byteOffset,input.byteLength);let hash2=5381n;for(let b of bytes)hash2=hash2*33n+BigInt(b)&0xffffffffffffffffn;return hash2}function killProcessTreeImpl(pid,signal,directKill,wasDetached){if(typeof pid!=="number"||pid<=0){directKill();return}if(process.platform==="win32"){try{nodeSpawnSync("taskkill",["/PID",String(pid),"/T","/F"])}catch{directKill()}return}if(wasDetached)try{process.kill(-pid,signal??"SIGKILL");return}catch{}directKill()}function streamFromNode(pipe2){let collected=new Promise((resolve2)=>{if(!pipe2){resolve2(Buffer.alloc(0));return}let chunks=[];pipe2.on("data",(chunk)=>{chunks.push(typeof chunk==="string"?Buffer.from(chunk):chunk)}),pipe2.on("end",()=>resolve2(Buffer.concat(chunks))),pipe2.on("error",()=>resolve2(Buffer.concat(chunks)))}),toWebReadable=()=>{if(!pipe2)return new ReadableStream({start(controller){controller.close()}});let r=pipe2;if(typeof r.toWeb==="function")return r.toWeb();return new ReadableStream({start(controller){pipe2.on("data",(chunk)=>{controller.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength))}),pipe2.on("end",()=>controller.close()),pipe2.on("error",(err)=>controller.error(err))},cancel(){let destroyable=pipe2;if(typeof destroyable.destroy==="function")try{destroyable.destroy()}catch{}}})};return{async text(){return(await collected).toString("utf-8")},async bytes(){let b=await collected;return new Uint8Array(b.buffer,b.byteOffset,b.byteLength)},getReader(){return toWebReadable().getReader()}}}function mapStdio(v){return v??"pipe"}function streamFromBun(stream){if(!stream||typeof stream!=="object")return{async text(){return""},async bytes(){return new Uint8Array(0)},getReader(){return new ReadableStream({start(controller){controller.close()}}).getReader()}};let candidate=stream,collect=async()=>{if(typeof candidate.getReader!=="function")return new Uint8Array(0);let reader=candidate.getReader(),chunks=[];for(;;){let{done,value}=await reader.read();if(done)break;if(value)chunks.push(value)}let total=chunks.reduce((acc,c)=>acc+c.byteLength,0),out=new Uint8Array(total),off=0;for(let c of chunks)out.set(c,off),off+=c.byteLength;return out},text=typeof candidate.text==="function"?()=>candidate.text():async()=>new TextDecoder().decode(await collect()),bytes=typeof candidate.bytes==="function"?()=>candidate.bytes():collect,getReader=typeof candidate.getReader==="function"?()=>candidate.getReader():()=>new ReadableStream({start(controller){controller.close()}}).getReader();return{text,bytes,getReader}}function bunSpawn(cmd,options){let bun=getBun();if(bun?.spawn){let proc2=bun.spawn(cmd,options);return{stdout:streamFromBun(proc2.stdout),stderr:streamFromBun(proc2.stderr),exited:proc2.exited,get exitCode(){return proc2.exitCode},kill(sig){if(options?.killProcessTree)killProcessTreeImpl(proc2.pid,sig,()=>proc2.kill(sig),!1);else proc2.kill(sig)}}}let[file2,...args2]=cmd,detached=options?.killProcessTree===!0,proc=nodeSpawn(file2,args2,{cwd:options?.cwd,env:options?.env,detached,windowsHide:!0,stdio:[mapStdio(options?.stdin),mapStdio(options?.stdout),mapStdio(options?.stderr)]}),killChild=(signal)=>{if(detached)killProcessTreeImpl(proc.pid,signal,()=>proc.kill(signal),!0);else proc.kill(signal)},timeoutHandle,exited=new Promise((resolve2)=>{if(proc.on("exit",(code)=>resolve2(code??0)),proc.on("error",()=>resolve2(1)),options?.timeout&&options.timeout>0){if(timeoutHandle=setTimeout(()=>{try{killChild("SIGKILL")}catch{}},options.timeout),typeof timeoutHandle.unref==="function")timeoutHandle.unref()}}).finally(()=>{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle)});return{stdout:streamFromNode(proc.stdout),stderr:streamFromNode(proc.stderr),exited,get exitCode(){return proc.exitCode},kill(signal){killChild(signal)}}}function bunSpawnSync(cmd,options){let bun=getBun();if(bun?.spawnSync)return bun.spawnSync(cmd,options);let argv,mergedOptions;if(Array.isArray(cmd))argv=cmd,mergedOptions={...options??{}};else if(argv=cmd.cmd,mergedOptions={cwd:cmd.cwd,env:cmd.env,stdin:"pipe",timeout:cmd.timeout,...options??{}},cmd.stdin!==void 0)mergedOptions.stdin=cmd.stdin;let[file2,...args2]=argv,result=nodeSpawnSync(file2,args2,{cwd:mergedOptions.cwd,env:mergedOptions.env,input:mergedOptions.stdin instanceof Uint8Array||typeof mergedOptions.stdin==="string"?mergedOptions.stdin:void 0,timeout:mergedOptions.timeout,windowsHide:!0}),stdout=result.stdout instanceof Buffer?new Uint8Array(result.stdout.buffer,result.stdout.byteOffset,result.stdout.byteLength):typeof result.stdout==="string"?new TextEncoder().encode(result.stdout):new Uint8Array(0),stderr=result.stderr instanceof Buffer?new Uint8Array(result.stderr.buffer,result.stderr.byteOffset,result.stderr.byteLength):typeof result.stderr==="string"?new TextEncoder().encode(result.stderr):new Uint8Array(0),exitCode=result.status??(result.signal?128:1);return{stdout,stderr,exitCode,success:exitCode===0&&!result.error}}var WINDOWS_RENAME_MAX_RETRIES=3,WINDOWS_RENAME_RETRY_DELAY_MS=50,tempCounter=0;var init_bun_compat=()=>{};import*as fsSync2 from"node:fs";import*as fs3 from"node:fs/promises";import*as path4 from"node:path";function sameStamp(a,b){return a.mtimeMs===b.mtimeMs&&a.ctimeMs===b.ctimeMs&&a.size===b.size}async function getStamp(filePath){try{let stat5=await fs3.stat(filePath);if(!stat5.isFile())return null;return{mtimeMs:stat5.mtimeMs,ctimeMs:stat5.ctimeMs,size:stat5.size}}catch{return stats.statFailureCount++,null}}function getStampSync(filePath){try{let stat5=fsSync2.statSync(filePath);if(!stat5.isFile())return null;return{mtimeMs:stat5.mtimeMs,ctimeMs:stat5.ctimeMs,size:stat5.size}}catch{return stats.statFailureCount++,null}}function canStoreRead(before,after){return after!==null&&sameStamp(before,after)}function setBounded(cache,key,value,cacheKind){cache.set(key,value);while(cache.size>MAX_CACHE_ENTRIES){let oldest=cache.keys().next().value;if(oldest===void 0)break;if(cache.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=path4.resolve(filePath),stamp=getStampSync(cacheKey);if(!stamp)return stats.textReadCount++,directRead();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=path4.resolve(filePath),stamp=await getStamp(cacheKey);if(!stamp)return stats.textReadCount++,directRead();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=path4.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=path4.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)}var MAX_CACHE_ENTRIES=128,textCache,parsedCache,stats;var init_swarm_artifact_cache=__esm(()=>{textCache=new Map,parsedCache=new Map,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}});import*as fs4 from"node:fs";import*as path5 from"node:path";function isFailClosedHandler(value){return typeof value==="function"&&Object.hasOwn(value,"__failClosed")&&value.__failClosed===!0}function safeHook(fn2){return async(input,output)=>{try{await fn2(input,output)}catch(_error){let functionName=fn2.name||"unknown";if(_error instanceof SwarmError)warn(`Hook '${functionName}' failed: ${_error.message}
161
161
  → ${_error.guidance}`);else warn(`Hook function '${functionName}' failed:`,_error)}}}function composeHandlers(...fns){if(fns.length===0)return async()=>{};return async(input,output)=>{for(let fn2 of fns){if(isFailClosedHandler(fn2))throw Error("composeHandlers cannot wrap fail-closed handlers; use composeBlockingHandlers or await them directly");await _internals3.safeHook(fn2)(input,output)}}}function validateSwarmPath(directory,filename){if(/[\0]/.test(filename))throw Error("Invalid filename: contains null bytes");if(/\.\.[/\\]/.test(filename))throw Error("Invalid filename: path traversal detected");if(/^[A-Za-z]:[\\/]/.test(filename))throw Error("Invalid filename: path escapes .swarm directory");if(filename.startsWith("/"))throw Error("Invalid filename: path escapes .swarm directory");let baseDir=path5.normalize(path5.resolve(directory,".swarm")),resolved=path5.normalize(path5.resolve(baseDir,filename));if(process.platform==="win32"){if(!resolved.toLowerCase().startsWith((baseDir+path5.sep).toLowerCase()))throw Error("Invalid filename: path escapes .swarm directory")}else if(!resolved.startsWith(baseDir+path5.sep))throw Error("Invalid filename: path escapes .swarm directory");let realBaseDir;try{if(fs4.lstatSync(baseDir).isSymbolicLink())throw Error("Invalid filename: path escapes .swarm directory");realBaseDir=fs4.realpathSync(baseDir)}catch(error49){if(error49 instanceof Error&&error49.message==="Invalid filename: path escapes .swarm directory")throw error49;if(error49.code==="ENOENT")return resolved;throw Error("Invalid filename: failed to resolve .swarm directory")}let existingPath=resolved;while(!fs4.existsSync(existingPath)){let parent=path5.dirname(existingPath);if(parent===existingPath||!isPathWithin(parent,baseDir)){existingPath=baseDir;break}existingPath=parent}let realExistingPath;try{realExistingPath=fs4.realpathSync(existingPath)}catch(error49){if(error49.code==="ENOENT")realExistingPath=realBaseDir;else throw Error("Invalid filename: failed to resolve path")}if(!isPathWithin(realExistingPath,realBaseDir))throw Error("Invalid filename: path escapes .swarm directory");return resolved}function isPathWithin(candidate,base){let normalizedCandidate=path5.normalize(candidate),normalizedBase=path5.normalize(base);if(process.platform==="win32"){let candidateLower=normalizedCandidate.toLowerCase(),baseLower=normalizedBase.toLowerCase();return candidateLower===baseLower||candidateLower.startsWith(`${baseLower}${path5.sep}`)}return normalizedCandidate===normalizedBase||normalizedCandidate.startsWith(`${normalizedBase}${path5.sep}`)}async function readSwarmFileAsync(directory,filename,cache){if(cache!==void 0){let key=`${directory}::${filename}`,cached2=cache.get(key);if(cached2!==void 0)return cached2;let promise2=readSwarmFileAsync(directory,filename);return cache.set(key,promise2),promise2}let maxAttempts=5,retryDelayMs=10;for(let attempt=0;attempt<maxAttempts;attempt++)try{let resolvedPath=_internals3.validateSwarmPath(directory,filename);return await _internals3.readCachedTextFile(resolvedPath,async()=>{return await bunFile(resolvedPath).text()})}catch(err){if(err?.code!=="ENOENT"||attempt===maxAttempts-1)return null;await new Promise((resolve4)=>setTimeout(resolve4,retryDelayMs))}return null}function estimateTokens(text){if(!text)return 0;return Math.ceil(text.length*0.33)}var _internals3;var init_utils2=__esm(()=>{init_utils();init_bun_compat();init_swarm_artifact_cache();_internals3={safeHook,composeHandlers,validateSwarmPath,readSwarmFileAsync,readCachedTextFile}});function isGitBinaryMissing(err){return typeof err==="object"&&err!==null&&"code"in err&&err.code==="ENOENT"}var GitBinaryMissingError;var init_git_binary_missing_error=__esm(()=>{GitBinaryMissingError=class GitBinaryMissingError extends Error{name="GitBinaryMissingError";constructor(message="git binary is not available",options){super(message,options)}}});function isTransientSpawnError(error49){if(!error49||typeof error49!=="object")return!1;return error49.code==="ETIMEDOUT"}function transientBackoff(attempt){let delay=200*2**attempt;try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,delay)}catch{let start=Date.now();while(Date.now()-start<delay);}}var MAX_TRANSIENT_RETRIES=5;import*as child_process from"node:child_process";import path6 from"node:path";function unique(values){return[...new Set(values.filter(Boolean))]}function windowsGitCandidates(){if(process.platform!=="win32")return["git"];let installed=unique([process.env.ProgramFiles??"",process.env["ProgramFiles(x86)"]??"",process.env.LOCALAPPDATA?path6.join(process.env.LOCALAPPDATA,"Programs"):""]).flatMap((root)=>[path6.join(root,"Git","cmd","git.exe"),path6.join(root,"Git","bin","git.exe")]);return unique(["git",...installed])}function errorMessage(err){return err instanceof Error?err.message:String(err)}function isNotGitRepositoryMessage(message){let lower=message.toLowerCase();return lower.includes("not a git repository")||lower.includes("not a git repo")}function gitExec(args2,cwd){let missingGitError,subcommand=args2[0],hardenedArgs=subcommand==="commit"||subcommand==="tag"?["-c","commit.gpgsign=false","-c","tag.gpgsign=false",...args2]:args2;for(let command of windowsGitCandidates())for(let attempt=0;attempt<MAX_TRANSIENT_RETRIES;attempt++){let result=child_process.spawnSync(command,hardenedArgs,{cwd,encoding:"utf-8",timeout:GIT_TIMEOUT_MS,windowsHide:!0,maxBuffer:GIT_MAX_BUFFER_BYTES,stdio:["ignore","pipe","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});if(!result.error&&result.status===0)return result.stdout;if(result.error){if(isGitBinaryMissing(result.error)){missingGitError??=result.error;break}if(isTransientSpawnError(result.error)&&attempt<MAX_TRANSIENT_RETRIES-1){transientBackoff(attempt);continue}throw Error(errorMessage(result.error))}if(result.status!==0)throw Error(result.stderr||result.stdout||`git exited with ${result.status}`)}throw new GitBinaryMissingError(process.platform==="win32"?"git executable is not available on PATH or common Windows install locations":"git executable is not available on PATH",{cause:missingGitError})}function getGitRepositoryStatus(cwd){try{return gitExec(["rev-parse","--git-dir"],cwd),{isRepo:!0}}catch(err){if(err instanceof GitBinaryMissingError)return{isRepo:!1,reason:"git_unavailable",message:err.message};let message=errorMessage(err);return{isRepo:!1,reason:isNotGitRepositoryMessage(message)?"not_git_repo":"git_error",message}}}function isGitRepo(cwd){return getGitRepositoryStatus(cwd).isRepo}function getCurrentBranch(cwd){return gitExec(["rev-parse","--abbrev-ref","HEAD"],cwd).trim()}function getDefaultBaseBranch(cwd){try{return gitExec(["rev-parse","--verify","origin/main"],cwd),"origin/main"}catch{try{return gitExec(["rev-parse","--verify","origin/master"],cwd),"origin/master"}catch{return"origin/main"}}}function hasUncommittedChanges(cwd){return gitExec(["status","--porcelain"],cwd).trim().length>0}function detectDefaultRemoteBranch(cwd){try{let trimmed=gitExec(["symbolic-ref","refs/remotes/origin/HEAD"],cwd).trim();if(trimmed.startsWith("refs/remotes/origin/"))return trimmed.slice(20)}catch{}try{let branch=gitExec(["config","init.defaultBranch"],cwd).trim();if(branch)return branch}catch{}try{return gitExec(["rev-parse","--verify","origin/main"],cwd),"main"}catch{}try{return gitExec(["rev-parse","--verify","origin/master"],cwd),"master"}catch{return null}}async function resetToRemoteBranch(cwd,options){let warnings=[],prunedBranches=[];try{let currentBranch=getCurrentBranch(cwd),defaultRemoteBranch=_internals4.detectDefaultRemoteBranch(cwd);if(!defaultRemoteBranch)return{success:!1,targetBranch:"",localBranch:currentBranch,message:"Could not detect default remote branch",alreadyAligned:!1,prunedBranches:[],warnings:[]};let targetBranch=`origin/${defaultRemoteBranch}`;if(currentBranch==="HEAD")return{success:!1,targetBranch,localBranch:"HEAD",message:"Cannot reset: detached HEAD state",alreadyAligned:!1,prunedBranches:[],warnings:[]};if(hasUncommittedChanges(cwd))return{success:!1,targetBranch,localBranch:currentBranch,message:"Cannot reset: uncommitted changes in working tree",alreadyAligned:!1,prunedBranches:[],warnings:[]};try{if(gitExec(["log",`${targetBranch}..HEAD`,"--oneline"],cwd).trim().length>0)return{success:!1,targetBranch,localBranch:currentBranch,message:"Cannot reset: unpushed commits",alreadyAligned:!1,prunedBranches:[],warnings:[]}}catch{}try{gitExec(["fetch","--prune","origin"],cwd)}catch(err){return{success:!1,targetBranch,localBranch:currentBranch,message:`Fetch failed: ${err instanceof Error?err.message:String(err)}`,alreadyAligned:!1,prunedBranches:[],warnings:[]}}let headSha=gitExec(["rev-parse","HEAD"],cwd).trim(),remoteSha=gitExec(["rev-parse",`${targetBranch}`],cwd).trim();if(headSha===remoteSha)return{success:!0,targetBranch,localBranch:currentBranch,message:"Already aligned with remote",alreadyAligned:!0,prunedBranches:[],warnings:[]};try{gitExec(["checkout",currentBranch],cwd)}catch(err){return{success:!1,targetBranch,localBranch:currentBranch,message:`Checkout failed: ${err instanceof Error?err.message:String(err)}`,alreadyAligned:!1,prunedBranches:[],warnings:[]}}let resetSucceeded=!1,lastError;for(let retry=0;retry<4;retry++){if(retry>0&&process.platform==="win32")await new Promise((resolve4)=>setTimeout(resolve4,500));try{gitExec(["reset","--hard",targetBranch],cwd),resetSucceeded=!0;break}catch(err){lastError=err}}if(!resetSucceeded)return{success:!1,targetBranch,localBranch:currentBranch,message:`Reset failed: ${lastError instanceof Error?lastError.message:String(lastError)}`,alreadyAligned:!1,prunedBranches:[],warnings:[]};if(options?.pruneBranches){try{let mergedLines=gitExec(["branch","--merged",targetBranch],cwd).split(`
@@ -331,7 +331,7 @@ ${similar.map((cmd)=>` - /swarm ${cmd}`).join(`
331
331
  ${text}`}}return{text,resolved:resolved??void 0,canonicalKey:resolved?canonicalCommandKey(resolved):void 0}}var init_command_dispatch=__esm(()=>{init_registry()});function lazySet(getValues){let cached2=null,ensure=()=>{if(cached2===null)cached2=new Set(getValues());return cached2};return new Proxy({},{get(_target,prop){let set2=ensure(),value=Reflect.get(set2,prop);return typeof value==="function"?value.bind(set2):value}})}function lazyArray(getValues){let cached2=null,ensure=()=>{if(cached2===null)cached2=getValues();return cached2};return new Proxy([],{get(_target,prop){let arr=ensure(),value=Reflect.get(arr,prop);return typeof value==="function"?value.bind(arr):value}})}function classifySwarmCommandToolUse(resolved){let canonicalKey=canonicalCommandKey(resolved),args2=resolved.remainingArgs;if(!SWARM_COMMAND_TOOL_ALLOWLIST.has(canonicalKey)){if(HUMAN_ONLY_SWARM_COMMANDS.has(canonicalKey))return{allowed:!1,message:`/swarm ${canonicalKey} is a human-only command. Present the situation to the user and ask them to run \`/swarm ${canonicalKey}\` themselves (or \`bunx opencode-swarm run ${canonicalKey}\` from a terminal). `+"You MUST NOT run it yourself via Bash, swarm_command, or any other tool — "+"the runtime guardrail will block such attempts."};return{allowed:!1,message:`/swarm ${canonicalKey} is not available through the chat tool yet.
332
332
 
333
333
  Use the canonical CLI path for now: \`bunx opencode-swarm run ${canonicalKey}\`.
334
- Commands with state changes, auto-heal behavior, or subprocesses need confirmation gates before chat-tool support.`}}if(canonicalKey==="config doctor"&&args2.some((arg)=>arg==="--fix"||arg==="-f"))return{allowed:!1,message:"/swarm config doctor --fix is not available through swarm_command. Run the CLI command directly when you intend to modify config files."};if(NO_ARGS.has(canonicalKey)&&args2.length>0)return{allowed:!1,message:`/swarm ${canonicalKey} does not accept arguments through swarm_command.`};if(canonicalKey==="knowledge"){if(args2.length===0)return{allowed:!0};if(args2.length===1&&(args2[0]==="list"||args2[0]==="unactionable"))return{allowed:!0};return{allowed:!1,message:"Only `/swarm knowledge`, `/swarm knowledge list`, and `/swarm knowledge unactionable` are available through swarm_command. Knowledge migrate/quarantine/restore/retry-hardening are intentionally excluded."}}if(canonicalKey==="memory"){if(args2.length===0)return{allowed:!0};return{allowed:!1,message:"Use `/swarm memory status`, `/swarm memory pending`, `/swarm memory recall-log`, `/swarm memory stale`, `/swarm memory export`, or `/swarm memory evaluate --json` through swarm_command. Memory import, migrate, and compact are intentionally excluded from chat-tool execution."}}if(canonicalKey==="memory evaluate"){if(args2.length===0)return{allowed:!0};if(args2.length===1&&args2[0]==="--json")return{allowed:!0};return{allowed:!1,message:"Usage through swarm_command: `/swarm memory evaluate --json`. Custom fixture directories are only available through direct user command execution."}}if(canonicalKey==="sdd status"){if(args2.length===0)return{allowed:!0};if(args2.length===1&&args2[0]==="--json")return{allowed:!0};return{allowed:!1,message:"Usage through swarm_command: `/swarm sdd status` or `/swarm sdd status --json`."}}if(canonicalKey==="sdd validate"){if(args2.length===0)return{allowed:!0};if(args2.length===1&&args2[0]==="--json")return{allowed:!0};if(args2.length===2&&args2[0]==="--change"&&/^[A-Za-z0-9_.-]{1,128}$/.test(args2[1]))return{allowed:!0};return{allowed:!1,message:"Usage through swarm_command: `/swarm sdd validate`, `/swarm sdd validate --json`, or `/swarm sdd validate --change <id>`."}}if(canonicalKey==="memory pending"||canonicalKey==="memory recall-log"||canonicalKey==="memory stale"){if(args2.length===0)return{allowed:!0};if(args2.length===2&&args2[0]==="--limit"&&/^\d+$/.test(args2[1]))return{allowed:!0};return{allowed:!1,message:`Usage through swarm_command: \`/swarm ${canonicalKey}\` or \`/swarm ${canonicalKey} --limit <n>\`.`}}if(canonicalKey==="retrieve"){if(args2.length!==1||!SUMMARY_ID_PATTERN.test(args2[0]))return{allowed:!1,message:"Usage through swarm_command: `/swarm retrieve <summary-id>` with a single summary ID such as S1."}}if(canonicalKey==="benchmark")for(let i=0;i<args2.length;i++){let arg=args2[i];if(arg==="--cumulative"||arg==="--ci-gate")continue;if(arg==="--max-cost-usd"&&i+1<args2.length&&/^\d+(\.\d+)?$/.test(args2[i+1])){i++;continue}return{allowed:!1,message:"Only `--cumulative`, `--ci-gate`, and `--max-cost-usd <n>` are supported for `/swarm benchmark` through swarm_command."}}if(canonicalKey==="costs"){if(args2.length===0)return{allowed:!0};if(args2.length===1&&args2[0]==="--json")return{allowed:!0};return{allowed:!1,message:"Usage through swarm_command: `/swarm costs` or `/swarm costs --json`."}}if(canonicalKey==="show-plan"){if(args2.length>1||args2[0]&&!/^\d+$/.test(args2[0]))return{allowed:!1,message:"Usage through swarm_command: `/swarm show-plan` or `/swarm show-plan <phase-number>`."}}if(canonicalKey==="evidence"){if(args2.length>1||args2[0]&&!TASK_ID_PATTERN.test(args2[0]))return{allowed:!1,message:"Usage through swarm_command: `/swarm evidence` or `/swarm evidence <task-id>`."}}if(canonicalKey==="help"&&args2.length>2)return{allowed:!1,message:"Usage through swarm_command: `/swarm help` or `/swarm help <command>`."};return{allowed:!0}}function classifySwarmCommandChatFallbackUse(resolved){let canonicalKey=canonicalCommandKey(resolved),args2=resolved.remainingArgs;if(canonicalKey==="config doctor"&&args2.some((arg)=>arg==="--fix"||arg==="-f"))return{allowed:!1,message:"/swarm config doctor --fix is not available through chat fallback because it can modify configuration files. Run the CLI command directly when you intend to apply fixes."};if(canonicalKey==="knowledge migrate"||canonicalKey==="knowledge quarantine"||canonicalKey==="knowledge restore"||canonicalKey==="memory import"||canonicalKey==="memory migrate"||canonicalKey==="memory compact"||canonicalKey==="sdd project")return{allowed:!1,message:`/swarm ${canonicalKey} is not available through chat fallback because it mutates .swarm state. Run the CLI command directly after confirming the intended state change.`};return{allowed:!0}}var SWARM_COMMAND_TOOL_COMMANDS,SWARM_COMMAND_TOOL_ALLOWLIST,HUMAN_ONLY_SWARM_COMMANDS,NO_ARGS,SUMMARY_ID_PATTERN,TASK_ID_PATTERN;var init_tool_policy=__esm(()=>{init_command_dispatch();init_registry();SWARM_COMMAND_TOOL_COMMANDS=lazyArray(()=>VALID_COMMANDS.filter((cmd)=>{let policy=COMMAND_REGISTRY[cmd]?.toolPolicy;return policy==="agent"||policy==="human-only"}).sort()),SWARM_COMMAND_TOOL_ALLOWLIST=lazySet(()=>VALID_COMMANDS.filter((cmd)=>COMMAND_REGISTRY[cmd]?.toolPolicy==="agent")),HUMAN_ONLY_SWARM_COMMANDS=lazySet(()=>VALID_COMMANDS.filter((cmd)=>{let entry=COMMAND_REGISTRY[cmd],policy=entry?.toolPolicy;if(policy==="human-only"||policy==="restricted")return!0;if(entry?.aliasOf){let targetPolicy=COMMAND_REGISTRY[entry.aliasOf]?.toolPolicy;return targetPolicy==="human-only"||targetPolicy==="restricted"}return!1})),NO_ARGS=lazySet(()=>VALID_COMMANDS.filter((cmd)=>COMMAND_REGISTRY[cmd]?.toolNoArgs===!0)),SUMMARY_ID_PATTERN=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,TASK_ID_PATTERN=/^[A-Za-z0-9_.:-]{1,64}$/});var exports_runner_client={};__export(exports_runner_client,{probe:()=>probe,execute:()=>execute,buildDefaultPolicy:()=>buildDefaultPolicy,_resetProbeCache:()=>_resetProbeCache,_internals:()=>_internals16,RUNNER_EXIT_CODES:()=>RUNNER_EXIT_CODES});import{spawn,spawnSync as spawnSync2}from"node:child_process";import*as fs13 from"node:fs";import*as os4 from"node:os";import*as path19 from"node:path";import{fileURLToPath}from"node:url";function findRunnerBinary(){let arch=process.arch==="x64"?"x64":"arm64",platform="win32",packagePaths=[path19.resolve(_runtimeDir,"..","..","..","binaries",`win32-${arch}`,"swarm-sandbox-runner.exe"),path19.resolve(_runtimeDir,"..","..","..","..","binaries",`win32-${arch}`,"swarm-sandbox-runner.exe")];for(let p of packagePaths)try{if(fs13.existsSync(p))return p}catch{}try{let result=spawnSync2("where",["swarm-sandbox-runner.exe"],{windowsHide:!0,encoding:"utf-8",timeout:2000,stdio:["ignore","pipe","ignore"]});if(result.status===0&&result.stdout?.trim())return result.stdout.trim().split(`
334
+ Commands with state changes, auto-heal behavior, or subprocesses need confirmation gates before chat-tool support.`}}if(canonicalKey==="config doctor"&&args2.some((arg)=>arg==="--fix"||arg==="-f"))return{allowed:!1,message:"/swarm config doctor --fix is not available through swarm_command. Run the CLI command directly when you intend to modify config files."};if(NO_ARGS.has(canonicalKey)&&args2.length>0)return{allowed:!1,message:`/swarm ${canonicalKey} does not accept arguments through swarm_command.`};if(canonicalKey==="knowledge"){if(args2.length===0)return{allowed:!0};if(args2.length===1&&(args2[0]==="list"||args2[0]==="unactionable"))return{allowed:!0};return{allowed:!1,message:"Only `/swarm knowledge`, `/swarm knowledge list`, and `/swarm knowledge unactionable` are available through swarm_command. Knowledge migrate/quarantine/restore/retry-hardening are intentionally excluded."}}if(canonicalKey==="memory"){if(args2.length===0)return{allowed:!0};return{allowed:!1,message:"Use `/swarm memory status`, `/swarm memory pending`, `/swarm memory recall-log`, `/swarm memory value-log`, `/swarm memory stale`, `/swarm memory export`, or `/swarm memory evaluate --json` through swarm_command. Memory import, migrate, and compact are intentionally excluded from chat-tool execution."}}if(canonicalKey==="memory evaluate"){if(args2.length===0)return{allowed:!0};if(args2.length===1&&args2[0]==="--json")return{allowed:!0};return{allowed:!1,message:"Usage through swarm_command: `/swarm memory evaluate --json`. Custom fixture directories are only available through direct user command execution."}}if(canonicalKey==="sdd status"){if(args2.length===0)return{allowed:!0};if(args2.length===1&&args2[0]==="--json")return{allowed:!0};return{allowed:!1,message:"Usage through swarm_command: `/swarm sdd status` or `/swarm sdd status --json`."}}if(canonicalKey==="sdd validate"){if(args2.length===0)return{allowed:!0};if(args2.length===1&&args2[0]==="--json")return{allowed:!0};if(args2.length===2&&args2[0]==="--change"&&/^[A-Za-z0-9_.-]{1,128}$/.test(args2[1]))return{allowed:!0};return{allowed:!1,message:"Usage through swarm_command: `/swarm sdd validate`, `/swarm sdd validate --json`, or `/swarm sdd validate --change <id>`."}}if(canonicalKey==="memory pending"||canonicalKey==="memory recall-log"||canonicalKey==="memory value-log"||canonicalKey==="memory stale"){if(args2.length===0)return{allowed:!0};if(args2.length===2&&args2[0]==="--limit"&&/^\d+$/.test(args2[1]))return{allowed:!0};return{allowed:!1,message:`Usage through swarm_command: \`/swarm ${canonicalKey}\` or \`/swarm ${canonicalKey} --limit <n>\`.`}}if(canonicalKey==="retrieve"){if(args2.length!==1||!SUMMARY_ID_PATTERN.test(args2[0]))return{allowed:!1,message:"Usage through swarm_command: `/swarm retrieve <summary-id>` with a single summary ID such as S1."}}if(canonicalKey==="benchmark")for(let i=0;i<args2.length;i++){let arg=args2[i];if(arg==="--cumulative"||arg==="--ci-gate")continue;if(arg==="--max-cost-usd"&&i+1<args2.length&&/^\d+(\.\d+)?$/.test(args2[i+1])){i++;continue}return{allowed:!1,message:"Only `--cumulative`, `--ci-gate`, and `--max-cost-usd <n>` are supported for `/swarm benchmark` through swarm_command."}}if(canonicalKey==="costs"){if(args2.length===0)return{allowed:!0};if(args2.length===1&&args2[0]==="--json")return{allowed:!0};return{allowed:!1,message:"Usage through swarm_command: `/swarm costs` or `/swarm costs --json`."}}if(canonicalKey==="show-plan"){if(args2.length>1||args2[0]&&!/^\d+$/.test(args2[0]))return{allowed:!1,message:"Usage through swarm_command: `/swarm show-plan` or `/swarm show-plan <phase-number>`."}}if(canonicalKey==="evidence"){if(args2.length>1||args2[0]&&!TASK_ID_PATTERN.test(args2[0]))return{allowed:!1,message:"Usage through swarm_command: `/swarm evidence` or `/swarm evidence <task-id>`."}}if(canonicalKey==="help"&&args2.length>2)return{allowed:!1,message:"Usage through swarm_command: `/swarm help` or `/swarm help <command>`."};return{allowed:!0}}function classifySwarmCommandChatFallbackUse(resolved){let canonicalKey=canonicalCommandKey(resolved),args2=resolved.remainingArgs;if(canonicalKey==="config doctor"&&args2.some((arg)=>arg==="--fix"||arg==="-f"))return{allowed:!1,message:"/swarm config doctor --fix is not available through chat fallback because it can modify configuration files. Run the CLI command directly when you intend to apply fixes."};if(canonicalKey==="knowledge migrate"||canonicalKey==="knowledge quarantine"||canonicalKey==="knowledge restore"||canonicalKey==="memory import"||canonicalKey==="memory migrate"||canonicalKey==="memory compact"||canonicalKey==="sdd project")return{allowed:!1,message:`/swarm ${canonicalKey} is not available through chat fallback because it mutates .swarm state. Run the CLI command directly after confirming the intended state change.`};return{allowed:!0}}var SWARM_COMMAND_TOOL_COMMANDS,SWARM_COMMAND_TOOL_ALLOWLIST,HUMAN_ONLY_SWARM_COMMANDS,NO_ARGS,SUMMARY_ID_PATTERN,TASK_ID_PATTERN;var init_tool_policy=__esm(()=>{init_command_dispatch();init_registry();SWARM_COMMAND_TOOL_COMMANDS=lazyArray(()=>VALID_COMMANDS.filter((cmd)=>{let policy=COMMAND_REGISTRY[cmd]?.toolPolicy;return policy==="agent"||policy==="human-only"}).sort()),SWARM_COMMAND_TOOL_ALLOWLIST=lazySet(()=>VALID_COMMANDS.filter((cmd)=>COMMAND_REGISTRY[cmd]?.toolPolicy==="agent")),HUMAN_ONLY_SWARM_COMMANDS=lazySet(()=>VALID_COMMANDS.filter((cmd)=>{let entry=COMMAND_REGISTRY[cmd],policy=entry?.toolPolicy;if(policy==="human-only"||policy==="restricted")return!0;if(entry?.aliasOf){let targetPolicy=COMMAND_REGISTRY[entry.aliasOf]?.toolPolicy;return targetPolicy==="human-only"||targetPolicy==="restricted"}return!1})),NO_ARGS=lazySet(()=>VALID_COMMANDS.filter((cmd)=>COMMAND_REGISTRY[cmd]?.toolNoArgs===!0)),SUMMARY_ID_PATTERN=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,TASK_ID_PATTERN=/^[A-Za-z0-9_.:-]{1,64}$/});var exports_runner_client={};__export(exports_runner_client,{probe:()=>probe,execute:()=>execute,buildDefaultPolicy:()=>buildDefaultPolicy,_resetProbeCache:()=>_resetProbeCache,_internals:()=>_internals16,RUNNER_EXIT_CODES:()=>RUNNER_EXIT_CODES});import{spawn,spawnSync as spawnSync2}from"node:child_process";import*as fs13 from"node:fs";import*as os4 from"node:os";import*as path19 from"node:path";import{fileURLToPath}from"node:url";function findRunnerBinary(){let arch=process.arch==="x64"?"x64":"arm64",platform="win32",packagePaths=[path19.resolve(_runtimeDir,"..","..","..","binaries",`win32-${arch}`,"swarm-sandbox-runner.exe"),path19.resolve(_runtimeDir,"..","..","..","..","binaries",`win32-${arch}`,"swarm-sandbox-runner.exe")];for(let p of packagePaths)try{if(fs13.existsSync(p))return p}catch{}try{let result=spawnSync2("where",["swarm-sandbox-runner.exe"],{windowsHide:!0,encoding:"utf-8",timeout:2000,stdio:["ignore","pipe","ignore"]});if(result.status===0&&result.stdout?.trim())return result.stdout.trim().split(`
335
335
  `)[0]?.trim()??null}catch{}return null}function probe(){if(_cachedProbe!==void 0)return _cachedProbe;if(process.platform!=="win32")return _cachedProbe={available:!1,mode:"none",capabilities:null,error:"not Windows"},_cachedProbe;let binary=_internals16.findRunnerBinary();if(!binary)return _cachedProbe={available:!1,mode:"none",capabilities:null,error:"runner binary not found"},warn("Sandbox runner binary not found — degrading to weak sandbox"),_cachedProbe;try{let result=_internals16.spawnRunner(binary,["--probe"],{windowsHide:!0,encoding:"utf-8",timeout:2000,stdio:["ignore","pipe","pipe"],cwd:os4.tmpdir()});if(result.error)return _cachedProbe={available:!1,mode:"none",capabilities:null,error:`probe spawn error: ${result.error.code??result.error.message}`},warn(`Sandbox runner probe failed: ${_cachedProbe.error}`),_cachedProbe;if(result.status!==0)return _cachedProbe={available:!1,mode:"none",capabilities:null,error:`probe exited with code ${result.status}`},warn(`Sandbox runner probe failed: ${_cachedProbe.error}`),_cachedProbe;let capabilities=JSON.parse(result.stdout?.trim()??"{}"),mode="none";if(capabilities.app_container_available)mode="app-container";else if(capabilities.restricted_token_available)mode="restricted-token";return _cachedProbe={available:mode!=="none",mode,capabilities},_cachedProbe}catch(err){let msg=err instanceof Error?err.message:String(err);return _cachedProbe={available:!1,mode:"none",capabilities:null,error:`probe threw: ${msg}`},warn(`Sandbox runner probe threw: ${msg}`),_cachedProbe}}async function execute(command,policy,mode="auto"){let binary=_internals16.findRunnerBinary();if(!binary)throw Error("runner binary not found");let policyJson=JSON.stringify(policy),args2=["--policy-stdin","--mode",mode,"--",...command];return new Promise((resolve14,reject)=>{let proc,timeout=setTimeout(()=>{proc?.kill(),reject(Error("runner execution timeout"))},policy.wall_clock_timeout_ms+5000),unref=timeout.unref;if(typeof unref==="function")unref.call(timeout);try{proc=_internals16.spawnAsync(binary,args2,{windowsHide:!0,stdio:["pipe","pipe","pipe"],cwd:policy.workspace_roots[0]??os4.tmpdir()})}catch(err){clearTimeout(timeout),reject(err);return}proc.stdin?.write(policyJson),proc.stdin?.end();let stdout="",stderr="",events=[];proc.stdout?.on("data",(chunk)=>{stdout+=chunk.toString()}),proc.stderr?.on("data",(chunk)=>{let lines=chunk.toString().split(`
336
336
  `);for(let line of lines){let trimmed=line.trim();if(!trimmed)continue;try{let event=JSON.parse(trimmed);if(event.type){events.push(event);continue}}catch{}stderr+=`${trimmed}
337
337
  `}}),proc.on("error",(err)=>{clearTimeout(timeout),reject(err)}),proc.on("close",(code)=>{clearTimeout(timeout);let runnerMode=events.find((e)=>e.type==="start")?.mode??mode;resolve14({exitCode:code??1,stdout,stderr,events,mode:runnerMode})})})}function _resetProbeCache(){_cachedProbe=void 0}function buildDefaultPolicy(workspaceRoot,runId){let id=runId??`swarm-${crypto.randomUUID?.()??Date.now()}`,appData=process.env.LOCALAPPDATA??path19.join(os4.homedir(),"AppData","Local"),tempRoot=path19.join(appData,"opencode-swarm","sandbox",id,"temp");return{schema_version:1,run_id:id,workspace_roots:[workspaceRoot],writable_roots:[workspaceRoot],read_only_subpaths:[".git",".codex",".agents",".swarm"],temp_root:tempRoot,temp_cap_bytes:524288000,memory_cap_bytes:2147483648,child_process_cap:16,wall_clock_timeout_ms:600000,network_mode:"off",env_allowlist:["PATH","TEMP","TMP","USERPROFILE","SYSTEMROOT"],env_overrides:{HTTP_PROXY:"http://127.0.0.1:1",HTTPS_PROXY:"http://127.0.0.1:1"},path_stubs:["ssh.exe","curl.exe","wget.exe","scp.exe","sftp.exe"],private_desktop:!0,deny_alternate_data_streams:!0,deny_unc_paths:!0,deny_device_paths:!0,deny_symlink_egress:!0}}var _runtimeDir,RUNNER_EXIT_CODES,_cachedProbe,_internals16;var init_runner_client=__esm(()=>{init_logger();_runtimeDir=fileURLToPath(new URL(".",import.meta.url)),RUNNER_EXIT_CODES={SUCCESS:0,CHILD_NON_ZERO:1,POLICY_VIOLATION:64,QUOTA_EXCEEDED:65,WALL_CLOCK_TIMEOUT:66,LAUNCHER_MISCONFIG:67,OS_API_FAILURE:68,PROBE_FAILED:69},_internals16={findRunnerBinary,spawnRunner:spawnSync2,spawnAsync:spawn}});var exports_capability_probe={};__export(exports_capability_probe,{isWindowsSandboxAvailable:()=>isWindowsSandboxAvailable,isSandboxExecAvailable:()=>isSandboxExecAvailable,isBubblewrapAvailable:()=>isBubblewrapAvailable,SandboxCapabilityProbe:()=>SandboxCapabilityProbe});import{execFile,spawnSync as spawnSync3}from"node:child_process";import*as os5 from"node:os";function withProbeTimeout(cmd,args2,ms){return new Promise((resolve14,reject)=>{let controller=new AbortController,timer=setTimeout(()=>{controller.abort(),proc?.kill()},ms),unref=timer.unref;if(typeof unref==="function")unref.call(timer);let proc;try{proc=execFile(cmd,args2,{signal:controller.signal,timeout:ms,windowsHide:!0,cwd:os5.tmpdir()},(error49,stdout,_stderr)=>{if(clearTimeout(timer),error49){let exc=error49;if(exc.code==="ENOENT"||exc.code==="ENOTFOUND")reject(Error("binary not found"));else reject(error49);return}resolve14(stdout?.trim()??"")})}catch(spawnError){clearTimeout(timer),reject(spawnError)}})}async function probeLinux(){try{if((await withProbeTimeout("bwrap",["--version"],2000)).length>0)return{status:"enabled",mechanism:"Bubblewrap",platform:"linux"};return{status:"disabled",mechanism:"Bubblewrap",platform:"linux",error:"binary returned empty version"}}catch(err){let msg=err instanceof Error?err.message:String(err);if(msg==="binary not found")return{status:"unsupported",mechanism:"Bubblewrap",platform:"linux",error:msg};return{status:"disabled",mechanism:"Bubblewrap",platform:"linux",error:msg}}}async function probeMacOS(){try{if((await withProbeTimeout("sandbox-exec",["--version"],2000)).length>0)return{status:"enabled",mechanism:"sandbox-exec",platform:"darwin"};return{status:"disabled",mechanism:"sandbox-exec",platform:"darwin",error:"binary returned empty version"}}catch(err){let msg=err instanceof Error?err.message:String(err);if(msg==="binary not found")return{status:"unsupported",mechanism:"sandbox-exec",platform:"darwin",error:msg};return{status:"disabled",mechanism:"sandbox-exec",platform:"darwin",error:msg}}}function probeWindows(){try{let{probe:runnerProbe}=(init_runner_client(),__toCommonJS(exports_runner_client)),result=runnerProbe();if(result.available)return{status:"enabled",platform:"win32",mechanism:`native-runner/${result.mode}`}}catch{}try{let result=spawnSync3("cmd",["/c","echo","ok"],{windowsHide:!0,encoding:"utf-8",timeout:5000,stdio:["ignore","pipe","ignore"]});if(result.error)return{status:"disabled",platform:"win32",mechanism:"PowerShell wrapper",error:`cmd.exe probe failed: ${result.error.code}`};return result.status===0?{status:"enabled",platform:"win32",mechanism:"PowerShell wrapper"}:{status:"disabled",platform:"win32",mechanism:"PowerShell wrapper",error:"cmd.exe probe returned non-zero"}}catch(err){return{status:"disabled",platform:"win32",mechanism:"PowerShell wrapper",error:String(err)}}}function isBubblewrapAvailable(){return _cached?.status==="enabled"&&_cached?.platform==="linux"}function isSandboxExecAvailable(){return _cached?.status==="enabled"&&_cached?.platform==="darwin"}function isWindowsSandboxAvailable(){return _cached?.status==="enabled"&&_cached?.platform==="win32"}class SandboxCapabilityProbe{async detect(){if(_cached!==void 0)return _cached;let platform=process.platform;switch(platform){case"linux":_cached=await probeLinux();break;case"darwin":_cached=await probeMacOS();break;case"win32":_cached=probeWindows();break;default:_cached={status:"unsupported",mechanism:"unknown",platform,error:`unsupported platform: ${platform}`}}return _cached}}var _cached;var init_capability_probe=()=>{};import{spawnSync as spawnSync4}from"node:child_process";function probeBwrap(){try{let result=spawnSync4("bwrap",["--version"],{windowsHide:!0,encoding:"utf-8",timeout:5000,stdio:["ignore","pipe","ignore"]});if(result.error){let code=result.error.code;if(code&&BWRAP_UNAVAILABLE_CODES.has(code))return warn(`Sandbox disabled: bwrap error (${code}). Falling through to tool-layer enforcement.`),!1;return warn(`Sandbox disabled: bwrap spawn error (${result.error.message}). Falling through to tool-layer enforcement.`),!1}return result.status===BWRAP_VERSION_EXIT&&result.stdout.trim().length>0}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`Sandbox disabled: probe threw (${message}). Falling through to tool-layer enforcement.`),!1}}function shellEscape(s){return s.replace(/'/g,"'\\''")}class BubblewrapSandboxExecutor{mechanism="Bubblewrap";_scopePaths;_tempDir;_available;_disabledReason;constructor(scopePaths=[],tempDir){this._scopePaths=scopePaths,this._tempDir=tempDir,this._available=!1,this._disabledReason=null;try{if(!_internals17.probeBwrap())this._disabledReason="bwrap not available or not functional",warn(`Sandbox disabled: ${this._disabledReason}. Falling through to tool-layer enforcement.`);else this._available=!0}catch(err){let message=err instanceof Error?err.message:String(err);this._disabledReason=`constructor threw: ${message}`,this._available=!1,warn(`Sandbox disabled: ${this._disabledReason}. Falling through to tool-layer enforcement.`)}}isAvailable(){return this._available}disable(reason){this._available=!1,this._disabledReason=reason,warn(`Sandbox disabled: ${reason}. Falling through to tool-layer enforcement.`)}wrapCommand(command,scopePaths,tempDir){if(!this._available)throw new SandboxError("Sandbox not available","SANDBOX_UNAVAILABLE");let temp=tempDir??this._tempDir??"/tmp";return`bwrap ${["--unshare-user","--unshare-net","--unshare-ipc","--die-with-parent","--new-session","--cap-drop","ALL",...[...this._scopePaths,...scopePaths].flatMap((p)=>["--bind",`'${shellEscape(p)}'`,`'${shellEscape(p)}'`]),"--dev","/dev","--size","500M","--tmpfs",`'${shellEscape(temp)}'`,"--ro-bind","/etc","/etc","--ro-bind","/usr","/usr","--ro-bind","/lib","/lib","--ro-bind","/lib64","/lib64","--proc","/proc","--unshare-pid","--","bash","-c",`'${shellEscape(command)}'`].join(" ")}`}getEnvOverrides(){return{}}}var BWRAP_VERSION_EXIT=0,BWRAP_UNAVAILABLE_CODES,_internals17;var init_bubblewrap_executor=__esm(()=>{init_logger();init_executor();BWRAP_UNAVAILABLE_CODES=new Set(["ENOENT","EACCES","ENOSPC"]);_internals17={probeBwrap}});var exports_bubblewrap={};__export(exports_bubblewrap,{BubblewrapSandboxExecutor:()=>BubblewrapSandboxExecutor});var init_bubblewrap=__esm(()=>{init_bubblewrap_executor()});import{spawnSync as spawnSync5}from"node:child_process";import{mkdtempSync,writeFileSync as writeFileSync6}from"node:fs";import*as os6 from"node:os";import*as path20 from"node:path";function probeSandboxExec(){try{let result=spawnSync5("sandbox-exec",["--version"],{windowsHide:!0,encoding:"utf-8",timeout:5000,stdio:["ignore","pipe","ignore"]});if(result.error){let code=result.error.code;if(code&&SANDBOX_UNAVAILABLE_CODES.has(code))return warn(`Sandbox disabled: sandbox-exec error (${code}). Falling through to tool-layer enforcement.`),!1;return warn(`Sandbox disabled: spawn error (${result.error.message}). Falling through to tool-layer enforcement.`),!1}return result.status===0}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`Sandbox disabled: probe threw (${message}). Falling through to tool-layer enforcement.`),!1}}function shellEscape2(s){return s.replace(/'/g,"'\\''")}function sbplEscapePath(path21){return path21.split("").filter((ch)=>{let cp=ch.codePointAt(0);return cp>=32&&cp!==127}).join("").replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}function buildSandboxProfile(scopePaths,tempDir){let rwPaths=[...scopePaths];if(tempDir)rwPaths.push(tempDir);return`(version 1)
@@ -488,7 +488,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
488
488
  `)){if(out.length>=max)break;let trimmed=line.trim();if(!trimmed)continue;try{out.push(JSON.parse(trimmed))}catch{warn(`[knowledge-events] Skipping corrupted JSONL line in ${filePath}: ${trimmed.slice(0,80)}`)}}return out}async function readHiveKnowledgeEvents(){let filePath=resolveHiveEventsPath2();if(!existsSync21(filePath))return[];let content=await readFile6(filePath,"utf-8");return parseEventLines(content.split(`
489
489
  `),filePath)}async function readLegacyApplicationRecords(directory){let filePath=resolveLegacyApplicationLogPath(directory);if(!existsSync21(filePath))return[];let content=await readFile6(filePath,"utf-8"),out=[];for(let line of content.split(`
490
490
  `)){let trimmed=line.trim();if(!trimmed)continue;try{out.push(JSON.parse(trimmed))}catch{warn(`[knowledge-events] Skipping corrupted JSONL line in ${filePath}: ${trimmed.slice(0,80)}`)}}return out}function emptyRollup(){return{shown_count:0,acknowledged_count:0,applied_explicit_count:0,ignored_count:0,violated_count:0,contradicted_count:0,n_a_count:0,succeeded_after_shown_count:0,failed_after_shown_count:0,partial_after_shown_count:0,violation_timestamps:[]}}function cloneRollup(input){return{...emptyRollup(),...input,violation_timestamps:[...input.violation_timestamps??[]]}}function cloneRollupMap(input){let out=new Map;for(let[id,rollup]of input)out.set(id,cloneRollup(rollup));return out}function normalizeRollupTimestamps(rollup){if(rollup.violation_timestamps.length>1)rollup.violation_timestamps.sort((a,b)=>a<b?1:a>b?-1:0);if(rollup.violation_timestamps.length>MAX_VIOLATION_TIMESTAMPS)rollup.violation_timestamps=rollup.violation_timestamps.slice(0,MAX_VIOLATION_TIMESTAMPS);return rollup}function mergeRollupInto(target,source){if(target.shown_count+=source.shown_count??0,target.acknowledged_count+=source.acknowledged_count??0,target.applied_explicit_count+=source.applied_explicit_count??0,target.ignored_count+=source.ignored_count??0,target.violated_count+=source.violated_count??0,target.contradicted_count+=source.contradicted_count??0,target.n_a_count+=source.n_a_count??0,target.succeeded_after_shown_count+=source.succeeded_after_shown_count??0,target.failed_after_shown_count+=source.failed_after_shown_count??0,target.partial_after_shown_count+=source.partial_after_shown_count??0,source.last_applied_at)target.last_applied_at=maxIso(target.last_applied_at,source.last_applied_at);if(source.last_acknowledged_at)target.last_acknowledged_at=maxIso(target.last_acknowledged_at,source.last_acknowledged_at);target.violation_timestamps.push(...source.violation_timestamps??[]),normalizeRollupTimestamps(target)}function get(map3,id){let r=map3.get(id);if(!r)r=emptyRollup(),map3.set(id,r);return r}function maxIso(current,candidate){if(!current)return candidate;return candidate>current?candidate:current}async function readCounterBaseline(directory){let filePath=resolveKnowledgeCounterBaselinePath(directory);if(!existsSync21(filePath))return new Map;let raw;try{raw=JSON.parse(await readFile6(filePath,"utf-8"))}catch(err){return warn(`[knowledge-events] corrupted counter baseline at ${filePath}; ignoring folded baseline and replaying live events only: ${err instanceof Error?err.message:String(err)}`),new Map}let map3=new Map;for(let[id,rollup]of Object.entries(raw))map3.set(id,normalizeRollupTimestamps(cloneRollup(rollup)));return map3}async function writeCounterBaseline(directory,baseline){let filePath=resolveKnowledgeCounterBaselinePath(directory),out={};for(let[id,rollup]of[...baseline.entries()].sort(([a],[b])=>a.localeCompare(b)))out[id]=normalizeRollupTimestamps(cloneRollup(rollup));await atomicWriteFile(filePath,`${JSON.stringify(out,null,2)}
491
- `)}async function statCacheKey(filePath){try{let fileStat=await stat6(filePath);return`${fileStat.mtimeMs}:${fileStat.ctimeMs}:${fileStat.size}`}catch(err){if(err?.code==="ENOENT")return"missing";throw err}}async function buildCounterRollupCacheKey(directory){let[eventsKey,legacyKey,baselineKey]=await Promise.all([statCacheKey(resolveKnowledgeEventsPath(directory)),statCacheKey(resolveLegacyApplicationLogPath(directory)),statCacheKey(resolveKnowledgeCounterBaselinePath(directory))]);return`${eventsKey}|${legacyKey}|${baselineKey}`}function setCounterRollupCache(directory,key,rollups){if(counterRollupCache.has(directory))counterRollupCache.delete(directory);counterRollupCache.set(directory,{key,rollups:cloneRollupMap(rollups)});while(counterRollupCache.size>MAX_COUNTER_ROLLUP_CACHE_DIRS){let oldestKey=counterRollupCache.keys().next().value;if(oldestKey===void 0)break;counterRollupCache.delete(oldestKey)}}function parseEventLines(lines,filePath){let out=[];for(let line of lines){let trimmed=line.trim();if(!trimmed)continue;try{out.push(JSON.parse(trimmed))}catch{warn(`[knowledge-events] Skipping corrupted JSONL line in ${filePath}: ${trimmed.slice(0,80)}`)}}return out}async function foldEvictedEventsIntoBaseline(directory,evictedLines,filePath){let evictedEvents=parseEventLines(evictedLines,filePath);if(evictedEvents.length===0)return;let baseline=await readCounterBaseline(directory);for(let[id,rollup]of recomputeCounters(evictedEvents))mergeRollupInto(get(baseline,id),rollup);await writeCounterBaseline(directory,baseline)}function recomputeCounters(events,legacyRecords=[],baseline=new Map){let map3=new Map,retrievedIds=new Set;for(let[id,rollup]of baseline)if(map3.set(id,cloneRollup(rollup)),(rollup.shown_count??0)>0)retrievedIds.add(id);for(let e of events)switch(e.type){case"retrieved":{for(let id of e.result_ids)retrievedIds.add(id),get(map3,id).shown_count+=1;break}case"acknowledged":{let r=get(map3,e.knowledge_id);r.acknowledged_count+=1,r.last_acknowledged_at=maxIso(r.last_acknowledged_at,e.timestamp);break}case"applied":{let r=get(map3,e.knowledge_id);r.applied_explicit_count+=1,r.last_applied_at=maxIso(r.last_applied_at,e.timestamp);break}case"ignored":get(map3,e.knowledge_id).ignored_count+=1;break;case"violated":{let r=get(map3,e.knowledge_id);r.violated_count+=1,r.violation_timestamps.push(e.timestamp);break}case"contradicted":get(map3,e.knowledge_id).contradicted_count+=1;break;case"n_a":get(map3,e.knowledge_id).n_a_count+=1;break;case"outcome":{if(!e.knowledge_id)break;let r=get(map3,e.knowledge_id);if(e.outcome==="success")r.succeeded_after_shown_count+=1;else if(e.outcome==="failure")r.failed_after_shown_count+=1;else if(e.outcome==="partial")r.partial_after_shown_count+=1;break}}for(let rec of legacyRecords){let r=get(map3,rec.knowledgeId);switch(rec.result){case"shown":if(!retrievedIds.has(rec.knowledgeId))r.shown_count+=1;break;case"acknowledged":r.acknowledged_count+=1,r.last_acknowledged_at=maxIso(r.last_acknowledged_at,rec.timestamp);break;case"applied":r.applied_explicit_count+=1,r.last_applied_at=maxIso(r.last_applied_at,rec.timestamp);break;case"ignored":r.ignored_count+=1;break;case"violated":r.violated_count+=1,r.violation_timestamps.push(rec.timestamp);break}}for(let r of map3.values())normalizeRollupTimestamps(r);return map3}function countViolationsInWindow(timestamps,windowDays,now=new Date){let cutoff=now.getTime()-windowDays*24*60*60*1000,count=0;for(let ts of timestamps){let t=Date.parse(ts);if(!Number.isNaN(t)&&t>=cutoff)count+=1}return count}async function countEntryViolationsInWindow(directory,entryId,windowDays,now=new Date){try{let cutoff=now.getTime()-windowDays*24*60*60*1000,[events,legacyRecords]=await Promise.all([readKnowledgeEvents(directory),readLegacyApplicationRecords(directory)]),count=0;for(let e of events){if(e.type!=="violated"||e.knowledge_id!==entryId)continue;let t=Date.parse(e.timestamp);if(!Number.isNaN(t)&&t>=cutoff)count+=1}for(let rec of legacyRecords){if(rec.result!=="violated"||rec.knowledgeId!==entryId)continue;let t=Date.parse(rec.timestamp);if(!Number.isNaN(t)&&t>=cutoff)count+=1}return count}catch{return 0}}async function readKnowledgeCounterRollups(directory){try{let cacheKey=await buildCounterRollupCacheKey(directory),cached3=counterRollupCache.get(directory);if(cached3?.key===cacheKey)return counterRollupCache.delete(directory),counterRollupCache.set(directory,cached3),cloneRollupMap(cached3.rollups);let[events,legacyRecords,baseline]=await Promise.all([readKnowledgeEvents(directory),readLegacyApplicationRecords(directory),readCounterBaseline(directory)]),rollups=recomputeCounters(events,legacyRecords,baseline);return setCounterRollupCache(directory,cacheKey,rollups),cloneRollupMap(rollups)}catch(err){return warn(`[knowledge-events] readKnowledgeCounterRollups failed: ${err instanceof Error?err.message:String(err)}`),new Map}}function effectiveRetrievalOutcomes(stored,rollup){let base=stored??{applied_count:0,succeeded_after_count:0,failed_after_count:0};if(!rollup)return base;let{n_a_count:_na,...rollupWithoutNa}=rollup;return{...base,...rollupWithoutNa,succeeded_after_shown_count:(base.succeeded_after_shown_count??0)+(rollup.succeeded_after_shown_count??0),failed_after_shown_count:(base.failed_after_shown_count??0)+(rollup.failed_after_shown_count??0)}}async function applyKnowledgeVerdictFeedback(directory,options){try{let actionable=(await readKnowledgeEvents(directory)).filter((e)=>{if(e.type!=="applied"&&e.type!=="violated"&&e.type!=="ignored")return!1;if(options?.sinceTimestamp&&e.timestamp<=options.sinceTimestamp)return!1;return!0});if(actionable.length===0)return{processed:0,bumps:0};let groups=new Map;for(let event of actionable){let kid=event.knowledge_id;if(!kid)continue;let g=groups.get(kid)??{applied:0,violated:0,ignored:0};if(event.type==="applied")g.applied++;else if(event.type==="violated")g.violated++;else if(event.type==="ignored")g.ignored++;groups.set(kid,g)}let deltas=[];for(let[id,counts]of groups){let positives=counts.applied,negatives=counts.violated+counts.ignored;if(positives===0&&negatives===0)continue;let delta=positives>negatives?VERDICT_CONFIDENCE_BOOST:-VERDICT_CONFIDENCE_DECAY;deltas.push({id,delta})}if(deltas.length>0){let{bumpKnowledgeConfidenceBatch:bumpKnowledgeConfidenceBatch2}=await Promise.resolve().then(() => (init_knowledge_store(),exports_knowledge_store));await bumpKnowledgeConfidenceBatch2(directory,deltas)}return{processed:groups.size,bumps:deltas.length}}catch(err){return warn(`[knowledge-events] applyKnowledgeVerdictFeedback failed (fail-open): ${err instanceof Error?err.message:String(err)}`),{processed:0,bumps:0}}}var import_proper_lockfile4,KNOWLEDGE_EVENT_SCHEMA_VERSION=1,MAX_EVENT_LOG_ENTRIES=5000,counterRollupCache,MAX_COUNTER_ROLLUP_CACHE_DIRS=32,RECEIPT_EVENT_TYPES,MAX_VIOLATION_TIMESTAMPS=10,VERDICT_CONFIDENCE_BOOST=0.03,VERDICT_CONFIDENCE_DECAY=0.05,_internals27;var init_knowledge_events=__esm(()=>{init_task_file();init_logger();init_knowledge_link();import_proper_lockfile4=__toESM(require_proper_lockfile(),1),counterRollupCache=new Map,RECEIPT_EVENT_TYPES=new Set(["acknowledged","applied","ignored","contradicted","violated","n_a","override"]);_internals27={resolveKnowledgeEventsPath,resolveKnowledgeCounterBaselinePath,appendKnowledgeEvent,recordKnowledgeEvent,readKnowledgeEvents,readCounterBaseline,readLegacyApplicationRecords,readKnowledgeCounterRollups,effectiveRetrievalOutcomes,recomputeCounters,applyKnowledgeVerdictFeedback,newTraceId,newEventId,resolveHiveEventsPath:resolveHiveEventsPath2,appendHiveKnowledgeEvent,recordHiveKnowledgeEvent,readHiveKnowledgeEvents}});var READ_ONLY_LANE_GUIDANCE=`## READ-ONLY ADVISORY LANE CONTEXT
491
+ `)}async function statCacheKey(filePath){try{let fileStat=await stat6(filePath);return`${fileStat.mtimeMs}:${fileStat.ctimeMs}:${fileStat.size}`}catch(err){if(err?.code==="ENOENT")return"missing";throw err}}async function buildCounterRollupCacheKey(directory){let[eventsKey,legacyKey,baselineKey]=await Promise.all([statCacheKey(resolveKnowledgeEventsPath(directory)),statCacheKey(resolveLegacyApplicationLogPath(directory)),statCacheKey(resolveKnowledgeCounterBaselinePath(directory))]);return`${eventsKey}|${legacyKey}|${baselineKey}`}function setCounterRollupCache(directory,key,rollups){if(counterRollupCache.has(directory))counterRollupCache.delete(directory);counterRollupCache.set(directory,{key,rollups:cloneRollupMap(rollups)});while(counterRollupCache.size>MAX_COUNTER_ROLLUP_CACHE_DIRS){let oldestKey=counterRollupCache.keys().next().value;if(oldestKey===void 0)break;counterRollupCache.delete(oldestKey)}}function parseEventLines(lines,filePath){let out=[];for(let line of lines){let trimmed=line.trim();if(!trimmed)continue;try{out.push(JSON.parse(trimmed))}catch{warn(`[knowledge-events] Skipping corrupted JSONL line in ${filePath}: ${trimmed.slice(0,80)}`)}}return out}async function foldEvictedEventsIntoBaseline(directory,evictedLines,filePath){let evictedEvents=parseEventLines(evictedLines,filePath);if(evictedEvents.length===0)return;let baseline=await readCounterBaseline(directory);for(let[id,rollup]of recomputeCounters(evictedEvents))mergeRollupInto(get(baseline,id),rollup);await writeCounterBaseline(directory,baseline)}function recomputeCounters(events,legacyRecords=[],baseline=new Map){let map3=new Map,retrievedIds=new Set;for(let[id,rollup]of baseline)if(map3.set(id,cloneRollup(rollup)),(rollup.shown_count??0)>0)retrievedIds.add(id);for(let e of events)switch(e.type){case"retrieved":{for(let id of e.result_ids)retrievedIds.add(id),get(map3,id).shown_count+=1;break}case"acknowledged":{let r=get(map3,e.knowledge_id);r.acknowledged_count+=1,r.last_acknowledged_at=maxIso(r.last_acknowledged_at,e.timestamp);break}case"applied":{let r=get(map3,e.knowledge_id);r.applied_explicit_count+=1,r.last_applied_at=maxIso(r.last_applied_at,e.timestamp);break}case"ignored":get(map3,e.knowledge_id).ignored_count+=1;break;case"violated":{let r=get(map3,e.knowledge_id);r.violated_count+=1,r.violation_timestamps.push(e.timestamp);break}case"contradicted":get(map3,e.knowledge_id).contradicted_count+=1;break;case"n_a":get(map3,e.knowledge_id).n_a_count+=1;break;case"outcome":{if(!e.knowledge_id)break;let r=get(map3,e.knowledge_id);if(e.outcome==="success")r.succeeded_after_shown_count+=1;else if(e.outcome==="failure")r.failed_after_shown_count+=1;else if(e.outcome==="partial")r.partial_after_shown_count+=1;break}}for(let rec of legacyRecords){let r=get(map3,rec.knowledgeId);switch(rec.result){case"shown":if(!retrievedIds.has(rec.knowledgeId))r.shown_count+=1;break;case"acknowledged":r.acknowledged_count+=1,r.last_acknowledged_at=maxIso(r.last_acknowledged_at,rec.timestamp);break;case"applied":r.applied_explicit_count+=1,r.last_applied_at=maxIso(r.last_applied_at,rec.timestamp);break;case"ignored":r.ignored_count+=1;break;case"violated":r.violated_count+=1,r.violation_timestamps.push(rec.timestamp);break}}for(let r of map3.values())normalizeRollupTimestamps(r);return map3}function countViolationsInWindow(timestamps,windowDays,now=new Date){let cutoff=now.getTime()-windowDays*24*60*60*1000,count=0;for(let ts of timestamps){let t=Date.parse(ts);if(!Number.isNaN(t)&&t>=cutoff)count+=1}return count}async function countEntryViolationsInWindow(directory,entryId,windowDays,now=new Date){try{let cutoff=now.getTime()-windowDays*24*60*60*1000,[events,legacyRecords]=await Promise.all([readKnowledgeEvents(directory),readLegacyApplicationRecords(directory)]),count=0;for(let e of events){if(e.type!=="violated"||e.knowledge_id!==entryId)continue;let t=Date.parse(e.timestamp);if(!Number.isNaN(t)&&t>=cutoff)count+=1}for(let rec of legacyRecords){if(rec.result!=="violated"||rec.knowledgeId!==entryId)continue;let t=Date.parse(rec.timestamp);if(!Number.isNaN(t)&&t>=cutoff)count+=1}return count}catch{return 0}}async function readKnowledgeCounterRollups(directory){try{let cacheKey=await buildCounterRollupCacheKey(directory),cached3=counterRollupCache.get(directory);if(cached3?.key===cacheKey)return counterRollupCache.delete(directory),counterRollupCache.set(directory,cached3),cloneRollupMap(cached3.rollups);let[events,legacyRecords,baseline]=await Promise.all([readKnowledgeEvents(directory),readLegacyApplicationRecords(directory),readCounterBaseline(directory)]),rollups=recomputeCounters(events,legacyRecords,baseline);return setCounterRollupCache(directory,cacheKey,rollups),cloneRollupMap(rollups)}catch(err){return warn(`[knowledge-events] readKnowledgeCounterRollups failed: ${err instanceof Error?err.message:String(err)}`),new Map}}function effectiveRetrievalOutcomes(stored,rollup){let base=stored??{applied_count:0,succeeded_after_count:0,failed_after_count:0};if(!rollup)return base;let{n_a_count:_na,...rollupWithoutNa}=rollup;return{...base,...rollupWithoutNa,succeeded_after_shown_count:(base.succeeded_after_shown_count??0)+(rollup.succeeded_after_shown_count??0),failed_after_shown_count:(base.failed_after_shown_count??0)+(rollup.failed_after_shown_count??0)}}async function applyKnowledgeVerdictFeedback(directory,options){try{let events=await readKnowledgeEvents(directory),markerIndex=options?.sinceTimestamp&&options.sinceEventId?events.findIndex((e)=>e.timestamp===options.sinceTimestamp&&e.event_id===options.sinceEventId):-1,actionable=events.filter((e,index)=>{if(e.type!=="applied"&&e.type!=="violated"&&e.type!=="ignored")return!1;if(options?.sinceTimestamp&&e.timestamp<options.sinceTimestamp)return!1;if(options?.sinceTimestamp&&e.timestamp===options.sinceTimestamp){if(!options.sinceEventId)return!1;if(markerIndex<0)return!1;return index>markerIndex}return!0});if(actionable.length===0)return{processed:0,bumps:0};let groups=new Map,lastProcessedTimestamp,lastProcessedEventId;for(let event of actionable){if(typeof event.timestamp==="string"&&(!lastProcessedTimestamp||event.timestamp>=lastProcessedTimestamp))lastProcessedTimestamp=event.timestamp,lastProcessedEventId=event.event_id;let kid=event.knowledge_id;if(!kid)continue;let g=groups.get(kid)??{applied:0,violated:0,ignored:0};if(event.type==="applied")g.applied++;else if(event.type==="violated")g.violated++;else if(event.type==="ignored")g.ignored++;groups.set(kid,g)}let deltas=[];for(let[id,counts]of groups){let positives=counts.applied,negatives=counts.violated+counts.ignored;if(positives===0&&negatives===0)continue;let delta=positives>negatives?VERDICT_CONFIDENCE_BOOST:-VERDICT_CONFIDENCE_DECAY;deltas.push({id,delta})}if(deltas.length>0){let{bumpKnowledgeConfidenceBatch:bumpKnowledgeConfidenceBatch2}=await Promise.resolve().then(() => (init_knowledge_store(),exports_knowledge_store));await bumpKnowledgeConfidenceBatch2(directory,deltas)}return{processed:groups.size,bumps:deltas.length,lastProcessedTimestamp,lastProcessedEventId}}catch(err){return warn(`[knowledge-events] applyKnowledgeVerdictFeedback failed (fail-open): ${err instanceof Error?err.message:String(err)}`),{processed:0,bumps:0}}}var import_proper_lockfile4,KNOWLEDGE_EVENT_SCHEMA_VERSION=1,MAX_EVENT_LOG_ENTRIES=5000,counterRollupCache,MAX_COUNTER_ROLLUP_CACHE_DIRS=32,RECEIPT_EVENT_TYPES,MAX_VIOLATION_TIMESTAMPS=10,VERDICT_CONFIDENCE_BOOST=0.03,VERDICT_CONFIDENCE_DECAY=0.05,_internals27;var init_knowledge_events=__esm(()=>{init_task_file();init_logger();init_knowledge_link();import_proper_lockfile4=__toESM(require_proper_lockfile(),1),counterRollupCache=new Map,RECEIPT_EVENT_TYPES=new Set(["acknowledged","applied","ignored","contradicted","violated","n_a","override"]);_internals27={resolveKnowledgeEventsPath,resolveKnowledgeCounterBaselinePath,appendKnowledgeEvent,recordKnowledgeEvent,readKnowledgeEvents,readCounterBaseline,readLegacyApplicationRecords,readKnowledgeCounterRollups,effectiveRetrievalOutcomes,recomputeCounters,applyKnowledgeVerdictFeedback,newTraceId,newEventId,resolveHiveEventsPath:resolveHiveEventsPath2,appendHiveKnowledgeEvent,recordHiveKnowledgeEvent,readHiveKnowledgeEvents}});var READ_ONLY_LANE_GUIDANCE=`## READ-ONLY ADVISORY LANE CONTEXT
492
492
 
493
493
  You may be invoked through dispatch_lanes or dispatch_lanes_async as a read-only advisory lane. In that context, your job is to inspect, reason, and report only.
494
494
 
@@ -1381,12 +1381,12 @@ Flags:
1381
1381
  enforced) or checkpoint (pause at phase gates)
1382
1382
  --depth <name> standard (default) or exhaustive (wider exploration)
1383
1383
  --resume resume the existing loop run from durable state in
1384
- .swarm/loop/ instead of starting a new objective`;var init_loop=__esm(()=>{DEPTHS2=new Set(["standard","exhaustive"]),AUTONOMY_LEVELS=new Set(["checkpoint","auto"]);_internals54={readLatestLoopState}});function resolveMemoryConfig(input){return{...DEFAULT_MEMORY_CONFIG,...input??{},sqlite:{...DEFAULT_MEMORY_CONFIG.sqlite,...input?.sqlite??{}},recall:{...DEFAULT_MEMORY_CONFIG.recall,...input?.recall??{},injection:{...DEFAULT_MEMORY_CONFIG.recall.injection,...input?.recall?.injection??{}}},writes:{...DEFAULT_MEMORY_CONFIG.writes,...input?.writes??{}},redaction:{...DEFAULT_MEMORY_CONFIG.redaction,...input?.redaction??{}},maintenance:{...DEFAULT_MEMORY_CONFIG.maintenance,...input?.maintenance??{},importance:{...DEFAULT_MEMORY_CONFIG.maintenance.importance,...input?.maintenance?.importance??{}}},consolidation:{...DEFAULT_MEMORY_CONFIG.consolidation,...input?.consolidation??{},decayHalfLifeDays:{...DEFAULT_MEMORY_CONFIG.consolidation.decayHalfLifeDays,...input?.consolidation?.decayHalfLifeDays??{}}},embeddings:{...DEFAULT_MEMORY_CONFIG.embeddings,...input?.embeddings??{}},retrieval:{...DEFAULT_MEMORY_CONFIG.retrieval,...input?.retrieval??{},weights:{...DEFAULT_MEMORY_CONFIG.retrieval.weights,...input?.retrieval?.weights??{}},rerank:{...DEFAULT_MEMORY_CONFIG.retrieval.rerank,...input?.retrieval?.rerank??{}}}}}var DEFAULT_DECAY_HALF_LIFE_DAYS,DEFAULT_IMPORTANCE_CONFIG,DEFAULT_CONSOLIDATION_CONFIG,DEFAULT_EMBEDDINGS_CONFIG,DEFAULT_RETRIEVAL_CONFIG,DEFAULT_MEMORY_CONFIG,DURABLE_MEMORY_KINDS,EVIDENCE_REQUIRED_KINDS;var init_config3=__esm(()=>{DEFAULT_DECAY_HALF_LIFE_DAYS={scratch:7,todo:30,code_pattern:90,test_pattern:90,failure_pattern:90,api_finding:180,evidence:180,architecture_decision:0,repo_convention:0,project_fact:0,security_note:0,user_preference:0},DEFAULT_IMPORTANCE_CONFIG={wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2},DEFAULT_CONSOLIDATION_CONFIG={enabled:!1,maxClustersPerPass:10,jaccardThreshold:0.3,autoApplyMinConfidence:0.6,decayHalfLifeDays:{...DEFAULT_DECAY_HALF_LIFE_DAYS}},DEFAULT_EMBEDDINGS_CONFIG={enabled:!1,model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheSize:256},DEFAULT_RETRIEVAL_CONFIG={rrfK:60,weights:{lexical:0.5,dense:0.4,metadata:0.1},rerank:{enabled:!1},latencyBudgetMs:250},DEFAULT_MEMORY_CONFIG={enabled:!1,provider:"sqlite",storageDir:".swarm/memory",sqlite:{path:".swarm/memory/memory.db",busyTimeoutMs:5000},recall:{defaultMaxItems:8,defaultTokenBudget:1200,minScore:0.05,injection:{enabled:!0,minScore:0.25,requireQuerySignal:!0,maxItems:6,tokenBudget:1000}},writes:{mode:"propose"},redaction:{rejectDurableSecrets:!0},maintenance:{lowUtilityMaxConfidence:0.45,lowUtilityMinAgeDays:30,autoCompactEveryNRecalls:50,importance:{...DEFAULT_IMPORTANCE_CONFIG}},consolidation:{...DEFAULT_CONSOLIDATION_CONFIG,decayHalfLifeDays:{...DEFAULT_DECAY_HALF_LIFE_DAYS}},embeddings:{...DEFAULT_EMBEDDINGS_CONFIG},retrieval:{...DEFAULT_RETRIEVAL_CONFIG},hardDelete:!1},DURABLE_MEMORY_KINDS=new Set(["user_preference","project_fact","architecture_decision","repo_convention","code_pattern","test_pattern","failure_pattern","security_note"]),EVIDENCE_REQUIRED_KINDS=new Set(["api_finding","evidence","security_note"])});var MemoryValidationError,MemoryDisabledError;var init_errors6=__esm(()=>{MemoryValidationError=class MemoryValidationError extends Error{code;constructor(message,code="memory_validation_error"){super(message);this.name="MemoryValidationError",this.code=code}};MemoryDisabledError=class MemoryDisabledError extends Error{constructor(message="Swarm memory is disabled"){super(message);this.name="MemoryDisabledError"}}});function findSecrets(text){let findings=[];for(let{type,pattern}of SECRET_PATTERNS){pattern.lastIndex=0;for(let match of text.matchAll(pattern))if(match[0])findings.push({type,match:match[0]})}return findings}function containsSecret(text){return findSecrets(text).length>0}function redactSecrets(text){let redacted=text;for(let{type,pattern}of SECRET_PATTERNS)pattern.lastIndex=0,redacted=redacted.replace(pattern,`[REDACTED:${type}]`);return redacted}var SECRET_PATTERNS;var init_redaction=__esm(()=>{SECRET_PATTERNS=[{type:"openai_api_key",pattern:/\bsk-[A-Za-z0-9_-]{20,}\b/g},{type:"github_token",pattern:/\b(?:ghp|gho|ghu|ghs|ghr|github_pat)_[A-Za-z0-9_]{20,}\b/g},{type:"aws_access_key_id",pattern:/\bAKIA[0-9A-Z]{16}\b/g},{type:"private_key_block",pattern:/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g},{type:"authorization_bearer",pattern:/\bAuthorization\s*:\s*Bearer\s+[A-Za-z0-9._~+/=-]{12,}/gi},{type:"env_secret",pattern:/\b(?:[A-Z][A-Z0-9]+_)+(?:KEY|TOKEN|SECRET|PASSWORD)\b\s*=\s*["']?[^\s"'`]{8,}["']?/gi},{type:"gitlab_token",pattern:/\bgl(?:pat|ptt)-[A-Za-z0-9_-]{15,}\b/g},{type:"slack_token",pattern:/\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g},{type:"jwt_token",pattern:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{type:"aws_secret_access_key",pattern:/\b(?:aws_secret_access_key|AWS_SECRET_ACCESS_KEY)\s*[=:]\s*[A-Za-z0-9/+=]{40}\b/g},{type:"stripe_secret_key",pattern:/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{type:"google_api_key",pattern:/\bAIza[0-9A-Za-z_-]{35}\b/g},{type:"openssh_private_key_block",pattern:/-----BEGIN[ ]OPENSSH[ ]PRIVATE[ ]KEY-----[\s\S]*?-----END[ ]OPENSSH[ ]PRIVATE[ ]KEY-----/g}]});var MEMORY_RECALL_SENTINEL="## Retrieved Swarm Memory";import{createHash as createHash13}from"node:crypto";function normalizeMemoryText(text){return text.replace(/\s+/g," ").trim()}function stableScopeKey(scope){let ordered={type:scope.type},keys=scope.type==="repository"?["repoId"]:["userId","workspaceId","projectId","repoId","repoRoot","runId","agentId"];for(let key of keys){let value=scope[key];if(value)ordered[key]=value}return JSON.stringify(ordered)}function computeMemoryContentHash(recordLike){let normalized=normalizeMemoryText(recordLike.text).toLowerCase();return createHash13("sha256").update(`${stableScopeKey(recordLike.scope)}
1384
+ .swarm/loop/ instead of starting a new objective`;var init_loop=__esm(()=>{DEPTHS2=new Set(["standard","exhaustive"]),AUTONOMY_LEVELS=new Set(["checkpoint","auto"]);_internals54={readLatestLoopState}});function resolveMemoryConfig(input){return{...DEFAULT_MEMORY_CONFIG,...input??{},sqlite:{...DEFAULT_MEMORY_CONFIG.sqlite,...input?.sqlite??{}},recall:{...DEFAULT_MEMORY_CONFIG.recall,...input?.recall??{},injection:{...DEFAULT_MEMORY_CONFIG.recall.injection,...input?.recall?.injection??{}}},learning:{...DEFAULT_MEMORY_CONFIG.learning,...input?.learning??{}},writes:{...DEFAULT_MEMORY_CONFIG.writes,...input?.writes??{}},redaction:{...DEFAULT_MEMORY_CONFIG.redaction,...input?.redaction??{}},maintenance:{...DEFAULT_MEMORY_CONFIG.maintenance,...input?.maintenance??{},importance:{...DEFAULT_MEMORY_CONFIG.maintenance.importance,...input?.maintenance?.importance??{}}},consolidation:{...DEFAULT_MEMORY_CONFIG.consolidation,...input?.consolidation??{},decayHalfLifeDays:{...DEFAULT_MEMORY_CONFIG.consolidation.decayHalfLifeDays,...input?.consolidation?.decayHalfLifeDays??{}}},embeddings:{...DEFAULT_MEMORY_CONFIG.embeddings,...input?.embeddings??{}},retrieval:{...DEFAULT_MEMORY_CONFIG.retrieval,...input?.retrieval??{},weights:{...DEFAULT_MEMORY_CONFIG.retrieval.weights,...input?.retrieval?.weights??{}},rerank:{...DEFAULT_MEMORY_CONFIG.retrieval.rerank,...input?.retrieval?.rerank??{}}}}}var DEFAULT_DECAY_HALF_LIFE_DAYS,DEFAULT_IMPORTANCE_CONFIG,DEFAULT_CONSOLIDATION_CONFIG,DEFAULT_MEMORY_LEARNING_CONFIG,DEFAULT_EMBEDDINGS_CONFIG,DEFAULT_RETRIEVAL_CONFIG,DEFAULT_MEMORY_CONFIG,DURABLE_MEMORY_KINDS,EVIDENCE_REQUIRED_KINDS;var init_config3=__esm(()=>{DEFAULT_DECAY_HALF_LIFE_DAYS={scratch:7,todo:30,code_pattern:90,test_pattern:90,failure_pattern:90,api_finding:180,evidence:180,architecture_decision:0,repo_convention:0,project_fact:0,security_note:0,user_preference:0},DEFAULT_IMPORTANCE_CONFIG={wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2},DEFAULT_CONSOLIDATION_CONFIG={enabled:!1,maxClustersPerPass:10,jaccardThreshold:0.3,autoApplyMinConfidence:0.6,decayHalfLifeDays:{...DEFAULT_DECAY_HALF_LIFE_DAYS}},DEFAULT_MEMORY_LEARNING_CONFIG={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},DEFAULT_EMBEDDINGS_CONFIG={enabled:!1,model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheSize:256},DEFAULT_RETRIEVAL_CONFIG={rrfK:60,weights:{lexical:0.5,dense:0.4,metadata:0.1},rerank:{enabled:!1},latencyBudgetMs:250},DEFAULT_MEMORY_CONFIG={enabled:!1,provider:"sqlite",storageDir:".swarm/memory",sqlite:{path:".swarm/memory/memory.db",busyTimeoutMs:5000},recall:{defaultMaxItems:8,defaultTokenBudget:1200,minScore:0.05,injection:{enabled:!0,minScore:0.25,requireQuerySignal:!0,maxItems:6,tokenBudget:1000}},learning:{...DEFAULT_MEMORY_LEARNING_CONFIG},writes:{mode:"propose"},redaction:{rejectDurableSecrets:!0},maintenance:{lowUtilityMaxConfidence:0.45,lowUtilityMinAgeDays:30,autoCompactEveryNRecalls:50,importance:{...DEFAULT_IMPORTANCE_CONFIG}},consolidation:{...DEFAULT_CONSOLIDATION_CONFIG,decayHalfLifeDays:{...DEFAULT_DECAY_HALF_LIFE_DAYS}},embeddings:{...DEFAULT_EMBEDDINGS_CONFIG},retrieval:{...DEFAULT_RETRIEVAL_CONFIG},hardDelete:!1},DURABLE_MEMORY_KINDS=new Set(["user_preference","project_fact","architecture_decision","repo_convention","code_pattern","test_pattern","failure_pattern","security_note"]),EVIDENCE_REQUIRED_KINDS=new Set(["api_finding","evidence","security_note"])});var MemoryValidationError,MemoryDisabledError;var init_errors6=__esm(()=>{MemoryValidationError=class MemoryValidationError extends Error{code;constructor(message,code="memory_validation_error"){super(message);this.name="MemoryValidationError",this.code=code}};MemoryDisabledError=class MemoryDisabledError extends Error{constructor(message="Swarm memory is disabled"){super(message);this.name="MemoryDisabledError"}}});function findSecrets(text){let findings=[];for(let{type,pattern}of SECRET_PATTERNS){pattern.lastIndex=0;for(let match of text.matchAll(pattern))if(match[0])findings.push({type,match:match[0]})}return findings}function containsSecret(text){return findSecrets(text).length>0}function redactSecrets(text){let redacted=text;for(let{type,pattern}of SECRET_PATTERNS)pattern.lastIndex=0,redacted=redacted.replace(pattern,`[REDACTED:${type}]`);return redacted}var SECRET_PATTERNS;var init_redaction=__esm(()=>{SECRET_PATTERNS=[{type:"openai_api_key",pattern:/\bsk-[A-Za-z0-9_-]{20,}\b/g},{type:"github_token",pattern:/\b(?:ghp|gho|ghu|ghs|ghr|github_pat)_[A-Za-z0-9_]{20,}\b/g},{type:"aws_access_key_id",pattern:/\bAKIA[0-9A-Z]{16}\b/g},{type:"private_key_block",pattern:/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g},{type:"authorization_bearer",pattern:/\bAuthorization\s*:\s*Bearer\s+[A-Za-z0-9._~+/=-]{12,}/gi},{type:"env_secret",pattern:/\b(?:[A-Z][A-Z0-9]+_)+(?:KEY|TOKEN|SECRET|PASSWORD)\b\s*=\s*["']?[^\s"'`]{8,}["']?/gi},{type:"gitlab_token",pattern:/\bgl(?:pat|ptt)-[A-Za-z0-9_-]{15,}\b/g},{type:"slack_token",pattern:/\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g},{type:"jwt_token",pattern:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{type:"aws_secret_access_key",pattern:/\b(?:aws_secret_access_key|AWS_SECRET_ACCESS_KEY)\s*[=:]\s*[A-Za-z0-9/+=]{40}\b/g},{type:"stripe_secret_key",pattern:/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{type:"google_api_key",pattern:/\bAIza[0-9A-Za-z_-]{35}\b/g},{type:"openssh_private_key_block",pattern:/-----BEGIN[ ]OPENSSH[ ]PRIVATE[ ]KEY-----[\s\S]*?-----END[ ]OPENSSH[ ]PRIVATE[ ]KEY-----/g}]});var MEMORY_RECALL_SENTINEL="## Retrieved Swarm Memory";import{createHash as createHash13}from"node:crypto";function normalizeMemoryText(text){return text.replace(/\s+/g," ").trim()}function stableScopeKey(scope){let ordered={type:scope.type},keys=scope.type==="repository"?["repoId"]:["userId","workspaceId","projectId","repoId","repoRoot","runId","agentId"];for(let key of keys){let value=scope[key];if(value)ordered[key]=value}return JSON.stringify(ordered)}function computeMemoryContentHash(recordLike){let normalized=normalizeMemoryText(recordLike.text).toLowerCase();return createHash13("sha256").update(`${stableScopeKey(recordLike.scope)}
1385
1385
  ${recordLike.kind}
1386
1386
  ${normalized}`).digest("hex")}function createMemoryId(recordLike){return`mem_${computeMemoryContentHash(recordLike).slice(0,16)}`}function createProposalId(input){return`prop_${createHash13("sha256").update(`${input.createdAt}
1387
1387
  ${input.proposer}
1388
1388
  ${normalizeMemoryText(input.text)}`).digest("hex").slice(0,16)}`}function createBundleId(query,generatedAt){let compactTimestamp=generatedAt.replace(/[-:.TZ]/g,"").slice(0,14),hash4=createHash13("sha256").update(`${generatedAt}
1389
- ${query}`).digest("hex").slice(0,8);return`bundle_${compactTimestamp}_${hash4}`}function isExpired(record3,now=new Date){if(!record3.expiresAt)return!1;let expires=Date.parse(record3.expiresAt);return Number.isFinite(expires)&&expires<=now.getTime()}function hasEvidenceSource(record3){return Boolean(record3.source.url||record3.source.filePath||record3.source.commitSha||record3.source.ref)}function validateMemoryRecordRules(record3,options){let parsed=MemoryRecordSchema.parse(record3);if(parsed.text.includes(MEMORY_RECALL_SENTINEL))throw new MemoryValidationError("memory text cannot contain the recall sentinel header");let expectedHash=computeMemoryContentHash(parsed),expectedId=createMemoryId(parsed);if(parsed.contentHash!==expectedHash)throw new MemoryValidationError("contentHash does not match memory content");if(parsed.id!==expectedId)throw new MemoryValidationError("id does not match memory content");if(parsed.stability==="durable"&&(parsed.scope.type==="run"||parsed.scope.type==="agent"))throw new MemoryValidationError("durable memories cannot use run or agent scope");if(parsed.stability==="durable"&&(DURABLE_MEMORY_KINDS.has(parsed.kind)||parsed.kind==="api_finding"||parsed.kind==="evidence")&&!hasEvidenceSource(parsed))throw new MemoryValidationError("durable project, repository, API, evidence, and security memories require source evidence");if(EVIDENCE_REQUIRED_KINDS.has(parsed.kind)&&!hasEvidenceSource(parsed))throw new MemoryValidationError(`${parsed.kind} memories require source evidence`);if(parsed.kind==="scratch"&&(!parsed.expiresAt||Date.parse(parsed.expiresAt)-Date.parse(parsed.createdAt)>604800000))throw new MemoryValidationError("scratch memories must expire within 7 days");if(options.rejectDurableSecrets&&parsed.stability==="durable"&&containsSecret(parsed.text))throw new MemoryValidationError("durable memory contains a likely secret");return parsed}function validateMemoryProposal(proposal){return MemoryProposalSchema.parse(proposal)}function validateCuratorMemoryDecision(decision){return CuratorMemoryDecisionSchema.parse(decision)}var MemoryScopeTypeSchema,MemoryScopeRefSchema,MemoryKindSchema,MemorySourceSchema,MemoryRecordSchema,MemoryProposalSchema,NewMemoryRecordSchema,MemoryPatchSchema,ProposalIdSchema,MemoryIdSchema,CuratorDecisionReasonSchema,CuratorMemoryDecisionSchema;var init_schema2=__esm(()=>{init_zod();init_config3();init_errors6();init_redaction();MemoryScopeTypeSchema=exports_external.enum(["global_user","workspace","project","repository","run","agent"]),MemoryScopeRefSchema=exports_external.object({type:MemoryScopeTypeSchema,userId:exports_external.string().optional(),workspaceId:exports_external.string().optional(),projectId:exports_external.string().optional(),repoId:exports_external.string().optional(),repoRoot:exports_external.string().optional(),runId:exports_external.string().optional(),agentId:exports_external.string().optional()}).strict(),MemoryKindSchema=exports_external.enum(["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"]),MemorySourceSchema=exports_external.object({type:exports_external.enum(["user","agent","tool","file","repo","commit","test","web","manual"]),ref:exports_external.string().optional(),url:exports_external.string().optional(),filePath:exports_external.string().optional(),commitSha:exports_external.string().optional(),createdBy:exports_external.string().optional()}).strict(),MemoryRecordSchema=exports_external.object({id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/),scope:MemoryScopeRefSchema,kind:MemoryKindSchema,text:exports_external.string().min(1).max(2000),tags:exports_external.array(exports_external.string().min(1).max(64)).max(32),confidence:exports_external.number().min(0).max(1),stability:exports_external.enum(["ephemeral","session","durable"]),source:MemorySourceSchema,createdAt:exports_external.string().datetime(),updatedAt:exports_external.string().datetime(),lastAccessedAt:exports_external.string().datetime().optional(),expiresAt:exports_external.string().datetime().optional(),supersedes:exports_external.array(exports_external.string()).optional(),supersededBy:exports_external.string().optional(),contentHash:exports_external.string().regex(/^[a-f0-9]{64}$/),metadata:exports_external.record(exports_external.string(),exports_external.unknown())}).strict(),MemoryProposalSchema=exports_external.object({id:exports_external.string().regex(/^prop_[a-f0-9]{16}$/),operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]),proposedRecord:MemoryRecordSchema.optional(),targetMemoryId:exports_external.string().optional(),relatedMemoryIds:exports_external.array(exports_external.string()).optional(),proposedBy:exports_external.object({agentRole:exports_external.string().optional(),agentId:exports_external.string().optional(),runId:exports_external.string().optional()}).strict(),rationale:exports_external.string().min(1).max(2000),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20),status:exports_external.enum(["pending","approved","rejected","superseded","applied"]),reviewer:exports_external.enum(["user","controller","curator_agent","auto_policy"]).optional(),reviewedAt:exports_external.string().datetime().optional(),rejectionReason:exports_external.string().optional(),createdAt:exports_external.string().datetime(),metadata:exports_external.record(exports_external.string(),exports_external.unknown())}).strict(),NewMemoryRecordSchema=exports_external.object({scope:MemoryScopeRefSchema.optional(),kind:MemoryKindSchema,text:exports_external.string().min(1).max(2000),tags:exports_external.array(exports_external.string().min(1).max(64)).max(32).optional(),confidence:exports_external.number().min(0).max(1).optional(),stability:exports_external.enum(["ephemeral","session","durable"]).optional(),source:MemorySourceSchema.optional(),expiresAt:exports_external.string().datetime().optional(),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}).strict(),MemoryPatchSchema=exports_external.object({scope:MemoryScopeRefSchema.optional(),kind:MemoryKindSchema.optional(),text:exports_external.string().min(1).max(2000).optional(),tags:exports_external.array(exports_external.string().min(1).max(64)).max(32).optional(),confidence:exports_external.number().min(0).max(1).optional(),stability:exports_external.enum(["ephemeral","session","durable"]).optional(),source:MemorySourceSchema.optional(),expiresAt:exports_external.string().datetime().optional(),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}).strict().refine((patch)=>Object.keys(patch).length>0,{message:"memory patch must not be empty"}),ProposalIdSchema=exports_external.string().regex(/^prop_[a-f0-9]{16}$/),MemoryIdSchema=exports_external.string().regex(/^mem_[a-f0-9]{16}$/),CuratorDecisionReasonSchema=exports_external.string().min(1).max(2000),CuratorMemoryDecisionSchema=exports_external.discriminatedUnion("action",[exports_external.object({action:exports_external.literal("add"),proposalId:ProposalIdSchema,memory:NewMemoryRecordSchema}).strict(),exports_external.object({action:exports_external.literal("update"),proposalId:ProposalIdSchema,targetMemoryId:MemoryIdSchema,patch:MemoryPatchSchema,reason:CuratorDecisionReasonSchema}).strict(),exports_external.object({action:exports_external.literal("supersede"),proposalId:ProposalIdSchema,oldMemoryId:MemoryIdSchema,replacement:NewMemoryRecordSchema,reason:CuratorDecisionReasonSchema}).strict(),exports_external.object({action:exports_external.literal("reject"),proposalId:ProposalIdSchema,reason:CuratorDecisionReasonSchema}).strict(),exports_external.object({action:exports_external.literal("noop"),proposalId:ProposalIdSchema,reason:CuratorDecisionReasonSchema}).strict()])});function validateDecisionMatchesProposal(decision,proposal){if(decision.action==="add"&&proposal.operation!=="add"||decision.action==="update"&&proposal.operation!=="update"||decision.action==="supersede"&&proposal.operation!=="supersede")throw new MemoryValidationError(`curator ${decision.action} decision does not match ${proposal.operation} proposal`);if(decision.action==="update"&&proposal.targetMemoryId&&proposal.targetMemoryId!==decision.targetMemoryId)throw new MemoryValidationError("curator update decision target does not match proposal target");if(decision.action==="supersede"&&proposal.targetMemoryId&&proposal.targetMemoryId!==decision.oldMemoryId)throw new MemoryValidationError("curator supersede decision target does not match proposal target")}function validateCuratorPromotableMemory(record3){if(record3.stability!=="durable")throw new MemoryValidationError("curator memory promotions must be durable facts");if(!DURABLE_MEMORY_KINDS.has(record3.kind))throw new MemoryValidationError("curator memory promotions must use durable fact kinds; store raw docs, search results, and other bulky source material as evidence records instead");if(normalizeMemoryText(record3.text).length>CURATOR_PROMOTED_MEMORY_MAX_TEXT_LENGTH)throw new MemoryValidationError(`curator memory promotions must be concise durable facts under ${CURATOR_PROMOTED_MEMORY_MAX_TEXT_LENGTH} characters`)}function applyPatchToMemory(existing,patch,updatedAt){let base={scope:patch.scope??existing.scope,kind:patch.kind??existing.kind,text:patch.text===void 0?existing.text:normalizeMemoryText(patch.text)},tags=patch.tags===void 0?existing.tags:normalizeTags(patch.tags);return{...existing,...patch,...base,id:createMemoryId(base),tags,updatedAt,contentHash:computeMemoryContentHash(base),metadata:patch.metadata===void 0?existing.metadata:{...existing.metadata,...patch.metadata}}}function markProposalReviewed(proposal,decision,status,reviewedAt,ids){let reason=curatorDecisionReason(decision);return validateMemoryProposal({...proposal,status,reviewer:"curator_agent",reviewedAt,rejectionReason:decision.action==="reject"?reason:void 0,metadata:{...proposal.metadata,curatorDecision:{action:decision.action,reason,...ids,appliedAt:reviewedAt}}})}function curatorDecisionReason(decision){switch(decision.action){case"add":return;case"update":case"supersede":case"reject":case"noop":return decision.reason}}function buildCuratorDecisionEvent(change,proposal){return{...change,proposalOperation:proposal.operation}}function normalizeTags(tags){return Array.from(new Set(tags.map((tag)=>tag.toLowerCase().replace(/[^\w-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")).filter(Boolean))).slice(0,32)}var CURATOR_PROMOTED_MEMORY_MAX_TEXT_LENGTH=500;var init_curator_decision_helpers=__esm(()=>{init_config3();init_errors6();init_schema2()});function resolveMemoryRecallProfile(agentRole){let role=normalizeMemoryAgentRole(agentRole);return MEMORY_RECALL_PROFILES[role]??MEMORY_RECALL_PROFILES.coder}function normalizeMemoryAgentRole(agentRole){let base=stripKnownSwarmPrefix(agentRole??"architect");if(base==="reviewer"||base==="test_engineer")return"qa";if(base==="critic"||base==="critic_sounding_board"||base==="critic_drift_verifier"||base==="critic_hallucination_verifier"||base==="critic_architecture_supervisor")return"security";if(base==="curator_init"||base==="curator_phase"||base==="curator_postmortem")return"curator";if(base==="docs")return"sme";if(base==="architect"||base==="sme"||base==="coder"||base==="security"||base==="curator")return base;return"coder"}var MEMORY_RECALL_PROFILES;var init_role_profiles=__esm(()=>{init_schema();MEMORY_RECALL_PROFILES={architect:{kinds:["project_fact","architecture_decision","repo_convention","failure_pattern","security_note"],maxItems:10,tokenBudget:1600},sme:{kinds:["api_finding","code_pattern","repo_convention","failure_pattern","evidence"],maxItems:8,tokenBudget:1200},coder:{kinds:["architecture_decision","repo_convention","code_pattern","test_pattern","failure_pattern"],maxItems:8,tokenBudget:1200},qa:{kinds:["test_pattern","failure_pattern","repo_convention","security_note"],maxItems:8,tokenBudget:1200},security:{kinds:["security_note","architecture_decision","repo_convention","evidence"],maxItems:8,tokenBudget:1200},curator:{kinds:["project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence"],maxItems:20,tokenBudget:3000}}});function tokenize(text){return new Set(text.toLowerCase().replace(/[^\w\s-]/g," ").split(/\s+/).map((token)=>token.trim()).filter(Boolean))}function jaccard(a,b){if(a.size===0&&b.size===0)return 0;let intersection3=0;for(let token of a)if(b.has(token))intersection3++;let union3=a.size+b.size-intersection3;return union3===0?0:intersection3/union3}function clusterByJaccard(items,getText,threshold){let clusters=[];for(let item of items){let tokens=tokenize(getText(item)),placed=!1;for(let cluster of clusters)if(jaccard(tokens,cluster.tokens)>=threshold){cluster.members.push(item),placed=!0;break}if(!placed)clusters.push({tokens,members:[item]})}return clusters.map((cluster)=>cluster.members)}function importanceScore(input,weights){let recency=input.daysSinceLastRecall===null?0:Math.exp(-weights.lambda*Math.max(0,input.daysSinceLastRecall)),denom=Math.log1p(Math.max(1,weights.n)),frequency=denom===0?0:Math.log1p(Math.max(0,input.retrievalCount))/denom,freshness=Math.exp(-weights.mu*Math.max(0,input.daysSinceCreated)),confidence=Math.min(1,Math.max(0,input.confidence));return weights.wRecency*recency+weights.wFrequency*frequency+weights.wFreshness*freshness+weights.wConfidence*confidence}function normalizeKindText(kind){return kind.replace(/_/g," ")}function collectMetadataStrings(metadata,keys){let values=[];for(let key of keys){let value=metadata[key];if(typeof value==="string")values.push(value);if(Array.isArray(value)){for(let item of value)if(typeof item==="string")values.push(item)}}return values}function overlap(a,b){if(a.size===0||b.size===0)return 0;let hits=0;for(let token of a)if(b.has(token))hits++;return hits/Math.max(a.size,1)}function scopeSpecificityBoost(scope){switch(scope.type){case"agent":return 1;case"run":return 0.9;case"repository":return 0.8;case"project":return 0.65;case"workspace":return 0.45;case"global_user":return 0.3}}function kindProfileBoost(kind,request){if(!request.kinds||request.kinds.length===0)return 0.5;return request.kinds.includes(kind)?1:0}function roleProfileBoost(kind,context){return context.roleProfileKinds?.has(kind)?1:0}function sameScope(a,b){return stableScopeKey(a)===stableScopeKey(b)}function scopeAllowed(recordScope,allowedScopes){return allowedScopes.some((scope)=>sameScope(recordScope,scope))}function scoreMemoryRecordDetailed(record3,request,context){if(!request.includeExpired&&isExpired(record3))return{item:null,skipReason:"filtered"};if(record3.supersededBy)return{item:null,skipReason:"filtered"};if(record3.metadata.deleted===!0)return{item:null,skipReason:"filtered"};if(!scopeAllowed(record3.scope,request.scopes))return{item:null,skipReason:"filtered"};if(request.kinds&&!request.kinds.includes(record3.kind))return{item:null,skipReason:"filtered"};let queryTokens=request.mode==="injection"&&context.taskTokens?context.taskTokens:context.queryTokens,textTokens=tokenize(record3.text),tagTokens=tokenize(record3.tags.join(" ")),fileTokens=tokenize([record3.source.filePath,...collectMetadataStrings(record3.metadata,["file","filePath","files","touchedFiles"])].filter((value)=>typeof value==="string").join(" ")),symbolTokens=tokenize(collectMetadataStrings(record3.metadata,["symbol","symbols"]).join(" ")),kindTokens=tokenize(normalizeKindText(record3.kind)),sourceRefTokens=tokenize(record3.source.ref??""),taskSearchTokens=unionTokens(textTokens,tagTokens,fileTokens,symbolTokens,kindTokens,sourceRefTokens),taskTermOverlap=context.taskTokens?overlap(context.taskTokens,taskSearchTokens):0,kindQueryOverlap=overlap(queryTokens,kindTokens),textOverlap=overlap(queryTokens,textTokens),tagOverlap=overlap(queryTokens,tagTokens),fileOverlap=overlap(queryTokens,fileTokens),symbolOverlap=overlap(queryTokens,symbolTokens),kindMatch=request.kinds?.includes(record3.kind)??!1,scopeMatch=scopeAllowed(record3.scope,request.scopes),roleBoost=roleProfileBoost(record3.kind,context),hasQuerySignal=textOverlap>0||tagOverlap>0||fileOverlap>0||symbolOverlap>0||kindQueryOverlap>0;if(request.mode==="injection"&&request.requireQuerySignal!==!1&&!hasQuerySignal)return{item:null,skipReason:"no_signal"};let score=textOverlap*SCORING_WEIGHTS.textOverlap+tagOverlap*SCORING_WEIGHTS.tagOverlap+fileOverlap*SCORING_WEIGHTS.fileOverlap+symbolOverlap*SCORING_WEIGHTS.symbolOverlap+taskTermOverlap*SCORING_WEIGHTS.taskTermOverlap+scopeSpecificityBoost(record3.scope)*SCORING_WEIGHTS.scopeSpecificityBoost+kindProfileBoost(record3.kind,request)*SCORING_WEIGHTS.kindProfileBoost+roleBoost*SCORING_WEIGHTS.roleBoost+record3.confidence*SCORING_WEIGHTS.confidence,reasonParts=[textOverlap>0?`text_overlap=${textOverlap.toFixed(2)}`:null,tagOverlap>0?`tag_overlap=${tagOverlap.toFixed(2)}`:null,fileOverlap>0?`file_overlap=${fileOverlap.toFixed(2)}`:null,symbolOverlap>0?`symbol_overlap=${symbolOverlap.toFixed(2)}`:null,taskTermOverlap>0?`task_terms=${taskTermOverlap.toFixed(2)}`:null,kindQueryOverlap>0?`kind_query=${kindQueryOverlap.toFixed(2)}`:null,roleBoost>0?"role_profile":null,`scope=${record3.scope.type}`,`confidence=${record3.confidence.toFixed(2)}`].filter(Boolean);return{item:{record:record3,score,reason:reasonParts.join(", "),signals:{textOverlap,tagOverlap,fileOverlap,symbolOverlap,kindMatch,scopeMatch}}}}function scoreMemoryRecordsWithDiagnostics(records,request){let minScore=request.minScore??0,context=createScoringContext(request),diagnostics={candidateCount:records.length,preScoredFilteredCount:0,scoredCount:0,returnedCount:0,noSignalCount:0,belowThresholdCount:0},items=[];for(let record3 of records){let result=scoreMemoryRecordDetailed(record3,request,context);if(!result.item){if(result.skipReason==="filtered")diagnostics.preScoredFilteredCount++;if(result.skipReason==="no_signal")diagnostics.noSignalCount++;continue}if(diagnostics.scoredCount++,result.item.score<minScore){diagnostics.belowThresholdCount++;continue}items.push(result.item)}return items.sort((a,b)=>b.score-a.score||a.record.id.localeCompare(b.record.id)),diagnostics.returnedCount=items.length,{items,diagnostics}}function createScoringContext(request){return{taskTokens:request.task?tokenize(request.task):void 0,queryTokens:tokenize(request.query),roleProfileKinds:request.agentRole?new Set(resolveMemoryRecallProfile(request.agentRole).kinds):void 0}}function unionTokens(...sets){let union3=new Set;for(let set3 of sets)for(let token of set3)union3.add(token);return union3}var SCORING_WEIGHTS;var init_scoring=__esm(()=>{init_role_profiles();init_schema2();SCORING_WEIGHTS={textOverlap:0.38,tagOverlap:0.16,fileOverlap:0.12,symbolOverlap:0.08,taskTermOverlap:0.08,scopeSpecificityBoost:0.12,kindProfileBoost:0.06,roleBoost:0.05,confidence:0.08}});async function buildMemoryMaintenanceReport(provider,options={}){let now=options.now??new Date,limit=Math.max(1,Math.trunc(options.limit??20)),memories=await provider.list({includeExpired:!0,includeInactive:!0}),proposals=await loadMaintenanceProposals(provider,limit),recallUsage=provider.listRecallUsage?await provider.listRecallUsage():[],usageByMemory=summarizeRecallByMemory(recallUsage),usageByRole=summarizeRecallByRole(recallUsage),activeMemories=memories.filter((memory)=>isActiveMemory(memory,now)),deletedMemories=memories.filter((memory)=>memory.metadata.deleted===!0),expiredScratchMemories=memories.filter((memory)=>memory.kind==="scratch"&&isExpired(memory,now)),supersededMemories=memories.filter((memory)=>Boolean(memory.supersededBy)),lowUtilityMemories=activeMemories.filter((memory)=>isLowUtility(memory,usageByMemory,now,{weights:options.importanceWeights??DEFAULT_IMPORTANCE_WEIGHTS,threshold:options.importanceThreshold??DEFAULT_IMPORTANCE_THRESHOLD})).sort(memorySort),neverRecalledMemories=activeMemories.filter((memory)=>!usageByMemory.has(memory.id)).sort(memorySort),rejectedProposalReasons=proposals.filter((proposal)=>proposal.status==="rejected").sort(proposalSort),pendingProposals=proposals.filter((proposal)=>proposal.status==="pending").sort(proposalSort);return{generatedAt:now.toISOString(),totalMemories:memories.length,activeMemories:activeMemories.length,deletedMemories:deletedMemories.slice(0,limit),expiredScratchMemories:expiredScratchMemories.slice(0,limit),supersededMemories:supersededMemories.slice(0,limit),supersededChains:buildSupersededChains(memories).slice(0,limit),lowUtilityMemories:lowUtilityMemories.slice(0,limit),neverRecalledMemories:neverRecalledMemories.slice(0,limit),mostRecalledMemories:Array.from(usageByMemory.values()).sort((a,b)=>b.count-a.count||b.lastRecalledAt.localeCompare(a.lastRecalledAt)||a.memoryId.localeCompare(b.memoryId)).slice(0,limit),recallByAgentRole:Array.from(usageByRole.values()).sort((a,b)=>b.count-a.count||a.agentRole.localeCompare(b.agentRole)).slice(0,limit),rejectedProposalReasons:rejectedProposalReasons.slice(0,limit),pendingProposals:pendingProposals.slice(0,limit),recallEventCount:recallUsage.length}}function shouldCompactMemory(memory,now=new Date){if(memory.metadata.deleted===!0)return"deleted";if(memory.supersededBy)return"superseded";if(memory.kind==="scratch"&&isExpired(memory,now))return"expired_scratch";return null}function isActiveMemory(memory,now){return memory.metadata.deleted!==!0&&!memory.supersededBy&&!isExpired(memory,now)}function isLowUtility(memory,usageByMemory,now,options){if(usageByMemory.has(memory.id))return!1;let created=Date.parse(memory.createdAt),daysSinceCreated=Number.isFinite(created)?Math.max(0,(now.getTime()-created)/MS_PER_DAY2):0;return importanceScore({confidence:memory.confidence,retrievalCount:0,daysSinceLastRecall:null,daysSinceCreated},options.weights)<options.threshold}function summarizeRecallByMemory(usageEvents){let byMemory=new Map;for(let event of usageEvents)event.memoryIds.forEach((memoryId,index)=>{let role=event.agentRole??"unknown",existing=byMemory.get(memoryId)??{memoryId,count:0,lastRecalledAt:event.timestamp,agentRoles:{},averageScore:0,scoreTotal:0,scoreCount:0};existing.count++,existing.lastRecalledAt=event.timestamp>existing.lastRecalledAt?event.timestamp:existing.lastRecalledAt,existing.agentRoles[role]=(existing.agentRoles[role]??0)+1;let score=event.scores[index];if(typeof score==="number"&&Number.isFinite(score))existing.scoreTotal+=score,existing.scoreCount++,existing.averageScore=existing.scoreTotal/existing.scoreCount;byMemory.set(memoryId,existing)});return new Map(Array.from(byMemory,([memoryId,value])=>[memoryId,{memoryId,count:value.count,lastRecalledAt:value.lastRecalledAt,agentRoles:value.agentRoles,averageScore:value.averageScore}]))}async function loadMaintenanceProposals(provider,limit){if(!provider.listProposals)return[];let[pending,rejected,recent]=await Promise.all([provider.listProposals({status:"pending",limit}),provider.listProposals({status:"rejected",limit}),provider.listProposals({limit:Math.max(limit*4,100)})]),byId=new Map;for(let proposal of[...pending,...rejected,...recent])byId.set(proposal.id,proposal);return Array.from(byId.values())}function summarizeRecallByRole(usageEvents){let byRole=new Map;for(let event of usageEvents){let role=event.agentRole??"unknown",existing=byRole.get(role)??{agentRole:role,count:0,memoryIds:{}};existing.count++;for(let memoryId of event.memoryIds)existing.memoryIds[memoryId]=(existing.memoryIds[memoryId]??0)+1;byRole.set(role,existing)}return byRole}function buildSupersededChains(memories){let byId=new Map(memories.map((memory)=>[memory.id,memory])),supersededIds=new Set(memories.filter((memory)=>memory.supersededBy).map((memory)=>memory.id));return memories.filter((memory)=>memory.supersededBy&&!(memory.supersedes??[]).some((id)=>supersededIds.has(id))).map((root)=>{let chain=[root.id],seen=new Set(chain),cursor=root;while(cursor?.supersededBy&&!seen.has(cursor.supersededBy))chain.push(cursor.supersededBy),seen.add(cursor.supersededBy),cursor=byId.get(cursor.supersededBy);return{rootId:root.id,chain,reason:typeof root.metadata.supersedeReason==="string"?root.metadata.supersedeReason:void 0}})}function memorySort(a,b){return b.updatedAt.localeCompare(a.updatedAt)||a.id.localeCompare(b.id)}function proposalSort(a,b){let aTime=a.reviewedAt??a.createdAt;return(b.reviewedAt??b.createdAt).localeCompare(aTime)||a.id.localeCompare(b.id)}var DEFAULT_IMPORTANCE_WEIGHTS,DEFAULT_IMPORTANCE_THRESHOLD=0.2,MS_PER_DAY2=86400000;var init_maintenance=__esm(()=>{init_schema2();init_scoring();DEFAULT_IMPORTANCE_WEIGHTS={wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50}});import{randomUUID as randomUUID7}from"node:crypto";import{existsSync as existsSync46}from"node:fs";import{appendFile as appendFile9,mkdir as mkdir18,readFile as readFile20,rename as rename10,writeFile as writeFile16}from"node:fs/promises";import*as path79 from"node:path";class LocalJsonlMemoryProvider{name="local-jsonl";rootDirectory;config;initialized=!1;memories=new Map;proposals=new Map;constructor(rootDirectory,config3={}){this.rootDirectory=rootDirectory,this.config={...DEFAULT_MEMORY_CONFIG,...config3}}pathFor(file3){let storageDir=this.config.storageDir.replace(/^\.swarm[/\\]?/,""),filename=file3==="memories"?"memories.jsonl":file3==="proposals"?"proposals.jsonl":"audit.jsonl";return validateSwarmPath(this.rootDirectory,path79.join(storageDir,filename))}async initialize(){if(this.initialized)return;let memoryPath=this.pathFor("memories"),proposalPath2=this.pathFor("proposals"),memoryLoad=validateLoadedMemories(await readJsonl(memoryPath),this.config),proposalLoad=validateLoadedProposals(await readJsonl(proposalPath2),this.config);if(this.memories=new Map(memoryLoad.records.map((record3)=>[record3.id,record3])),this.proposals=new Map(proposalLoad.records.map((proposal)=>[proposal.id,proposal])),this.initialized=!0,memoryLoad.invalidCount>0)await this.audit("invalid_load","memories",`${memoryLoad.invalidCount} invalid memory JSONL row(s) skipped`);if(proposalLoad.invalidCount>0)await this.audit("invalid_load","proposals",`${proposalLoad.invalidCount} invalid proposal JSONL row(s) skipped`)}async upsert(record3){await this.initialize();let existing=this.memories.get(record3.id);if(existing?.metadata.deleted===!0)throw new MemoryValidationError("memory is tombstoned and cannot be upserted");let next=validateMemoryRecordRules({...record3,createdAt:existing?.createdAt??record3.createdAt},{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets});return this.memories.set(next.id,next),await appendJsonl(this.pathFor("memories"),next),await this.audit("upsert",next.id),next}async get(id){return await this.initialize(),this.memories.get(id)??null}async delete(id,reason){await this.initialize();let existing=this.memories.get(id);if(!existing)return;if(this.config.hardDelete)this.memories.delete(id),await this.compact();else{let tombstone={...existing,updatedAt:new Date().toISOString(),metadata:{...existing.metadata,deleted:!0,deleteReason:reason}};this.memories.set(id,tombstone),await appendJsonl(this.pathFor("memories"),tombstone)}await this.audit("delete",id,reason)}async recall(request){return(await this.recallWithDiagnostics(request)).items}async recallWithDiagnostics(request){await this.initialize();let records=await this.list({scopes:request.scopes,kinds:request.kinds,includeExpired:request.includeExpired}),result=scoreMemoryRecordsWithDiagnostics(records,request);return{items:result.items.slice(0,request.maxItems),diagnostics:{...result.diagnostics,returnedCount:Math.min(result.diagnostics.returnedCount,request.maxItems)}}}async recordRecallUsage(event){await this.initialize(),await this.audit("recall",event.bundleId,void 0,event)}async listRecallUsage(filter={}){await this.initialize();let events=await readAuditEvents(this.pathFor("audit")),usage=[];for(let event of events){if(event.operation!=="recall")continue;let parsed=parseRecallUsageEvent(event);if(parsed)usage.push(parsed)}return usage.sort((a,b)=>b.timestamp.localeCompare(a.timestamp)),usage.slice(0,filter.limit??usage.length)}async list(filter={}){await this.initialize();let records=Array.from(this.memories.values());if(filter.scopes&&filter.scopes.length>0)records=records.filter((record3)=>scopeAllowed(record3.scope,filter.scopes??[]));if(filter.kinds&&filter.kinds.length>0)records=records.filter((record3)=>filter.kinds?.includes(record3.kind));if(!filter.includeExpired){let now=Date.now();records=records.filter((record3)=>{if(!record3.expiresAt)return!0;let expires=Date.parse(record3.expiresAt);return!Number.isFinite(expires)||expires>now})}if(!filter.includeInactive)records=records.filter((record3)=>!record3.supersededBy&&record3.metadata.deleted!==!0);return records.sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt)),records.slice(0,filter.limit??records.length)}async createProposal(proposal){await this.initialize();let next=validateMemoryProposal(proposal);return this.proposals.set(next.id,next),await appendJsonl(this.pathFor("proposals"),next),await this.audit("proposal",next.id),next}async listProposals(filter={}){await this.initialize();let proposals=Array.from(this.proposals.values());if(filter.status)proposals=proposals.filter((proposal)=>proposal.status===filter.status);return proposals.sort((a,b)=>b.createdAt.localeCompare(a.createdAt)),proposals.slice(0,filter.limit??proposals.length)}async applyCuratorDecision(decision){await this.initialize();let appliedAt=new Date().toISOString(),proposal=this.proposals.get(decision.proposalId);if(!proposal)throw new MemoryValidationError("memory proposal was not found");if(proposal.status!=="pending")throw new MemoryValidationError("memory proposal is not pending");validateDecisionMatchesProposal(decision,proposal);let memoryId,targetMemoryId,oldMemoryId,replacementMemoryId;if(decision.action==="add"){let memory=this.validateDecisionMemory({...decision.memory,updatedAt:appliedAt});validateCuratorPromotableMemory(memory),this.memories.set(memory.id,memory),await appendJsonl(this.pathFor("memories"),memory),memoryId=memory.id}else if(decision.action==="update"){let existing=this.activeMemory(decision.targetMemoryId),updated=this.validateDecisionMemory(applyPatchToMemory(existing,decision.patch,appliedAt));if(validateCuratorPromotableMemory(updated),updated.id!==existing.id){let tombstone=this.validateDecisionMemory({...existing,updatedAt:appliedAt,metadata:{...existing.metadata,deleted:!0,deleteReason:decision.reason,updateReplacementId:updated.id}});this.memories.set(tombstone.id,tombstone),await appendJsonl(this.pathFor("memories"),tombstone)}this.memories.set(updated.id,updated),await appendJsonl(this.pathFor("memories"),updated),memoryId=updated.id,targetMemoryId=existing.id}else if(decision.action==="supersede"){let oldMemory=this.activeMemory(decision.oldMemoryId),replacement=this.validateDecisionMemory({...decision.replacement,updatedAt:appliedAt,supersedes:Array.from(new Set([...decision.replacement.supersedes??[],oldMemory.id]))});validateCuratorPromotableMemory(replacement);let superseded=this.validateDecisionMemory({...oldMemory,updatedAt:appliedAt,supersededBy:replacement.id,metadata:{...oldMemory.metadata,supersedeReason:decision.reason}});this.memories.set(superseded.id,superseded),this.memories.set(replacement.id,replacement),await appendJsonl(this.pathFor("memories"),superseded),await appendJsonl(this.pathFor("memories"),replacement),oldMemoryId=oldMemory.id,replacementMemoryId=replacement.id,memoryId=replacement.id}let proposalStatus=decision.action==="reject"?"rejected":"applied",reviewedProposal=markProposalReviewed(proposal,decision,proposalStatus,appliedAt,{memoryId,targetMemoryId,oldMemoryId,replacementMemoryId});this.proposals.set(reviewedProposal.id,reviewedProposal),await appendJsonl(this.pathFor("proposals"),reviewedProposal);let change={action:decision.action,proposalId:decision.proposalId,proposalStatus,appliedAt,memoryId,targetMemoryId,oldMemoryId,replacementMemoryId,reason:curatorDecisionReason(decision)};return await this.audit("curator_decision",decision.proposalId,change.reason,buildCuratorDecisionEvent(change,proposal)),change}async compact(){await this.initialize(),await writeJsonlAtomic(this.pathFor("memories"),Array.from(this.memories.values())),await this.audit("compact","memories")}async compactMaintenance(options={}){await this.initialize();let now=options.now?new Date(options.now):new Date,kept=[],result={dryRun:options.dryRun!==!1,removedDeleted:0,removedSuperseded:0,removedExpiredScratch:0,remaining:0};for(let memory of this.memories.values()){let compactReason=shouldCompactMemory(memory,now);if(compactReason==="deleted"){result.removedDeleted++;continue}if(compactReason==="superseded"){result.removedSuperseded++;continue}if(compactReason==="expired_scratch"){result.removedExpiredScratch++;continue}kept.push(memory)}if(result.remaining=kept.length,result.dryRun)return result;return this.memories=new Map(kept.map((memory)=>[memory.id,memory])),await writeJsonlAtomic(this.pathFor("memories"),kept),await this.audit("compact","memories","removed deleted, superseded, and expired scratch memories",result),result}async audit(operation,targetId,reason,eventJson){let event={id:randomUUID7(),operation,targetId,reason,eventJson,timestamp:new Date().toISOString()};await appendJsonl(this.pathFor("audit"),event)}activeMemory(memoryId){let memory=this.memories.get(memoryId);if(!memory)throw new MemoryValidationError("target memory was not found");if(memory.metadata.deleted===!0)throw new MemoryValidationError("target memory is deleted");if(memory.supersededBy)throw new MemoryValidationError("target memory is superseded");return memory}validateDecisionMemory(record3){return validateMemoryRecordRules(record3,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets})}}function validateLoadedMemories(values,config3){let records=[],invalidCount=0;for(let value of values)try{records.push(validateMemoryRecordRules(value,{rejectDurableSecrets:config3.redaction.rejectDurableSecrets}))}catch{invalidCount++}return{records,invalidCount}}function validateLoadedProposals(values,config3){let records=[],invalidCount=0;for(let value of values)try{let proposal=validateMemoryProposal(value);if(proposal.proposedRecord)validateMemoryRecordRules(proposal.proposedRecord,{rejectDurableSecrets:config3.redaction.rejectDurableSecrets});records.push(proposal)}catch{invalidCount++}return{records,invalidCount}}async function readJsonl(filePath){if(!existsSync46(filePath))return[];let content=await readFile20(filePath,"utf-8"),records=[];for(let line of content.split(`
1389
+ ${query}`).digest("hex").slice(0,8);return`bundle_${compactTimestamp}_${hash4}`}function isExpired(record3,now=new Date){if(!record3.expiresAt)return!1;let expires=Date.parse(record3.expiresAt);return Number.isFinite(expires)&&expires<=now.getTime()}function hasEvidenceSource(record3){return Boolean(record3.source.url||record3.source.filePath||record3.source.commitSha||record3.source.ref)}function validateMemoryRecordRules(record3,options){let parsed=MemoryRecordSchema.parse(record3);if(parsed.text.includes(MEMORY_RECALL_SENTINEL))throw new MemoryValidationError("memory text cannot contain the recall sentinel header");let expectedHash=computeMemoryContentHash(parsed),expectedId=createMemoryId(parsed);if(parsed.contentHash!==expectedHash)throw new MemoryValidationError("contentHash does not match memory content");if(parsed.id!==expectedId)throw new MemoryValidationError("id does not match memory content");if(parsed.stability==="durable"&&(parsed.scope.type==="run"||parsed.scope.type==="agent"))throw new MemoryValidationError("durable memories cannot use run or agent scope");if(parsed.stability==="durable"&&(DURABLE_MEMORY_KINDS.has(parsed.kind)||parsed.kind==="api_finding"||parsed.kind==="evidence")&&!hasEvidenceSource(parsed))throw new MemoryValidationError("durable project, repository, API, evidence, and security memories require source evidence");if(EVIDENCE_REQUIRED_KINDS.has(parsed.kind)&&!hasEvidenceSource(parsed))throw new MemoryValidationError(`${parsed.kind} memories require source evidence`);if(parsed.kind==="scratch"&&(!parsed.expiresAt||Date.parse(parsed.expiresAt)-Date.parse(parsed.createdAt)>604800000))throw new MemoryValidationError("scratch memories must expire within 7 days");if(options.rejectDurableSecrets&&parsed.stability==="durable"&&containsSecret(parsed.text))throw new MemoryValidationError("durable memory contains a likely secret");return parsed}function validateMemoryProposal(proposal){return MemoryProposalSchema.parse(proposal)}function validateCuratorMemoryDecision(decision){return CuratorMemoryDecisionSchema.parse(decision)}var MemoryScopeTypeSchema,MemoryScopeRefSchema,MemoryKindSchema,MemorySourceSchema,MemoryRecordSchema,MemoryProposalSchema,NewMemoryRecordSchema,MemoryPatchSchema,ProposalIdSchema,MemoryIdSchema,CuratorDecisionReasonSchema,CuratorMemoryDecisionSchema;var init_schema2=__esm(()=>{init_zod();init_config3();init_errors6();init_redaction();MemoryScopeTypeSchema=exports_external.enum(["global_user","workspace","project","repository","run","agent"]),MemoryScopeRefSchema=exports_external.object({type:MemoryScopeTypeSchema,userId:exports_external.string().optional(),workspaceId:exports_external.string().optional(),projectId:exports_external.string().optional(),repoId:exports_external.string().optional(),repoRoot:exports_external.string().optional(),runId:exports_external.string().optional(),agentId:exports_external.string().optional()}).strict(),MemoryKindSchema=exports_external.enum(["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"]),MemorySourceSchema=exports_external.object({type:exports_external.enum(["user","agent","tool","file","repo","commit","test","web","manual"]),ref:exports_external.string().optional(),url:exports_external.string().optional(),filePath:exports_external.string().optional(),commitSha:exports_external.string().optional(),createdBy:exports_external.string().optional()}).strict(),MemoryRecordSchema=exports_external.object({id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/),scope:MemoryScopeRefSchema,kind:MemoryKindSchema,text:exports_external.string().min(1).max(2000),tags:exports_external.array(exports_external.string().min(1).max(64)).max(32),confidence:exports_external.number().min(0).max(1),stability:exports_external.enum(["ephemeral","session","durable"]),source:MemorySourceSchema,createdAt:exports_external.string().datetime(),updatedAt:exports_external.string().datetime(),lastAccessedAt:exports_external.string().datetime().optional(),expiresAt:exports_external.string().datetime().optional(),qValue:exports_external.number().min(0).max(1).optional(),supersedes:exports_external.array(exports_external.string()).optional(),supersededBy:exports_external.string().optional(),contentHash:exports_external.string().regex(/^[a-f0-9]{64}$/),metadata:exports_external.record(exports_external.string(),exports_external.unknown())}).strict(),MemoryProposalSchema=exports_external.object({id:exports_external.string().regex(/^prop_[a-f0-9]{16}$/),operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]),proposedRecord:MemoryRecordSchema.optional(),targetMemoryId:exports_external.string().optional(),relatedMemoryIds:exports_external.array(exports_external.string()).optional(),proposedBy:exports_external.object({agentRole:exports_external.string().optional(),agentId:exports_external.string().optional(),runId:exports_external.string().optional()}).strict(),rationale:exports_external.string().min(1).max(2000),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20),status:exports_external.enum(["pending","approved","rejected","superseded","applied"]),reviewer:exports_external.enum(["user","controller","curator_agent","auto_policy"]).optional(),reviewedAt:exports_external.string().datetime().optional(),rejectionReason:exports_external.string().optional(),createdAt:exports_external.string().datetime(),metadata:exports_external.record(exports_external.string(),exports_external.unknown())}).strict(),NewMemoryRecordSchema=exports_external.object({scope:MemoryScopeRefSchema.optional(),kind:MemoryKindSchema,text:exports_external.string().min(1).max(2000),tags:exports_external.array(exports_external.string().min(1).max(64)).max(32).optional(),confidence:exports_external.number().min(0).max(1).optional(),stability:exports_external.enum(["ephemeral","session","durable"]).optional(),source:MemorySourceSchema.optional(),expiresAt:exports_external.string().datetime().optional(),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}).strict(),MemoryPatchSchema=exports_external.object({scope:MemoryScopeRefSchema.optional(),kind:MemoryKindSchema.optional(),text:exports_external.string().min(1).max(2000).optional(),tags:exports_external.array(exports_external.string().min(1).max(64)).max(32).optional(),confidence:exports_external.number().min(0).max(1).optional(),stability:exports_external.enum(["ephemeral","session","durable"]).optional(),source:MemorySourceSchema.optional(),expiresAt:exports_external.string().datetime().optional(),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}).strict().refine((patch)=>Object.keys(patch).length>0,{message:"memory patch must not be empty"}),ProposalIdSchema=exports_external.string().regex(/^prop_[a-f0-9]{16}$/),MemoryIdSchema=exports_external.string().regex(/^mem_[a-f0-9]{16}$/),CuratorDecisionReasonSchema=exports_external.string().min(1).max(2000),CuratorMemoryDecisionSchema=exports_external.discriminatedUnion("action",[exports_external.object({action:exports_external.literal("add"),proposalId:ProposalIdSchema,memory:NewMemoryRecordSchema}).strict(),exports_external.object({action:exports_external.literal("update"),proposalId:ProposalIdSchema,targetMemoryId:MemoryIdSchema,patch:MemoryPatchSchema,reason:CuratorDecisionReasonSchema}).strict(),exports_external.object({action:exports_external.literal("supersede"),proposalId:ProposalIdSchema,oldMemoryId:MemoryIdSchema,replacement:NewMemoryRecordSchema,reason:CuratorDecisionReasonSchema}).strict(),exports_external.object({action:exports_external.literal("reject"),proposalId:ProposalIdSchema,reason:CuratorDecisionReasonSchema}).strict(),exports_external.object({action:exports_external.literal("noop"),proposalId:ProposalIdSchema,reason:CuratorDecisionReasonSchema}).strict()])});function validateDecisionMatchesProposal(decision,proposal){if(decision.action==="add"&&proposal.operation!=="add"||decision.action==="update"&&proposal.operation!=="update"||decision.action==="supersede"&&proposal.operation!=="supersede")throw new MemoryValidationError(`curator ${decision.action} decision does not match ${proposal.operation} proposal`);if(decision.action==="update"&&proposal.targetMemoryId&&proposal.targetMemoryId!==decision.targetMemoryId)throw new MemoryValidationError("curator update decision target does not match proposal target");if(decision.action==="supersede"&&proposal.targetMemoryId&&proposal.targetMemoryId!==decision.oldMemoryId)throw new MemoryValidationError("curator supersede decision target does not match proposal target")}function validateCuratorPromotableMemory(record3){if(record3.stability!=="durable")throw new MemoryValidationError("curator memory promotions must be durable facts");if(!DURABLE_MEMORY_KINDS.has(record3.kind))throw new MemoryValidationError("curator memory promotions must use durable fact kinds; store raw docs, search results, and other bulky source material as evidence records instead");if(normalizeMemoryText(record3.text).length>CURATOR_PROMOTED_MEMORY_MAX_TEXT_LENGTH)throw new MemoryValidationError(`curator memory promotions must be concise durable facts under ${CURATOR_PROMOTED_MEMORY_MAX_TEXT_LENGTH} characters`)}function applyPatchToMemory(existing,patch,updatedAt){let base={scope:patch.scope??existing.scope,kind:patch.kind??existing.kind,text:patch.text===void 0?existing.text:normalizeMemoryText(patch.text)},tags=patch.tags===void 0?existing.tags:normalizeTags(patch.tags);return{...existing,...patch,...base,id:createMemoryId(base),tags,updatedAt,contentHash:computeMemoryContentHash(base),metadata:patch.metadata===void 0?existing.metadata:{...existing.metadata,...patch.metadata}}}function markProposalReviewed(proposal,decision,status,reviewedAt,ids){let reason=curatorDecisionReason(decision);return validateMemoryProposal({...proposal,status,reviewer:"curator_agent",reviewedAt,rejectionReason:decision.action==="reject"?reason:void 0,metadata:{...proposal.metadata,curatorDecision:{action:decision.action,reason,...ids,appliedAt:reviewedAt}}})}function curatorDecisionReason(decision){switch(decision.action){case"add":return;case"update":case"supersede":case"reject":case"noop":return decision.reason}}function buildCuratorDecisionEvent(change,proposal){return{...change,proposalOperation:proposal.operation}}function normalizeTags(tags){return Array.from(new Set(tags.map((tag)=>tag.toLowerCase().replace(/[^\w-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")).filter(Boolean))).slice(0,32)}var CURATOR_PROMOTED_MEMORY_MAX_TEXT_LENGTH=500;var init_curator_decision_helpers=__esm(()=>{init_config3();init_errors6();init_schema2()});function resolveMemoryRecallProfile(agentRole){let role=normalizeMemoryAgentRole(agentRole);return MEMORY_RECALL_PROFILES[role]??MEMORY_RECALL_PROFILES.coder}function normalizeMemoryAgentRole(agentRole){let base=stripKnownSwarmPrefix(agentRole??"architect");if(base==="reviewer"||base==="test_engineer")return"qa";if(base==="critic"||base==="critic_sounding_board"||base==="critic_drift_verifier"||base==="critic_hallucination_verifier"||base==="critic_architecture_supervisor")return"security";if(base==="curator_init"||base==="curator_phase"||base==="curator_postmortem")return"curator";if(base==="docs")return"sme";if(base==="architect"||base==="sme"||base==="coder"||base==="security"||base==="curator")return base;return"coder"}var MEMORY_RECALL_PROFILES;var init_role_profiles=__esm(()=>{init_schema();MEMORY_RECALL_PROFILES={architect:{kinds:["project_fact","architecture_decision","repo_convention","failure_pattern","security_note"],maxItems:10,tokenBudget:1600},sme:{kinds:["api_finding","code_pattern","repo_convention","failure_pattern","evidence"],maxItems:8,tokenBudget:1200},coder:{kinds:["architecture_decision","repo_convention","code_pattern","test_pattern","failure_pattern"],maxItems:8,tokenBudget:1200},qa:{kinds:["test_pattern","failure_pattern","repo_convention","security_note"],maxItems:8,tokenBudget:1200},security:{kinds:["security_note","architecture_decision","repo_convention","evidence"],maxItems:8,tokenBudget:1200},curator:{kinds:["project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence"],maxItems:20,tokenBudget:3000}}});function tokenize(text){return new Set(text.toLowerCase().replace(/[^\w\s-]/g," ").split(/\s+/).map((token)=>token.trim()).filter(Boolean))}function jaccard(a,b){if(a.size===0&&b.size===0)return 0;let intersection3=0;for(let token of a)if(b.has(token))intersection3++;let union3=a.size+b.size-intersection3;return union3===0?0:intersection3/union3}function clusterByJaccard(items,getText,threshold){let clusters=[];for(let item of items){let tokens=tokenize(getText(item)),placed=!1;for(let cluster of clusters)if(jaccard(tokens,cluster.tokens)>=threshold){cluster.members.push(item),placed=!0;break}if(!placed)clusters.push({tokens,members:[item]})}return clusters.map((cluster)=>cluster.members)}function importanceScore(input,weights){let recency=input.daysSinceLastRecall===null?0:Math.exp(-weights.lambda*Math.max(0,input.daysSinceLastRecall)),denom=Math.log1p(Math.max(1,weights.n)),frequency=denom===0?0:Math.log1p(Math.max(0,input.retrievalCount))/denom,freshness=Math.exp(-weights.mu*Math.max(0,input.daysSinceCreated)),confidence=Math.min(1,Math.max(0,input.confidence));return weights.wRecency*recency+weights.wFrequency*frequency+weights.wFreshness*freshness+weights.wConfidence*confidence}function normalizeKindText(kind){return kind.replace(/_/g," ")}function collectMetadataStrings(metadata,keys){let values=[];for(let key of keys){let value=metadata[key];if(typeof value==="string")values.push(value);if(Array.isArray(value)){for(let item of value)if(typeof item==="string")values.push(item)}}return values}function overlap(a,b){if(a.size===0||b.size===0)return 0;let hits=0;for(let token of a)if(b.has(token))hits++;return hits/Math.max(a.size,1)}function scopeSpecificityBoost(scope){switch(scope.type){case"agent":return 1;case"run":return 0.9;case"repository":return 0.8;case"project":return 0.65;case"workspace":return 0.45;case"global_user":return 0.3}}function kindProfileBoost(kind,request){if(!request.kinds||request.kinds.length===0)return 0.5;return request.kinds.includes(kind)?1:0}function roleProfileBoost(kind,context){return context.roleProfileKinds?.has(kind)?1:0}function sameScope(a,b){return stableScopeKey(a)===stableScopeKey(b)}function scopeAllowed(recordScope,allowedScopes){return allowedScopes.some((scope)=>sameScope(recordScope,scope))}function scoreMemoryRecordDetailed(record3,request,context){if(!request.includeExpired&&isExpired(record3))return{item:null,skipReason:"filtered"};if(record3.supersededBy)return{item:null,skipReason:"filtered"};if(record3.metadata.deleted===!0)return{item:null,skipReason:"filtered"};let qValue=memoryQValue(record3),suppressionThreshold=request.suppressionThreshold??0;if(request.includeLowQ!==!0&&suppressionThreshold>0&&qValue<suppressionThreshold)return{item:null,skipReason:"filtered"};if(!scopeAllowed(record3.scope,request.scopes))return{item:null,skipReason:"filtered"};if(request.kinds&&!request.kinds.includes(record3.kind))return{item:null,skipReason:"filtered"};let queryTokens=request.mode==="injection"&&context.taskTokens?context.taskTokens:context.queryTokens,textTokens=tokenize(record3.text),tagTokens=tokenize(record3.tags.join(" ")),fileTokens=tokenize([record3.source.filePath,...collectMetadataStrings(record3.metadata,["file","filePath","files","touchedFiles"])].filter((value)=>typeof value==="string").join(" ")),symbolTokens=tokenize(collectMetadataStrings(record3.metadata,["symbol","symbols"]).join(" ")),kindTokens=tokenize(normalizeKindText(record3.kind)),sourceRefTokens=tokenize(record3.source.ref??""),taskSearchTokens=unionTokens(textTokens,tagTokens,fileTokens,symbolTokens,kindTokens,sourceRefTokens),taskTermOverlap=context.taskTokens?overlap(context.taskTokens,taskSearchTokens):0,kindQueryOverlap=overlap(queryTokens,kindTokens),textOverlap=overlap(queryTokens,textTokens),tagOverlap=overlap(queryTokens,tagTokens),fileOverlap=overlap(queryTokens,fileTokens),symbolOverlap=overlap(queryTokens,symbolTokens),kindMatch=request.kinds?.includes(record3.kind)??!1,scopeMatch=scopeAllowed(record3.scope,request.scopes),roleBoost=roleProfileBoost(record3.kind,context),hasQuerySignal=textOverlap>0||tagOverlap>0||fileOverlap>0||symbolOverlap>0||kindQueryOverlap>0;if(request.mode==="injection"&&request.requireQuerySignal!==!1&&!hasQuerySignal)return{item:null,skipReason:"no_signal"};let score=textOverlap*SCORING_WEIGHTS.textOverlap+tagOverlap*SCORING_WEIGHTS.tagOverlap+fileOverlap*SCORING_WEIGHTS.fileOverlap+symbolOverlap*SCORING_WEIGHTS.symbolOverlap+taskTermOverlap*SCORING_WEIGHTS.taskTermOverlap+scopeSpecificityBoost(record3.scope)*SCORING_WEIGHTS.scopeSpecificityBoost+kindProfileBoost(record3.kind,request)*SCORING_WEIGHTS.kindProfileBoost+roleBoost*SCORING_WEIGHTS.roleBoost+record3.confidence*SCORING_WEIGHTS.confidence+(qValue-DEFAULT_MEMORY_Q_VALUE)*(request.qValueBoostWeight??0),reasonParts=[textOverlap>0?`text_overlap=${textOverlap.toFixed(2)}`:null,tagOverlap>0?`tag_overlap=${tagOverlap.toFixed(2)}`:null,fileOverlap>0?`file_overlap=${fileOverlap.toFixed(2)}`:null,symbolOverlap>0?`symbol_overlap=${symbolOverlap.toFixed(2)}`:null,taskTermOverlap>0?`task_terms=${taskTermOverlap.toFixed(2)}`:null,kindQueryOverlap>0?`kind_query=${kindQueryOverlap.toFixed(2)}`:null,roleBoost>0?"role_profile":null,request.qValueBoostWeight&&request.qValueBoostWeight>0?`q_value=${qValue.toFixed(2)}`:null,`scope=${record3.scope.type}`,`confidence=${record3.confidence.toFixed(2)}`].filter(Boolean);return{item:{record:record3,score,reason:reasonParts.join(", "),signals:{textOverlap,tagOverlap,fileOverlap,symbolOverlap,qValue,kindMatch,scopeMatch}}}}function memoryQValue(record3){if(typeof record3.qValue==="number"&&Number.isFinite(record3.qValue))return clamp01(record3.qValue);let metadataValue=record3.metadata.qValue;if(typeof metadataValue==="number"&&Number.isFinite(metadataValue))return clamp01(metadataValue);return DEFAULT_MEMORY_Q_VALUE}function clamp01(value){return Math.min(1,Math.max(0,value))}function scoreMemoryRecordsWithDiagnostics(records,request){let minScore=request.minScore??0,context=createScoringContext(request),diagnostics={candidateCount:records.length,preScoredFilteredCount:0,scoredCount:0,returnedCount:0,noSignalCount:0,belowThresholdCount:0},items=[];for(let record3 of records){let result=scoreMemoryRecordDetailed(record3,request,context);if(!result.item){if(result.skipReason==="filtered")diagnostics.preScoredFilteredCount++;if(result.skipReason==="no_signal")diagnostics.noSignalCount++;continue}if(diagnostics.scoredCount++,result.item.score<minScore){diagnostics.belowThresholdCount++;continue}items.push(result.item)}return items.sort((a,b)=>b.score-a.score||a.record.id.localeCompare(b.record.id)),diagnostics.returnedCount=items.length,{items,diagnostics}}function createScoringContext(request){return{taskTokens:request.task?tokenize(request.task):void 0,queryTokens:tokenize(request.query),roleProfileKinds:request.agentRole?new Set(resolveMemoryRecallProfile(request.agentRole).kinds):void 0}}function unionTokens(...sets){let union3=new Set;for(let set3 of sets)for(let token of set3)union3.add(token);return union3}var SCORING_WEIGHTS,DEFAULT_MEMORY_Q_VALUE=0.5;var init_scoring=__esm(()=>{init_role_profiles();init_schema2();SCORING_WEIGHTS={textOverlap:0.38,tagOverlap:0.16,fileOverlap:0.12,symbolOverlap:0.08,taskTermOverlap:0.08,scopeSpecificityBoost:0.12,kindProfileBoost:0.06,roleBoost:0.05,confidence:0.08}});async function buildMemoryMaintenanceReport(provider,options={}){let now=options.now??new Date,limit=Math.max(1,Math.trunc(options.limit??20)),memories=await provider.list({includeExpired:!0,includeInactive:!0}),proposals=await loadMaintenanceProposals(provider,limit),recallUsage=provider.listRecallUsage?await provider.listRecallUsage():[],suppressionValueLog=provider.listMemoryValueLog?await provider.listMemoryValueLog({includeSuppressionCandidatesOnly:!0,limit}):[],promotionValueLog=provider.listMemoryValueLog?await provider.listMemoryValueLog({includePromotionCandidatesOnly:!0,limit}):[],usageByMemory=summarizeRecallByMemory(recallUsage),usageByRole=summarizeRecallByRole(recallUsage),activeMemories=memories.filter((memory)=>isActiveMemory(memory,now)),deletedMemories=memories.filter((memory)=>memory.metadata.deleted===!0),expiredScratchMemories=memories.filter((memory)=>memory.kind==="scratch"&&isExpired(memory,now)),supersededMemories=memories.filter((memory)=>Boolean(memory.supersededBy)),lowUtilityMemories=activeMemories.filter((memory)=>isLowUtility(memory,usageByMemory,now,{weights:options.importanceWeights??DEFAULT_IMPORTANCE_WEIGHTS,threshold:options.importanceThreshold??DEFAULT_IMPORTANCE_THRESHOLD})).sort(memorySort),neverRecalledMemories=activeMemories.filter((memory)=>!usageByMemory.has(memory.id)).sort(memorySort),rejectedProposalReasons=proposals.filter((proposal)=>proposal.status==="rejected").sort(proposalSort),pendingProposals=proposals.filter((proposal)=>proposal.status==="pending").sort(proposalSort);return{generatedAt:now.toISOString(),totalMemories:memories.length,activeMemories:activeMemories.length,deletedMemories:deletedMemories.slice(0,limit),expiredScratchMemories:expiredScratchMemories.slice(0,limit),supersededMemories:supersededMemories.slice(0,limit),supersededChains:buildSupersededChains(memories).slice(0,limit),lowUtilityMemories:lowUtilityMemories.slice(0,limit),lowQValueMemories:suppressionValueLog.slice(0,limit),promotionCandidates:promotionValueLog.slice(0,limit),neverRecalledMemories:neverRecalledMemories.slice(0,limit),mostRecalledMemories:Array.from(usageByMemory.values()).sort((a,b)=>b.count-a.count||b.lastRecalledAt.localeCompare(a.lastRecalledAt)||a.memoryId.localeCompare(b.memoryId)).slice(0,limit),recallByAgentRole:Array.from(usageByRole.values()).sort((a,b)=>b.count-a.count||a.agentRole.localeCompare(b.agentRole)).slice(0,limit),rejectedProposalReasons:rejectedProposalReasons.slice(0,limit),pendingProposals:pendingProposals.slice(0,limit),recallEventCount:recallUsage.length}}function shouldCompactMemory(memory,now=new Date){if(memory.metadata.deleted===!0)return"deleted";if(memory.supersededBy)return"superseded";if(memory.kind==="scratch"&&isExpired(memory,now))return"expired_scratch";return null}function isActiveMemory(memory,now){return memory.metadata.deleted!==!0&&!memory.supersededBy&&!isExpired(memory,now)}function isLowUtility(memory,usageByMemory,now,options){if(usageByMemory.has(memory.id))return!1;let created=Date.parse(memory.createdAt),daysSinceCreated=Number.isFinite(created)?Math.max(0,(now.getTime()-created)/MS_PER_DAY2):0;return importanceScore({confidence:memory.confidence,retrievalCount:0,daysSinceLastRecall:null,daysSinceCreated},options.weights)<options.threshold}function summarizeRecallByMemory(usageEvents){let byMemory=new Map;for(let event of usageEvents)event.memoryIds.forEach((memoryId,index)=>{let role=event.agentRole??"unknown",existing=byMemory.get(memoryId)??{memoryId,count:0,lastRecalledAt:event.timestamp,agentRoles:{},averageScore:0,scoreTotal:0,scoreCount:0};existing.count++,existing.lastRecalledAt=event.timestamp>existing.lastRecalledAt?event.timestamp:existing.lastRecalledAt,existing.agentRoles[role]=(existing.agentRoles[role]??0)+1;let score=event.scores[index];if(typeof score==="number"&&Number.isFinite(score))existing.scoreTotal+=score,existing.scoreCount++,existing.averageScore=existing.scoreTotal/existing.scoreCount;byMemory.set(memoryId,existing)});return new Map(Array.from(byMemory,([memoryId,value])=>[memoryId,{memoryId,count:value.count,lastRecalledAt:value.lastRecalledAt,agentRoles:value.agentRoles,averageScore:value.averageScore}]))}async function loadMaintenanceProposals(provider,limit){if(!provider.listProposals)return[];let[pending,rejected,recent]=await Promise.all([provider.listProposals({status:"pending",limit}),provider.listProposals({status:"rejected",limit}),provider.listProposals({limit:Math.max(limit*4,100)})]),byId=new Map;for(let proposal of[...pending,...rejected,...recent])byId.set(proposal.id,proposal);return Array.from(byId.values())}function summarizeRecallByRole(usageEvents){let byRole=new Map;for(let event of usageEvents){let role=event.agentRole??"unknown",existing=byRole.get(role)??{agentRole:role,count:0,memoryIds:{}};existing.count++;for(let memoryId of event.memoryIds)existing.memoryIds[memoryId]=(existing.memoryIds[memoryId]??0)+1;byRole.set(role,existing)}return byRole}function buildSupersededChains(memories){let byId=new Map(memories.map((memory)=>[memory.id,memory])),supersededIds=new Set(memories.filter((memory)=>memory.supersededBy).map((memory)=>memory.id));return memories.filter((memory)=>memory.supersededBy&&!(memory.supersedes??[]).some((id)=>supersededIds.has(id))).map((root)=>{let chain=[root.id],seen=new Set(chain),cursor=root;while(cursor?.supersededBy&&!seen.has(cursor.supersededBy))chain.push(cursor.supersededBy),seen.add(cursor.supersededBy),cursor=byId.get(cursor.supersededBy);return{rootId:root.id,chain,reason:typeof root.metadata.supersedeReason==="string"?root.metadata.supersedeReason:void 0}})}function memorySort(a,b){return b.updatedAt.localeCompare(a.updatedAt)||a.id.localeCompare(b.id)}function proposalSort(a,b){let aTime=a.reviewedAt??a.createdAt;return(b.reviewedAt??b.createdAt).localeCompare(aTime)||a.id.localeCompare(b.id)}var DEFAULT_IMPORTANCE_WEIGHTS,DEFAULT_IMPORTANCE_THRESHOLD=0.2,MS_PER_DAY2=86400000;var init_maintenance=__esm(()=>{init_schema2();init_scoring();DEFAULT_IMPORTANCE_WEIGHTS={wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50}});import{randomUUID as randomUUID7}from"node:crypto";import{existsSync as existsSync46}from"node:fs";import{appendFile as appendFile9,mkdir as mkdir18,readFile as readFile20,rename as rename10,writeFile as writeFile16}from"node:fs/promises";import*as path79 from"node:path";class LocalJsonlMemoryProvider{name="local-jsonl";rootDirectory;config;initialized=!1;memories=new Map;proposals=new Map;constructor(rootDirectory,config3={}){this.rootDirectory=rootDirectory,this.config={...DEFAULT_MEMORY_CONFIG,...config3}}pathFor(file3){let storageDir=this.config.storageDir.replace(/^\.swarm[/\\]?/,""),filename=file3==="memories"?"memories.jsonl":file3==="proposals"?"proposals.jsonl":"audit.jsonl";return validateSwarmPath(this.rootDirectory,path79.join(storageDir,filename))}async initialize(){if(this.initialized)return;let memoryPath=this.pathFor("memories"),proposalPath2=this.pathFor("proposals"),memoryLoad=validateLoadedMemories(await readJsonl(memoryPath),this.config),proposalLoad=validateLoadedProposals(await readJsonl(proposalPath2),this.config);if(this.memories=new Map(memoryLoad.records.map((record3)=>[record3.id,record3])),this.proposals=new Map(proposalLoad.records.map((proposal)=>[proposal.id,proposal])),this.initialized=!0,memoryLoad.invalidCount>0)await this.audit("invalid_load","memories",`${memoryLoad.invalidCount} invalid memory JSONL row(s) skipped`);if(proposalLoad.invalidCount>0)await this.audit("invalid_load","proposals",`${proposalLoad.invalidCount} invalid proposal JSONL row(s) skipped`)}async upsert(record3){await this.initialize();let existing=this.memories.get(record3.id);if(existing?.metadata.deleted===!0)throw new MemoryValidationError("memory is tombstoned and cannot be upserted");let next=validateMemoryRecordRules({...record3,createdAt:existing?.createdAt??record3.createdAt},{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets});return this.memories.set(next.id,next),await appendJsonl(this.pathFor("memories"),next),await this.audit("upsert",next.id),next}async get(id){return await this.initialize(),this.memories.get(id)??null}async delete(id,reason){await this.initialize();let existing=this.memories.get(id);if(!existing)return;if(this.config.hardDelete)this.memories.delete(id),await this.compact();else{let tombstone={...existing,updatedAt:new Date().toISOString(),metadata:{...existing.metadata,deleted:!0,deleteReason:reason}};this.memories.set(id,tombstone),await appendJsonl(this.pathFor("memories"),tombstone)}await this.audit("delete",id,reason)}async recall(request){return(await this.recallWithDiagnostics(request)).items}async recallWithDiagnostics(request){await this.initialize();let records=await this.list({scopes:request.scopes,kinds:request.kinds,includeExpired:request.includeExpired}),result=scoreMemoryRecordsWithDiagnostics(records,request);return{items:result.items.slice(0,request.maxItems),diagnostics:{...result.diagnostics,returnedCount:Math.min(result.diagnostics.returnedCount,request.maxItems)}}}async recordRecallUsage(event){await this.initialize(),await this.audit("recall",event.bundleId,void 0,event)}async listRecallUsage(filter={}){await this.initialize();let events=await readAuditEvents(this.pathFor("audit")),usage=[];for(let event of events){if(event.operation!=="recall")continue;let parsed=parseRecallUsageEvent(event);if(parsed)usage.push(parsed)}return usage.sort((a,b)=>b.timestamp.localeCompare(a.timestamp)),usage.slice(0,filter.limit??usage.length)}async list(filter={}){await this.initialize();let records=Array.from(this.memories.values());if(filter.scopes&&filter.scopes.length>0)records=records.filter((record3)=>scopeAllowed(record3.scope,filter.scopes??[]));if(filter.kinds&&filter.kinds.length>0)records=records.filter((record3)=>filter.kinds?.includes(record3.kind));if(!filter.includeExpired){let now=Date.now();records=records.filter((record3)=>{if(!record3.expiresAt)return!0;let expires=Date.parse(record3.expiresAt);return!Number.isFinite(expires)||expires>now})}if(!filter.includeInactive)records=records.filter((record3)=>!record3.supersededBy&&record3.metadata.deleted!==!0);return records.sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt)),records.slice(0,filter.limit??records.length)}async createProposal(proposal){await this.initialize();let next=validateMemoryProposal(proposal);return this.proposals.set(next.id,next),await appendJsonl(this.pathFor("proposals"),next),await this.audit("proposal",next.id),next}async listProposals(filter={}){await this.initialize();let proposals=Array.from(this.proposals.values());if(filter.status)proposals=proposals.filter((proposal)=>proposal.status===filter.status);return proposals.sort((a,b)=>b.createdAt.localeCompare(a.createdAt)),proposals.slice(0,filter.limit??proposals.length)}async applyCuratorDecision(decision){await this.initialize();let appliedAt=new Date().toISOString(),proposal=this.proposals.get(decision.proposalId);if(!proposal)throw new MemoryValidationError("memory proposal was not found");if(proposal.status!=="pending")throw new MemoryValidationError("memory proposal is not pending");validateDecisionMatchesProposal(decision,proposal);let memoryId,targetMemoryId,oldMemoryId,replacementMemoryId;if(decision.action==="add"){let memory=this.validateDecisionMemory({...decision.memory,updatedAt:appliedAt});validateCuratorPromotableMemory(memory),this.memories.set(memory.id,memory),await appendJsonl(this.pathFor("memories"),memory),memoryId=memory.id}else if(decision.action==="update"){let existing=this.activeMemory(decision.targetMemoryId),updated=this.validateDecisionMemory(applyPatchToMemory(existing,decision.patch,appliedAt));if(validateCuratorPromotableMemory(updated),updated.id!==existing.id){let tombstone=this.validateDecisionMemory({...existing,updatedAt:appliedAt,metadata:{...existing.metadata,deleted:!0,deleteReason:decision.reason,updateReplacementId:updated.id}});this.memories.set(tombstone.id,tombstone),await appendJsonl(this.pathFor("memories"),tombstone)}this.memories.set(updated.id,updated),await appendJsonl(this.pathFor("memories"),updated),memoryId=updated.id,targetMemoryId=existing.id}else if(decision.action==="supersede"){let oldMemory=this.activeMemory(decision.oldMemoryId),replacement=this.validateDecisionMemory({...decision.replacement,updatedAt:appliedAt,supersedes:Array.from(new Set([...decision.replacement.supersedes??[],oldMemory.id]))});validateCuratorPromotableMemory(replacement);let superseded=this.validateDecisionMemory({...oldMemory,updatedAt:appliedAt,supersededBy:replacement.id,metadata:{...oldMemory.metadata,supersedeReason:decision.reason}});this.memories.set(superseded.id,superseded),this.memories.set(replacement.id,replacement),await appendJsonl(this.pathFor("memories"),superseded),await appendJsonl(this.pathFor("memories"),replacement),oldMemoryId=oldMemory.id,replacementMemoryId=replacement.id,memoryId=replacement.id}let proposalStatus=decision.action==="reject"?"rejected":"applied",reviewedProposal=markProposalReviewed(proposal,decision,proposalStatus,appliedAt,{memoryId,targetMemoryId,oldMemoryId,replacementMemoryId});this.proposals.set(reviewedProposal.id,reviewedProposal),await appendJsonl(this.pathFor("proposals"),reviewedProposal);let change={action:decision.action,proposalId:decision.proposalId,proposalStatus,appliedAt,memoryId,targetMemoryId,oldMemoryId,replacementMemoryId,reason:curatorDecisionReason(decision)};return await this.audit("curator_decision",decision.proposalId,change.reason,buildCuratorDecisionEvent(change,proposal)),change}async compact(){await this.initialize(),await writeJsonlAtomic(this.pathFor("memories"),Array.from(this.memories.values())),await this.audit("compact","memories")}async compactMaintenance(options={}){await this.initialize();let now=options.now?new Date(options.now):new Date,kept=[],result={dryRun:options.dryRun!==!1,removedDeleted:0,removedSuperseded:0,removedExpiredScratch:0,remaining:0};for(let memory of this.memories.values()){let compactReason=shouldCompactMemory(memory,now);if(compactReason==="deleted"){result.removedDeleted++;continue}if(compactReason==="superseded"){result.removedSuperseded++;continue}if(compactReason==="expired_scratch"){result.removedExpiredScratch++;continue}kept.push(memory)}if(result.remaining=kept.length,result.dryRun)return result;return this.memories=new Map(kept.map((memory)=>[memory.id,memory])),await writeJsonlAtomic(this.pathFor("memories"),kept),await this.audit("compact","memories","removed deleted, superseded, and expired scratch memories",result),result}async audit(operation,targetId,reason,eventJson){let event={id:randomUUID7(),operation,targetId,reason,eventJson,timestamp:new Date().toISOString()};await appendJsonl(this.pathFor("audit"),event)}activeMemory(memoryId){let memory=this.memories.get(memoryId);if(!memory)throw new MemoryValidationError("target memory was not found");if(memory.metadata.deleted===!0)throw new MemoryValidationError("target memory is deleted");if(memory.supersededBy)throw new MemoryValidationError("target memory is superseded");return memory}validateDecisionMemory(record3){return validateMemoryRecordRules(record3,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets})}}function validateLoadedMemories(values,config3){let records=[],invalidCount=0;for(let value of values)try{records.push(validateMemoryRecordRules(value,{rejectDurableSecrets:config3.redaction.rejectDurableSecrets}))}catch{invalidCount++}return{records,invalidCount}}function validateLoadedProposals(values,config3){let records=[],invalidCount=0;for(let value of values)try{let proposal=validateMemoryProposal(value);if(proposal.proposedRecord)validateMemoryRecordRules(proposal.proposedRecord,{rejectDurableSecrets:config3.redaction.rejectDurableSecrets});records.push(proposal)}catch{invalidCount++}return{records,invalidCount}}async function readJsonl(filePath){if(!existsSync46(filePath))return[];let content=await readFile20(filePath,"utf-8"),records=[];for(let line of content.split(`
1390
1390
  `)){let trimmed=line.trim();if(!trimmed)continue;try{records.push(JSON.parse(trimmed))}catch{}}return records}async function readAuditEvents(filePath){let values=await readJsonl(filePath),events=[];for(let value of values){if(!value||typeof value!=="object")continue;let candidate=value;if(typeof candidate.id!=="string"||typeof candidate.operation!=="string"||typeof candidate.targetId!=="string"||typeof candidate.timestamp!=="string")continue;events.push(candidate)}return events}function parseRecallUsageEvent(event){let raw=event.eventJson??event.reason;if(typeof raw!=="string"&&(!raw||typeof raw!=="object"))return null;try{let parsed=typeof raw==="string"?JSON.parse(raw):raw;if(!Array.isArray(parsed.memoryIds)||typeof parsed.query!=="string")return null;return{bundleId:typeof parsed.bundleId==="string"?parsed.bundleId:event.targetId,query:parsed.query,scopes:Array.isArray(parsed.scopes)?parsed.scopes:[],kinds:Array.isArray(parsed.kinds)?parsed.kinds:void 0,memoryIds:parsed.memoryIds.filter((memoryId)=>typeof memoryId==="string"),scores:Array.isArray(parsed.scores)?parsed.scores.filter((score)=>typeof score==="number"&&Number.isFinite(score)):[],tokenEstimate:typeof parsed.tokenEstimate==="number"?parsed.tokenEstimate:0,agentRole:typeof parsed.agentRole==="string"?parsed.agentRole:void 0,runId:typeof parsed.runId==="string"?parsed.runId:void 0,timestamp:typeof parsed.timestamp==="string"?parsed.timestamp:event.timestamp}}catch{return null}}async function appendJsonl(filePath,value){await mkdir18(path79.dirname(filePath),{recursive:!0}),await appendFile9(filePath,`${JSON.stringify(value)}
1391
1391
  `,"utf-8")}async function writeJsonlAtomic(filePath,values){await mkdir18(path79.dirname(filePath),{recursive:!0});let tmp=`${filePath}.tmp.${randomUUID7()}`,content=values.map((value)=>JSON.stringify(value)).join(`
1392
1392
  `)+(values.length>0?`
@@ -1396,18 +1396,32 @@ ${query}`).digest("hex").slice(0,8);return`bundle_${compactTimestamp}_${hash4}`}
1396
1396
  `;if(selected.length>0&&estimateTokens(candidate)>tokenBudget)break;if(estimateTokens(candidate)>tokenBudget)break;selected.push(item),promptBlock=candidate}return{promptBlock:selected.length>0?promptBlock.trimEnd():header.trimEnd(),tokenEstimate:estimateTokens(promptBlock),items:selected}}function toRecallBundle(input){let block=buildRecallPromptBlock(input.items,input.tokenBudget,input.generatedAt);return{id:input.id,query:input.query,generatedAt:input.generatedAt,items:block.items,tokenEstimate:block.tokenEstimate,promptBlock:block.promptBlock,diagnostics:input.diagnostics}}var init_prompt_block=__esm(()=>{init_utils2();init_redaction()});function normalizeQuery(query){return query.toLowerCase().trim()}function compositeKey(modelVersion,normalizedQuery){return`${modelVersion}\x00${normalizedQuery}`}class EmbeddingCache{cache;maxSize;constructor(maxSize=256){this.maxSize=maxSize,this.cache=new Map}get size(){return this.cache.size}get(modelVersion,query){let key=compositeKey(modelVersion,normalizeQuery(query)),entry=this.cache.get(key);if(entry!==void 0)this.cache.delete(key),this.cache.set(key,entry);return entry}set(modelVersion,query,entry){let key=compositeKey(modelVersion,normalizeQuery(query));if(this.cache.has(key))this.cache.delete(key);else if(this.cache.size>=this.maxSize){let oldestKey=this.cache.keys().next().value;if(oldestKey!==void 0)this.cache.delete(oldestKey)}if(this.cache.size<this.maxSize)this.cache.set(key,entry)}has(modelVersion,query){let key=compositeKey(modelVersion,normalizeQuery(query));return this.cache.has(key)}clear(){this.cache.clear()}}function fuseRankings(lexicalRankedIds,denseRankedIds,metadataRankedIds,weights,rrfK){let lexicalRanks=buildRankMap(lexicalRankedIds),denseRanks=buildRankMap(denseRankedIds),metadataRanks=buildRankMap(metadataRankedIds),allIds=new Set;for(let id of lexicalRankedIds)allIds.add(id);for(let id of denseRankedIds)allIds.add(id);for(let id of metadataRankedIds)allIds.add(id);let candidates=[];for(let id of allIds){let lexicalRank=lexicalRanks.get(id)??null,denseRank=denseRanks.get(id)??null,metadataRank=metadataRanks.get(id)??null,rawScore=(lexicalRank!==null?weights.lexical*rrfTerm(lexicalRank,rrfK):0)+(denseRank!==null?weights.dense*rrfTerm(denseRank,rrfK):0)+(metadataRank!==null?weights.metadata*rrfTerm(metadataRank,rrfK):0);candidates.push({id,fusedScore:rawScore,lexicalRank,denseRank,metadataRank})}return minMaxNormalise(candidates)}function buildRankMap(rankedIds){let map3=new Map;for(let i=0;i<rankedIds.length;i++)map3.set(rankedIds[i],i+1);return map3}function rrfTerm(rank,rrfK){return 1/(rrfK+rank)}function minMaxNormalise(candidates){if(candidates.length===0)return candidates;let min=1/0,max=-1/0;for(let c of candidates){if(c.fusedScore<min)min=c.fusedScore;if(c.fusedScore>max)max=c.fusedScore}let range=max-min,normalised=[];for(let c of candidates){let normalisedScore=range===0?1:(c.fusedScore-min)/range;normalised.push({...c,fusedScore:normalisedScore})}return normalised.sort((a,b)=>b.fusedScore-a.fusedScore||a.id.localeCompare(b.id)),normalised}var EmbeddingUnavailableError,EmbeddingVersionMismatchError;var init_types=__esm(()=>{EmbeddingUnavailableError=class EmbeddingUnavailableError extends Error{constructor(message){super(message??"Embedding provider is unavailable (dependency not installed or model failed to load)");this.name="EmbeddingUnavailableError"}};EmbeddingVersionMismatchError=class EmbeddingVersionMismatchError extends Error{queryVersion;storedVersion;constructor(queryVersion,storedVersion){super(`Embedding version mismatch: query uses ${queryVersion} but stored vectors are ${storedVersion}. Rebuild the index or pin the model version.`);this.name="EmbeddingVersionMismatchError",this.queryVersion=queryVersion,this.storedVersion=storedVersion}}});import{mkdirSync as mkdirSync28}from"node:fs";import{createRequire as createRequire3}from"node:module";import*as os17 from"node:os";import*as path80 from"node:path";function resolveEmbeddingCacheDir(){return _internals55.resolveEmbeddingCacheDir()}class LocalEmbeddingProvider{modelName;dimension;modelVersion;_available=!1;loadFailed=!1;pipeline=null;static downloadNoticePrinted=!1;constructor(config3){this.modelName=config3.model,this.dimension=config3.dimension,this.modelVersion=config3.version??`${config3.model}:${config3.dimension}`}get available(){return this._available}async ensurePipeline(){if(this.loadFailed)return null;if(this.pipeline)return this.pipeline;try{let transformers=createRequire3(import.meta.url)("@xenova/transformers");if(!LocalEmbeddingProvider.downloadNoticePrinted)LocalEmbeddingProvider.downloadNoticePrinted=!0,console.log(`[opencode-swarm] Downloading embedding model "${this.modelName}" (~25 MB) — this happens once per process.`);let cacheDir2=resolveEmbeddingCacheDir();return mkdirSync28(cacheDir2,{recursive:!0}),this.pipeline=await transformers.pipeline("feature-extraction",this.modelName,{cache_dir:cacheDir2}),this._available=!0,this.pipeline}catch(err){return this.loadFailed=!0,this._available=!1,warn("Local embedding provider unavailable — falling back to lexical-only",{reason:err instanceof Error?err.message:String(err)}),null}}async embed(text){let pipeline=await this.ensurePipeline();if(!pipeline)throw new EmbeddingUnavailableError("Embedding provider is unavailable (dependency not installed or model failed to load)");let result=await pipeline(text,{pooling:"mean",normalize:!0});return this.tensorToFloat32Array(result)}async embedBatch(texts){if(texts.length===0)return[];let pipeline=await this.ensurePipeline();if(!pipeline)throw new EmbeddingUnavailableError("Embedding provider is unavailable (dependency not installed or model failed to load)");let result=await pipeline(texts,{pooling:"mean",normalize:!0});if(Array.isArray(result))return result.map((t)=>this.tensorToFloat32Array(t));return this.tensorToFloat32ArrayBatch(result)}tensorToFloat32Array(tensor){if(tensor instanceof Float32Array)return tensor;let obj=tensor;if(obj?.data&&obj.data instanceof Float32Array)return obj.data;let entries=Object.entries(tensor);for(let[,value]of entries)if(value instanceof Float32Array)return value;throw Error(`Unexpected embedding tensor shape: ${JSON.stringify(tensor)}`)}tensorToFloat32ArrayBatch(tensor){let obj=tensor;if(obj?.data&&obj.data instanceof Float32Array&&obj.dims&&obj.dims.length>=2){let batchSize=obj.dims[0],dim=obj.dims[1],result=[];for(let i=0;i<batchSize;i++){let offset=i*dim;result.push(obj.data.slice(offset,offset+dim))}return result}if(Array.isArray(tensor))return tensor.map((t)=>this.tensorToFloat32Array(t));throw Error(`Unexpected batch embedding tensor shape: ${JSON.stringify(tensor)}`)}}var _internals55;var init_local_provider=__esm(()=>{init_utils();init_types();_internals55={resolveEmbeddingCacheDir(){let base;if(process.platform==="win32")base=process.env.LOCALAPPDATA||path80.join(os17.homedir(),"AppData","Local");else if(process.platform==="darwin")base=path80.join(os17.homedir(),"Library","Caches");else base=process.env.XDG_CACHE_HOME||path80.join(os17.homedir(),".cache");let resolved=path80.join(base,"opencode","embeddings");if(resolved.split(path80.sep).includes(".swarm")){let safeDefault=process.platform==="win32"?path80.join(os17.homedir(),"AppData","Local","opencode","embeddings"):process.platform==="darwin"?path80.join(os17.homedir(),"Library","Caches","opencode","embeddings"):path80.join(os17.homedir(),".cache","opencode","embeddings");return warn("Embedding cache dir resolved under .swarm/ — falling back to safe default"),safeDefault}return resolved}}});import{mkdirSync as mkdirSync29}from"node:fs";import{createRequire as createRequire4}from"node:module";import*as os18 from"node:os";import*as path81 from"node:path";function shouldRerank(previousRecallElapsedMs,latencyBudgetMs){return previousRecallElapsedMs<=latencyBudgetMs}class CrossEncoderReranker{options;loadFailed=!1;_available=!1;pipeline=null;constructor(options){this.options=options}get available(){return this._available}async ensurePipeline(){if(this.loadFailed)return null;if(this.pipeline)return this.pipeline;try{let transformers=createRequire4(import.meta.url)("@xenova/transformers"),modelName=this.options.model??"Xenova/ms-marco-MiniLM-L-6-v2",cacheDir2=resolveRerankerCacheDir();return mkdirSync29(cacheDir2,{recursive:!0}),this.pipeline=await transformers.pipeline("text-classification",modelName,{cache_dir:cacheDir2}),this._available=!0,this.pipeline}catch(err){return this.loadFailed=!0,this._available=!1,warn("Cross-encoder reranker unavailable — skipping rerank",{reason:err instanceof Error?err.message:String(err)}),null}}async rerank(candidates,query,topN){if(candidates.length===0)return candidates;let pipeline=await this.ensurePipeline();if(!pipeline)return candidates;try{let inputs=candidates.map((c)=>[query,c.text]),results=await pipeline(inputs,{truncation:!0}),scored=candidates.map((c,idx)=>({...c,score:results[idx]?.score??0}));if(scored.sort((a,b)=>(b.score??0)-(a.score??0)),typeof topN==="number"&&topN>0)return scored.slice(0,topN);return scored}catch(err){return warn("Rerank scoring failed — returning original order",{reason:err instanceof Error?err.message:String(err)}),candidates}}}function resolveRerankerCacheDir(){let base;if(process.platform==="win32")base=process.env.LOCALAPPDATA||path81.join(os18.homedir(),"AppData","Local");else if(process.platform==="darwin")base=path81.join(os18.homedir(),"Library","Caches");else base=process.env.XDG_CACHE_HOME||path81.join(os18.homedir(),".cache");let resolved=path81.join(base,"opencode","embeddings");if(resolved.split(path81.sep).includes(".swarm")){let safeDefault=process.platform==="win32"?path81.join(os18.homedir(),"AppData","Local","opencode","embeddings"):process.platform==="darwin"?path81.join(os18.homedir(),"Library","Caches","opencode","embeddings"):path81.join(os18.homedir(),".cache","opencode","embeddings");return warn("Reranker cache dir resolved under .swarm/ — falling back to safe default"),safeDefault}return resolved}var init_reranker=__esm(()=>{init_utils()});import{existsSync as existsSync47,renameSync as renameSync18,unlinkSync as unlinkSync14}from"node:fs";import{copyFile as copyFile2,mkdir as mkdir19,readFile as readFile21,stat as stat10,writeFile as writeFile17}from"node:fs/promises";import*as path82 from"node:path";function resolveMemoryStorageDir(rootDirectory,config3={}){let storageDir=resolveConfig(config3).storageDir.replace(/^\.swarm[/\\]?/,"");return validateSwarmPath(rootDirectory,storageDir)}function resolveSqliteDatabasePath(rootDirectory,config3={}){let relativePath=resolveConfig(config3).sqlite.path.replace(/^\.swarm[/\\]?/,"");return validateSwarmPath(rootDirectory,relativePath)}async function readLegacyJsonl(rootDirectory,config3={}){let resolved=resolveConfig(config3),storageDir=resolveMemoryStorageDir(rootDirectory,resolved),memoryLoad=await readMemoryJsonl(path82.join(storageDir,"memories.jsonl"),resolved),proposalLoad=await readProposalJsonl(path82.join(storageDir,"proposals.jsonl"),resolved);return{memories:memoryLoad.records,proposals:proposalLoad.records,invalidRows:[...memoryLoad.invalidRows,...proposalLoad.invalidRows],totalRows:memoryLoad.totalRows+proposalLoad.totalRows}}async function backupLegacyJsonl(rootDirectory,config3={}){let storageDir=resolveMemoryStorageDir(rootDirectory,config3),backupDir=path82.join(storageDir,"backups");await mkdir19(backupDir,{recursive:!0});let results=[];for(let filename of["memories.jsonl","proposals.jsonl"]){let source=path82.join(storageDir,filename);if(!existsSync47(source))continue;let backup=path82.join(backupDir,`${filename}.pre-sqlite-migration`);if(existsSync47(backup)){results.push({source,backup,created:!1});continue}await copyFile2(source,backup),results.push({source,backup,created:!0})}return results}async function writeJsonlExport(rootDirectory,config3,memories,proposals){let exportDir=path82.join(resolveMemoryStorageDir(rootDirectory,config3),"export");await mkdir19(exportDir,{recursive:!0});let memoriesPath=path82.join(exportDir,"memories.jsonl"),proposalsPath=path82.join(exportDir,"proposals.jsonl"),memoriesTempPath=path82.join(path82.dirname(memoriesPath),`${path82.basename(memoriesPath)}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await writeFile17(memoriesTempPath,toJsonl(memories),"utf-8"),renameSync18(memoriesTempPath,memoriesPath)}catch(err){try{unlinkSync14(memoriesTempPath)}catch{}throw err}let proposalsTempPath=path82.join(path82.dirname(proposalsPath),`${path82.basename(proposalsPath)}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await writeFile17(proposalsTempPath,toJsonl(proposals),"utf-8"),renameSync18(proposalsTempPath,proposalsPath)}catch(err){try{unlinkSync14(proposalsTempPath)}catch{}throw err}return{directory:exportDir,memoriesPath,proposalsPath}}async function writeMigrationReport(rootDirectory,report,config3={}){let reportPath=path82.join(resolveMemoryStorageDir(rootDirectory,config3),"migration-report.json");await mkdir19(path82.dirname(reportPath),{recursive:!0});let reportTempPath=path82.join(path82.dirname(reportPath),`${path82.basename(reportPath)}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await writeFile17(reportTempPath,`${JSON.stringify(report,null,2)}
1397
1397
  `,"utf-8"),renameSync18(reportTempPath,reportPath)}catch(err){try{unlinkSync14(reportTempPath)}catch{}throw err}return reportPath}async function readMigrationReport(rootDirectory,config3={}){let reportPath=path82.join(resolveMemoryStorageDir(rootDirectory,config3),"migration-report.json");if(!existsSync47(reportPath))return null;try{return JSON.parse(await readFile21(reportPath,"utf-8"))}catch{return null}}async function getLegacyJsonlFileStatus(rootDirectory,config3={}){let storageDir=resolveMemoryStorageDir(rootDirectory,config3),statuses=[];for(let file3 of["memories.jsonl","proposals.jsonl"]){let filePath=path82.join(storageDir,file3),sizeBytes=0;if(existsSync47(filePath))sizeBytes=(await stat10(filePath)).size;statuses.push({file:file3,path:filePath,exists:existsSync47(filePath),sizeBytes})}return statuses}function resolveConfig(config3){return{...DEFAULT_MEMORY_CONFIG,...config3,sqlite:{...DEFAULT_MEMORY_CONFIG.sqlite,...config3.sqlite??{}},recall:{...DEFAULT_MEMORY_CONFIG.recall,...config3.recall??{},injection:{...DEFAULT_MEMORY_CONFIG.recall.injection,...config3.recall?.injection??{}}},writes:{...DEFAULT_MEMORY_CONFIG.writes,...config3.writes??{}},redaction:{...DEFAULT_MEMORY_CONFIG.redaction,...config3.redaction??{}}}}async function readMemoryJsonl(filePath,config3){let rows=await readJsonlRows(filePath),records=[],invalidRows=[];for(let row of rows.rows)try{records.push(validateMemoryRecordRules(row.value,{rejectDurableSecrets:config3.redaction.rejectDurableSecrets}))}catch(err){invalidRows.push({file:"memories.jsonl",line:row.line,error:err instanceof Error?err.message:String(err)})}for(let row of rows.invalidRows)invalidRows.push({file:"memories.jsonl",...row});return{records,invalidRows,totalRows:rows.totalRows}}async function readProposalJsonl(filePath,config3){let rows=await readJsonlRows(filePath),records=[],invalidRows=[];for(let row of rows.rows)try{let proposal=validateMemoryProposal(row.value);if(proposal.proposedRecord)validateMemoryRecordRules(proposal.proposedRecord,{rejectDurableSecrets:config3.redaction.rejectDurableSecrets});records.push(proposal)}catch(err){invalidRows.push({file:"proposals.jsonl",line:row.line,error:err instanceof Error?err.message:String(err)})}for(let row of rows.invalidRows)invalidRows.push({file:"proposals.jsonl",...row});return{records,invalidRows,totalRows:rows.totalRows}}async function readJsonlRows(filePath){if(!existsSync47(filePath))return{rows:[],invalidRows:[],totalRows:0};let content=await readFile21(filePath,"utf-8"),rows=[],invalidRows=[],totalRows=0,lines=content.split(/\r?\n/);for(let index=0;index<lines.length;index++){let trimmed=lines[index].trim();if(!trimmed)continue;totalRows++;try{rows.push({line:index+1,value:JSON.parse(trimmed)})}catch(err){invalidRows.push({line:index+1,error:err instanceof Error?err.message:String(err)})}}return{rows,invalidRows,totalRows}}function toJsonl(values){return values.map((value)=>JSON.stringify(value)).join(`
1398
1398
  `)+(values.length>0?`
1399
- `:"")}var LEGACY_JSONL_MIGRATION_VERSION=2,LEGACY_JSONL_MIGRATION_NAME="legacy_jsonl_import_complete";var init_jsonl_migration=__esm(()=>{init_utils2();init_config3();init_schema2()});import{randomUUID as randomUUID8}from"node:crypto";import{mkdirSync as mkdirSync30}from"node:fs";import{createRequire as createRequire5}from"node:module";import*as path83 from"node:path";function loadDatabaseCtor2(){if(_DatabaseCtor2)return _DatabaseCtor2;return _DatabaseCtor2=createRequire5(import.meta.url)("bun:sqlite").Database,_DatabaseCtor2}class SQLiteMemoryProvider{name="sqlite";rootDirectory;config;initialized=!1;initPromise=null;db=null;ftsAvailable=!1;vecAvailable=!1;embeddingProvider=null;embeddingCache=null;reranker=null;memories=new Map;proposals=new Map;lastAutomaticJsonlMigration=null;recallCountSinceLastCompaction=0;isCompacting=!1;constructor(rootDirectory,config3={}){this.rootDirectory=rootDirectory,this.config={...DEFAULT_MEMORY_CONFIG,...config3,sqlite:{...DEFAULT_MEMORY_CONFIG.sqlite,...config3.sqlite??{}},recall:{...DEFAULT_MEMORY_CONFIG.recall,...config3.recall??{},injection:{...DEFAULT_MEMORY_CONFIG.recall.injection,...config3.recall?.injection??{}}},writes:{...DEFAULT_MEMORY_CONFIG.writes,...config3.writes??{}},redaction:{...DEFAULT_MEMORY_CONFIG.redaction,...config3.redaction??{}},maintenance:{...DEFAULT_MEMORY_CONFIG.maintenance,...config3.maintenance??{}}}}databasePath(){let relativePath=this.config.sqlite.path.replace(/^\.swarm[/\\]?/,"");return validateSwarmPath(this.rootDirectory,relativePath)}async initialize(){if(this.initialized)return;if(!this.initPromise)this.initPromise=this.doInitialize().catch((err)=>{throw this.initPromise=null,err});return this.initPromise}async doInitialize(){let dbPath=this.databasePath();mkdirSync30(path83.dirname(dbPath),{recursive:!0});let Db=loadDatabaseCtor2();this.db=new Db(dbPath),this.db.run("PRAGMA journal_mode = WAL;"),this.db.run("PRAGMA synchronous = NORMAL;");let busyTimeoutMs=Math.min(60000,Math.max(0,Math.trunc(this.config.sqlite.busyTimeoutMs)));if(this.db.run(`PRAGMA busy_timeout = ${busyTimeoutMs};`),this.db.run("PRAGMA foreign_keys = ON;"),this.runMigrations(),this.backfillScopeKeys(),this.ftsAvailable=this.initializeFtsIndex(),this.initializeVecExtension(),this.config.embeddings.enabled&&!this.embeddingProvider){try{this.embeddingProvider=new LocalEmbeddingProvider({model:this.config.embeddings.model,dimension:this.config.embeddings.dimension,version:this.config.embeddings.version})}catch(err){this.embeddingProvider=null,warn("Failed to construct embedding provider — dense retrieval disabled",{reason:err instanceof Error?err.message:String(err)})}try{this.embeddingCache=new EmbeddingCache(this.config.embeddings.cacheSize)}catch(err){this.embeddingCache=null,warn("Failed to construct embedding cache — recall works without cache",{reason:err instanceof Error?err.message:String(err)})}}this.lastAutomaticJsonlMigration=null,await this.migrateLegacyJsonlIfNeeded();let memoryLoad=this.loadMemories(),proposalLoad=this.loadProposals();if(this.memories=new Map(memoryLoad.records.map((record3)=>[record3.id,record3])),this.proposals=new Map(proposalLoad.records.map((proposal)=>[proposal.id,proposal])),this.initialized=!0,memoryLoad.invalidCount>0)await this.event("invalid_load","memory_items",`${memoryLoad.invalidCount} invalid SQLite memory row(s) skipped`);if(proposalLoad.invalidCount>0)await this.event("invalid_load","memory_proposals",`${proposalLoad.invalidCount} invalid SQLite proposal row(s) skipped`)}async upsert(record3){await this.initialize();let existing=this.memories.get(record3.id);if(existing?.metadata.deleted===!0)throw new MemoryValidationError("memory is tombstoned and cannot be upserted");let next=validateMemoryRecordRules({...record3,createdAt:existing?.createdAt??record3.createdAt},{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets});return this.memories.set(next.id,next),this.writeMemory(next),await this.writeMemoryVec(next),await this.event("upsert",next.id),next}async get(id){return await this.initialize(),this.memories.get(id)??null}async delete(id,reason){await this.initialize();let existing=this.memories.get(id);if(!existing)return;if(this.config.hardDelete)this.memories.delete(id),this.requireDb().run("DELETE FROM memory_items WHERE id = ?",[id]),this.deleteMemoryFts(id),this.deleteMemoryVec(id);else{let tombstone={...existing,updatedAt:new Date().toISOString(),metadata:{...existing.metadata,deleted:!0,deleteReason:reason}};this.memories.set(id,tombstone),this.writeMemory(tombstone)}await this.event("delete",id,reason)}async recall(request){return(await this.recallWithDiagnostics(request)).items}async recallWithDiagnostics(request){if(await this.initialize(),!this.config.embeddings.enabled||!this.vecAvailable||!this.embeddingProvider){let scopedRecords2=await this.list({scopes:request.scopes,kinds:request.kinds,includeExpired:request.includeExpired,limit:RECALL_CANDIDATE_LIMIT}),candidates=this.selectRecallCandidates(request,scopedRecords2),result=scoreMemoryRecordsWithDiagnostics(candidates.records,request),reranked=candidates.ftsOrder?rerankWithFts(result.items,candidates.ftsOrder):result.items;return{items:reranked.slice(0,request.maxItems),diagnostics:{...result.diagnostics,returnedCount:Math.min(reranked.length,request.maxItems)}}}let recallElapsedStart=Date.now(),scopedRecords=await this.list({scopes:request.scopes,kinds:request.kinds,includeExpired:request.includeExpired,limit:RECALL_CANDIDATE_LIMIT}),lexicalCandidates=this.selectRecallCandidates(request,scopedRecords),lexicalResult=scoreMemoryRecordsWithDiagnostics(lexicalCandidates.records,request),lexicalReranked=lexicalCandidates.ftsOrder?rerankWithFts(lexicalResult.items,lexicalCandidates.ftsOrder):lexicalResult.items,lexicalIds=lexicalReranked.map((item)=>item.record.id),denseIds=[];try{let modelVersion=this.embeddingProvider.modelVersion,normalizedQuery=normalizeMemoryText(request.query).toLowerCase(),queryEmbedding=this.embeddingCache?.get(modelVersion,normalizedQuery)?.vector??null;if(queryEmbedding===null)queryEmbedding=await this.embeddingProvider.embed(normalizedQuery),this.embeddingCache?.set(modelVersion,normalizedQuery,{vector:queryEmbedding,modelVersion,queryHash:normalizedQuery});denseIds=(await this.selectDenseCandidates(request,queryEmbedding)).map((record3)=>record3.id)}catch(err){if(err instanceof EmbeddingVersionMismatchError||err instanceof EmbeddingUnavailableError)warn("Dense retrieval failed — falling back to lexical-only",{reason:err instanceof Error?err.message:String(err)});else warn("Dense retrieval failed — falling back to lexical-only",{reason:err instanceof Error?err.message:String(err)});return{items:lexicalReranked.slice(0,request.maxItems),diagnostics:{...lexicalResult.diagnostics,returnedCount:Math.min(lexicalReranked.length,request.maxItems)}}}let metadataIds=buildMetadataRankedIds(lexicalReranked,request),weights=this.config.retrieval.weights,rrfK=this.config.retrieval.rrfK,fused=fuseRankings(lexicalIds,denseIds,metadataIds,weights,rrfK),lexicalItemMap=new Map(lexicalReranked.map((item)=>[item.record.id,item])),minScore=request.minScore??this.config.recall.minScore,fusedItems=[];for(let candidate of fused){if(candidate.fusedScore<minScore)continue;let lexicalItem=lexicalItemMap.get(candidate.id);if(lexicalItem)fusedItems.push({record:lexicalItem.record,score:candidate.fusedScore,reason:`${lexicalItem.reason}, rrf_fused=${candidate.fusedScore.toFixed(4)}`,signals:lexicalItem.signals});else{let record3=this.memories.get(candidate.id);if(record3)fusedItems.push({record:record3,score:candidate.fusedScore,reason:`rrf_fused=${candidate.fusedScore.toFixed(4)}`,signals:{textOverlap:0,tagOverlap:0,fileOverlap:0,symbolOverlap:0,kindMatch:!1,scopeMatch:!1}})}}let previousRecallElapsedMs=Date.now()-recallElapsedStart,rerankedItems=fusedItems;if(this.config.retrieval.rerank.enabled&&shouldRerank(previousRecallElapsedMs,this.config.retrieval.latencyBudgetMs))try{if(!this.reranker)this.reranker=new CrossEncoderReranker({model:this.config.retrieval.rerank.model});let topN=Math.min(20,fusedItems.length),rerankCandidates=fusedItems.slice(0,topN).map((item)=>({id:item.record.id,text:item.record.text,score:item.score})),rerankResult=await this.reranker.rerank(rerankCandidates,request.query,topN),topNPrefix=fusedItems.slice(0,topN),tail=fusedItems.slice(topN),rerankOrder=new Map(rerankResult.map((c,idx)=>[c.id,idx]));rerankedItems=[...[...topNPrefix].sort((a,b)=>(rerankOrder.get(a.record.id)??0)-(rerankOrder.get(b.record.id)??0)),...tail]}catch(err){warn("Rerank failed — returning fused order",{reason:err instanceof Error?err.message:String(err)}),rerankedItems=fusedItems}return{items:rerankedItems.slice(0,request.maxItems),diagnostics:{...lexicalResult.diagnostics,returnedCount:Math.min(rerankedItems.length,request.maxItems),fusionActive:!0}}}async recordRecallUsage(event){await this.initialize(),this.requireDb().run(`INSERT INTO memory_recall_usage (
1399
+ `:"")}var LEGACY_JSONL_MIGRATION_VERSION=2,LEGACY_JSONL_MIGRATION_NAME="legacy_jsonl_import_complete";var init_jsonl_migration=__esm(()=>{init_utils2();init_config3();init_schema2()});import{randomUUID as randomUUID8}from"node:crypto";import{mkdirSync as mkdirSync30}from"node:fs";import{createRequire as createRequire5}from"node:module";import*as path83 from"node:path";function loadDatabaseCtor2(){if(_DatabaseCtor2)return _DatabaseCtor2;return _DatabaseCtor2=createRequire5(import.meta.url)("bun:sqlite").Database,_DatabaseCtor2}class SQLiteMemoryProvider{name="sqlite";rootDirectory;config;initialized=!1;initPromise=null;db=null;ftsAvailable=!1;vecAvailable=!1;embeddingProvider=null;embeddingCache=null;reranker=null;memories=new Map;proposals=new Map;lastAutomaticJsonlMigration=null;recallCountSinceLastCompaction=0;isCompacting=!1;_internals={writeMemory:(record3)=>this.writeMemory(record3),setEmbeddingProvider:(provider)=>{this.embeddingProvider=provider}};constructor(rootDirectory,config3={}){this.rootDirectory=rootDirectory,this.config=resolveMemoryConfig(config3)}databasePath(){let relativePath=this.config.sqlite.path.replace(/^\.swarm[/\\]?/,"");return validateSwarmPath(this.rootDirectory,relativePath)}async initialize(){if(this.initialized)return;if(!this.initPromise)this.initPromise=this.doInitialize().catch((err)=>{throw this.initPromise=null,err});return this.initPromise}async doInitialize(){let dbPath=this.databasePath();mkdirSync30(path83.dirname(dbPath),{recursive:!0});let Db=loadDatabaseCtor2();this.db=new Db(dbPath),this.db.run("PRAGMA journal_mode = WAL;"),this.db.run("PRAGMA synchronous = NORMAL;");let busyTimeoutMs=Math.min(60000,Math.max(0,Math.trunc(this.config.sqlite.busyTimeoutMs)));if(this.db.run(`PRAGMA busy_timeout = ${busyTimeoutMs};`),this.db.run("PRAGMA foreign_keys = ON;"),this.runMigrations(),this.backfillScopeKeys(),this.ftsAvailable=this.initializeFtsIndex(),this.initializeVecExtension(),this.config.embeddings.enabled&&!this.embeddingProvider){try{this.embeddingProvider=new LocalEmbeddingProvider({model:this.config.embeddings.model,dimension:this.config.embeddings.dimension,version:this.config.embeddings.version})}catch(err){this.embeddingProvider=null,warn("Failed to construct embedding provider — dense retrieval disabled",{reason:err instanceof Error?err.message:String(err)})}try{this.embeddingCache=new EmbeddingCache(this.config.embeddings.cacheSize)}catch(err){this.embeddingCache=null,warn("Failed to construct embedding cache — recall works without cache",{reason:err instanceof Error?err.message:String(err)})}}this.lastAutomaticJsonlMigration=null,await this.migrateLegacyJsonlIfNeeded();let memoryLoad=this.loadMemories(),proposalLoad=this.loadProposals();if(this.memories=new Map(memoryLoad.records.map((record3)=>[record3.id,record3])),this.proposals=new Map(proposalLoad.records.map((proposal)=>[proposal.id,proposal])),this.initialized=!0,memoryLoad.invalidCount>0)await this.event("invalid_load","memory_items",`${memoryLoad.invalidCount} invalid SQLite memory row(s) skipped`);if(proposalLoad.invalidCount>0)await this.event("invalid_load","memory_proposals",`${proposalLoad.invalidCount} invalid SQLite proposal row(s) skipped`)}async upsert(record3){await this.initialize();let existing=this.memories.get(record3.id);if(existing?.metadata.deleted===!0)throw new MemoryValidationError("memory is tombstoned and cannot be upserted");let next=validateMemoryRecordRules({...record3,createdAt:existing?.createdAt??record3.createdAt},{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets});return this.memories.set(next.id,next),this.writeMemory(next),await this.writeMemoryVec(next),await this.event("upsert",next.id),next}async get(id){return await this.initialize(),this.memories.get(id)??null}async delete(id,reason){await this.initialize();let existing=this.memories.get(id);if(!existing)return;if(this.config.hardDelete)this.memories.delete(id),this.requireDb().run("DELETE FROM memory_items WHERE id = ?",[id]),this.deleteMemoryFts(id),this.deleteMemoryVec(id);else{let tombstone={...existing,updatedAt:new Date().toISOString(),metadata:{...existing.metadata,deleted:!0,deleteReason:reason}};this.memories.set(id,tombstone),this.writeMemory(tombstone)}await this.event("delete",id,reason)}async recall(request){return(await this.recallWithDiagnostics(request)).items}async recallWithDiagnostics(request){if(await this.initialize(),!this.config.embeddings.enabled||!this.vecAvailable||!this.embeddingProvider){let scopedRecords2=await this.list({scopes:request.scopes,kinds:request.kinds,includeExpired:request.includeExpired,limit:RECALL_CANDIDATE_LIMIT}),candidates=this.selectRecallCandidates(request,scopedRecords2),result=scoreMemoryRecordsWithDiagnostics(candidates.records,request),reranked=candidates.ftsOrder?rerankWithFts(result.items,candidates.ftsOrder):result.items;return{items:reranked.slice(0,request.maxItems),diagnostics:{...result.diagnostics,returnedCount:Math.min(reranked.length,request.maxItems)}}}let recallElapsedStart=Date.now(),scopedRecords=await this.list({scopes:request.scopes,kinds:request.kinds,includeExpired:request.includeExpired,limit:RECALL_CANDIDATE_LIMIT}),lexicalCandidates=this.selectRecallCandidates(request,scopedRecords),lexicalResult=scoreMemoryRecordsWithDiagnostics(lexicalCandidates.records,request),lexicalReranked=lexicalCandidates.ftsOrder?rerankWithFts(lexicalResult.items,lexicalCandidates.ftsOrder):lexicalResult.items,lexicalIds=lexicalReranked.map((item)=>item.record.id),denseIds=[];try{let modelVersion=this.embeddingProvider.modelVersion,normalizedQuery=normalizeMemoryText(request.query).toLowerCase(),queryEmbedding=this.embeddingCache?.get(modelVersion,normalizedQuery)?.vector??null;if(queryEmbedding===null)queryEmbedding=await this.embeddingProvider.embed(normalizedQuery),this.embeddingCache?.set(modelVersion,normalizedQuery,{vector:queryEmbedding,modelVersion,queryHash:normalizedQuery});denseIds=(await this.selectDenseCandidates(request,queryEmbedding)).map((record3)=>record3.id)}catch(err){if(err instanceof EmbeddingVersionMismatchError||err instanceof EmbeddingUnavailableError)warn("Dense retrieval failed — falling back to lexical-only",{reason:err instanceof Error?err.message:String(err)});else warn("Dense retrieval failed — falling back to lexical-only",{reason:err instanceof Error?err.message:String(err)});return{items:lexicalReranked.slice(0,request.maxItems),diagnostics:{...lexicalResult.diagnostics,returnedCount:Math.min(lexicalReranked.length,request.maxItems)}}}let metadataIds=buildMetadataRankedIds(lexicalReranked,request),weights=this.config.retrieval.weights,rrfK=this.config.retrieval.rrfK,fused=fuseRankings(lexicalIds,denseIds,metadataIds,weights,rrfK),lexicalItemMap=new Map(lexicalReranked.map((item)=>[item.record.id,item])),minScore=request.minScore??this.config.recall.minScore,fusedItems=[];for(let candidate of fused){if(candidate.fusedScore<minScore)continue;let lexicalItem=lexicalItemMap.get(candidate.id);if(lexicalItem)fusedItems.push({record:lexicalItem.record,score:candidate.fusedScore,reason:`${lexicalItem.reason}, rrf_fused=${candidate.fusedScore.toFixed(4)}`,signals:lexicalItem.signals});else{let record3=this.memories.get(candidate.id);if(record3)fusedItems.push({record:record3,score:candidate.fusedScore,reason:`rrf_fused=${candidate.fusedScore.toFixed(4)}`,signals:{textOverlap:0,tagOverlap:0,fileOverlap:0,symbolOverlap:0,kindMatch:!1,scopeMatch:!1}})}}let previousRecallElapsedMs=Date.now()-recallElapsedStart,rerankedItems=fusedItems;if(this.config.retrieval.rerank.enabled&&shouldRerank(previousRecallElapsedMs,this.config.retrieval.latencyBudgetMs))try{if(!this.reranker)this.reranker=new CrossEncoderReranker({model:this.config.retrieval.rerank.model});let topN=Math.min(20,fusedItems.length),rerankCandidates=fusedItems.slice(0,topN).map((item)=>({id:item.record.id,text:item.record.text,score:item.score})),rerankResult=await this.reranker.rerank(rerankCandidates,request.query,topN),topNPrefix=fusedItems.slice(0,topN),tail=fusedItems.slice(topN),rerankOrder=new Map(rerankResult.map((c,idx)=>[c.id,idx]));rerankedItems=[...[...topNPrefix].sort((a,b)=>(rerankOrder.get(a.record.id)??0)-(rerankOrder.get(b.record.id)??0)),...tail]}catch(err){warn("Rerank failed — returning fused order",{reason:err instanceof Error?err.message:String(err)}),rerankedItems=fusedItems}return{items:rerankedItems.slice(0,request.maxItems),diagnostics:{...lexicalResult.diagnostics,returnedCount:Math.min(rerankedItems.length,request.maxItems),fusionActive:!0}}}async recordRecallUsage(event){await this.initialize();let recalledRecords=event.memoryIds.map((id)=>this.memories.get(id)).filter(isMemoryRecord),qValue=typeof event.qValue==="number"&&Number.isFinite(event.qValue)?clamp012(event.qValue):averageMemoryQValue(recalledRecords),eventWithQValue={...event,qValue};this.requireDb().run(`INSERT INTO memory_recall_usage (
1400
1400
  id,
1401
1401
  bundle_id,
1402
1402
  timestamp,
1403
- usage_json
1404
- ) VALUES (?, ?, ?, ?)`,[randomUUID8(),event.bundleId,event.timestamp,JSON.stringify(event)]),this.recallCountSinceLastCompaction++;let threshold=this.config.maintenance?.autoCompactEveryNRecalls??50;if(threshold>0&&this.recallCountSinceLastCompaction>=threshold&&!this.isCompacting)this.recallCountSinceLastCompaction=0,this.isCompacting=!0,this.compactMaintenance({dryRun:!1}).then((result)=>{let rowsInspected=result.remaining+result.removedDeleted+result.removedSuperseded+result.removedExpiredScratch,rowsPurged=result.removedDeleted+result.removedSuperseded+result.removedExpiredScratch;return this.insertEvent("compact_triggered","memory_items","auto compaction triggered",JSON.stringify({trigger:"auto",threshold,rowsInspected,rowsPurged,timestamp:new Date().toISOString()}))}).catch((err)=>{if(process.env.OPENCODE_SWARM_DEBUG==="1")console.debug(`[memory] auto-compaction failed: ${err}`)}).finally(()=>{this.isCompacting=!1})}async listRecallUsage(filter={}){await this.initialize();let rows=typeof filter.limit==="number"?this.requireDb().query(`SELECT usage_json
1403
+ usage_json,
1404
+ q_value
1405
+ ) VALUES (?, ?, ?, ?, ?)`,[randomUUID8(),event.bundleId,event.timestamp,JSON.stringify(eventWithQValue),qValue]),this.recallCountSinceLastCompaction++;let threshold=this.config.maintenance?.autoCompactEveryNRecalls??50;if(threshold>0&&this.recallCountSinceLastCompaction>=threshold&&!this.isCompacting)this.recallCountSinceLastCompaction=0,this.isCompacting=!0,this.compactMaintenance({dryRun:!1}).then((result)=>{let rowsInspected=result.remaining+result.removedDeleted+result.removedSuperseded+result.removedExpiredScratch,rowsPurged=result.removedDeleted+result.removedSuperseded+result.removedExpiredScratch;return this.insertEvent("compact_triggered","memory_items","auto compaction triggered",JSON.stringify({trigger:"auto",threshold,rowsInspected,rowsPurged,timestamp:new Date().toISOString()}))}).catch((err)=>{if(process.env.OPENCODE_SWARM_DEBUG==="1")console.debug(`[memory] auto-compaction failed: ${err}`)}).finally(()=>{this.isCompacting=!1})}async listRecallUsage(filter={}){await this.initialize();let rows=typeof filter.limit==="number"?this.requireDb().query(`SELECT id, usage_json, q_value, last_reward, task_outcome, council_verdict_json, reward_key
1405
1406
  FROM memory_recall_usage
1406
1407
  ORDER BY timestamp DESC
1407
- LIMIT ?`).all(Math.max(1,Math.trunc(filter.limit))):this.requireDb().query(`SELECT usage_json
1408
+ LIMIT ?`).all(Math.max(1,Math.trunc(filter.limit))):this.requireDb().query(`SELECT id, usage_json, q_value, last_reward, task_outcome, council_verdict_json, reward_key
1408
1409
  FROM memory_recall_usage
1409
1410
  ORDER BY timestamp DESC
1410
- `).all(),events=[];for(let row of rows)try{let parsed=JSON.parse(row.usage_json);if(Array.isArray(parsed.memoryIds)&&typeof parsed.query==="string")events.push(parsed)}catch{}return events}async list(filter={}){await this.initialize();let db=this.requireDb(),conditions=[],params=[];if(filter.scopes&&filter.scopes.length>0){let scopeKeys=filter.scopes.map((scope)=>stableScopeKey(scope)),placeholders=scopeKeys.map(()=>"?").join(", ");conditions.push(`scope_key IN (${placeholders})`),params.push(...scopeKeys)}if(filter.kinds&&filter.kinds.length>0)if(filter.kinds.length===1)conditions.push("kind = ?"),params.push(filter.kinds[0]);else{let placeholders=filter.kinds.map(()=>"?").join(", ");conditions.push(`kind IN (${placeholders})`),params.push(...filter.kinds)}if(!filter.includeInactive)conditions.push("superseded_by IS NULL"),conditions.push("deleted = 0");if(!filter.includeExpired){let nowIso=new Date().toISOString();conditions.push("(expires_at IS NULL OR expires_at > ?)"),params.push(nowIso)}let sql=`SELECT id, record_json FROM memory_items ${conditions.length>0?`WHERE ${conditions.join(" AND ")}`:""} ORDER BY updated_at DESC`;if(typeof filter.limit==="number")sql+=" LIMIT ?",params.push(Math.trunc(filter.limit));let rows=db.query(sql).all(...params),records=[];for(let row of rows){let parsed=this.parseMemoryRow(row);if(parsed)records.push(parsed)}if(!filter.includeExpired){let now=Date.now();records=records.filter((record3)=>{if(!record3.expiresAt)return!0;let expires=Date.parse(record3.expiresAt);return!Number.isFinite(expires)||expires>now})}return records}async createProposal(proposal){await this.initialize();let next=validateMemoryProposal(proposal);if(next.proposedRecord)validateMemoryRecordRules(next.proposedRecord,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets});return this.proposals.set(next.id,next),this.writeProposal(next),await this.event("proposal",next.id),next}async listProposals(filter={}){await this.initialize();let proposals=Array.from(this.proposals.values());if(filter.status)proposals=proposals.filter((proposal)=>proposal.status===filter.status);return proposals.sort((a,b)=>b.createdAt.localeCompare(a.createdAt)),proposals.slice(0,filter.limit??proposals.length)}async applyCuratorDecision(decision){await this.initialize();let result=this.requireDb().transaction(()=>{let appliedAt=new Date().toISOString(),proposal=this.readPendingProposal(decision.proposalId);validateDecisionMatchesProposal(decision,proposal);let result2=this.applyDecisionToStorage(decision,proposal,appliedAt);this.writeProposal(result2.proposal);let eventId=randomUUID8(),eventJson=JSON.stringify(buildCuratorDecisionEvent(result2.change,proposal));return this.insertEvent("curator_decision",decision.proposalId,result2.change.reason,eventJson,eventId),{...result2,change:{...result2.change,eventId}}})();this.proposals.set(result.proposal.id,result.proposal);for(let id of result.removeMemoryIds)this.memories.delete(id);for(let memory of result.memories)this.memories.set(memory.id,memory);for(let memory of result.memories)if(memory.metadata.deleted!==!0)await this.writeMemoryVec(memory);return result.change}close(){if(!this.db)return;this.db.close(),this.db=null,this.ftsAvailable=!1,this.initialized=!1,this.initPromise=null,this.lastAutomaticJsonlMigration=null}async rebuildEmbeddingIndex(){if(await this.initialize(),!this.vecAvailable||!this.embeddingProvider){warn("rebuildEmbeddingIndex skipped — sqlite-vec or embedding provider not available");return}let currentVersion=this.embeddingProvider.modelVersion,durableRecords=Array.from(this.memories.values()).filter((record3)=>DURABLE_MEMORY_KINDS.has(record3.kind)&&record3.metadata.deleted!==!0&&record3.supersededBy===void 0&&record3.stability!=="ephemeral"),successCount=0,failureCount=0,db=this.requireDb();for(let record3 of durableRecords)try{let normalizedText=normalizeMemoryText(record3.text).toLowerCase();if(normalizedText.length===0)continue;let vector=await this.embeddingProvider.embed(normalizedText);db.run("INSERT OR REPLACE INTO memory_items_vec (id, embedding) VALUES (?, ?)",[record3.id,vector]),successCount++}catch(err){let reason=err instanceof Error?err.message:String(err);warn("rebuildEmbeddingIndex: failed to embed record",{id:record3.id,reason}),failureCount++}if(failureCount===0)db.run("INSERT OR REPLACE INTO embedding_config (key, value) VALUES (?, ?)",["model_version",currentVersion]);if(this.embeddingCache?.clear(),failureCount>0)warn("rebuildEmbeddingIndex completed with failures",{successCount,failureCount,total:durableRecords.length})}async importJsonl(){let wasInitialized=this.initialized;if(await this.initialize(),!wasInitialized&&this.lastAutomaticJsonlMigration)return this.lastAutomaticJsonlMigration;return this.importLegacyJsonlRows()}async exportJsonl(){await this.initialize();let memories=await this.list({includeExpired:!0}),proposals=await this.listProposals();return{...await writeJsonlExport(this.rootDirectory,this.config,memories,proposals),memories:memories.length,proposals:proposals.length}}async compactMaintenance(options={}){await this.initialize();let now=options.now?new Date(options.now):new Date,kept=[],removeIds=[],result={dryRun:options.dryRun!==!1,removedDeleted:0,removedSuperseded:0,removedExpiredScratch:0,remaining:0};for(let memory of this.memories.values()){let compactReason=shouldCompactMemory(memory,now);if(compactReason==="deleted"){result.removedDeleted++,removeIds.push(memory.id);continue}if(compactReason==="superseded"){result.removedSuperseded++,removeIds.push(memory.id);continue}if(compactReason==="expired_scratch"){result.removedExpiredScratch++,removeIds.push(memory.id);continue}kept.push(memory)}if(result.remaining=kept.length,result.dryRun)return result;let db=this.requireDb();return db.transaction(()=>{for(let id of removeIds)db.run("DELETE FROM memory_items WHERE id = ?",[id]),this.deleteMemoryFts(id),this.deleteMemoryVec(id);this.insertEvent("compact","memory_items","removed deleted, superseded, and expired scratch memories",JSON.stringify(result))})(),this.memories=new Map(kept.map((memory)=>[memory.id,memory])),result}hasMigration(name){let row=this.requireDb().query("SELECT version, name FROM schema_migrations WHERE name = ? LIMIT 1").get(name);return Boolean(row)}markMigration(version5,name){this.requireDb().run("INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (?, ?)",[version5,name])}selectRecallCandidates(request,scopedRecords){let ftsQuery=buildFtsQuery(request);if(!this.ftsAvailable||!ftsQuery)return{records:scopedRecords,usedFts:!1};let scopedIds=new Set(scopedRecords.map((record3)=>record3.id));if(scopedIds.size===0)return{records:[],usedFts:!0,ftsOrder:new Map};try{let rows=this.requireDb().query(`SELECT id, bm25(${FTS_TABLE_NAME}) AS rank
1411
+ `).all(),events=[];for(let row of rows){let parsed=parseRecallUsageRow(row);if(parsed)events.push(parsed)}return events}async applyRecallReward(input){await this.initialize();let matches=this.matchingRecallUsageRows(input.runIds);if(matches.length===0)return emptyRewardResult(input.outcome,"no_recall_usage_for_run");let rewardKey=deriveRewardKey(input.verdictPayload),pending=rewardKey===null?matches:matches.filter((match)=>match.rewardKey!==rewardKey);if(pending.length===0){let first=matches[0];return{success:!0,bundleId:first?.event.bundleId,bundleIds:matches.map((match)=>match.event.bundleId),outcome:input.outcome,memoryIds:uniqueStrings2(matches.flatMap((match)=>match.event.memoryIds)),reward:rewardForOutcome(input.outcome),updatedMemoryIds:[],propagatedMemoryIds:[],qValue:first?.event.qValue,reason:"already_rewarded"}}let reward=rewardForOutcome(input.outcome),updatedAt=input.timestamp??new Date().toISOString(),sourceIds=uniqueStrings2(pending.flatMap((match)=>match.event.memoryIds)),directUpdates=new Map,propagatedUpdates=new Map;for(let memoryId of sourceIds){let nextQValue=this.updateMemoryQValue(memoryId,reward,updatedAt);if(nextQValue!==null)directUpdates.set(memoryId,nextQValue)}let promotionThreshold=this.config.learning.promotionThreshold,promotionRecallThreshold=5,usageSummary=summarizeRecallUsage(this.listRecallUsageSync());for(let[memoryId,nextQValue]of directUpdates){let memory=this.memories.get(memoryId),recallCount=usageSummary.get(memoryId)?.count??0;if(memory&&memory.stability==="session"&&nextQValue>promotionThreshold&&recallCount>promotionRecallThreshold)memory.stability="durable",this._internals.writeMemory(memory)}let propagationTargets=await this.findPropagationTargets(sourceIds),db=this.requireDb(),verdictJson=truncateJsonPayload(input.verdictPayload),result=db.transaction(()=>{for(let targetId of propagationTargets){let propagatedSignal=propagatedRewardSignal(reward,this.config.learning.propagationFactor),nextQValue=this.updateMemoryQValue(targetId,propagatedSignal,updatedAt);if(nextQValue!==null)propagatedUpdates.set(targetId,nextQValue)}let updatedMemoryIds=[...directUpdates.keys()],propagatedMemoryIds=[...propagatedUpdates.keys()],combinedQValues=[...directUpdates.values(),...propagatedUpdates.values()],qValue=combinedQValues.length>0?averageNumbers(combinedQValues):pending[0]?.event.qValue;for(let match of pending){let updatedEvent={...match.event,qValue,lastReward:reward,taskOutcome:input.outcome};db.run(`UPDATE memory_recall_usage
1412
+ SET usage_json = ?,
1413
+ q_value = ?,
1414
+ last_reward = ?,
1415
+ task_outcome = ?,
1416
+ council_verdict_json = ?,
1417
+ reward_key = ?
1418
+ WHERE id = ?`,[JSON.stringify(updatedEvent),qValue??null,reward,input.outcome,verdictJson,rewardKey,match.id])}return{updatedMemoryIds,propagatedMemoryIds,qValue}})();for(let match of pending)await this.event("recall",match.event.bundleId,`applied ${input.outcome} recall reward`);return{success:!0,bundleId:pending[0]?.event.bundleId,bundleIds:pending.map((match)=>match.event.bundleId),outcome:input.outcome,memoryIds:sourceIds,reward,updatedMemoryIds:result.updatedMemoryIds,propagatedMemoryIds:result.propagatedMemoryIds,qValue:result.qValue}}async listMemoryValueLog(filter={}){await this.initialize();let usageSummary=summarizeRecallUsage(this.listRecallUsageSync()),threshold=this.config.learning.suppressionThreshold,promotionThreshold=this.config.learning.promotionThreshold;return Array.from(this.memories.values()).map((record3)=>{let recall=usageSummary.get(record3.id),qValue=memoryQValue(record3),recallCount=recall?.count??0;return{memoryId:record3.id,kind:record3.kind,scopeKey:stableScopeKey(record3.scope),textPreview:truncateText(record3.text,120),qValue,recallCount,lastRecalledAt:recall?.lastRecalledAt,lastReward:recall?.lastReward,taskOutcome:recall?.taskOutcome,promotionCandidate:qValue>promotionThreshold&&recallCount>5,suppressionCandidate:qValue<threshold}}).filter((entry)=>{if(filter.includePromotionCandidatesOnly)return entry.promotionCandidate;if(filter.includeSuppressionCandidatesOnly)return entry.suppressionCandidate;return!0}).sort((a,b)=>(b.lastRecalledAt??"").localeCompare(a.lastRecalledAt??"")||b.qValue-a.qValue||a.memoryId.localeCompare(b.memoryId)).slice(0,Math.max(1,Math.trunc(filter.limit??20)))}async list(filter={}){await this.initialize();let db=this.requireDb(),conditions=[],params=[];if(filter.scopes&&filter.scopes.length>0){let scopeKeys=filter.scopes.map((scope)=>stableScopeKey(scope)),placeholders=scopeKeys.map(()=>"?").join(", ");conditions.push(`scope_key IN (${placeholders})`),params.push(...scopeKeys)}if(filter.kinds&&filter.kinds.length>0)if(filter.kinds.length===1)conditions.push("kind = ?"),params.push(filter.kinds[0]);else{let placeholders=filter.kinds.map(()=>"?").join(", ");conditions.push(`kind IN (${placeholders})`),params.push(...filter.kinds)}if(!filter.includeInactive)conditions.push("superseded_by IS NULL"),conditions.push("deleted = 0");if(!filter.includeExpired){let nowIso=new Date().toISOString();conditions.push("(expires_at IS NULL OR expires_at > ?)"),params.push(nowIso)}let sql=`SELECT id, record_json FROM memory_items ${conditions.length>0?`WHERE ${conditions.join(" AND ")}`:""} ORDER BY updated_at DESC`;if(typeof filter.limit==="number")sql+=" LIMIT ?",params.push(Math.trunc(filter.limit));let rows=db.query(sql).all(...params),records=[];for(let row of rows){let parsed=this.parseMemoryRow(row);if(parsed)records.push(parsed)}if(!filter.includeExpired){let now=Date.now();records=records.filter((record3)=>{if(!record3.expiresAt)return!0;let expires=Date.parse(record3.expiresAt);return!Number.isFinite(expires)||expires>now})}return records}async createProposal(proposal){await this.initialize();let next=validateMemoryProposal(proposal);if(next.proposedRecord)validateMemoryRecordRules(next.proposedRecord,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets});return this.proposals.set(next.id,next),this.writeProposal(next),await this.event("proposal",next.id),next}async listProposals(filter={}){await this.initialize();let proposals=Array.from(this.proposals.values());if(filter.status)proposals=proposals.filter((proposal)=>proposal.status===filter.status);return proposals.sort((a,b)=>b.createdAt.localeCompare(a.createdAt)),proposals.slice(0,filter.limit??proposals.length)}async applyCuratorDecision(decision){await this.initialize();let result=this.requireDb().transaction(()=>{let appliedAt=new Date().toISOString(),proposal=this.readPendingProposal(decision.proposalId);validateDecisionMatchesProposal(decision,proposal);let result2=this.applyDecisionToStorage(decision,proposal,appliedAt);this.writeProposal(result2.proposal);let eventId=randomUUID8(),eventJson=JSON.stringify(buildCuratorDecisionEvent(result2.change,proposal));return this.insertEvent("curator_decision",decision.proposalId,result2.change.reason,eventJson,eventId),{...result2,change:{...result2.change,eventId}}})();this.proposals.set(result.proposal.id,result.proposal);for(let id of result.removeMemoryIds)this.memories.delete(id);for(let memory of result.memories)this.memories.set(memory.id,memory);for(let memory of result.memories)if(memory.metadata.deleted!==!0)await this.writeMemoryVec(memory);return result.change}close(){if(!this.db)return;this.db.close(),this.db=null,this.ftsAvailable=!1,this.initialized=!1,this.initPromise=null,this.lastAutomaticJsonlMigration=null}async rebuildEmbeddingIndex(){if(await this.initialize(),!this.vecAvailable||!this.embeddingProvider){warn("rebuildEmbeddingIndex skipped — sqlite-vec or embedding provider not available");return}let currentVersion=this.embeddingProvider.modelVersion,durableRecords=Array.from(this.memories.values()).filter((record3)=>DURABLE_MEMORY_KINDS.has(record3.kind)&&record3.metadata.deleted!==!0&&record3.supersededBy===void 0&&record3.stability!=="ephemeral"),successCount=0,failureCount=0,db=this.requireDb();for(let record3 of durableRecords)try{let normalizedText=normalizeMemoryText(record3.text).toLowerCase();if(normalizedText.length===0)continue;let vector=await this.embeddingProvider.embed(normalizedText);db.run("INSERT OR REPLACE INTO memory_items_vec (id, embedding) VALUES (?, ?)",[record3.id,vector]),successCount++}catch(err){let reason=err instanceof Error?err.message:String(err);warn("rebuildEmbeddingIndex: failed to embed record",{id:record3.id,reason}),failureCount++}if(failureCount===0)db.run("INSERT OR REPLACE INTO embedding_config (key, value) VALUES (?, ?)",["model_version",currentVersion]);if(this.embeddingCache?.clear(),failureCount>0)warn("rebuildEmbeddingIndex completed with failures",{successCount,failureCount,total:durableRecords.length})}async importJsonl(){let wasInitialized=this.initialized;if(await this.initialize(),!wasInitialized&&this.lastAutomaticJsonlMigration)return this.lastAutomaticJsonlMigration;return this.importLegacyJsonlRows()}async exportJsonl(){await this.initialize();let memories=await this.list({includeExpired:!0}),proposals=await this.listProposals();return{...await writeJsonlExport(this.rootDirectory,this.config,memories,proposals),memories:memories.length,proposals:proposals.length}}async compactMaintenance(options={}){await this.initialize();let now=options.now?new Date(options.now):new Date,kept=[],removeIds=[],result={dryRun:options.dryRun!==!1,removedDeleted:0,removedSuperseded:0,removedExpiredScratch:0,remaining:0};for(let memory of this.memories.values()){let compactReason=shouldCompactMemory(memory,now);if(compactReason==="deleted"){result.removedDeleted++,removeIds.push(memory.id);continue}if(compactReason==="superseded"){result.removedSuperseded++,removeIds.push(memory.id);continue}if(compactReason==="expired_scratch"){result.removedExpiredScratch++,removeIds.push(memory.id);continue}kept.push(memory)}if(result.remaining=kept.length,result.dryRun)return result;let db=this.requireDb();return db.transaction(()=>{for(let id of removeIds)db.run("DELETE FROM memory_items WHERE id = ?",[id]),this.deleteMemoryFts(id),this.deleteMemoryVec(id);this.insertEvent("compact","memory_items","removed deleted, superseded, and expired scratch memories",JSON.stringify(result))})(),this.memories=new Map(kept.map((memory)=>[memory.id,memory])),result}matchingRecallUsageRows(runIds){let idSet=new Set(runIds.filter((id)=>id.length>0));if(idSet.size===0)return[];let rows=this.requireDb().query(`SELECT id, usage_json, q_value, last_reward, task_outcome, council_verdict_json, reward_key
1419
+ FROM memory_recall_usage
1420
+ ORDER BY timestamp DESC
1421
+ LIMIT ?`).all(100),matches=[],seenRunIds=new Set;for(let row of rows){if(!row.id)continue;let event=parseRecallUsageRow(row);if(!event?.runId||!idSet.has(event.runId))continue;if(seenRunIds.has(event.runId))continue;seenRunIds.add(event.runId),matches.push({id:row.id,event,rewardKey:row.reward_key??null})}return matches}updateMemoryQValue(memoryId,rewardSignal,updatedAt){let current=this.memories.get(memoryId);if(!current)return null;if(current.metadata.deleted===!0||current.supersededBy)return null;let eta=this.config.learning.learningRate,nextQValue=clamp012((1-eta)*memoryQValue(current)+eta*rewardSignal),next={...current,updatedAt,qValue:nextQValue};return this.memories.set(memoryId,next),this.writeMemory(next),nextQValue}async findPropagationTargets(sourceMemoryIds){let lookbackIds=this.recentlyRecalledMemoryIds(this.config.learning.propagationLookbackDays);if(lookbackIds.size===0)return[];let sourceRecords=sourceMemoryIds.map((id)=>this.memories.get(id)).filter(isMemoryRecord);if(sourceRecords.length===0)return[];let targets=[],sourceTokenSets=sourceRecords.map((record3)=>tokenizeText(record3.text)),cosineEnabled=this.config.embeddings.enabled&&Boolean(this.embeddingProvider),cosineThreshold=this.config.learning.propagationEmbeddingCosineThreshold,sourceVectors=cosineEnabled?await Promise.all(sourceRecords.map((record3)=>this.getCachedEmbeddingForPropagation(record3.text))):[];for(let candidate of this.memories.values()){if(sourceMemoryIds.includes(candidate.id))continue;if(!lookbackIds.has(candidate.id))continue;if(candidate.metadata.deleted===!0||candidate.supersededBy)continue;let candidateTokens=tokenizeText(candidate.text),bestOverlap=0,sameScopeAsAnySource=!1,sameScopeBySourceIndex=[];for(let i=0;i<sourceRecords.length;i++){let source=sourceRecords[i],sameScope2=stableScopeKey(candidate.scope)===stableScopeKey(source.scope);if(sameScopeBySourceIndex[i]=sameScope2,sameScope2)sameScopeAsAnySource=!0;if(!sameScope2||candidate.kind!==source.kind)continue;bestOverlap=Math.max(bestOverlap,jaccard2(sourceTokenSets[i]??new Set,candidateTokens))}let bestCosine=0;if(cosineEnabled&&sameScopeAsAnySource){let candidateVector=await this.getCachedEmbeddingForPropagation(candidate.text);if(candidateVector)for(let i=0;i<sourceVectors.length;i++){if(!sameScopeBySourceIndex[i])continue;let sourceVector=sourceVectors[i];if(!sourceVector)continue;bestCosine=Math.max(bestCosine,cosineSimilarity(sourceVector,candidateVector))}}let qualifiesByOverlap=bestOverlap>=this.config.learning.propagationTokenOverlapThreshold,qualifiesByCosine=cosineEnabled&&bestCosine>=cosineThreshold;if(qualifiesByOverlap||qualifiesByCosine)targets.push({id:candidate.id,overlap:Math.max(bestOverlap,bestCosine)})}return targets.sort((a,b)=>b.overlap-a.overlap||a.id.localeCompare(b.id)).slice(0,this.config.learning.propagationFanout).map((target)=>target.id)}async getCachedEmbeddingForPropagation(text){if(!this.embeddingProvider)return null;let modelVersion=this.embeddingProvider.modelVersion,normalized=normalizeMemoryText(text).toLowerCase();if(!normalized)return null;let cached3=this.embeddingCache?.get(modelVersion,normalized)?.vector;if(cached3)return cached3;try{let vector=await this.embeddingProvider.embed(normalized);return this.embeddingCache?.set(modelVersion,normalized,{vector,modelVersion,queryHash:normalized}),vector}catch{return null}}recentlyRecalledMemoryIds(lookbackDays){let cutoffMs=Date.now()-Math.max(0,lookbackDays)*24*60*60*1000,memoryIds=new Set;for(let event of this.listRecallUsageSync(500)){let timestamp=Date.parse(event.timestamp);if(Number.isFinite(timestamp)&&timestamp<cutoffMs)continue;for(let memoryId of event.memoryIds)memoryIds.add(memoryId)}return memoryIds}listRecallUsageSync(limit=1000){return this.requireDb().query(`SELECT id, usage_json, q_value, last_reward, task_outcome, council_verdict_json, reward_key
1422
+ FROM memory_recall_usage
1423
+ ORDER BY timestamp DESC
1424
+ LIMIT ?`).all(Math.max(1,Math.trunc(limit))).map((row)=>parseRecallUsageRow(row)).filter(isRecallUsageEvent)}hasMigration(name){let row=this.requireDb().query("SELECT version, name FROM schema_migrations WHERE name = ? LIMIT 1").get(name);return Boolean(row)}markMigration(version5,name){this.requireDb().run("INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (?, ?)",[version5,name])}selectRecallCandidates(request,scopedRecords){let ftsQuery=buildFtsQuery(request);if(!this.ftsAvailable||!ftsQuery)return{records:scopedRecords,usedFts:!1};let scopedIds=new Set(scopedRecords.map((record3)=>record3.id));if(scopedIds.size===0)return{records:[],usedFts:!0,ftsOrder:new Map};try{let rows=this.requireDb().query(`SELECT id, bm25(${FTS_TABLE_NAME}) AS rank
1411
1425
  FROM ${FTS_TABLE_NAME}
1412
1426
  WHERE ${FTS_TABLE_NAME} MATCH ?
1413
1427
  AND id IN (SELECT value FROM json_each(?))
@@ -1416,7 +1430,7 @@ ${query}`).digest("hex").slice(0,8);return`bundle_${compactTimestamp}_${hash4}`}
1416
1430
  version INTEGER PRIMARY KEY,
1417
1431
  name TEXT NOT NULL,
1418
1432
  applied_at TEXT NOT NULL DEFAULT (datetime('now'))
1419
- )`);let currentVersion=db.query("SELECT MAX(version) as version FROM schema_migrations").get()?.version??0;for(let migration of MIGRATIONS2){if(migration.version<=currentVersion)continue;db.transaction(()=>{for(let statement of splitSql(migration.sql))db.run(statement);db.run("INSERT INTO schema_migrations (version, name) VALUES (?, ?)",[migration.version,migration.name]),this.insertEvent("migration",String(migration.version),migration.name)})()}}backfillScopeKeys(){let db=this.requireDb();if(db.query("SELECT value FROM _meta WHERE key = 'scope_key_backfilled'").get("scope_key_backfilled")?.value==="1")return;let rows=db.query("SELECT id, record_json, scope_key FROM memory_items").all(),backfillCount=0;for(let row of rows)try{let record3=JSON.parse(row.record_json),canonicalKey=stableScopeKey(record3.scope);if(row.scope_key!==canonicalKey)db.run("UPDATE memory_items SET scope_key = ? WHERE id = ?",[canonicalKey,row.id]),backfillCount++}catch{}if(backfillCount>0)this.insertEvent("migration","backfill_scope_keys",`${backfillCount} memory item(s) scope_key backfilled to canonical form`);db.run("INSERT OR REPLACE INTO _meta (key, value) VALUES ('scope_key_backfilled', '1')")}initializeFtsIndex(){let db=this.requireDb();try{if(!this.hasMigration(FTS_SCHEMA_MIGRATION_NAME))this.recreateFtsIndex();else db.run(`CREATE VIRTUAL TABLE IF NOT EXISTS ${FTS_TABLE_NAME} USING fts5(
1433
+ )`);let currentVersion=db.query("SELECT MAX(version) as version FROM schema_migrations").get()?.version??0;for(let migration of MIGRATIONS2){if(migration.version<=currentVersion)continue;db.transaction(()=>{for(let statement of splitSql(migration.sql))try{db.run(statement)}catch(err){let message=err instanceof Error?err.message:String(err);if(!/duplicate column name/i.test(message))throw err}db.run("INSERT INTO schema_migrations (version, name) VALUES (?, ?)",[migration.version,migration.name]),this.insertEvent("migration",String(migration.version),migration.name)})()}}backfillScopeKeys(){let db=this.requireDb();if(db.query("SELECT value FROM _meta WHERE key = 'scope_key_backfilled'").get("scope_key_backfilled")?.value==="1")return;let rows=db.query("SELECT id, record_json, scope_key FROM memory_items").all(),backfillCount=0;for(let row of rows)try{let record3=JSON.parse(row.record_json),canonicalKey=stableScopeKey(record3.scope);if(row.scope_key!==canonicalKey)db.run("UPDATE memory_items SET scope_key = ? WHERE id = ?",[canonicalKey,row.id]),backfillCount++}catch{}if(backfillCount>0)this.insertEvent("migration","backfill_scope_keys",`${backfillCount} memory item(s) scope_key backfilled to canonical form`);db.run("INSERT OR REPLACE INTO _meta (key, value) VALUES ('scope_key_backfilled', '1')")}initializeFtsIndex(){let db=this.requireDb();try{if(!this.hasMigration(FTS_SCHEMA_MIGRATION_NAME))this.recreateFtsIndex();else db.run(`CREATE VIRTUAL TABLE IF NOT EXISTS ${FTS_TABLE_NAME} USING fts5(
1420
1434
  ${ftsCreateColumnsSql()}
1421
1435
  )`);this.ftsAvailable=!0;let validMemoryCount=this.countValidMemoryRows(),ftsCount=db.query(`SELECT COUNT(*) AS count FROM ${FTS_TABLE_NAME}`).get()?.count??0;if(validMemoryCount!==ftsCount)this.rebuildFtsIndex();return!0}catch{return this.ftsAvailable=!1,!1}}initializeVecExtension(){let db=this.requireDb();try{let dimension=Math.max(1,Math.trunc(this.config.embeddings.dimension??384)),req=createRequire5(import.meta.url),pkgDir=path83.dirname(req.resolve("@sqlite/sqlite-vec/package.json")),ext=process.platform==="win32"?".dll":process.platform==="darwin"?".dylib":".so",vec0Path=path83.join(pkgDir,`vec0${ext}`);db.loadExtension(vec0Path),db.run(`CREATE VIRTUAL TABLE IF NOT EXISTS memory_items_vec USING vec0(
1422
1436
  id TEXT PRIMARY KEY, embedding FLOAT[${dimension}]
@@ -1445,7 +1459,7 @@ ${query}`).digest("hex").slice(0,8);return`bundle_${compactTimestamp}_${hash4}`}
1445
1459
  reason,
1446
1460
  timestamp,
1447
1461
  event_json
1448
- ) VALUES (?, ?, ?, ?, ?, ?)`,[id,operation,targetId,reason??null,new Date().toISOString(),eventJson??(reason?JSON.stringify({reason}):null)])}requireDb(){if(!this.db)throw new MemoryValidationError("SQLite memory provider is not initialized","provider_not_initialized");return this.db}}function splitSql(sql){let statements=[],current="",inSingleQuote=!1,inLineComment=!1;for(let i=0;i<sql.length;i++){let char=sql[i],next=sql[i+1];if(inLineComment){if(char===`
1462
+ ) VALUES (?, ?, ?, ?, ?, ?)`,[id,operation,targetId,reason??null,new Date().toISOString(),eventJson??(reason?JSON.stringify({reason}):null)])}requireDb(){if(!this.db)throw new MemoryValidationError("SQLite memory provider is not initialized","provider_not_initialized");return this.db}}function averageMemoryQValue(records){if(records.length===0)return DEFAULT_MEMORY_Q_VALUE;return averageNumbers(records.map((record3)=>memoryQValue(record3)))}function averageNumbers(values){let finite=values.filter((value)=>Number.isFinite(value));if(finite.length===0)return DEFAULT_MEMORY_Q_VALUE;return finite.reduce((sum,value)=>sum+value,0)/finite.length}function isMemoryRecord(record3){return record3!==void 0}function isRecallUsageEvent(event){return event!==null}function rewardForOutcome(outcome){switch(outcome){case"approved":return 1;case"rejected":return-1;case"concerns":case"unknown":return 0}}function propagatedRewardSignal(reward,propagationFactor){let factor=Math.max(0,Math.min(1,propagationFactor));return DEFAULT_MEMORY_Q_VALUE+factor*(reward-DEFAULT_MEMORY_Q_VALUE)}function emptyRewardResult(outcome,reason){return{success:!1,outcome,memoryIds:[],reward:rewardForOutcome(outcome),updatedMemoryIds:[],propagatedMemoryIds:[],reason}}function parseRecallUsageRow(row){try{let parsed=JSON.parse(row.usage_json);if(!Array.isArray(parsed.memoryIds)||typeof parsed.query!=="string")return null;let event={...parsed};if(typeof row.q_value==="number"&&Number.isFinite(row.q_value))event.qValue=clamp012(row.q_value);if(typeof row.last_reward==="number"&&Number.isFinite(row.last_reward))event.lastReward=row.last_reward;let taskOutcome=normalizeTaskOutcome(row.task_outcome);if(taskOutcome)event.taskOutcome=taskOutcome;return event}catch{return null}}function normalizeTaskOutcome(value){if(value==="approved"||value==="rejected"||value==="concerns"||value==="unknown")return value;return}function truncateJsonPayload(value){if(value===void 0)return null;let json3;try{json3=JSON.stringify(value)}catch(err){return JSON.stringify({unserializable:!0,reason:err instanceof Error?err.message:String(err)})}let maxLength=8192;if(json3.length<=maxLength)return json3;return JSON.stringify({truncated:!0,preview:json3.slice(0,maxLength-32)})}function deriveRewardKey(verdictPayload){if(!verdictPayload||typeof verdictPayload!=="object")return null;let payload=verdictPayload,swarmId=payload.swarmId,roundNumber=payload.roundNumber,unit=payload.taskId??payload.phaseNumber,unitOk=typeof unit==="string"||typeof unit==="number",roundOk=typeof roundNumber==="string"||typeof roundNumber==="number";if(typeof swarmId!=="string"||swarmId.length===0||!unitOk||!roundOk)return null;return`${swarmId}:${unit}:${roundNumber}`}function summarizeRecallUsage(events){let summary=new Map;for(let event of events)for(let memoryId of event.memoryIds){let existing=summary.get(memoryId)??{count:0,lastRecalledAt:event.timestamp};if(existing.count++,event.timestamp>=existing.lastRecalledAt)existing.lastRecalledAt=event.timestamp,existing.lastReward=event.lastReward,existing.taskOutcome=event.taskOutcome;summary.set(memoryId,existing)}return summary}function uniqueStrings2(values){return Array.from(new Set(values.filter((value)=>value.length>0)))}function truncateText(value,maxLength){if(value.length<=maxLength)return value;return`${value.slice(0,maxLength-3)}...`}function tokenizeText(value){let tokens=new Set;for(let match of value.toLowerCase().matchAll(/[a-z0-9_]{3,}/g)){let token=match[0];if(!FTS_STOP_WORDS.has(token))tokens.add(token)}return tokens}function jaccard2(left,right){if(left.size===0||right.size===0)return 0;let intersection3=0;for(let token of left)if(right.has(token))intersection3++;let union3=left.size+right.size-intersection3;return union3>0?intersection3/union3:0}function cosineSimilarity(a,b){if(a.length===0||a.length!==b.length)return 0;let dot=0,normA=0,normB=0;for(let i=0;i<a.length;i++)dot+=a[i]*b[i],normA+=a[i]*a[i],normB+=b[i]*b[i];if(normA===0||normB===0)return 0;let similarity=dot/(Math.sqrt(normA)*Math.sqrt(normB));return Number.isFinite(similarity)?similarity:0}function clamp012(value){if(!Number.isFinite(value))return DEFAULT_MEMORY_Q_VALUE;return Math.min(1,Math.max(0,value))}function splitSql(sql){let statements=[],current="",inSingleQuote=!1,inLineComment=!1;for(let i=0;i<sql.length;i++){let char=sql[i],next=sql[i+1];if(inLineComment){if(char===`
1449
1463
  `)inLineComment=!1;continue}if(inSingleQuote){if(char==="'"&&next==="'"){current+="''",i++;continue}if(current+=char,char==="'")inSingleQuote=!1;continue}if(char==="-"&&next==="-"){inLineComment=!0,i++;continue}if(char==="'"){inSingleQuote=!0,current+=char;continue}if(char===";"){let trimmed2=current.trim();if(trimmed2)statements.push(trimmed2);current="";continue}current+=char}let trimmed=current.trim();if(trimmed)statements.push(trimmed);return statements}function buildFtsQuery(request){let text=request.mode==="injection"&&request.task?`${request.task}
1450
1464
  ${request.query}`:`${request.query}
1451
1465
  ${request.task??""}`,terms=Array.from(extractFtsTerms(text)).slice(0,40);if(terms.length===0)return null;return terms.map((term)=>`"${term}"`).join(" OR ")}function extractFtsTerms(text){let terms=new Set;for(let match of text.toLowerCase().matchAll(/[a-z0-9_]{2,}/g)){let term=match[0];if(FTS_STOP_WORDS.has(term))continue;if(term.length<3&&!/^\d+$/.test(term))continue;terms.add(term)}return terms}function ftsCreateColumnsSql(){return["id UNINDEXED",...FTS_INDEX_COLUMNS.map((column)=>column.name)].join(`,
@@ -1508,25 +1522,33 @@ ${request.task??""}`,terms=Array.from(extractFtsTerms(text)).slice(0,40);if(term
1508
1522
  key TEXT PRIMARY KEY,
1509
1523
  value TEXT
1510
1524
  );
1511
- `}];FTS_STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","goal","how","in","into","is","it","of","on","or","role","task","that","the","this","to","user","what","when","with"])});import{realpathSync as realpathSync8}from"node:fs";import*as path84 from"node:path";function markAsPooled(provider){let originalClose=provider.close;if(provider.close=()=>{return releaseProvider(provider),Promise.resolve()},provider[POOLED_MARKER]=!0,originalClose)provider[REAL_CLOSE]=originalClose}function callRealClose(provider){let realClose=provider[REAL_CLOSE];try{realClose?.call(provider)}catch(err){let msg=err instanceof Error?err.message:String(err);if(process.env.OPENCODE_SWARM_DEBUG==="1")console.debug(`[provider-pool] real close failed: ${msg}`)}}function isPooledProvider(provider){return POOLED_MARKER in provider}function getOrCreateProvider(directory,config3){let key=resolvePoolKey(directory),existing=entriesByKey.get(key);if(existing)return moveToHead(existing),existing.refCount++,existing.provider;for(let deferred of deferredEntries)if(deferred.key===key){if(deferredEntries.delete(deferred),entriesByKey.size>=MAX_POOL_SIZE)evictLru();if(deferred.prev=null,deferred.next=head,head)head.prev=deferred;if(head=deferred,!tail)tail=deferred;return entriesByKey.set(key,deferred),deferred.refCount++,deferred.provider}let provider=new SQLiteMemoryProvider(directory,config3);if(markAsPooled(provider),entriesByKey.size>=MAX_POOL_SIZE)evictLru();let entry={key,provider,refCount:1,prev:null,next:head};if(head)head.prev=entry;if(head=entry,!tail)tail=entry;return entriesByKey.set(key,entry),provider}function releaseProvider(provider){for(let[_key,entry]of entriesByKey)if(entry.provider===provider){entry.refCount=Math.max(0,entry.refCount-1);return}for(let entry of deferredEntries)if(entry.provider===provider){if(entry.refCount--,entry.refCount<=0)deferredEntries.delete(entry),callRealClose(provider);return}if(isPooledProvider(provider))callRealClose(provider)}function evictLru(){if(!tail)return;let evicted=tail;if(entriesByKey.delete(evicted.key),unlinkEntry(evicted),evicted.refCount>0)deferredEntries.add(evicted);else callRealClose(evicted.provider)}function moveToHead(entry){if(head===entry)return;if(unlinkEntry(entry),entry.prev=null,entry.next=head,head)head.prev=entry;if(head=entry,!tail)tail=entry}function unlinkEntry(entry){if(entry.prev)entry.prev.next=entry.next;if(entry.next)entry.next.prev=entry.prev;if(head===entry)head=entry.next;if(tail===entry)tail=entry.prev}function resolvePoolKey(directory){try{return realpathSync8(directory)}catch{return path84.resolve(directory)}}var MAX_POOL_SIZE=16,POOLED_MARKER,REAL_CLOSE,head=null,tail=null,entriesByKey,deferredEntries;var init_provider_pool=__esm(()=>{init_sqlite_provider();POOLED_MARKER=Symbol("opencode-swarm-pooled-provider"),REAL_CLOSE=Symbol("opencode-swarm-real-close"),entriesByKey=new Map,deferredEntries=new Set});import{createHash as createHash14}from"node:crypto";import{existsSync as existsSync48,readFileSync as readFileSync28}from"node:fs";import*as path85 from"node:path";class MemoryGateway{context;config;provider;now;disposed=!1;constructor(context,options={}){this.context=context;this.config=resolveMemoryConfig(options.config??DEFAULT_MEMORY_CONFIG),this.provider=options.provider??createConfiguredMemoryProvider(context.directory,this.config),this.now=options.now??(()=>new Date)}isEnabled(){return this.config.enabled}async dispose(){if(this.disposed)return;this.disposed=!0,await this.provider.close?.()}deriveAllowedScopes(){let resolvedRoot=path85.resolve(this.context.directory),repoId=createStableId(readGitRemoteUrl(resolvedRoot)??path85.basename(resolvedRoot)),scopes=[{type:"workspace",workspaceId:createStableId(path85.dirname(resolvedRoot))},{type:"repository",repoId,repoRoot:resolvedRoot}];if(this.context.runId||this.context.sessionID)scopes.push({type:"run",runId:this.context.runId??this.context.sessionID});if(this.context.agentId||this.context.agentRole)scopes.push({type:"agent",agentId:this.context.agentId??this.context.agentRole,runId:this.context.runId??this.context.sessionID});return scopes}async recall(input){this.assertEnabled();let query=normalizeMemoryText(input.query);if(query.length<3)throw new MemoryValidationError("query must be at least 3 characters");let maxItems=clampInt(input.maxItems??this.config.recall.defaultMaxItems,1,20),tokenBudget=clampInt(input.tokenBudget??this.config.recall.defaultTokenBudget,100,5000),generatedAt=this.now().toISOString(),allowedScopes=this.deriveAllowedScopes(),scopes=input.scopes?validateRequestedScopes(input.scopes,allowedScopes):allowedScopes,request={query,task:input.task,agentRole:this.context.agentRole,mode:input.mode??"manual",scopes,kinds:input.kinds,maxItems,tokenBudget,minScore:input.minScore??this.config.recall.minScore,requireQuerySignal:input.requireQuerySignal,includeExpired:input.includeExpired},recallResult=this.provider.recallWithDiagnostics?await this.provider.recallWithDiagnostics(request):{items:await this.provider.recall(request)},bundle=toRecallBundle({id:createBundleId(query,generatedAt),query,generatedAt,items:recallResult.items,tokenBudget,diagnostics:recallResult.diagnostics?{injectionSkipReason:input.mode==="injection"?resolveInjectionSkipReason(recallResult.diagnostics):void 0,candidateCount:recallResult.diagnostics.candidateCount,preScoredFilteredCount:recallResult.diagnostics.preScoredFilteredCount,noSignalCount:recallResult.diagnostics.noSignalCount,belowThresholdCount:recallResult.diagnostics.belowThresholdCount}:void 0});return await this.provider.recordRecallUsage?.({bundleId:bundle.id,query,scopes,kinds:input.kinds,memoryIds:bundle.items.map((item)=>item.record.id),scores:bundle.items.map((item)=>item.score),tokenEstimate:bundle.tokenEstimate,agentRole:this.context.agentRole,runId:this.context.runId??this.context.sessionID,timestamp:generatedAt}),bundle}async propose(input){if(this.assertEnabled(),!this.provider.createProposal)throw new MemoryValidationError("memory provider does not support proposals");let redactedFields=new Set,redactProposalField=(field,value)=>{let redacted=redactSecrets(value);if(redacted!==value)redactedFields.add(field);return redacted},rationale=redactProposalField("rationale",normalizeMemoryText(input.rationale));if(!rationale)throw new MemoryValidationError("rationale is required");let evidenceRefs=(input.evidenceRefs??[]).map((ref)=>normalizeMemoryText(ref)).filter(Boolean).map((ref)=>redactProposalField("evidenceRefs",ref)).slice(0,20),needsRecord=input.operation==="add"||input.operation==="update"||input.operation==="supersede",proposedRecord,status="pending",reviewer,reviewedAt,rejectionReason,targetMemoryId=input.targetMemoryId===void 0?void 0:redactProposalField("targetMemoryId",normalizeMemoryText(input.targetMemoryId)),relatedMemoryIds=input.relatedMemoryIds?.map((id)=>redactProposalField("relatedMemoryIds",normalizeMemoryText(id))),proposalText=`${input.operation}:${targetMemoryId??""}`;if(needsRecord){if(!input.kind)throw new MemoryValidationError("kind is required for this operation");if(!input.text)throw new MemoryValidationError("text is required for this operation");proposalText=input.text;let normalizedText=normalizeMemoryText(input.text),redactedText=redactProposalField("text",normalizedText),extractedPaths=extractFilePaths(evidenceRefs),extractedSymbols=extractSymbols(evidenceRefs),recordMetadata={};if(extractedPaths.length>0)recordMetadata.files=extractedPaths;if(extractedSymbols.length>0)recordMetadata.symbols=extractedSymbols;proposedRecord=this.createRecord({kind:input.kind,text:redactedText,evidenceRefs,source:sourceFromEvidence(evidenceRefs,this.context),metadata:recordMetadata}),validateMemoryRecordRules(proposedRecord,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets})}if(redactedFields.size>0)status="rejected",reviewer="auto_policy",reviewedAt=this.now().toISOString(),rejectionReason=`proposal field(s) contained a likely secret and were redacted: ${Array.from(redactedFields).join(", ")}`;if((input.operation==="update"||input.operation==="delete"||input.operation==="supersede")&&!targetMemoryId)throw new MemoryValidationError(`${input.operation} proposals require targetMemoryId`);if(input.operation==="merge"&&(relatedMemoryIds??[]).length<2)throw new MemoryValidationError("merge proposals require relatedMemoryIds");let createdAt=this.now().toISOString(),proposer=this.context.agentId??this.context.agentRole??this.context.sessionID??"unknown",proposal={id:createProposalId({createdAt,proposer,text:proposalText}),operation:input.operation,proposedRecord,targetMemoryId,relatedMemoryIds,proposedBy:{agentRole:this.context.agentRole,agentId:this.context.agentId,runId:this.context.runId??this.context.sessionID},rationale,evidenceRefs,status,reviewer,reviewedAt,rejectionReason,createdAt,metadata:{}};return this.provider.createProposal(proposal)}async listMemories(filter={}){return this.assertEnabled(),this.provider.list(filter)}async listProposals(filter){if(this.assertEnabled(),!this.provider.listProposals)throw new MemoryValidationError("memory provider does not support proposals");return this.provider.listProposals(filter)}async listRecallUsage(filter){if(this.assertEnabled(),!this.provider.listRecallUsage)return[];return this.provider.listRecallUsage(filter)}async upsertCurated(record3){this.assertEnabled();let parsed=validateMemoryRecordRules(record3,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets});return this.provider.upsert(parsed)}async applyCuratorDecision(decision){if(this.assertEnabled(),!this.provider.applyCuratorDecision)throw new MemoryValidationError("memory provider does not support curator decisions");let parsed=validateCuratorMemoryDecision(decision),resolved=this.resolveCuratorDecision(parsed);return this.provider.applyCuratorDecision(resolved)}createRecord(input){let now=this.now().toISOString(),text=normalizeMemoryText(input.text),scope=this.resolveRecordScope(input.scope),kind=input.kind,stability=input.stability??(kind==="scratch"?"ephemeral":"durable"),expiresAt=kind==="scratch"?new Date(this.now().getTime()+604800000).toISOString():void 0,recordBase={scope,kind,text};return{id:createMemoryId(recordBase),scope,kind,text,tags:normalizeTags2(input.tags??inferTags2(text)),confidence:clamp(input.confidence??0.5,0,1),stability,source:input.source??sourceFromEvidence(input.evidenceRefs??[],this.context),createdAt:now,updatedAt:now,expiresAt,contentHash:computeMemoryContentHash(recordBase),metadata:input.metadata??{}}}resolveCuratorDecision(decision){switch(decision.action){case"add":return{action:"add",proposalId:decision.proposalId,memory:this.createRecordFromNew(decision.memory)};case"supersede":return{action:"supersede",proposalId:decision.proposalId,oldMemoryId:decision.oldMemoryId,replacement:this.createRecordFromNew(decision.replacement),reason:normalizeMemoryText(decision.reason)};case"update":{let patch=normalizeMemoryPatch(decision.patch);if(patch.scope)patch.scope=this.resolveRecordScope(patch.scope);return{action:"update",proposalId:decision.proposalId,targetMemoryId:decision.targetMemoryId,patch,reason:normalizeMemoryText(decision.reason)}}case"reject":case"noop":return{action:decision.action,proposalId:decision.proposalId,reason:normalizeMemoryText(decision.reason)}}}createRecordFromNew(input){let record3=this.createRecord({kind:input.kind,text:input.text,scope:input.scope,tags:input.tags,confidence:input.confidence,stability:input.stability,source:input.source,metadata:input.metadata}),next=input.expiresAt?{...record3,expiresAt:input.expiresAt}:record3;return validateMemoryRecordRules(next,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets})}resolveRecordScope(scope){let allowedScopes=this.deriveAllowedScopes();if(!scope){let defaultScope=allowedScopes[1]??allowedScopes[0];if(!defaultScope)throw new MemoryValidationError("memory scope is not available for this context");return defaultScope}return validateRequestedScopes([scope],allowedScopes,"memory scope is not allowed for this context"),scope}assertEnabled(){if(!this.config.enabled)throw new MemoryDisabledError}}function createMemoryGateway(context,options={}){return new MemoryGateway(context,options)}function createConfiguredMemoryProvider(directory,config3){if(config3.provider==="sqlite")return getOrCreateProvider(directory,config3);return new LocalJsonlMemoryProvider(directory,config3)}function sourceFromEvidence(evidenceRefs,context){let first=evidenceRefs[0];if(!first)return{type:"agent",createdBy:context.agentId??context.agentRole};if(/^https?:\/\//i.test(first))return{type:"web",url:first};if(/^[a-f0-9]{40}$/i.test(first))return{type:"commit",commitSha:first};let filePath=extractFilePaths(evidenceRefs)[0]??first;if(filePath!==first&&(filePath.includes("/")||filePath.includes("\\")||filePath.includes(".")))return{type:"file",filePath};if(first.includes("/")||first.includes("\\")||first.includes("."))return{type:"file",filePath:first};return{type:"manual",ref:first}}function createStableId(value){return createHash14("sha256").update(value.toLowerCase()).digest("hex").slice(0,16)}function readGitRemoteUrl(directory){if(gitRemoteUrlCache.has(directory))return gitRemoteUrlCache.get(directory);let gitConfigPath=path85.join(directory,".git","config");if(!existsSync48(gitConfigPath)){gitRemoteUrlCache.set(directory,void 0);return}try{let remoteUrl=readFileSync28(gitConfigPath,"utf-8").match(/\[remote "origin"\][\s\S]*?\n\s*url\s*=\s*(.+)/)?.[1]?.trim();return gitRemoteUrlCache.set(directory,remoteUrl),remoteUrl}catch{gitRemoteUrlCache.set(directory,void 0);return}}function validateRequestedScopes(requested,allowed,disallowedMessage="recall scope is not allowed for this context"){if(requested.length===0)throw new MemoryValidationError("recall scopes must not be empty");let allowedKeys=new Set(allowed.map(scopeKey));for(let scope of requested)if(!allowedKeys.has(scopeKey(scope)))throw new MemoryValidationError(disallowedMessage);return requested}function resolveInjectionSkipReason(diagnostics){if(diagnostics.returnedCount>0)return;if(diagnostics.candidateCount===0)return"no_results";let signalEligibleCount=diagnostics.candidateCount-diagnostics.preScoredFilteredCount;if(signalEligibleCount>0&&diagnostics.noSignalCount>0&&diagnostics.noSignalCount>=signalEligibleCount)return"no_signal";if(diagnostics.belowThresholdCount>0)return"below_threshold";return"no_results"}function scopeKey(scope){return JSON.stringify({type:scope.type,userId:scope.userId,workspaceId:scope.workspaceId,projectId:scope.projectId,repoId:scope.repoId,repoRoot:scope.repoRoot?path85.resolve(scope.repoRoot):void 0,runId:scope.runId,agentId:scope.agentId})}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function clampInt(value,min,max){return Math.trunc(clamp(value,min,max))}function normalizeTags2(tags){return Array.from(new Set(tags.map((tag)=>tag.toLowerCase().replace(/[^\w-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")).filter(Boolean))).slice(0,32)}function normalizeMemoryPatch(patch){return{...patch,text:patch.text===void 0?void 0:normalizeMemoryText(patch.text),tags:patch.tags===void 0?void 0:normalizeTags2(patch.tags)}}function inferTags2(text){let lower=text.toLowerCase(),tags=[];for(let[tag,pattern]of[["testing",/\b(test|spec|bun|jest|vitest)\b/],["tooling",/\b(pnpm|npm|yarn|bun|biome|eslint|typescript)\b/],["security",/\b(security|auth|token|secret|password|csp)\b/],["api",/\b(api|endpoint|graphql|rest|sdk)\b/],["architecture",/\b(architecture|decision|adr|pattern)\b/],["failure",/\b(fail|failure|regression|flaky|timeout)\b/]])if(pattern.test(lower))tags.push(tag);return tags}function extractFilePaths(refs){let seen=new Set,paths=[];for(let ref of refs){FILE_PATH_REGEX.lastIndex=0;let matches=ref.match(FILE_PATH_REGEX);if(!matches)continue;for(let m of matches)if(!seen.has(m)){if(seen.add(m),paths.push(m),paths.length>=20)return paths}}return paths}function extractSymbols(refs){let seen=new Set,symbols=[],identRegex=/\b[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*\b/g;for(let ref of refs){identRegex.lastIndex=0;let matches=ref.match(identRegex);if(!matches)continue;for(let m of matches)if(m.length>=3&&!seen.has(m)&&!RESERVED_IDENTIFIERS.has(m)){if(seen.add(m),symbols.push(m),symbols.length>=20)return symbols}}return symbols}var gitRemoteUrlCache,FILE_PATH_REGEX,RESERVED_IDENTIFIERS;var init_gateway=__esm(()=>{init_config3();init_errors6();init_local_jsonl_provider();init_prompt_block();init_provider_pool();init_redaction();init_schema2();gitRemoteUrlCache=new Map;FILE_PATH_REGEX=/\b(?:src|tests|test|docs|scripts|packages|lib|config|examples|internal|cmd|pkg|bin|tools|cli|api|server|client|app|core|utils|hooks|services|commands|agents|memory)\/[A-Za-z0-9._/@+-]+/g,RESERVED_IDENTIFIERS=new Set(["const","let","var","function","class","interface","type","async","await","return","if","else","for","while","do","switch","case","break","continue","new","this","super","extends","implements","import","export","from","default","try","catch","finally","throw","typeof","instanceof","in","of","as","yield","static","get","set","readonly","public","private","protected"])});import*as fs38 from"node:fs/promises";import*as os19 from"node:os";import*as path86 from"node:path";async function evaluateMemoryRecallFixtures(options){let fixtureDirectory=path86.resolve(options.fixtureDirectory),providers=options.providers??DEFAULT_PROVIDERS,modes=options.modes??DEFAULT_MODES,generatedAt=new Date().toISOString(),fixtures=await loadRecallEvaluationFixtures(fixtureDirectory),runs=[];for(let fixture of fixtures){let materialized=materializeFixture(fixture);for(let providerName of providers){let tempRoot=await fs38.realpath(await fs38.mkdtemp(path86.join(os19.tmpdir(),"swarm-memory-eval-"))),provider=createEvaluationProvider(providerName,tempRoot);try{await provider.initialize?.();for(let record3 of materialized.records)await provider.upsert(record3);for(let mode of modes){let request=buildRecallRequest(fixture,mode),retrievedIds=(await provider.recall(request)).map((item)=>item.record.id),run=buildRun({fixture,provider:providerName,mode,k:fixture.k??request.maxItems,retrievedIds,materialized});runs.push(run)}}finally{if(await provider.close?.(),!options.keepTempRoots)await fs38.rm(tempRoot,{recursive:!0,force:!0})}}}return{schema_version:1,generated_at:generatedAt,fixture_directory:fixtureDirectory,providers,modes,summary:summarizeRuns(fixtures.length,runs),runs}}async function loadRecallEvaluationFixtures(fixtureDirectory){let files=(await fs38.readdir(fixtureDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).map((entry)=>entry.name).sort((a,b)=>a.localeCompare(b)),fixtures=[];for(let file3 of files){let raw=await fs38.readFile(path86.join(fixtureDirectory,file3),"utf-8");fixtures.push(validateFixture(JSON.parse(raw),file3))}return fixtures}function createEvaluationProvider(provider,root){let config3={...DEFAULT_MEMORY_CONFIG,enabled:!0,provider};return createConfiguredMemoryProvider(root,config3)}function buildRecallRequest(fixture,mode){let maxItems=fixture.maxItems??fixture.k??5;return{query:fixture.query,task:fixture.task,agentRole:mode==="curator"?"curator":fixture.agentRole,mode,scopes:fixture.scopes,kinds:fixture.kinds,maxItems,tokenBudget:fixture.tokenBudget??1000,minScore:mode==="injection"?0.25:0,requireQuerySignal:mode==="injection"}}function materializeFixture(fixture){let idsByLabel=new Map,labelsById=new Map,baseRecords=fixture.records.map((record3)=>{let base={scope:record3.scope,kind:record3.kind,text:record3.text},id=createMemoryId(base);return idsByLabel.set(record3.label,id),labelsById.set(id,record3.label),{input:record3,id,base}}),expectedIds=new Set(fixture.expectedLabels.map((label)=>{let id=idsByLabel.get(label);if(!id)throw Error(`fixture ${fixture.name} expected unknown label ${label}`);return id})),allowedScopeKeys=new Set(fixture.scopes.map(stableScopeKey)),staleIds=new Set,crossScopeIds=new Set,sameScopeNoiseIds=new Set;return{records:baseRecords.map(({input,id,base})=>{let supersededBy=input.state?.supersededByLabel?idsByLabel.get(input.state.supersededByLabel):void 0;if(input.state?.supersededByLabel&&!supersededBy)throw Error(`fixture ${fixture.name} record ${input.label} supersedes unknown label ${input.state.supersededByLabel}`);let metadata={...input.metadata??{},fixture:fixture.name,fixtureLabel:input.label,...input.state?.deleted?{deleted:!0}:{}},record3={id,...base,tags:input.tags??[],confidence:input.confidence??0.8,stability:input.stability??"durable",source:input.source??{type:"manual",ref:fixture.name},createdAt:DEFAULT_TIMESTAMP,updatedAt:DEFAULT_TIMESTAMP,expiresAt:input.state?.expiresAt,supersededBy,contentHash:computeMemoryContentHash(base),metadata};if(record3.metadata.deleted===!0||record3.supersededBy||record3.expiresAt&&Date.parse(record3.expiresAt)<=Date.now())staleIds.add(record3.id);if(!allowedScopeKeys.has(stableScopeKey(record3.scope)))crossScopeIds.add(record3.id);else if(!expectedIds.has(record3.id)&&!staleIds.has(record3.id))sameScopeNoiseIds.add(record3.id);return validateMemoryRecordRules(record3,{rejectDurableSecrets:!0})}),idsByLabel,labelsById,expectedIds,staleIds,crossScopeIds,sameScopeNoiseIds}}function buildRun(args2){let{fixture,provider,mode,k,retrievedIds,materialized}=args2,relevantAtK=retrievedIds.slice(0,k).filter((id)=>materialized.expectedIds.has(id)).length,crossScopeLeakCount=retrievedIds.filter((id)=>materialized.crossScopeIds.has(id)).length,staleMemoryCount=retrievedIds.filter((id)=>materialized.staleIds.has(id)).length,noisyInjectionCount=mode==="injection"?retrievedIds.filter((id)=>materialized.sameScopeNoiseIds.has(id)).length:0,sameScopeNoiseCount=retrievedIds.filter((id)=>materialized.sameScopeNoiseIds.has(id)).length,metrics={"precision@k":relevantAtK/Math.max(k,1),"recall@k":relevantAtK/Math.max(materialized.expectedIds.size,1),injection_count:mode==="injection"?retrievedIds.length:0,noisy_injection_count:noisyInjectionCount,same_scope_noise_count:sameScopeNoiseCount,cross_scope_leak_count:crossScopeLeakCount,stale_memory_count:staleMemoryCount};return{fixture:fixture.name,provider,mode,k,query:fixture.query,expected_labels:fixture.expectedLabels,expected_ids:fixture.expectedLabels.map((label)=>materialized.idsByLabel.get(label)??label),retrieved_labels:retrievedIds.map((id)=>materialized.labelsById.get(id)??id),retrieved_ids:retrievedIds,metrics,passed:metrics["recall@k"]>=1&&metrics.noisy_injection_count===0&&metrics.cross_scope_leak_count===0&&metrics.stale_memory_count===0}}function summarizeRuns(fixtureCount,runs){let total=runs.reduce((acc,run)=>{if(acc["precision@k"]+=run.metrics["precision@k"],acc["recall@k"]+=run.metrics["recall@k"],acc.injection_count+=run.metrics.injection_count,acc.noisy_injection_count+=run.metrics.noisy_injection_count,acc.same_scope_noise_count+=run.metrics.same_scope_noise_count,acc.cross_scope_leak_count+=run.metrics.cross_scope_leak_count,acc.stale_memory_count+=run.metrics.stale_memory_count,run.passed)acc.passed_run_count++;return acc},{"precision@k":0,"recall@k":0,injection_count:0,noisy_injection_count:0,same_scope_noise_count:0,cross_scope_leak_count:0,stale_memory_count:0,passed_run_count:0}),denominator=Math.max(runs.length,1);return{fixture_count:fixtureCount,run_count:runs.length,passed_run_count:total.passed_run_count,"precision@k":total["precision@k"]/denominator,"recall@k":total["recall@k"]/denominator,injection_count:total.injection_count,noisy_injection_count:total.noisy_injection_count,same_scope_noise_count:total.same_scope_noise_count,cross_scope_leak_count:total.cross_scope_leak_count,stale_memory_count:total.stale_memory_count}}function validateFixture(value,file3){if(!value||typeof value!=="object")throw Error(`memory recall fixture ${file3} must be an object`);let fixture=value;if(typeof fixture.name!=="string"||!fixture.name)throw Error(`memory recall fixture ${file3} is missing name`);if(typeof fixture.query!=="string"||fixture.query.length<3)throw Error(`memory recall fixture ${file3} has invalid query`);if(!Array.isArray(fixture.scopes)||fixture.scopes.length===0)throw Error(`memory recall fixture ${file3} must define scopes`);let scopes=fixture.scopes.map((scope,index)=>validateScope(scope,file3,`scope #${index+1}`));if(!Array.isArray(fixture.expectedLabels)||fixture.expectedLabels.length===0)throw Error(`memory recall fixture ${file3} must define expectedLabels`);let expectedLabels=fixture.expectedLabels.map((label,index)=>{if(typeof label!=="string"||!label)throw Error(`memory recall fixture ${file3} expectedLabels #${index+1} must be a non-empty string`);return label});if(!Array.isArray(fixture.records)||fixture.records.length===0)throw Error(`memory recall fixture ${file3} must define records`);let records=fixture.records.map((record3,index)=>validateFixtureRecord(record3,file3,index));return{...fixture,name:fixture.name,query:fixture.query,scopes,expectedLabels,records}}function validateFixtureRecord(value,file3,index){if(!value||typeof value!=="object")throw Error(`memory recall fixture ${file3} record #${index+1} must be an object`);let record3=value,labelForError=typeof record3.label==="string"&&record3.label?record3.label:`#${index+1}`;if(typeof record3.label!=="string"||!record3.label)throw Error(`memory recall fixture ${file3} record ${labelForError} is missing label`);let scope=validateScope(record3.scope,file3,`record ${record3.label}`);if(!("kind"in record3)||record3.kind==="")throw Error(`memory recall fixture ${file3} record ${record3.label} is missing kind`);if(typeof record3.kind!=="string")throw Error(`memory recall fixture ${file3} record ${record3.label} has invalid kind`);let parsedKind=MemoryKindSchema.safeParse(record3.kind);if(!parsedKind.success)throw Error(`memory recall fixture ${file3} record ${record3.label} has invalid kind`);if(!("text"in record3)||record3.text==="")throw Error(`memory recall fixture ${file3} record ${record3.label} is missing text`);if(typeof record3.text!=="string")throw Error(`memory recall fixture ${file3} record ${record3.label} has invalid text`);return{...record3,label:record3.label,scope,kind:parsedKind.data,text:record3.text}}function validateScope(value,file3,descriptor){if(!value||typeof value!=="object")throw Error(`memory recall fixture ${file3} ${descriptor} is missing scope`);let scope=value;if(typeof scope.type!=="string")throw Error(`memory recall fixture ${file3} ${descriptor} has invalid scope type`);let parsed=MemoryScopeRefSchema.safeParse(scope);if(!parsed.success)throw Error(`memory recall fixture ${file3} ${descriptor} has invalid scope`);return parsed.data}var DEFAULT_PROVIDERS,DEFAULT_MODES,DEFAULT_TIMESTAMP="2026-05-26T12:00:00.000Z";var init_evaluation=__esm(()=>{init_config3();init_gateway();init_schema2();DEFAULT_PROVIDERS=["local-jsonl","sqlite"],DEFAULT_MODES=["manual","injection","curator"]});function extractMemoryProposalsFromAgentOutput(outputText){let candidates=candidateJsonBlocks(outputText);for(let candidate of candidates){let parsedJson=parseJsonObject(candidate);if(parsedJson===null)continue;let parsed=AgentOutputMemorySchema.safeParse(parsedJson);if(!parsed.success)return{proposals:[],error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")};if(parsed.data.memoryProposals)return{proposals:parsed.data.memoryProposals}}return{proposals:[]}}function extractCuratorMemoryDecisionsFromAgentOutput(outputText){let candidates=candidateJsonBlocks(outputText);for(let candidate of candidates){let parsedJson=parseJsonObject(candidate);if(parsedJson===null)continue;let parsed=CuratorOutputMemoryDecisionSchema.safeParse(parsedJson);if(!parsed.success)return{decisions:[],error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")};if(parsed.data.curatorMemoryDecisions)return{decisions:parsed.data.curatorMemoryDecisions}}return{decisions:[]}}function candidateJsonBlocks(outputText){let trimmed=outputText.trim(),candidates=[];if(trimmed.startsWith("{")&&trimmed.endsWith("}"))candidates.push(trimmed);let fencePattern=/```(?:json)?\s*([\s\S]*?)```/gi;for(let match of outputText.matchAll(fencePattern)){let block=match[1]?.trim();if(block?.startsWith("{")&&block.endsWith("}"))candidates.push(block)}return candidates}function parseJsonObject(candidate){try{let parsed=JSON.parse(candidate);return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}catch{return null}}var AgentMemoryProposalSchema,AgentOutputMemorySchema,CuratorOutputMemoryDecisionSchema;var init_agent_output_schema=__esm(()=>{init_zod();init_schema2();AgentMemoryProposalSchema=exports_external.object({operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]),kind:MemoryKindSchema.optional(),text:exports_external.string().min(1).max(2000).optional(),targetMemoryId:exports_external.string().optional(),relatedMemoryIds:exports_external.array(exports_external.string()).optional(),rationale:exports_external.string().min(1).max(2000),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional()}).strict(),AgentOutputMemorySchema=exports_external.object({memoryProposals:exports_external.array(AgentMemoryProposalSchema).max(20).optional()}).passthrough(),CuratorOutputMemoryDecisionSchema=exports_external.object({curatorMemoryDecisions:exports_external.array(CuratorMemoryDecisionSchema).max(20).optional()}).passthrough()});function buildMemoryRecallPlan(input,options={}){let profile=options.profile??resolveMemoryRecallProfile(input.agentRole),scopes=options.scopes??[];return{query:buildRecallQuery(input),scopes,kinds:[...profile.kinds],maxItems:profile.maxItems,tokenBudget:profile.tokenBudget}}function buildRecallQuery(input){let lines=[`${input.agentRole} task: ${input.agentTask}`,`user goal: ${input.userGoal}`],repoProject=[input.projectId,input.repoId,input.repoRoot].filter((value)=>Boolean(value?.trim())).join(" ");if(repoProject)lines.push(`repo/project: ${repoProject}`);if(input.touchedFiles&&input.touchedFiles.length>0)lines.push(`touched files: ${input.touchedFiles.join(", ")}`);if(input.currentPlanSummary?.trim())lines.push(`current plan: ${input.currentPlanSummary.trim()}`);return lines.join(`
1525
+ `},{version:7,name:"add_recall_learning_columns",sql:`
1526
+ ALTER TABLE memory_recall_usage ADD COLUMN q_value REAL DEFAULT 0.5;
1527
+ ALTER TABLE memory_recall_usage ADD COLUMN last_reward REAL;
1528
+ ALTER TABLE memory_recall_usage ADD COLUMN task_outcome TEXT;
1529
+ ALTER TABLE memory_recall_usage ADD COLUMN council_verdict_json TEXT;
1530
+ `},{version:8,name:"add_recall_reward_idempotency_key",sql:`
1531
+ ALTER TABLE memory_recall_usage ADD COLUMN reward_key TEXT;
1532
+ `}];FTS_STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","goal","how","in","into","is","it","of","on","or","role","task","that","the","this","to","user","what","when","with"])});import{realpathSync as realpathSync8}from"node:fs";import*as path84 from"node:path";function markAsPooled(provider){let originalClose=provider.close;if(provider.close=()=>{return releaseProvider(provider),Promise.resolve()},provider[POOLED_MARKER]=!0,originalClose)provider[REAL_CLOSE]=originalClose}function callRealClose(provider){let realClose=provider[REAL_CLOSE];try{realClose?.call(provider)}catch(err){let msg=err instanceof Error?err.message:String(err);if(process.env.OPENCODE_SWARM_DEBUG==="1")console.debug(`[provider-pool] real close failed: ${msg}`)}}function isPooledProvider(provider){return POOLED_MARKER in provider}function getOrCreateProvider(directory,config3){let key=resolvePoolKey(directory),existing=entriesByKey.get(key);if(existing)return moveToHead(existing),existing.refCount++,existing.provider;for(let deferred of deferredEntries)if(deferred.key===key){if(deferredEntries.delete(deferred),entriesByKey.size>=MAX_POOL_SIZE)evictLru();if(deferred.prev=null,deferred.next=head,head)head.prev=deferred;if(head=deferred,!tail)tail=deferred;return entriesByKey.set(key,deferred),deferred.refCount++,deferred.provider}let provider=new SQLiteMemoryProvider(directory,config3);if(markAsPooled(provider),entriesByKey.size>=MAX_POOL_SIZE)evictLru();let entry={key,provider,refCount:1,prev:null,next:head};if(head)head.prev=entry;if(head=entry,!tail)tail=entry;return entriesByKey.set(key,entry),provider}function releaseProvider(provider){for(let[_key,entry]of entriesByKey)if(entry.provider===provider){entry.refCount=Math.max(0,entry.refCount-1);return}for(let entry of deferredEntries)if(entry.provider===provider){if(entry.refCount--,entry.refCount<=0)deferredEntries.delete(entry),callRealClose(provider);return}if(isPooledProvider(provider))callRealClose(provider)}function evictLru(){if(!tail)return;let evicted=tail;if(entriesByKey.delete(evicted.key),unlinkEntry(evicted),evicted.refCount>0)deferredEntries.add(evicted);else callRealClose(evicted.provider)}function moveToHead(entry){if(head===entry)return;if(unlinkEntry(entry),entry.prev=null,entry.next=head,head)head.prev=entry;if(head=entry,!tail)tail=entry}function unlinkEntry(entry){if(entry.prev)entry.prev.next=entry.next;if(entry.next)entry.next.prev=entry.prev;if(head===entry)head=entry.next;if(tail===entry)tail=entry.prev}function resolvePoolKey(directory){try{return realpathSync8(directory)}catch{return path84.resolve(directory)}}function evictAndClose(directory){let key=resolvePoolKey(directory),active=entriesByKey.get(key);if(active)entriesByKey.delete(key),unlinkEntry(active),callRealClose(active.provider);for(let deferred of[...deferredEntries])if(deferred.key===key)deferredEntries.delete(deferred),callRealClose(deferred.provider)}var MAX_POOL_SIZE=16,POOLED_MARKER,REAL_CLOSE,head=null,tail=null,entriesByKey,deferredEntries;var init_provider_pool=__esm(()=>{init_sqlite_provider();POOLED_MARKER=Symbol("opencode-swarm-pooled-provider"),REAL_CLOSE=Symbol("opencode-swarm-real-close"),entriesByKey=new Map,deferredEntries=new Set});import{createHash as createHash14}from"node:crypto";import{existsSync as existsSync48,readFileSync as readFileSync28}from"node:fs";import*as path85 from"node:path";class MemoryGateway{context;config;provider;now;disposed=!1;constructor(context,options={}){this.context=context;this.config=resolveMemoryConfig(options.config??DEFAULT_MEMORY_CONFIG),this.provider=options.provider??createConfiguredMemoryProvider(context.directory,this.config),this.now=options.now??(()=>new Date)}isEnabled(){return this.config.enabled}async dispose(){if(this.disposed)return;this.disposed=!0,await this.provider.close?.()}deriveAllowedScopes(){let resolvedRoot=path85.resolve(this.context.directory),repoId=createStableId(readGitRemoteUrl(resolvedRoot)??path85.basename(resolvedRoot)),scopes=[{type:"workspace",workspaceId:createStableId(path85.dirname(resolvedRoot))},{type:"repository",repoId,repoRoot:resolvedRoot}];if(this.context.runId||this.context.sessionID)scopes.push({type:"run",runId:this.context.runId??this.context.sessionID});if(this.context.agentId||this.context.agentRole)scopes.push({type:"agent",agentId:this.context.agentId??this.context.agentRole,runId:this.context.runId??this.context.sessionID});return scopes}async recall(input){this.assertEnabled();let query=normalizeMemoryText(input.query);if(query.length<3)throw new MemoryValidationError("query must be at least 3 characters");let maxItems=clampInt(input.maxItems??this.config.recall.defaultMaxItems,1,20),tokenBudget=clampInt(input.tokenBudget??this.config.recall.defaultTokenBudget,100,5000),generatedAt=this.now().toISOString(),allowedScopes=this.deriveAllowedScopes(),scopes=input.scopes?validateRequestedScopes(input.scopes,allowedScopes):allowedScopes,request={query,task:input.task,agentRole:this.context.agentRole,mode:input.mode??"manual",scopes,kinds:input.kinds,maxItems,tokenBudget,minScore:input.minScore??this.config.recall.minScore,qValueBoostWeight:this.config.learning.qValueBoostWeight,suppressionThreshold:this.config.learning.suppressionThreshold,includeLowQ:input.includeLowQ,requireQuerySignal:input.requireQuerySignal,includeExpired:input.includeExpired},recallResult=this.provider.recallWithDiagnostics?await this.provider.recallWithDiagnostics(request):{items:await this.provider.recall(request)},bundle=toRecallBundle({id:createBundleId(query,generatedAt),query,generatedAt,items:recallResult.items,tokenBudget,diagnostics:recallResult.diagnostics?{injectionSkipReason:input.mode==="injection"?resolveInjectionSkipReason(recallResult.diagnostics):void 0,candidateCount:recallResult.diagnostics.candidateCount,preScoredFilteredCount:recallResult.diagnostics.preScoredFilteredCount,noSignalCount:recallResult.diagnostics.noSignalCount,belowThresholdCount:recallResult.diagnostics.belowThresholdCount}:void 0});return await this.provider.recordRecallUsage?.({bundleId:bundle.id,query,scopes,kinds:input.kinds,memoryIds:bundle.items.map((item)=>item.record.id),scores:bundle.items.map((item)=>item.score),tokenEstimate:bundle.tokenEstimate,agentRole:this.context.agentRole,runId:this.context.runId??this.context.sessionID,timestamp:generatedAt}),bundle}async propose(input){if(this.assertEnabled(),!this.provider.createProposal)throw new MemoryValidationError("memory provider does not support proposals");let redactedFields=new Set,redactProposalField=(field,value)=>{let redacted=redactSecrets(value);if(redacted!==value)redactedFields.add(field);return redacted},rationale=redactProposalField("rationale",normalizeMemoryText(input.rationale));if(!rationale)throw new MemoryValidationError("rationale is required");let evidenceRefs=(input.evidenceRefs??[]).map((ref)=>normalizeMemoryText(ref)).filter(Boolean).map((ref)=>redactProposalField("evidenceRefs",ref)).slice(0,20),needsRecord=input.operation==="add"||input.operation==="update"||input.operation==="supersede",proposedRecord,status="pending",reviewer,reviewedAt,rejectionReason,targetMemoryId=input.targetMemoryId===void 0?void 0:redactProposalField("targetMemoryId",normalizeMemoryText(input.targetMemoryId)),relatedMemoryIds=input.relatedMemoryIds?.map((id)=>redactProposalField("relatedMemoryIds",normalizeMemoryText(id))),proposalText=`${input.operation}:${targetMemoryId??""}`;if(needsRecord){if(!input.kind)throw new MemoryValidationError("kind is required for this operation");if(!input.text)throw new MemoryValidationError("text is required for this operation");proposalText=input.text;let normalizedText=normalizeMemoryText(input.text),redactedText=redactProposalField("text",normalizedText),extractedPaths=extractFilePaths(evidenceRefs),extractedSymbols=extractSymbols(evidenceRefs),recordMetadata={};if(extractedPaths.length>0)recordMetadata.files=extractedPaths;if(extractedSymbols.length>0)recordMetadata.symbols=extractedSymbols;proposedRecord=this.createRecord({kind:input.kind,text:redactedText,evidenceRefs,source:sourceFromEvidence(evidenceRefs,this.context),metadata:recordMetadata}),validateMemoryRecordRules(proposedRecord,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets})}if(redactedFields.size>0)status="rejected",reviewer="auto_policy",reviewedAt=this.now().toISOString(),rejectionReason=`proposal field(s) contained a likely secret and were redacted: ${Array.from(redactedFields).join(", ")}`;if((input.operation==="update"||input.operation==="delete"||input.operation==="supersede")&&!targetMemoryId)throw new MemoryValidationError(`${input.operation} proposals require targetMemoryId`);if(input.operation==="merge"&&(relatedMemoryIds??[]).length<2)throw new MemoryValidationError("merge proposals require relatedMemoryIds");let createdAt=this.now().toISOString(),proposer=this.context.agentId??this.context.agentRole??this.context.sessionID??"unknown",proposal={id:createProposalId({createdAt,proposer,text:proposalText}),operation:input.operation,proposedRecord,targetMemoryId,relatedMemoryIds,proposedBy:{agentRole:this.context.agentRole,agentId:this.context.agentId,runId:this.context.runId??this.context.sessionID},rationale,evidenceRefs,status,reviewer,reviewedAt,rejectionReason,createdAt,metadata:{}};return this.provider.createProposal(proposal)}async listMemories(filter={}){return this.assertEnabled(),this.provider.list(filter)}async listProposals(filter){if(this.assertEnabled(),!this.provider.listProposals)throw new MemoryValidationError("memory provider does not support proposals");return this.provider.listProposals(filter)}async listRecallUsage(filter){if(this.assertEnabled(),!this.provider.listRecallUsage)return[];return this.provider.listRecallUsage(filter)}async upsertCurated(record3){this.assertEnabled();let parsed=validateMemoryRecordRules(record3,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets});return this.provider.upsert(parsed)}async applyCuratorDecision(decision){if(this.assertEnabled(),!this.provider.applyCuratorDecision)throw new MemoryValidationError("memory provider does not support curator decisions");let parsed=validateCuratorMemoryDecision(decision),resolved=this.resolveCuratorDecision(parsed);return this.provider.applyCuratorDecision(resolved)}createRecord(input){let now=this.now().toISOString(),text=normalizeMemoryText(input.text),scope=this.resolveRecordScope(input.scope),kind=input.kind,stability=input.stability??(kind==="scratch"?"ephemeral":"durable"),expiresAt=kind==="scratch"?new Date(this.now().getTime()+604800000).toISOString():void 0,recordBase={scope,kind,text};return{id:createMemoryId(recordBase),scope,kind,text,tags:normalizeTags2(input.tags??inferTags2(text)),confidence:clamp(input.confidence??0.5,0,1),stability,source:input.source??sourceFromEvidence(input.evidenceRefs??[],this.context),createdAt:now,updatedAt:now,expiresAt,contentHash:computeMemoryContentHash(recordBase),metadata:input.metadata??{}}}resolveCuratorDecision(decision){switch(decision.action){case"add":return{action:"add",proposalId:decision.proposalId,memory:this.createRecordFromNew(decision.memory)};case"supersede":return{action:"supersede",proposalId:decision.proposalId,oldMemoryId:decision.oldMemoryId,replacement:this.createRecordFromNew(decision.replacement),reason:normalizeMemoryText(decision.reason)};case"update":{let patch=normalizeMemoryPatch(decision.patch);if(patch.scope)patch.scope=this.resolveRecordScope(patch.scope);return{action:"update",proposalId:decision.proposalId,targetMemoryId:decision.targetMemoryId,patch,reason:normalizeMemoryText(decision.reason)}}case"reject":case"noop":return{action:decision.action,proposalId:decision.proposalId,reason:normalizeMemoryText(decision.reason)}}}createRecordFromNew(input){let record3=this.createRecord({kind:input.kind,text:input.text,scope:input.scope,tags:input.tags,confidence:input.confidence,stability:input.stability,source:input.source,metadata:input.metadata}),next=input.expiresAt?{...record3,expiresAt:input.expiresAt}:record3;return validateMemoryRecordRules(next,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets})}resolveRecordScope(scope){let allowedScopes=this.deriveAllowedScopes();if(!scope){let defaultScope=allowedScopes[1]??allowedScopes[0];if(!defaultScope)throw new MemoryValidationError("memory scope is not available for this context");return defaultScope}return validateRequestedScopes([scope],allowedScopes,"memory scope is not allowed for this context"),scope}assertEnabled(){if(!this.config.enabled)throw new MemoryDisabledError}}function createMemoryGateway(context,options={}){return new MemoryGateway(context,options)}function createConfiguredMemoryProvider(directory,config3){if(config3.provider==="sqlite")return getOrCreateProvider(directory,config3);return new LocalJsonlMemoryProvider(directory,config3)}function sourceFromEvidence(evidenceRefs,context){let first=evidenceRefs[0];if(!first)return{type:"agent",createdBy:context.agentId??context.agentRole};if(/^https?:\/\//i.test(first))return{type:"web",url:first};if(/^[a-f0-9]{40}$/i.test(first))return{type:"commit",commitSha:first};let filePath=extractFilePaths(evidenceRefs)[0]??first;if(filePath!==first&&(filePath.includes("/")||filePath.includes("\\")||filePath.includes(".")))return{type:"file",filePath};if(first.includes("/")||first.includes("\\")||first.includes("."))return{type:"file",filePath:first};return{type:"manual",ref:first}}function createStableId(value){return createHash14("sha256").update(value.toLowerCase()).digest("hex").slice(0,16)}function readGitRemoteUrl(directory){if(gitRemoteUrlCache.has(directory))return gitRemoteUrlCache.get(directory);let gitConfigPath=path85.join(directory,".git","config");if(!existsSync48(gitConfigPath)){gitRemoteUrlCache.set(directory,void 0);return}try{let remoteUrl=readFileSync28(gitConfigPath,"utf-8").match(/\[remote "origin"\][\s\S]*?\n\s*url\s*=\s*(.+)/)?.[1]?.trim();return gitRemoteUrlCache.set(directory,remoteUrl),remoteUrl}catch{gitRemoteUrlCache.set(directory,void 0);return}}function validateRequestedScopes(requested,allowed,disallowedMessage="recall scope is not allowed for this context"){if(requested.length===0)throw new MemoryValidationError("recall scopes must not be empty");let allowedKeys=new Set(allowed.map(scopeKey));for(let scope of requested)if(!allowedKeys.has(scopeKey(scope)))throw new MemoryValidationError(disallowedMessage);return requested}function resolveInjectionSkipReason(diagnostics){if(diagnostics.returnedCount>0)return;if(diagnostics.candidateCount===0)return"no_results";let signalEligibleCount=diagnostics.candidateCount-diagnostics.preScoredFilteredCount;if(signalEligibleCount>0&&diagnostics.noSignalCount>0&&diagnostics.noSignalCount>=signalEligibleCount)return"no_signal";if(diagnostics.belowThresholdCount>0)return"below_threshold";return"no_results"}function scopeKey(scope){return JSON.stringify({type:scope.type,userId:scope.userId,workspaceId:scope.workspaceId,projectId:scope.projectId,repoId:scope.repoId,repoRoot:scope.repoRoot?path85.resolve(scope.repoRoot):void 0,runId:scope.runId,agentId:scope.agentId})}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function clampInt(value,min,max){return Math.trunc(clamp(value,min,max))}function normalizeTags2(tags){return Array.from(new Set(tags.map((tag)=>tag.toLowerCase().replace(/[^\w-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")).filter(Boolean))).slice(0,32)}function normalizeMemoryPatch(patch){return{...patch,text:patch.text===void 0?void 0:normalizeMemoryText(patch.text),tags:patch.tags===void 0?void 0:normalizeTags2(patch.tags)}}function inferTags2(text){let lower=text.toLowerCase(),tags=[];for(let[tag,pattern]of[["testing",/\b(test|spec|bun|jest|vitest)\b/],["tooling",/\b(pnpm|npm|yarn|bun|biome|eslint|typescript)\b/],["security",/\b(security|auth|token|secret|password|csp)\b/],["api",/\b(api|endpoint|graphql|rest|sdk)\b/],["architecture",/\b(architecture|decision|adr|pattern)\b/],["failure",/\b(fail|failure|regression|flaky|timeout)\b/]])if(pattern.test(lower))tags.push(tag);return tags}function extractFilePaths(refs){let seen=new Set,paths=[];for(let ref of refs){FILE_PATH_REGEX.lastIndex=0;let matches=ref.match(FILE_PATH_REGEX);if(!matches)continue;for(let m of matches)if(!seen.has(m)){if(seen.add(m),paths.push(m),paths.length>=20)return paths}}return paths}function extractSymbols(refs){let seen=new Set,symbols=[],identRegex=/\b[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*\b/g;for(let ref of refs){identRegex.lastIndex=0;let matches=ref.match(identRegex);if(!matches)continue;for(let m of matches)if(m.length>=3&&!seen.has(m)&&!RESERVED_IDENTIFIERS.has(m)){if(seen.add(m),symbols.push(m),symbols.length>=20)return symbols}}return symbols}var gitRemoteUrlCache,FILE_PATH_REGEX,RESERVED_IDENTIFIERS;var init_gateway=__esm(()=>{init_config3();init_errors6();init_local_jsonl_provider();init_prompt_block();init_provider_pool();init_redaction();init_schema2();gitRemoteUrlCache=new Map;FILE_PATH_REGEX=/\b(?:src|tests|test|docs|scripts|packages|lib|config|examples|internal|cmd|pkg|bin|tools|cli|api|server|client|app|core|utils|hooks|services|commands|agents|memory)\/[A-Za-z0-9._/@+-]+/g,RESERVED_IDENTIFIERS=new Set(["const","let","var","function","class","interface","type","async","await","return","if","else","for","while","do","switch","case","break","continue","new","this","super","extends","implements","import","export","from","default","try","catch","finally","throw","typeof","instanceof","in","of","as","yield","static","get","set","readonly","public","private","protected"])});import*as fs38 from"node:fs/promises";import*as os19 from"node:os";import*as path86 from"node:path";async function evaluateMemoryRecallFixtures(options){let fixtureDirectory=path86.resolve(options.fixtureDirectory),providers=options.providers??DEFAULT_PROVIDERS,modes=options.modes??DEFAULT_MODES,generatedAt=new Date().toISOString(),fixtures=await loadRecallEvaluationFixtures(fixtureDirectory),runs=[];for(let fixture of fixtures){let materialized=materializeFixture(fixture);for(let providerName of providers){let tempRoot=await fs38.realpath(await fs38.mkdtemp(path86.join(os19.tmpdir(),"swarm-memory-eval-"))),provider=createEvaluationProvider(providerName,tempRoot);try{await provider.initialize?.();for(let record3 of materialized.records)await provider.upsert(record3);for(let mode of modes){let request=buildRecallRequest(fixture,mode),retrievedIds=(await provider.recall(request)).map((item)=>item.record.id),run=buildRun({fixture,provider:providerName,mode,k:fixture.k??request.maxItems,retrievedIds,materialized});runs.push(run)}}finally{if(await provider.close?.(),!options.keepTempRoots)evictAndClose(tempRoot),await rmTempRoot(tempRoot)}}}return{schema_version:1,generated_at:generatedAt,fixture_directory:fixtureDirectory,providers,modes,summary:summarizeRuns(fixtures.length,runs),runs}}async function rmTempRoot(tempRoot){for(let attempt=0;attempt<10;attempt++)try{await fs38.rm(tempRoot,{recursive:!0,force:!0});return}catch(err){if(attempt===9)throw err;await new Promise((resolve37)=>setTimeout(resolve37,50))}}async function loadRecallEvaluationFixtures(fixtureDirectory){let files=(await fs38.readdir(fixtureDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).map((entry)=>entry.name).sort((a,b)=>a.localeCompare(b)),fixtures=[];for(let file3 of files){let raw=await fs38.readFile(path86.join(fixtureDirectory,file3),"utf-8");fixtures.push(validateFixture(JSON.parse(raw),file3))}return fixtures}function createEvaluationProvider(provider,root){let config3={...DEFAULT_MEMORY_CONFIG,enabled:!0,provider};return createConfiguredMemoryProvider(root,config3)}function buildRecallRequest(fixture,mode){let maxItems=fixture.maxItems??fixture.k??5;return{query:fixture.query,task:fixture.task,agentRole:mode==="curator"?"curator":fixture.agentRole,mode,scopes:fixture.scopes,kinds:fixture.kinds,maxItems,tokenBudget:fixture.tokenBudget??1000,minScore:mode==="injection"?0.25:0,requireQuerySignal:mode==="injection"}}function materializeFixture(fixture){let idsByLabel=new Map,labelsById=new Map,baseRecords=fixture.records.map((record3)=>{let base={scope:record3.scope,kind:record3.kind,text:record3.text},id=createMemoryId(base);return idsByLabel.set(record3.label,id),labelsById.set(id,record3.label),{input:record3,id,base}}),expectedIds=new Set(fixture.expectedLabels.map((label)=>{let id=idsByLabel.get(label);if(!id)throw Error(`fixture ${fixture.name} expected unknown label ${label}`);return id})),allowedScopeKeys=new Set(fixture.scopes.map(stableScopeKey)),staleIds=new Set,crossScopeIds=new Set,sameScopeNoiseIds=new Set;return{records:baseRecords.map(({input,id,base})=>{let supersededBy=input.state?.supersededByLabel?idsByLabel.get(input.state.supersededByLabel):void 0;if(input.state?.supersededByLabel&&!supersededBy)throw Error(`fixture ${fixture.name} record ${input.label} supersedes unknown label ${input.state.supersededByLabel}`);let metadata={...input.metadata??{},fixture:fixture.name,fixtureLabel:input.label,...input.state?.deleted?{deleted:!0}:{}},record3={id,...base,tags:input.tags??[],confidence:input.confidence??0.8,stability:input.stability??"durable",source:input.source??{type:"manual",ref:fixture.name},createdAt:DEFAULT_TIMESTAMP,updatedAt:DEFAULT_TIMESTAMP,expiresAt:input.state?.expiresAt,supersededBy,contentHash:computeMemoryContentHash(base),metadata};if(record3.metadata.deleted===!0||record3.supersededBy||record3.expiresAt&&Date.parse(record3.expiresAt)<=Date.now())staleIds.add(record3.id);if(!allowedScopeKeys.has(stableScopeKey(record3.scope)))crossScopeIds.add(record3.id);else if(!expectedIds.has(record3.id)&&!staleIds.has(record3.id))sameScopeNoiseIds.add(record3.id);return validateMemoryRecordRules(record3,{rejectDurableSecrets:!0})}),idsByLabel,labelsById,expectedIds,staleIds,crossScopeIds,sameScopeNoiseIds}}function buildRun(args2){let{fixture,provider,mode,k,retrievedIds,materialized}=args2,relevantAtK=retrievedIds.slice(0,k).filter((id)=>materialized.expectedIds.has(id)).length,crossScopeLeakCount=retrievedIds.filter((id)=>materialized.crossScopeIds.has(id)).length,staleMemoryCount=retrievedIds.filter((id)=>materialized.staleIds.has(id)).length,noisyInjectionCount=mode==="injection"?retrievedIds.filter((id)=>materialized.sameScopeNoiseIds.has(id)).length:0,sameScopeNoiseCount=retrievedIds.filter((id)=>materialized.sameScopeNoiseIds.has(id)).length,metrics={"precision@k":relevantAtK/Math.max(k,1),"recall@k":relevantAtK/Math.max(materialized.expectedIds.size,1),injection_count:mode==="injection"?retrievedIds.length:0,noisy_injection_count:noisyInjectionCount,same_scope_noise_count:sameScopeNoiseCount,cross_scope_leak_count:crossScopeLeakCount,stale_memory_count:staleMemoryCount};return{fixture:fixture.name,provider,mode,k,query:fixture.query,expected_labels:fixture.expectedLabels,expected_ids:fixture.expectedLabels.map((label)=>materialized.idsByLabel.get(label)??label),retrieved_labels:retrievedIds.map((id)=>materialized.labelsById.get(id)??id),retrieved_ids:retrievedIds,metrics,passed:metrics["recall@k"]>=1&&metrics.noisy_injection_count===0&&metrics.cross_scope_leak_count===0&&metrics.stale_memory_count===0}}function summarizeRuns(fixtureCount,runs){let total=runs.reduce((acc,run)=>{if(acc["precision@k"]+=run.metrics["precision@k"],acc["recall@k"]+=run.metrics["recall@k"],acc.injection_count+=run.metrics.injection_count,acc.noisy_injection_count+=run.metrics.noisy_injection_count,acc.same_scope_noise_count+=run.metrics.same_scope_noise_count,acc.cross_scope_leak_count+=run.metrics.cross_scope_leak_count,acc.stale_memory_count+=run.metrics.stale_memory_count,run.passed)acc.passed_run_count++;return acc},{"precision@k":0,"recall@k":0,injection_count:0,noisy_injection_count:0,same_scope_noise_count:0,cross_scope_leak_count:0,stale_memory_count:0,passed_run_count:0}),denominator=Math.max(runs.length,1);return{fixture_count:fixtureCount,run_count:runs.length,passed_run_count:total.passed_run_count,"precision@k":total["precision@k"]/denominator,"recall@k":total["recall@k"]/denominator,injection_count:total.injection_count,noisy_injection_count:total.noisy_injection_count,same_scope_noise_count:total.same_scope_noise_count,cross_scope_leak_count:total.cross_scope_leak_count,stale_memory_count:total.stale_memory_count}}function validateFixture(value,file3){if(!value||typeof value!=="object")throw Error(`memory recall fixture ${file3} must be an object`);let fixture=value;if(typeof fixture.name!=="string"||!fixture.name)throw Error(`memory recall fixture ${file3} is missing name`);if(typeof fixture.query!=="string"||fixture.query.length<3)throw Error(`memory recall fixture ${file3} has invalid query`);if(!Array.isArray(fixture.scopes)||fixture.scopes.length===0)throw Error(`memory recall fixture ${file3} must define scopes`);let scopes=fixture.scopes.map((scope,index)=>validateScope(scope,file3,`scope #${index+1}`));if(!Array.isArray(fixture.expectedLabels)||fixture.expectedLabels.length===0)throw Error(`memory recall fixture ${file3} must define expectedLabels`);let expectedLabels=fixture.expectedLabels.map((label,index)=>{if(typeof label!=="string"||!label)throw Error(`memory recall fixture ${file3} expectedLabels #${index+1} must be a non-empty string`);return label});if(!Array.isArray(fixture.records)||fixture.records.length===0)throw Error(`memory recall fixture ${file3} must define records`);let records=fixture.records.map((record3,index)=>validateFixtureRecord(record3,file3,index));return{...fixture,name:fixture.name,query:fixture.query,scopes,expectedLabels,records}}function validateFixtureRecord(value,file3,index){if(!value||typeof value!=="object")throw Error(`memory recall fixture ${file3} record #${index+1} must be an object`);let record3=value,labelForError=typeof record3.label==="string"&&record3.label?record3.label:`#${index+1}`;if(typeof record3.label!=="string"||!record3.label)throw Error(`memory recall fixture ${file3} record ${labelForError} is missing label`);let scope=validateScope(record3.scope,file3,`record ${record3.label}`);if(!("kind"in record3)||record3.kind==="")throw Error(`memory recall fixture ${file3} record ${record3.label} is missing kind`);if(typeof record3.kind!=="string")throw Error(`memory recall fixture ${file3} record ${record3.label} has invalid kind`);let parsedKind=MemoryKindSchema.safeParse(record3.kind);if(!parsedKind.success)throw Error(`memory recall fixture ${file3} record ${record3.label} has invalid kind`);if(!("text"in record3)||record3.text==="")throw Error(`memory recall fixture ${file3} record ${record3.label} is missing text`);if(typeof record3.text!=="string")throw Error(`memory recall fixture ${file3} record ${record3.label} has invalid text`);return{...record3,label:record3.label,scope,kind:parsedKind.data,text:record3.text}}function validateScope(value,file3,descriptor){if(!value||typeof value!=="object")throw Error(`memory recall fixture ${file3} ${descriptor} is missing scope`);let scope=value;if(typeof scope.type!=="string")throw Error(`memory recall fixture ${file3} ${descriptor} has invalid scope type`);let parsed=MemoryScopeRefSchema.safeParse(scope);if(!parsed.success)throw Error(`memory recall fixture ${file3} ${descriptor} has invalid scope`);return parsed.data}var DEFAULT_PROVIDERS,DEFAULT_MODES,DEFAULT_TIMESTAMP="2026-05-26T12:00:00.000Z";var init_evaluation=__esm(()=>{init_config3();init_gateway();init_provider_pool();init_schema2();DEFAULT_PROVIDERS=["local-jsonl","sqlite"],DEFAULT_MODES=["manual","injection","curator"]});function extractMemoryProposalsFromAgentOutput(outputText){let candidates=candidateJsonBlocks(outputText);for(let candidate of candidates){let parsedJson=parseJsonObject(candidate);if(parsedJson===null)continue;let parsed=AgentOutputMemorySchema.safeParse(parsedJson);if(!parsed.success)return{proposals:[],error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")};if(parsed.data.memoryProposals)return{proposals:parsed.data.memoryProposals}}return{proposals:[]}}function extractCuratorMemoryDecisionsFromAgentOutput(outputText){let candidates=candidateJsonBlocks(outputText);for(let candidate of candidates){let parsedJson=parseJsonObject(candidate);if(parsedJson===null)continue;let parsed=CuratorOutputMemoryDecisionSchema.safeParse(parsedJson);if(!parsed.success)return{decisions:[],error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")};if(parsed.data.curatorMemoryDecisions)return{decisions:parsed.data.curatorMemoryDecisions}}return{decisions:[]}}function candidateJsonBlocks(outputText){let trimmed=outputText.trim(),candidates=[];if(trimmed.startsWith("{")&&trimmed.endsWith("}"))candidates.push(trimmed);let fencePattern=/```(?:json)?\s*([\s\S]*?)```/gi;for(let match of outputText.matchAll(fencePattern)){let block=match[1]?.trim();if(block?.startsWith("{")&&block.endsWith("}"))candidates.push(block)}return candidates}function parseJsonObject(candidate){try{let parsed=JSON.parse(candidate);return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}catch{return null}}var AgentMemoryProposalSchema,AgentOutputMemorySchema,CuratorOutputMemoryDecisionSchema;var init_agent_output_schema=__esm(()=>{init_zod();init_schema2();AgentMemoryProposalSchema=exports_external.object({operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]),kind:MemoryKindSchema.optional(),text:exports_external.string().min(1).max(2000).optional(),targetMemoryId:exports_external.string().optional(),relatedMemoryIds:exports_external.array(exports_external.string()).optional(),rationale:exports_external.string().min(1).max(2000),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional()}).strict(),AgentOutputMemorySchema=exports_external.object({memoryProposals:exports_external.array(AgentMemoryProposalSchema).max(20).optional()}).passthrough(),CuratorOutputMemoryDecisionSchema=exports_external.object({curatorMemoryDecisions:exports_external.array(CuratorMemoryDecisionSchema).max(20).optional()}).passthrough()});function buildMemoryRecallPlan(input,options={}){let profile=options.profile??resolveMemoryRecallProfile(input.agentRole),scopes=options.scopes??[];return{query:buildRecallQuery(input),scopes,kinds:[...profile.kinds],maxItems:profile.maxItems,tokenBudget:profile.tokenBudget}}function buildRecallQuery(input){let lines=[`${input.agentRole} task: ${input.agentTask}`,`user goal: ${input.userGoal}`],repoProject=[input.projectId,input.repoId,input.repoRoot].filter((value)=>Boolean(value?.trim())).join(" ");if(repoProject)lines.push(`repo/project: ${repoProject}`);if(input.touchedFiles&&input.touchedFiles.length>0)lines.push(`touched files: ${input.touchedFiles.join(", ")}`);if(input.currentPlanSummary?.trim())lines.push(`current plan: ${input.currentPlanSummary.trim()}`);return lines.join(`
1512
1533
  `)}var init_recall_planner=__esm(()=>{init_role_profiles()});import{appendFile as appendFile10,mkdir as mkdir20}from"node:fs/promises";import*as path87 from"node:path";async function appendMemoryRunLog(directory,runId,event){let safeRunId=sanitizeRunId(runId),relativePath=path87.join("runs",safeRunId,"memory.jsonl"),filePath=validateSwarmPath(directory,relativePath);await mkdir20(path87.dirname(filePath),{recursive:!0}),await appendFile10(filePath,`${JSON.stringify({...event,runId:safeRunId,timestamp:event.timestamp??new Date().toISOString()})}
1513
1534
  `,"utf-8")}function sanitizeRunId(runId){return(runId?.trim()||"unknown").replace(/[^A-Za-z0-9._-]/g,"_").slice(0,80)||"unknown"}var init_run_log=__esm(()=>{init_utils2()});function createMemoryLifecycleHooks(options){let internals={createGateway:options.createGateway??createMemoryGateway,appendRunLog:options.appendRunLog??appendMemoryRunLog};return{messagesTransform:async(input,output)=>{await injectIntoMessages(input,output,options,internals)},toolAfter:async(input,output)=>{await captureTaskOutputProposals(input,output,options,internals)}}}async function injectIntoMessages(input,output,options,internals){let messages=output?.messages;if(!Array.isArray(messages)||messages.length===0)return;if(messagesContainRecall(messages))return;let sessionID=getSessionID(input,messages),agentRole=resolveMessageAgent(messages,options,sessionID),latestUserText=latestTextForRole(messages,"user");if(!latestUserText)return;let agentTask=extractTaskToolPrompt(messages)??latestUserText,result=await recallForAgent({directory:options.directory,config:options.config,sessionID,agentRole,agentId:agentRole,userGoal:latestUserText,agentTask,createGateway:internals.createGateway,appendRunLog:internals.appendRunLog});if(!result||result.bundle.items.length===0)return;let insertAt=recallMessageInsertIndex(messages),recallMessage={info:{role:"system",agent:agentRole,sessionID},parts:[{type:"text",text:result.bundle.promptBlock}]};messages.splice(insertAt,0,recallMessage),await internals.appendRunLog(options.directory,sessionID,{event:"prompt_injected",runId:sessionID??"unknown",agentRole,agentId:agentRole,bundleId:result.bundle.id,memoryIds:result.bundle.items.map((item)=>item.record.id),tokenEstimate:result.bundle.tokenEstimate,metadata:{surface:"chat_messages"}})}async function captureTaskOutputProposals(input,output,options,internals){let task=parseTaskToolInput(input);if(!task)return;let outputText=output?.output;if(typeof outputText!=="string"||!outputText.includes("memoryProposals")&&!outputText.includes("curatorMemoryDecisions"))return;let extracted=outputText.includes("memoryProposals")?extractMemoryProposalsFromAgentOutput(outputText):{proposals:[]};if(extracted.error){await internals.appendRunLog(options.directory,task.sessionID,{event:"proposal_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:extracted.error});return}let decisionExtraction=outputText.includes("curatorMemoryDecisions")?extractCuratorMemoryDecisionsFromAgentOutput(outputText):{decisions:[]};if(decisionExtraction.error){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:decisionExtraction.error});return}if(extracted.proposals.length===0&&decisionExtraction.decisions.length===0)return;let gateway=internals.createGateway({directory:options.directory,sessionID:task.sessionID,agentRole:task.agentRole,agentId:task.agentRole,runId:task.sessionID},{config:options.config});if(!gateway.isEnabled()){await gateway.dispose?.();return}try{for(let proposalInput of extracted.proposals)try{let proposal=await gateway.propose(proposalInput);await internals.appendRunLog(options.directory,task.sessionID,{event:proposal.status==="pending"?"proposal_created":"proposal_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,proposalId:proposal.id,rejectionReason:proposal.rejectionReason})}catch(err){await internals.appendRunLog(options.directory,task.sessionID,{event:"proposal_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:err instanceof Error?err.message:String(err)})}if(decisionExtraction.decisions.length>0&&!isCuratorAgent(task.agentRole)){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:"only curator agents may emit curatorMemoryDecisions"});return}if(decisionExtraction.decisions.length>0){let applyCuratorDecisionMethod=gateway.applyCuratorDecision;if(!applyCuratorDecisionMethod){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:"memory gateway does not support curator decisions"});return}let applyCuratorDecision=applyCuratorDecisionMethod.bind(gateway);for(let decision of decisionExtraction.decisions)try{let change=await applyCuratorDecision(decision);await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_applied",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,proposalId:change.proposalId,memoryIds:[change.memoryId,change.targetMemoryId,change.oldMemoryId,change.replacementMemoryId].filter((id)=>Boolean(id)),rejectionReason:change.reason,metadata:{action:change.action,proposalStatus:change.proposalStatus,eventId:change.eventId}})}catch(err){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,proposalId:decision.proposalId,rejectionReason:err instanceof Error?err.message:String(err),metadata:{action:decision.action}})}}}finally{await gateway.dispose?.()}}async function recallForAgent(input){let gateway=input.createGateway({directory:input.directory,sessionID:input.sessionID,agentRole:input.agentRole,agentId:input.agentId,runId:input.sessionID},{config:input.config});try{let resolvedConfig=resolveMemoryConfig(input.config);if(!gateway.isEnabled())return await logInjectionSkipped(input,"disabled"),null;if(!resolvedConfig.recall.injection.enabled)return await logInjectionSkipped(input,"disabled"),null;let scopes=gateway.deriveAllowedScopes(),planInput={userGoal:compactText(input.userGoal),runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,agentTask:compactText(input.agentTask),touchedFiles:extractTouchedFiles(input.agentTask)},plan=buildMemoryRecallPlan(planInput,{scopes});plan.maxItems=resolvedConfig.recall.injection.maxItems,plan.tokenBudget=resolvedConfig.recall.injection.tokenBudget,await input.appendRunLog(input.directory,input.sessionID,{event:"recall_requested",runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,metadata:{kinds:plan.kinds,maxItems:plan.maxItems,tokenBudget:plan.tokenBudget,scopeTypes:plan.scopes.map((scope)=>scope.type)}});let recallInput={query:plan.query,task:planInput.agentTask,mode:"injection",scopes:plan.scopes,kinds:plan.kinds,maxItems:plan.maxItems,tokenBudget:plan.tokenBudget,minScore:resolvedConfig.recall.injection.minScore,requireQuerySignal:resolvedConfig.recall.injection.requireQuerySignal},bundle=await gateway.recall(recallInput);if(await input.appendRunLog(input.directory,input.sessionID,{event:"recall_returned",runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,bundleId:bundle.id,memoryIds:bundle.items.map((item)=>item.record.id),scores:bundle.items.map((item)=>item.score),tokenEstimate:bundle.tokenEstimate}),bundle.items.length===0)await logInjectionSkipped(input,bundle.diagnostics?.injectionSkipReason??"no_results",bundle);return{bundle,scopes}}finally{await gateway.dispose?.()}}async function logInjectionSkipped(input,reason,bundle){await input.appendRunLog(input.directory,input.sessionID,{event:"prompt_injection_skipped",runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,bundleId:bundle?.id,memoryIds:bundle?.items.map((item)=>item.record.id),scores:bundle?.items.map((item)=>item.score),tokenEstimate:bundle?.tokenEstimate,rejectionReason:reason,metadata:{reason,candidateCount:bundle?.diagnostics?.candidateCount,preScoredFilteredCount:bundle?.diagnostics?.preScoredFilteredCount,noSignalCount:bundle?.diagnostics?.noSignalCount,belowThresholdCount:bundle?.diagnostics?.belowThresholdCount}})}function parseTaskToolInput(input){let record3=input,rawTool=typeof record3.tool==="string"?record3.tool:void 0,toolName=rawTool?normalizeToolName(rawTool)??rawTool:void 0;if(toolName!=="Task"&&toolName!=="task")return null;if(!record3.args||typeof record3.args!=="object")return null;let args2=record3.args,prompt=args2.prompt;if(typeof prompt!=="string"||prompt.trim().length===0)return null;let target=typeof args2.subagent_type==="string"?args2.subagent_type:typeof args2.agent==="string"?args2.agent:typeof record3.agent==="string"?record3.agent:"architect";return{sessionID:typeof record3.sessionID==="string"?record3.sessionID:void 0,agentRole:stripKnownSwarmPrefix(target),prompt}}function isCuratorAgent(agentRole){return agentRole==="curator"||agentRole==="curator_init"||agentRole==="curator_phase"||agentRole==="curator_postmortem"}function messagesContainRecall(messages){return messages.some((message)=>message?.parts?.some((part)=>typeof part?.text==="string"&&(part.text.includes(MEMORY_SENTINEL)||part.text.includes("Retrieved Swarm Memory"))))}function getSessionID(input,messages){let inputSession=input?.sessionID;if(typeof inputSession==="string")return inputSession;for(let message of messages){let sessionID=message?.info?.sessionID;if(typeof sessionID==="string")return sessionID}return}function resolveMessageAgent(messages,options,sessionID){let configured=options.getActiveAgentName?.(sessionID);if(configured)return stripKnownSwarmPrefix(configured);for(let message of messages){let agent=message?.info?.agent;if(typeof agent==="string")return stripKnownSwarmPrefix(agent)}return"architect"}function latestTextForRole(messages,role){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(message.info?.role!==role||!Array.isArray(message.parts))continue;let text=message.parts.map((part)=>part?.text).filter((partText)=>typeof partText==="string").join(`
1514
- `).trim();if(text)return text}return null}function extractTaskToolPrompt(messages){for(let i=messages.length-1;i>=0;i--){let msg=messages[i];if((msg.role??msg.info?.role)!=="assistant")continue;let content=Array.isArray(msg.content)?msg.content:Array.isArray(msg.parts)?msg.parts:[];for(let j=content.length-1;j>=0;j--){let block=content[j];if(block&&typeof block==="object"){let b=block;if(b.type==="tool_use"&&b.name==="Task"){let prompt=b.input?.prompt;if(typeof prompt==="string"&&prompt.length>0)return prompt}}}}return null}function recallMessageInsertIndex(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="user")return i;return messages.length}function extractTouchedFiles(text){let matches=text.match(/\b(?:src|tests|test|docs|scripts|packages)\/[A-Za-z0-9._/@+-]+/g);return Array.from(new Set(matches??[])).slice(0,20)}function compactText(text){let compacted=text.replace(/\s+/g," ").trim();if(compacted.length<=2000)return compacted;return Array.from(compacted).slice(0,2000).join("")}var MEMORY_SENTINEL;var init_injector=__esm(()=>{init_agent_output_schema();init_schema();init_normalize_tool_name();init_config3();init_gateway();init_recall_planner();init_run_log();MEMORY_SENTINEL=MEMORY_RECALL_SENTINEL});var init_memory=__esm(()=>{init_config3();init_errors6();init_evaluation();init_gateway();init_injector();init_jsonl_migration();init_local_jsonl_provider();init_maintenance();init_prompt_block();init_recall_planner();init_redaction();init_role_profiles();init_run_log();init_schema2();init_sqlite_provider()});import{appendFile as appendFile11,mkdir as mkdir21,readFile as readFile23}from"node:fs/promises";import*as path88 from"node:path";async function readConsolidationLog(directory){let filePath=validateSwarmPath(directory,LOG_RELATIVE_PATH),raw;try{raw=await readFile23(filePath,"utf-8")}catch{return[]}let records=[];for(let line of raw.split(`
1535
+ `).trim();if(text)return text}return null}function extractTaskToolPrompt(messages){for(let i=messages.length-1;i>=0;i--){let msg=messages[i];if((msg.role??msg.info?.role)!=="assistant")continue;let content=Array.isArray(msg.content)?msg.content:Array.isArray(msg.parts)?msg.parts:[];for(let j=content.length-1;j>=0;j--){let block=content[j];if(block&&typeof block==="object"){let b=block;if(b.type==="tool_use"&&b.name==="Task"){let prompt=b.input?.prompt;if(typeof prompt==="string"&&prompt.length>0)return prompt}}}}return null}function recallMessageInsertIndex(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="user")return i;return messages.length}function extractTouchedFiles(text){let matches=text.match(/\b(?:src|tests|test|docs|scripts|packages)\/[A-Za-z0-9._/@+-]+/g);return Array.from(new Set(matches??[])).slice(0,20)}function compactText(text){let compacted=text.replace(/\s+/g," ").trim();if(compacted.length<=2000)return compacted;return Array.from(compacted).slice(0,2000).join("")}var MEMORY_SENTINEL;var init_injector=__esm(()=>{init_agent_output_schema();init_schema();init_normalize_tool_name();init_config3();init_gateway();init_recall_planner();init_run_log();MEMORY_SENTINEL=MEMORY_RECALL_SENTINEL});function councilVerdictToMemoryOutcome(verdict){switch(verdict){case"APPROVE":return"approved";case"REJECT":return"rejected";case"CONCERNS":return"concerns"}}function resolveRewardRunIds(input){let seen=new Set,resolved=[];for(let id of input.trustedSessionIds){if(!id||seen.has(id))continue;seen.add(id),resolved.push(id)}for(let id of input.untrustedSessionIds){if(!id||seen.has(id))continue;if(!input.isKnownSession(id))continue;seen.add(id),resolved.push(id)}return resolved}async function applyRecallRewardForCouncil(directory,configInput,input){let config3=resolveMemoryConfig(configInput),outcome=councilVerdictToMemoryOutcome(input.verdict);if(!config3.enabled)return skippedRewardResult(outcome,"memory_disabled");if(input.runIds.length===0)return skippedRewardResult(outcome,"no_recall_usage_for_run");let provider=createConfiguredMemoryProvider(directory,config3);try{if(await provider.initialize?.(),!provider.applyRecallReward)return skippedRewardResult(outcome,"provider_does_not_support_learning");return await provider.applyRecallReward({runIds:input.runIds,outcome,verdictPayload:input.verdictPayload,timestamp:input.timestamp})}finally{await provider.close?.()}}function skippedRewardResult(outcome,reason){return{success:!1,outcome,memoryIds:[],reward:outcome==="approved"?1:outcome==="rejected"?-1:0,updatedMemoryIds:[],propagatedMemoryIds:[],reason}}var init_reward=__esm(()=>{init_config3();init_gateway()});var init_memory=__esm(()=>{init_config3();init_errors6();init_evaluation();init_gateway();init_injector();init_jsonl_migration();init_local_jsonl_provider();init_maintenance();init_prompt_block();init_recall_planner();init_redaction();init_reward();init_role_profiles();init_run_log();init_schema2();init_sqlite_provider()});import{appendFile as appendFile11,mkdir as mkdir21,readFile as readFile23}from"node:fs/promises";import*as path88 from"node:path";async function readConsolidationLog(directory){let filePath=validateSwarmPath(directory,LOG_RELATIVE_PATH),raw;try{raw=await readFile23(filePath,"utf-8")}catch{return[]}let records=[];for(let line of raw.split(`
1515
1536
  `)){let trimmed=line.trim();if(!trimmed)continue;try{records.push(JSON.parse(trimmed))}catch{}}return records}async function appendConsolidationLog(directory,record3){let filePath=validateSwarmPath(directory,LOG_RELATIVE_PATH);await mkdir21(path88.dirname(filePath),{recursive:!0}),await appendFile11(filePath,`${JSON.stringify(record3)}
1516
- `,"utf-8")}var LOG_RELATIVE_PATH;var init_consolidation_log=__esm(()=>{init_utils2();LOG_RELATIVE_PATH=path88.join("memory","consolidation-log.jsonl")});import{existsSync as existsSync49}from"node:fs";import*as path89 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";async function handleMemoryCommand(_directory,_args){return["## Swarm Memory","","- `/swarm memory status` - show provider, SQLite path, JSONL files, and last migration report","- `/swarm memory pending` - show pending proposals and recent rejection reasons","- `/swarm memory recall-log` - summarize recall usage by agent role and memory ID","- `/swarm memory stale` - list expired scratch, superseded, deleted, and low-utility memories","- `/swarm memory compact` - dry-run compaction; pass `--confirm` to remove deleted, superseded, and expired scratch records","- `/swarm memory export` - export current memory and proposals to `.swarm/memory/export/*.jsonl`","- `/swarm memory import` - import `.swarm/memory/{memories,proposals}.jsonl` into SQLite","- `/swarm memory migrate` - run the one-time legacy JSONL to SQLite migration","- `/swarm memory evaluate --json` - run the golden recall evaluation fixtures and emit a JSON report","- `/swarm memory consolidation-log [--limit <n>]` - summarize recent episodic→semantic consolidation passes (max 50 per query)"].join(`
1537
+ `,"utf-8")}var LOG_RELATIVE_PATH;var init_consolidation_log=__esm(()=>{init_utils2();LOG_RELATIVE_PATH=path88.join("memory","consolidation-log.jsonl")});import{existsSync as existsSync49}from"node:fs";import*as path89 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";async function handleMemoryCommand(_directory,_args){return["## Swarm Memory","","- `/swarm memory status` - show provider, SQLite path, JSONL files, and last migration report","- `/swarm memory pending` - show pending proposals and recent rejection reasons","- `/swarm memory recall-log` - summarize recall usage by agent role and memory ID","- `/swarm memory value-log` - show recent Q-value, reward, suppression, and promotion signals","- `/swarm memory stale` - list expired scratch, superseded, deleted, and low-utility memories","- `/swarm memory compact` - dry-run compaction; pass `--confirm` to remove deleted, superseded, and expired scratch records","- `/swarm memory export` - export current memory and proposals to `.swarm/memory/export/*.jsonl`","- `/swarm memory import` - import `.swarm/memory/{memories,proposals}.jsonl` into SQLite","- `/swarm memory migrate` - run the one-time legacy JSONL to SQLite migration","- `/swarm memory evaluate --json` - run the golden recall evaluation fixtures and emit a JSON report","- `/swarm memory consolidation-log [--limit <n>]` - summarize recent episodic→semantic consolidation passes (max 50 per query)"].join(`
1517
1538
  `)}async function handleMemoryConsolidationLogCommand(directory,args2){let parsed=parseMaintenanceArgs(args2,{usage:"Usage: /swarm memory consolidation-log [--limit <n>] (max 50 records per query)",allowConfirm:!1});if("error"in parsed)return parsed.error;let limit=Math.min(parsed.limit,50),records=await readConsolidationLog(directory),recent=records.slice(-limit).reverse(),lines=["## Swarm Memory Consolidation Log","",`- Total recorded passes: \`${records.length}\``,`- Showing: \`${recent.length}\``];if(recent.length===0)return lines.push("","No consolidation passes have been recorded yet."),lines.join(`
1518
1539
  `);for(let record3 of recent)lines.push("",`### Phase ${record3.phaseNumber} — ${record3.completedAt}`,`- Run: \`${record3.runId??"unknown"}\``,`- Clusters: \`${record3.clusterCount}\` (deferred \`${record3.clustersDeferred}\`)`,`- Decisions applied: \`${record3.decisionsEmitted}\` (added \`${record3.added}\`, superseded \`${record3.superseded}\`)`,`- Contradictions: \`${record3.contradictionsDetected}\` | Deduped: \`${record3.deduped}\` | Proposed: \`${record3.proposed}\``,`- Memories decayed: \`${record3.memoriesDecayed}\` | Errored: \`${record3.errored}\``,`- Processed proposals: \`${record3.processedProposalIds.length}\``);return lines.join(`
1519
1540
  `)}async function handleMemoryStatusCommand(directory,_args){let config3=resolveCommandMemoryConfig(directory),storageDir=resolveMemoryStorageDir(directory,config3),sqlitePath=resolveSqliteDatabasePath(directory,config3),jsonlFiles=await getLegacyJsonlFileStatus(directory,config3),report=await readMigrationReport(directory,config3),lines=["## Swarm Memory Status","",`- Enabled: \`${config3.enabled}\``,`- Provider: \`${config3.provider}\``,`- Storage: \`${storageDir}\``,`- SQLite path: \`${sqlitePath}\``,`- SQLite database exists: \`${existsSync49(sqlitePath)}\``,"- Automatic destructive cleanup: `disabled`","","### Legacy JSONL"];for(let file3 of jsonlFiles)lines.push(`- ${file3.file}: \`${file3.exists?"present":"missing"}\` (${file3.sizeBytes} bytes)`);if(lines.push("","### Migration"),!report)lines.push("- Last report: `none`");else if(lines.push(`- Completed at: \`${report.completedAt}\``,`- Imported memories: \`${report.importedMemories}\``,`- Imported proposals: \`${report.importedProposals}\``,`- Invalid rows: \`${report.invalidRows.length}\``,`- Backups: \`${report.backups.length}\``),report.invalidRows.length>0){lines.push("","Invalid rows:");for(let row of report.invalidRows.slice(0,20))lines.push(`- ${row.file}:${row.line} - ${row.error}`);if(report.invalidRows.length>20)lines.push(`- ... ${report.invalidRows.length-20} more`)}return lines.join(`
1520
- `)}async function handleMemoryPendingCommand(directory,args2){let parsed=parseMaintenanceArgs(args2,{usage:"Usage: /swarm memory pending [--limit <n>]",allowConfirm:!1});if("error"in parsed)return parsed.error;let config3=resolveCommandMemoryConfig(directory),provider=createMaintenanceProvider(directory,config3);try{await provider.initialize?.();let report=await buildMemoryMaintenanceReport(provider,{...maintenanceReportOptions(config3,parsed.limit)}),lines=["## Swarm Memory Pending","",`- Pending proposals shown: \`${report.pendingProposals.length}\``,`- Rejected proposal reasons shown: \`${report.rejectedProposalReasons.length}\``];return appendProposalLines(lines,"Pending proposals",report.pendingProposals),appendProposalLines(lines,"Rejected proposal reasons",report.rejectedProposalReasons),lines.join(`
1541
+ `)}async function handleMemoryPendingCommand(directory,args2){let parsed=parseMaintenanceArgs(args2,{usage:"Usage: /swarm memory pending [--limit <n>]",allowConfirm:!1});if("error"in parsed)return parsed.error;let config3=resolveCommandMemoryConfig(directory),provider=createMaintenanceProvider(directory,config3);try{await provider.initialize?.();let report=await buildMemoryMaintenanceReport(provider,{...maintenanceReportOptions(config3,parsed.limit)}),lines=["## Swarm Memory Pending","",`- Pending proposals shown: \`${report.pendingProposals.length}\``,`- Rejected proposal reasons shown: \`${report.rejectedProposalReasons.length}\``,`- Promotion candidates shown: \`${report.promotionCandidates.length}\``];return appendProposalLines(lines,"Pending proposals",report.pendingProposals),appendProposalLines(lines,"Rejected proposal reasons",report.rejectedProposalReasons),appendValueLogLines(lines,"Promotion candidates",report.promotionCandidates),lines.join(`
1521
1542
  `)}finally{await provider.close?.()}}async function handleMemoryRecallLogCommand(directory,args2){let parsed=parseMaintenanceArgs(args2,{usage:"Usage: /swarm memory recall-log [--limit <n>]",allowConfirm:!1});if("error"in parsed)return parsed.error;let config3=resolveCommandMemoryConfig(directory),provider=createMaintenanceProvider(directory,config3);try{await provider.initialize?.();let report=await buildMemoryMaintenanceReport(provider,{...maintenanceReportOptions(config3,parsed.limit)}),lines=["## Swarm Memory Recall Log","",`- Recall events scanned: \`${report.recallEventCount}\``,`- Most-recalled memories shown: \`${report.mostRecalledMemories.length}\``,`- Never-recalled memories shown: \`${report.neverRecalledMemories.length}\``];return appendRecallRoleLines(lines,report.recallByAgentRole),appendRecallMemoryLines(lines,report.mostRecalledMemories),appendMemoryLines(lines,"Never-recalled memories",report.neverRecalledMemories),lines.join(`
1522
- `)}finally{await provider.close?.()}}async function handleMemoryStaleCommand(directory,args2){let parsed=parseMaintenanceArgs(args2,{usage:"Usage: /swarm memory stale [--limit <n>]",allowConfirm:!1});if("error"in parsed)return parsed.error;let config3=resolveCommandMemoryConfig(directory),provider=createMaintenanceProvider(directory,config3);try{await provider.initialize?.();let report=await buildMemoryMaintenanceReport(provider,{...maintenanceReportOptions(config3,parsed.limit)}),lines=["## Swarm Memory Stale","",`- Active memories: \`${report.activeMemories}\``,`- Expired scratch memories shown: \`${report.expiredScratchMemories.length}\``,`- Deleted tombstones shown: \`${report.deletedMemories.length}\``,`- Superseded memories shown: \`${report.supersededMemories.length}\``,`- Low-utility memories shown: \`${report.lowUtilityMemories.length}\``];return appendMemoryLines(lines,"Expired scratch memories",report.expiredScratchMemories),appendMemoryLines(lines,"Deleted tombstones",report.deletedMemories),appendSupersededChains(lines,report),appendMemoryLines(lines,"Low-utility memories",report.lowUtilityMemories),lines.join(`
1543
+ `)}finally{await provider.close?.()}}async function handleMemoryValueLogCommand(directory,args2){let parsed=parseMaintenanceArgs(args2,{usage:"Usage: /swarm memory value-log [--limit <n>]",allowConfirm:!1});if("error"in parsed)return parsed.error;let config3=resolveCommandMemoryConfig(directory),provider=createMaintenanceProvider(directory,config3);try{if(await provider.initialize?.(),!provider.listMemoryValueLog)return"Memory provider does not support value-log reporting.";let valueLog=await provider.listMemoryValueLog({limit:parsed.limit}),promotionCandidates=valueLog.filter((entry)=>entry.promotionCandidate),suppressionCandidates=valueLog.filter((entry)=>entry.suppressionCandidate),lines=["## Swarm Memory Value Log","",`- Entries shown: \`${valueLog.length}\``,`- Promotion candidates shown: \`${promotionCandidates.length}\``,`- Suppression candidates shown: \`${suppressionCandidates.length}\``];return appendValueLogLines(lines,"Recent Q-value updates",valueLog),appendValueLogLines(lines,"Promotion candidates",promotionCandidates),appendValueLogLines(lines,"Suppression candidates",suppressionCandidates),lines.join(`
1544
+ `)}finally{await provider.close?.()}}async function handleMemoryStaleCommand(directory,args2){let parsed=parseMaintenanceArgs(args2,{usage:"Usage: /swarm memory stale [--limit <n>]",allowConfirm:!1});if("error"in parsed)return parsed.error;let config3=resolveCommandMemoryConfig(directory),provider=createMaintenanceProvider(directory,config3);try{await provider.initialize?.();let report=await buildMemoryMaintenanceReport(provider,{...maintenanceReportOptions(config3,parsed.limit)}),lines=["## Swarm Memory Stale","",`- Active memories: \`${report.activeMemories}\``,`- Expired scratch memories shown: \`${report.expiredScratchMemories.length}\``,`- Deleted tombstones shown: \`${report.deletedMemories.length}\``,`- Superseded memories shown: \`${report.supersededMemories.length}\``,`- Low-utility memories shown: \`${report.lowUtilityMemories.length}\``,`- Low-Q memories shown: \`${report.lowQValueMemories.length}\``];return appendMemoryLines(lines,"Expired scratch memories",report.expiredScratchMemories),appendMemoryLines(lines,"Deleted tombstones",report.deletedMemories),appendSupersededChains(lines,report),appendMemoryLines(lines,"Low-utility memories",report.lowUtilityMemories),appendValueLogLines(lines,"Low-Q memories",report.lowQValueMemories),lines.join(`
1523
1545
  `)}finally{await provider.close?.()}}async function handleMemoryCompactCommand(directory,args2){let parsed=parseMaintenanceArgs(args2,{usage:"Usage: /swarm memory compact [--confirm]",allowConfirm:!0,allowLimit:!1});if("error"in parsed)return parsed.error;let provider=createMaintenanceProvider(directory,resolveCommandMemoryConfig(directory));try{if(await provider.initialize?.(),!provider.compactMaintenance)return"Memory provider does not support compaction.";let result=await provider.compactMaintenance({dryRun:!parsed.confirm});return formatCompactResult(result,parsed.confirm)}finally{await provider.close?.()}}async function handleMemoryMigrateCommand(directory,_args){let config3={...resolveCommandMemoryConfig(directory),provider:"sqlite"},provider=new SQLiteMemoryProvider(directory,config3);try{await provider.initialize();let report=await readMigrationReport(directory,config3);return formatMigrationResult("migration",report)}finally{provider.close()}}async function handleMemoryImportCommand(directory,_args){let config3={...resolveCommandMemoryConfig(directory),provider:"sqlite"},provider=new SQLiteMemoryProvider(directory,config3);try{let result=await provider.importJsonl(),lines=["## Swarm Memory Import","",`- Imported memories: \`${result.importedMemories}\``,`- Imported proposals: \`${result.importedProposals}\``,`- Total JSONL rows scanned: \`${result.totalRows}\``,`- Invalid rows: \`${result.invalidRows.length}\``];return appendInvalidRows(lines,result.invalidRows),lines.join(`
1524
1546
  `)}finally{provider.close()}}async function handleMemoryExportCommand(directory,_args){let config3=resolveCommandMemoryConfig(directory),provider=createConfiguredMemoryProvider(directory,config3);try{await provider.initialize?.();let memories=await provider.list({includeExpired:!0}),proposals=provider.listProposals?await provider.listProposals():[],output=await writeJsonlExport(directory,config3,memories,proposals);return["## Swarm Memory Export","",`- Memories: \`${memories.length}\` -> \`${output.memoriesPath}\``,`- Proposals: \`${proposals.length}\` -> \`${output.proposalsPath}\``].join(`
1525
1547
  `)}finally{await provider.close?.()}}function createMaintenanceProvider(directory,config3){return createConfiguredMemoryProvider(directory,config3)}function maintenanceReportOptions(config3,limit){let{threshold,...weights}=config3.maintenance.importance;return{limit,importanceWeights:weights,importanceThreshold:threshold}}async function handleMemoryEvaluateCommand(directory,args2){let parsed=parseEvaluateArgs(directory,args2);if("error"in parsed)return parsed.error;let report=await evaluateMemoryRecallFixtures({fixtureDirectory:parsed.fixtureDirectory});if(parsed.json)return`${JSON.stringify(report,null,2)}
1526
1548
  `;return["## Swarm Memory Recall Evaluation","",`- Fixtures: \`${report.summary.fixture_count}\``,`- Runs: \`${report.summary.run_count}\``,`- Passed runs: \`${report.summary.passed_run_count}\``,`- Precision@k: \`${report.summary["precision@k"].toFixed(3)}\``,`- Recall@k: \`${report.summary["recall@k"].toFixed(3)}\``,`- Injection count: \`${report.summary.injection_count}\``,`- Noisy injections: \`${report.summary.noisy_injection_count}\``,`- Same-scope noise: \`${report.summary.same_scope_noise_count}\``,`- Cross-scope leaks: \`${report.summary.cross_scope_leak_count}\``,`- Stale memories: \`${report.summary.stale_memory_count}\``,"","Use `/swarm memory evaluate --json` for the full report."].join(`
1527
1549
  `)}function resolveCommandMemoryConfig(directory){let loaded=loadPluginConfig(directory).memory;return resolveMemoryConfig(loaded??DEFAULT_MEMORY_CONFIG)}function parseEvaluateArgs(directory,args2){let json3=!1,fixtureDirectory=path89.join(PACKAGE_ROOT,"tests","fixtures","memory-recall");for(let i=0;i<args2.length;i++){let arg=args2[i];if(arg==="--json"){json3=!0;continue}if(arg==="--fixtures"){let next=args2[i+1];if(!next)return{error:"Usage: /swarm memory evaluate [--json] [--fixtures <directory>]"};let resolvedFixtures=path89.resolve(directory,next),canonical=path89.normalize(resolvedFixtures)+path89.sep,allowedRootA=path89.normalize(directory)+path89.sep,allowedRootB=path89.normalize(path89.join(PACKAGE_ROOT,"tests","fixtures","memory-recall"))+path89.sep;if(!canonical.startsWith(allowedRootA)&&!canonical.startsWith(allowedRootB))return{error:"--fixtures <directory> must resolve under the project directory or the bundled tests/fixtures/memory-recall directory"};fixtureDirectory=resolvedFixtures,i++;continue}return{error:"Usage: /swarm memory evaluate [--json] [--fixtures <directory>]"}}return{json:json3,fixtureDirectory}}function parseMaintenanceArgs(args2,options){let limit=20,confirm=!1,allowLimit=options.allowLimit??!0;for(let i=0;i<args2.length;i++){let arg=args2[i];if(arg==="--confirm"&&options.allowConfirm){confirm=!0;continue}if(arg==="--limit"&&allowLimit){let next=args2[i+1];if(!next||!/^\d+$/.test(next))return{error:options.usage};limit=Math.min(100,Math.max(1,Number(next))),i++;continue}return{error:options.usage}}return{limit,confirm}}function resolvePackageRootFromModule(modulePath){let moduleDir=path89.dirname(modulePath),leaf=path89.basename(moduleDir);if(leaf==="commands"||leaf==="cli")return path89.resolve(moduleDir,"..","..");if(leaf==="dist")return path89.resolve(moduleDir,"..");return path89.resolve(moduleDir,"..")}function formatMigrationResult(label,report){if(!report)return[`## Swarm Memory ${label}`,"","No migration report was written."].join(`
1528
1550
  `);let lines=[`## Swarm Memory ${label}`,"",`- Completed at: \`${report.completedAt}\``,`- Imported memories: \`${report.importedMemories}\``,`- Imported proposals: \`${report.importedProposals}\``,`- Invalid rows: \`${report.invalidRows.length}\``,`- Backups: \`${report.backups.length}\``];if(report.backups.length>0){lines.push("","Backups:");for(let backup of report.backups)lines.push(`- \`${backup.backup}\` (${backup.created?"created":"already existed"})`)}return appendInvalidRows(lines,report.invalidRows),lines.join(`
1529
- `)}function appendInvalidRows(lines,invalidRows){if(invalidRows.length===0)return;lines.push("","Invalid rows:");for(let row of invalidRows.slice(0,20))lines.push(`- ${row.file}:${row.line} - ${row.error}`);if(invalidRows.length>20)lines.push(`- ... ${invalidRows.length-20} more`)}function appendProposalLines(lines,title,proposals){if(lines.push("",`### ${title}`),proposals.length===0){lines.push("- none");return}for(let proposal of proposals){let reason=proposal.status==="rejected"?` - ${proposal.rejectionReason??"no reason recorded"}`:"";lines.push(`- \`${proposal.id}\` ${proposal.operation} ${proposal.targetMemoryId??proposal.proposedRecord?.id??"new"} (${proposal.status})${reason}`)}}function appendMemoryLines(lines,title,memories){if(lines.push("",`### ${title}`),memories.length===0){lines.push("- none");return}for(let memory of memories)lines.push(`- \`${memory.id}\` ${memory.kind} confidence=${memory.confidence.toFixed(2)} updated=${memory.updatedAt} - ${truncate(memory.text,100)}`)}function appendRecallRoleLines(lines,roles){if(lines.push("","### Recall by agent role"),roles.length===0){lines.push("- none");return}for(let role of roles){let memoryCount=Object.keys(role.memoryIds).length;lines.push(`- \`${role.agentRole}\`: ${role.count} recall event(s), ${memoryCount} memory ID(s)`)}}function appendRecallMemoryLines(lines,memories){if(lines.push("","### Most-recalled memories"),memories.length===0){lines.push("- none");return}for(let memory of memories)lines.push(`- \`${memory.memoryId}\`: ${memory.count} hit(s), last=${memory.lastRecalledAt}, avgScore=${memory.averageScore.toFixed(3)}`)}function appendSupersededChains(lines,report){if(lines.push("","### Superseded chains"),report.supersededChains.length===0){lines.push("- none");return}for(let chain of report.supersededChains){let reason=chain.reason?` - ${chain.reason}`:"";lines.push(`- ${chain.chain.map((id)=>`\`${id}\``).join(" -> ")}${reason}`)}}function formatCompactResult(result,confirmed){let lines=["## Swarm Memory Compact","",`- Mode: \`${confirmed?"confirmed":"dry-run"}\``,`- Deleted tombstones: \`${result.removedDeleted}\``,`- Superseded records: \`${result.removedSuperseded}\``,`- Expired scratch records: \`${result.removedExpiredScratch}\``,`- Remaining memories: \`${result.remaining}\``];if(!confirmed)lines.push("","No records were removed. Re-run `/swarm memory compact --confirm` to apply this compaction.");return lines.join(`
1551
+ `)}function appendInvalidRows(lines,invalidRows){if(invalidRows.length===0)return;lines.push("","Invalid rows:");for(let row of invalidRows.slice(0,20))lines.push(`- ${row.file}:${row.line} - ${row.error}`);if(invalidRows.length>20)lines.push(`- ... ${invalidRows.length-20} more`)}function appendProposalLines(lines,title,proposals){if(lines.push("",`### ${title}`),proposals.length===0){lines.push("- none");return}for(let proposal of proposals){let reason=proposal.status==="rejected"?` - ${proposal.rejectionReason??"no reason recorded"}`:"";lines.push(`- \`${proposal.id}\` ${proposal.operation} ${proposal.targetMemoryId??proposal.proposedRecord?.id??"new"} (${proposal.status})${reason}`)}}function appendMemoryLines(lines,title,memories){if(lines.push("",`### ${title}`),memories.length===0){lines.push("- none");return}for(let memory of memories)lines.push(`- \`${memory.id}\` ${memory.kind} confidence=${memory.confidence.toFixed(2)} updated=${memory.updatedAt} - ${truncate(memory.text,100)}`)}function appendRecallRoleLines(lines,roles){if(lines.push("","### Recall by agent role"),roles.length===0){lines.push("- none");return}for(let role of roles){let memoryCount=Object.keys(role.memoryIds).length;lines.push(`- \`${role.agentRole}\`: ${role.count} recall event(s), ${memoryCount} memory ID(s)`)}}function appendRecallMemoryLines(lines,memories){if(lines.push("","### Most-recalled memories"),memories.length===0){lines.push("- none");return}for(let memory of memories)lines.push(`- \`${memory.memoryId}\`: ${memory.count} hit(s), last=${memory.lastRecalledAt}, avgScore=${memory.averageScore.toFixed(3)}`)}function appendValueLogLines(lines,title,entries){if(lines.push("",`### ${title}`),entries.length===0){lines.push("- none");return}for(let entry of entries){let outcome=entry.taskOutcome?` outcome=${entry.taskOutcome}`:"",reward=typeof entry.lastReward==="number"?` reward=${entry.lastReward.toFixed(2)}`:"",last=entry.lastRecalledAt?` last=${entry.lastRecalledAt}`:"";lines.push(`- \`${entry.memoryId}\` ${entry.kind} q=${entry.qValue.toFixed(3)} recalls=${entry.recallCount}${reward}${outcome}${last} - ${entry.textPreview}`)}}function appendSupersededChains(lines,report){if(lines.push("","### Superseded chains"),report.supersededChains.length===0){lines.push("- none");return}for(let chain of report.supersededChains){let reason=chain.reason?` - ${chain.reason}`:"";lines.push(`- ${chain.chain.map((id)=>`\`${id}\``).join(" -> ")}${reason}`)}}function formatCompactResult(result,confirmed){let lines=["## Swarm Memory Compact","",`- Mode: \`${confirmed?"confirmed":"dry-run"}\``,`- Deleted tombstones: \`${result.removedDeleted}\``,`- Superseded records: \`${result.removedSuperseded}\``,`- Expired scratch records: \`${result.removedExpiredScratch}\``,`- Remaining memories: \`${result.remaining}\``];if(!confirmed)lines.push("","No records were removed. Re-run `/swarm memory compact --confirm` to apply this compaction.");return lines.join(`
1530
1552
  `)}function truncate(value,maxLength){if(value.length<=maxLength)return value;return`${value.slice(0,maxLength-3)}...`}var PACKAGE_ROOT;var init_memory2=__esm(()=>{init_loader();init_memory();init_consolidation_log();PACKAGE_ROOT=path89.resolve(resolvePackageRootFromModule(fileURLToPath3(import.meta.url)))});async function getPlanData(directory,phaseArg){let plan=await _internals56.loadPlanJsonOnly(directory);if(plan){let fullMarkdown=_internals56.derivePlanMarkdown(plan);if(phaseArg===void 0||phaseArg===null||phaseArg==="")return{hasPlan:!0,fullMarkdown,requestedPhase:null,phaseMarkdown:null,errorMessage:null,isLegacy:!1};let phaseNum2=typeof phaseArg==="number"?phaseArg:parseInt(String(phaseArg),10);if(Number.isNaN(phaseNum2))return{hasPlan:!0,fullMarkdown,requestedPhase:null,phaseMarkdown:null,errorMessage:`Invalid phase number: "${phaseArg}"`,isLegacy:!1};if(!plan.phases.find((p)=>p.id===phaseNum2))return{hasPlan:!0,fullMarkdown,requestedPhase:phaseNum2,phaseMarkdown:null,errorMessage:`Phase ${phaseNum2} not found in plan.`,isLegacy:!1};let phaseMarkdown2=extractPhaseMarkdown(fullMarkdown,phaseNum2);return{hasPlan:!0,fullMarkdown,requestedPhase:phaseNum2,phaseMarkdown:phaseMarkdown2,errorMessage:null,isLegacy:!1}}let planContent=await _internals56.readSwarmFileAsync(directory,"plan.md");if(!planContent)return{hasPlan:!1,fullMarkdown:"",requestedPhase:null,phaseMarkdown:null,errorMessage:null,isLegacy:!0};if(phaseArg===void 0||phaseArg===null||phaseArg==="")return{hasPlan:!0,fullMarkdown:planContent,requestedPhase:null,phaseMarkdown:null,errorMessage:null,isLegacy:!0};let phaseNum=typeof phaseArg==="number"?phaseArg:parseInt(String(phaseArg),10);if(Number.isNaN(phaseNum))return{hasPlan:!0,fullMarkdown:planContent,requestedPhase:null,phaseMarkdown:null,errorMessage:`Invalid phase number: "${phaseArg}"`,isLegacy:!0};let phaseMarkdown=extractPhaseMarkdown(planContent,phaseNum);if(phaseMarkdown===null)return{hasPlan:!0,fullMarkdown:planContent,requestedPhase:phaseNum,phaseMarkdown:null,errorMessage:`Phase ${phaseNum} not found in plan.`,isLegacy:!0};return{hasPlan:!0,fullMarkdown:planContent,requestedPhase:phaseNum,phaseMarkdown,errorMessage:null,isLegacy:!0}}function extractPhaseMarkdown(markdown,phaseNum){let lines=markdown.split(`
1531
1553
  `),phaseLines=[],inTargetPhase=!1;for(let line of lines){let phaseMatch=line.match(/^## Phase (\d+)/);if(phaseMatch){if(parseInt(phaseMatch[1],10)===phaseNum){inTargetPhase=!0,phaseLines.push(line);continue}else if(inTargetPhase)break}if(inTargetPhase&&line.trim()==="---"&&phaseLines.length>1)break;if(inTargetPhase)phaseLines.push(line)}return phaseLines.length>0?phaseLines.join(`
1532
1554
  `).trim():null}function formatPlanMarkdown(planData){if(!planData.hasPlan)return"No active swarm plan found.";if(planData.errorMessage!==null)return planData.errorMessage;if(planData.requestedPhase!==null&&planData.phaseMarkdown)return planData.phaseMarkdown;return planData.fullMarkdown}async function handlePlanCommand(directory,args2){let phaseArg=args2.length>0?args2[0]:void 0,planData=await getPlanData(directory,phaseArg);return formatPlanMarkdown(planData)}var _internals56;var init_plan_service=__esm(()=>{init_utils2();init_manager();_internals56={loadPlanJsonOnly,derivePlanMarkdown,readSwarmFileAsync}});var init_plan=__esm(()=>{init_plan_service()});async function handlePostMortemCommand(directory,args2,options){try{let pmOptions={force:args2.includes("--force")};if(options?.sessionID)try{pmOptions.llmDelegate=_internals57.createCuratorLLMDelegate(directory,"postmortem",options.sessionID)}catch{}let result=await _internals57.runCuratorPostMortem(directory,pmOptions),lines=[];if(result.success){if(lines.push("## Post-Mortem Report Generated"),lines.push(""),result.reportPath)lines.push(`Report: \`${result.reportPath}\``);if(result.summary)lines.push(""),lines.push(result.summary)}else lines.push("## Post-Mortem Failed"),lines.push(""),lines.push("The post-mortem report could not be generated.");if(result.warnings.length>0){lines.push(""),lines.push("### Warnings");for(let w of result.warnings)lines.push(`- ${w}`)}return lines.join(`
@@ -1755,7 +1777,7 @@ Run \`/swarm evidence ${result.task_id??"unknown"}\` to view it, or \`/swarm sta
1755
1777
  `)}var init_guardrail_explain_service=__esm(()=>{init_tool_policy();init_audit_log();init_destructive_command();init_file_authority();init_helpers();init_shell_write_detect()});var exports_guardrail_explain={};__export(exports_guardrail_explain,{handleGuardrailExplain:()=>handleGuardrailExplain});var init_guardrail_explain=__esm(()=>{init_guardrail_explain_service()});import*as fs61 from"node:fs/promises";import*as path116 from"node:path";function isBlockEntry(entry){if(entry.type===null||entry.type===void 0)return!1;return BLOCK_TYPES.has(entry.type)}function redactSummary(entry){if(entry.type==="file_write"||entry.type==="scope_violation"){let raw=entry.path??"";return redactPath(raw)}if(entry.type==="destructive_block"||entry.type==="sandbox_wrap"||entry.type==="sandbox_skip"||entry.type==="shell"||entry.type===null||entry.type===void 0){let raw=entry.command??"";return redactShellCommand(raw)}return""}function formatEntry(entry){let decisionType=entry.type??"shell",summary=redactSummary(entry);return`- [${entry.ts}] ${decisionType} | agent: ${entry.agent} | ${summary}`}async function handleGuardrailLog(directory,args2){let auditPath=path116.join(directory,".swarm","session","shell-audit.jsonl"),raw;try{raw=await fs61.readFile(auditPath,"utf-8")}catch(error93){if(typeof error93==="object"&&error93!==null&&"code"in error93&&error93.code==="ENOENT")return"No guardrail decisions recorded yet.";throw error93}let lines=raw.split(/\r?\n/),entries=[];for(let line of lines){if(line.trim().length===0)continue;let parsed;try{parsed=JSON.parse(line)}catch{continue}if(!isPlainObject5(parsed))continue;if(typeof parsed.ts!=="string")continue;if(typeof parsed.sessionID!=="string")continue;if(typeof parsed.agent!=="string")continue;if(typeof parsed.tool!=="string")continue;let entry={ts:parsed.ts,sessionID:parsed.sessionID,agent:parsed.agent,tool:parsed.tool};if(typeof parsed.type==="string")entry.type=parsed.type;if(typeof parsed.command==="string")entry.command=parsed.command;if(typeof parsed.path==="string")entry.path=parsed.path;entries.push(entry)}if(entries.length===0)return"No guardrail decisions recorded yet.";let blocksOnly=args2.includes("--blocks-only"),filtered=blocksOnly?entries.filter(isBlockEntry):entries;if(filtered.length===0){if(blocksOnly)return"No guardrail block decisions recorded yet.";return"No guardrail decisions recorded yet."}filtered.sort((a,b)=>{let diff=b.ts.localeCompare(a.ts);return diff===0?0:diff});let header=blocksOnly?"# Guardrail Block Log (most-recent-first)":"# Guardrail Decision Log (most-recent-first)",body=filtered.map(formatEntry).join(`
1756
1778
  `);return`${header}
1757
1779
 
1758
- ${body}`}function isPlainObject5(value){return typeof value==="object"&&value!==null&&(value.constructor===Object||Object.getPrototypeOf(value)===null)}var BLOCK_TYPES;var init_guardrail_log_service=__esm(()=>{init_audit_log();init_helpers();BLOCK_TYPES=new Set(["file_write","scope_violation","destructive_block"])});var exports_guardrail_log={};__export(exports_guardrail_log,{handleGuardrailLog:()=>handleGuardrailLog});var init_guardrail_log=__esm(()=>{init_guardrail_log_service()});var exports_commands={};__export(exports_commands,{resolveCommand:()=>resolveCommand,normalizeSwarmCommandInput:()=>normalizeSwarmCommandInput,handleWriteRetroCommand:()=>handleWriteRetroCommand,handleUnlinkCommand:()=>handleUnlinkCommand,handleTurboCommand:()=>handleTurboCommand,handleSyncPlanCommand:()=>handleSyncPlanCommand,handleStatusCommand:()=>handleStatusCommand,handleSpecifyCommand:()=>handleSpecifyCommand,handleSimulateCommand:()=>handleSimulateCommand,handleSddValidateCommand:()=>handleSddValidateCommand,handleSddStatusCommand:()=>handleSddStatusCommand,handleSddProjectCommand:()=>handleSddProjectCommand,handleSddCommand:()=>handleSddCommand,handleRollbackCommand:()=>handleRollbackCommand,handleRetrieveCommand:()=>handleRetrieveCommand,handleResetSessionCommand:()=>handleResetSessionCommand,handleResetCommand:()=>handleResetCommand,handleQaGatesCommand:()=>handleQaGatesCommand,handlePromoteCommand:()=>handlePromoteCommand,handlePreflightCommand:()=>handlePreflightCommand,handlePlanCommand:()=>handlePlanCommand,handleMemoryStatusCommand:()=>handleMemoryStatusCommand,handleMemoryMigrateCommand:()=>handleMemoryMigrateCommand,handleMemoryImportCommand:()=>handleMemoryImportCommand,handleMemoryExportCommand:()=>handleMemoryExportCommand,handleMemoryCommand:()=>handleMemoryCommand,handleLinkCommand:()=>handleLinkCommand,handleLearningCommand:()=>handleLearningCommand,handleKnowledgeUnactionableCommand:()=>handleKnowledgeUnactionableCommand,handleKnowledgeRetryHardeningCommand:()=>handleKnowledgeRetryHardeningCommand,handleKnowledgeRestoreCommand:()=>handleKnowledgeRestoreCommand,handleKnowledgeQuarantineCommand:()=>handleKnowledgeQuarantineCommand,handleKnowledgeMigrateCommand:()=>handleKnowledgeMigrateCommand,handleKnowledgeListCommand:()=>handleKnowledgeListCommand,handleHistoryCommand:()=>handleHistoryCommand,handleHelpCommand:()=>handleHelpCommand,handleHandoffCommand:()=>handleHandoffCommand,handleGuardrailLog:()=>handleGuardrailLog,handleGuardrailExplain:()=>handleGuardrailExplain,handleFullAutoCommand:()=>handleFullAutoCommand,handleExportCommand:()=>handleExportCommand,handleEvidenceSummaryCommand:()=>handleEvidenceSummaryCommand,handleEvidenceCommand:()=>handleEvidenceCommand,handleDoctorCommand:()=>handleDoctorCommand,handleDiagnoseCommand:()=>handleDiagnoseCommand,handleDeepResearchCommand:()=>handleDeepResearchCommand,handleDeepDiveCommand:()=>handleDeepDiveCommand,handleDarkMatterCommand:()=>handleDarkMatterCommand,handleCurateCommand:()=>handleCurateCommand,handleCouncilCommand:()=>handleCouncilCommand,handleCostsCommand:()=>handleCostsCommand,handleConsolidateCommand:()=>handleConsolidateCommand,handleConfigCommand:()=>handleConfigCommand,handleConcurrencyCommand:()=>handleConcurrencyCommand,handleCodebaseReviewCommand:()=>handleCodebaseReviewCommand,handleCloseCommand:()=>handleCloseCommand,handleClarifyCommand:()=>handleClarifyCommand,handleCheckpointCommand:()=>handleCheckpointCommand,handleBrainstormCommand:()=>handleBrainstormCommand,handleBenchmarkCommand:()=>handleBenchmarkCommand,handleAutoProceedCommand:()=>handleAutoProceedCommand,handleArchiveCommand:()=>handleArchiveCommand,handleAnalyzeCommand:()=>handleAnalyzeCommand,handleAgentsCommand:()=>handleAgentsCommand,handleAcknowledgeSpecDriftCommand:()=>handleAcknowledgeSpecDriftCommand,formatCommandNotFound:()=>formatCommandNotFound,executeSwarmCommand:()=>executeSwarmCommand,createSwarmCommandHandler:()=>createSwarmCommandHandler,classifySwarmCommandToolUse:()=>classifySwarmCommandToolUse,classifySwarmCommandChatFallbackUse:()=>classifySwarmCommandChatFallbackUse,buildHelpText:()=>buildHelpText,agentHasSwarmCommandTool:()=>agentHasSwarmCommandTool,VALID_COMMANDS:()=>VALID_COMMANDS,SWARM_COMMAND_TOOL_COMMANDS:()=>SWARM_COMMAND_TOOL_COMMANDS,SWARM_COMMAND_TOOL_ALLOWLIST:()=>SWARM_COMMAND_TOOL_ALLOWLIST,COMMAND_REGISTRY:()=>COMMAND_REGISTRY,COMMAND_NAME_SET:()=>COMMAND_NAME_SET,COMMAND_NAMES:()=>COMMAND_NAMES});function buildHelpText(){let lines=["## Swarm Commands","","**Chat routing note**: supported read-only `/swarm` commands are routed through the `swarm_command` tool when the active agent has that tool. Unsupported or state-changing commands remain chat-mediated; use `bunx opencode-swarm run <subcommand>` when you need canonical output.",""],CATEGORIES=["core","agent","config","diagnostics","utility"],byCategory=new Map;for(let cat of CATEGORIES)byCategory.set(cat,[]);let deprecatedAliases=[];for(let cmd of VALID_COMMANDS){let entry=COMMAND_REGISTRY[cmd];if(entry.aliasOf){deprecatedAliases.push({name:cmd,aliasOf:entry.aliasOf});continue}if(entry.subcommandOf)continue;if(cmd.includes(" "))continue;let category=entry.category||"utility",catLines=byCategory.get(category)||[];catLines.push(cmd),byCategory.set(category,catLines)}let shownAsSubcommand=new Set;for(let cat of CATEGORIES){let catLines=byCategory.get(cat);if(!catLines||catLines.length===0)continue;let catTitle=cat.charAt(0).toUpperCase()+cat.slice(1);lines.push(`### ${catTitle}`,"");for(let cmd of catLines){let entry=COMMAND_REGISTRY[cmd];if(lines.push(`- \`/swarm ${cmd}\` — ${entry.description}`),entry.clashesWithNativeCcCommand)lines.push(` ⚠️ Name conflicts with CC built-in \`${entry.clashesWithNativeCcCommand}\` — always use \`/swarm ${cmd}\``);if(entry.args)lines.push(` Args: \`${entry.args}\``);if(entry.details)lines.push(` ${entry.details}`);let subcommands=VALID_COMMANDS.filter((sub)=>sub.startsWith(`${cmd} `)&&sub!==cmd);for(let sub of subcommands){shownAsSubcommand.add(sub);let subEntry=COMMAND_REGISTRY[sub],subName=sub.slice(cmd.length+1);if(lines.push(` - \`${subName}\` — ${subEntry.description}`),subEntry.args)lines.push(` Args: \`${subEntry.args}\``);if(subEntry.details)lines.push(` ${subEntry.details}`)}}lines.push("")}for(let cmd of VALID_COMMANDS){if(!cmd.includes(" ")||shownAsSubcommand.has(cmd))continue;let entry=COMMAND_REGISTRY[cmd];if(entry.aliasOf||entry.subcommandOf)continue;if(lines.push(`- \`/swarm ${cmd}\` — ${entry.description}`),entry.clashesWithNativeCcCommand)lines.push(` ⚠️ Name conflicts with CC built-in \`${entry.clashesWithNativeCcCommand}\` — always use \`/swarm ${cmd}\``);if(entry.args)lines.push(` Args: \`${entry.args}\``);if(entry.details)lines.push(` ${entry.details}`)}if(deprecatedAliases.length>0){lines.push("### Deprecated Commands","");for(let{name,aliasOf}of deprecatedAliases){lines.push(`- \`/swarm ${name}\` → Use \`/swarm ${aliasOf}\``);let aliasEntry=COMMAND_REGISTRY[name];if(aliasEntry?.clashesWithNativeCcCommand)lines.push(` ⚠️ Name conflicts with CC built-in \`${aliasEntry.clashesWithNativeCcCommand}\` — always use \`/swarm ${aliasOf}\``)}}return lines.join(`
1780
+ ${body}`}function isPlainObject5(value){return typeof value==="object"&&value!==null&&(value.constructor===Object||Object.getPrototypeOf(value)===null)}var BLOCK_TYPES;var init_guardrail_log_service=__esm(()=>{init_audit_log();init_helpers();BLOCK_TYPES=new Set(["file_write","scope_violation","destructive_block"])});var exports_guardrail_log={};__export(exports_guardrail_log,{handleGuardrailLog:()=>handleGuardrailLog});var init_guardrail_log=__esm(()=>{init_guardrail_log_service()});var exports_commands={};__export(exports_commands,{resolveCommand:()=>resolveCommand,normalizeSwarmCommandInput:()=>normalizeSwarmCommandInput,handleWriteRetroCommand:()=>handleWriteRetroCommand,handleUnlinkCommand:()=>handleUnlinkCommand,handleTurboCommand:()=>handleTurboCommand,handleSyncPlanCommand:()=>handleSyncPlanCommand,handleStatusCommand:()=>handleStatusCommand,handleSpecifyCommand:()=>handleSpecifyCommand,handleSimulateCommand:()=>handleSimulateCommand,handleSddValidateCommand:()=>handleSddValidateCommand,handleSddStatusCommand:()=>handleSddStatusCommand,handleSddProjectCommand:()=>handleSddProjectCommand,handleSddCommand:()=>handleSddCommand,handleRollbackCommand:()=>handleRollbackCommand,handleRetrieveCommand:()=>handleRetrieveCommand,handleResetSessionCommand:()=>handleResetSessionCommand,handleResetCommand:()=>handleResetCommand,handleQaGatesCommand:()=>handleQaGatesCommand,handlePromoteCommand:()=>handlePromoteCommand,handlePreflightCommand:()=>handlePreflightCommand,handlePlanCommand:()=>handlePlanCommand,handleMemoryValueLogCommand:()=>handleMemoryValueLogCommand,handleMemoryStatusCommand:()=>handleMemoryStatusCommand,handleMemoryMigrateCommand:()=>handleMemoryMigrateCommand,handleMemoryImportCommand:()=>handleMemoryImportCommand,handleMemoryExportCommand:()=>handleMemoryExportCommand,handleMemoryCommand:()=>handleMemoryCommand,handleLinkCommand:()=>handleLinkCommand,handleLearningCommand:()=>handleLearningCommand,handleKnowledgeUnactionableCommand:()=>handleKnowledgeUnactionableCommand,handleKnowledgeRetryHardeningCommand:()=>handleKnowledgeRetryHardeningCommand,handleKnowledgeRestoreCommand:()=>handleKnowledgeRestoreCommand,handleKnowledgeQuarantineCommand:()=>handleKnowledgeQuarantineCommand,handleKnowledgeMigrateCommand:()=>handleKnowledgeMigrateCommand,handleKnowledgeListCommand:()=>handleKnowledgeListCommand,handleHistoryCommand:()=>handleHistoryCommand,handleHelpCommand:()=>handleHelpCommand,handleHandoffCommand:()=>handleHandoffCommand,handleGuardrailLog:()=>handleGuardrailLog,handleGuardrailExplain:()=>handleGuardrailExplain,handleFullAutoCommand:()=>handleFullAutoCommand,handleExportCommand:()=>handleExportCommand,handleEvidenceSummaryCommand:()=>handleEvidenceSummaryCommand,handleEvidenceCommand:()=>handleEvidenceCommand,handleDoctorCommand:()=>handleDoctorCommand,handleDiagnoseCommand:()=>handleDiagnoseCommand,handleDeepResearchCommand:()=>handleDeepResearchCommand,handleDeepDiveCommand:()=>handleDeepDiveCommand,handleDarkMatterCommand:()=>handleDarkMatterCommand,handleCurateCommand:()=>handleCurateCommand,handleCouncilCommand:()=>handleCouncilCommand,handleCostsCommand:()=>handleCostsCommand,handleConsolidateCommand:()=>handleConsolidateCommand,handleConfigCommand:()=>handleConfigCommand,handleConcurrencyCommand:()=>handleConcurrencyCommand,handleCodebaseReviewCommand:()=>handleCodebaseReviewCommand,handleCloseCommand:()=>handleCloseCommand,handleClarifyCommand:()=>handleClarifyCommand,handleCheckpointCommand:()=>handleCheckpointCommand,handleBrainstormCommand:()=>handleBrainstormCommand,handleBenchmarkCommand:()=>handleBenchmarkCommand,handleAutoProceedCommand:()=>handleAutoProceedCommand,handleArchiveCommand:()=>handleArchiveCommand,handleAnalyzeCommand:()=>handleAnalyzeCommand,handleAgentsCommand:()=>handleAgentsCommand,handleAcknowledgeSpecDriftCommand:()=>handleAcknowledgeSpecDriftCommand,formatCommandNotFound:()=>formatCommandNotFound,executeSwarmCommand:()=>executeSwarmCommand,createSwarmCommandHandler:()=>createSwarmCommandHandler,classifySwarmCommandToolUse:()=>classifySwarmCommandToolUse,classifySwarmCommandChatFallbackUse:()=>classifySwarmCommandChatFallbackUse,buildHelpText:()=>buildHelpText,agentHasSwarmCommandTool:()=>agentHasSwarmCommandTool,VALID_COMMANDS:()=>VALID_COMMANDS,SWARM_COMMAND_TOOL_COMMANDS:()=>SWARM_COMMAND_TOOL_COMMANDS,SWARM_COMMAND_TOOL_ALLOWLIST:()=>SWARM_COMMAND_TOOL_ALLOWLIST,COMMAND_REGISTRY:()=>COMMAND_REGISTRY,COMMAND_NAME_SET:()=>COMMAND_NAME_SET,COMMAND_NAMES:()=>COMMAND_NAMES});function buildHelpText(){let lines=["## Swarm Commands","","**Chat routing note**: supported read-only `/swarm` commands are routed through the `swarm_command` tool when the active agent has that tool. Unsupported or state-changing commands remain chat-mediated; use `bunx opencode-swarm run <subcommand>` when you need canonical output.",""],CATEGORIES=["core","agent","config","diagnostics","utility"],byCategory=new Map;for(let cat of CATEGORIES)byCategory.set(cat,[]);let deprecatedAliases=[];for(let cmd of VALID_COMMANDS){let entry=COMMAND_REGISTRY[cmd];if(entry.aliasOf){deprecatedAliases.push({name:cmd,aliasOf:entry.aliasOf});continue}if(entry.subcommandOf)continue;if(cmd.includes(" "))continue;let category=entry.category||"utility",catLines=byCategory.get(category)||[];catLines.push(cmd),byCategory.set(category,catLines)}let shownAsSubcommand=new Set;for(let cat of CATEGORIES){let catLines=byCategory.get(cat);if(!catLines||catLines.length===0)continue;let catTitle=cat.charAt(0).toUpperCase()+cat.slice(1);lines.push(`### ${catTitle}`,"");for(let cmd of catLines){let entry=COMMAND_REGISTRY[cmd];if(lines.push(`- \`/swarm ${cmd}\` — ${entry.description}`),entry.clashesWithNativeCcCommand)lines.push(` ⚠️ Name conflicts with CC built-in \`${entry.clashesWithNativeCcCommand}\` — always use \`/swarm ${cmd}\``);if(entry.args)lines.push(` Args: \`${entry.args}\``);if(entry.details)lines.push(` ${entry.details}`);let subcommands=VALID_COMMANDS.filter((sub)=>sub.startsWith(`${cmd} `)&&sub!==cmd);for(let sub of subcommands){shownAsSubcommand.add(sub);let subEntry=COMMAND_REGISTRY[sub],subName=sub.slice(cmd.length+1);if(lines.push(` - \`${subName}\` — ${subEntry.description}`),subEntry.args)lines.push(` Args: \`${subEntry.args}\``);if(subEntry.details)lines.push(` ${subEntry.details}`)}}lines.push("")}for(let cmd of VALID_COMMANDS){if(!cmd.includes(" ")||shownAsSubcommand.has(cmd))continue;let entry=COMMAND_REGISTRY[cmd];if(entry.aliasOf||entry.subcommandOf)continue;if(lines.push(`- \`/swarm ${cmd}\` — ${entry.description}`),entry.clashesWithNativeCcCommand)lines.push(` ⚠️ Name conflicts with CC built-in \`${entry.clashesWithNativeCcCommand}\` — always use \`/swarm ${cmd}\``);if(entry.args)lines.push(` Args: \`${entry.args}\``);if(entry.details)lines.push(` ${entry.details}`)}if(deprecatedAliases.length>0){lines.push("### Deprecated Commands","");for(let{name,aliasOf}of deprecatedAliases){lines.push(`- \`/swarm ${name}\` → Use \`/swarm ${aliasOf}\``);let aliasEntry=COMMAND_REGISTRY[name];if(aliasEntry?.clashesWithNativeCcCommand)lines.push(` ⚠️ Name conflicts with CC built-in \`${aliasEntry.clashesWithNativeCcCommand}\` — always use \`/swarm ${aliasOf}\``)}}return lines.join(`
1759
1781
  `)}function createSwarmCommandHandler(directory,agents,options={}){return async(input,output)=>{let normalized=normalizeSwarmCommandInput(input.command,input.arguments);if(!normalized.isSwarmCommand)return;output.parts.splice(0,output.parts.length,{type:"text",text:await buildSwarmCommandPrompt({directory,agents,sessionID:input.sessionID,tokens:normalized.tokens,activeAgentName:options.getActiveAgentName?.(input.sessionID),packageRoot:options.packageRoot,registeredAgents:options.registeredAgents})});return}}async function buildSwarmCommandPrompt(args2){let{directory,agents,sessionID,tokens,activeAgentName,packageRoot,registeredAgents}=args2,resolved=_internals15.resolveCommand(tokens);if(!resolved){if(tokens.length===0)return buildHelpText();return formatCommandNotFound(tokens)}let typedResolved=resolved,canonicalKey=canonicalCommandKey(typedResolved),policy=classifySwarmCommandToolUse(typedResolved),isV1ToolCommand=SWARM_COMMAND_TOOL_ALLOWLIST.has(canonicalKey),canUseTool=agentHasSwarmCommandTool(activeAgentName,agents,registeredAgents);if(canUseTool&&policy.allowed&&isV1ToolCommand)return routeToSwarmCommandTool({command:canonicalKey,args:resolved.remainingArgs,original:`/swarm ${tokens.join(" ")}`.trim()});if(canUseTool&&isV1ToolCommand&&!policy.allowed)return[`The user typed \`/swarm ${tokens.join(" ")}\`.`,policy.message,"Do not invent command output. Explain the limitation and recommend the canonical CLI path above."].join(`
1760
1782
  `);let chatFallbackPolicy=classifySwarmCommandChatFallbackUse(typedResolved);if(!chatFallbackPolicy.allowed)return[`The user typed \`/swarm ${tokens.join(" ")}\`.`,chatFallbackPolicy.message,"Do not execute this command through chat and do not invent command output."].join(`
1761
1783
  `);let result=await executeSwarmCommand({directory,agents,sessionID,tokens,packageRoot});return formatCanonicalPromptFallback({original:`/swarm ${tokens.join(" ")}`.trim(),text:result.text})}function agentHasSwarmCommandTool(activeAgentName,agents,registeredAgents){let name=activeAgentName??ORCHESTRATOR_NAME,registeredTools=registeredAgents?.[name]?.tools;if(registeredTools)return registeredTools.swarm_command===!0;let explicitTools=agents[name]?.config?.tools;if(explicitTools)return explicitTools.swarm_command===!0;let baseName=stripKnownSwarmPrefix(name);return AGENT_TOOL_MAP[baseName]?.includes("swarm_command")===!0}function formatCanonicalPromptFallback(args2){if(/^\s*\[MODE:/.test(args2.text))return[`The user typed \`${args2.original}\`.`,"The line below is a swarm MODE-activation signal, NOT output to display.","Enter the mode named in its `[MODE: X ...]` header now: follow your",'prompt’s "### MODE: X" section, load the SKILL.md it references, and',"follow that protocol exactly. Treat any text after the closing bracket as","additional instructions. Do NOT echo this signal verbatim.","",args2.text].join(`
@@ -1804,7 +1826,7 @@ Subcommands:
1804
1826
  `+` turbo epic — toggle Epic Mode (+ Lean Turbo) on/off
1805
1827
  `+` turbo status — show detailed status including active strategy and lanes
1806
1828
  `+`
1807
- `+"Session-scoped — resets on new session. `/swarm epic` remains as the epic-only toggle that does not also flip Lean Turbo session state.",category:"utility",toolPolicy:"none"},"full-auto":{handler:(ctx)=>handleFullAutoCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle Full-Auto Mode for the active session [on [mode]|off|status]",args:"on [assisted|supervised|strict], off, status",details:'First-class toggle for Full-Auto Mode — autonomous execution with the critic reviewing escalations on your behalf. No config-level enablement is required: "on" activates immediately (unless full_auto.locked is true in config), "off" disarms the run and returns the session to normal interactive operation, "status" reports the durable run state. '+'An optional mode after "on" overrides full_auto.mode for this run: assisted (critic consulted only on policy escalations), supervised (default — risky/high-impact actions reviewed by the critic), strict (ALL plan mutations reviewed by the critic). '+"While active, the critic answers architect questions and reviews phase boundaries, delegations, and risky actions on your behalf; only ESCALATE_TO_HUMAN verdicts halt the run for your input. The run state is durable (.swarm/full-auto-state.json) and survives restarts; toggle with no argument flips the current state.",category:"utility",toolPolicy:"none"},"auto-proceed":{handler:(ctx)=>handleAutoProceedCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle or set auto-proceed override for the active session",args:"[on|off]",category:"config",details:'Without argument, toggles auto-proceed mode. With "on" or "off", sets the state explicitly.',toolPolicy:"agent"},"write-retro":{handler:(ctx)=>handleWriteRetroCommand(ctx.directory,ctx.args),description:"Write a retrospective evidence bundle for a completed phase <json>",details:"Writes retrospective evidence bundle to .swarm/evidence/retro-{phase}/evidence.json. Required JSON: phase, summary, task_count, task_complexity, total_tool_calls, coder_revisions, reviewer_rejections, test_failures, security_findings, integration_issues. Optional: lessons_learned (max 5), top_rejection_reasons, task_id, metadata.",args:"<json: {phase, summary, task_count, task_complexity, ...}>",category:"utility",toolPolicy:"none"},"knowledge migrate":{handler:(ctx)=>handleKnowledgeMigrateCommand(ctx.directory,ctx.args),description:"Migrate knowledge entries to the current format",subcommandOf:"knowledge",details:"One-time migration from .swarm/context.md SME cache to .swarm/knowledge.jsonl. Skips if sentinel file .swarm/.knowledge-migrated exists, if context.md is absent, or if context.md is empty. Reports entries migrated, dropped (validation/dedup), and total processed.",args:"<directory>",category:"utility"},"knowledge quarantine":{handler:(ctx)=>handleKnowledgeQuarantineCommand(ctx.directory,ctx.args),description:"Move a knowledge entry to quarantine <id> [reason]",subcommandOf:"knowledge",details:'Moves a knowledge entry to quarantine with optional reason string (defaults to "Quarantined via /swarm knowledge quarantine command"). Validates entry ID format (1-64 alphanumeric/hyphen/underscore). Quarantined entries are excluded from knowledge queries.',args:"<entry-id> [reason]",category:"utility"},"knowledge restore":{handler:(ctx)=>handleKnowledgeRestoreCommand(ctx.directory,ctx.args),description:"Restore a quarantined knowledge entry <id>",subcommandOf:"knowledge",details:"Restores a quarantined knowledge entry back to the active knowledge store by ID. Validates entry ID format (1-64 alphanumeric/hyphen/underscore). Entry must currently be in quarantine state.",args:"<entry-id>",category:"utility"},"knowledge unactionable":{handler:(ctx)=>handleKnowledgeUnactionableCommand(ctx.directory,ctx.args),description:"List unactionable knowledge entries pending hardening",subcommandOf:"knowledge",details:"Lists entries from .swarm/knowledge-unactionable.jsonl that failed the actionability gate. Shows pending entries (awaiting next hardening pass) and retire candidates (hardening failed). Use `/swarm knowledge retry-hardening` to reset retire candidates.",category:"utility"},"knowledge retry-hardening":{handler:(ctx)=>handleKnowledgeRetryHardeningCommand(ctx.directory,ctx.args),description:"Reset retire candidates for re-hardening [id]",subcommandOf:"knowledge",details:"Resets the retire_candidate flag on unactionable entries so the next scheduled hardening pass re-attempts LLM enrichment. Without arguments, resets all retire candidates. With an ID prefix, resets only the matching entry.",args:"[entry-id]",category:"utility"},knowledge:{handler:(ctx)=>handleKnowledgeListCommand(ctx.directory,ctx.args),description:"List knowledge entries",category:"utility",toolPolicy:"agent"},memory:{handler:(ctx)=>handleMemoryCommand(ctx.directory,ctx.args),description:"Show Swarm memory commands",category:"utility",toolPolicy:"agent",toolNoArgs:!0},"memory status":{handler:(ctx)=>handleMemoryStatusCommand(ctx.directory,ctx.args),description:"Show Swarm memory provider, JSONL, and migration status",subcommandOf:"memory",args:"",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"memory pending":{handler:(ctx)=>handleMemoryPendingCommand(ctx.directory,ctx.args),description:"Show pending Swarm memory proposals and rejection reasons",subcommandOf:"memory",args:"--limit <n>",category:"diagnostics",toolPolicy:"agent"},"memory recall-log":{handler:(ctx)=>handleMemoryRecallLogCommand(ctx.directory,ctx.args),description:"Summarize Swarm memory recall usage",subcommandOf:"memory",args:"--limit <n>",category:"diagnostics",toolPolicy:"agent"},"memory compact":{handler:(ctx)=>handleMemoryCompactCommand(ctx.directory,ctx.args),description:"Compact deleted, superseded, and expired scratch memories",subcommandOf:"memory",args:"--confirm",category:"utility",toolPolicy:"human-only"},"memory stale":{handler:(ctx)=>handleMemoryStaleCommand(ctx.directory,ctx.args),description:"List stale and low-utility Swarm memories",subcommandOf:"memory",args:"--limit <n>",category:"diagnostics",toolPolicy:"agent"},"memory export":{handler:(ctx)=>handleMemoryExportCommand(ctx.directory,ctx.args),description:"Export current Swarm memory to JSONL files",subcommandOf:"memory",args:"",category:"utility",toolPolicy:"agent",toolNoArgs:!0},"memory evaluate":{handler:(ctx)=>handleMemoryEvaluateCommand(ctx.directory,ctx.args),description:"Run golden Swarm memory recall evaluation fixtures",subcommandOf:"memory",args:"--json, --fixtures <directory>",category:"diagnostics",toolPolicy:"agent"},"memory import":{handler:(ctx)=>handleMemoryImportCommand(ctx.directory,ctx.args),description:"Import legacy JSONL memory into SQLite",subcommandOf:"memory",args:"",category:"utility",toolPolicy:"human-only"},"memory migrate":{handler:(ctx)=>handleMemoryMigrateCommand(ctx.directory,ctx.args),description:"Run the one-time legacy JSONL to SQLite migration",subcommandOf:"memory",args:"",category:"utility",toolPolicy:"human-only"},"memory consolidation-log":{handler:(ctx)=>handleMemoryConsolidationLogCommand(ctx.directory,ctx.args),description:"Summarize recent memory consolidation passes and metrics",subcommandOf:"memory",args:"--limit <n>",category:"diagnostics",toolPolicy:"agent"},"memory-status":{handler:(ctx)=>handleMemoryStatusCommand(ctx.directory,ctx.args),description:"Show Swarm memory provider, JSONL, and migration status",aliasOf:"memory status",deprecated:!0},"memory-export":{handler:(ctx)=>handleMemoryExportCommand(ctx.directory,ctx.args),description:"Export current Swarm memory to JSONL files",aliasOf:"memory export",deprecated:!0},"memory-import":{handler:(ctx)=>handleMemoryImportCommand(ctx.directory,ctx.args),description:"Import legacy JSONL memory into SQLite",aliasOf:"memory import",deprecated:!0},"memory-migrate":{handler:(ctx)=>handleMemoryMigrateCommand(ctx.directory,ctx.args),description:"Run the one-time legacy JSONL to SQLite migration",aliasOf:"memory migrate",deprecated:!0},checkpoint:{handler:(ctx)=>handleCheckpointCommand(ctx.directory,ctx.args),description:"Manage project checkpoints [save|restore|delete|list] <label>",details:"save: creates named snapshot of current .swarm/ state. restore: soft-resets to checkpoint by overwriting current .swarm/ files. delete: removes named checkpoint. list: shows all checkpoints with timestamps. All subcommands require a label except list.",args:"<save|restore|delete|list> <label>",category:"utility",clashesWithNativeCcCommand:"/checkpoint",toolPolicy:"restricted"}},VALID_COMMANDS=Object.keys(COMMAND_REGISTRY);_internals15={handleHelpCommand,validateAliases,validateToolPolicy,emitValidationWarnings,resolveCommand,levenshteinDistance:levenshteinDistance2,findSimilarCommands,buildDetailedHelp},validation=_internals15.validateAliases();if(!validation.valid)throw Error(`COMMAND_REGISTRY alias validation failed:
1829
+ `+"Session-scoped — resets on new session. `/swarm epic` remains as the epic-only toggle that does not also flip Lean Turbo session state.",category:"utility",toolPolicy:"none"},"full-auto":{handler:(ctx)=>handleFullAutoCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle Full-Auto Mode for the active session [on [mode]|off|status]",args:"on [assisted|supervised|strict], off, status",details:'First-class toggle for Full-Auto Mode — autonomous execution with the critic reviewing escalations on your behalf. No config-level enablement is required: "on" activates immediately (unless full_auto.locked is true in config), "off" disarms the run and returns the session to normal interactive operation, "status" reports the durable run state. '+'An optional mode after "on" overrides full_auto.mode for this run: assisted (critic consulted only on policy escalations), supervised (default — risky/high-impact actions reviewed by the critic), strict (ALL plan mutations reviewed by the critic). '+"While active, the critic answers architect questions and reviews phase boundaries, delegations, and risky actions on your behalf; only ESCALATE_TO_HUMAN verdicts halt the run for your input. The run state is durable (.swarm/full-auto-state.json) and survives restarts; toggle with no argument flips the current state.",category:"utility",toolPolicy:"none"},"auto-proceed":{handler:(ctx)=>handleAutoProceedCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle or set auto-proceed override for the active session",args:"[on|off]",category:"config",details:'Without argument, toggles auto-proceed mode. With "on" or "off", sets the state explicitly.',toolPolicy:"agent"},"write-retro":{handler:(ctx)=>handleWriteRetroCommand(ctx.directory,ctx.args),description:"Write a retrospective evidence bundle for a completed phase <json>",details:"Writes retrospective evidence bundle to .swarm/evidence/retro-{phase}/evidence.json. Required JSON: phase, summary, task_count, task_complexity, total_tool_calls, coder_revisions, reviewer_rejections, test_failures, security_findings, integration_issues. Optional: lessons_learned (max 5), top_rejection_reasons, task_id, metadata.",args:"<json: {phase, summary, task_count, task_complexity, ...}>",category:"utility",toolPolicy:"none"},"knowledge migrate":{handler:(ctx)=>handleKnowledgeMigrateCommand(ctx.directory,ctx.args),description:"Migrate knowledge entries to the current format",subcommandOf:"knowledge",details:"One-time migration from .swarm/context.md SME cache to .swarm/knowledge.jsonl. Skips if sentinel file .swarm/.knowledge-migrated exists, if context.md is absent, or if context.md is empty. Reports entries migrated, dropped (validation/dedup), and total processed.",args:"<directory>",category:"utility"},"knowledge quarantine":{handler:(ctx)=>handleKnowledgeQuarantineCommand(ctx.directory,ctx.args),description:"Move a knowledge entry to quarantine <id> [reason]",subcommandOf:"knowledge",details:'Moves a knowledge entry to quarantine with optional reason string (defaults to "Quarantined via /swarm knowledge quarantine command"). Validates entry ID format (1-64 alphanumeric/hyphen/underscore). Quarantined entries are excluded from knowledge queries.',args:"<entry-id> [reason]",category:"utility"},"knowledge restore":{handler:(ctx)=>handleKnowledgeRestoreCommand(ctx.directory,ctx.args),description:"Restore a quarantined knowledge entry <id>",subcommandOf:"knowledge",details:"Restores a quarantined knowledge entry back to the active knowledge store by ID. Validates entry ID format (1-64 alphanumeric/hyphen/underscore). Entry must currently be in quarantine state.",args:"<entry-id>",category:"utility"},"knowledge unactionable":{handler:(ctx)=>handleKnowledgeUnactionableCommand(ctx.directory,ctx.args),description:"List unactionable knowledge entries pending hardening",subcommandOf:"knowledge",details:"Lists entries from .swarm/knowledge-unactionable.jsonl that failed the actionability gate. Shows pending entries (awaiting next hardening pass) and retire candidates (hardening failed). Use `/swarm knowledge retry-hardening` to reset retire candidates.",category:"utility"},"knowledge retry-hardening":{handler:(ctx)=>handleKnowledgeRetryHardeningCommand(ctx.directory,ctx.args),description:"Reset retire candidates for re-hardening [id]",subcommandOf:"knowledge",details:"Resets the retire_candidate flag on unactionable entries so the next scheduled hardening pass re-attempts LLM enrichment. Without arguments, resets all retire candidates. With an ID prefix, resets only the matching entry.",args:"[entry-id]",category:"utility"},knowledge:{handler:(ctx)=>handleKnowledgeListCommand(ctx.directory,ctx.args),description:"List knowledge entries",category:"utility",toolPolicy:"agent"},memory:{handler:(ctx)=>handleMemoryCommand(ctx.directory,ctx.args),description:"Show Swarm memory commands",category:"utility",toolPolicy:"agent",toolNoArgs:!0},"memory status":{handler:(ctx)=>handleMemoryStatusCommand(ctx.directory,ctx.args),description:"Show Swarm memory provider, JSONL, and migration status",subcommandOf:"memory",args:"",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"memory pending":{handler:(ctx)=>handleMemoryPendingCommand(ctx.directory,ctx.args),description:"Show pending Swarm memory proposals and rejection reasons",subcommandOf:"memory",args:"--limit <n>",category:"diagnostics",toolPolicy:"agent"},"memory recall-log":{handler:(ctx)=>handleMemoryRecallLogCommand(ctx.directory,ctx.args),description:"Summarize Swarm memory recall usage",subcommandOf:"memory",args:"--limit <n>",category:"diagnostics",toolPolicy:"agent"},"memory value-log":{handler:(ctx)=>handleMemoryValueLogCommand(ctx.directory,ctx.args),description:"Show Swarm memory Q-value and reward updates",subcommandOf:"memory",args:"--limit <n>",category:"diagnostics",toolPolicy:"agent"},"memory compact":{handler:(ctx)=>handleMemoryCompactCommand(ctx.directory,ctx.args),description:"Compact deleted, superseded, and expired scratch memories",subcommandOf:"memory",args:"--confirm",category:"utility",toolPolicy:"human-only"},"memory stale":{handler:(ctx)=>handleMemoryStaleCommand(ctx.directory,ctx.args),description:"List stale and low-utility Swarm memories",subcommandOf:"memory",args:"--limit <n>",category:"diagnostics",toolPolicy:"agent"},"memory export":{handler:(ctx)=>handleMemoryExportCommand(ctx.directory,ctx.args),description:"Export current Swarm memory to JSONL files",subcommandOf:"memory",args:"",category:"utility",toolPolicy:"agent",toolNoArgs:!0},"memory evaluate":{handler:(ctx)=>handleMemoryEvaluateCommand(ctx.directory,ctx.args),description:"Run golden Swarm memory recall evaluation fixtures",subcommandOf:"memory",args:"--json, --fixtures <directory>",category:"diagnostics",toolPolicy:"agent"},"memory import":{handler:(ctx)=>handleMemoryImportCommand(ctx.directory,ctx.args),description:"Import legacy JSONL memory into SQLite",subcommandOf:"memory",args:"",category:"utility",toolPolicy:"human-only"},"memory migrate":{handler:(ctx)=>handleMemoryMigrateCommand(ctx.directory,ctx.args),description:"Run the one-time legacy JSONL to SQLite migration",subcommandOf:"memory",args:"",category:"utility",toolPolicy:"human-only"},"memory consolidation-log":{handler:(ctx)=>handleMemoryConsolidationLogCommand(ctx.directory,ctx.args),description:"Summarize recent memory consolidation passes and metrics",subcommandOf:"memory",args:"--limit <n>",category:"diagnostics",toolPolicy:"agent"},"memory-status":{handler:(ctx)=>handleMemoryStatusCommand(ctx.directory,ctx.args),description:"Show Swarm memory provider, JSONL, and migration status",aliasOf:"memory status",deprecated:!0},"memory-export":{handler:(ctx)=>handleMemoryExportCommand(ctx.directory,ctx.args),description:"Export current Swarm memory to JSONL files",aliasOf:"memory export",deprecated:!0},"memory-import":{handler:(ctx)=>handleMemoryImportCommand(ctx.directory,ctx.args),description:"Import legacy JSONL memory into SQLite",aliasOf:"memory import",deprecated:!0},"memory-migrate":{handler:(ctx)=>handleMemoryMigrateCommand(ctx.directory,ctx.args),description:"Run the one-time legacy JSONL to SQLite migration",aliasOf:"memory migrate",deprecated:!0},checkpoint:{handler:(ctx)=>handleCheckpointCommand(ctx.directory,ctx.args),description:"Manage project checkpoints [save|restore|delete|list] <label>",details:"save: creates named snapshot of current .swarm/ state. restore: soft-resets to checkpoint by overwriting current .swarm/ files. delete: removes named checkpoint. list: shows all checkpoints with timestamps. All subcommands require a label except list.",args:"<save|restore|delete|list> <label>",category:"utility",clashesWithNativeCcCommand:"/checkpoint",toolPolicy:"restricted"}},VALID_COMMANDS=Object.keys(COMMAND_REGISTRY);_internals15={handleHelpCommand,validateAliases,validateToolPolicy,emitValidationWarnings,resolveCommand,levenshteinDistance:levenshteinDistance2,findSimilarCommands,buildDetailedHelp},validation=_internals15.validateAliases();if(!validation.valid)throw Error(`COMMAND_REGISTRY alias validation failed:
1808
1830
  ${validation.errors.join(`
1809
1831
  `)}`);_internals15.emitValidationWarnings("COMMAND_REGISTRY alias warnings",validation.warnings);try{let toolPolicyValidation=_internals15.validateToolPolicy();_internals15.emitValidationWarnings("COMMAND_REGISTRY toolPolicy warnings",toolPolicyValidation.warnings)}catch(e){warn(`COMMAND_REGISTRY toolPolicy validation failed (non-fatal): ${e.message}`)}});function buildArchitectureSupervisionWorkflow(arch){if(arch?.enabled!==!0)return"";return`## ARCHITECTURE SUPERVISION (summary-level cross-task review)
1810
1832
 
@@ -4991,7 +5013,7 @@ If you call @coder instead of @${swarmId}_coder, the call will FAIL or go to the
4991
5013
  `).slice(0,maxChars)}var _indexLockChain;var init_review_receipt=__esm(()=>{_indexLockChain=Promise.resolve()});function truncateWords(text,maxWords){let trimmed=text.trim();if(trimmed.length===0)return{text:trimmed,truncated:!1};let words=trimmed.split(/\s+/);if(words.length<=maxWords)return{text:trimmed,truncated:!1};return{text:`${words.slice(0,maxWords).join(" ")}…`,truncated:!0}}function capArray(items,maxItems){if(items.length<=maxItems)return{items,truncated:!1};return{items:items.slice(0,maxItems),truncated:!0}}function normalizeAgentWorkSummary(input,maxSummaryWords=MAX_AGENT_SUMMARY_WORDS){let truncated=!1,sum=truncateWords(input.summary,maxSummaryWords);truncated||=sum.truncated;let cap=(items)=>{let r=capArray(items??[],MAX_LIST_ITEMS);return truncated||=r.truncated,r.items},candidate={schema_version:SUMMARY_SCHEMA_VERSION,phase:input.phase,task_id:input.task_id,session_id:input.session_id,agent:input.agent,parent_agent:input.parent_agent,summary:sum.text,key_decisions:cap(input.key_decisions),constraints_observed:cap(input.constraints_observed),constraints_violated:cap(input.constraints_violated),assumptions:cap(input.assumptions),risks:cap(input.risks),files_touched:input.files_touched?capArray(input.files_touched,50).items:void 0,evidence_refs:capArray(input.evidence_refs??[],20).items,created_at:input.created_at??new Date().toISOString(),truncated:truncated||void 0};return AgentWorkSummarySchema.parse(candidate)}var SUMMARY_SCHEMA_VERSION="1.0.0",MAX_AGENT_SUMMARY_WORDS=100,MAX_PHASE_SUMMARY_WORDS=250,MAX_LIST_ITEMS=5,SupervisorVerdictSchema,AgentWorkSummarySchema,PhaseArchitectureSummarySchema,SupervisorFindingSchema,KnowledgeRecommendationSchema,EvidenceProvenanceSchema,ArchitectureSupervisorReportSchema;var init_schema3=__esm(()=>{init_zod();SupervisorVerdictSchema=exports_external.enum(["APPROVE","CONCERNS","REJECT"]);AgentWorkSummarySchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),task_id:exports_external.string().min(1).optional(),session_id:exports_external.string().min(1),agent:exports_external.string().min(1),parent_agent:exports_external.string().min(1).optional(),summary:exports_external.string().min(1),key_decisions:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),constraints_observed:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),constraints_violated:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),assumptions:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),risks:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),files_touched:exports_external.array(exports_external.string().min(1)).max(50).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).max(20).default([]),created_at:exports_external.string().datetime(),truncated:exports_external.boolean().optional()});PhaseArchitectureSummarySchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),summary:exports_external.string().default(""),agents_seen:exports_external.array(exports_external.string().min(1)).default([]),tasks_seen:exports_external.array(exports_external.string().min(1)).default([]),key_decisions:exports_external.array(exports_external.string().min(1)).default([]),conflicts:exports_external.array(exports_external.string().min(1)).default([]),unresolved_risks:exports_external.array(exports_external.string().min(1)).default([]),constraint_violations:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),created_at:exports_external.string().datetime()}),SupervisorFindingSchema=exports_external.object({severity:exports_external.enum(["low","medium","high","critical"]),category:exports_external.string().min(1),agents:exports_external.array(exports_external.string().min(1)).default([]),tasks:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),description:exports_external.string().min(1),recommendation:exports_external.string().default("")}),KnowledgeRecommendationSchema=exports_external.object({lesson:exports_external.string().min(1),target_agents:exports_external.array(exports_external.string().min(1)).default([]),confidence:exports_external.number().min(0).max(1).default(0.5),evidence_refs:exports_external.array(exports_external.string().min(1)).default([])}),EvidenceProvenanceSchema=exports_external.object({agent_name:exports_external.string().min(1).optional(),session_id:exports_external.string().min(1).optional(),captured_at:exports_external.string().datetime().optional()}),ArchitectureSupervisorReportSchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),verdict:SupervisorVerdictSchema,findings:exports_external.array(SupervisorFindingSchema).default([]),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema).default([]),created_at:exports_external.string().datetime(),provenance:EvidenceProvenanceSchema.optional()})});import{existsSync as existsSync75,mkdirSync as mkdirSync41,readFileSync as readFileSync50,renameSync as renameSync26,unlinkSync as unlinkSync23,writeFileSync as writeFileSync25}from"node:fs";import*as path131 from"node:path";function writeRawSidecar(absPath,bundle){mkdirSync41(path131.dirname(absPath),{recursive:!0});let tempFile=`${absPath}.tmp-${Date.now()}-${process.pid}`;try{writeFileSync25(tempFile,JSON.stringify(bundle,null,2),"utf-8"),renameSync26(tempFile,absPath)}finally{if(existsSync75(tempFile))try{unlinkSync23(tempFile)}catch{}}}async function writeAgentSummary(directory,summary){let taskId=summary.task_id??`phase-${summary.phase}-summaries`;return await saveEvidence(directory,taskId,{task_id:taskId,type:"note",timestamp:summary.created_at,agent:summary.agent,verdict:"info",summary:summary.summary,metadata:{kind:AGENT_SUMMARY_METADATA_KIND,phase:summary.phase,session_id:summary.session_id,payload:summary}}),taskId}async function listAgentSummaries(directory,filter={}){let taskIds=await listEvidenceTaskIds(directory),results=[];for(let taskId of taskIds){let loaded=await loadEvidence(directory,taskId);if(loaded.status!=="found")continue;for(let entry of loaded.bundle.entries){if(entry.type!=="note")continue;let meta3=entry.metadata;if(!meta3||meta3.kind!==AGENT_SUMMARY_METADATA_KIND)continue;if(filter.phase!==void 0&&meta3.phase!==filter.phase)continue;if(filter.session!==void 0&&meta3.session_id!==filter.session)continue;let parsed=AgentWorkSummarySchema.safeParse(meta3.payload);if(!parsed.success){warn(`Skipping malformed agent summary in task ${taskId}: ${parsed.error.issues.map((i)=>i.message).join(", ")}`);continue}results.push(parsed.data)}}return results}function writePhaseArchitectureSummary(directory,summary){let rel=path131.join("evidence",String(summary.phase),PHASE_SUMMARY_FILE),abs=validateSwarmPath(directory,rel);return writeRawSidecar(abs,summary),abs}function writeSupervisorReport(directory,report){let rel=path131.join("evidence",String(report.phase),SUPERVISOR_REPORT_FILE),abs=validateSwarmPath(directory,rel),bundle={entries:[{type:SUPERVISOR_ENTRY_TYPE,phase_number:report.phase,scope:"phase",timestamp:report.created_at,verdict:report.verdict,findings:report.findings,knowledge_recommendations:report.knowledge_recommendations,...report.provenance?{provenance:report.provenance}:{}}]};return writeRawSidecar(abs,bundle),abs}function readSupervisorReportRaw(directory,phase){let rel=path131.join("evidence",String(phase),SUPERVISOR_REPORT_FILE),abs;try{abs=validateSwarmPath(directory,rel)}catch{return null}if(!existsSync75(abs))return null;try{return JSON.parse(readFileSync50(abs,"utf-8")).entries?.find((e)=>e.type===SUPERVISOR_ENTRY_TYPE)??null}catch{return null}}var AGENT_SUMMARY_METADATA_KIND="agent_summary",PHASE_SUMMARY_FILE="phase-architecture-summary.json",SUPERVISOR_REPORT_FILE="architecture-supervisor.json",SUPERVISOR_ENTRY_TYPE="architecture-supervisor";var init_store=__esm(()=>{init_manager2();init_utils2();init_utils();init_schema3()});var exports_aggregate={};__export(exports_aggregate,{aggregatePhaseSummary:()=>aggregatePhaseSummary});function dedupe(values){return Array.from(new Set(values)).filter((v)=>v.trim().length>0)}function detectConflicts(summaries){let observedBy=new Map,violatedBy=new Map;for(let s of summaries){for(let c of s.constraints_observed){if(!observedBy.has(c))observedBy.set(c,new Set);observedBy.get(c)?.add(s.agent)}for(let c of s.constraints_violated){if(!violatedBy.has(c))violatedBy.set(c,new Set);violatedBy.get(c)?.add(s.agent)}}let conflicts=[];for(let[constraint,violators]of violatedBy){let observers=observedBy.get(constraint);if(observers&&observers.size>0){let obs=Array.from(observers).sort().join(", "),vio=Array.from(violators).sort().join(", ");conflicts.push(`Constraint "${constraint}" observed by [${obs}] but violated by [${vio}]`)}}return conflicts.sort()}async function aggregatePhaseSummary(directory,phase,options={}){let summaries=await listAgentSummaries(directory,{phase});if(summaries.length===0)return null;let agentsSeen=dedupe(summaries.map((s)=>s.agent)).sort(),tasksSeen=dedupe(summaries.map((s)=>s.task_id).filter((t)=>Boolean(t))).sort(),keyDecisions=dedupe(summaries.flatMap((s)=>s.key_decisions)),unresolvedRisks=dedupe(summaries.flatMap((s)=>s.risks)),constraintViolations=dedupe(summaries.flatMap((s)=>s.constraints_violated)),evidenceRefs=dedupe(summaries.flatMap((s)=>s.evidence_refs)),conflicts=detectConflicts(summaries),headline=`Phase ${phase}: ${summaries.length} agent summary(ies) across ${tasksSeen.length} task(s); ${constraintViolations.length} constraint violation(s), ${conflicts.length} cross-agent conflict(s).`,cap=options.maxPhaseSummaryWords??MAX_PHASE_SUMMARY_WORDS,summaryText=truncateWords(headline,cap).text,phaseSummary={schema_version:SUMMARY_SCHEMA_VERSION,phase,summary:summaryText,agents_seen:agentsSeen,tasks_seen:tasksSeen,key_decisions:keyDecisions,conflicts,unresolved_risks:unresolvedRisks,constraint_violations:constraintViolations,evidence_refs:evidenceRefs,created_at:options.now?.()??new Date().toISOString()};return writePhaseArchitectureSummary(directory,phaseSummary),phaseSummary}var init_aggregate=__esm(()=>{init_schema3();init_store()});var exports_runtime={};__export(exports_runtime,{resolveGrammarsDir:()=>resolveGrammarsDir,parserCache:()=>parserCache,loadGrammar:()=>loadGrammar,isGrammarAvailable:()=>isGrammarAvailable,getSupportedLanguages:()=>getSupportedLanguages,getInitializedLanguages:()=>getInitializedLanguages,clearParserCache:()=>clearParserCache,_internals:()=>_internals82});import{existsSync as existsSync76,statSync as statSync25}from"node:fs";import*as path133 from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";import{Language,Parser as TreeSitterParser}from"web-tree-sitter";async function initTreeSitter(){if(!treeSitterInitPromise)treeSitterInitPromise=(async()=>{if(_internals82.getModuleDir().replace(/\\/g,"/").endsWith("/src/lang"))await _internals82.parserInit();else{let grammarsDir=getGrammarsDirAbsolute(),coreWasmPath=path133.join(grammarsDir,"tree-sitter.wasm");if(!_internals82.fileExists(coreWasmPath))throw Error(`Core tree-sitter WASM runtime missing: ${coreWasmPath}
4992
5014
  The installed OpenCode plugin cache is incomplete or stale. Run 'bunx opencode-swarm update', then restart OpenCode so it fetches a fresh package from npm.`);await _internals82.parserInit({locateFile(scriptName){return path133.join(grammarsDir,scriptName)}})}})().catch((err)=>{throw treeSitterInitPromise=null,err});return treeSitterInitPromise}function sanitizeLanguageId(languageId){let normalized=languageId.toLowerCase();if(!/^[a-z0-9-]+$/.test(normalized))throw Error(`Invalid language ID: ${languageId}`);return normalized}function getWasmFileName(languageId){let sanitized=sanitizeLanguageId(languageId).toLowerCase();if(LANGUAGE_WASM_MAP[sanitized])return LANGUAGE_WASM_MAP[sanitized];return`tree-sitter-${sanitized}.wasm`}function resolveGrammarsDir(thisDir){let normalized=thisDir.replace(/\\/g,"/"),isSource=normalized.endsWith("/src/lang"),isCliBundle=normalized.endsWith("/cli");return isSource?path133.join(thisDir,"grammars"):isCliBundle?path133.join(thisDir,"..","lang","grammars"):path133.join(thisDir,"lang","grammars")}function getGrammarsDirAbsolute(){let thisDir=_internals82.getModuleDir();return resolveGrammarsDir(thisDir)}async function loadGrammar(languageId){if(typeof languageId!=="string"||languageId.length>100)throw Error("Invalid languageId: must be a string of at most 100 characters");let normalizedId=sanitizeLanguageId(languageId).toLowerCase();if(normalizedId.length===0)throw Error("Invalid languageId: empty after sanitization");if(parserCache.has(normalizedId))return parserCache.get(normalizedId);let existing=inflightLoads.get(normalizedId);if(existing)return existing;let loadPromise=(async()=>{await initTreeSitter();let parser=new TreeSitterParser,wasmFileName=getWasmFileName(normalizedId),wasmPath=path133.join(getGrammarsDirAbsolute(),wasmFileName);if(!_internals82.fileExists(wasmPath))throw Error(`Grammar file not found for ${languageId}: ${wasmPath}
4993
5015
  Make sure to run 'bun run build' to copy grammar files to dist/lang/grammars/. If this is an installed OpenCode plugin cache, run 'bunx opencode-swarm update' and restart OpenCode.`);try{let language=await withTimeout(Language.load(wasmPath),GRAMMAR_LOAD_TIMEOUT_MS,Error(`Timed out after ${GRAMMAR_LOAD_TIMEOUT_MS}ms loading grammar`));parser.setLanguage(language)}catch(error93){throw Error(`Failed to load grammar for ${languageId}: ${error93 instanceof Error?error93.message:String(error93)}
4994
- WASM path: ${wasmPath}`)}return parserCache.set(normalizedId,parser),initializedLanguages.add(normalizedId),parser})();inflightLoads.set(normalizedId,loadPromise);try{return await loadPromise}finally{inflightLoads.delete(normalizedId)}}async function isGrammarAvailable(languageId){if(typeof languageId!=="string"||languageId.length>100)return!1;let normalizedId;try{normalizedId=sanitizeLanguageId(languageId).toLowerCase()}catch{return!1}if(normalizedId.length===0)return!1;if(parserCache.has(normalizedId))return!0;try{let wasmFileName=getWasmFileName(normalizedId),wasmPath=path133.join(getGrammarsDirAbsolute(),wasmFileName);return statSync25(wasmPath),!0}catch{return!1}}function clearParserCache(){parserCache.clear(),inflightLoads.clear(),initializedLanguages.clear(),treeSitterInitPromise=null}function getInitializedLanguages(){return Array.from(initializedLanguages)}function getSupportedLanguages(){return Object.keys(LANGUAGE_WASM_MAP)}var parserCache,inflightLoads,GRAMMAR_LOAD_TIMEOUT_MS=1e4,initializedLanguages,treeSitterInitPromise=null,_internals82,LANGUAGE_WASM_MAP;var init_runtime=__esm(()=>{parserCache=new Map,inflightLoads=new Map,initializedLanguages=new Set,_internals82={parserInit:TreeSitterParser.init,getModuleDir:()=>path133.dirname(fileURLToPath4(import.meta.url)),fileExists:existsSync76};LANGUAGE_WASM_MAP={javascript:"tree-sitter-javascript.wasm",typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",python:"tree-sitter-python.wasm",go:"tree-sitter-go.wasm",rust:"tree-sitter-rust.wasm",cpp:"tree-sitter-cpp.wasm",c:"tree-sitter-cpp.wasm",csharp:"tree-sitter-c-sharp.wasm",css:"tree-sitter-css.wasm",bash:"tree-sitter-bash.wasm",ruby:"tree-sitter-ruby.wasm",php:"tree-sitter-php.wasm",java:"tree-sitter-java.wasm",kotlin:"tree-sitter-kotlin.wasm",swift:"tree-sitter-swift.wasm",dart:"tree-sitter-dart.wasm",powershell:"tree-sitter-powershell.wasm",ini:"tree-sitter-ini.wasm",regex:"tree-sitter-regex.wasm"}});var exports_preflight_integration={};__export(exports_preflight_integration,{runManualPreflight:()=>runManualPreflight,createPreflightIntegration:()=>createPreflightIntegration});function createPreflightIntegration(config3){let{automationConfig,directory,swarmDir,preflightConfig,updateStatusArtifact=!0}=config3;if(automationConfig?.capabilities?.phase_preflight!==!0)throw Error("Preflight is not enabled in automation capabilities. Set automation.capabilities.phase_preflight to true.");let manager=new PreflightTriggerManager(automationConfig,void 0,{directory}),statusArtifact=null;if(updateStatusArtifact&&swarmDir)statusArtifact=new AutomationStatusArtifact(swarmDir);let preflightHandler=async(request)=>{log("[PreflightIntegration] Handling preflight request",{requestId:request.id,phase:request.currentPhase,source:request.source});let report=await runPreflight(directory,request.currentPhase,preflightConfig);if(statusArtifact){let state=report.overall==="pass"?"success":"failure";statusArtifact.recordOutcome(state,request.currentPhase,report.message),log("[PreflightIntegration] Status artifact updated",{state,phase:request.currentPhase,message:report.message})}log("[PreflightIntegration] Preflight complete",{requestId:request.id,overall:report.overall,message:report.message,durationMs:report.totalDurationMs})};return manager.registerHandler(preflightHandler),{manager,cleanup:()=>{manager.unregisterHandler()}}}async function runManualPreflight(directory,phase,config3){return runPreflight(directory,phase,config3)}var init_preflight_integration=__esm(()=>{init_status_artifact();init_trigger();init_preflight_service();init_logger()});var exports_doc_scan={};__export(exports_doc_scan,{scanDocIndex:()=>scanDocIndex,extractDocConstraints:()=>extractDocConstraints,doc_scan:()=>doc_scan,doc_extract:()=>doc_extract});import*as crypto10 from"node:crypto";import*as fs82 from"node:fs";import{mkdir as mkdir26,readdir as readdir9,readFile as readFile28,realpath as realpath4,stat as stat13,writeFile as writeFile21}from"node:fs/promises";import*as path146 from"node:path";function normalizeSeparators(filePath){return filePath.replace(/\\/g,"/")}function matchesDocPattern(filePath,patterns){let normalizedPath=normalizeSeparators(filePath),basename18=path146.basename(filePath);for(let pattern of patterns){if(!pattern.includes("/")&&!pattern.includes("\\")){if(basename18===pattern)return!0;continue}if(pattern.startsWith("**/")){let filenamePattern=pattern.slice(3);if(basename18===filenamePattern)return!0;continue}let dirPrefix=normalizeSeparators(pattern).replace(/\/\*\*.*$/,"").replace(/\/\*.*$/,"");if(normalizedPath.startsWith(`${dirPrefix}/`)||normalizedPath===dirPrefix)return!0}return!1}function extractTitleAndSummary(content,filename){let lines=content.split(`
5016
+ WASM path: ${wasmPath}`)}return parserCache.set(normalizedId,parser),initializedLanguages.add(normalizedId),parser})();inflightLoads.set(normalizedId,loadPromise);try{return await loadPromise}finally{inflightLoads.delete(normalizedId)}}async function isGrammarAvailable(languageId){if(typeof languageId!=="string"||languageId.length>100)return!1;let normalizedId;try{normalizedId=sanitizeLanguageId(languageId).toLowerCase()}catch{return!1}if(normalizedId.length===0)return!1;if(parserCache.has(normalizedId))return!0;try{let wasmFileName=getWasmFileName(normalizedId),wasmPath=path133.join(getGrammarsDirAbsolute(),wasmFileName);return statSync25(wasmPath),!0}catch{return!1}}function clearParserCache(){parserCache.clear(),inflightLoads.clear(),initializedLanguages.clear(),treeSitterInitPromise=null}function getInitializedLanguages(){return Array.from(initializedLanguages)}function getSupportedLanguages(){return Object.keys(LANGUAGE_WASM_MAP)}var parserCache,inflightLoads,GRAMMAR_LOAD_TIMEOUT_MS=1e4,initializedLanguages,treeSitterInitPromise=null,_internals82,LANGUAGE_WASM_MAP;var init_runtime=__esm(()=>{parserCache=new Map,inflightLoads=new Map,initializedLanguages=new Set,_internals82={parserInit:TreeSitterParser.init,getModuleDir:()=>path133.dirname(fileURLToPath4(import.meta.url)),fileExists:existsSync76};LANGUAGE_WASM_MAP={javascript:"tree-sitter-javascript.wasm",typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",python:"tree-sitter-python.wasm",go:"tree-sitter-go.wasm",rust:"tree-sitter-rust.wasm",cpp:"tree-sitter-cpp.wasm",c:"tree-sitter-cpp.wasm",csharp:"tree-sitter-c-sharp.wasm",css:"tree-sitter-css.wasm",bash:"tree-sitter-bash.wasm",ruby:"tree-sitter-ruby.wasm",php:"tree-sitter-php.wasm",java:"tree-sitter-java.wasm",kotlin:"tree-sitter-kotlin.wasm",swift:"tree-sitter-swift.wasm",dart:"tree-sitter-dart.wasm",powershell:"tree-sitter-powershell.wasm",ini:"tree-sitter-ini.wasm",regex:"tree-sitter-regex.wasm"}});var exports_preflight_integration={};__export(exports_preflight_integration,{runManualPreflight:()=>runManualPreflight,createPreflightIntegration:()=>createPreflightIntegration});function createPreflightIntegration(config3){let{automationConfig,directory,swarmDir,preflightConfig,updateStatusArtifact=!0}=config3;if(automationConfig?.capabilities?.phase_preflight!==!0)throw Error("Preflight is not enabled in automation capabilities. Set automation.capabilities.phase_preflight to true.");let manager=new PreflightTriggerManager(automationConfig,void 0,{directory}),statusArtifact=null;if(updateStatusArtifact&&swarmDir)statusArtifact=new AutomationStatusArtifact(swarmDir);let preflightHandler=async(request)=>{log("[PreflightIntegration] Handling preflight request",{requestId:request.id,phase:request.currentPhase,source:request.source});let report=await runPreflight(directory,request.currentPhase,preflightConfig);if(statusArtifact){let state=report.overall==="pass"?"success":"failure";statusArtifact.recordOutcome(state,request.currentPhase,report.message),log("[PreflightIntegration] Status artifact updated",{state,phase:request.currentPhase,message:report.message})}log("[PreflightIntegration] Preflight complete",{requestId:request.id,overall:report.overall,message:report.message,durationMs:report.totalDurationMs})};return manager.registerHandler(preflightHandler),{manager,cleanup:()=>{manager.unregisterHandler()}}}async function runManualPreflight(directory,phase,config3){return runPreflight(directory,phase,config3)}var init_preflight_integration=__esm(()=>{init_status_artifact();init_trigger();init_preflight_service();init_logger()});var exports_doc_scan={};__export(exports_doc_scan,{scanDocIndex:()=>scanDocIndex,extractDocConstraints:()=>extractDocConstraints,doc_scan:()=>doc_scan,doc_extract:()=>doc_extract});import*as crypto10 from"node:crypto";import*as fs82 from"node:fs";import{mkdir as mkdir26,readdir as readdir9,readFile as readFile28,realpath as realpath4,stat as stat13,writeFile as writeFile21}from"node:fs/promises";import*as path146 from"node:path";function normalizeSeparators(filePath){return filePath.replace(/\\/g,"/")}function matchesDocPattern(filePath,patterns){let normalizedPath=normalizeSeparators(filePath),basename20=path146.basename(filePath);for(let pattern of patterns){if(!pattern.includes("/")&&!pattern.includes("\\")){if(basename20===pattern)return!0;continue}if(pattern.startsWith("**/")){let filenamePattern=pattern.slice(3);if(basename20===filenamePattern)return!0;continue}let dirPrefix=normalizeSeparators(pattern).replace(/\/\*\*.*$/,"").replace(/\/\*.*$/,"");if(normalizedPath.startsWith(`${dirPrefix}/`)||normalizedPath===dirPrefix)return!0}return!1}function extractTitleAndSummary(content,filename){let lines=content.split(`
4995
5017
  `),title=filename,summary="",foundTitle=!1,potentialSummaryLines=[];for(let i=0;i<lines.length&&i<READ_LINES_LIMIT;i++){let line=lines[i].trim();if(!foundTitle&&line.startsWith("# ")){title=line.slice(2).trim(),foundTitle=!0;continue}if(line&&!line.startsWith("#"))potentialSummaryLines.push(line)}for(let line of potentialSummaryLines)if(summary+=(summary?" ":"")+line,summary.length>=MAX_SUMMARY_LENGTH)break;if(summary.length>MAX_SUMMARY_LENGTH)summary=`${summary.slice(0,MAX_SUMMARY_LENGTH-3)}...`;return{title,summary}}function stripMarkdown(text){return text.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/^\s*[-*•]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").trim()}async function scanDocIndex(directory){let manifestPath=path146.join(directory,".swarm","doc-manifest.json"),defaultPatterns=DocsConfigSchema.parse({}).doc_patterns,extraPatterns=["ARCHITECTURE.md","CLAUDE.md","AGENTS.md",".github/*.md","doc/**/*.md"],allPatterns=[...defaultPatterns,...extraPatterns];try{let manifestContent=await readFile28(manifestPath,"utf-8"),existingManifest=JSON.parse(manifestContent);if(existingManifest.schema_version===1&&existingManifest.files){let cacheValid=!0;for(let file3 of existingManifest.files)try{let fullPath=path146.join(directory,file3.path);if(fs82.statSync(fullPath).mtimeMs>file3.mtime){cacheValid=!1;break}}catch{cacheValid=!1;break}if(cacheValid)return{manifest:existingManifest,cached:!0}}}catch{}let resolvedDirectory=await realpath4(directory).catch(()=>directory),discoveredFiles=[],rootReadable=!1,truncated=!1,walkDir2=async(dir)=>{let entries;try{if(entries=await readdir9(dir,{withFileTypes:!0}),dir===directory)rootReadable=!0}catch{return}for(let entry of entries){if(discoveredFiles.length>=MAX_INDEXED_FILES){truncated=!0;return}let isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let symlinkPath=path146.join(dir,entry.name),resolved=await realpath4(symlinkPath),rel=path146.relative(resolvedDirectory,resolved);if(rel.startsWith("..")||path146.isAbsolute(rel))continue;isFile=(await stat13(symlinkPath)).isFile()}catch{continue}if(isDir){if(!SKIP_DIRECTORIES3.has(entry.name))await walkDir2(path146.join(dir,entry.name));continue}if(!isFile)continue;let fullPath=path146.join(dir,entry.name),relPath=normalizeSeparators(path146.relative(directory,fullPath)),skipThisFile=!1;for(let pattern of SKIP_PATTERNS)if(pattern.test(relPath)){skipThisFile=!0;break}if(skipThisFile)continue;if(!matchesDocPattern(relPath,allPatterns))continue;let fileStat;try{fileStat=await stat13(fullPath)}catch{continue}let content;try{content=await readFile28(fullPath,"utf-8")}catch{continue}let{title,summary}=extractTitleAndSummary(content,path146.basename(relPath));discoveredFiles.push({path:relPath,title,summary,lines:content.split(`
4996
5018
  `).length,mtime:fileStat.mtimeMs})}};if(await walkDir2(directory),!rootReadable)return{manifest:{schema_version:1,scanned_at:new Date().toISOString(),files:[]},cached:!1};if(discoveredFiles.sort((a,b)=>a.path.toLowerCase().localeCompare(b.path.toLowerCase())),discoveredFiles.length>MAX_INDEXED_FILES)discoveredFiles.splice(MAX_INDEXED_FILES),truncated=!0;if(truncated&&discoveredFiles.length>0)discoveredFiles[0].summary=`[Warning: ${MAX_INDEXED_FILES}+ docs found, listing first ${MAX_INDEXED_FILES}] `+discoveredFiles[0].summary;let manifest={schema_version:1,scanned_at:new Date().toISOString(),files:discoveredFiles};try{await mkdir26(path146.dirname(manifestPath),{recursive:!0}),await writeFile21(manifestPath,JSON.stringify(manifest,null,2),"utf-8")}catch{}return{manifest,cached:!1}}function isConstraintLine(line){let upperLine=line.toUpperCase();for(let pattern of CONSTRAINT_PATTERNS)if(pattern.test(upperLine))return!0;if(/^\s*[-*•]/.test(line)&&ACTION_WORDS.test(line))return!0;return!1}function extractConstraintsFromContent(content){let lines=content.split(`
4997
5019
  `),constraints=[];for(let line of lines){if(constraints.length>=MAX_CONSTRAINTS_PER_DOC)break;let trimmed=line.trim();if(!trimmed)continue;if(isConstraintLine(trimmed)){let cleaned=stripMarkdown(trimmed),len=cleaned.length;if(len>=MIN_LESSON_LENGTH&&len<=MAX_CONSTRAINT_LENGTH)constraints.push(cleaned)}}return constraints}async function extractDocConstraints(directory,taskFiles,taskDescription){let manifestPath=path146.join(directory,".swarm","doc-manifest.json"),manifest;try{let content=await readFile28(manifestPath,"utf-8");manifest=JSON.parse(content)}catch{manifest=(await scanDocIndex(directory)).manifest}let knowledgePath=resolveSwarmKnowledgePath(directory),existingEntries=await readKnowledge(knowledgePath),taskContext=[...taskFiles,taskDescription].join(" "),taskBigrams=wordBigrams(normalize5(taskContext)),extractedCount=0,skippedCount=0,details=[];for(let docFile of manifest.files){let docContext=`${docFile.path} ${docFile.title} ${docFile.summary}`,docBigrams=wordBigrams(normalize5(docContext)),score=jaccardBigram(taskBigrams,docBigrams);if(score<=RELEVANCE_THRESHOLD){skippedCount++;continue}let fullContent;try{fullContent=await readFile28(path146.join(directory,docFile.path),"utf-8")}catch{skippedCount++;continue}let constraints=extractConstraintsFromContent(fullContent);if(constraints.length===0){skippedCount++;continue}let docDetails={path:docFile.path,score,constraints:[]};for(let constraint of constraints)if(!findNearDuplicate(constraint,existingEntries,DEDUP_THRESHOLD3)){let entry={id:crypto10.randomUUID(),tier:"swarm",lesson:constraint,category:"architecture",tags:["doc-scan",path146.basename(docFile.path)],scope:"global",confidence:0.5,status:"candidate",confirmed_by:[],project_name:"",retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:1,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),auto_generated:!0,hive_eligible:!1};await appendKnowledge(knowledgePath,entry),existingEntries.push(entry),extractedCount++,docDetails.constraints.push(constraint)}if(docDetails.constraints.length>0)details.push(docDetails);else skippedCount++}return{extracted:extractedCount,skipped:skippedCount,details}}var SKIP_DIRECTORIES3,SKIP_PATTERNS,MAX_SUMMARY_LENGTH=200,MAX_INDEXED_FILES=100,READ_LINES_LIMIT=30,MIN_LESSON_LENGTH=15,MAX_CONSTRAINTS_PER_DOC=5,MAX_CONSTRAINT_LENGTH=200,RELEVANCE_THRESHOLD=0.1,DEDUP_THRESHOLD3=0.6,CONSTRAINT_PATTERNS,ACTION_WORDS,doc_scan,doc_extract;var init_doc_scan=__esm(()=>{init_zod();init_schema();init_knowledge_store();init_create_tool();SKIP_DIRECTORIES3=new Set(["node_modules",".git",".swarm","dist","build",".next","vendor","bazel-out","bazel-bin","bazel-genfiles","bazel-testlogs",".gradle","target"]),SKIP_PATTERNS=[/\.test\./,/\.spec\./,/\.d\.ts$/];CONSTRAINT_PATTERNS=[/\bMUST\b/,/\bMUST NOT\b/,/\bSHOULD\b/,/\bSHOULD NOT\b/,/\bDO NOT\b/,/\bALWAYS\b/,/\bNEVER\b/,/\bREQUIRED\b/],ACTION_WORDS=/\b(must|should|don't|avoid|ensure|use|follow)\b/i;doc_scan=createSwarmTool({description:"Scan project documentation files and build an index manifest. Caches results in .swarm/doc-manifest.json for fast subsequent scans.",args:{force:exports_external.boolean().optional().describe("Force re-scan even if cache is valid")},execute:async(args2,directory)=>{let force=!1;try{if(args2&&typeof args2==="object"){if(args2.force===!0)force=!0}}catch{}if(force){let manifestPath=path146.join(directory,".swarm","doc-manifest.json");try{fs82.unlinkSync(manifestPath)}catch{}}let{manifest,cached:cached3}=await scanDocIndex(directory);return JSON.stringify({success:!0,files_count:manifest.files.length,cached:cached3,manifest},null,2)}}),doc_extract=createSwarmTool({description:"Extract actionable constraints from project documentation relevant to the current task. Scans docs via doc-manifest, scores relevance via Jaccard bigram similarity, and stores non-duplicate constraints in .swarm/knowledge.jsonl.",args:{task_files:exports_external.array(exports_external.string()).describe("List of file paths involved in the current task"),task_description:exports_external.string().describe("Description of the current task")},execute:async(args2,directory)=>{let taskFiles=[],taskDescription="";try{if(args2&&typeof args2==="object"){let obj=args2;if(Array.isArray(obj.task_files))taskFiles=obj.task_files.filter((f)=>typeof f==="string");if(typeof obj.task_description==="string")taskDescription=obj.task_description}}catch{}if(taskFiles.length===0&&!taskDescription)return JSON.stringify({success:!1,error:"task_files or task_description is required"});let result=await extractDocConstraints(directory,taskFiles,taskDescription);return JSON.stringify({success:!0,...result},null,2)}})});import{existsSync as existsSync81}from"node:fs";import{readFile as readFile29}from"node:fs/promises";import*as path147 from"node:path";function inferCategoriesFromPhase(phaseDescription){let lower=phaseDescription.toLowerCase(),patterns=[{pattern:/\b(?:test|qa|quality|verification|validation)\b/,categories:["testing","debugging"]},{pattern:/\b(?:implement|build|develop|coding|code)\b/,categories:["tooling","architecture","debugging"]},{pattern:/\b(?:integrat|deploy|ci|cd|release|publish)\b/,categories:["integration","tooling","performance"]},{pattern:/\b(?:plan|design|architect|spec|requirement)\b/,categories:["architecture","process"]},{pattern:/\b(?:review|refactor|cleanup|polish|optimi)\b/,categories:["performance","architecture","process"]},{pattern:/\b(?:secur|audit|harden|compliance)\b/,categories:["security","testing"]},{pattern:/\b(?:setup|config|scaffold|init|bootstrap)\b/,categories:["tooling","other"]},{pattern:/\b(?:doc|readme|changelog)\b/,categories:["process","tooling"]}];for(let{pattern,categories}of patterns)if(pattern.test(lower))return categories;return["process","tooling"]}async function transactShownFile(shownFile,mutate){return transactFile(shownFile,async(filePath)=>{if(!existsSync81(filePath))return{};try{let content=await readFile29(filePath,"utf-8");return JSON.parse(content)}catch{return{}}},async(filePath,data)=>{await atomicWriteFile(filePath,JSON.stringify(data,null,2))},mutate)}async function recordLessonsShown(directory,lessonIds,currentPhase){let shownFile=path147.join(directory,".swarm",".knowledge-shown.json");try{let phaseMatch=/^Phase\s+(\d+)/i.exec(currentPhase),canonicalKey=phaseMatch?`Phase ${phaseMatch[1]}`:currentPhase;if(!await transactShownFile(shownFile,(shownData)=>{return shownData[canonicalKey]=lessonIds,shownData}))warn("[swarm] Knowledge: failed to record shown lessons")}catch{warn("[swarm] Knowledge: failed to record shown lessons")}}async function readMergedKnowledge(directory,config3,context,opts){let swarmPath=resolveSwarmKnowledgePath(directory),swarmEntries=await readKnowledge(swarmPath),hiveEntries=[];if(config3.hive_enabled!==!1){let hivePath=resolveHiveKnowledgePath();hiveEntries=await readKnowledge(hivePath)}let seenLessons=new Set,merged=[];for(let entry of hiveEntries){let normalized=normalize5(entry.lesson);seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}for(let entry of swarmEntries){let normalized=normalize5(entry.lesson);if(seenLessons.has(normalized))continue;let swarmBigrams=wordBigrams(normalized);if(hiveEntries.some((hiveEntry)=>jaccardBigram(swarmBigrams,wordBigrams(normalize5(hiveEntry.lesson)))>=JACCARD_THRESHOLD2))continue;if(merged.some((m)=>m.tier==="swarm"&&jaccardBigram(swarmBigrams,wordBigrams(normalize5(m.lesson)))>=JACCARD_THRESHOLD2))continue;seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}let retractionRecords=await readRetractionRecords(directory),suppressedLessons=new Set(retractionRecords.map((record3)=>record3.normalized_lesson).filter((value)=>typeof value==="string"&&value.length>0)),scopeFilter=config3.scope_filter??["global"],ranked=merged.filter((entry)=>(opts?.skipScopeFilter||scopeFilter.some((pattern)=>(entry.scope??"global")===pattern))&&entry.status!==QUARANTINED_STATUS&&!suppressedLessons.has(normalize5(entry.lesson))).map((entry)=>{let categoryScore=0;if(context?.currentPhase){if(inferCategoriesFromPhase(context.currentPhase).includes(entry.category))categoryScore=1;else if(entry.category==="process")categoryScore=0.5}else categoryScore=0.5;let confidenceScore=entry.confidence,keywordsScore=0;if(context?.techStack&&entry.tags.length>0){let matchingTags=entry.tags.filter((t)=>context.techStack.some((s)=>t.toLowerCase().includes(s.toLowerCase())||s.toLowerCase().includes(t.toLowerCase()))).length;keywordsScore=Math.min(matchingTags/Math.max(entry.tags.length,1),1)}else if(entry.tags.length===0)keywordsScore=0.5;let tierBoost=0,isSameProject=!1;if(entry.tier==="hive"&&"source_project"in entry){let sourceProject=entry.source_project;isSameProject=!!(context?.projectName&&sourceProject===context.projectName),tierBoost=HIVE_TIER_BOOST}let sameProjectPenalty=isSameProject?DEFAULT_SAME_PROJECT_PENALTY:0,finalScore=categoryScore*0.4+confidenceScore*0.35+keywordsScore*0.25+tierBoost+sameProjectPenalty;return{...entry,relevanceScore:{category:categoryScore,confidence:confidenceScore,keywords:keywordsScore},finalScore:Math.min(Math.max(finalScore,0),1)}});ranked.sort((a,b)=>{let scoreDiff=b.finalScore-a.finalScore;if(Math.abs(scoreDiff)>0.001)return scoreDiff;let dateA=new Date(a.created_at).getTime();return new Date(b.created_at).getTime()-dateA});let maxInject=config3.max_inject_count??5,topN=ranked.slice(0,maxInject);if(topN.length>0&&context?.currentPhase)recordLessonsShown(directory,topN.map((e)=>e.id),context.currentPhase).catch((err)=>{warn("[knowledge-reader] recordLessonsShown unexpected rejection:",err)});return topN}async function updateRetrievalOutcome(directory,phaseInfo,phaseSucceeded){let shownFile=path147.join(directory,".swarm",".knowledge-shown.json");try{if(!existsSync81(shownFile))return;let shownIds;try{let content=await readFile29(shownFile,"utf-8");shownIds=JSON.parse(content)[phaseInfo]}catch{return}if(!shownIds||shownIds.length===0)return;let outcome=phaseSucceeded?"success":"failure",evidenceSummary=`${phaseInfo} ${phaseSucceeded?"succeeded":"failed"} after entry was shown`;await transactShownFile(shownFile,(data)=>{return delete data[phaseInfo],data});for(let id of shownIds)await _internals85.recordKnowledgeEvent(directory,{type:"outcome",knowledge_id:id,phase:phaseInfo,outcome,evidence_summary:evidenceSummary})}catch{warn("[swarm] Knowledge: failed to update retrieval outcomes")}}function lc(s){return(s??"").toLowerCase()}function anyMatch(haystack,needles){if(needles.length===0)return!1;let hay=haystack.map(lc);return needles.some((n)=>hay.some((h)=>h.includes(lc(n))))}function tokenizeContext(ctx){let parts=[];if(ctx.taskTitle)parts.push(ctx.taskTitle);if(ctx.taskDescription)parts.push(ctx.taskDescription);if(ctx.lastUserMessage)parts.push(ctx.lastUserMessage);if(ctx.currentAction)parts.push(ctx.currentAction);if(ctx.currentTool)parts.push(ctx.currentTool);if(ctx.targetAgent)parts.push(ctx.targetAgent);if(ctx.declaredScope)parts.push(ctx.declaredScope);if(ctx.recentReviewerFailures)parts.push(...ctx.recentReviewerFailures);if(ctx.recentTestFailures)parts.push(...ctx.recentTestFailures);if(ctx.recentToolErrors)parts.push(...ctx.recentToolErrors);if(ctx.planConstraints)parts.push(...ctx.planConstraints);if(ctx.filePaths)parts.push(...ctx.filePaths);return parts.map(lc)}function scoreDirectiveAgainstContext(entry,ctx){let haystack=tokenizeContext(ctx),triggerHit=entry.triggers&&entry.triggers.length>0?anyMatch(haystack,entry.triggers):!1,actionHit=entry.applies_to_tools&&entry.applies_to_tools.length>0?entry.applies_to_tools.map(lc).some((t)=>t===lc(ctx.currentTool)||t===lc(ctx.currentAction)):!1,agentHit=entry.applies_to_agents&&entry.applies_to_agents.length>0?entry.applies_to_agents.map(lc).some((a)=>a===lc(ctx.targetAgent)):!1,score=0;if(triggerHit)score+=0.5;if(actionHit)score+=0.35;if(agentHit)score+=0.25;if(entry.directive_priority==="critical")score+=0.4;else if(entry.directive_priority==="high")score+=0.2;else if(entry.directive_priority==="medium")score+=0.1;return{triggerHit,actionHit,agentHit,score:Math.min(1,score)}}var JACCARD_THRESHOLD2=0.6,HIVE_TIER_BOOST=0.05,DEFAULT_SAME_PROJECT_PENALTY=-0.05,QUARANTINED_STATUS="quarantined",_internals85;var init_knowledge_reader=__esm(()=>{init_task_file();init_logger();init_knowledge_events();init_knowledge_store();_internals85={readMergedKnowledge,updateRetrievalOutcome,scoreDirectiveAgainstContext,transactShownFile,recordKnowledgeEvent}});function entryText(e){return`${e.lesson} ${e.tags.join(" ")} ${e.category}`}function entryAgePhases(e){let cb=e.confirmed_by;if(!Array.isArray(cb)||cb.length===0)return 0;let phases=new Set;for(let c of cb)if(typeof c?.phase_number==="number")phases.add(c.phase_number);return phases.size>0?phases.size:cb.length}function clampLambda(v){if(typeof v!=="number"||Number.isNaN(v))return 0.5;return Math.min(1,Math.max(0,v))}function mmrRerank(pool,pinned,max,lambda){if(pool.length===0)return[];let bigrams=new Map,bg=(e)=>{let s=bigrams.get(e.id);if(!s)s=wordBigrams(normalize5(e.lesson??"")),bigrams.set(e.id,s);return s},selected=[...pinned],candidates=[...pool],out=[];while(selected.length<max&&candidates.length>0){let bestIdx=-1,bestScore=Number.NEGATIVE_INFINITY,best=null;for(let i=0;i<candidates.length;i++){let c=candidates[i],maxSim=0;for(let s of selected){let sim=jaccardBigram(bg(c),bg(s));if(sim>maxSim)maxSim=sim}let score=lambda*c.finalScore-(1-lambda)*maxSim;if(score>bestScore+0.000000001||Math.abs(score-bestScore)<=0.000000001&&best!==null&&tieBreak(c,best)<0)bestScore=score,bestIdx=i,best=c}if(bestIdx<0||best===null)break;out.push(best),selected.push(best),candidates.splice(bestIdx,1)}return out}function tieBreak(a,b){if(Math.abs(a.finalScore-b.finalScore)>0.000000001)return b.finalScore-a.finalScore;let at=new Date(a.created_at).getTime(),bt=new Date(b.created_at).getTime();if(at!==bt)return bt-at;return a.id<b.id?-1:a.id>b.id?1:0}function statusBoost(status){if(status==="established")return 0.1;if(status==="promoted")return 0.05;return 0}async function searchKnowledge(params){let{directory,config:config3,query,context,mode,agent="unknown",sessionId="unknown",tier="all",emitEvent=!0,applyScopeFilter=!0,forceReadHive=!1,applyRoleScope=!0}=params,traceId=newTraceId(),max=params.maxResults??config3.max_inject_count??5,results=[],synonymTokens=[],synonymTrace={};try{let mergeConfig={...config3,hive_enabled:tier==="swarm"?!1:forceReadHive?!0:config3.hive_enabled,max_inject_count:Math.max(20,max)},projected={projectName:context?.projectName??"unknown",currentPhase:context?.currentPhase??"",techStack:context?.techStack,recentErrors:[...context?.recentReviewerFailures??[],...context?.recentTestFailures??[],...context?.recentToolErrors??[]]},candidates=await readMergedKnowledge(directory,mergeConfig,projected,{skipScopeFilter:!applyScopeFilter}),counterRollups=await readKnowledgeCounterRollups(directory);candidates=candidates.filter((e)=>{if(e.status==="archived")return!1;if(e.status==="quarantined")return!1;if(tier==="hive"&&e.tier!=="hive")return!1;return!0});let role=stripKnownSwarmPrefix(agent).toLowerCase();if(applyRoleScope&&role&&role!=="unknown")candidates=candidates.filter((e)=>{if(!e.applies_to_agents||e.applies_to_agents.length===0)return!0;if(role==="architect")return!0;return e.applies_to_agents.map((a)=>stripKnownSwarmPrefix(a).toLowerCase()).includes(role)});let queryText=(query??"").trim(),queryBigrams=queryText?wordBigrams(normalize5(queryText)):null,hasQuery=queryBigrams!==null,textWeight=hasQuery?TEXT_WEIGHT:0,metaWeight=hasQuery?META_WEIGHT:1,compositeRaw=[queryText,context?.taskTitle,context?.taskDescription,context?.lastUserMessage,context?.currentAction,...context?.recentReviewerFailures??[],...context?.recentTestFailures??[],...context?.recentToolErrors??[]].filter((s)=>typeof s==="string"&&s.length>0).join(" "),compositeNorm=normalize5(compositeRaw),hasComposite=compositeNorm.length>0;try{if(hasComposite){let synMap=await readSynonymMap(directory,config3.retrieval?.synonym_map_max_pairs),synIndex=buildSynonymIndex(synMap,config3.retrieval?.synonym_min_cooccurrence),baseTokens=compositeNorm.split(" ").filter(Boolean);synonymTokens=expandTokens(synIndex,baseTokens)}}catch{synonymTokens=[]}let minConf=typeof config3.directive_min_confidence==="number"?config3.directive_min_confidence:DIRECTIVE_BOOST_MIN_CONFIDENCE,scored=candidates.map((entry)=>{let retrievalOutcomes=effectiveRetrievalOutcomes(entry.retrieval_outcomes,counterRollups.get(entry.id)),textScore=queryBigrams?jaccardBigram(queryBigrams,wordBigrams(normalize5(entryText(entry)))):0,metaScore=entry.finalScore,ds=context?scoreDirectiveAgainstContext(entry,context):{triggerHit:!1,actionHit:!1,agentHit:!1,score:0},confBoost=context&&entry.confidence>=minConf&&(ds.actionHit||ds.agentHit)?0.25:0,generatedSkillBoost=entry.generated_skill_path&&entry.status!=="archived"?0.05:0,outcomeBoost=computeOutcomeSignal(retrievalOutcomes)*OUTCOME_RANK_WEIGHT,coldStartBonus=(retrievalOutcomes.applied_explicit_count??0)===0&&entryAgePhases(entry)<(config3.retrieval?.cold_start_max_age_phases??DEFAULT_COLD_START_MAX_AGE_PHASES)?config3.retrieval?.cold_start_bonus??DEFAULT_COLD_START_BONUS:0,synonymBoost=0;if(synonymTokens.length>0){let entryHay=normalize5(entryText(entry)),matched=[];for(let t of synonymTokens)if(t.length>0&&entryHay.includes(t))matched.push(t);if(matched.length>0)synonymBoost=SYNONYM_TEXT_BOOST,synonymTrace[entry.id]=matched}let triggerRecallBoost=!ds.triggerHit&&hasComposite&&Array.isArray(entry.triggers)&&entry.triggers.some((tr)=>{let n=normalize5(tr);return n.length>=TRIGGER_RECALL_MIN_LEN&&compositeNorm.includes(n)})?TRIGGER_RECALL_BOOST:0,finalScore=Math.min(1,Math.max(0,textWeight*textScore+metaWeight*metaScore+ds.score+confBoost+generatedSkillBoost+outcomeBoost+coldStartBonus+synonymBoost+triggerRecallBoost+(hasQuery?statusBoost(entry.status):0))),isCritical=entry.directive_priority==="critical"&&(ds.triggerHit||ds.actionHit||ds.agentHit),isForceHive=forceReadHive&&entry.tier==="hive";return{...entry,retrieval_outcomes:retrievalOutcomes,finalScore,coldStartBoost:coldStartBonus,__critical:isCritical,__forceHive:isForceHive}});scored.sort((a,b)=>{let diff=b.finalScore-a.finalScore;if(Math.abs(diff)>0.001)return diff;return new Date(b.created_at).getTime()-new Date(a.created_at).getTime()});let top=[],seen=new Set;for(let e of scored){if(top.length>=max)break;if(e.__critical&&!seen.has(e.id))top.push(e),seen.add(e.id)}for(let e of scored){if(top.length>=max)break;if(e.__forceHive&&!seen.has(e.id))top.push(e),seen.add(e.id)}let lambda=clampLambda(config3.retrieval?.mmr_lambda),remaining=scored.filter((e)=>!seen.has(e.id)),selected=mmrRerank(remaining,top,max,lambda);for(let e of selected){if(top.length>=max)break;if(!seen.has(e.id))top.push(e),seen.add(e.id)}results=top.map(({__critical:_c,__forceHive:_f,...rest})=>rest)}catch(err){warn(`[search-knowledge] retrieval failed: ${err instanceof Error?err.message:String(err)}`),results=[]}if(emitEvent){let ranks={},scores={};results.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore});let synonymBreakdown={};for(let e of results)if(synonymTrace[e.id])synonymBreakdown[e.id]=synonymTrace[e.id];let scoreBreakdown=synonymTokens.length>0?{synonyms_expanded:synonymTokens,synonym_matches:synonymBreakdown}:void 0;await recordKnowledgeEvent(directory,{type:"retrieved",trace_id:traceId,session_id:sessionId,phase:context?.currentPhase,task_id:context?.taskId,agent,query:query??context?.lastUserMessage??context?.currentPhase??"",retrieval_mode:mode,result_ids:results.map((e)=>e.id),ranks,scores,...scoreBreakdown?{score_breakdown:scoreBreakdown}:{}})}return{trace_id:traceId,results}}var TEXT_WEIGHT=0.6,META_WEIGHT=0.4,DIRECTIVE_BOOST_MIN_CONFIDENCE=0.75,SYNONYM_TEXT_BOOST=0.15,TRIGGER_RECALL_BOOST=0.3,TRIGGER_RECALL_MIN_LEN=3,DEFAULT_COLD_START_BONUS=0.08,DEFAULT_COLD_START_MAX_AGE_PHASES=3,OUTCOME_RANK_WEIGHT=0.1;var init_search_knowledge=__esm(()=>{init_schema();init_synonym_map();init_logger();init_knowledge_events();init_knowledge_reader();init_knowledge_store()});var exports_knowledge_recall={};__export(exports_knowledge_recall,{knowledge_recall:()=>knowledge_recall,_internals:()=>_internals86});var knowledge_recall,_internals86;var init_knowledge_recall=__esm(()=>{init_zod();init_config();init_schema();init_search_knowledge();init_knowledge_diagnostics();init_create_tool();knowledge_recall=createSwarmTool({description:"Performs semantic natural-language search across the knowledge base for relevant past decisions, patterns, and lessons learned. Returns ranked results via the unified hybrid retrieval service and a trace_id for knowledge_receipt. This is the tool to use when the user has a QUESTION about what the knowledge base contains. For structured filter-based retrieval (by category, status, or score), use `knowledge_query` instead.",args:{query:exports_external.string().min(3).describe("Natural language search query"),top_n:exports_external.number().int().min(1).max(20).optional().describe("Maximum results to return (default: 5)"),tier:exports_external.enum(["all","swarm","hive"]).optional().describe("Knowledge tier to search (default: 'all')"),debug:exports_external.boolean().optional().describe("Include path/version/health debug metadata in the response")},execute:async(args2,directory,ctx)=>{let queryInput,topNInput,tierInput,debugInput;try{if(args2&&typeof args2==="object"){let obj=args2;queryInput=obj.query,topNInput=obj.top_n,tierInput=obj.tier,debugInput=obj.debug}}catch{}let wantDebug=debugInput===!0;if(typeof queryInput!=="string"||queryInput.length<3)return JSON.stringify({results:[],total:0,error:"query must be a string with at least 3 characters"});let topN=5;if(typeof topNInput==="number"&&Number.isInteger(topNInput))topN=Math.max(1,Math.min(20,topNInput));let tier="all";if(tierInput==="swarm"||tierInput==="hive")tier=tierInput;let knowledgeConfig=KnowledgeConfigSchema.parse({});try{let{config:config3}=loadPluginConfigWithMeta(directory);knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch{}let{trace_id,results}=await searchKnowledge({directory,config:knowledgeConfig,query:queryInput,mode:"manual",agent:ctx?.agent??"unknown",sessionId:ctx?.sessionID??"unknown",tier,maxResults:topN,applyScopeFilter:!1,forceReadHive:!0,applyRoleScope:!1}),scored=results.map((e)=>({id:e.id,confidence:e.confidence,category:e.category,lesson:e.lesson,score:e.finalScore})),result={results:scored,total:scored.length,trace_id};if(wantDebug)result.debug=await computeKnowledgeDebug(directory);return JSON.stringify(result)}}),_internals86={knowledge_recall}});var exports_prompt_renderer={};__export(exports_prompt_renderer,{renderEnvironmentPrompt:()=>renderEnvironmentPrompt});function renderEnvironmentPrompt(profile,audience){let policy=deriveCommandPolicy(profile),header=["RUNTIME ENVIRONMENT",`- Host OS: ${profile.hostOS}`,`- Shell family: ${profile.shellFamily}`,`- Execution mode: ${profile.executionMode}`,`- Path style: ${profile.pathStyle}`].join(`
@@ -5123,7 +5145,7 @@ ${phaseNumber!==null&&phaseNumber>=4?`
5123
5145
 
5124
5146
  ---
5125
5147
 
5126
- ${originalText}`})}}init_constants();import*as path142 from"node:path";init_profiles();import*as fsSync8 from"node:fs";import{existsSync as existsSync77,realpathSync as realpathSync15}from"node:fs";import*as fsPromises5 from"node:fs/promises";import*as os20 from"node:os";import*as path137 from"node:path";var PUBLIC_INFO={exported:!0,visibility:"public",exportedReason:"top_level_public",apiSurfaceKind:"public"},PRIVATE_INFO={exported:!1,visibility:"private",exportedReason:"unknown",apiSurfaceKind:"private"};function collectCommonJsExports(source){let sanitized=maskCommentsAndStrings(source),exportsByLocal=new Map,add2=(localName,exportedName,sourceIndex)=>{if(!isIdentifier(localName)||!isIdentifier(exportedName))return;let existing=exportsByLocal.get(localName);if(existing&&existing.sourceIndex<=sourceIndex)return;exportsByLocal.set(localName,{localName,exportedName,exportedReason:"explicit_export",sourceIndex})};for(let match of sanitized.matchAll(/\bmodule\s*\.\s*exports\s*=\s*([A-Za-z_$][\w$]*)\b/g))add2(match[1],match[1],match.index??0);for(let match of sanitized.matchAll(/\bmodule\s*\.\s*exports\s*=\s*\{([^}]*)\}/g)){let body=match[1],baseIndex=match.index??0;for(let part of body.split(",")){let entry=part.trim();if(!entry)continue;let alias=entry.match(/^([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)$/);if(alias){add2(alias[2],alias[1],baseIndex+match[0].indexOf(part));continue}let shorthand=entry.match(/^([A-Za-z_$][\w$]*)$/);if(shorthand)add2(shorthand[1],shorthand[1],baseIndex+match[0].indexOf(part))}}for(let match of sanitized.matchAll(/\b(?:module\s*\.\s*exports|exports)\s*\.\s*([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\b/g))add2(match[2],match[1],match.index??0);return exportsByLocal}function collectPythonAllNames(source){let match=source.match(/__all__\s*=\s*([[({])([\s\S]*?)[\])}]/);if(!match)return null;let body=match[2].trim();if(!body)return new Set;let names=new Set;for(let part of body.split(",")){let trimmed=part.trim();if(!trimmed)continue;let stringMatch=trimmed.match(/^['"]([^'"]+)['"]$/);if(!stringMatch)return null;names.add(stringMatch[1])}return names}function getSymbolVisibilityInfo(ctx){if(hasPrivateContainer(ctx.defNode))return{...PRIVATE_INFO};if(ctx.explicitExported||ctx.commonJsExport)return{exported:!0,visibility:"public",exportedReason:"explicit_export",apiSurfaceKind:"export"};let ownVisibility=visibilityFromText(ctx.grammarId,ctx.defNode.text);if(ctx.kind==="method")return{exported:!1,visibility:ownVisibility,exportedReason:ownVisibility==="unknown"?"unknown":"modifier",apiSurfaceKind:ownVisibility==="private"?"private":"public"};if(!ctx.isTopLevel&&isMemberLikeNode(ctx.defNode))return{exported:!1,visibility:ownVisibility==="unknown"?"public":ownVisibility,exportedReason:ownVisibility==="unknown"?"module_public":"modifier",apiSurfaceKind:ownVisibility==="private"?"private":"public"};if(!ctx.isTopLevel)return{...PRIVATE_INFO};switch(ctx.grammarId){case"typescript":case"javascript":case"tsx":return{...PRIVATE_INFO};case"python":return pythonVisibility(ctx);case"rust":return rustVisibility(ctx);case"go":return isUppercasePublic(ctx.localName)?{...PUBLIC_INFO,exportedReason:"naming_convention"}:{...PRIVATE_INFO};case"java":case"kotlin":case"csharp":case"swift":case"php":return modifierLanguageVisibility(ctx);case"cpp":return cppVisibility(ctx);case"dart":return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"naming_convention"};case"ruby":return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"module_public"};default:return{exported:!1,visibility:"unknown",exportedReason:"unknown",apiSurfaceKind:"unknown"}}}function pythonVisibility(ctx){if(ctx.pythonAllNames)return ctx.pythonAllNames.has(ctx.localName)?{exported:!0,visibility:"public",exportedReason:"module_public",apiSurfaceKind:"public"}:{...PRIVATE_INFO};return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"naming_convention"}}function rustVisibility(ctx){let text=ctx.defNode.text.trimStart();if(!/^pub\b|^pub\s*\(/.test(text))return{...PRIVATE_INFO};return{exported:!0,visibility:/^pub\s*\(\s*(crate|super|in\b)/.test(text)?"internal":"public",exportedReason:"modifier",apiSurfaceKind:"public"}}function modifierLanguageVisibility(ctx){if(ctx.grammarId==="php"&&ctx.localName.startsWith("_"))return{...PRIVATE_INFO};let visibility=visibilityFromText(ctx.grammarId,ctx.defNode.text);if(visibility==="private")return{...PRIVATE_INFO};if(visibility==="unknown")return{exported:!0,visibility:ctx.grammarId==="java"?"package":defaultModuleVisibility(ctx.grammarId),exportedReason:"module_public",apiSurfaceKind:"public"};return{exported:!0,visibility,exportedReason:"modifier",apiSurfaceKind:"public"}}function cppVisibility(ctx){let text=ctx.defNode.text.trimStart();if(/^static\b/.test(text)||ctx.localName.startsWith("_"))return{...PRIVATE_INFO};return{exported:!0,visibility:"public",exportedReason:"namespace_public",apiSurfaceKind:"public"}}function visibilityFromText(grammarId,text){let normalized=declarationPrefix(text).trimStart();if(/\b(private|fileprivate)\b/.test(normalized))return"private";if(/\bprotected\b/.test(normalized))return"protected";if(/\binternal\b/.test(normalized))return"internal";if(/\b(public|open)\b/.test(normalized))return"public";if(grammarId==="rust"&&/^pub\s*\(\s*(crate|super|in\b)/.test(normalized))return"internal";if(grammarId==="rust"&&/^pub\b|^pub\s*\(/.test(normalized))return"public";return"unknown"}function declarationPrefix(text){let bodyStart=text.search(/[{\n]/);return bodyStart===-1?text:text.slice(0,bodyStart)}function defaultModuleVisibility(grammarId){switch(grammarId){case"kotlin":case"swift":case"csharp":return"internal";case"php":return"public";default:return"public"}}function hasPrivateContainer(node){let current=node.parent;while(current){if(isContainerNode(current)&&visibilityFromText("",current.text)==="private")return!0;current=current.parent}return!1}function isContainerNode(node){return/(?:class|struct|interface|object|protocol|namespace|module)/.test(node.type)}function isMemberLikeNode(node){return/(?:method|function)_declaration|function_definition/.test(node.type)}function isUppercasePublic(name){return/^[A-Z]/.test(name)}function isIdentifier(value){return/^[A-Za-z_$][\w$]*$/.test(value)}function maskCommentsAndStrings(source){let chars=[...source],i=0;while(i<chars.length){let ch=chars[i],next=chars[i+1];if(ch==="/"&&next==="/"){chars[i++]=" ",chars[i++]=" ";while(i<chars.length&&chars[i]!==`
5148
+ ${originalText}`})}}init_constants();import*as path142 from"node:path";init_profiles();import*as fsSync8 from"node:fs";import{existsSync as existsSync77,realpathSync as realpathSync15}from"node:fs";import*as fsPromises5 from"node:fs/promises";import*as os20 from"node:os";import*as path137 from"node:path";var PUBLIC_INFO={exported:!0,visibility:"public",exportedReason:"top_level_public",apiSurfaceKind:"public"},PRIVATE_INFO={exported:!1,visibility:"private",exportedReason:"unknown",apiSurfaceKind:"private"};function collectCommonJsExports(source){let sanitized=maskCommentsAndStrings(source),exportsByLocal=new Map,add2=(localName,exportedName,sourceIndex)=>{if(!isIdentifier(localName)||!isIdentifier(exportedName))return;let existing=exportsByLocal.get(localName);if(existing&&existing.sourceIndex<=sourceIndex)return;exportsByLocal.set(localName,{localName,exportedName,exportedReason:"explicit_export",sourceIndex})};for(let match of sanitized.matchAll(/\bmodule\s*\.\s*exports\s*=\s*([A-Za-z_$][\w$]*)\b/g))add2(match[1],match[1],match.index??0);for(let match of sanitized.matchAll(/\bmodule\s*\.\s*exports\s*=\s*\{([^}]*)\}/g)){let body=match[1],baseIndex=match.index??0;for(let part of body.split(",")){let entry=part.trim();if(!entry)continue;let alias=entry.match(/^([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)$/);if(alias){add2(alias[2],alias[1],baseIndex+match[0].indexOf(part));continue}let shorthand=entry.match(/^([A-Za-z_$][\w$]*)$/);if(shorthand)add2(shorthand[1],shorthand[1],baseIndex+match[0].indexOf(part))}}for(let match of sanitized.matchAll(/\b(?:module\s*\.\s*exports|exports)\s*\.\s*([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\b/g))add2(match[2],match[1],match.index??0);return exportsByLocal}function collectPythonAllNames(source){let match=source.match(/__all__\s*=\s*([[({])([\s\S]*?)[\])}]/);if(!match)return null;let body=match[2].trim();if(!body)return new Set;let names=new Set;for(let part of body.split(",")){let trimmed=part.trim();if(!trimmed)continue;let stringMatch=trimmed.match(/^['"]([^'"]+)['"]$/);if(!stringMatch)return null;names.add(stringMatch[1])}return names}function getSymbolVisibilityInfo(ctx){if(hasPrivateContainer(ctx.defNode))return{...PRIVATE_INFO};if(ctx.explicitExported||ctx.commonJsExport)return{exported:!0,visibility:"public",exportedReason:"explicit_export",apiSurfaceKind:"export"};let ownVisibility=visibilityFromText(ctx.grammarId,ctx.defNode.text);if(ctx.kind==="method"){if(ctx.grammarId==="go")return isUppercasePublic(ctx.localName)?{...PUBLIC_INFO,exportedReason:"naming_convention"}:{...PRIVATE_INFO};if(ctx.grammarId==="python"&&ctx.pythonParentClassExported){let isPrivate=ctx.localName.startsWith("_"),isInit=ctx.localName==="__init__";if(isPrivate||isInit)return{...PRIVATE_INFO};return{exported:!0,visibility:"public",exportedReason:"modifier",apiSurfaceKind:"public"}}return{exported:!1,visibility:ownVisibility,exportedReason:ownVisibility==="unknown"?"unknown":"modifier",apiSurfaceKind:ownVisibility==="private"?"private":"public"}}if(!ctx.isTopLevel&&isMemberLikeNode(ctx.defNode))return{exported:!1,visibility:ownVisibility==="unknown"?"public":ownVisibility,exportedReason:ownVisibility==="unknown"?"module_public":"modifier",apiSurfaceKind:ownVisibility==="private"?"private":"public"};if(!ctx.isTopLevel)return{...PRIVATE_INFO};switch(ctx.grammarId){case"typescript":case"javascript":case"tsx":return{...PRIVATE_INFO};case"python":return pythonVisibility(ctx);case"rust":return rustVisibility(ctx);case"go":return isUppercasePublic(ctx.localName)?{...PUBLIC_INFO,exportedReason:"naming_convention"}:{...PRIVATE_INFO};case"java":case"kotlin":case"csharp":case"swift":case"php":return modifierLanguageVisibility(ctx);case"cpp":return cppVisibility(ctx);case"dart":return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"naming_convention"};case"ruby":return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"module_public"};default:return{exported:!1,visibility:"unknown",exportedReason:"unknown",apiSurfaceKind:"unknown"}}}function pythonVisibility(ctx){if(ctx.pythonAllNames)return ctx.pythonAllNames.has(ctx.localName)?{exported:!0,visibility:"public",exportedReason:"module_public",apiSurfaceKind:"public"}:{...PRIVATE_INFO};return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"naming_convention"}}function rustVisibility(ctx){let text=ctx.defNode.text.trimStart();if(!/^pub\b|^pub\s*\(/.test(text))return{...PRIVATE_INFO};return{exported:!0,visibility:/^pub\s*\(\s*(crate|super|in\b)/.test(text)?"internal":"public",exportedReason:"modifier",apiSurfaceKind:"public"}}function modifierLanguageVisibility(ctx){if(ctx.grammarId==="php"&&ctx.localName.startsWith("_"))return{...PRIVATE_INFO};let visibility=visibilityFromText(ctx.grammarId,ctx.defNode.text);if(visibility==="private")return{...PRIVATE_INFO};if(visibility==="unknown")return{exported:!0,visibility:ctx.grammarId==="java"?"package":defaultModuleVisibility(ctx.grammarId),exportedReason:"module_public",apiSurfaceKind:"public"};return{exported:!0,visibility,exportedReason:"modifier",apiSurfaceKind:"public"}}function cppVisibility(ctx){let text=ctx.defNode.text.trimStart();if(/^static\b/.test(text)||ctx.localName.startsWith("_"))return{...PRIVATE_INFO};return{exported:!0,visibility:"public",exportedReason:"namespace_public",apiSurfaceKind:"public"}}function visibilityFromText(grammarId,text){let normalized=declarationPrefix(text).trimStart();if(/\b(private|fileprivate)\b/.test(normalized))return"private";if(/\bprotected\b/.test(normalized))return"protected";if(/\binternal\b/.test(normalized))return"internal";if(/\b(public|open)\b/.test(normalized))return"public";if(grammarId==="rust"&&/^pub\s*\(\s*(crate|super|in\b)/.test(normalized))return"internal";if(grammarId==="rust"&&/^pub\b|^pub\s*\(/.test(normalized))return"public";return"unknown"}function declarationPrefix(text){let bodyStart=text.search(/[{\n]/);return bodyStart===-1?text:text.slice(0,bodyStart)}function defaultModuleVisibility(grammarId){switch(grammarId){case"kotlin":case"swift":case"csharp":return"internal";case"php":return"public";default:return"public"}}function hasPrivateContainer(node){let current=node.parent;while(current){if(isContainerNode(current)&&visibilityFromText("",current.text)==="private")return!0;current=current.parent}return!1}function isContainerNode(node){return/(?:class|struct|interface|object|protocol|namespace|module)/.test(node.type)}function isMemberLikeNode(node){return/(?:method|function)_declaration|function_definition/.test(node.type)}function isUppercasePublic(name){return/^[A-Z]/.test(name)}function isIdentifier(value){return/^[A-Za-z_$][\w$]*$/.test(value)}function maskCommentsAndStrings(source){let chars=[...source],i=0;while(i<chars.length){let ch=chars[i],next=chars[i+1];if(ch==="/"&&next==="/"){chars[i++]=" ",chars[i++]=" ";while(i<chars.length&&chars[i]!==`
5127
5149
  `)chars[i++]=" ";continue}if(ch==="/"&&next==="*"){chars[i++]=" ",chars[i++]=" ";while(i<chars.length){let end=chars[i]==="*"&&chars[i+1]==="/";if(chars[i++]=" ",end){chars[i++]=" ";break}}continue}if(ch==='"'||ch==="'"||ch==="`"){let quote=ch;chars[i++]=" ";while(i<chars.length){if(chars[i]==="\\"){if(chars[i++]=" ",i<chars.length)chars[i++]=" ";continue}let done=chars[i]===quote;if(chars[i++]=" ",done)break}continue}i++}return chars.join("")}var _QueryCtor=null,AST_TIMEOUT_MS=500,QUERIES={typescript:{defs:`
5128
5150
  (function_declaration name: (identifier) @func.name) @func.def
5129
5151
  (generator_function_declaration name: (identifier) @func.name) @func.def
@@ -5202,14 +5224,25 @@ ${originalText}`})}}init_constants();import*as path142 from"node:path";init_prof
5202
5224
  (struct_item
5203
5225
  name: (type_identifier) @struct.name
5204
5226
  ) @struct.def
5205
- (impl_item type: (type_identifier) @impl.name) @impl.def
5227
+ (enum_item
5228
+ name: (type_identifier) @enum.name
5229
+ ) @enum.def
5230
+ (trait_item
5231
+ name: (type_identifier) @trait.name
5232
+ ) @trait.def
5233
+ (mod_item
5234
+ name: (identifier) @mod.name
5235
+ ) @mod.def
5206
5236
  `,imports:`
5207
5237
  (use_declaration) @import
5208
5238
  `,refs:`
5209
5239
  (identifier) @ref.identifier
5210
5240
  `,exports:""},go:{defs:`
5211
5241
  (function_declaration name: (identifier) @func.name) @func.def
5242
+ (method_declaration name: (field_identifier) @method.name) @method.def
5212
5243
  (type_declaration (type_spec name: (type_identifier) @type.name)) @type.def
5244
+ (var_declaration (var_spec name: (identifier) @const.name)) @const.def
5245
+ (const_declaration (const_spec name: (identifier) @const.name)) @const.def
5213
5246
  `,imports:`
5214
5247
  (import_declaration) @import
5215
5248
  `,refs:`
@@ -5308,15 +5341,17 @@ ${originalText}`})}}init_constants();import*as path142 from"node:path";init_prof
5308
5341
  (namespace_use_declaration) @import
5309
5342
  `,refs:`
5310
5343
  (name) @ref.identifier
5311
- `,exports:""}},CAPTURE_KIND={func:"function",class:"class",const:"const",type:"type",interface:"interface",enum:"enum",method:"method",struct:"type",impl:"type",object:"class",mixin:"type",protocol:"interface"},DEF_TYPES=new Set(["function_declaration","class_declaration","variable_declaration","type_alias_declaration","interface_declaration","enum_declaration","method_definition","function_item","function_signature","class_specifier","struct_specifier","struct_item","struct_declaration","method_declaration","type_declaration","object_declaration","protocol_declaration","mixin_declaration","function_definition","generator_function_declaration","class_definition","lexical_declaration","impl_item","method","class"]),PARAM_TYPES=new Set(["formal_parameters","required_parameter","optional_parameter","rest_parameter","array_pattern","object_pattern"]);async function extractFileSymbols(grammarId,source){let treeRef={value:null},timeoutId;try{return await Promise.race([(async()=>{try{if(!_QueryCtor)_QueryCtor=(await import("web-tree-sitter")).Query;let{loadGrammar:loadGrammarDynamic}=await Promise.resolve().then(() => (init_runtime(),exports_runtime)),parser=await loadGrammarDynamic(grammarId);if(treeRef.value=parser.parse(source),!treeRef.value)return null;let qs=QUERIES[grammarId];if(!qs)return null;return buildFacts(treeRef.value,qs,grammarId)}finally{if(treeRef.value)treeRef.value.delete(),treeRef.value=null}})(),new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error("AST_TIMEOUT")),AST_TIMEOUT_MS)})]).finally(()=>{if(timeoutId)clearTimeout(timeoutId)})}catch{return null}}function asTs(node){return node}function buildFacts(tree,qs,grammarId){let root=asTs(tree.rootNode),lang=tree.language;if(!lang)return{defs:[],imports:[],refs:[]};let defMatches=safeMatches(lang,qs.defs,root),importMatches=safeMatches(lang,qs.imports,root),refMatches=safeMatches(lang,qs.refs,root),exportMatches=safeMatches(lang,qs.exports,root),exportNodes=[];for(let m of exportMatches){let cap=m.captures.find((c)=>c.name==="export");if(cap)exportNodes.push(asTs(cap.node))}let commonJsExports=isEsMGrammar(grammarId)?collectCommonJsExports(root.text):new Map,pythonAllNames=grammarId==="python"?collectPythonAllNames(root.text):null,defs=[],defNodes=[],defNameKeys=new Set;for(let m of defMatches){let defCap=m.captures.find((c)=>c.name.endsWith(".def")),nameCaps=m.captures.filter((c)=>c.name.endsWith(".name"));if(!defCap||nameCaps.length===0)continue;let kindKey=defCap.name.replace(/\.def$/,""),kind=CAPTURE_KIND[kindKey]??"function",originalDefNode=asTs(defCap.node),defNode=originalDefNode,explicitExported=exportNodes.some((en)=>isNodeInside(en,defNode)),isDefaultExport=!1;if(explicitExported&&isEsMGrammar(grammarId))isDefaultExport=exportNodes.some((en)=>isNodeInside(en,defNode)&&isDefaultExportStatement(en));if(grammarId==="dart"&&defNode.type==="function_signature"){let rawBody=defNode.nextSibling;if(rawBody){let bodyNode=asTs(rawBody);if(bodyNode.type==="function_body")defNode=asTs({...defNode,endIndex:bodyNode.endIndex,endPosition:bodyNode.endPosition})}}for(let nc of nameCaps){let nameNode=asTs(nc.node),localName=nameNode.text,commonJsExport=commonJsExports.get(localName),visibilityInfo=getSymbolVisibilityInfo({grammarId,localName,kind,defNode:originalDefNode,rootNode:root,isTopLevel:isTopLevelDef(originalDefNode,root),explicitExported,commonJsExport,pythonAllNames}),exportedName=isDefaultExport?"default":commonJsExport?.exportedName??localName;defs.push({name:exportedName,kind,exported:visibilityInfo.exported,visibilityInfo,startLine:defNode.startPosition.row+1,endLine:defNode.endPosition.row+1}),defNodes.push({node:defNode,name:localName}),defNameKeys.add(nodeKey(nameNode))}}let importsWithIndex=[],addImport=(entry,node)=>{if(!entry)return;importsWithIndex.push({index:node.startIndex,entry:entry.reExport?{...entry,startLine:node.startPosition.row+1,endLine:node.endPosition.row+1}:entry})};for(let m of importMatches){let importCap=m.captures.find((c)=>c.name==="import");if(importCap){let importNode=asTs(importCap.node),rawText=importNode.text.trim();if(grammarId==="go"&&rawText.startsWith("import (")){let specListNode=importNode.children.find((c)=>c!==null&&c.type==="import_spec_list");if(specListNode){for(let spec of asTs(specListNode).children)if(spec&&spec.type==="import_spec"){let parsed=parseGoImport(spec.text.trim());addImport(parsed,asTs(spec))}}}else{let parsed=parseImport(grammarId,rawText);addImport(parsed,importNode)}}if(grammarId==="ruby"){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){let fnText=asTs(reqName.node).text;if(fnText==="require"||fnText==="require_relative"){let callNode=asTs(reqName.node).parent,rawText=callNode?callNode.text:asTs(reqSpec.node).text,parsed=parseRubyRequire(rawText);addImport(parsed,asTs(callNode??reqSpec.node))}}}if(isEsMGrammar(grammarId)){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){if(asTs(reqName.node).text==="require"){let specText=asTs(reqSpec.node).text.replace(/['"]/g,"");addImport({specifier:specText,importType:"commonjs",bindings:[]},asTs(reqName.node))}}}}if(isEsMGrammar(grammarId))for(let exportNode of exportNodes)addImport(parseImport(grammarId,exportNode.text.trim()),exportNode);let imports=importsWithIndex.sort((a,b)=>a.index-b.index).map((item)=>item.entry),topLevelDefs=defNodes.filter((d)=>isTopLevelDef(d.node,root)).map((d)=>({name:d.name,node:d.node})),refs=[];for(let m of refMatches){let cap=m.captures.find((c)=>c.name==="ref.identifier");if(!cap)continue;let refNode=asTs(cap.node);if(defNameKeys.has(nodeKey(refNode)))continue;if(hasAncestorOfType(refNode,"import_statement"))continue;if(isInsideImportStatement(refNode))continue;if(hasAncestorOfType(refNode,PARAM_TYPES))continue;if(refNode.text==="require"&&isInsideRequireCall(refNode))continue;refs.push({identifier:refNode.text,line:refNode.startPosition.row+1,enclosingDecl:findEnclosingDecl(refNode,topLevelDefs)})}return{defs,imports,refs}}function safeMatches(lang,pattern,root){if(!_QueryCtor)return[];try{return new _QueryCtor(lang,pattern).matches(root)}catch{return[]}}function parseEsmImport(text){let t=text.trim(),sideEffect=t.match(/^import\s+['"]([^'"]+)['"]/);if(sideEffect)return{specifier:sideEffect[1],importType:"sideeffect",bindings:[]};let reExportAllAs=t.match(/^export\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(reExportAllAs)return{specifier:reExportAllAs[2],importType:"namespace",bindings:[{imported:"*",local:reExportAllAs[1]}],reExport:!0,exportedBindings:[{imported:"*",exported:reExportAllAs[1]}]};let reExportAll=t.match(/^export\s+\*\s+from\s+['"]([^'"]+)['"]/);if(reExportAll)return{specifier:reExportAll[1],importType:"namespace",bindings:[],reExport:!0};let namedTypeReExport=t.match(/^export\s+type\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(namedTypeReExport)return{specifier:namedTypeReExport[2],importType:"type",bindings:[],reExport:!0};let namedReExport=t.match(/^export\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(namedReExport){let bindings=[],exportedBindings=[];for(let rawPart of namedReExport[1].split(",")){let p=rawPart.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let alias=p.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/),imported=alias?alias[1]:p,exported=alias?alias[2]:p;if(!/^[A-Za-z_$][\w$]*$/.test(imported))continue;if(!/^[A-Za-z_$][\w$]*$/.test(exported))continue;bindings.push({imported,local:exported}),exportedBindings.push({imported,exported})}return{specifier:namedReExport[2],importType:"named",bindings,reExport:!0,exportedBindings}}let isTypeOnlyImport=/^import\s+type\s/.test(t),withoutTypeQualifier=t.replace(/^import\s+type\s+/,"import "),named=withoutTypeQualifier.match(/^import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(named){if(isTypeOnlyImport)return{specifier:named[2],importType:"named",bindings:[]};let bindings=[];for(let part of named[1].split(",")){let p=part.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let stripped=p.replace(/^type\s+/,"");if(!stripped)continue;let alias=stripped.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^[A-Za-z_$][\w$]*$/.test(stripped))bindings.push({imported:stripped,local:stripped})}return{specifier:named[2],importType:"named",bindings}}let combined=withoutTypeQualifier.match(/^import\s+([A-Za-z_$][\w$]*)\s*,\s*\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(combined){if(isTypeOnlyImport)return{specifier:combined[3],importType:"named",bindings:[]};return{specifier:combined[3],importType:"named",bindings:[{imported:"default",local:combined[1]},{imported:"*",local:combined[2]}]}}let combinedNamed=withoutTypeQualifier.match(/^import\s+([A-Za-z_$][\w$]*)\s*,\s*\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(combinedNamed){if(isTypeOnlyImport)return{specifier:combinedNamed[3],importType:"named",bindings:[]};let bindings=[{imported:"default",local:combinedNamed[1]}];for(let part of combinedNamed[2].split(",")){let p=part.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let stripped=p.replace(/^type\s+/,"");if(!stripped)continue;let alias=stripped.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^[A-Za-z_$][\w$]*$/.test(stripped))bindings.push({imported:stripped,local:stripped})}return{specifier:combinedNamed[3],importType:"named",bindings}}let ns=t.match(/^import\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(ns)return{specifier:ns[2],importType:"namespace",bindings:[{imported:"*",local:ns[1]}]};let def=t.match(/^import\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(def)return{specifier:def[2],importType:"default",bindings:[{imported:"default",local:def[1]}]};return null}function parseImport(grammarId,text){switch(grammarId){case"python":return parsePythonImport(text);case"rust":return parseRustUse(text);case"go":return parseGoImport(text);case"java":return parseJavaImport(text);case"kotlin":return parseKotlinImport(text);case"csharp":return parseCSharpUsing(text);case"cpp":return parseCppInclude(text);case"swift":return parseSwiftImport(text);case"dart":return parseDartImport(text);case"ruby":return parseRubyRequire(text);case"php":return parsePhpUse(text);case"typescript":case"tsx":case"javascript":return parseEsmImport(text);default:return null}}function parsePythonImport(text){let t=text.trim(),fullImport=t.match(/^import\s+(.+)$/);if(fullImport){let rest=fullImport[1].trim(),alias=rest.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)return{specifier:alias[1],importType:"named",bindings:[{imported:alias[1],local:alias[2]}]};return{specifier:rest,importType:"namespace",bindings:[]}}let fromImport=t.match(/^from\s+(\S+)\s+import\s+(.+)$/);if(fromImport){let bindings=[];for(let part of fromImport[2].split(",")){let p=part.trim();if(!p)continue;let alias=p.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else bindings.push({imported:p,local:p})}return{specifier:fromImport[1],importType:"named",bindings}}return null}function parseRustUse(text){let t=text.trim(),m=t.match(/^use\s+(.+?)\s*as\s+(\w+)\s*;?\s*$/);if(m)return{specifier:m[1].trim(),importType:"named",bindings:[{imported:m[1].trim(),local:m[2]}]};let simple=t.match(/^use\s+(.+?)\s*;?\s*$/);if(simple)return{specifier:simple[1].trim(),importType:"namespace",bindings:[]};return null}function parseGoImport(text){let t=text.trim();if(t.startsWith("import ("))return null;let bareAliased=t.match(/^(\w+)\s+"([^"]+)"$/);if(bareAliased)return{specifier:bareAliased[2],importType:"named",bindings:[{imported:bareAliased[2],local:bareAliased[1]}]};let aliased=t.match(/^import\s+(\w+)\s+"([^"]+)"/);if(aliased)return{specifier:aliased[2],importType:"named",bindings:[{imported:aliased[2],local:aliased[1]}]};let simple=t.match(/^import\s+"([^"]+)"|^"([^"]+)"$/);if(simple)return{specifier:simple[1]??simple[2],importType:"namespace",bindings:[]};return null}function parseJavaImport(text){let m=text.trim().match(/^import\s+(?:static\s+)?([^;\s]+)\s*;?\s*$/);if(m)return{specifier:m[1],importType:"namespace",bindings:[]};return null}function parseKotlinImport(text){let t=text.trim(),aliased=t.match(/^import\s+([^;\s]+)\s+as\s+(\w+)/);if(aliased)return{specifier:aliased[1],importType:"named",bindings:[{imported:aliased[1],local:aliased[2]}]};let simple=t.match(/^import\s+([^;\s]+)/);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function parseCSharpUsing(text){let m=text.trim().match(/^using\s+(?:static\s+)?([^=;\s]+)\s*(?:=\s*(.+?))?\s*;?\s*$/);if(m){let specifier=m[2]?m[2].trim():m[1].trim();if(m[2])return{specifier,importType:"named",bindings:[{imported:specifier,local:m[1].trim()}]};return{specifier:m[1].trim(),importType:"namespace",bindings:[]}}return null}function parseCppInclude(text){let t=text.trim(),include=t.match(/^#\s*include\s+[<"]([^>"]+)[>"]/);if(include)return{specifier:include[1],importType:"namespace",bindings:[]};let using=t.match(/^using\s+(?:namespace\s+)?(.+?)\s*;?\s*$/);if(using)return{specifier:using[1].trim(),importType:"namespace",bindings:[]};return null}function parseSwiftImport(text){let m=text.trim().match(/^import\s+(?:class\s+)?([^;\s]+)/);if(m)return{specifier:m[1],importType:"namespace",bindings:[]};return null}function parseDartImport(text){let t=text.trim(),m=t.match(/^import\s+['"]([^'"]+)['"]\s+as\s+(\w+)/);if(m)return{specifier:m[1],importType:"named",bindings:[{imported:m[1],local:m[2]}]};let simple=t.match(/^import\s+['"]([^'"]+)['"]/);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function parseRubyRequire(text){let t=text.trim(),stripped=t.replace(/^(?:require(?:_relative)?)\s+['"]?/,"").replace(/['"]$/,"");if(!stripped||stripped===t)return null;let isRelative=stripped.startsWith("./")||stripped.startsWith("../");return{specifier:stripped,importType:isRelative?"default":"namespace",bindings:[]}}function parsePhpUse(text){let t=text.trim(),m=t.match(/^use\s+(?:(?:function|const)\s+)?([^;\s]+)\s+as\s+(\w+)\s*;?\s*$/i);if(m)return{specifier:m[1],importType:"named",bindings:[{imported:m[1],local:m[2]}]};let simple=t.match(/^use\s+(?:(?:function|const)\s+)?([^;\s]+)\s*;?\s*$/i);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function isTopLevelDef(defNode,root){let parent=defNode.parent;while(parent&&parent!==root){if(DEF_TYPES.has(parent.type))return!1;parent=parent.parent}return!0}function findEnclosingDecl(refNode,topLevelDefs){let best=null,bestDist=1/0;for(let def of topLevelDefs)if(isNodeInside(def.node,refNode)){let dist=refNode.startPosition.row-def.node.startPosition.row;if(dist<bestDist)bestDist=dist,best=def}return best?.name??"<module>"}function isNodeInside(outer,inner){return inner.startIndex>=outer.startIndex&&inner.endIndex<=outer.endIndex}function hasAncestorOfType(node,types2){let typeSet=typeof types2==="string"?new Set([types2]):types2,current=node.parent;while(current){if(typeSet.has(current.type))return!0;current=current.parent}return!1}function isInsideRequireCall(node){let current=node.parent;while(current){if(current.type==="call_expression"){let fn2=current.children.find((c)=>c&&c.type==="identifier");if(fn2&&fn2.text==="require")return!0}if(DEF_TYPES.has(current.type))return!1;current=current.parent}return!1}var IMPORT_ANCESTOR_TYPES=new Set(["import_statement","import_from_statement","import_declaration","import_header","use_declaration","using_directive","namespace_use_declaration","library_import"]);function isInsideImportStatement(node){return hasAncestorOfType(node,IMPORT_ANCESTOR_TYPES)}function nodeKey(node){return`${node.startPosition.row},${node.startPosition.column}-${node.endPosition.row},${node.endPosition.column}`}function isDefaultExportStatement(en){if(en.children.some((c)=>c!==null&&c.type==="default"))return!0;return/^export\s+default\b/.test(en.text)}function isEsMGrammar(grammarId){return grammarId==="typescript"||grammarId==="tsx"||grammarId==="javascript"}init_logger();init_path_security();init_zod();init_create_tool();init_path_security();import*as fs77 from"node:fs";import*as path134 from"node:path";var MAX_FILE_SIZE_BYTES2=1048576,MAX_WORKSPACE_RESULTS=50,MAX_WORKSPACE_SCANNED_FILES=200,WORKSPACE_TIMEOUT_MS=1e4,WINDOWS_RESERVED_NAMES2=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i,SYMBOL_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py"]),SKIP_DIRECTORIES=new Set(["node_modules",".git","dist","build","out",".next","coverage","__pycache__"]);function containsWindowsAttacks(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES2.test(part))return!0;return!1}function isPathInWorkspace(filePath,workspace){try{let resolvedPath=path134.resolve(workspace,filePath),realWorkspace=fs77.realpathSync(workspace),realResolvedPath=fs77.realpathSync(resolvedPath),relativePath=path134.relative(realWorkspace,realResolvedPath);if(relativePath.startsWith("..")||path134.isAbsolute(relativePath))return!1;return!0}catch{return!1}}function validatePathForRead(filePath,workspace){return isPathInWorkspace(filePath,workspace)}function extractTSSymbols(filePath,cwd){let fullPath=path134.join(cwd,filePath);if(!validatePathForRead(fullPath,cwd))return[];let content;try{let stats2=fs77.statSync(fullPath);if(stats2.size>MAX_FILE_SIZE_BYTES2)throw Error(`File too large: ${stats2.size} bytes (max: ${MAX_FILE_SIZE_BYTES2})`);content=fs77.readFileSync(fullPath,"utf-8")}catch{return[]}let lines=content.split(`
5344
+ `,exports:""}},CAPTURE_KIND={func:"function",class:"class",const:"const",type:"type",interface:"interface",enum:"enum",method:"method",struct:"type",trait:"interface",mod:"type",object:"class",mixin:"type",protocol:"interface"},DEF_TYPES=new Set(["function_declaration","class_declaration","variable_declaration","type_alias_declaration","interface_declaration","enum_declaration","method_definition","function_item","function_signature","class_specifier","struct_specifier","struct_item","struct_declaration","method_declaration","type_declaration","object_declaration","protocol_declaration","mixin_declaration","function_definition","generator_function_declaration","class_definition","lexical_declaration","impl_item","enum_item","trait_item","mod_item","var_declaration","const_declaration","method","class"]),PARAM_TYPES=new Set(["formal_parameters","required_parameter","optional_parameter","rest_parameter","array_pattern","object_pattern"]);async function extractFileSymbols(grammarId,source){let treeRef={value:null},timeoutId;try{return await Promise.race([(async()=>{try{if(!_QueryCtor)_QueryCtor=(await import("web-tree-sitter")).Query;let{loadGrammar:loadGrammarDynamic}=await Promise.resolve().then(() => (init_runtime(),exports_runtime)),parser=await loadGrammarDynamic(grammarId);if(treeRef.value=parser.parse(source),!treeRef.value)return null;let qs=QUERIES[grammarId];if(!qs)return null;return buildFacts(treeRef.value,qs,grammarId)}finally{if(treeRef.value)treeRef.value.delete(),treeRef.value=null}})(),new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error("AST_TIMEOUT")),AST_TIMEOUT_MS)})]).finally(()=>{if(timeoutId)clearTimeout(timeoutId)})}catch{return null}}function asTs(node){return node}function buildFacts(tree,qs,grammarId){let root=asTs(tree.rootNode),lang=tree.language;if(!lang)return{defs:[],imports:[],refs:[]};let defMatches=safeMatches(lang,qs.defs,root),importMatches=safeMatches(lang,qs.imports,root),refMatches=safeMatches(lang,qs.refs,root),exportMatches=safeMatches(lang,qs.exports,root),exportNodes=[];for(let m of exportMatches){let cap=m.captures.find((c)=>c.name==="export");if(cap)exportNodes.push(asTs(cap.node))}let commonJsExports=isEsMGrammar(grammarId)?collectCommonJsExports(root.text):new Map,pythonAllNames=grammarId==="python"?collectPythonAllNames(root.text):null,defs=[],defNodes=[],defNameKeys=new Set;for(let m of defMatches){let defCap=m.captures.find((c)=>c.name.endsWith(".def")),nameCaps=m.captures.filter((c)=>c.name.endsWith(".name"));if(!defCap||nameCaps.length===0)continue;let kindKey=defCap.name.replace(/\.def$/,""),originalDefNode=asTs(defCap.node),defNode=originalDefNode,kind=CAPTURE_KIND[kindKey]??"function";if(grammarId==="python"&&kindKey==="func"&&hasAncestorOfType(originalDefNode,"class_definition"))kind="method";if(grammarId==="rust"&&kindKey==="func"&&hasAncestorOfType(originalDefNode,"impl_item"))kind="method";let explicitExported=exportNodes.some((en)=>isNodeInside(en,defNode)),isDefaultExport=!1;if(explicitExported&&isEsMGrammar(grammarId))isDefaultExport=exportNodes.some((en)=>isNodeInside(en,defNode)&&isDefaultExportStatement(en));if(grammarId==="dart"&&defNode.type==="function_signature"){let rawBody=defNode.nextSibling;if(rawBody){let bodyNode=asTs(rawBody);if(bodyNode.type==="function_body")defNode=asTs({...defNode,endIndex:bodyNode.endIndex,endPosition:bodyNode.endPosition})}}if(grammarId==="python"&&defNode.parent?.type==="decorated_definition")defNode=asTs(defNode.parent);let pythonParentClassExported=!1;if(grammarId==="python"&&kind==="method"){let current=originalDefNode.parent;while(current){if(current.type==="class_definition"){let classNameNode=current.children?.find((c)=>c!=null&&c.type==="identifier");if(classNameNode){let className=classNameNode.text;pythonParentClassExported=pythonAllNames?pythonAllNames.has(className):!className.startsWith("_")}break}current=current.parent}}for(let nc of nameCaps){let nameNode=asTs(nc.node),localName=nameNode.text,commonJsExport=commonJsExports.get(localName),visibilityInfo=getSymbolVisibilityInfo({grammarId,localName,kind,defNode:originalDefNode,rootNode:root,isTopLevel:isTopLevelDef(originalDefNode,root),explicitExported,commonJsExport,pythonAllNames,pythonParentClassExported}),exportedName=isDefaultExport?"default":commonJsExport?.exportedName??localName;defs.push({name:exportedName,kind,exported:visibilityInfo.exported,visibilityInfo,startLine:defNode.startPosition.row+1,endLine:defNode.endPosition.row+1}),defNodes.push({node:defNode,name:localName}),defNameKeys.add(nodeKey(nameNode))}}let importsWithIndex=[],addImport=(entry,node)=>{if(!entry)return;for(let item of Array.isArray(entry)?entry:[entry]){let pythonExportedBindings=grammarId==="python"&&pythonAllNames&&item.bindings.length>0?item.bindings.filter((binding)=>pythonAllNames.has(binding.local)).map((binding)=>({imported:binding.imported,exported:binding.local})):[],normalizedItem=pythonExportedBindings.length>0?{...item,reExport:!0,exportedBindings:pythonExportedBindings}:item;importsWithIndex.push({index:node.startIndex,entry:normalizedItem.reExport?{...normalizedItem,startLine:node.startPosition.row+1,endLine:node.endPosition.row+1}:normalizedItem})}};for(let m of importMatches){let importCap=m.captures.find((c)=>c.name==="import");if(importCap){let importNode=asTs(importCap.node),rawText=importNode.text.trim();if(grammarId==="go"&&rawText.startsWith("import (")){let seenGoSpecifiers=new Set,specListNode=importNode.children.find((c)=>c!==null&&c.type==="import_spec_list");if(specListNode){for(let spec of asTs(specListNode).children)if(spec&&spec.type==="import_spec"){let parsed=parseGoImportHardened(spec.text.trim());if(parsed)seenGoSpecifiers.add(parsed.specifier);addImport(parsed,asTs(spec))}}for(let parsed of parseGoBlockImports(rawText)){if(seenGoSpecifiers.has(parsed.specifier))continue;addImport(parsed,importNode)}}else{let parsed=parseImport(grammarId,rawText);addImport(parsed,importNode)}}if(grammarId==="ruby"){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){let fnText=asTs(reqName.node).text;if(fnText==="require"||fnText==="require_relative"){let callNode=asTs(reqName.node).parent,rawText=callNode?callNode.text:asTs(reqSpec.node).text,parsed=parseRubyRequire(rawText);addImport(parsed,asTs(callNode??reqSpec.node))}}}if(isEsMGrammar(grammarId)){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){if(asTs(reqName.node).text==="require"){let specText=asTs(reqSpec.node).text.replace(/['"]/g,"");addImport({specifier:specText,importType:"commonjs",bindings:[]},asTs(reqName.node))}}}}if(isEsMGrammar(grammarId))for(let exportNode of exportNodes)addImport(parseImport(grammarId,exportNode.text.trim()),exportNode);let imports=importsWithIndex.sort((a,b)=>a.index-b.index).map((item)=>item.entry),topLevelDefs=defNodes.filter((d)=>isTopLevelDef(d.node,root)).map((d)=>({name:d.name,node:d.node})),refs=[];for(let m of refMatches){let cap=m.captures.find((c)=>c.name==="ref.identifier");if(!cap)continue;let refNode=asTs(cap.node);if(defNameKeys.has(nodeKey(refNode)))continue;if(hasAncestorOfType(refNode,"import_statement"))continue;if(isInsideImportStatement(refNode))continue;if(hasAncestorOfType(refNode,PARAM_TYPES))continue;if(refNode.text==="require"&&isInsideRequireCall(refNode))continue;refs.push({identifier:refNode.text,line:refNode.startPosition.row+1,enclosingDecl:findEnclosingDecl(refNode,topLevelDefs)})}return{defs,imports,refs}}function safeMatches(lang,pattern,root){if(!_QueryCtor)return[];try{return new _QueryCtor(lang,pattern).matches(root)}catch{return[]}}function parseEsmImport(text){let t=text.trim(),sideEffect=t.match(/^import\s+['"]([^'"]+)['"]/);if(sideEffect)return{specifier:sideEffect[1],importType:"sideeffect",bindings:[]};let reExportAllAs=t.match(/^export\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(reExportAllAs)return{specifier:reExportAllAs[2],importType:"namespace",bindings:[{imported:"*",local:reExportAllAs[1]}],reExport:!0,exportedBindings:[{imported:"*",exported:reExportAllAs[1]}]};let reExportAll=t.match(/^export\s+\*\s+from\s+['"]([^'"]+)['"]/);if(reExportAll)return{specifier:reExportAll[1],importType:"namespace",bindings:[],reExport:!0};let namedTypeReExport=t.match(/^export\s+type\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(namedTypeReExport)return{specifier:namedTypeReExport[2],importType:"type",bindings:[],reExport:!0};let namedReExport=t.match(/^export\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(namedReExport){let bindings=[],exportedBindings=[];for(let rawPart of namedReExport[1].split(",")){let p=rawPart.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let alias=p.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/),imported=alias?alias[1]:p,exported=alias?alias[2]:p;if(!/^[A-Za-z_$][\w$]*$/.test(imported))continue;if(!/^[A-Za-z_$][\w$]*$/.test(exported))continue;bindings.push({imported,local:exported}),exportedBindings.push({imported,exported})}return{specifier:namedReExport[2],importType:"named",bindings,reExport:!0,exportedBindings}}let isTypeOnlyImport=/^import\s+type\s/.test(t),withoutTypeQualifier=t.replace(/^import\s+type\s+/,"import "),named=withoutTypeQualifier.match(/^import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(named){if(isTypeOnlyImport)return{specifier:named[2],importType:"named",bindings:[]};let bindings=[];for(let part of named[1].split(",")){let p=part.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let stripped=p.replace(/^type\s+/,"");if(!stripped)continue;let alias=stripped.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^[A-Za-z_$][\w$]*$/.test(stripped))bindings.push({imported:stripped,local:stripped})}return{specifier:named[2],importType:"named",bindings}}let combined=withoutTypeQualifier.match(/^import\s+([A-Za-z_$][\w$]*)\s*,\s*\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(combined){if(isTypeOnlyImport)return{specifier:combined[3],importType:"named",bindings:[]};return{specifier:combined[3],importType:"named",bindings:[{imported:"default",local:combined[1]},{imported:"*",local:combined[2]}]}}let combinedNamed=withoutTypeQualifier.match(/^import\s+([A-Za-z_$][\w$]*)\s*,\s*\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(combinedNamed){if(isTypeOnlyImport)return{specifier:combinedNamed[3],importType:"named",bindings:[]};let bindings=[{imported:"default",local:combinedNamed[1]}];for(let part of combinedNamed[2].split(",")){let p=part.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let stripped=p.replace(/^type\s+/,"");if(!stripped)continue;let alias=stripped.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^[A-Za-z_$][\w$]*$/.test(stripped))bindings.push({imported:stripped,local:stripped})}return{specifier:combinedNamed[3],importType:"named",bindings}}let ns=t.match(/^import\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(ns)return{specifier:ns[2],importType:"namespace",bindings:[{imported:"*",local:ns[1]}]};let def=t.match(/^import\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(def)return{specifier:def[2],importType:"default",bindings:[{imported:"default",local:def[1]}]};return null}function parseImport(grammarId,text){switch(grammarId){case"python":return parsePythonImportHardened(text);case"rust":return parseRustUseHardened(text);case"go":return parseGoImportHardened(text);case"java":return parseJavaImport(text);case"kotlin":return parseKotlinImport(text);case"csharp":return parseCSharpUsing(text);case"cpp":return parseCppInclude(text);case"swift":return parseSwiftImport(text);case"dart":return parseDartImport(text);case"ruby":return parseRubyRequire(text);case"php":return parsePhpUse(text);case"typescript":case"tsx":case"javascript":return parseEsmImport(text);default:return null}}function parsePythonImportHardened(text){let t=text.trim(),fullImport=t.match(/^import\s+(.+)$/);if(fullImport){let entries=[];for(let rawPart of fullImport[1].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^([\w.]+)\s+as\s+(\w+)$/),specifier=alias?alias[1]:part,local=alias?alias[2]:specifier.split(".")[0];if(!specifier||!/^\w+$/.test(local))continue;entries.push({specifier,importType:alias?"named":"namespace",bindings:[{imported:specifier,local}]})}if(entries.length===0)return null;return entries.length===1?entries[0]:entries}let fromImport=t.match(/^from\s+(\S+)\s+import\s+(.+)$/);if(!fromImport)return null;let bindings=[];for(let rawPart of fromImport[2].split(",")){let part=rawPart.trim();if(!part)continue;if(part==="*")return{specifier:normalizePythonModuleSpecifier(fromImport[1]),importType:"namespace",bindings:[]};let alias=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^\w+$/.test(part))bindings.push({imported:part,local:part})}return{specifier:normalizePythonModuleSpecifier(fromImport[1]),importType:"named",bindings}}function normalizePythonModuleSpecifier(specifier){let leadingDots=specifier.match(/^\.+/)?.[0].length??0;if(leadingDots===0)return specifier;let rest=specifier.slice(leadingDots).replace(/\./g,"/");return`${leadingDots===1?"./":"../".repeat(leadingDots-1)}${rest}`}function parseRustUseHardened(text){let t=text.trim(),aliased=t.match(/^use\s+(.+?)\s+as\s+(\w+)\s*;?\s*$/);if(aliased){let parts2=aliased[1].trim().split("::").filter(Boolean),imported2=parts2.pop()??aliased[1].trim();return{specifier:parts2.length>0?parts2.join("::"):aliased[1].trim(),importType:"named",bindings:[{imported:imported2,local:aliased[2]}]}}let grouped=t.match(/^use\s+(.+?)::\{(.+)\}\s*;?\s*$/);if(grouped){let base=grouped[1].trim(),bindings=[];for(let rawPart of grouped[2].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^\w+$/.test(part)){let local2=part==="self"?base.split("::").pop()||base:part;bindings.push({imported:part,local:local2})}}return{specifier:base,importType:"named",bindings}}let simple=t.match(/^use\s+(.+?)\s*;?\s*$/);if(!simple)return null;let parts=simple[1].trim().split("::").filter(Boolean),imported=parts.pop()??simple[1].trim(),specifier=parts.length>0?parts.join("::"):simple[1].trim(),local=imported;return{specifier,importType:"named",bindings:/^\w+$/.test(imported)?[{imported,local}]:[]}}function parseGoBlockImports(text){let entries=[],body=text.match(/^import\s*\(([\s\S]*?)\)\s*$/)?.[1];if(!body)return entries;for(let line of body.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("//"))continue;let parsed=parseGoImportHardened(trimmed);if(parsed)entries.push(parsed)}return entries}function parseGoImportHardened(text){let t=text.trim();if(t.startsWith("import ("))return null;let aliased=t.match(/^([\w._]+)\s+["`]([^"`]+)["`]$/)??t.match(/^import\s+([\w._]+)\s+["`]([^"`]+)["`]/);if(aliased){if(aliased[1]==="_")return{specifier:aliased[2],importType:"sideeffect",bindings:[]};if(aliased[1]===".")return{specifier:aliased[2],importType:"namespace",bindings:[{imported:"*",local:"."}]};return{specifier:aliased[2],importType:"named",bindings:[{imported:aliased[2],local:aliased[1]}]}}let simple=t.match(/^import\s+["`]([^"`]+)["`]|^["`]([^"`]+)["`]$/);if(!simple)return null;return{specifier:simple[1]??simple[2],importType:"namespace",bindings:[]}}function parseJavaImport(text){let m=text.trim().match(/^import\s+(?:static\s+)?([^;\s]+)\s*;?\s*$/);if(m)return{specifier:m[1],importType:"namespace",bindings:[]};return null}function parseKotlinImport(text){let t=text.trim(),aliased=t.match(/^import\s+([^;\s]+)\s+as\s+(\w+)/);if(aliased)return{specifier:aliased[1],importType:"named",bindings:[{imported:aliased[1],local:aliased[2]}]};let simple=t.match(/^import\s+([^;\s]+)/);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function parseCSharpUsing(text){let m=text.trim().match(/^using\s+(?:static\s+)?([^=;\s]+)\s*(?:=\s*(.+?))?\s*;?\s*$/);if(m){let specifier=m[2]?m[2].trim():m[1].trim();if(m[2])return{specifier,importType:"named",bindings:[{imported:specifier,local:m[1].trim()}]};return{specifier:m[1].trim(),importType:"namespace",bindings:[]}}return null}function parseCppInclude(text){let t=text.trim(),include=t.match(/^#\s*include\s+[<"]([^>"]+)[>"]/);if(include)return{specifier:include[1],importType:"namespace",bindings:[]};let using=t.match(/^using\s+(?:namespace\s+)?(.+?)\s*;?\s*$/);if(using)return{specifier:using[1].trim(),importType:"namespace",bindings:[]};return null}function parseSwiftImport(text){let m=text.trim().match(/^import\s+(?:class\s+)?([^;\s]+)/);if(m)return{specifier:m[1],importType:"namespace",bindings:[]};return null}function parseDartImport(text){let t=text.trim(),m=t.match(/^import\s+['"]([^'"]+)['"]\s+as\s+(\w+)/);if(m)return{specifier:m[1],importType:"named",bindings:[{imported:m[1],local:m[2]}]};let simple=t.match(/^import\s+['"]([^'"]+)['"]/);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function parseRubyRequire(text){let t=text.trim(),stripped=t.replace(/^(?:require(?:_relative)?)\s+['"]?/,"").replace(/['"]$/,"");if(!stripped||stripped===t)return null;let isRelative=stripped.startsWith("./")||stripped.startsWith("../");return{specifier:stripped,importType:isRelative?"default":"namespace",bindings:[]}}function parsePhpUse(text){let t=text.trim(),m=t.match(/^use\s+(?:(?:function|const)\s+)?([^;\s]+)\s+as\s+(\w+)\s*;?\s*$/i);if(m)return{specifier:m[1],importType:"named",bindings:[{imported:m[1],local:m[2]}]};let simple=t.match(/^use\s+(?:(?:function|const)\s+)?([^;\s]+)\s*;?\s*$/i);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function isTopLevelDef(defNode,root){let parent=defNode.parent;while(parent&&parent!==root){if(DEF_TYPES.has(parent.type))return!1;parent=parent.parent}return!0}function findEnclosingDecl(refNode,topLevelDefs){let best=null,bestDist=1/0;for(let def of topLevelDefs)if(isNodeInside(def.node,refNode)){let dist=refNode.startPosition.row-def.node.startPosition.row;if(dist<bestDist)bestDist=dist,best=def}return best?.name??"<module>"}function isNodeInside(outer,inner){return inner.startIndex>=outer.startIndex&&inner.endIndex<=outer.endIndex}function hasAncestorOfType(node,types2){let typeSet=typeof types2==="string"?new Set([types2]):types2,current=node.parent;while(current){if(typeSet.has(current.type))return!0;current=current.parent}return!1}function isInsideRequireCall(node){let current=node.parent;while(current){if(current.type==="call_expression"){let fn2=current.children.find((c)=>c&&c.type==="identifier");if(fn2&&fn2.text==="require")return!0}if(DEF_TYPES.has(current.type))return!1;current=current.parent}return!1}var IMPORT_ANCESTOR_TYPES=new Set(["import_statement","import_from_statement","import_declaration","import_header","use_declaration","using_directive","namespace_use_declaration","library_import"]);function isInsideImportStatement(node){return hasAncestorOfType(node,IMPORT_ANCESTOR_TYPES)}function nodeKey(node){return`${node.startPosition.row},${node.startPosition.column}-${node.endPosition.row},${node.endPosition.column}`}function isDefaultExportStatement(en){if(en.children.some((c)=>c!==null&&c.type==="default"))return!0;return/^export\s+default\b/.test(en.text)}function isEsMGrammar(grammarId){return grammarId==="typescript"||grammarId==="tsx"||grammarId==="javascript"}init_logger();init_path_security();init_zod();import*as fs77 from"node:fs";import*as path134 from"node:path";init_create_tool();init_path_security();var MAX_FILE_SIZE_BYTES2=1048576,MAX_WORKSPACE_RESULTS=50,MAX_WORKSPACE_SCANNED_FILES=200,WORKSPACE_TIMEOUT_MS=1e4,WINDOWS_RESERVED_NAMES2=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i,SYMBOL_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".rs",".go"]),SKIP_DIRECTORIES=new Set(["node_modules",".git","dist","build","out",".next","coverage","__pycache__"]);function containsWindowsAttacks(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES2.test(part))return!0;return!1}function isPathInWorkspace(filePath,workspace){try{let resolvedPath=path134.resolve(workspace,filePath),realWorkspace=fs77.realpathSync(workspace),realResolvedPath=fs77.realpathSync(resolvedPath),relativePath=path134.relative(realWorkspace,realResolvedPath);if(relativePath.startsWith("..")||path134.isAbsolute(relativePath))return!1;return!0}catch{return!1}}function validatePathForRead(filePath,workspace){return isPathInWorkspace(filePath,workspace)}function readValidatedSourceFile(filePath,cwd){let fullPath=path134.join(cwd,filePath);if(!validatePathForRead(fullPath,cwd))return null;try{if(fs77.statSync(fullPath).size>MAX_FILE_SIZE_BYTES2)return null;return fs77.readFileSync(fullPath,"utf-8")}catch{return null}}function extractTSSymbols(filePath,cwd){let fullPath=path134.join(cwd,filePath);if(!validatePathForRead(fullPath,cwd))return[];let content;try{let stats2=fs77.statSync(fullPath);if(stats2.size>MAX_FILE_SIZE_BYTES2)throw Error(`File too large: ${stats2.size} bytes (max: ${MAX_FILE_SIZE_BYTES2})`);content=fs77.readFileSync(fullPath,"utf-8")}catch{return[]}let lines=content.split(`
5312
5345
  `),symbols=[];for(let i=0;i<lines.length;i++){let line=lines[i],lineNum=i+1,jsdoc;if(i>0&&lines[i-1].trim().endsWith("*/")){let jsdocLines=[];for(let j=i-1;j>=0;j--)if(jsdocLines.unshift(lines[j]),lines[j].trim().startsWith("/**"))break;if(jsdoc=jsdocLines.join(`
5313
- `).trim(),jsdoc.length>300)jsdoc=`${jsdoc.substring(0,300)}...`}let fnMatch=line.match(/^export\s+(?:async\s+)?function\s+(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)(?:\s*:\s*(.+?))?(?:\s*\{|$)/);if(fnMatch){symbols.push({name:fnMatch[1],kind:"function",exported:!0,signature:`function ${fnMatch[1]}${fnMatch[2]||""}(${fnMatch[3].trim()})${fnMatch[4]?`: ${fnMatch[4].trim()}`:""}`,line:lineNum,jsdoc});continue}let constMatch=line.match(/^export\s+const\s+(\w+)(?:\s*:\s*(.+?))?\s*=/);if(constMatch){let restOfLine=line.substring(line.indexOf("=")+1).trim(),isArrow=restOfLine.startsWith("(")||restOfLine.startsWith("async (")||restOfLine.match(/^\w+\s*=>/);symbols.push({name:constMatch[1],kind:isArrow?"function":"const",exported:!0,signature:`const ${constMatch[1]}${constMatch[2]?`: ${constMatch[2].trim()}`:""}`,line:lineNum,jsdoc});continue}let classMatch=line.match(/^export\s+(?:abstract\s+)?class\s+(\w+)(?:\s+(?:extends|implements)\s+(.+?))?(?:\s*\{|$)/);if(classMatch){symbols.push({name:classMatch[1],kind:"class",exported:!0,signature:`class ${classMatch[1]}${classMatch[2]?` extends/implements ${classMatch[2].trim()}`:""}`,line:lineNum,jsdoc});let braceDepth=(line.match(/\{/g)||[]).length-(line.match(/\}/g)||[]).length;for(let j=i+1;j<lines.length&&braceDepth>0;j++){let memberLine=lines[j];braceDepth+=(memberLine.match(/\{/g)||[]).length-(memberLine.match(/\}/g)||[]).length;let methodMatch=memberLine.match(/^\s+(?:public\s+)?(?:async\s+)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*(.+?))?(?:\s*\{|;|$)/);if(methodMatch&&!memberLine.includes("private")&&!memberLine.includes("protected")&&!memberLine.trim().startsWith("//"))symbols.push({name:`${classMatch[1]}.${methodMatch[1]}`,kind:"method",exported:!0,signature:`${methodMatch[1]}(${methodMatch[2].trim()})${methodMatch[3]?`: ${methodMatch[3].trim()}`:""}`,line:j+1});let propMatch=memberLine.match(/^\s+(?:public\s+)?(?:readonly\s+)?(\w+)(?:\?)?:\s*(.+?)(?:\s*[;=]|$)/);if(propMatch&&!memberLine.includes("private")&&!memberLine.includes("protected")&&!memberLine.trim().startsWith("//"))symbols.push({name:`${classMatch[1]}.${propMatch[1]}`,kind:"property",exported:!0,signature:`${propMatch[1]}: ${propMatch[2].trim()}`,line:j+1})}continue}let ifaceMatch=line.match(/^export\s+interface\s+(\w+)(?:\s*<([^>]+)>)?(?:\s+extends\s+(.+?))?(?:\s*\{|$)/);if(ifaceMatch){symbols.push({name:ifaceMatch[1],kind:"interface",exported:!0,signature:`interface ${ifaceMatch[1]}${ifaceMatch[2]?`<${ifaceMatch[2]}>`:""}${ifaceMatch[3]?` extends ${ifaceMatch[3].trim()}`:""}`,line:lineNum,jsdoc});continue}let typeMatch=line.match(/^export\s+type\s+(\w+)(?:\s*<([^>]+)>)?\s*=/);if(typeMatch){let typeValue=line.substring(line.indexOf("=")+1).trim().substring(0,100);symbols.push({name:typeMatch[1],kind:"type",exported:!0,signature:`type ${typeMatch[1]}${typeMatch[2]?`<${typeMatch[2]}>`:""} = ${typeValue}`,line:lineNum,jsdoc});continue}let enumMatch=line.match(/^export\s+(?:const\s+)?enum\s+(\w+)/);if(enumMatch){symbols.push({name:enumMatch[1],kind:"enum",exported:!0,signature:`enum ${enumMatch[1]}`,line:lineNum,jsdoc});continue}let defaultMatch=line.match(/^export\s+default\s+(?:function\s+)?(\w+)/);if(defaultMatch)symbols.push({name:defaultMatch[1],kind:"function",exported:!0,signature:`default ${defaultMatch[1]}`,line:lineNum,jsdoc})}return symbols.sort((a,b)=>{if(a.line!==b.line)return a.line-b.line;return a.name.localeCompare(b.name)})}function extractPythonSymbols(filePath,cwd){let fullPath=path134.join(cwd,filePath);if(!validatePathForRead(fullPath,cwd))return[];let content;try{let stats2=fs77.statSync(fullPath);if(stats2.size>MAX_FILE_SIZE_BYTES2)throw Error(`File too large: ${stats2.size} bytes (max: ${MAX_FILE_SIZE_BYTES2})`);content=fs77.readFileSync(fullPath,"utf-8")}catch{return[]}let lines=content.split(`
5314
- `),symbols=[],allMatch=content.match(/__all__\s*=\s*\[([^\]]+)\]/),explicitExports=allMatch?allMatch[1].split(",").map((s)=>s.trim().replace(/['"]/g,"")):null;for(let i=0;i<lines.length;i++){let line=lines[i];if(line.startsWith(" ")||line.startsWith("\t"))continue;let fnMatch=line.match(/^(?:async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*(.+?))?:/);if(fnMatch&&!fnMatch[1].startsWith("_")){let exported=!explicitExports||explicitExports.includes(fnMatch[1]);symbols.push({name:fnMatch[1],kind:"function",exported,signature:`def ${fnMatch[1]}(${fnMatch[2].trim()})${fnMatch[3]?` -> ${fnMatch[3].trim()}`:""}`,line:i+1})}let classMatch=line.match(/^class\s+(\w+)(?:\(([^)]*)\))?:/);if(classMatch&&!classMatch[1].startsWith("_")){let exported=!explicitExports||explicitExports.includes(classMatch[1]);symbols.push({name:classMatch[1],kind:"class",exported,signature:`class ${classMatch[1]}${classMatch[2]?`(${classMatch[2].trim()})`:""}`,line:i+1})}let constMatch=line.match(/^([A-Z][A-Z0-9_]+)\s*[:=]/);if(constMatch)symbols.push({name:constMatch[1],kind:"const",exported:!0,signature:line.trim().substring(0,100),line:i+1})}return symbols.sort((a,b)=>{if(a.line!==b.line)return a.line-b.line;return a.name.localeCompare(b.name)})}function findSourceFiles(cwd,maxFiles){let files=[];return walkDir(cwd,cwd,files,maxFiles),files}function walkDir(currentDir,rootDir,files,maxFiles){let entries;try{entries=fs77.readdirSync(currentDir,{withFileTypes:!0})}catch{return}entries.sort((a,b)=>a.name.toLowerCase().localeCompare(b.name.toLowerCase()));for(let entry of entries){if(files.length>=maxFiles)return;if(SKIP_DIRECTORIES.has(entry.name))continue;let fullPath=path134.join(currentDir,entry.name);if(entry.isDirectory())walkDir(fullPath,rootDir,files,maxFiles);else if(entry.isFile()&&SYMBOL_EXTENSIONS.has(path134.extname(entry.name).toLowerCase()))files.push(path134.relative(rootDir,fullPath))}}function searchWorkspaceSymbols(cwd,name,exportedOnly=!0){let startTime=Date.now(),sourceFiles=findSourceFiles(cwd,MAX_WORKSPACE_SCANNED_FILES),files=[],scannedCount=0,truncated=!1;if(sourceFiles.length>=MAX_WORKSPACE_SCANNED_FILES)truncated=!0;let totalSymbols=0;for(let relFile of sourceFiles){if(Date.now()-startTime>WORKSPACE_TIMEOUT_MS){truncated=!0;break}scannedCount++;let syms;switch(path134.extname(relFile).toLowerCase()){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(relFile,cwd);break;case".py":syms=extractPythonSymbols(relFile,cwd);break;default:continue}if(exportedOnly)syms=syms.filter((s)=>s.exported);if(name)syms=syms.filter((s)=>s.name.includes(name));if(syms.length>0){let remaining=MAX_WORKSPACE_RESULTS-totalSymbols;if(remaining<=0){truncated=!0;break}let cappedSyms=syms.slice(0,remaining);if(files.push({file:relFile,symbolCount:cappedSyms.length,symbols:cappedSyms}),totalSymbols+=cappedSyms.length,totalSymbols>=MAX_WORKSPACE_RESULTS){truncated=syms.length>remaining||scannedCount<sourceFiles.length;break}}}return{query:{workspace:!0,name},fileCount:files.length,scannedFileCount:scannedCount,totalSymbols,files,truncated}}var symbols=createSwarmTool({description:"Extract all exported symbols from a source file: functions with signatures, classes with public members, interfaces, types, enums, constants. Supports TypeScript/JavaScript and Python. Use for architect planning, designer scaffolding, and understanding module public API surface.",args:{file:exports_external.string().optional().describe('File path to extract symbols from (e.g., "src/auth/login.ts"). Required when not using workspace mode.'),exported_only:exports_external.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols."),workspace:exports_external.boolean().optional().describe("When true, search across the workspace instead of a single file. Returns per-file symbol summaries."),name:exports_external.string().optional().describe("Search for symbols by name (case-sensitive substring match). When provided without workspace, only searches the specified file.")},execute:async(args2,directory)=>{let file3,exportedOnly=!0,workspace=!1,name;try{let obj=args2;file3=obj.file!=null&&typeof obj.file==="string"?obj.file:void 0,exportedOnly=obj.exported_only===!0,workspace=obj.workspace===!0,name=obj.name!=null&&typeof obj.name==="string"?obj.name:void 0}catch{return JSON.stringify({file:"<unknown>",error:"Invalid arguments: could not extract parameters",symbols:[]},null,2)}let cwd=directory;if(workspace)return JSON.stringify(searchWorkspaceSymbols(cwd,name,exportedOnly),null,2);if(!file3)return JSON.stringify({error:"file parameter is required when not using workspace mode",symbols:[]},null,2);if(containsControlChars(file3))return JSON.stringify({file:file3,error:"Path contains invalid control characters",symbols:[]},null,2);if(containsPathTraversal(file3))return JSON.stringify({file:file3,error:"Path contains path traversal sequence",symbols:[]},null,2);if(containsWindowsAttacks(file3))return JSON.stringify({file:file3,error:"Path contains invalid Windows-specific sequence",symbols:[]},null,2);if(!isPathInWorkspace(file3,cwd))return JSON.stringify({file:file3,error:"Path is outside workspace",symbols:[]},null,2);let ext=path134.extname(file3),syms;switch(ext){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(file3,cwd);break;case".py":syms=extractPythonSymbols(file3,cwd);break;default:return JSON.stringify({file:file3,error:`Unsupported file extension: ${ext}. Supported: .ts, .tsx, .js, .jsx, .mjs, .cjs, .py`,symbols:[]},null,2)}if(exportedOnly)syms=syms.filter((s)=>s.exported);if(name)syms=syms.filter((s)=>s.name.includes(name));return JSON.stringify({file:file3,symbolCount:syms.length,symbols:syms},null,2)}});import*as path135 from"node:path";var HTTP_METHODS=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"],MAX_FACTS_PER_KIND=50;function stripComments(content){let out="",i=0,state="code";while(i<content.length){let ch=content[i],next=i+1<content.length?content[i+1]:"";switch(state){case"code":if(ch==="/"&&next==="/")state="line",i+=2;else if(ch==="/"&&next==="*")state="block",i+=2;else{if(ch==="'")state="single";else if(ch==='"')state="double";else if(ch==="`")state="template";out+=ch,i++}break;case"single":case"double":case"template":{let quote=state==="single"?"'":state==="double"?'"':"`";if(ch==="\\")out+=ch+next,i+=2;else{if(ch===quote)state="code";out+=ch,i++}break}case"line":if(ch===`
5346
+ `).trim(),jsdoc.length>300)jsdoc=`${jsdoc.substring(0,300)}...`}let fnMatch=line.match(/^export\s+(?:async\s+)?function\s+(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)(?:\s*:\s*(.+?))?(?:\s*\{|$)/);if(fnMatch){symbols.push({name:fnMatch[1],kind:"function",exported:!0,signature:`function ${fnMatch[1]}${fnMatch[2]||""}(${fnMatch[3].trim()})${fnMatch[4]?`: ${fnMatch[4].trim()}`:""}`,line:lineNum,jsdoc});continue}let constMatch=line.match(/^export\s+const\s+(\w+)(?:\s*:\s*(.+?))?\s*=/);if(constMatch){let restOfLine=line.substring(line.indexOf("=")+1).trim(),isArrow=restOfLine.startsWith("(")||restOfLine.startsWith("async (")||restOfLine.match(/^\w+\s*=>/);symbols.push({name:constMatch[1],kind:isArrow?"function":"const",exported:!0,signature:`const ${constMatch[1]}${constMatch[2]?`: ${constMatch[2].trim()}`:""}`,line:lineNum,jsdoc});continue}let classMatch=line.match(/^export\s+(?:abstract\s+)?class\s+(\w+)(?:\s+(?:extends|implements)\s+(.+?))?(?:\s*\{|$)/);if(classMatch){symbols.push({name:classMatch[1],kind:"class",exported:!0,signature:`class ${classMatch[1]}${classMatch[2]?` extends/implements ${classMatch[2].trim()}`:""}`,line:lineNum,jsdoc});let braceDepth=(line.match(/\{/g)||[]).length-(line.match(/\}/g)||[]).length;for(let j=i+1;j<lines.length&&braceDepth>0;j++){let memberLine=lines[j];braceDepth+=(memberLine.match(/\{/g)||[]).length-(memberLine.match(/\}/g)||[]).length;let methodMatch=memberLine.match(/^\s+(?:public\s+)?(?:async\s+)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*(.+?))?(?:\s*\{|;|$)/);if(methodMatch&&!memberLine.includes("private")&&!memberLine.includes("protected")&&!memberLine.trim().startsWith("//"))symbols.push({name:`${classMatch[1]}.${methodMatch[1]}`,kind:"method",exported:!0,signature:`${methodMatch[1]}(${methodMatch[2].trim()})${methodMatch[3]?`: ${methodMatch[3].trim()}`:""}`,line:j+1});let propMatch=memberLine.match(/^\s+(?:public\s+)?(?:readonly\s+)?(\w+)(?:\?)?:\s*(.+?)(?:\s*[;=]|$)/);if(propMatch&&!memberLine.includes("private")&&!memberLine.includes("protected")&&!memberLine.trim().startsWith("//"))symbols.push({name:`${classMatch[1]}.${propMatch[1]}`,kind:"property",exported:!0,signature:`${propMatch[1]}: ${propMatch[2].trim()}`,line:j+1})}continue}let ifaceMatch=line.match(/^export\s+interface\s+(\w+)(?:\s*<([^>]+)>)?(?:\s+extends\s+(.+?))?(?:\s*\{|$)/);if(ifaceMatch){symbols.push({name:ifaceMatch[1],kind:"interface",exported:!0,signature:`interface ${ifaceMatch[1]}${ifaceMatch[2]?`<${ifaceMatch[2]}>`:""}${ifaceMatch[3]?` extends ${ifaceMatch[3].trim()}`:""}`,line:lineNum,jsdoc});continue}let typeMatch=line.match(/^export\s+type\s+(\w+)(?:\s*<([^>]+)>)?\s*=/);if(typeMatch){let typeValue=line.substring(line.indexOf("=")+1).trim().substring(0,100);symbols.push({name:typeMatch[1],kind:"type",exported:!0,signature:`type ${typeMatch[1]}${typeMatch[2]?`<${typeMatch[2]}>`:""} = ${typeValue}`,line:lineNum,jsdoc});continue}let enumMatch=line.match(/^export\s+(?:const\s+)?enum\s+(\w+)/);if(enumMatch){symbols.push({name:enumMatch[1],kind:"enum",exported:!0,signature:`enum ${enumMatch[1]}`,line:lineNum,jsdoc});continue}let defaultMatch=line.match(/^export\s+default\s+(?:function\s+)?(\w+)/);if(defaultMatch)symbols.push({name:defaultMatch[1],kind:"function",exported:!0,signature:`default ${defaultMatch[1]}`,line:lineNum,jsdoc})}return symbols.sort((a,b)=>{if(a.line!==b.line)return a.line-b.line;return a.name.localeCompare(b.name)})}function extractPythonSymbols(filePath,cwd){let content=readValidatedSourceFile(filePath,cwd);if(content===null)return[];let lines=content.split(`
5347
+ `),symbols=[],explicitExports=collectPythonAllNames(content),isExplicitlyExported=(name)=>explicitExports?explicitExports.has(name):!name.startsWith("_"),isPackageInit=["__init__.py","__init__.pyw"].includes(path134.basename(filePath)),seenNames=new Set,currentClass=null,addSymbol=(symbol3)=>{if(seenNames.has(symbol3.name))return;seenNames.add(symbol3.name),symbols.push(symbol3)};for(let i=0;i<lines.length;i++){let line=lines[i],indent=line.match(/^\s*/)?.[0].length??0;if(indent===0)currentClass=null;if(currentClass&&indent>currentClass.indent){let methodMatch=line.trim().match(/^(?:async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*(.+?))?:/);if(methodMatch){let name=`${currentClass.name}.${methodMatch[1]}`;addSymbol({name,kind:"method",exported:currentClass.exported&&!methodMatch[1].startsWith("_")&&methodMatch[1]!=="__init__",signature:`def ${methodMatch[1]}(${methodMatch[2].trim()})${methodMatch[3]?` -> ${methodMatch[3].trim()}`:""}`,line:i+1});continue}}if(line.startsWith(" ")||line.startsWith("\t"))continue;let fnMatch=line.match(/^(?:async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*(.+?))?:/);if(fnMatch){let exported=isExplicitlyExported(fnMatch[1]);addSymbol({name:fnMatch[1],kind:"function",exported,signature:`def ${fnMatch[1]}(${fnMatch[2].trim()})${fnMatch[3]?` -> ${fnMatch[3].trim()}`:""}`,line:i+1})}let classMatch=line.match(/^class\s+(\w+)(?:\(([^)]*)\))?:/);if(classMatch){let exported=isExplicitlyExported(classMatch[1]);currentClass={name:classMatch[1],exported,indent},addSymbol({name:classMatch[1],kind:"class",exported,signature:`class ${classMatch[1]}${classMatch[2]?`(${classMatch[2].trim()})`:""}`,line:i+1})}let constMatch=line.match(/^([A-Z][A-Z0-9_]+)\s*[:=]/);if(constMatch)addSymbol({name:constMatch[1],kind:"const",exported:isExplicitlyExported(constMatch[1]),signature:line.trim().substring(0,100),line:i+1});let importMatch=line.match(/^from\s+[\w.]+\s+import\s+(.+?)(?:\s*#.*)?$/);if(importMatch&&(isPackageInit||explicitExports))for(let rawPart of importMatch[1].split(",")){let part=rawPart.trim();if(!part||part==="*")continue;let alias=part.match(/^(\w+)\s+as\s+(\w+)$/),importedName=alias?alias[1]:part,localName=alias?alias[2]:part;if(!/^\w+$/.test(importedName)||!/^\w+$/.test(localName))continue;let exported=isExplicitlyExported(localName);if(!exported&&explicitExports)continue;addSymbol({name:localName,kind:"variable",exported,signature:line.trim().substring(0,100),line:i+1})}}return symbols.sort((a,b)=>{if(a.line!==b.line)return a.line-b.line;return a.name.localeCompare(b.name)})}function extractRustSymbols(filePath,cwd){let content=readValidatedSourceFile(filePath,cwd);if(content===null)return[];let symbols=[],lines=content.split(`
5348
+ `),implDepth=0,braceDelta=(text)=>(text.match(/{/g)?.length??0)-(text.match(/}/g)?.length??0);for(let i=0;i<lines.length;i++){let line=lines[i],trimmed=line.trim(),inImpl=implDepth>0;if(!inImpl&&/^impl\b/.test(trimmed)){implDepth=Math.max(0,implDepth+braceDelta(trimmed));continue}if(inImpl){let method=trimmed.match(/^(pub(?:\s*\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)/);if(method){let modifier2=method[1]??"";symbols.push({name:method[2],kind:"method",exported:modifier2.trim().startsWith("pub"),signature:trimmed.substring(0,100),line:i+1})}implDepth=Math.max(0,implDepth+braceDelta(trimmed));continue}if(/^\s/.test(line))continue;let item=trimmed.match(/^(pub(?:\s*\([^)]*\))?\s+)?(?:async\s+)?(fn|struct|enum|trait|mod)\s+([A-Za-z_][A-Za-z0-9_]*)/);if(!item)continue;let exported=(item[1]??"").trim().startsWith("pub"),kindMap={fn:"function",struct:"type",enum:"enum",trait:"interface",mod:"type"};symbols.push({name:item[3],kind:kindMap[item[2]]??"type",exported,signature:trimmed.substring(0,100),line:i+1})}return symbols.sort((a,b)=>{if(a.line!==b.line)return a.line-b.line;return a.name.localeCompare(b.name)})}function extractGoSymbols(filePath,cwd){let content=readValidatedSourceFile(filePath,cwd);if(content===null)return[];let symbols=[],lines=content.split(`
5349
+ `);for(let i=0;i<lines.length;i++){let line=lines[i],method=line.match(/^func\s+\([^)]*\)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);if(method){symbols.push({name:method[1],kind:"method",exported:/^[A-Z]/.test(method[1]),signature:line.trim().substring(0,100),line:i+1});continue}let fn2=line.match(/^func\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);if(fn2){symbols.push({name:fn2[1],kind:"function",exported:/^[A-Z]/.test(fn2[1]),signature:line.trim().substring(0,100),line:i+1});continue}let typeDecl=line.match(/^type\s+([A-Za-z_][A-Za-z0-9_]*)\b/);if(typeDecl){symbols.push({name:typeDecl[1],kind:"type",exported:/^[A-Z]/.test(typeDecl[1]),signature:line.trim().substring(0,100),line:i+1});continue}let valueDecl=line.match(/^(var|const)\s+([A-Za-z_][A-Za-z0-9_]*)\b/);if(valueDecl)symbols.push({name:valueDecl[2],kind:valueDecl[1]==="const"?"const":"variable",exported:/^[A-Z]/.test(valueDecl[2]),signature:line.trim().substring(0,100),line:i+1})}return symbols.sort((a,b)=>{if(a.line!==b.line)return a.line-b.line;return a.name.localeCompare(b.name)})}function findSourceFiles(cwd,maxFiles){let files=[];return walkDir(cwd,cwd,files,maxFiles),files}function walkDir(currentDir,rootDir,files,maxFiles){let entries;try{entries=fs77.readdirSync(currentDir,{withFileTypes:!0})}catch{return}entries.sort((a,b)=>a.name.toLowerCase().localeCompare(b.name.toLowerCase()));for(let entry of entries){if(files.length>=maxFiles)return;if(SKIP_DIRECTORIES.has(entry.name))continue;let fullPath=path134.join(currentDir,entry.name);if(entry.isDirectory())walkDir(fullPath,rootDir,files,maxFiles);else if(entry.isFile()&&SYMBOL_EXTENSIONS.has(path134.extname(entry.name).toLowerCase()))files.push(path134.relative(rootDir,fullPath))}}function searchWorkspaceSymbols(cwd,name,exportedOnly=!0){let startTime=Date.now(),sourceFiles=findSourceFiles(cwd,MAX_WORKSPACE_SCANNED_FILES),files=[],scannedCount=0,truncated=!1;if(sourceFiles.length>=MAX_WORKSPACE_SCANNED_FILES)truncated=!0;let totalSymbols=0;for(let relFile of sourceFiles){if(Date.now()-startTime>WORKSPACE_TIMEOUT_MS){truncated=!0;break}scannedCount++;let syms;switch(path134.extname(relFile).toLowerCase()){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(relFile,cwd);break;case".py":case".pyw":syms=extractPythonSymbols(relFile,cwd);break;case".rs":syms=extractRustSymbols(relFile,cwd);break;case".go":syms=extractGoSymbols(relFile,cwd);break;default:continue}if(exportedOnly)syms=syms.filter((s)=>s.exported);if(name)syms=syms.filter((s)=>s.name.includes(name));if(syms.length>0){let remaining=MAX_WORKSPACE_RESULTS-totalSymbols;if(remaining<=0){truncated=!0;break}let cappedSyms=syms.slice(0,remaining);if(files.push({file:relFile,symbolCount:cappedSyms.length,symbols:cappedSyms}),totalSymbols+=cappedSyms.length,totalSymbols>=MAX_WORKSPACE_RESULTS){truncated=syms.length>remaining||scannedCount<sourceFiles.length;break}}}return{query:{workspace:!0,name},fileCount:files.length,scannedFileCount:scannedCount,totalSymbols,files,truncated}}var symbols=createSwarmTool({description:"Extract all exported symbols from a source file: functions with signatures, classes with public members, interfaces, types, enums, constants. Supports TypeScript/JavaScript, Python, Rust, and Go. Use for architect planning, designer scaffolding, and understanding module public API surface.",args:{file:exports_external.string().optional().describe('File path to extract symbols from (e.g., "src/auth/login.ts"). Required when not using workspace mode.'),exported_only:exports_external.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols."),workspace:exports_external.boolean().optional().describe("When true, search across the workspace instead of a single file. Returns per-file symbol summaries."),name:exports_external.string().optional().describe("Search for symbols by name (case-sensitive substring match). When provided without workspace, only searches the specified file.")},execute:async(args2,directory)=>{let file3,exportedOnly=!0,workspace=!1,name;try{let obj=args2;file3=obj.file!=null&&typeof obj.file==="string"?obj.file:void 0,exportedOnly=obj.exported_only!==!1,workspace=obj.workspace===!0,name=obj.name!=null&&typeof obj.name==="string"?obj.name:void 0}catch{return JSON.stringify({file:"<unknown>",error:"Invalid arguments: could not extract parameters",symbols:[]},null,2)}let cwd=directory;if(workspace)return JSON.stringify(searchWorkspaceSymbols(cwd,name,exportedOnly),null,2);if(!file3)return JSON.stringify({error:"file parameter is required when not using workspace mode",symbols:[]},null,2);if(containsControlChars(file3))return JSON.stringify({file:file3,error:"Path contains invalid control characters",symbols:[]},null,2);if(containsPathTraversal(file3))return JSON.stringify({file:file3,error:"Path contains path traversal sequence",symbols:[]},null,2);if(containsWindowsAttacks(file3))return JSON.stringify({file:file3,error:"Path contains invalid Windows-specific sequence",symbols:[]},null,2);if(!isPathInWorkspace(file3,cwd))return JSON.stringify({file:file3,error:"Path is outside workspace",symbols:[]},null,2);let ext=path134.extname(file3),syms;switch(ext){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(file3,cwd);break;case".py":case".pyw":syms=extractPythonSymbols(file3,cwd);break;case".rs":syms=extractRustSymbols(file3,cwd);break;case".go":syms=extractGoSymbols(file3,cwd);break;default:return JSON.stringify({file:file3,error:`Unsupported file extension: ${ext}. Supported: .ts, .tsx, .js, .jsx, .mjs, .cjs, .py, .pyw, .rs, .go`,symbols:[]},null,2)}if(exportedOnly)syms=syms.filter((s)=>s.exported);if(name)syms=syms.filter((s)=>s.name.includes(name));return JSON.stringify({file:file3,symbolCount:syms.length,symbols:syms},null,2)}});import*as path135 from"node:path";var HTTP_METHODS=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"],MAX_FACTS_PER_KIND=50;function stripComments(content){let out="",i=0,state="code";while(i<content.length){let ch=content[i],next=i+1<content.length?content[i+1]:"";switch(state){case"code":if(ch==="/"&&next==="/")state="line",i+=2;else if(ch==="/"&&next==="*")state="block",i+=2;else{if(ch==="'")state="single";else if(ch==='"')state="double";else if(ch==="`")state="template";out+=ch,i++}break;case"single":case"double":case"template":{let quote=state==="single"?"'":state==="double"?'"':"`";if(ch==="\\")out+=ch+next,i+=2;else{if(ch===quote)state="code";out+=ch,i++}break}case"line":if(ch===`
5315
5350
  `)state="code",out+=ch;i++;break;case"block":if(ch==="*"&&next==="/")state="code",i+=2;else{if(ch===`
5316
- `)out+=ch;i++}break}}return out}function normalizeModuleName(moduleName){return moduleName.replace(/\\/g,"/").replace(/^(?:\.\/)+/,"")}function uniqueSorted(values){return[...new Set(values)].sort((a,b)=>a.localeCompare(b))}function addRole(roles,role){roles.add(role)}function boundaryForModule(moduleName){let parts=normalizeModuleName(moduleName).split("/").filter(Boolean);if(parts.length===0)return".";if((parts[0]==="packages"||parts[0]==="crates")&&parts.length>=2)return`${parts[0]}/${parts[1]}`;if(parts[0]==="src"&&parts.length>=3){if(parts[1]==="tools"&&parts[2]==="repo-graph")return"src/tools/repo-graph";return`src/${parts[1]}`}if(parts[0]==="tests"&&parts.length>=2)return`tests/${parts[1]}`;return parts[0]}function inferRoles(moduleName,content){let normalized=normalizeModuleName(moduleName).toLowerCase(),roles=new Set;if(/(^|\/)(__tests__|tests?)\//.test(normalized)||/\.(test|spec)\.[cm]?[jt]sx?$/.test(normalized))addRole(roles,"test_file");if(/(^|\/)(app\/api|pages\/api)\//.test(normalized)||/(^|\/)(routes?|controllers?)\//.test(normalized)||/\/route\.[cm]?[jt]sx?$/.test(normalized)||/\b(router|app|server)\s*\.\s*(get|post|put|patch|delete|all)\s*\(/i.test(content))addRole(roles,"api_route");if(/(^|\/)middleware\.[cm]?[jt]sx?$/.test(normalized))addRole(roles,"middleware");if(normalized.startsWith("src/tools/"))addRole(roles,"swarm_tool");if(normalized.startsWith("src/hooks/"))addRole(roles,"hook");if(normalized.startsWith("src/agents/"))addRole(roles,"agent");if(normalized.startsWith("src/cli/")||normalized.startsWith("src/commands/"))addRole(roles,"cli_command");if(normalized.startsWith("src/config/")||/(^|\/)(config|settings)\.[cm]?[jt]s$/.test(normalized))addRole(roles,"config");if(/(^|\/)(schema|schemas|types)\//.test(normalized)||/\b(z\.object|type\s+\w+\s*=|interface\s+\w+)/.test(content))addRole(roles,"schema");if(/(^|\/)(db|database|repositories?|models?|migrations?)\//.test(normalized)||/\b(prisma|drizzle|sequelize|knex|sqlite|sql`|db\.)/i.test(content))addRole(roles,"data_module");if(/(^|\/)(services?|lib|utils?)\//.test(normalized)||/\bexport\s+(async\s+)?function\b/.test(content))addRole(roles,"service_module");if(/\.(md|mdx|rst)$/.test(normalized))addRole(roles,"documentation");if(roles.size===0)addRole(roles,"source_module");return uniqueSorted(roles)}function pathRouteFromModule(moduleName){let parts=normalizeModuleName(moduleName).split("/"),appApi=parts.findIndex((part,index)=>{return part==="api"&&index>0&&parts[index-1]==="app"});if(appApi>=0)return`/${parts.slice(appApi).filter((part)=>!/^route\.[cm]?[jt]sx?$/.test(part)).map(routeSegment).join("/")}`.replace(/\/+/g,"/");let pagesApi=parts.findIndex((part,index)=>{return part==="api"&&index>0&&parts[index-1]==="pages"});if(pagesApi>=0){let last=parts[parts.length-1]?.replace(/\.[^.]+$/,"");return`/${[...parts.slice(pagesApi,-1),last].filter(Boolean).map(routeSegment).join("/")}`.replace(/\/+/g,"/")}return null}function routeSegment(segment){return segment.replace(/^\[(\.\.\.)?(.+)]$/,(_m,rest,name)=>rest?`:${name}*`:`:${name}`).replace(/\.[^.]+$/,"")}function extractRoutes(moduleName,content){let routes=[],pathRoute=pathRouteFromModule(moduleName),lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){let line=lines[i];for(let method of HTTP_METHODS){let exportPattern=new RegExp(`\\bexport\\s+(?:async\\s+)?(?:function|const)\\s+${method}\\b`);if(pathRoute&&exportPattern.test(line))routes.push({method,path:pathRoute,line:i+1,source:"handler_export"})}let routerMatch=line.match(/\b(?:router|app|server)\s*\.\s*(get|post|put|patch|delete|options|head|all)\s*\(\s*['"`]([^'"`\0\r\n]+)['"`]/i);if(routerMatch)routes.push({method:routerMatch[1].toUpperCase(),path:routerMatch[2],line:i+1,source:"router_call"})}if(pathRoute&&routes.length===0)routes.push({method:"ALL",path:pathRoute,source:"file_path"});return routes.slice(0,MAX_FACTS_PER_KIND)}function classifyDataOperation(line){let trimmed=line.trim(),lower=trimmed.toLowerCase(),evidence=trimmed.slice(0,160),operation=null,access5="unknown",entity;if(/\b(transaction|begintransaction|commit|rollback)\b/i.test(trimmed))operation="transaction",access5="database";if(/\b(migrate|migration|schema\.alter|createTable|dropTable)\b/i.test(trimmed))operation="migration",access5="database";if(/\b(findMany|findUnique|findFirst|select|query|count|aggregate)\b/.test(trimmed))operation??="read";if(/\b(create|insert|update|upsert|save|patch)\b/.test(trimmed))operation??="write";if(/\b(delete|deleteMany|remove|destroy)\b/.test(trimmed))operation="delete";if(/\b(sql`|\bselect\b|\binsert\b|\bupdate\b|\bdelete\b|\bfrom\b)/i.test(trimmed))access5="sql";if(/\b(prisma|drizzle|sequelize|knex|db\.|database\.|repository\.)/i.test(trimmed))access5=access5==="sql"?"sql":"orm";if(/\b(readFile|writeFile|appendFile|rmSync|unlink)\b/.test(trimmed))access5="filesystem",operation??=lower.includes("read")?"read":"write";if(/\b(fetch|axios|http\.|https\.)\b/.test(trimmed))access5="network",operation??="read";let entityMatch=trimmed.match(/\b(?:prisma|db|database)\.(\w+)/i);if(entityMatch)entity=entityMatch[1];if(!operation)return null;return{operation,access:access5,entity,line:0,evidence}}function extractDataOperations(content){let facts=[],lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){let fact=classifyDataOperation(lines[i]);if(!fact)continue;if(fact.line=i+1,facts.push(fact),facts.length>=MAX_FACTS_PER_KIND)break}return facts}function extractSecurityFacts(content){let facts=[],lines=content.split(/\r?\n/),push=(kind,line,evidence,confidence)=>{facts.push({kind,line,evidence:evidence.trim().slice(0,160),confidence})};for(let i=0;i<lines.length&&facts.length<MAX_FACTS_PER_KIND;i++){let line=lines[i];if(/\b(requireAuth|requireUser|getServerSession|currentUser|verifyToken|jwt|isAuthenticated|ctx\.user|session)\b/i.test(line))push("authentication",i+1,line,"high");if(/\b(requireRole|hasPermission|authorize|authorization|isAdmin|rbac|policy\.check|can\()\b/i.test(line))push("authorization",i+1,line,"high");if(/\b(z\.object|safeParse|\.parse\(|joi\.|yup\.|validate\w*)\b/i.test(line))push("input_validation",i+1,line,"high");if(/\b(csrf|csrfToken|sameSite)\b/i.test(line))push("csrf",i+1,line,"medium");if(/\b(sanitize|escapeHtml|DOMPurify|xss)\b/i.test(line))push("sanitization",i+1,line,"medium");if(/\b(secret|api[_-]?key|token|password)\b/i.test(line))push("secret_handling",i+1,line,"low")}return facts}function extractConventions(moduleName,roles,routes){let conventions=[];if(roles.includes("test_file"))conventions.push({name:"test_file_naming",evidence:`${path135.basename(moduleName)} matches test/spec naming`});if(routes.some((route)=>route.source==="handler_export"))conventions.push({name:"next_app_route_handler",evidence:"HTTP method exports map to route handlers"});if(roles.includes("swarm_tool"))conventions.push({name:"swarm_tool_module",evidence:"module lives under src/tools"});if(roles.includes("hook"))conventions.push({name:"hook_module",evidence:"module lives under src/hooks"});return conventions}function buildFindings(roles,routes,dataOperations,security){let findings=[],hasAuth=security.some((fact)=>fact.kind==="authentication"||fact.kind==="authorization"||fact.kind==="csrf"),hasValidation=security.some((fact)=>fact.kind==="input_validation"||fact.kind==="sanitization"),mutatingRoute=routes.some((route)=>["POST","PUT","PATCH","DELETE","ALL"].includes(route.method)),writes=dataOperations.filter((fact)=>["write","delete","migration"].includes(fact.operation)),hasTransaction=dataOperations.some((fact)=>fact.operation==="transaction");if(roles.includes("api_route")&&routes.length>0&&!hasAuth)findings.push({code:"api_route_without_detected_auth",severity:"medium",message:"No authentication, authorization, or CSRF guard was detected near this route.",line:routes[0]?.line});if(mutatingRoute&&!hasValidation)findings.push({code:"mutating_route_without_detected_validation",severity:"medium",message:"Route appears to mutate state without a detected validation or sanitization fact.",line:routes.find((route)=>["POST","PUT","PATCH","DELETE","ALL"].includes(route.method))?.line});if(writes.length>1&&!hasTransaction)findings.push({code:"multiple_writes_without_detected_transaction",severity:"low",message:"Multiple write/delete operations were detected without a transaction fact.",line:writes[0]?.line});return findings}function extractFileOntology(input){let moduleName=normalizeModuleName(input.moduleName),content=stripComments(input.content),roles=inferRoles(moduleName,content),routes=extractRoutes(moduleName,content),dataOperations=extractDataOperations(content),security=extractSecurityFacts(content),conventions=extractConventions(moduleName,roles,routes),findings=buildFindings(roles,routes,dataOperations,security);return{roles,packageBoundary:boundaryForModule(moduleName),routes,dataOperations,security,conventions,findings}}import{realpathSync as realpathSync14}from"node:fs";function safeRealpathSync(targetPath,fallback,realpathResolver=realpathSync14){try{return realpathResolver(targetPath)}catch(error93){if(error93 instanceof Error&&error93.code==="ENOENT")return fallback;return null}}import*as path136 from"node:path";var REPO_GRAPH_FILENAME="repo-graph.json",GRAPH_SCHEMA_VERSION="1.2.0";function isSchemaVersionAtLeast(version5,minimum){let parse10=(v)=>v.split(".").map((part)=>{let n=Number.parseInt(part,10);return Number.isFinite(n)?n:0}),a=parse10(version5??""),b=parse10(minimum),len=Math.max(a.length,b.length);for(let i=0;i<len;i++){let av=a[i]??0,bv=b[i]??0;if(av>bv)return!0;if(av<bv)return!1}return!0}var FILE_ROLE_VALUES=["api_route","middleware","service_module","data_module","swarm_tool","agent","hook","config","schema","test_file","cli_command","documentation","source_module"],ROUTE_METHOD_VALUES=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD","ALL"],ROUTE_SOURCE_VALUES=["file_path","handler_export","router_call"],DATA_OPERATION_VALUES=["read","write","delete","transaction","migration"],DATA_ACCESS_VALUES=["database","orm","sql","filesystem","network","unknown"],SECURITY_KIND_VALUES=["authentication","authorization","input_validation","csrf","sanitization","secret_handling"],SECURITY_CONFIDENCE_VALUES=["low","medium","high"],ONTOLOGY_FINDING_SEVERITY_VALUES=["info","low","medium","high"],IMPORT_TYPE_VALUES=["default","named","namespace","require","sideeffect","type"];function normalizeGraphPath(filePath){return path136.normalize(filePath).replace(/\\/g,"/")}function createEmptyGraph(workspaceRoot){return{schema_version:GRAPH_SCHEMA_VERSION,workspaceRoot:path136.normalize(workspaceRoot),nodes:{},edges:[],metadata:{generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:0,edgeCount:0}}}function updateGraphMetadata(graph){graph.metadata={generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length}}init_path_security();var FILE_ROLE_SET=new Set(FILE_ROLE_VALUES),ROUTE_METHOD_SET=new Set(ROUTE_METHOD_VALUES),ROUTE_SOURCE_SET=new Set(ROUTE_SOURCE_VALUES),DATA_OPERATION_SET=new Set(DATA_OPERATION_VALUES),DATA_ACCESS_SET=new Set(DATA_ACCESS_VALUES),SECURITY_KIND_SET=new Set(SECURITY_KIND_VALUES),SECURITY_CONFIDENCE_SET=new Set(SECURITY_CONFIDENCE_VALUES),ONTOLOGY_FINDING_SEVERITY_SET=new Set(ONTOLOGY_FINDING_SEVERITY_VALUES),IMPORT_TYPE_SET=new Set(IMPORT_TYPE_VALUES),ONTOLOGY_NAME_PATTERN=/^[a-z][a-z0-9_]*$/;function validateWorkspace(workspace){if(!workspace||typeof workspace!=="string"||workspace.trim()==="")throw Error("Invalid workspace: must be a non-empty string");if(containsControlChars(workspace))throw Error("Invalid workspace: control characters detected");if(containsPathTraversal(workspace))throw Error("Invalid workspace: path traversal detected")}function validateGraphNode(node){if(!node||typeof node!=="object")throw Error("Invalid node: must be an object");if(!node.filePath||typeof node.filePath!=="string")throw Error("Invalid node: filePath is required");if(!node.filePath.startsWith("/")&&!/^[A-Za-z]:[/\\]/.test(node.filePath))throw Error("Invalid node: filePath must be absolute");if(containsPathTraversal(node.filePath))throw Error("Invalid node: filePath contains path traversal");if(containsControlChars(node.filePath))throw Error("Invalid node: filePath contains control characters");if(!node.moduleName||typeof node.moduleName!=="string")throw Error("Invalid node: moduleName is required");if(node.moduleName.startsWith("/")||node.moduleName.startsWith("\\")||/^[A-Za-z]:[/\\]/.test(node.moduleName))throw Error("Invalid node: moduleName must be relative");if(containsPathTraversal(node.moduleName))throw Error("Invalid node: moduleName contains path traversal");if(containsControlChars(node.moduleName))throw Error("Invalid node: moduleName contains control characters");if(typeof node.language!=="string")throw Error("Invalid node: language is required");if(typeof node.mtime!=="string")throw Error("Invalid node: mtime is required");if(!Array.isArray(node.exports))throw Error("Invalid node: exports must be an array");for(let exp of node.exports){if(typeof exp!=="string")throw Error("Invalid node: exports must be an array of strings");if(containsControlChars(exp)){let preview=exp.slice(0,120);throw Error(`Invalid node: exports contains control characters (file=${node.filePath}, value="${preview}")`)}}if(!Array.isArray(node.imports))throw Error("Invalid node: imports must be an array");for(let imp of node.imports){if(typeof imp!=="string")throw Error("Invalid node: imports must be an array of strings");if(containsControlChars(imp)){let preview=imp.slice(0,120);throw Error(`Invalid node: imports contains control characters (file=${node.filePath}, value="${preview}")`)}}if(node.exportLines!==void 0){if(typeof node.exportLines!=="object"||node.exportLines===null||Array.isArray(node.exportLines))throw Error("Invalid node: exportLines must be an object");for(let[name,line]of Object.entries(node.exportLines)){if(containsControlChars(name))throw Error("Invalid node: exportLines key contains control characters");if(typeof line!=="number"||!Number.isFinite(line)||line<0)throw Error("Invalid node: exportLines values must be non-negative numbers")}}if(node.exportRanges!==void 0){if(typeof node.exportRanges!=="object"||node.exportRanges===null||Array.isArray(node.exportRanges))throw Error("Invalid node: exportRanges must be an object");for(let[name,range]of Object.entries(node.exportRanges)){if(containsControlChars(name))throw Error("Invalid node: exportRanges key contains control characters");if(typeof range!=="object"||range===null||Array.isArray(range))throw Error("Invalid node: exportRanges values must be objects");let r=range;if(typeof r.startLine!=="number"||!Number.isFinite(r.startLine)||!Number.isInteger(r.startLine)||r.startLine<1||typeof r.endLine!=="number"||!Number.isFinite(r.endLine)||!Number.isInteger(r.endLine)||r.endLine<1)throw Error("Invalid node: exportRanges value must have positive integer startLine and endLine (1-based)");if(r.startLine>r.endLine)throw Error("Invalid node: exportRanges value must have startLine <= endLine")}}if(node.ontology!==void 0)validateOntologyStrings(node)}function validateOntologyStrings(node){let ontology=node.ontology;if(!ontology||typeof ontology!=="object")throw Error("Invalid node: ontology must be an object");let values=[...ontology.roles??[],ontology.packageBoundary,...(ontology.routes??[]).flatMap((route)=>[route.method,route.path,route.source]),...(ontology.dataOperations??[]).flatMap((fact)=>[fact.operation,fact.access,fact.entity??"",fact.evidence]),...(ontology.security??[]).flatMap((fact)=>[fact.kind,fact.evidence,fact.confidence]),...(ontology.conventions??[]).flatMap((fact)=>[fact.name,fact.evidence]),...(ontology.findings??[]).flatMap((finding)=>[finding.code,finding.severity,finding.message])];for(let value of values){if(typeof value!=="string")throw Error("Invalid node: ontology contains non-string value");if(containsControlChars(value)){let preview=value.slice(0,120);throw Error(`Invalid node: ontology contains control characters (file=${node.filePath}, value="${preview}")`)}}for(let role of ontology.roles??[])validateAllowedOntologyValue(node,"ontology.roles",role,FILE_ROLE_SET);for(let route of ontology.routes??[])validateAllowedOntologyValue(node,"ontology.routes.method",route.method,ROUTE_METHOD_SET),validateAllowedOntologyValue(node,"ontology.routes.source",route.source,ROUTE_SOURCE_SET);for(let fact of ontology.dataOperations??[])validateAllowedOntologyValue(node,"ontology.dataOperations.operation",fact.operation,DATA_OPERATION_SET),validateAllowedOntologyValue(node,"ontology.dataOperations.access",fact.access,DATA_ACCESS_SET);for(let fact of ontology.security??[])validateAllowedOntologyValue(node,"ontology.security.kind",fact.kind,SECURITY_KIND_SET),validateAllowedOntologyValue(node,"ontology.security.confidence",fact.confidence,SECURITY_CONFIDENCE_SET);for(let finding of ontology.findings??[])validateOntologyName(node,"ontology.findings.code",finding.code),validateAllowedOntologyValue(node,"ontology.findings.severity",finding.severity,ONTOLOGY_FINDING_SEVERITY_SET)}function validateOntologyName(node,field,value){if(ONTOLOGY_NAME_PATTERN.test(value))return;let preview=value.slice(0,120);throw Error(`Invalid node: ${field} must be lower_snake_case (file=${node.filePath}, value="${preview}")`)}function validateAllowedOntologyValue(node,field,value,allowed){if(allowed.has(value))return;let preview=value.slice(0,120);throw Error(`Invalid node: ${field} contains invalid value (file=${node.filePath}, value="${preview}")`)}function validateGraphEdge(edge){if(!edge||typeof edge!=="object")throw Error("Invalid edge: must be an object");if(!edge.source||typeof edge.source!=="string")throw Error("Invalid edge: source is required");if(!edge.target||typeof edge.target!=="string")throw Error("Invalid edge: target is required");if(containsPathTraversal(edge.source)||containsPathTraversal(edge.target))throw Error("Invalid edge: path traversal detected");if(containsControlChars(edge.source)||containsControlChars(edge.target))throw Error("Invalid edge: control characters detected");if(!edge.importSpecifier||typeof edge.importSpecifier!=="string")throw Error("Invalid edge: importSpecifier is required");if(containsControlChars(edge.importSpecifier))throw Error("Invalid edge: importSpecifier contains control characters");if(!IMPORT_TYPE_SET.has(edge.importType))throw Error("Invalid edge: importType is invalid");if(edge.importedSymbols!==void 0){if(!Array.isArray(edge.importedSymbols))throw Error("Invalid edge: importedSymbols must be an array");for(let symbol3 of edge.importedSymbols){if(typeof symbol3!=="string")throw Error("Invalid edge: importedSymbols must be an array of strings");if(containsControlChars(symbol3))throw Error("Invalid edge: importedSymbols contains control characters")}}if(edge.usedSymbols!==void 0){if(!Array.isArray(edge.usedSymbols))throw Error("Invalid edge: usedSymbols must be an array");for(let symbol3 of edge.usedSymbols){if(typeof symbol3!=="string")throw Error("Invalid edge: usedSymbols must be an array of strings");if(containsControlChars(symbol3))throw Error("Invalid edge: usedSymbols contains control characters")}}}var _internals83={safeRealpathSync,extractTSSymbols,extractPythonSymbols,parseFileImports,extractFileOntology,stripComments:stripComments2,computeUsedSymbols,extractFileSymbols},SKIP_DIRECTORIES2=new Set(["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".cache","vendor",".svn",".hg",".svelte-kit"]);function resolveSkipDirectories(excludeDirs){let extras=excludeDirs?.filter((d)=>d.length>0)??[];if(extras.length===0)return SKIP_DIRECTORIES2;return new Set([...SKIP_DIRECTORIES2,...extras])}var SUPPORTED_EXTENSIONS=new Set(LANGUAGE_REGISTRY.getAll().filter((p)=>!p.parserOnly).flatMap((p)=>p.extensions)),DEFAULT_WALK_FILE_CAP=1e4,DEFAULT_WALK_BUDGET_MS=5000,ASYNC_WALK_YIELD_INTERVAL=200,MAX_DIAGNOSTIC_ENTRIES=200,EXTENSION_TO_LANGUAGE={};for(let profile of LANGUAGE_REGISTRY.getAll()){if(profile.parserOnly)continue;for(let ext of profile.extensions)EXTENSION_TO_LANGUAGE[ext]=profile.treeSitter.grammarId}var JS_FAMILY_EXTENSION_TO_LANGUAGE={".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".ts":"typescript",".tsx":"tsx"};function upsertNode(graph,node){validateGraphNode(node);let key=normalizeGraphPath(node.filePath);graph.nodes[key]=node,updateGraphMetadata(graph)}function addEdge(graph,edge){if(validateGraphEdge(edge),!graph.edges.some((e)=>e.source===edge.source&&e.target===edge.target&&e.importSpecifier===edge.importSpecifier))graph.edges.push(edge),updateGraphMetadata(graph)}function buildLoopEdgeKey(edge){return`${edge.source}\x00${edge.target}\x00${edge.importSpecifier}`}function appendNodeFast(graph,node){validateGraphNode(node),graph.nodes[normalizeGraphPath(node.filePath)]=node}function appendEdgeFast(graph,edge,seenEdgeKeys){validateGraphEdge(edge);let key=buildLoopEdgeKey(edge);if(seenEdgeKeys.has(key))return;seenEdgeKeys.add(key),graph.edges.push(edge)}function resolveModuleSpecifier(workspaceRoot,sourceFile,specifier){if(containsControlChars(specifier))return null;if(specifier.startsWith("/")||specifier.startsWith("\\"))return null;if(/^[A-Za-z]:[/\\]/.test(specifier))return null;if(specifier.startsWith("http://")||specifier.startsWith("https://"))return null;try{if(specifier.startsWith(".")){let sourceDir=path137.dirname(sourceFile),resolved=path137.resolve(sourceDir,specifier),initialRealResolved=_internals83.safeRealpathSync(resolved,resolved);if(initialRealResolved===null)return null;let realResolved=initialRealResolved,realRoot=_internals83.safeRealpathSync(workspaceRoot,path137.normalize(workspaceRoot));if(realRoot===null)return null;if(!existsSync77(resolved)){let EXTENSIONS=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".json"],found=null;for(let ext of EXTENSIONS){let candidate=resolved+ext;if(existsSync77(candidate)){found=candidate;break}}if(found){let foundRealPath=_internals83.safeRealpathSync(found,found);if(foundRealPath===null)return null;realResolved=foundRealPath,resolved=found}else return null}let normalizedResolved=path137.normalize(realResolved),normalizedRoot=path137.normalize(realRoot);if(!normalizedResolved.startsWith(normalizedRoot+path137.sep)&&normalizedResolved!==normalizedRoot)return null;return resolved}return null}catch{return null}}function isRefusedWorkspaceRoot(target){let resolved;try{resolved=realpathSync15(target)}catch{resolved=path137.resolve(target)}let refused=new Set,add2=(p)=>{if(typeof p==="string"&&p.length>0)refused.add(path137.resolve(p))};if(add2(os20.homedir()),add2(os20.tmpdir()),add2("/"),add2("/Users"),add2("/home"),add2("/root"),process.platform==="win32")add2("C:\\"),add2("C:\\Users");return refused.has(resolved)}function createEmptyDiagnostics(){return{extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],lowConfidenceEdgeCount:0}}function diagnosticsHaveEntries(diagnostics){return(diagnostics.extractionFailures?.length??0)>0||(diagnostics.unresolvedImports?.length??0)>0||(diagnostics.oversizedFiles?.length??0)>0||(diagnostics.unsupportedFiles?.length??0)>0||(diagnostics.binaryFiles?.length??0)>0||(diagnostics.unreadableFiles?.length??0)>0||(diagnostics.lowConfidenceEdgeCount??0)>0}function pushCapped(target,value){if(target.length<MAX_DIAGNOSTIC_ENTRIES)target.push(value)}function mergeDiagnostics(target,source){if(!source)return;for(let entry of source.extractionFailures??[])pushCapped(target.extractionFailures,entry);for(let entry of source.unresolvedImports??[])pushCapped(target.unresolvedImports,entry);for(let entry of source.oversizedFiles??[])pushCapped(target.oversizedFiles,entry);for(let entry of source.unsupportedFiles??[])pushCapped(target.unsupportedFiles,entry);for(let entry of source.binaryFiles??[])pushCapped(target.binaryFiles,entry);for(let entry of source.unreadableFiles??[])pushCapped(target.unreadableFiles,entry);target.lowConfidenceEdgeCount+=source.lowConfidenceEdgeCount??0}function isRelativeImportSpecifier(specifier){return specifier==="."||specifier===".."||specifier.startsWith("./")||specifier.startsWith("../")}function unresolvedRelativeImportsFor(parsedImports,filePath,absoluteRoot){let unresolved=[],moduleName=toModuleName(filePath,absoluteRoot);for(let parsed of parsedImports){if(!isRelativeImportSpecifier(parsed.specifier))continue;if(resolveModuleSpecifier(absoluteRoot,filePath,parsed.specifier)===null)unresolved.push({file:moduleName,specifier:parsed.specifier})}return unresolved}var REGEX_ALLOWED_AFTER=new Set("(,=:[!&|?{};*+-~^<>%".split(""));function stripComments2(content){let out="",i=0,n=content.length,state="code",prevSignificant="",regexInClass=!1;while(i<n){let ch=content[i],next=i+1<n?content[i+1]:"";switch(state){case"code":if(ch==="/"&&next==="/")state="line",i+=2;else if(ch==="/"&&next==="*")state="block",i+=2;else if(ch==="/"&&REGEX_ALLOWED_AFTER.has(prevSignificant))state="regex",regexInClass=!1,out+=ch,i+=1;else{if(ch==="'")state="single";else if(ch==='"')state="double";else if(ch==="`")state="template";if(out+=ch,ch.trim()!=="")prevSignificant=ch;i+=1}break;case"single":case"double":case"template":{let quote=state==="single"?"'":state==="double"?'"':"`";if(ch==="\\")out+=ch+next,i+=2;else{if(ch===quote)state="code",prevSignificant=quote;out+=ch,i+=1}break}case"regex":if(ch==="\\")out+=ch+next,i+=2;else if(ch===`
5351
+ `)out+=ch;i++}break}}return out}function normalizeModuleName(moduleName){return moduleName.replace(/\\/g,"/").replace(/^(?:\.\/)+/,"")}function uniqueSorted(values){return[...new Set(values)].sort((a,b)=>a.localeCompare(b))}function addRole(roles,role){roles.add(role)}function boundaryForModule(moduleName){let parts=normalizeModuleName(moduleName).split("/").filter(Boolean);if(parts.length===0)return".";if((parts[0]==="packages"||parts[0]==="crates")&&parts.length>=2)return`${parts[0]}/${parts[1]}`;if(parts[0]==="src"&&parts.length>=3){if(parts[1]==="tools"&&parts[2]==="repo-graph")return"src/tools/repo-graph";return`src/${parts[1]}`}if(parts[0]==="tests"&&parts.length>=2)return`tests/${parts[1]}`;return parts[0]}function inferRoles(moduleName,content){let normalized=normalizeModuleName(moduleName).toLowerCase(),roles=new Set;if(/(^|\/)(__tests__|tests?)\//.test(normalized)||/\.(test|spec)\.[cm]?[jt]sx?$/.test(normalized))addRole(roles,"test_file");if(/(^|\/)(app\/api|pages\/api)\//.test(normalized)||/(^|\/)(routes?|controllers?)\//.test(normalized)||/\/route\.[cm]?[jt]sx?$/.test(normalized)||/\b(router|app|server)\s*\.\s*(get|post|put|patch|delete|all)\s*\(/i.test(content))addRole(roles,"api_route");if(/(^|\/)middleware\.[cm]?[jt]sx?$/.test(normalized))addRole(roles,"middleware");if(normalized.startsWith("src/tools/"))addRole(roles,"swarm_tool");if(normalized.startsWith("src/hooks/"))addRole(roles,"hook");if(normalized.startsWith("src/agents/"))addRole(roles,"agent");if(normalized.startsWith("src/cli/")||normalized.startsWith("src/commands/"))addRole(roles,"cli_command");if(normalized.startsWith("src/config/")||/(^|\/)(config|settings)\.[cm]?[jt]s$/.test(normalized))addRole(roles,"config");if(/(^|\/)(schema|schemas|types)\//.test(normalized)||/\b(z\.object|type\s+\w+\s*=|interface\s+\w+)/.test(content))addRole(roles,"schema");if(/(^|\/)(db|database|repositories?|models?|migrations?)\//.test(normalized)||/\b(prisma|drizzle|sequelize|knex|sqlite|sql`|db\.)/i.test(content))addRole(roles,"data_module");if(/(^|\/)(services?|lib|utils?)\//.test(normalized)||/\bexport\s+(async\s+)?function\b/.test(content))addRole(roles,"service_module");if(/\.(md|mdx|rst)$/.test(normalized))addRole(roles,"documentation");if(roles.size===0)addRole(roles,"source_module");return uniqueSorted(roles)}function pathRouteFromModule(moduleName){let parts=normalizeModuleName(moduleName).split("/"),appApi=parts.findIndex((part,index)=>{return part==="api"&&index>0&&parts[index-1]==="app"});if(appApi>=0)return`/${parts.slice(appApi).filter((part)=>!/^route\.[cm]?[jt]sx?$/.test(part)).map(routeSegment).join("/")}`.replace(/\/+/g,"/");let pagesApi=parts.findIndex((part,index)=>{return part==="api"&&index>0&&parts[index-1]==="pages"});if(pagesApi>=0){let last=parts[parts.length-1]?.replace(/\.[^.]+$/,"");return`/${[...parts.slice(pagesApi,-1),last].filter(Boolean).map(routeSegment).join("/")}`.replace(/\/+/g,"/")}return null}function routeSegment(segment){return segment.replace(/^\[(\.\.\.)?(.+)]$/,(_m,rest,name)=>rest?`:${name}*`:`:${name}`).replace(/\.[^.]+$/,"")}function extractRoutes(moduleName,content){let routes=[],pathRoute=pathRouteFromModule(moduleName),lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){let line=lines[i];for(let method of HTTP_METHODS){let exportPattern=new RegExp(`\\bexport\\s+(?:async\\s+)?(?:function|const)\\s+${method}\\b`);if(pathRoute&&exportPattern.test(line))routes.push({method,path:pathRoute,line:i+1,source:"handler_export"})}let routerMatch=line.match(/\b(?:router|app|server)\s*\.\s*(get|post|put|patch|delete|options|head|all)\s*\(\s*['"`]([^'"`\0\r\n]+)['"`]/i);if(routerMatch)routes.push({method:routerMatch[1].toUpperCase(),path:routerMatch[2],line:i+1,source:"router_call"})}if(pathRoute&&routes.length===0)routes.push({method:"ALL",path:pathRoute,source:"file_path"});return routes.slice(0,MAX_FACTS_PER_KIND)}function classifyDataOperation(line){let trimmed=line.trim(),lower=trimmed.toLowerCase(),evidence=trimmed.slice(0,160),operation=null,access5="unknown",entity;if(/\b(transaction|begintransaction|commit|rollback)\b/i.test(trimmed))operation="transaction",access5="database";if(/\b(migrate|migration|schema\.alter|createTable|dropTable)\b/i.test(trimmed))operation="migration",access5="database";if(/\b(findMany|findUnique|findFirst|select|query|count|aggregate)\b/.test(trimmed))operation??="read";if(/\b(create|insert|update|upsert|save|patch)\b/.test(trimmed))operation??="write";if(/\b(delete|deleteMany|remove|destroy)\b/.test(trimmed))operation="delete";if(/\b(sql`|\bselect\b|\binsert\b|\bupdate\b|\bdelete\b|\bfrom\b)/i.test(trimmed))access5="sql";if(/\b(prisma|drizzle|sequelize|knex|db\.|database\.|repository\.)/i.test(trimmed))access5=access5==="sql"?"sql":"orm";if(/\b(readFile|writeFile|appendFile|rmSync|unlink)\b/.test(trimmed))access5="filesystem",operation??=lower.includes("read")?"read":"write";if(/\b(fetch|axios|http\.|https\.)\b/.test(trimmed))access5="network",operation??="read";let entityMatch=trimmed.match(/\b(?:prisma|db|database)\.(\w+)/i);if(entityMatch)entity=entityMatch[1];if(!operation)return null;return{operation,access:access5,entity,line:0,evidence}}function extractDataOperations(content){let facts=[],lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){let fact=classifyDataOperation(lines[i]);if(!fact)continue;if(fact.line=i+1,facts.push(fact),facts.length>=MAX_FACTS_PER_KIND)break}return facts}function extractSecurityFacts(content){let facts=[],lines=content.split(/\r?\n/),push=(kind,line,evidence,confidence)=>{facts.push({kind,line,evidence:evidence.trim().slice(0,160),confidence})};for(let i=0;i<lines.length&&facts.length<MAX_FACTS_PER_KIND;i++){let line=lines[i];if(/\b(requireAuth|requireUser|getServerSession|currentUser|verifyToken|jwt|isAuthenticated|ctx\.user|session)\b/i.test(line))push("authentication",i+1,line,"high");if(/\b(requireRole|hasPermission|authorize|authorization|isAdmin|rbac|policy\.check|can\()\b/i.test(line))push("authorization",i+1,line,"high");if(/\b(z\.object|safeParse|\.parse\(|joi\.|yup\.|validate\w*)\b/i.test(line))push("input_validation",i+1,line,"high");if(/\b(csrf|csrfToken|sameSite)\b/i.test(line))push("csrf",i+1,line,"medium");if(/\b(sanitize|escapeHtml|DOMPurify|xss)\b/i.test(line))push("sanitization",i+1,line,"medium");if(/\b(secret|api[_-]?key|token|password)\b/i.test(line))push("secret_handling",i+1,line,"low")}return facts}function extractConventions(moduleName,roles,routes){let conventions=[];if(roles.includes("test_file"))conventions.push({name:"test_file_naming",evidence:`${path135.basename(moduleName)} matches test/spec naming`});if(routes.some((route)=>route.source==="handler_export"))conventions.push({name:"next_app_route_handler",evidence:"HTTP method exports map to route handlers"});if(roles.includes("swarm_tool"))conventions.push({name:"swarm_tool_module",evidence:"module lives under src/tools"});if(roles.includes("hook"))conventions.push({name:"hook_module",evidence:"module lives under src/hooks"});return conventions}function buildFindings(roles,routes,dataOperations,security){let findings=[],hasAuth=security.some((fact)=>fact.kind==="authentication"||fact.kind==="authorization"||fact.kind==="csrf"),hasValidation=security.some((fact)=>fact.kind==="input_validation"||fact.kind==="sanitization"),mutatingRoute=routes.some((route)=>["POST","PUT","PATCH","DELETE","ALL"].includes(route.method)),writes=dataOperations.filter((fact)=>["write","delete","migration"].includes(fact.operation)),hasTransaction=dataOperations.some((fact)=>fact.operation==="transaction");if(roles.includes("api_route")&&routes.length>0&&!hasAuth)findings.push({code:"api_route_without_detected_auth",severity:"medium",message:"No authentication, authorization, or CSRF guard was detected near this route.",line:routes[0]?.line});if(mutatingRoute&&!hasValidation)findings.push({code:"mutating_route_without_detected_validation",severity:"medium",message:"Route appears to mutate state without a detected validation or sanitization fact.",line:routes.find((route)=>["POST","PUT","PATCH","DELETE","ALL"].includes(route.method))?.line});if(writes.length>1&&!hasTransaction)findings.push({code:"multiple_writes_without_detected_transaction",severity:"low",message:"Multiple write/delete operations were detected without a transaction fact.",line:writes[0]?.line});return findings}function extractFileOntology(input){let moduleName=normalizeModuleName(input.moduleName),content=stripComments(input.content),roles=inferRoles(moduleName,content),routes=extractRoutes(moduleName,content),dataOperations=extractDataOperations(content),security=extractSecurityFacts(content),conventions=extractConventions(moduleName,roles,routes),findings=buildFindings(roles,routes,dataOperations,security);return{roles,packageBoundary:boundaryForModule(moduleName),routes,dataOperations,security,conventions,findings}}import{realpathSync as realpathSync14}from"node:fs";function safeRealpathSync(targetPath,fallback,realpathResolver=realpathSync14){try{return realpathResolver(targetPath)}catch(error93){if(error93 instanceof Error&&error93.code==="ENOENT")return fallback;return null}}import*as path136 from"node:path";var REPO_GRAPH_FILENAME="repo-graph.json",GRAPH_SCHEMA_VERSION="1.2.0";function isSchemaVersionAtLeast(version5,minimum){let parse10=(v)=>v.split(".").map((part)=>{let n=Number.parseInt(part,10);return Number.isFinite(n)?n:0}),a=parse10(version5??""),b=parse10(minimum),len=Math.max(a.length,b.length);for(let i=0;i<len;i++){let av=a[i]??0,bv=b[i]??0;if(av>bv)return!0;if(av<bv)return!1}return!0}var FILE_ROLE_VALUES=["api_route","middleware","service_module","data_module","swarm_tool","agent","hook","config","schema","test_file","cli_command","documentation","source_module"],ROUTE_METHOD_VALUES=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD","ALL"],ROUTE_SOURCE_VALUES=["file_path","handler_export","router_call"],DATA_OPERATION_VALUES=["read","write","delete","transaction","migration"],DATA_ACCESS_VALUES=["database","orm","sql","filesystem","network","unknown"],SECURITY_KIND_VALUES=["authentication","authorization","input_validation","csrf","sanitization","secret_handling"],SECURITY_CONFIDENCE_VALUES=["low","medium","high"],ONTOLOGY_FINDING_SEVERITY_VALUES=["info","low","medium","high"],IMPORT_TYPE_VALUES=["default","named","namespace","require","sideeffect","type"];function normalizeGraphPath(filePath){return path136.normalize(filePath).replace(/\\/g,"/")}function createEmptyGraph(workspaceRoot){return{schema_version:GRAPH_SCHEMA_VERSION,workspaceRoot:path136.normalize(workspaceRoot),nodes:{},edges:[],metadata:{generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:0,edgeCount:0}}}function updateGraphMetadata(graph){graph.metadata={generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length}}init_path_security();var FILE_ROLE_SET=new Set(FILE_ROLE_VALUES),ROUTE_METHOD_SET=new Set(ROUTE_METHOD_VALUES),ROUTE_SOURCE_SET=new Set(ROUTE_SOURCE_VALUES),DATA_OPERATION_SET=new Set(DATA_OPERATION_VALUES),DATA_ACCESS_SET=new Set(DATA_ACCESS_VALUES),SECURITY_KIND_SET=new Set(SECURITY_KIND_VALUES),SECURITY_CONFIDENCE_SET=new Set(SECURITY_CONFIDENCE_VALUES),ONTOLOGY_FINDING_SEVERITY_SET=new Set(ONTOLOGY_FINDING_SEVERITY_VALUES),IMPORT_TYPE_SET=new Set(IMPORT_TYPE_VALUES),ONTOLOGY_NAME_PATTERN=/^[a-z][a-z0-9_]*$/;function validateWorkspace(workspace){if(!workspace||typeof workspace!=="string"||workspace.trim()==="")throw Error("Invalid workspace: must be a non-empty string");if(containsControlChars(workspace))throw Error("Invalid workspace: control characters detected");if(containsPathTraversal(workspace))throw Error("Invalid workspace: path traversal detected")}function validateGraphNode(node){if(!node||typeof node!=="object")throw Error("Invalid node: must be an object");if(!node.filePath||typeof node.filePath!=="string")throw Error("Invalid node: filePath is required");if(!node.filePath.startsWith("/")&&!/^[A-Za-z]:[/\\]/.test(node.filePath))throw Error("Invalid node: filePath must be absolute");if(containsPathTraversal(node.filePath))throw Error("Invalid node: filePath contains path traversal");if(containsControlChars(node.filePath))throw Error("Invalid node: filePath contains control characters");if(!node.moduleName||typeof node.moduleName!=="string")throw Error("Invalid node: moduleName is required");if(node.moduleName.startsWith("/")||node.moduleName.startsWith("\\")||/^[A-Za-z]:[/\\]/.test(node.moduleName))throw Error("Invalid node: moduleName must be relative");if(containsPathTraversal(node.moduleName))throw Error("Invalid node: moduleName contains path traversal");if(containsControlChars(node.moduleName))throw Error("Invalid node: moduleName contains control characters");if(typeof node.language!=="string")throw Error("Invalid node: language is required");if(typeof node.mtime!=="string")throw Error("Invalid node: mtime is required");if(!Array.isArray(node.exports))throw Error("Invalid node: exports must be an array");for(let exp of node.exports){if(typeof exp!=="string")throw Error("Invalid node: exports must be an array of strings");if(containsControlChars(exp)){let preview=exp.slice(0,120);throw Error(`Invalid node: exports contains control characters (file=${node.filePath}, value="${preview}")`)}}if(!Array.isArray(node.imports))throw Error("Invalid node: imports must be an array");for(let imp of node.imports){if(typeof imp!=="string")throw Error("Invalid node: imports must be an array of strings");if(containsControlChars(imp)){let preview=imp.slice(0,120);throw Error(`Invalid node: imports contains control characters (file=${node.filePath}, value="${preview}")`)}}if(node.exportLines!==void 0){if(typeof node.exportLines!=="object"||node.exportLines===null||Array.isArray(node.exportLines))throw Error("Invalid node: exportLines must be an object");for(let[name,line]of Object.entries(node.exportLines)){if(containsControlChars(name))throw Error("Invalid node: exportLines key contains control characters");if(typeof line!=="number"||!Number.isFinite(line)||line<0)throw Error("Invalid node: exportLines values must be non-negative numbers")}}if(node.exportRanges!==void 0){if(typeof node.exportRanges!=="object"||node.exportRanges===null||Array.isArray(node.exportRanges))throw Error("Invalid node: exportRanges must be an object");for(let[name,range]of Object.entries(node.exportRanges)){if(containsControlChars(name))throw Error("Invalid node: exportRanges key contains control characters");if(typeof range!=="object"||range===null||Array.isArray(range))throw Error("Invalid node: exportRanges values must be objects");let r=range;if(typeof r.startLine!=="number"||!Number.isFinite(r.startLine)||!Number.isInteger(r.startLine)||r.startLine<1||typeof r.endLine!=="number"||!Number.isFinite(r.endLine)||!Number.isInteger(r.endLine)||r.endLine<1)throw Error("Invalid node: exportRanges value must have positive integer startLine and endLine (1-based)");if(r.startLine>r.endLine)throw Error("Invalid node: exportRanges value must have startLine <= endLine")}}if(node.ontology!==void 0)validateOntologyStrings(node)}function validateOntologyStrings(node){let ontology=node.ontology;if(!ontology||typeof ontology!=="object")throw Error("Invalid node: ontology must be an object");let values=[...ontology.roles??[],ontology.packageBoundary,...(ontology.routes??[]).flatMap((route)=>[route.method,route.path,route.source]),...(ontology.dataOperations??[]).flatMap((fact)=>[fact.operation,fact.access,fact.entity??"",fact.evidence]),...(ontology.security??[]).flatMap((fact)=>[fact.kind,fact.evidence,fact.confidence]),...(ontology.conventions??[]).flatMap((fact)=>[fact.name,fact.evidence]),...(ontology.findings??[]).flatMap((finding)=>[finding.code,finding.severity,finding.message])];for(let value of values){if(typeof value!=="string")throw Error("Invalid node: ontology contains non-string value");if(containsControlChars(value)){let preview=value.slice(0,120);throw Error(`Invalid node: ontology contains control characters (file=${node.filePath}, value="${preview}")`)}}for(let role of ontology.roles??[])validateAllowedOntologyValue(node,"ontology.roles",role,FILE_ROLE_SET);for(let route of ontology.routes??[])validateAllowedOntologyValue(node,"ontology.routes.method",route.method,ROUTE_METHOD_SET),validateAllowedOntologyValue(node,"ontology.routes.source",route.source,ROUTE_SOURCE_SET);for(let fact of ontology.dataOperations??[])validateAllowedOntologyValue(node,"ontology.dataOperations.operation",fact.operation,DATA_OPERATION_SET),validateAllowedOntologyValue(node,"ontology.dataOperations.access",fact.access,DATA_ACCESS_SET);for(let fact of ontology.security??[])validateAllowedOntologyValue(node,"ontology.security.kind",fact.kind,SECURITY_KIND_SET),validateAllowedOntologyValue(node,"ontology.security.confidence",fact.confidence,SECURITY_CONFIDENCE_SET);for(let finding of ontology.findings??[])validateOntologyName(node,"ontology.findings.code",finding.code),validateAllowedOntologyValue(node,"ontology.findings.severity",finding.severity,ONTOLOGY_FINDING_SEVERITY_SET)}function validateOntologyName(node,field,value){if(ONTOLOGY_NAME_PATTERN.test(value))return;let preview=value.slice(0,120);throw Error(`Invalid node: ${field} must be lower_snake_case (file=${node.filePath}, value="${preview}")`)}function validateAllowedOntologyValue(node,field,value,allowed){if(allowed.has(value))return;let preview=value.slice(0,120);throw Error(`Invalid node: ${field} contains invalid value (file=${node.filePath}, value="${preview}")`)}function validateGraphEdge(edge){if(!edge||typeof edge!=="object")throw Error("Invalid edge: must be an object");if(!edge.source||typeof edge.source!=="string")throw Error("Invalid edge: source is required");if(!edge.target||typeof edge.target!=="string")throw Error("Invalid edge: target is required");if(containsPathTraversal(edge.source)||containsPathTraversal(edge.target))throw Error("Invalid edge: path traversal detected");if(containsControlChars(edge.source)||containsControlChars(edge.target))throw Error("Invalid edge: control characters detected");if(!edge.importSpecifier||typeof edge.importSpecifier!=="string")throw Error("Invalid edge: importSpecifier is required");if(containsControlChars(edge.importSpecifier))throw Error("Invalid edge: importSpecifier contains control characters");if(!IMPORT_TYPE_SET.has(edge.importType))throw Error("Invalid edge: importType is invalid");if(edge.importedSymbols!==void 0){if(!Array.isArray(edge.importedSymbols))throw Error("Invalid edge: importedSymbols must be an array");for(let symbol3 of edge.importedSymbols){if(typeof symbol3!=="string")throw Error("Invalid edge: importedSymbols must be an array of strings");if(containsControlChars(symbol3))throw Error("Invalid edge: importedSymbols contains control characters")}}if(edge.usedSymbols!==void 0){if(!Array.isArray(edge.usedSymbols))throw Error("Invalid edge: usedSymbols must be an array");for(let symbol3 of edge.usedSymbols){if(typeof symbol3!=="string")throw Error("Invalid edge: usedSymbols must be an array of strings");if(containsControlChars(symbol3))throw Error("Invalid edge: usedSymbols contains control characters")}}}var _internals83={safeRealpathSync,extractTSSymbols,extractPythonSymbols,extractRustSymbols,extractGoSymbols,parseFileImports,extractFileOntology,stripComments:stripComments2,computeUsedSymbols,extractFileSymbols},SKIP_DIRECTORIES2=new Set(["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".cache","vendor",".svn",".hg",".svelte-kit"]);function resolveSkipDirectories(excludeDirs){let extras=excludeDirs?.filter((d)=>d.length>0)??[];if(extras.length===0)return SKIP_DIRECTORIES2;return new Set([...SKIP_DIRECTORIES2,...extras])}var SUPPORTED_EXTENSIONS=new Set(LANGUAGE_REGISTRY.getAll().filter((p)=>!p.parserOnly).flatMap((p)=>p.extensions)),DEFAULT_WALK_FILE_CAP=1e4,DEFAULT_WALK_BUDGET_MS=5000,ASYNC_WALK_YIELD_INTERVAL=200,MAX_DIAGNOSTIC_ENTRIES=200,EXTENSION_TO_LANGUAGE={};for(let profile of LANGUAGE_REGISTRY.getAll()){if(profile.parserOnly)continue;for(let ext of profile.extensions)EXTENSION_TO_LANGUAGE[ext]=profile.treeSitter.grammarId}var JS_FAMILY_EXTENSION_TO_LANGUAGE={".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".ts":"typescript",".tsx":"tsx"};function upsertNode(graph,node){validateGraphNode(node);let key=normalizeGraphPath(node.filePath);graph.nodes[key]=node,updateGraphMetadata(graph)}function addEdge(graph,edge){if(validateGraphEdge(edge),!graph.edges.some((e)=>e.source===edge.source&&e.target===edge.target&&e.importSpecifier===edge.importSpecifier))graph.edges.push(edge),updateGraphMetadata(graph)}function buildLoopEdgeKey(edge){return`${edge.source}\x00${edge.target}\x00${edge.importSpecifier}`}function appendNodeFast(graph,node){validateGraphNode(node),graph.nodes[normalizeGraphPath(node.filePath)]=node}function appendEdgeFast(graph,edge,seenEdgeKeys){validateGraphEdge(edge);let key=buildLoopEdgeKey(edge);if(seenEdgeKeys.has(key))return;seenEdgeKeys.add(key),graph.edges.push(edge)}function resolveModuleSpecifier(workspaceRoot,sourceFile,specifier){if(containsControlChars(specifier))return null;if(specifier.startsWith("/")||specifier.startsWith("\\"))return null;if(/^[A-Za-z]:[/\\]/.test(specifier))return null;if(specifier.startsWith("http://")||specifier.startsWith("https://"))return null;try{let normalizedSpecifier=specifier,rustParts=specifier.split("::").filter(Boolean);if(rustParts[0]==="crate"){let target=path137.join(workspaceRoot,...rustParts.slice(1));if(!(existsSync77(target)||existsSync77(`${target}.rs`)||existsSync77(path137.join(target,"mod.rs"))))target=path137.join(path137.dirname(sourceFile),...rustParts.slice(1));if(normalizedSpecifier=path137.relative(path137.dirname(sourceFile),target).replace(/\\/g,"/"),!normalizedSpecifier.startsWith("."))normalizedSpecifier=`./${normalizedSpecifier}`}else if(rustParts[0]==="self")normalizedSpecifier=`./${rustParts.slice(1).join("/")}`;else if(rustParts[0]==="super"){let superCount=0;while(rustParts[superCount]==="super")superCount++;normalizedSpecifier=`${"../".repeat(superCount)}${rustParts.slice(superCount).join("/")}`}if(normalizedSpecifier.startsWith(".")){let sourceDir=path137.dirname(sourceFile),resolved=path137.resolve(sourceDir,normalizedSpecifier),initialRealResolved=_internals83.safeRealpathSync(resolved,resolved);if(initialRealResolved===null)return null;let realResolved=initialRealResolved,realRoot=_internals83.safeRealpathSync(workspaceRoot,path137.normalize(workspaceRoot));if(realRoot===null)return null;let findDirectoryEntry=(directory)=>{for(let initName of["__init__.py","__init__.pyw","mod.rs"]){let candidate=path137.join(directory,initName);if(existsSync77(candidate))return candidate}if(path137.extname(sourceFile).toLowerCase()===".go"){let basenameCandidate=path137.join(directory,`${path137.basename(directory)}.go`);if(existsSync77(basenameCandidate))return basenameCandidate;try{let firstGo=fsSync8.readdirSync(directory).filter((entry)=>entry.endsWith(".go")&&!entry.endsWith("_test.go")).sort((a,b)=>a.localeCompare(b))[0];if(firstGo)return path137.join(directory,firstGo)}catch{return null}}return null};if(existsSync77(resolved))try{if(fsSync8.statSync(resolved).isDirectory()){let found=findDirectoryEntry(resolved);if(!found)return null;let foundRealPath=_internals83.safeRealpathSync(found,found);if(foundRealPath===null)return null;realResolved=foundRealPath,resolved=found}}catch{return null}if(!existsSync77(resolved)){let EXTENSIONS=path137.extname(sourceFile).toLowerCase()===".pyw"?[".pyw",".py",".rs",".go",".ts",".tsx",".js",".jsx",".mjs",".cjs",".json"]:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".rs",".go",".json"],found=null;for(let ext of EXTENSIONS){let candidate=resolved+ext;if(existsSync77(candidate)){found=candidate;break}}if(!found)found=findDirectoryEntry(resolved);if(found){let foundRealPath=_internals83.safeRealpathSync(found,found);if(foundRealPath===null)return null;realResolved=foundRealPath,resolved=found}else return null}let normalizedResolved=path137.normalize(realResolved),normalizedRoot=path137.normalize(realRoot);if(!normalizedResolved.startsWith(normalizedRoot+path137.sep)&&normalizedResolved!==normalizedRoot)return null;return resolved}return null}catch{return null}}function isRefusedWorkspaceRoot(target){let resolved;try{resolved=realpathSync15(target)}catch{resolved=path137.resolve(target)}let refused=new Set,add2=(p)=>{if(typeof p==="string"&&p.length>0)refused.add(path137.resolve(p))};if(add2(os20.homedir()),add2(os20.tmpdir()),add2("/"),add2("/Users"),add2("/home"),add2("/root"),process.platform==="win32")add2("C:\\"),add2("C:\\Users");return refused.has(resolved)}function createEmptyDiagnostics(){return{extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],lowConfidenceEdgeCount:0}}function diagnosticsHaveEntries(diagnostics){return(diagnostics.extractionFailures?.length??0)>0||(diagnostics.unresolvedImports?.length??0)>0||(diagnostics.oversizedFiles?.length??0)>0||(diagnostics.unsupportedFiles?.length??0)>0||(diagnostics.binaryFiles?.length??0)>0||(diagnostics.unreadableFiles?.length??0)>0||(diagnostics.lowConfidenceEdgeCount??0)>0}function pushCapped(target,value){if(target.length<MAX_DIAGNOSTIC_ENTRIES)target.push(value)}function mergeDiagnostics(target,source){if(!source)return;for(let entry of source.extractionFailures??[])pushCapped(target.extractionFailures,entry);for(let entry of source.unresolvedImports??[])pushCapped(target.unresolvedImports,entry);for(let entry of source.oversizedFiles??[])pushCapped(target.oversizedFiles,entry);for(let entry of source.unsupportedFiles??[])pushCapped(target.unsupportedFiles,entry);for(let entry of source.binaryFiles??[])pushCapped(target.binaryFiles,entry);for(let entry of source.unreadableFiles??[])pushCapped(target.unreadableFiles,entry);target.lowConfidenceEdgeCount+=source.lowConfidenceEdgeCount??0}function isRelativeImportSpecifier(specifier){return specifier==="."||specifier===".."||specifier.startsWith("./")||specifier.startsWith("../")}function unresolvedRelativeImportsFor(parsedImports,filePath,absoluteRoot){let unresolved=[],moduleName=toModuleName(filePath,absoluteRoot);for(let parsed of parsedImports){if(!isRelativeImportSpecifier(parsed.specifier))continue;if(resolveModuleSpecifier(absoluteRoot,filePath,parsed.specifier)===null)unresolved.push({file:moduleName,specifier:parsed.specifier})}return unresolved}var REGEX_ALLOWED_AFTER=new Set("(,=:[!&|?{};*+-~^<>%".split(""));function stripComments2(content){let out="",i=0,n=content.length,state="code",prevSignificant="",regexInClass=!1;while(i<n){let ch=content[i],next=i+1<n?content[i+1]:"";switch(state){case"code":if(ch==="/"&&next==="/")state="line",i+=2;else if(ch==="/"&&next==="*")state="block",i+=2;else if(ch==="/"&&REGEX_ALLOWED_AFTER.has(prevSignificant))state="regex",regexInClass=!1,out+=ch,i+=1;else{if(ch==="'")state="single";else if(ch==='"')state="double";else if(ch==="`")state="template";if(out+=ch,ch.trim()!=="")prevSignificant=ch;i+=1}break;case"single":case"double":case"template":{let quote=state==="single"?"'":state==="double"?'"':"`";if(ch==="\\")out+=ch+next,i+=2;else{if(ch===quote)state="code",prevSignificant=quote;out+=ch,i+=1}break}case"regex":if(ch==="\\")out+=ch+next,i+=2;else if(ch===`
5317
5352
  `)state="code",out+=ch,i+=1;else{if(ch==="[")regexInClass=!0;else if(ch==="]")regexInClass=!1;else if(ch==="/"&&!regexInClass)state="code",prevSignificant="/";out+=ch,i+=1}break;case"line":if(ch===`
5318
5353
  `)state="code",out+=ch;i+=1;break;case"block":if(ch==="*"&&next==="/")state="code",i+=2;else{if(ch===`
5319
- `)out+=ch;i+=1}break}}return out}function parseFileImports(rawContent){let imports=[],content=stripComments2(rawContent),importRegex=/import\s+(?:\{[\s\S]*?\}|(?:\*\s+as\s+\w+)|\w+)\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s+['"`]([^'"`\0\t\r\n]+)['"`]|require\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)|export\s*\{[^}]*\}\s*from\s+['"`]([^'"`\0\t\r\n]+)['"`]|export\s+\*(?:\s+as\s+\w+)?\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)/g;for(let match of content.matchAll(importRegex)){let modulePath=match[1]||match[2]||match[3]||match[4]||match[5]||match[6];if(!modulePath)continue;if(containsControlChars(modulePath))continue;let matchedString=match[0],importType="named";if(matchedString.includes("* as"))importType="namespace";else if(/^import\s*\(/.test(matchedString))importType="sideeffect";else if(/^export\s*\{/.test(matchedString))importType="named";else if(/^export\s+\*/.test(matchedString))importType="namespace";else if(/^import\s+\{/.test(matchedString))importType="named";else if(/^import\s+\w+\s+from\s+['"`]/.test(matchedString))importType="default";else if(/^import\s+['"`]/m.test(matchedString))importType="sideeffect";else if(matchedString.includes("require("))importType="require";imports.push({specifier:modulePath,importType,importedSymbols:parseImportedSymbols(matchedString,importType),bindings:parseImportBindings(matchedString,importType),reExport:/^\s*export\b/.test(matchedString)})}return imports}function parseImportBindings(matchedString,importType){if(importType==="namespace")return[];if(importType==="default"){let defaultMatch=matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/);return defaultMatch?[{imported:"default",local:defaultMatch[1]}]:[]}if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let bindings=[],seen=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim().replace(/^type\s+/,"");if(!part)continue;let aliasSplit=part.split(/\s+as\s+/i),imported=aliasSplit[0].trim(),local=(aliasSplit[1]??aliasSplit[0]).trim();if(!/^[A-Za-z_$][\w$]*$/.test(imported))continue;if(!/^[A-Za-z_$][\w$]*$/.test(local))continue;if(seen.has(imported))continue;seen.add(imported),bindings.push({imported,local})}return bindings}var SAFE_USAGE_IDENTIFIER=/^[A-Za-z_][A-Za-z0-9_]*$/;function computeUsedSymbols(strippedContent,bindings){if(bindings.length===0)return[];let used=new Set;for(let binding of bindings){if(!SAFE_USAGE_IDENTIFIER.test(binding.local)){used.add(binding.imported);continue}let re=new RegExp(`\\b${binding.local}\\b`,"g"),count=0;for(let _match of strippedContent.matchAll(re))if(count++,count>1)break;if(count>1)used.add(binding.imported)}return[...used].sort((a,b)=>a.localeCompare(b))}function usedSymbolsForImport(parsed,strippedContent){if(parsed.importType==="namespace"||parsed.importType==="sideeffect"||parsed.importType==="require")return;if(parsed.reExport)return[...new Set(parsed.bindings.map((b)=>b.imported))].sort((a,b)=>a.localeCompare(b));return computeUsedSymbols(strippedContent,parsed.bindings)}function collectExports(symbols2){let exported=symbols2.filter((s)=>s.exported),exports=exported.map((s)=>s.signature===`default ${s.name}`?"default":s.name),exportLines={};for(let i=0;i<exported.length;i++){let s=exported[i],name=exports[i];if(typeof s.line==="number"&&Number.isFinite(s.line)&&exportLines[name]===void 0)exportLines[name]=s.line}return{exports,exportLines}}function parseImportedSymbols(matchedString,importType){if(importType==="namespace")return["*"];if(importType==="default")return matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/)?["default"]:[];if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let symbols2=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim();if(!part)continue;let cleaned=part.replace(/^type\s+/,"").split(/\s+as\s+/i)[0].trim();if(/^[A-Za-z_$][\w$]*$/.test(cleaned))symbols2.add(cleaned)}return[...symbols2].sort((a,b)=>a.localeCompare(b))}function isWalkBudgetExceeded(ctx){if(ctx.abortReason!==void 0)return!0;if(Date.now()-ctx.startedAt>ctx.walkBudgetMs)return ctx.abortReason="budget",!0;return!1}function isFileCapReached(ctx,filesLength){if(filesLength>=ctx.maxFiles)return ctx.abortReason="cap",!0;return!1}async function canonicalDirKeyAsync(dir){try{return await fsPromises5.realpath(dir)}catch{return null}}async function findSourceFilesAsync(dir,stats2,options){let ctx={stats:stats2,seenRealPaths:new Set,startedAt:Date.now(),walkBudgetMs:options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,maxFiles:options?.maxFiles??DEFAULT_WALK_FILE_CAP,followSymlinks:options?.followSymlinks??!1,skipDirs:resolveSkipDirectories(options?.excludeDirs)},files=[],queue=[dir],processed=0;while(queue.length>0){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;let current=queue.shift(),key=await canonicalDirKeyAsync(current);if(key!==null){if(ctx.seenRealPaths.has(key)){ctx.stats.skippedDirs++;continue}ctx.seenRealPaths.add(key)}let entries;try{entries=await fsPromises5.readdir(current,{withFileTypes:!0})}catch{continue}entries.sort((a,b)=>a.name.toLowerCase().localeCompare(b.name.toLowerCase()));for(let entry of entries){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;if(ctx.skipDirs.has(entry.name)){ctx.stats.skippedDirs++;continue}let fullPath=path137.join(current,entry.name);if(entry.isSymbolicLink()&&!ctx.followSymlinks){ctx.stats.skippedDirs++;continue}if(entry.isDirectory())queue.push(fullPath);else if(entry.isFile()){let ext=path137.extname(fullPath).toLowerCase();if(SUPPORTED_EXTENSIONS.has(ext))files.push(fullPath)}if(processed++,processed%ASYNC_WALK_YIELD_INTERVAL===0)await yieldToEventLoop()}}if(ctx.abortReason==="cap"||ctx.abortReason==="budget")ctx.stats.truncated=!0;return files}function toModuleName(filePath,workspaceRoot){return path137.relative(workspaceRoot,filePath).split(path137.sep).join("/")}function getLanguage(filePath){let ext=path137.extname(filePath).toLowerCase(),jsFamilyLanguage=JS_FAMILY_EXTENSION_TO_LANGUAGE[ext];if(jsFamilyLanguage)return jsFamilyLanguage;return EXTENSION_TO_LANGUAGE[ext]??"unknown"}function isBinaryContent(content){if(content.includes("\x00"))return!0;return!1}function scanFile(filePath,absoluteRoot,maxFileSize){let content,fileStats;try{if(fileStats=fsSync8.statSync(filePath),fileStats.size>maxFileSize)return{node:null,edges:[]};content=fsSync8.readFileSync(filePath,"utf-8")}catch{return{node:null,edges:[]}}if(isBinaryContent(content))return{node:null,edges:[]};let ext=path137.extname(filePath).toLowerCase(),exports=[],exportLines={};try{if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(ext)){let relativePath=path137.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals83.extractTSSymbols(relativePath,absoluteRoot)))}else if(ext===".py"){let relativePath=path137.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals83.extractPythonSymbols(relativePath,absoluteRoot)))}let parsedImports=_internals83.parseFileImports(content),strippedForUsage=parsedImports.length>0?_internals83.stripComments(content):"",moduleName=toModuleName(filePath,absoluteRoot),node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},imports:parsedImports.map((p)=>p.specifier),language:getLanguage(filePath),mtime:fileStats.mtime.toISOString(),ontology:_internals83.extractFileOntology({moduleName,filePath,content,language:getLanguage(filePath),exports,imports:parsedImports.map((p)=>p.specifier)})},edges=[],sortedImports=[...parsedImports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let parsed of sortedImports){let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,parsed.specifier);if(resolvedTarget!==null){let usedSymbols=usedSymbolsForImport(parsed,strippedForUsage);edges.push({source:filePath,target:resolvedTarget,importSpecifier:parsed.specifier,importType:parsed.importType,importedSymbols:parsed.importedSymbols,...usedSymbols!==void 0?{usedSymbols}:{}})}}return{node,edges}}catch{return{node:null,edges:[]}}}async function scanFileAsync(filePath,absoluteRoot,maxFileSize){let content,fileStats;try{if(fileStats=fsSync8.statSync(filePath),fileStats.size>maxFileSize)return{node:null,edges:[],symbolEdges:[],diagnostics:{oversizedFiles:[toModuleName(filePath,absoluteRoot)]}};content=fsSync8.readFileSync(filePath,"utf-8")}catch{return{node:null,edges:[],symbolEdges:[],diagnostics:{unreadableFiles:[toModuleName(filePath,absoluteRoot)]}}}if(isBinaryContent(content))return{node:null,edges:[],symbolEdges:[],diagnostics:{binaryFiles:[toModuleName(filePath,absoluteRoot)]}};let grammarId=getLanguage(filePath),facts=await _internals83.extractFileSymbols(grammarId,content);if(facts===null){let fallback=scanFile(filePath,absoluteRoot,maxFileSize),parsedImports=[];try{parsedImports=_internals83.parseFileImports(content)}catch{parsedImports=[]}return{...fallback,symbolEdges:[],diagnostics:{extractionFailures:[{file:toModuleName(filePath,absoluteRoot),language:grammarId,reason:"symbol_extraction_failed"}],unresolvedImports:unresolvedRelativeImportsFor(parsedImports,filePath,absoluteRoot)}}}let exportedDefs=facts.defs.filter((d)=>d.exported),exports=exportedDefs.map((d)=>d.name),exportLines={},exportRanges={};for(let d of exportedDefs)exportLines[d.name]=d.startLine,exportRanges[d.name]={startLine:d.startLine,endLine:d.endLine};let exportsSet=new Set(exports);for(let imp of facts.imports){if(!imp.reExport||!imp.exportedBindings)continue;for(let binding of imp.exportedBindings){if(binding.imported==="*"){if(!exportsSet.has(binding.exported))exportsSet.add(binding.exported),exports.push(binding.exported);if(imp.startLine!==void 0&&exportLines[binding.exported]===void 0)exportLines[binding.exported]=imp.startLine;if(imp.startLine!==void 0&&imp.endLine!==void 0&&exportRanges[binding.exported]===void 0)exportRanges[binding.exported]={startLine:imp.startLine,endLine:imp.endLine};continue}if(!exportsSet.has(binding.exported))exportsSet.add(binding.exported),exports.push(binding.exported);if(imp.startLine!==void 0&&exportLines[binding.exported]===void 0)exportLines[binding.exported]=imp.startLine;if(imp.startLine!==void 0&&imp.endLine!==void 0&&exportRanges[binding.exported]===void 0)exportRanges[binding.exported]={startLine:imp.startLine,endLine:imp.endLine}}}let imports=facts.imports.map((i)=>i.specifier),moduleName=toModuleName(filePath,absoluteRoot),language=grammarId,node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},...Object.keys(exportRanges).length>0?{exportRanges}:{},imports,language,mtime:fileStats.mtime.toISOString(),ontology:_internals83.extractFileOntology({moduleName,filePath,content,language,exports,imports})},edges=[],sortedImports=[...facts.imports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let imp of sortedImports){let edgeImportType=imp.importType==="commonjs"?"require":imp.importType,resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(resolvedTarget!==null){let usedBindings=imp.reExport?imp.bindings:imp.bindings.filter((b)=>facts.refs.some((r)=>r.identifier===b.local)),usedSymbols=edgeImportType!=="namespace"&&edgeImportType!=="require"&&edgeImportType!=="sideeffect"?usedBindings.map((b)=>b.imported):void 0;edges.push({source:filePath,target:resolvedTarget,importSpecifier:imp.specifier,importType:edgeImportType,importedSymbols:imp.bindings.map((b)=>b.imported),...usedSymbols!==void 0?{usedSymbols}:{}})}}let unresolvedImports=sortedImports.filter((imp)=>isRelativeImportSpecifier(imp.specifier)).filter((imp)=>resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier)===null).map((imp)=>({file:moduleName,specifier:imp.specifier})),symbolEdges=[],localToImported=new Map;for(let imp of facts.imports){if(imp.reExport)continue;for(let binding of imp.bindings)localToImported.set(binding.local,{specifier:imp.specifier,imported:binding.imported})}let seenSymbolEdgeKeys=new Set;for(let ref of facts.refs){let mapping=localToImported.get(ref.identifier);if(!mapping)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,mapping.specifier);if(!resolvedTarget)continue;let fromSymbol=ref.enclosingDecl??"<module>",key=filePath+"\x00"+fromSymbol+"\x00"+resolvedTarget+"\x00"+mapping.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol,toFile:resolvedTarget,toSymbol:mapping.imported})}for(let imp of facts.imports){if(!imp.reExport||!imp.exportedBindings)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(!resolvedTarget)continue;for(let binding of imp.exportedBindings){if(binding.imported==="*")continue;let key=filePath+"\x00"+binding.exported+"\x00"+resolvedTarget+"\x00"+binding.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol:binding.exported,toFile:resolvedTarget,toSymbol:binding.imported})}}return{node,edges,symbolEdges,diagnostics:unresolvedImports.length>0?{unresolvedImports}:void 0}}async function buildWorkspaceGraphAsync(workspaceRoot,options){validateWorkspace(workspaceRoot);let maxFileSize=options?.maxFileSizeBytes??1048576,maxFiles=options?.maxFiles??DEFAULT_WALK_FILE_CAP,walkBudgetMs=options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,followSymlinks=options?.followSymlinks??!1,absoluteRoot=path137.resolve(workspaceRoot);if(!existsSync77(absoluteRoot))throw Error(`Workspace directory does not exist: ${workspaceRoot}`);if(isRefusedWorkspaceRoot(absoluteRoot))throw Error(`Refusing to scan top-level system path as workspace: ${absoluteRoot}. Set workspaceRoot to a project directory.`);let graph=createEmptyGraph(workspaceRoot),stats2={filesScanned:0,skippedDirs:0,skippedFiles:0,truncated:!1},diagnostics=createEmptyDiagnostics(),sourceFiles=await findSourceFilesAsync(absoluteRoot,stats2,{walkBudgetMs,maxFiles,followSymlinks,excludeDirs:options?.excludeDirs});if(sourceFiles.sort((a,b)=>{let normA=normalizeGraphPath(a),normB=normalizeGraphPath(b);return normA.localeCompare(normB)}),stats2.truncated)warn(`[repo-graph] Walk truncated: collected ${sourceFiles.length} files within ${walkBudgetMs}ms / ${maxFiles}-file budget.`);let seenEdges=new Set,seenSymbolEdges=new Set,allSymbolEdges=[],processedSinceYield=0;for(let filePath of sourceFiles){let result=await scanFileAsync(filePath,absoluteRoot,maxFileSize);if(mergeDiagnostics(diagnostics,result.diagnostics),result.node){let appended=!1;try{appendNodeFast(graph,result.node),appended=!0}catch{stats2.skippedFiles++}if(appended){for(let edge of result.edges)try{appendEdgeFast(graph,edge,seenEdges)}catch{}for(let symbolEdge of result.symbolEdges){let key=symbolEdge.fromFile+"\x00"+symbolEdge.fromSymbol+"\x00"+symbolEdge.toFile+"\x00"+symbolEdge.toSymbol;if(!seenSymbolEdges.has(key))seenSymbolEdges.add(key),allSymbolEdges.push(symbolEdge)}stats2.filesScanned++}}else stats2.skippedFiles++;if(processedSinceYield++,processedSinceYield%ASYNC_WALK_YIELD_INTERVAL===0)await yieldToEventLoop()}if(graph.metadata={generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length},allSymbolEdges.length>0)graph.symbolEdges=allSymbolEdges;if(graph.diagnostics=diagnosticsHaveEntries(diagnostics)?diagnostics:createEmptyDiagnostics(),stats2.skippedFiles>0||stats2.skippedDirs>0||stats2.truncated)log(`[repo-graph] Scan stats: ${stats2.filesScanned} files scanned, ${stats2.skippedFiles} files skipped, ${stats2.skippedDirs} dirs skipped`+(stats2.truncated?", TRUNCATED":""));return graph}import*as path138 from"node:path";var graphCache=new Map,dirtyFlags=new Map,mtimeCache=new Map;function getCachedGraph(workspace){return graphCache.get(path138.normalize(workspace))}function setCachedGraph(workspace,graph,mtime){let normalized=path138.normalize(workspace);if(graphCache.set(normalized,graph),dirtyFlags.set(normalized,!1),mtime!==void 0)mtimeCache.set(normalized,mtime)}function isDirty(workspace){return dirtyFlags.get(path138.normalize(workspace))??!1}function clearCache(workspace){let normalized=path138.normalize(workspace);graphCache.delete(normalized),dirtyFlags.delete(normalized),mtimeCache.delete(normalized)}function getCachedMtime(workspace){return mtimeCache.get(path138.normalize(workspace))}init_logger();init_path_security();import{existsSync as existsSync79}from"node:fs";import*as fsPromises7 from"node:fs/promises";import*as path141 from"node:path";init_path_security();import*as fsSync9 from"node:fs";import*as path139 from"node:path";var GRAPH_HEALTH_OUTPUT_LIMIT=50,MAX_HEALTH_PATH_LENGTH=500,cachedReverseIndex=null;function normalizeLookupPath(input){return normalizeGraphPath(input).replace(/^(?:\.\/)+/,"")}function graphRoot(graph){return path139.resolve(graph.workspaceRoot)}function toModuleName2(graph,input){let normalized=normalizeLookupPath(input);if(path139.isAbsolute(normalized)||/^[A-Za-z]:\//.test(normalized))return normalizeLookupPath(path139.relative(graphRoot(graph),normalized));return normalized}function absoluteKeyForModule(graph,moduleName){return normalizeGraphPath(path139.resolve(graphRoot(graph),moduleName))}function getGraphNode(graph,input){let moduleName=toModuleName2(graph,input),direct=graph.nodes[absoluteKeyForModule(graph,moduleName)];if(direct)return direct;return getQueryIndexes(graph).moduleNameIndex.get(moduleName)}function moduleNameForEdgePath(graph,edgePath){let key=normalizeGraphPath(edgePath),node=graph.nodes[key];if(node)return normalizeLookupPath(node.moduleName);return normalizeLookupPath(path139.relative(graphRoot(graph),edgePath))}function buildReverseIndex(graph){let reverse=new Map,forward=new Map,moduleNameIndex=new Map;for(let node of Object.values(graph.nodes))moduleNameIndex.set(normalizeLookupPath(node.moduleName),node);for(let edge of graph.edges){let source=normalizeGraphPath(edge.source),target=normalizeGraphPath(edge.target),sourceRef={file:moduleNameForEdgePath(graph,edge.source),importType:edge.importType},targetRef={file:moduleNameForEdgePath(graph,edge.target),importType:edge.importType},reverseRefs=reverse.get(target);if(reverseRefs)reverseRefs.push(sourceRef);else reverse.set(target,[sourceRef]);let forwardRefs=forward.get(source);if(forwardRefs)forwardRefs.push(targetRef);else forward.set(source,[targetRef])}for(let refs of reverse.values())refs.sort((a,b)=>a.file.localeCompare(b.file));for(let refs of forward.values())refs.sort((a,b)=>a.file.localeCompare(b.file));return cachedReverseIndex={graph,index:reverse,forwardIndex:forward,moduleNameIndex},reverse}function getQueryIndexes(graph){if(cachedReverseIndex&&cachedReverseIndex.graph===graph)return cachedReverseIndex;return buildReverseIndex(graph),cachedReverseIndex}function getReverseIndex(graph){return getQueryIndexes(graph).index}function getForwardIndex(graph){return getQueryIndexes(graph).forwardIndex}function resetQueryCache(){cachedReverseIndex=null}function isGraphFresh(graph,maxAgeMs=300000){if(!graph)return!1;let built=Date.parse(graph.metadata?.generatedAt??"");if(!Number.isFinite(built))return!1;return Date.now()-built<=maxAgeMs}function isSafeHealthPath(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value)||containsPathTraversal(value))return!1;if(path139.isAbsolute(value)||/^[A-Za-z]:[\\/]/.test(value))return!1;return!0}function isSafeHealthText(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value))return!1;return!0}function cap(entries){return entries.slice(0,GRAPH_HEALTH_OUTPUT_LIMIT)}function sanitizeExtractionFailures(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.language)&&isSafeHealthText(entry.reason))entries.push({file:entry.file,language:entry.language,reason:entry.reason})}return cap(entries)}function sanitizeUnresolvedImports(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.specifier))entries.push({file:entry.file,specifier:entry.specifier})}return cap(entries)}function sanitizePathList(value){if(!Array.isArray(value))return[];return cap(value.filter(isSafeHealthPath))}function getStaleFiles(graph,workspaceRoot){let built=Date.parse(graph.metadata.generatedAt);if(!Number.isFinite(built))return[];let root=workspaceRoot??graph.workspaceRoot,stale=[];for(let node of Object.values(graph.nodes)){let moduleName=normalizeGraphPath(node.moduleName);if(!isSafeHealthPath(moduleName))continue;let filePath=path139.join(root,moduleName);try{if(fsSync9.statSync(filePath).mtimeMs>built){if(stale.push(moduleName),stale.length>=GRAPH_HEALTH_OUTPUT_LIMIT)break}}catch{}}return stale}function getGraphHealth(graph,workspaceRoot){if(!graph)return{schemaVersion:null,fresh:!1,staleFiles:[],extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],lowConfidenceEdgeCount:0,notes:['No repo graph found at .swarm/repo-graph.json. Run repo_map with action="build" first.']};let diagnostics=graph.diagnostics,fresh=isGraphFresh(graph),staleFiles=getStaleFiles(graph,workspaceRoot),notes=[];if(!fresh||staleFiles.length>0)notes.push('Graph is stale. Run repo_map with action="build" to refresh.');if(!diagnostics)notes.push('Graph has no recorded diagnostics. Rebuild with repo_map action="build" to collect health details.');let binaryFiles=sanitizePathList(diagnostics?.binaryFiles),binaryCount=binaryFiles.length;if(binaryCount>0)notes.push(`${binaryCount} binary files skipped during last build.`);let unreadableFiles=sanitizePathList(diagnostics?.unreadableFiles),unreadableCount=unreadableFiles.length;if(unreadableCount>0)notes.push(`${unreadableCount} unreadable files skipped during last build.`);return{schemaVersion:graph.schema_version,fresh,staleFiles,extractionFailures:sanitizeExtractionFailures(diagnostics?.extractionFailures),unresolvedImports:sanitizeUnresolvedImports(diagnostics?.unresolvedImports),oversizedFiles:sanitizePathList(diagnostics?.oversizedFiles),unsupportedFiles:sanitizePathList(diagnostics?.unsupportedFiles),binaryFiles,unreadableFiles,lowConfidenceEdgeCount:typeof diagnostics?.lowConfidenceEdgeCount==="number"&&Number.isFinite(diagnostics.lowConfidenceEdgeCount)&&diagnostics.lowConfidenceEdgeCount>0?Math.floor(diagnostics.lowConfidenceEdgeCount):0,notes}}function getImporters(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];return getReverseIndex(graph).get(normalizeGraphPath(node.filePath))??[]}function getDependencies(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];let sourceKey=normalizeGraphPath(node.filePath);return getForwardIndex(graph).get(sourceKey)??[]}function getSymbolConsumers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[];for(let edge of graph.edges){if(normalizeGraphPath(edge.target)!==targetKey)continue;let importedSymbols=edge.importedSymbols??[];if(edge.importType==="namespace"){refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:"*"});continue}if(importedSymbols.includes(symbolName))refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:symbolName})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}function getCallers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[],seen=new Set;for(let edge of graph.edges){if(normalizeGraphPath(edge.target)!==targetKey)continue;let file3=moduleNameForEdgePath(graph,edge.source);if(seen.has(file3))continue;if(edge.usedSymbols!==void 0){if(edge.usedSymbols.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"used"});continue}let imported=edge.importedSymbols??[];if(edge.importType==="namespace"||imported.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"imported"})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}var DEAD_EXPORT_EXCLUDED_ROLES=new Set(["api_route","cli_command","test_file","agent","hook","middleware"]);function getDeadExports(graph,options){if(!isSchemaVersionAtLeast(graph.schema_version,"1.1.0"))return{schemaSupported:!1,analyzedFiles:0,skippedUnresolvable:0,candidates:[],note:'Graph predates schema 1.1.0 (no usedSymbols data). Run repo_map action="build" to enable dead_exports.'};let usage=new Map;for(let edge of graph.edges){let target=normalizeGraphPath(edge.target),entry=usage.get(target);if(!entry)entry={used:new Set,unresolvable:!1},usage.set(target,entry);if(edge.importType==="namespace"||edge.importType==="sideeffect"||edge.importType==="require")entry.unresolvable=!0;else if(edge.usedSymbols)for(let symbol3 of edge.usedSymbols)entry.used.add(symbol3)}let reverse=getReverseIndex(graph),candidates=[],analyzedFiles=0,skippedUnresolvable=0;for(let node of Object.values(graph.nodes)){if(node.exports.length===0)continue;let key=normalizeGraphPath(node.filePath),importerCount=reverse.get(key)?.length??0;if(importerCount===0)continue;if((node.ontology?.roles??[]).some((r)=>DEAD_EXPORT_EXCLUDED_ROLES.has(r)))continue;let entry=usage.get(key);if(entry?.unresolvable){skippedUnresolvable++;continue}analyzedFiles++;let used=entry?.used??new Set;for(let symbol3 of node.exports){if(symbol3==="default")continue;if(used.has(symbol3))continue;candidates.push({file:node.moduleName,symbol:symbol3,line:node.exportLines?.[symbol3],importerCount})}}candidates.sort((a,b)=>a.file.localeCompare(b.file)||a.symbol.localeCompare(b.symbol));let limit=options?.maxCandidates??100,truncated=candidates.length>limit;return{schemaSupported:!0,analyzedFiles,skippedUnresolvable,candidates:candidates.slice(0,limit),note:"Advisory: exported symbols with no detected in-repo reference, limited to files imported by >=1 other file. Regex analysis cannot see dynamic dispatch, string-keyed access, or namespace/barrel re-export usage; verify before removing."+(truncated?` Showing ${limit} of ${candidates.length}.`:"")}}function getBlastRadius(graph,filePaths,maxDepth=3){let targetNodes=filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0),targets=targetNodes.map((node)=>normalizeLookupPath(node.moduleName));if(maxDepth<=0||targetNodes.length===0)return{target:filePaths.map((filePath)=>toModuleName2(graph,filePath)),directDependents:[],transitiveDependents:[],depthReached:0,totalDependents:0,riskLevel:"low"};let reverse=getReverseIndex(graph),visited=new Set(targetNodes.map((node)=>normalizeGraphPath(node.filePath))),direct=new Set,transitive=new Set,depthReached=0,queue=targetNodes.map((node)=>({key:normalizeGraphPath(node.filePath),depth:0}));while(queue.length>0){let next=[];for(let{key,depth}of queue){let importers=reverse.get(key)??[];for(let ref of importers){let importerNode=getGraphNode(graph,ref.file);if(!importerNode)continue;let importerKey=normalizeGraphPath(importerNode.filePath);if(visited.has(importerKey))continue;if(visited.add(importerKey),depth===0)direct.add(ref.file);else transitive.add(ref.file);if(depthReached=Math.max(depthReached,depth+1),depth+1<maxDepth)next.push({key:importerKey,depth:depth+1})}}queue=next}let totalDependents=direct.size+transitive.size;return{target:targets,directDependents:[...direct].sort(),transitiveDependents:[...transitive].sort(),depthReached,totalDependents,riskLevel:classifyRisk(totalDependents)}}function classifyRisk(count){if(count<=3)return"low";if(count<=10)return"medium";if(count<=25)return"high";return"critical"}function getKeyFiles(graph,topN=10){let reverse=getReverseIndex(graph),scored=Object.values(graph.nodes).map((node)=>({node,inDegree:reverse.get(normalizeGraphPath(node.filePath))?.length??0}));return scored.sort((a,b)=>{if(b.inDegree!==a.inDegree)return b.inDegree-a.inDegree;return a.node.moduleName.localeCompare(b.node.moduleName)}),scored.slice(0,topN).map((item)=>item.node)}function getFileOntology(graph,filePath){return getGraphNode(graph,filePath)?.ontology??null}function getLocalizationContext(graph,filePath,options={}){let target=toModuleName2(graph,filePath),node=getGraphNode(graph,target),importers=getImporters(graph,target),dependencies=getDependencies(graph,target),blast=getBlastRadius(graph,[target],options.maxDepth??2),externalSymbols=collectExternallyUsedSymbols(graph,node),summary=formatLocalizationSummary({target,importers,dependencies,blast,externalSymbols,ontology:node?.ontology??null,maxImporters:options.maxImporters??5,maxDeps:options.maxDeps??5});return{target,importerCount:importers.length,importers:importers.slice(0,options.maxImporters??5),dependencyCount:dependencies.length,dependencies:dependencies.slice(0,options.maxDeps??5),exportedSymbolsUsedExternally:externalSymbols,blastRadius:blast,summary}}function getContextPack(graph,file3,symbol3,options={}){if(!isSchemaVersionAtLeast(graph.schema_version,"1.2.0"))return{schemaSupported:!1,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:'rebuild with repo_map action="build"'};let maxDepth=options.maxDepth??2,maxTokens=options.maxTokens??4000,targetNode=getGraphNode(graph,file3);if(!targetNode)return{schemaSupported:!0,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:"Target file not found in graph"};let targetFile=normalizeGraphPath(targetNode.filePath),forward=new Map,reverse=new Map,symbolEdges=graph.symbolEdges??[];for(let edge of symbolEdges){let fromKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`,toKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`,fromEdges=forward.get(fromKey);if(fromEdges)fromEdges.push(edge);else forward.set(fromKey,[edge]);let toEdges=reverse.get(toKey);if(toEdges)toEdges.push(edge);else reverse.set(toKey,[edge])}let targetKey=`${targetFile}\x00${symbol3}`,visited=new Map,queue=[{key:targetKey,depth:0}];visited.set(targetKey,0);let reached=[],queueHead=0;while(queueHead<queue.length){let{key,depth}=queue[queueHead];queueHead++;let[curFile,curSymbol]=key.split("\x00",2);if(reached.push({file:curFile,symbol:curSymbol,depth}),depth>=maxDepth)continue;let outEdges=forward.get(key)??[];for(let edge of outEdges){let nextKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}let inEdges=reverse.get(key)??[];for(let edge of inEdges){let nextKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}}let TOKENS_PER_LINE=12,TOKENS_PER_SIGNATURE=10,spansWithDepth=[];for(let{file:symFile,symbol:sym,depth:d}of reached){let range=graph.nodes[symFile]?.exportRanges?.[sym];if(!range)continue;let mode=d===0?"full":d<maxDepth?"full":"signature";spansWithDepth.push({span:{file:symFile,symbol:sym,startLine:range.startLine,endLine:range.endLine,mode},depth:d})}spansWithDepth.sort((a,b)=>{let aIsTarget=a.span.file===targetFile&&a.span.symbol===symbol3?0:1,bIsTarget=b.span.file===targetFile&&b.span.symbol===symbol3?0:1;if(aIsTarget!==bIsTarget)return aIsTarget-bIsTarget;if(a.depth!==b.depth)return a.depth-b.depth;let fileCmp=a.span.file.localeCompare(b.span.file);if(fileCmp!==0)return fileCmp;return a.span.symbol.localeCompare(b.span.symbol)});let estimatedTokens=0,finalSpans=[],truncated=!1;for(let{span}of spansWithDepth){let spanTokens=span.mode==="full"?(span.endLine-span.startLine+1)*TOKENS_PER_LINE:TOKENS_PER_SIGNATURE;if(finalSpans.length>0&&estimatedTokens+spanTokens>maxTokens){truncated=!0;break}finalSpans.push(span),estimatedTokens+=spanTokens}return{schemaSupported:!0,target:{file:targetFile,symbol:symbol3},spans:finalSpans,truncated,estimatedTokens}}function collectExternallyUsedSymbols(graph,node){if(!node)return[];let exported=new Set(node.exports),used=new Set,targetKey=normalizeGraphPath(node.filePath);for(let edge of graph.edges){if(normalizeGraphPath(edge.target)!==targetKey)continue;for(let symbol3 of edge.importedSymbols??[])if(exported.has(symbol3))used.add(symbol3)}return[...used].sort((a,b)=>a.localeCompare(b))}function formatLocalizationSummary(opts){let importerList=opts.importers.length===0?"(none)":opts.importers.slice(0,opts.maxImporters).map((ref)=>ref.file).join(", ")+(opts.importers.length>opts.maxImporters?`, +${opts.importers.length-opts.maxImporters} more`:""),depList=opts.dependencies.length===0?"(none)":opts.dependencies.slice(0,opts.maxDeps).map((ref)=>ref.file).join(", ")+(opts.dependencies.length>opts.maxDeps?`, +${opts.dependencies.length-opts.maxDeps} more`:""),symbolList=opts.externalSymbols.length===0?"(none used externally)":opts.externalSymbols.slice(0,8).join(", ")+(opts.externalSymbols.length>8?`, +${opts.externalSymbols.length-8} more`:""),roles=opts.ontology?.roles.join(", ")||"unknown",findings=opts.ontology?.findings.length??0;return["LOCALIZATION CONTEXT",` Target: ${opts.target}`,` Roles: ${roles}`,` Imported by (${opts.importers.length}): ${importerList}`,` Imports (${opts.dependencies.length}): ${depList}`,` Exports used externally: ${symbolList}`,` Blast radius: ${opts.blast.totalDependents} files (${opts.blast.riskLevel} risk)`,` Ontology findings: ${findings}`].join(`
5354
+ `)out+=ch;i+=1}break}}return out}function parseFileImports(rawContent,sourceFile,workspaceRoot){let ext=sourceFile?path137.extname(sourceFile).toLowerCase():"";if(ext===".py"||ext===".pyw")return parsePythonFileImports(rawContent,sourceFile);if(ext===".rs")return parseRustFileImports(rawContent,sourceFile,workspaceRoot);if(ext===".go")return parseGoFileImports(rawContent);let imports=[],content=stripComments2(rawContent),importRegex=/import\s+(?:\{[\s\S]*?\}|(?:\*\s+as\s+\w+)|\w+)\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s+['"`]([^'"`\0\t\r\n]+)['"`]|require\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)|export\s*\{[^}]*\}\s*from\s+['"`]([^'"`\0\t\r\n]+)['"`]|export\s+\*(?:\s+as\s+\w+)?\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)/g;for(let match of content.matchAll(importRegex)){let modulePath=match[1]||match[2]||match[3]||match[4]||match[5]||match[6];if(!modulePath)continue;if(containsControlChars(modulePath))continue;let matchedString=match[0],importType="named";if(matchedString.includes("* as"))importType="namespace";else if(/^import\s*\(/.test(matchedString))importType="sideeffect";else if(/^export\s*\{/.test(matchedString))importType="named";else if(/^export\s+\*/.test(matchedString))importType="namespace";else if(/^import\s+\{/.test(matchedString))importType="named";else if(/^import\s+\w+\s+from\s+['"`]/.test(matchedString))importType="default";else if(/^import\s+['"`]/m.test(matchedString))importType="sideeffect";else if(matchedString.includes("require("))importType="require";imports.push({specifier:modulePath,importType,importedSymbols:parseImportedSymbols(matchedString,importType),bindings:parseImportBindings(matchedString,importType),reExport:/^\s*export\b/.test(matchedString)})}return imports}function makeParsedImport(specifier,importType,bindings,reExport=!1){if(!specifier||containsControlChars(specifier))return null;return{specifier,importType,importedSymbols:bindings.map((binding)=>binding.imported),bindings,reExport}}function parsePythonFileImports(rawContent,sourceFile){let imports=[],isPackageInit=sourceFile?["__init__.py","__init__.pyw"].includes(path137.basename(sourceFile)):!1;for(let line of rawContent.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let fullImport=trimmed.match(/^import\s+(.+?)(?:\s*#.*)?$/);if(fullImport){for(let rawPart of fullImport[1].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^([\w.]+)\s+as\s+(\w+)$/),specifier=alias?alias[1]:part,local=alias?alias[2]:specifier.split(".")[0];if(!/^\w+$/.test(local))continue;let parsed2=makeParsedImport(specifier,"namespace",[{imported:specifier,local}]);if(parsed2)imports.push(parsed2)}continue}let fromImport=trimmed.match(/^from\s+(\S+)\s+import\s+(.+?)(?:\s*#.*)?$/);if(!fromImport)continue;if(fromImport[2].trim()==="*"){let parsed2=makeParsedImport(normalizePythonModuleSpecifier2(fromImport[1]),"namespace",[],isPackageInit);if(parsed2)imports.push(parsed2);continue}let bindings=[];for(let rawPart of fromImport[2].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^\w+$/.test(part))bindings.push({imported:part,local:part})}let parsed=makeParsedImport(normalizePythonModuleSpecifier2(fromImport[1]),"named",bindings,isPackageInit);if(parsed)imports.push(parsed)}return imports}function normalizePythonModuleSpecifier2(specifier){let leadingDots=specifier.match(/^\.+/)?.[0].length??0;if(leadingDots===0)return specifier;let rest=specifier.slice(leadingDots).replace(/\./g,"/");return`${leadingDots===1?"./":"../".repeat(leadingDots-1)}${rest}`}function rustModulePathToSpecifier(modulePath,sourceFile,workspaceRoot){let parts=modulePath.split("::").filter(Boolean);if(parts.length===0)return modulePath;if(parts[0]==="self")return`./${parts.slice(1).join("/")}`;if(parts[0]==="super"){let superCount=0;while(parts[superCount]==="super")superCount++;return`${"../".repeat(superCount)}${parts.slice(superCount).join("/")}`}if(parts[0]==="crate"&&sourceFile&&workspaceRoot){let target=path137.join(workspaceRoot,...parts.slice(1)),relative22=path137.relative(path137.dirname(sourceFile),target).replace(/\\/g,"/");if(!relative22.startsWith("."))relative22=`./${relative22}`;return relative22}return modulePath}function parseRustFileImports(rawContent,sourceFile,workspaceRoot){let imports=[];for(let line of rawContent.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed.startsWith("use "))continue;let grouped=trimmed.match(/^use\s+(.+?)::\{(.+)\}\s*;?\s*$/);if(grouped){let specifier2=rustModulePathToSpecifier(grouped[1].trim(),sourceFile,workspaceRoot),bindings=[];for(let rawPart of grouped[2].split(",")){let part=rawPart.trim();if(!part)continue;let alias2=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias2)bindings.push({imported:alias2[1],local:alias2[2]});else if(/^\w+$/.test(part)){let local2=part==="self"?grouped[1].split("::").pop()||grouped[1]:part;bindings.push({imported:part,local:local2})}}let parsed2=makeParsedImport(specifier2,"named",bindings);if(parsed2)imports.push(parsed2);continue}let simple=trimmed.match(/^use\s+(.+?)\s*;?\s*$/);if(!simple)continue;let rawPath=simple[1].trim(),alias=rawPath.match(/^(.+?)\s+as\s+(\w+)$/),fullPath=(alias?alias[1]:rawPath).trim(),parts=fullPath.split("::").filter(Boolean),imported=parts.pop()??fullPath,specifier=rustModulePathToSpecifier(parts.join("::")||fullPath,sourceFile,workspaceRoot),local=alias?alias[2]:imported,parsed=makeParsedImport(specifier,"named",/^\w+$/.test(imported)&&/^\w+$/.test(local)?[{imported,local}]:[]);if(parsed)imports.push(parsed)}return imports}function parseGoFileImports(rawContent){let imports=[],content=stripComments2(rawContent),parseSpec=(text)=>{let spec=text.trim();if(!spec)return;let aliased=spec.match(/^([\w._]+)\s+["`]([^"`]+)["`]$/);if(aliased){if(aliased[1]==="_"){let parsed2=makeParsedImport(aliased[2],"sideeffect",[]);if(parsed2)imports.push(parsed2);return}if(aliased[1]==="."){let parsed2=makeParsedImport(aliased[2],"namespace",[{imported:"*",local:"."}]);if(parsed2)imports.push(parsed2);return}let parsed=makeParsedImport(aliased[2],"named",[{imported:aliased[2],local:aliased[1]}]);if(parsed)imports.push(parsed);return}let simple=spec.match(/^["`]([^"`]+)["`]$/);if(simple){let parsed=makeParsedImport(simple[1],"namespace",[]);if(parsed)imports.push(parsed)}};for(let block of content.matchAll(/import\s*\(([\s\S]*?)\)/g))for(let line of block[1].split(/\r?\n/))parseSpec(line);let withoutBlocks=content.replace(/import\s*\([\s\S]*?\)/g,"");for(let match of withoutBlocks.matchAll(/^\s*import\s+(.+)$/gm))parseSpec(match[1]);return imports}function parseImportBindings(matchedString,importType){if(importType==="namespace")return[];if(importType==="default"){let defaultMatch=matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/);return defaultMatch?[{imported:"default",local:defaultMatch[1]}]:[]}if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let bindings=[],seen=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim().replace(/^type\s+/,"");if(!part)continue;let aliasSplit=part.split(/\s+as\s+/i),imported=aliasSplit[0].trim(),local=(aliasSplit[1]??aliasSplit[0]).trim();if(!/^[A-Za-z_$][\w$]*$/.test(imported))continue;if(!/^[A-Za-z_$][\w$]*$/.test(local))continue;if(seen.has(imported))continue;seen.add(imported),bindings.push({imported,local})}return bindings}var SAFE_USAGE_IDENTIFIER=/^[A-Za-z_][A-Za-z0-9_]*$/;function computeUsedSymbols(strippedContent,bindings){if(bindings.length===0)return[];let used=new Set;for(let binding of bindings){if(!SAFE_USAGE_IDENTIFIER.test(binding.local)){used.add(binding.imported);continue}let re=new RegExp(`\\b${binding.local}\\b`,"g"),count=0;for(let _match of strippedContent.matchAll(re))if(count++,count>1)break;if(count>1)used.add(binding.imported)}return[...used].sort((a,b)=>a.localeCompare(b))}function usedSymbolsForImport(parsed,strippedContent){if(parsed.importType==="namespace"||parsed.importType==="sideeffect"||parsed.importType==="require")return;if(parsed.reExport)return[...new Set(parsed.bindings.map((b)=>b.imported))].sort((a,b)=>a.localeCompare(b));return computeUsedSymbols(strippedContent,parsed.bindings)}function collectExports(symbols2){let exported=symbols2.filter((s)=>s.exported),exports=exported.map((s)=>s.signature===`default ${s.name}`?"default":s.name),exportLines={};for(let i=0;i<exported.length;i++){let s=exported[i],name=exports[i];if(typeof s.line==="number"&&Number.isFinite(s.line)&&exportLines[name]===void 0)exportLines[name]=s.line}return{exports,exportLines}}function parseImportedSymbols(matchedString,importType){if(importType==="namespace")return["*"];if(importType==="default")return matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/)?["default"]:[];if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let symbols2=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim();if(!part)continue;let cleaned=part.replace(/^type\s+/,"").split(/\s+as\s+/i)[0].trim();if(/^[A-Za-z_$][\w$]*$/.test(cleaned))symbols2.add(cleaned)}return[...symbols2].sort((a,b)=>a.localeCompare(b))}function isWalkBudgetExceeded(ctx){if(ctx.abortReason!==void 0)return!0;if(Date.now()-ctx.startedAt>ctx.walkBudgetMs)return ctx.abortReason="budget",!0;return!1}function isFileCapReached(ctx,filesLength){if(filesLength>=ctx.maxFiles)return ctx.abortReason="cap",!0;return!1}async function canonicalDirKeyAsync(dir){try{return await fsPromises5.realpath(dir)}catch{return null}}async function findSourceFilesAsync(dir,stats2,options){let ctx={stats:stats2,seenRealPaths:new Set,startedAt:Date.now(),walkBudgetMs:options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,maxFiles:options?.maxFiles??DEFAULT_WALK_FILE_CAP,followSymlinks:options?.followSymlinks??!1,skipDirs:resolveSkipDirectories(options?.excludeDirs)},files=[],queue=[dir],processed=0;while(queue.length>0){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;let current=queue.shift(),key=await canonicalDirKeyAsync(current);if(key!==null){if(ctx.seenRealPaths.has(key)){ctx.stats.skippedDirs++;continue}ctx.seenRealPaths.add(key)}let entries;try{entries=await fsPromises5.readdir(current,{withFileTypes:!0})}catch{continue}entries.sort((a,b)=>a.name.toLowerCase().localeCompare(b.name.toLowerCase()));for(let entry of entries){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;if(ctx.skipDirs.has(entry.name)){ctx.stats.skippedDirs++;continue}let fullPath=path137.join(current,entry.name);if(entry.isSymbolicLink()&&!ctx.followSymlinks){ctx.stats.skippedDirs++;continue}if(entry.isDirectory())queue.push(fullPath);else if(entry.isFile()){let ext=path137.extname(fullPath).toLowerCase();if(SUPPORTED_EXTENSIONS.has(ext))files.push(fullPath)}if(processed++,processed%ASYNC_WALK_YIELD_INTERVAL===0)await yieldToEventLoop()}}if(ctx.abortReason==="cap"||ctx.abortReason==="budget")ctx.stats.truncated=!0;return files}function toModuleName(filePath,workspaceRoot){return path137.relative(workspaceRoot,filePath).split(path137.sep).join("/")}function getLanguage(filePath){let ext=path137.extname(filePath).toLowerCase(),jsFamilyLanguage=JS_FAMILY_EXTENSION_TO_LANGUAGE[ext];if(jsFamilyLanguage)return jsFamilyLanguage;return EXTENSION_TO_LANGUAGE[ext]??"unknown"}function isBinaryContent(content){if(content.includes("\x00"))return!0;return!1}function scanFile(filePath,absoluteRoot,maxFileSize){let content,fileStats;try{if(fileStats=fsSync8.statSync(filePath),fileStats.size>maxFileSize)return{node:null,edges:[]};content=fsSync8.readFileSync(filePath,"utf-8")}catch{return{node:null,edges:[]}}if(isBinaryContent(content))return{node:null,edges:[]};let ext=path137.extname(filePath).toLowerCase(),exports=[],exportLines={};try{if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(ext)){let relativePath=path137.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals83.extractTSSymbols(relativePath,absoluteRoot)))}else if(ext===".py"||ext===".pyw"){let relativePath=path137.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals83.extractPythonSymbols(relativePath,absoluteRoot)))}else if(ext===".rs"){let relativePath=path137.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals83.extractRustSymbols(relativePath,absoluteRoot)))}else if(ext===".go"){let relativePath=path137.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals83.extractGoSymbols(relativePath,absoluteRoot)))}let parsedImports=_internals83.parseFileImports(content,filePath,absoluteRoot),strippedForUsage=parsedImports.length>0?_internals83.stripComments(content):"",moduleName=toModuleName(filePath,absoluteRoot),node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},imports:parsedImports.map((p)=>p.specifier),language:getLanguage(filePath),mtime:fileStats.mtime.toISOString(),ontology:_internals83.extractFileOntology({moduleName,filePath,content,language:getLanguage(filePath),exports,imports:parsedImports.map((p)=>p.specifier)})},edges=[],sortedImports=[...parsedImports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let parsed of sortedImports){let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,parsed.specifier);if(resolvedTarget!==null){let usedSymbols=usedSymbolsForImport(parsed,strippedForUsage);edges.push({source:filePath,target:resolvedTarget,importSpecifier:parsed.specifier,importType:parsed.importType,importedSymbols:parsed.importedSymbols,...usedSymbols!==void 0?{usedSymbols}:{}})}}return{node,edges}}catch{return{node:null,edges:[]}}}async function scanFileAsync(filePath,absoluteRoot,maxFileSize){let content,fileStats;try{if(fileStats=fsSync8.statSync(filePath),fileStats.size>maxFileSize)return{node:null,edges:[],symbolEdges:[],diagnostics:{oversizedFiles:[toModuleName(filePath,absoluteRoot)]}};content=fsSync8.readFileSync(filePath,"utf-8")}catch{return{node:null,edges:[],symbolEdges:[],diagnostics:{unreadableFiles:[toModuleName(filePath,absoluteRoot)]}}}if(isBinaryContent(content))return{node:null,edges:[],symbolEdges:[],diagnostics:{binaryFiles:[toModuleName(filePath,absoluteRoot)]}};let grammarId=getLanguage(filePath),facts=await _internals83.extractFileSymbols(grammarId,content);if(facts===null){let fallback=scanFile(filePath,absoluteRoot,maxFileSize),parsedImports=[];try{parsedImports=_internals83.parseFileImports(content,filePath,absoluteRoot)}catch{parsedImports=[]}return{...fallback,symbolEdges:[],diagnostics:{extractionFailures:[{file:toModuleName(filePath,absoluteRoot),language:grammarId,reason:"symbol_extraction_failed"}],unresolvedImports:unresolvedRelativeImportsFor(parsedImports,filePath,absoluteRoot)}}}let exportedDefs=facts.defs.filter((d)=>d.exported),exports=exportedDefs.map((d)=>d.name),exportLines={},exportRanges={};for(let d of exportedDefs)exportLines[d.name]=d.startLine,exportRanges[d.name]={startLine:d.startLine,endLine:d.endLine};let exportsSet=new Set(exports),isPythonPackageInit=grammarId==="python"&&["__init__.py","__init__.pyw"].includes(path137.basename(filePath));for(let imp of facts.imports){let packageInitBindings=isPythonPackageInit&&imp.bindings.length>0?imp.bindings.filter((binding)=>!binding.local.startsWith("_")).map((binding)=>({imported:binding.imported,exported:binding.local})):[],exportedBindings=imp.reExport&&imp.exportedBindings?imp.exportedBindings:packageInitBindings;if(exportedBindings.length===0)continue;for(let binding of exportedBindings){if(binding.imported==="*"){if(!exportsSet.has(binding.exported))exportsSet.add(binding.exported),exports.push(binding.exported);if(imp.startLine!==void 0&&exportLines[binding.exported]===void 0)exportLines[binding.exported]=imp.startLine;if(imp.startLine!==void 0&&imp.endLine!==void 0&&exportRanges[binding.exported]===void 0)exportRanges[binding.exported]={startLine:imp.startLine,endLine:imp.endLine};continue}if(!exportsSet.has(binding.exported))exportsSet.add(binding.exported),exports.push(binding.exported);if(imp.startLine!==void 0&&exportLines[binding.exported]===void 0)exportLines[binding.exported]=imp.startLine;if(imp.startLine!==void 0&&imp.endLine!==void 0&&exportRanges[binding.exported]===void 0)exportRanges[binding.exported]={startLine:imp.startLine,endLine:imp.endLine}}}let imports=facts.imports.map((i)=>i.specifier),moduleName=toModuleName(filePath,absoluteRoot),language=grammarId,node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},...Object.keys(exportRanges).length>0?{exportRanges}:{},imports,language,mtime:fileStats.mtime.toISOString(),ontology:_internals83.extractFileOntology({moduleName,filePath,content,language,exports,imports})},edges=[],sortedImports=[...facts.imports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let imp of sortedImports){let edgeImportType=imp.importType==="commonjs"?"require":imp.importType,resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(resolvedTarget!==null){let usedBindings=imp.reExport?imp.bindings:imp.bindings.filter((b)=>facts.refs.some((r)=>r.identifier===b.local)),usedSymbols=edgeImportType!=="namespace"&&edgeImportType!=="require"&&edgeImportType!=="sideeffect"?usedBindings.map((b)=>b.imported):void 0;edges.push({source:filePath,target:resolvedTarget,importSpecifier:imp.specifier,importType:edgeImportType,importedSymbols:imp.bindings.map((b)=>b.imported),...usedSymbols!==void 0?{usedSymbols}:{}})}}let unresolvedImports=sortedImports.filter((imp)=>isRelativeImportSpecifier(imp.specifier)).filter((imp)=>resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier)===null).map((imp)=>({file:moduleName,specifier:imp.specifier})),symbolEdges=[],localToImported=new Map;for(let imp of facts.imports){if(imp.reExport)continue;for(let binding of imp.bindings)localToImported.set(binding.local,{specifier:imp.specifier,imported:binding.imported})}let seenSymbolEdgeKeys=new Set;for(let ref of facts.refs){let mapping=localToImported.get(ref.identifier);if(!mapping)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,mapping.specifier);if(!resolvedTarget)continue;let fromSymbol=ref.enclosingDecl??"<module>",key=filePath+"\x00"+fromSymbol+"\x00"+resolvedTarget+"\x00"+mapping.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol,toFile:resolvedTarget,toSymbol:mapping.imported})}for(let imp of facts.imports){let packageInitBindings=isPythonPackageInit&&imp.bindings.length>0?imp.bindings.filter((binding)=>!binding.local.startsWith("_")).map((binding)=>({imported:binding.imported,exported:binding.local})):[],exportedBindings=imp.reExport&&imp.exportedBindings?imp.exportedBindings:packageInitBindings;if(exportedBindings.length===0)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(!resolvedTarget)continue;for(let binding of exportedBindings){if(binding.imported==="*")continue;let key=filePath+"\x00"+binding.exported+"\x00"+resolvedTarget+"\x00"+binding.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol:binding.exported,toFile:resolvedTarget,toSymbol:binding.imported})}}return{node,edges,symbolEdges,diagnostics:unresolvedImports.length>0?{unresolvedImports}:void 0}}async function buildWorkspaceGraphAsync(workspaceRoot,options){validateWorkspace(workspaceRoot);let maxFileSize=options?.maxFileSizeBytes??1048576,maxFiles=options?.maxFiles??DEFAULT_WALK_FILE_CAP,walkBudgetMs=options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,followSymlinks=options?.followSymlinks??!1,absoluteRoot=path137.resolve(workspaceRoot);if(!existsSync77(absoluteRoot))throw Error(`Workspace directory does not exist: ${workspaceRoot}`);if(isRefusedWorkspaceRoot(absoluteRoot))throw Error(`Refusing to scan top-level system path as workspace: ${absoluteRoot}. Set workspaceRoot to a project directory.`);let graph=createEmptyGraph(workspaceRoot),stats2={filesScanned:0,skippedDirs:0,skippedFiles:0,truncated:!1},diagnostics=createEmptyDiagnostics(),sourceFiles=await findSourceFilesAsync(absoluteRoot,stats2,{walkBudgetMs,maxFiles,followSymlinks,excludeDirs:options?.excludeDirs});if(sourceFiles.sort((a,b)=>{let normA=normalizeGraphPath(a),normB=normalizeGraphPath(b);return normA.localeCompare(normB)}),stats2.truncated)warn(`[repo-graph] Walk truncated: collected ${sourceFiles.length} files within ${walkBudgetMs}ms / ${maxFiles}-file budget.`);let seenEdges=new Set,seenSymbolEdges=new Set,allSymbolEdges=[],processedSinceYield=0;for(let filePath of sourceFiles){let result=await scanFileAsync(filePath,absoluteRoot,maxFileSize);if(mergeDiagnostics(diagnostics,result.diagnostics),result.node){let appended=!1;try{appendNodeFast(graph,result.node),appended=!0}catch{stats2.skippedFiles++}if(appended){for(let edge of result.edges)try{appendEdgeFast(graph,edge,seenEdges)}catch{}for(let symbolEdge of result.symbolEdges){let key=symbolEdge.fromFile+"\x00"+symbolEdge.fromSymbol+"\x00"+symbolEdge.toFile+"\x00"+symbolEdge.toSymbol;if(!seenSymbolEdges.has(key))seenSymbolEdges.add(key),allSymbolEdges.push(symbolEdge)}stats2.filesScanned++}}else stats2.skippedFiles++;if(processedSinceYield++,processedSinceYield%ASYNC_WALK_YIELD_INTERVAL===0)await yieldToEventLoop()}if(graph.metadata={generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length},allSymbolEdges.length>0)graph.symbolEdges=allSymbolEdges;if(graph.diagnostics=diagnosticsHaveEntries(diagnostics)?diagnostics:createEmptyDiagnostics(),stats2.skippedFiles>0||stats2.skippedDirs>0||stats2.truncated)log(`[repo-graph] Scan stats: ${stats2.filesScanned} files scanned, ${stats2.skippedFiles} files skipped, ${stats2.skippedDirs} dirs skipped`+(stats2.truncated?", TRUNCATED":""));return graph}import*as path138 from"node:path";var graphCache=new Map,dirtyFlags=new Map,mtimeCache=new Map;function getCachedGraph(workspace){return graphCache.get(path138.normalize(workspace))}function setCachedGraph(workspace,graph,mtime){let normalized=path138.normalize(workspace);if(graphCache.set(normalized,graph),dirtyFlags.set(normalized,!1),mtime!==void 0)mtimeCache.set(normalized,mtime)}function isDirty(workspace){return dirtyFlags.get(path138.normalize(workspace))??!1}function clearCache(workspace){let normalized=path138.normalize(workspace);graphCache.delete(normalized),dirtyFlags.delete(normalized),mtimeCache.delete(normalized)}function getCachedMtime(workspace){return mtimeCache.get(path138.normalize(workspace))}init_logger();init_path_security();import{existsSync as existsSync79}from"node:fs";import*as fsPromises7 from"node:fs/promises";import*as path141 from"node:path";init_path_security();import*as fsSync9 from"node:fs";import*as path139 from"node:path";var GRAPH_HEALTH_OUTPUT_LIMIT=50,MAX_HEALTH_PATH_LENGTH=500,cachedReverseIndex=null;function normalizeLookupPath(input){return normalizeGraphPath(input).replace(/^(?:\.\/)+/,"")}function graphRoot(graph){return path139.resolve(graph.workspaceRoot)}function toModuleName2(graph,input){let normalized=normalizeLookupPath(input);if(path139.isAbsolute(normalized)||/^[A-Za-z]:\//.test(normalized))return normalizeLookupPath(path139.relative(graphRoot(graph),normalized));return normalized}function absoluteKeyForModule(graph,moduleName){return normalizeGraphPath(path139.resolve(graphRoot(graph),moduleName))}function getGraphNode(graph,input){let moduleName=toModuleName2(graph,input),direct=graph.nodes[absoluteKeyForModule(graph,moduleName)];if(direct)return direct;return getQueryIndexes(graph).moduleNameIndex.get(moduleName)}function moduleNameForEdgePath(graph,edgePath){let key=normalizeGraphPath(edgePath),node=graph.nodes[key];if(node)return normalizeLookupPath(node.moduleName);return normalizeLookupPath(path139.relative(graphRoot(graph),edgePath))}function buildReverseIndex(graph){let reverse=new Map,forward=new Map,moduleNameIndex=new Map;for(let node of Object.values(graph.nodes))moduleNameIndex.set(normalizeLookupPath(node.moduleName),node);for(let edge of graph.edges){let source=normalizeGraphPath(edge.source),target=normalizeGraphPath(edge.target),sourceRef={file:moduleNameForEdgePath(graph,edge.source),importType:edge.importType},targetRef={file:moduleNameForEdgePath(graph,edge.target),importType:edge.importType},reverseRefs=reverse.get(target);if(reverseRefs)reverseRefs.push(sourceRef);else reverse.set(target,[sourceRef]);let forwardRefs=forward.get(source);if(forwardRefs)forwardRefs.push(targetRef);else forward.set(source,[targetRef])}for(let refs of reverse.values())refs.sort((a,b)=>a.file.localeCompare(b.file));for(let refs of forward.values())refs.sort((a,b)=>a.file.localeCompare(b.file));return cachedReverseIndex={graph,index:reverse,forwardIndex:forward,moduleNameIndex},reverse}function getQueryIndexes(graph){if(cachedReverseIndex&&cachedReverseIndex.graph===graph)return cachedReverseIndex;return buildReverseIndex(graph),cachedReverseIndex}function getReverseIndex(graph){return getQueryIndexes(graph).index}function getForwardIndex(graph){return getQueryIndexes(graph).forwardIndex}function resetQueryCache(){cachedReverseIndex=null}function isGraphFresh(graph,maxAgeMs=300000){if(!graph)return!1;let built=Date.parse(graph.metadata?.generatedAt??"");if(!Number.isFinite(built))return!1;return Date.now()-built<=maxAgeMs}function isSafeHealthPath(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value)||containsPathTraversal(value))return!1;if(path139.isAbsolute(value)||/^[A-Za-z]:[\\/]/.test(value))return!1;return!0}function isSafeHealthText(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value))return!1;return!0}function cap(entries){return entries.slice(0,GRAPH_HEALTH_OUTPUT_LIMIT)}function sanitizeExtractionFailures(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.language)&&isSafeHealthText(entry.reason))entries.push({file:entry.file,language:entry.language,reason:entry.reason})}return cap(entries)}function sanitizeUnresolvedImports(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.specifier))entries.push({file:entry.file,specifier:entry.specifier})}return cap(entries)}function sanitizePathList(value){if(!Array.isArray(value))return[];return cap(value.filter(isSafeHealthPath))}function getStaleFiles(graph,workspaceRoot){let built=Date.parse(graph.metadata.generatedAt);if(!Number.isFinite(built))return[];let root=workspaceRoot??graph.workspaceRoot,stale=[];for(let node of Object.values(graph.nodes)){let moduleName=normalizeGraphPath(node.moduleName);if(!isSafeHealthPath(moduleName))continue;let filePath=path139.join(root,moduleName);try{if(fsSync9.statSync(filePath).mtimeMs>built){if(stale.push(moduleName),stale.length>=GRAPH_HEALTH_OUTPUT_LIMIT)break}}catch{}}return stale}function getGraphHealth(graph,workspaceRoot){if(!graph)return{schemaVersion:null,fresh:!1,staleFiles:[],extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],lowConfidenceEdgeCount:0,notes:['No repo graph found at .swarm/repo-graph.json. Run repo_map with action="build" first.']};let diagnostics=graph.diagnostics,fresh=isGraphFresh(graph),staleFiles=getStaleFiles(graph,workspaceRoot),notes=[];if(!fresh||staleFiles.length>0)notes.push('Graph is stale. Run repo_map with action="build" to refresh.');if(!diagnostics)notes.push('Graph has no recorded diagnostics. Rebuild with repo_map action="build" to collect health details.');let binaryFiles=sanitizePathList(diagnostics?.binaryFiles),binaryCount=binaryFiles.length;if(binaryCount>0)notes.push(`${binaryCount} binary files skipped during last build.`);let unreadableFiles=sanitizePathList(diagnostics?.unreadableFiles),unreadableCount=unreadableFiles.length;if(unreadableCount>0)notes.push(`${unreadableCount} unreadable files skipped during last build.`);return{schemaVersion:graph.schema_version,fresh,staleFiles,extractionFailures:sanitizeExtractionFailures(diagnostics?.extractionFailures),unresolvedImports:sanitizeUnresolvedImports(diagnostics?.unresolvedImports),oversizedFiles:sanitizePathList(diagnostics?.oversizedFiles),unsupportedFiles:sanitizePathList(diagnostics?.unsupportedFiles),binaryFiles,unreadableFiles,lowConfidenceEdgeCount:typeof diagnostics?.lowConfidenceEdgeCount==="number"&&Number.isFinite(diagnostics.lowConfidenceEdgeCount)&&diagnostics.lowConfidenceEdgeCount>0?Math.floor(diagnostics.lowConfidenceEdgeCount):0,notes}}function getImporters(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];return getReverseIndex(graph).get(normalizeGraphPath(node.filePath))??[]}function getDependencies(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];let sourceKey=normalizeGraphPath(node.filePath);return getForwardIndex(graph).get(sourceKey)??[]}function getSymbolConsumers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[];for(let edge of graph.edges){if(normalizeGraphPath(edge.target)!==targetKey)continue;let importedSymbols=edge.importedSymbols??[];if(edge.importType==="namespace"){refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:"*"});continue}if(importedSymbols.includes(symbolName))refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:symbolName})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}function getCallers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[],seen=new Set;for(let edge of graph.edges){if(normalizeGraphPath(edge.target)!==targetKey)continue;let file3=moduleNameForEdgePath(graph,edge.source);if(seen.has(file3))continue;if(edge.usedSymbols!==void 0){if(edge.usedSymbols.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"used"});continue}let imported=edge.importedSymbols??[];if(edge.importType==="namespace"||imported.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"imported"})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}var DEAD_EXPORT_EXCLUDED_ROLES=new Set(["api_route","cli_command","test_file","agent","hook","middleware"]);function getDeadExports(graph,options){if(!isSchemaVersionAtLeast(graph.schema_version,"1.1.0"))return{schemaSupported:!1,analyzedFiles:0,skippedUnresolvable:0,candidates:[],note:'Graph predates schema 1.1.0 (no usedSymbols data). Run repo_map action="build" to enable dead_exports.'};let usage=new Map;for(let edge of graph.edges){let target=normalizeGraphPath(edge.target),entry=usage.get(target);if(!entry)entry={used:new Set,unresolvable:!1},usage.set(target,entry);if(edge.importType==="namespace"||edge.importType==="sideeffect"||edge.importType==="require")entry.unresolvable=!0;else if(edge.usedSymbols)for(let symbol3 of edge.usedSymbols)entry.used.add(symbol3)}let reverse=getReverseIndex(graph),candidates=[],analyzedFiles=0,skippedUnresolvable=0;for(let node of Object.values(graph.nodes)){if(node.exports.length===0)continue;let key=normalizeGraphPath(node.filePath),importerCount=reverse.get(key)?.length??0;if(importerCount===0)continue;if((node.ontology?.roles??[]).some((r)=>DEAD_EXPORT_EXCLUDED_ROLES.has(r)))continue;let entry=usage.get(key);if(entry?.unresolvable){skippedUnresolvable++;continue}analyzedFiles++;let used=entry?.used??new Set;for(let symbol3 of node.exports){if(symbol3==="default")continue;if(used.has(symbol3))continue;candidates.push({file:node.moduleName,symbol:symbol3,line:node.exportLines?.[symbol3],importerCount})}}candidates.sort((a,b)=>a.file.localeCompare(b.file)||a.symbol.localeCompare(b.symbol));let limit=options?.maxCandidates??100,truncated=candidates.length>limit;return{schemaSupported:!0,analyzedFiles,skippedUnresolvable,candidates:candidates.slice(0,limit),note:"Advisory: exported symbols with no detected in-repo reference, limited to files imported by >=1 other file. Regex analysis cannot see dynamic dispatch, string-keyed access, or namespace/barrel re-export usage; verify before removing."+(truncated?` Showing ${limit} of ${candidates.length}.`:"")}}function getBlastRadius(graph,filePaths,maxDepth=3){let targetNodes=filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0),targets=targetNodes.map((node)=>normalizeLookupPath(node.moduleName));if(maxDepth<=0||targetNodes.length===0)return{target:filePaths.map((filePath)=>toModuleName2(graph,filePath)),directDependents:[],transitiveDependents:[],depthReached:0,totalDependents:0,riskLevel:"low"};let reverse=getReverseIndex(graph),visited=new Set(targetNodes.map((node)=>normalizeGraphPath(node.filePath))),direct=new Set,transitive=new Set,depthReached=0,queue=targetNodes.map((node)=>({key:normalizeGraphPath(node.filePath),depth:0}));while(queue.length>0){let next=[];for(let{key,depth}of queue){let importers=reverse.get(key)??[];for(let ref of importers){let importerNode=getGraphNode(graph,ref.file);if(!importerNode)continue;let importerKey=normalizeGraphPath(importerNode.filePath);if(visited.has(importerKey))continue;if(visited.add(importerKey),depth===0)direct.add(ref.file);else transitive.add(ref.file);if(depthReached=Math.max(depthReached,depth+1),depth+1<maxDepth)next.push({key:importerKey,depth:depth+1})}}queue=next}let totalDependents=direct.size+transitive.size;return{target:targets,directDependents:[...direct].sort(),transitiveDependents:[...transitive].sort(),depthReached,totalDependents,riskLevel:classifyRisk(totalDependents)}}function classifyRisk(count){if(count<=3)return"low";if(count<=10)return"medium";if(count<=25)return"high";return"critical"}function getKeyFiles(graph,topN=10){let reverse=getReverseIndex(graph),scored=Object.values(graph.nodes).map((node)=>({node,inDegree:reverse.get(normalizeGraphPath(node.filePath))?.length??0}));return scored.sort((a,b)=>{if(b.inDegree!==a.inDegree)return b.inDegree-a.inDegree;return a.node.moduleName.localeCompare(b.node.moduleName)}),scored.slice(0,topN).map((item)=>item.node)}function getFileOntology(graph,filePath){return getGraphNode(graph,filePath)?.ontology??null}function getLocalizationContext(graph,filePath,options={}){let target=toModuleName2(graph,filePath),node=getGraphNode(graph,target),importers=getImporters(graph,target),dependencies=getDependencies(graph,target),blast=getBlastRadius(graph,[target],options.maxDepth??2),externalSymbols=collectExternallyUsedSymbols(graph,node),summary=formatLocalizationSummary({target,importers,dependencies,blast,externalSymbols,ontology:node?.ontology??null,maxImporters:options.maxImporters??5,maxDeps:options.maxDeps??5});return{target,importerCount:importers.length,importers:importers.slice(0,options.maxImporters??5),dependencyCount:dependencies.length,dependencies:dependencies.slice(0,options.maxDeps??5),exportedSymbolsUsedExternally:externalSymbols,blastRadius:blast,summary}}function getContextPack(graph,file3,symbol3,options={}){if(!isSchemaVersionAtLeast(graph.schema_version,"1.2.0"))return{schemaSupported:!1,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:'rebuild with repo_map action="build"'};let maxDepth=options.maxDepth??2,maxTokens=options.maxTokens??4000,targetNode=getGraphNode(graph,file3);if(!targetNode)return{schemaSupported:!0,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:"Target file not found in graph"};let targetFile=normalizeGraphPath(targetNode.filePath),forward=new Map,reverse=new Map,symbolEdges=graph.symbolEdges??[];for(let edge of symbolEdges){let fromKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`,toKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`,fromEdges=forward.get(fromKey);if(fromEdges)fromEdges.push(edge);else forward.set(fromKey,[edge]);let toEdges=reverse.get(toKey);if(toEdges)toEdges.push(edge);else reverse.set(toKey,[edge])}let targetKey=`${targetFile}\x00${symbol3}`,visited=new Map,queue=[{key:targetKey,depth:0}];visited.set(targetKey,0);let reached=[],queueHead=0;while(queueHead<queue.length){let{key,depth}=queue[queueHead];queueHead++;let[curFile,curSymbol]=key.split("\x00",2);if(reached.push({file:curFile,symbol:curSymbol,depth}),depth>=maxDepth)continue;let outEdges=forward.get(key)??[];for(let edge of outEdges){let nextKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}let inEdges=reverse.get(key)??[];for(let edge of inEdges){let nextKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}}let TOKENS_PER_LINE=12,TOKENS_PER_SIGNATURE=10,spansWithDepth=[];for(let{file:symFile,symbol:sym,depth:d}of reached){let range=graph.nodes[symFile]?.exportRanges?.[sym];if(!range)continue;let mode=d===0?"full":d<maxDepth?"full":"signature";spansWithDepth.push({span:{file:symFile,symbol:sym,startLine:range.startLine,endLine:range.endLine,mode},depth:d})}spansWithDepth.sort((a,b)=>{let aIsTarget=a.span.file===targetFile&&a.span.symbol===symbol3?0:1,bIsTarget=b.span.file===targetFile&&b.span.symbol===symbol3?0:1;if(aIsTarget!==bIsTarget)return aIsTarget-bIsTarget;if(a.depth!==b.depth)return a.depth-b.depth;let fileCmp=a.span.file.localeCompare(b.span.file);if(fileCmp!==0)return fileCmp;return a.span.symbol.localeCompare(b.span.symbol)});let estimatedTokens=0,finalSpans=[],truncated=!1;for(let{span}of spansWithDepth){let spanTokens=span.mode==="full"?(span.endLine-span.startLine+1)*TOKENS_PER_LINE:TOKENS_PER_SIGNATURE;if(finalSpans.length>0&&estimatedTokens+spanTokens>maxTokens){truncated=!0;break}finalSpans.push(span),estimatedTokens+=spanTokens}return{schemaSupported:!0,target:{file:targetFile,symbol:symbol3},spans:finalSpans,truncated,estimatedTokens}}function collectExternallyUsedSymbols(graph,node){if(!node)return[];let exported=new Set(node.exports),used=new Set,targetKey=normalizeGraphPath(node.filePath);for(let edge of graph.edges){if(normalizeGraphPath(edge.target)!==targetKey)continue;for(let symbol3 of edge.importedSymbols??[])if(exported.has(symbol3))used.add(symbol3)}return[...used].sort((a,b)=>a.localeCompare(b))}function formatLocalizationSummary(opts){let importerList=opts.importers.length===0?"(none)":opts.importers.slice(0,opts.maxImporters).map((ref)=>ref.file).join(", ")+(opts.importers.length>opts.maxImporters?`, +${opts.importers.length-opts.maxImporters} more`:""),depList=opts.dependencies.length===0?"(none)":opts.dependencies.slice(0,opts.maxDeps).map((ref)=>ref.file).join(", ")+(opts.dependencies.length>opts.maxDeps?`, +${opts.dependencies.length-opts.maxDeps} more`:""),symbolList=opts.externalSymbols.length===0?"(none used externally)":opts.externalSymbols.slice(0,8).join(", ")+(opts.externalSymbols.length>8?`, +${opts.externalSymbols.length-8} more`:""),roles=opts.ontology?.roles.join(", ")||"unknown",findings=opts.ontology?.findings.length??0;return["LOCALIZATION CONTEXT",` Target: ${opts.target}`,` Roles: ${roles}`,` Imported by (${opts.importers.length}): ${importerList}`,` Imports (${opts.dependencies.length}): ${depList}`,` Exports used externally: ${symbolList}`,` Blast radius: ${opts.blast.totalDependents} files (${opts.blast.riskLevel} risk)`,` Ontology findings: ${findings}`].join(`
5320
5355
  `)}function getPackageBoundaries(graph,topN=25){return summarizePackageBoundaries(Object.values(graph.nodes),graph.edges,topN)}function summarizePackageBoundaries(nodes,edges,topN){let groups=new Map,ensure=(node)=>{let name=node.ontology?.packageBoundary||inferBoundary(node.moduleName),group=groups.get(name);if(!group)group={name,root:name,fileCount:0,roles:{},dependsOn:[],dependedOnBy:[],routeCount:0,dataOperationCount:0,findingCount:0,publicFiles:[]},groups.set(name,group);return group},boundaryByPath=new Map;for(let node of nodes){let group=ensure(node);boundaryByPath.set(normalizeGraphPath(node.filePath),group.name),group.fileCount++;let ontology=node.ontology;for(let role of ontology?.roles??["source_module"])group.roles[role]=(group.roles[role]??0)+1;if(group.routeCount+=ontology?.routes.length??0,group.dataOperationCount+=ontology?.dataOperations.length??0,group.findingCount+=ontology?.findings.length??0,node.exports.length>0)group.publicFiles.push(node.moduleName)}let dependsOn=new Map,dependedOnBy=new Map;for(let edge of edges){let sourceBoundary=boundaryByPath.get(normalizeGraphPath(edge.source)),targetBoundary=boundaryByPath.get(normalizeGraphPath(edge.target));if(!sourceBoundary||!targetBoundary||sourceBoundary===targetBoundary)continue;if(!dependsOn.has(sourceBoundary))dependsOn.set(sourceBoundary,new Set);if(!dependedOnBy.has(targetBoundary))dependedOnBy.set(targetBoundary,new Set);dependsOn.get(sourceBoundary)?.add(targetBoundary),dependedOnBy.get(targetBoundary)?.add(sourceBoundary)}for(let group of groups.values())group.dependsOn=[...dependsOn.get(group.name)??[]].sort(),group.dependedOnBy=[...dependedOnBy.get(group.name)??[]].sort(),group.publicFiles.sort((a,b)=>a.localeCompare(b)),group.publicFiles=group.publicFiles.slice(0,20);return[...groups.values()].sort((a,b)=>{if(b.findingCount!==a.findingCount)return b.findingCount-a.findingCount;if(b.fileCount!==a.fileCount)return b.fileCount-a.fileCount;return a.name.localeCompare(b.name)}).slice(0,topN)}function summarizeSelectedPackageBoundaries(graph,nodes,topN=25){let summaries=summarizePackageBoundaries(nodes,[],topN),boundaryByModule=new Map;for(let node of nodes)boundaryByModule.set(normalizeLookupPath(node.moduleName),node.ontology?.packageBoundary??inferBoundary(node.moduleName));let byName=new Map(summaries.map((summary)=>[summary.name,summary])),dependsOn=new Map,dependedOnBy=new Map;for(let node of nodes){let sourceBoundary=boundaryByModule.get(normalizeLookupPath(node.moduleName));if(!sourceBoundary)continue;for(let dep of getDependencies(graph,node.moduleName)){let targetBoundary=boundaryByModule.get(normalizeLookupPath(dep.file));if(!targetBoundary||sourceBoundary===targetBoundary||!byName.has(sourceBoundary)||!byName.has(targetBoundary))continue;if(!dependsOn.has(sourceBoundary))dependsOn.set(sourceBoundary,new Set);if(!dependedOnBy.has(targetBoundary))dependedOnBy.set(targetBoundary,new Set);dependsOn.get(sourceBoundary)?.add(targetBoundary),dependedOnBy.get(targetBoundary)?.add(sourceBoundary)}}for(let summary of summaries)summary.dependsOn=[...dependsOn.get(summary.name)??[]].sort(),summary.dependedOnBy=[...dependedOnBy.get(summary.name)??[]].sort();return summaries}function inferBoundary(moduleName){let parts=normalizeLookupPath(moduleName).split("/").filter(Boolean);if(parts[0]==="src"&&parts.length>=2)return`src/${parts[1]}`;if(parts.length>=2&&(parts[0]==="packages"||parts[0]==="crates"))return`${parts[0]}/${parts[1]}`;return parts[0]||"."}function buildOntologyPreflightPacket(graph,filePaths=[],options={}){let maxFiles=options.maxFiles??12,maxFindings=options.maxFindings??20,boundedNodes=(filePaths.length>0?filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0):getKeyFiles(graph,maxFiles)).slice(0,maxFiles),findings=boundedNodes.flatMap((node)=>(node.ontology?.findings??[]).map((finding)=>({file:node.moduleName,...finding}))).slice(0,maxFindings),routes=boundedNodes.flatMap((node)=>(node.ontology?.routes??[]).map((route)=>({file:node.moduleName,...route}))),dataOperations=boundedNodes.flatMap((node)=>(node.ontology?.dataOperations??[]).map((fact)=>({file:node.moduleName,...fact}))),security=boundedNodes.flatMap((node)=>(node.ontology?.security??[]).map((fact)=>({file:node.moduleName,...fact})));return{generatedAt:new Date().toISOString(),targets:boundedNodes.map((node)=>node.moduleName),summary:{fileCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length,targetCount:boundedNodes.length,findingCount:findings.length,routeCount:routes.length,dataOperationCount:dataOperations.length,securityFactCount:security.length},files:boundedNodes.map((node)=>({file:node.moduleName,roles:node.ontology?.roles??[],packageBoundary:node.ontology?.packageBoundary??inferBoundary(node.moduleName),importerCount:getImporters(graph,node.moduleName).length,dependencyCount:getDependencies(graph,node.moduleName).length,routeCount:node.ontology?.routes.length??0,dataOperationCount:node.ontology?.dataOperations.length??0,securityFactCount:node.ontology?.security.length??0,findingCount:node.ontology?.findings.length??0})),routes,dataOperations,security,findings,packageBoundaries:summarizeSelectedPackageBoundaries(graph,boundedNodes,options.maxBoundaries??10)}}init_utils2();init_logger();init_path_security();import{constants as constants5,existsSync as existsSync78,readFileSync as readFileSync53,statSync as statSync29}from"node:fs";import*as fsPromises6 from"node:fs/promises";import*as path140 from"node:path";var WINDOWS_RENAME_MAX_RETRIES2=5,WINDOWS_RENAME_RETRY_DELAY_MS2=100,_internals84={safeRealpathSync,fsRename:fsPromises6.rename.bind(fsPromises6),retryDelayMs:WINDOWS_RENAME_RETRY_DELAY_MS2};function validateLoadedGraph(parsed){if(!parsed.schema_version)throw Object.assign(Error("repo-graph.json missing schema_version"),{code:"CORRUPTION"});if(!parsed.nodes||typeof parsed.nodes!=="object")throw Object.assign(Error("repo-graph.json missing or invalid nodes"),{code:"CORRUPTION"});if(!Array.isArray(parsed.edges))throw Object.assign(Error("repo-graph.json missing or invalid edges"),{code:"CORRUPTION"});for(let[key,node]of Object.entries(parsed.nodes)){if(!key||typeof key!=="string")throw Object.assign(Error("repo-graph.json contains invalid node key"),{code:"CORRUPTION"});try{validateGraphNode(node)}catch(err){let msg=err instanceof Error?err.message:"Invalid node structure";throw Object.assign(Error(`repo-graph.json node validation failed: ${msg}`),{code:"CORRUPTION"})}}for(let edge of parsed.edges)try{validateGraphEdge(edge)}catch(err){let msg=err instanceof Error?err.message:"Invalid edge structure";throw Object.assign(Error(`repo-graph.json edge validation failed: ${msg}`),{code:"CORRUPTION"})}if(!parsed.metadata||typeof parsed.metadata!=="object"||typeof parsed.metadata.generatedAt!=="string"||typeof parsed.metadata.generator!=="string"||typeof parsed.metadata.nodeCount!=="number"||typeof parsed.metadata.edgeCount!=="number")throw Object.assign(Error("repo-graph.json missing or invalid metadata"),{code:"CORRUPTION"});if(parsed.symbolEdges!==void 0){if(!Array.isArray(parsed.symbolEdges))throw Object.assign(Error("repo-graph.json symbolEdges must be an array"),{code:"CORRUPTION"});for(let entry of parsed.symbolEdges)if(typeof entry!=="object"||entry===null||typeof entry.fromFile!=="string"||typeof entry.fromSymbol!=="string"||typeof entry.toFile!=="string"||typeof entry.toSymbol!=="string"||entry.fromFile===""||entry.fromSymbol===""||entry.toFile===""||entry.toSymbol===""||containsControlChars(entry.fromFile)||containsControlChars(entry.fromSymbol)||containsControlChars(entry.toFile)||containsControlChars(entry.toSymbol)||containsPathTraversal(entry.fromFile)||containsPathTraversal(entry.toFile))throw Object.assign(Error("repo-graph.json contains invalid symbolEdges entry"),{code:"CORRUPTION"})}}function getGraphPath(workspace){validateWorkspace(workspace);let basePath=validateSwarmPath(workspace,REPO_GRAPH_FILENAME);return validateSymlinkBoundary(basePath,workspace),basePath}async function loadGraph(workspace){validateWorkspace(workspace);let normalized=path140.normalize(workspace),cached3=getCachedGraph(normalized);if(cached3&&!isDirty(normalized))try{let graphPath=getGraphPath(workspace);if(existsSync78(graphPath)){let stats2=await fsPromises6.stat(graphPath),cachedMtime=getCachedMtime(normalized);if(cachedMtime!==void 0&&stats2.mtimeMs!==cachedMtime)clearCache(normalized);else return cached3}else clearCache(normalized)}catch{clearCache(normalized)}try{let graphPath=getGraphPath(workspace);if(!existsSync78(graphPath))return null;let stats2=await fsPromises6.stat(graphPath),content=await fsPromises6.readFile(graphPath,"utf-8");if(content.includes("\x00")||content.includes("�"))throw Object.assign(Error("repo-graph.json contains null bytes or invalid encoding"),{code:"CORRUPTION"});let parsed;try{parsed=JSON.parse(content)}catch{throw Object.assign(Error("repo-graph.json contains invalid JSON"),{code:"CORRUPTION"})}return validateLoadedGraph(parsed),setCachedGraph(normalized,parsed,stats2.mtimeMs),parsed}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="CORRUPTION")throw error93;if(error93 instanceof Error&&"code"in error93&&error93.code==="ENOENT")return null;throw error93}}function loadGraphSync(workspace){validateWorkspace(workspace);let normalized=path140.normalize(workspace);try{let graphPath=getGraphPath(workspace);if(!existsSync78(graphPath))return null;let stats2=statSync29(graphPath),content=readFileSync53(graphPath,"utf-8");if(content.includes("\x00")||content.includes("�"))throw Object.assign(Error("repo-graph.json contains null bytes or invalid encoding"),{code:"CORRUPTION"});let parsed;try{parsed=JSON.parse(content)}catch{throw Object.assign(Error("repo-graph.json contains invalid JSON"),{code:"CORRUPTION"})}return validateLoadedGraph(parsed),setCachedGraph(normalized,parsed,stats2.mtimeMs),parsed}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="ENOENT")return null;throw error93}}async function saveGraph(workspace,graph,options){if(validateWorkspace(workspace),!graph.schema_version)throw Error("Graph must have schema_version");if(!graph.nodes||typeof graph.nodes!=="object")throw Error("Graph must have nodes object");if(!Array.isArray(graph.edges))throw Error("Graph must have edges array");let normalizedWorkspace=path140.normalize(workspace),realWorkspace=_internals84.safeRealpathSync(workspace,normalizedWorkspace);if(realWorkspace===null)throw Error(`Workspace realpath security check failed (non-ENOENT): ${workspace}`);let normalizedGraphRoot=path140.normalize(graph.workspaceRoot),realGraphRoot=_internals84.safeRealpathSync(graph.workspaceRoot,normalizedGraphRoot);if(realGraphRoot===null)throw Error(`Graph workspaceRoot realpath security check failed (non-ENOENT): ${graph.workspaceRoot}`);if(path140.normalize(realWorkspace)!==path140.normalize(realGraphRoot))throw Error(`Graph workspaceRoot mismatch: graph was built for "${graph.workspaceRoot}" but save was called for "${workspace}"`);let normalized=normalizedWorkspace,graphPath=getGraphPath(workspace);updateGraphMetadata(graph);let tempPath=`${graphPath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;await fsPromises6.mkdir(path140.dirname(tempPath),{recursive:!0});let lastError=null;try{if(options?.createAtomic)try{let handle=await fsPromises6.open(tempPath,"wx",420);await handle.writeFile(JSON.stringify(graph,null,2),"utf-8"),await handle.close()}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="EEXIST")throw Error("file already exists");throw error93}else await fsPromises6.writeFile(tempPath,JSON.stringify(graph,null,2),"utf-8");if(options?.createAtomic)try{await fsPromises6.copyFile(tempPath,graphPath,constants5.COPYFILE_EXCL)}catch(error93){throw lastError=error93 instanceof Error?error93:Error(String(error93)),lastError}else{for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES2;attempt++)try{await _internals84.fsRename(tempPath,graphPath),lastError=null;break}catch(error93){lastError=error93 instanceof Error?error93:Error(String(error93));let code=lastError.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")break;if(attempt<WINDOWS_RENAME_MAX_RETRIES2-1)await new Promise((resolve49)=>setTimeout(resolve49,_internals84.retryDelayMs))}if(lastError)throw lastError}}finally{try{await fsPromises6.unlink(tempPath)}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code!=="ENOENT")error48(`Failed to clean up temp file ${tempPath}:`,error93)}}let stats2=await fsPromises6.stat(graphPath);setCachedGraph(normalized,graph,stats2.mtimeMs)}async function updateGraphForFiles(workspaceRoot,filePaths,options){if(options?.forceRebuild){let graph2=await buildWorkspaceGraphAsync(workspaceRoot);return await saveGraph(workspaceRoot,graph2),graph2}let existingGraph=await loadGraph(workspaceRoot);if(!existingGraph){let graph2=await buildWorkspaceGraphAsync(workspaceRoot);return await saveGraph(workspaceRoot,graph2),graph2}let graph=existingGraph,absoluteRoot=path141.resolve(workspaceRoot),maxFileSize=1048576,updatedPaths=new Set;for(let rawFilePath of filePaths){let normalizedPath=normalizeGraphPath(rawFilePath);if(existsSync79(rawFilePath)){if(graph.edges=graph.edges.filter((e)=>normalizeGraphPath(e.source)!==normalizedPath),graph.symbolEdges)graph.symbolEdges=graph.symbolEdges.filter((se)=>normalizeGraphPath(se.fromFile)!==normalizedPath);let result=await scanFileAsync(rawFilePath,absoluteRoot,maxFileSize);if(result.node){let sanitizedImports=result.node.imports.filter((imp)=>!containsControlChars(imp)),sanitizedNode={...result.node,imports:sanitizedImports};delete graph.nodes[normalizedPath],upsertNode(graph,sanitizedNode);for(let edge of result.edges)if(!graph.edges.some((e)=>e.source===edge.source&&e.target===edge.target&&e.importSpecifier===edge.importSpecifier))addEdge(graph,edge);if(result.symbolEdges.length>0){if(!graph.symbolEdges)graph.symbolEdges=[];let existingKeys=new Set(graph.symbolEdges.map((se)=>`${se.fromFile}\x00${se.fromSymbol}\x00${se.toFile}\x00${se.toSymbol}`));for(let symbolEdge of result.symbolEdges){let key=`${symbolEdge.fromFile}\x00${symbolEdge.fromSymbol}\x00${symbolEdge.toFile}\x00${symbolEdge.toSymbol}`;if(!existingKeys.has(key))graph.symbolEdges.push(symbolEdge),existingKeys.add(key)}}}}else if(delete graph.nodes[normalizedPath],graph.edges=graph.edges.filter((e)=>normalizeGraphPath(e.source)!==normalizedPath&&normalizeGraphPath(e.target)!==normalizedPath),graph.symbolEdges)graph.symbolEdges=graph.symbolEdges.filter((se)=>normalizeGraphPath(se.fromFile)!==normalizedPath&&normalizeGraphPath(se.toFile)!==normalizedPath);updatedPaths.add(normalizedPath)}let validationFailed=!1;for(let edge of graph.edges){let normalizedSource=normalizeGraphPath(edge.source),normalizedTarget=normalizeGraphPath(edge.target);if(!graph.nodes[normalizedSource]||!graph.nodes[normalizedTarget]){validationFailed=!0;break}}if(graph.symbolEdges&&graph.symbolEdges.length>0){let validSymbolEdges=[];for(let symbolEdge of graph.symbolEdges){let normalizedFromFile=normalizeGraphPath(symbolEdge.fromFile),normalizedToFile=normalizeGraphPath(symbolEdge.toFile);if(graph.nodes[normalizedFromFile]&&graph.nodes[normalizedToFile])validSymbolEdges.push(symbolEdge)}graph.symbolEdges=validSymbolEdges}if(validationFailed){warn("[repo-graph] Incremental update failed, falling back to full rebuild");let rebuiltGraph=await buildWorkspaceGraphAsync(workspaceRoot);return await saveGraph(workspaceRoot,rebuiltGraph),rebuiltGraph}let normalizedWorkspace=path141.normalize(workspaceRoot),loadedMtime=getCachedMtime(normalizedWorkspace);if(loadedMtime!==void 0)try{let graphPath=getGraphPath(workspaceRoot);if(existsSync79(graphPath)){if((await fsPromises7.stat(graphPath)).mtimeMs!==loadedMtime){warn("[repo-graph] Concurrent modification detected — falling back to full rebuild");let rebuiltGraph=await buildWorkspaceGraphAsync(workspaceRoot);return await saveGraph(workspaceRoot,rebuiltGraph),rebuiltGraph}}}catch{}if(graph.symbolEdges&&graph.symbolEdges.length===0)delete graph.symbolEdges;return updateGraphMetadata(graph),resetQueryCache(),await saveGraph(workspaceRoot,graph),graph}init_logger();var SUPPORTED_EXTENSIONS2=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py"];function extractFilePath(args2){if(!args2||typeof args2!=="object")return null;let a=args2,filePath=a.file_path??a.path??a.filePath;if(!filePath||typeof filePath!=="string")return null;for(let i=0;i<3;i++)try{let decoded=decodeURIComponent(filePath);if(decoded===filePath)break;filePath=decoded}catch{break}return filePath=filePath.replace(/./g,".").replace(///g,"/").replace(/․/g,"."),filePath}function isSupportedSourceFile(filePath){let ext=filePath.substring(filePath.lastIndexOf(".")).toLowerCase();return SUPPORTED_EXTENSIONS2.includes(ext)}function createRepoGraphBuilderHook(workspaceRoot,deps,options){let _buildWorkspaceGraph=deps?.buildWorkspaceGraph??buildWorkspaceGraphAsync,_saveGraph=deps?.saveGraph??saveGraph,_updateGraphForFiles=deps?.updateGraphForFiles??updateGraphForFiles,_safeRealpathSync=deps?.safeRealpathSync??safeRealpathSync,_excludeDirs=(options?.excludeDirs??[]).filter((d)=>d.length>0),_excludeDirSet=new Set(_excludeDirs),initStarted=!1,initPromise=Promise.resolve(),FAILURE_ADVISORY_THRESHOLD=3,FAILURE_DECAY_MS=300000,ADVISORY_COOLDOWN_MS=60000,MAX_TRACKED_SESSIONS=100,failuresBySession=new Map;function recordSuccess(sessionID){failuresBySession.delete(sessionID)}function recordFailure(sessionID,now){let state=failuresBySession.get(sessionID);if(state&&now-state.lastFailureAt>FAILURE_DECAY_MS)failuresBySession.delete(sessionID),state=void 0;if(!state){if(failuresBySession.size>=MAX_TRACKED_SESSIONS){let oldest=failuresBySession.keys().next().value;if(oldest!==void 0)failuresBySession.delete(oldest)}state={failures:0,lastFailureAt:0,lastAdvisoryAt:0},failuresBySession.set(sessionID,state)}state.failures+=1,state.lastFailureAt=now;let advise=!1;if(state.failures>=FAILURE_ADVISORY_THRESHOLD&&now-state.lastAdvisoryAt>=ADVISORY_COOLDOWN_MS)advise=!0,state.lastAdvisoryAt=now;return{count:state.failures,advise}}async function doInit(){await yieldToEventLoop();try{let graph=await _buildWorkspaceGraph(workspaceRoot,{excludeDirs:_excludeDirs});await _saveGraph(workspaceRoot,graph),log(`[repo-graph] Built graph: ${graph.metadata.nodeCount} nodes, ${graph.metadata.edgeCount} edges`)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);if(message.includes("does not exist")||message.includes("Refusing to scan")){log(`[repo-graph] Skipping scan: ${message}`);return}error48(`[repo-graph] Failed to build graph: ${message}`)}}return{init(){if(!initStarted)initStarted=!0,initPromise=doInit();return initPromise},async toolAfter(input,_output){if(await initPromise.catch(()=>{}),!WRITE_TOOL_NAMES.includes(input.tool))return;let filePath=extractFilePath(input.args);if(!filePath)return;if(filePath.includes("\x00"))return;if(!isSupportedSourceFile(filePath))return;if(_excludeDirSet.size>0&&filePath.split(/[/\\]/).some((segment)=>_excludeDirSet.has(segment)))return;let absoluteFilePath=path142.isAbsolute(filePath)?filePath:path142.resolve(workspaceRoot,filePath),realFilePath=_safeRealpathSync(absoluteFilePath,absoluteFilePath);if(realFilePath===null)return;let realWorkspace=_safeRealpathSync(workspaceRoot,workspaceRoot);if(realWorkspace===null)return;let normalizedAbsolute=realFilePath.replace(/\\/g,"/"),normalizedWorkspace=realWorkspace.replace(/\\/g,"/");if(!normalizedAbsolute.startsWith(`${normalizedWorkspace}/`)&&normalizedAbsolute!==normalizedWorkspace)return;try{await _updateGraphForFiles(workspaceRoot,[absoluteFilePath]),recordSuccess(input.sessionID),log(`[repo-graph] Incremental update for ${path142.basename(filePath)}`)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93),{count,advise}=recordFailure(input.sessionID,Date.now());if(error48(`[repo-graph] Incremental update failed: ${message}`),advise)warn(`[repo-graph] ${count} consecutive incremental update failures. The dependency graph may be stale. Consider reloading the workspace.`)}}}}init_review_receipt();init_constants();init_schema();init_manager2();init_detector();init_manager();init_state2();init_swarm_artifact_cache();import*as fs83 from"node:fs";import*as path148 from"node:path";init_utils2();init_manager();init_utils();import*as fs78 from"node:fs";import*as path143 from"node:path";var DEFAULT_DRIFT_CONFIG={staleThresholdPhases:1,detectContradictions:!0,maxSignals:5};function extractDecisionsFromContext(contextContent){let decisions=[],lines=contextContent.split(`
5321
5356
  `),inDecisionsSection=!1,currentPhase=null,lineNumber=0;for(let i=0;i<lines.length;i++){let line=lines[i];lineNumber=i+1;let phaseMatch=line.match(/^## Phase (\d+)/);if(phaseMatch)currentPhase=parseInt(phaseMatch[1],10);if(line.trim()==="## Decisions"){inDecisionsSection=!0;continue}if(inDecisionsSection&&line.startsWith("## "))break;if(inDecisionsSection&&line.trim().startsWith("- ")){let text=line.trim().substring(2),confirmed=text.includes("✅")||text.includes("[confirmed]"),timestampMatch=text.match(/\[(\d{4}-\d{2}-\d{2}T[\d:.]+Z?)\]/),timestamp=timestampMatch?timestampMatch[1]:null,decisionPhaseMatch=text.match(/Phase (\d+)/),decisionPhase=decisionPhaseMatch?parseInt(decisionPhaseMatch[1],10):currentPhase;decisions.push({text:text.replace(/\s*\[.*?\]\s*/g,"").trim(),phase:decisionPhase,confirmed,timestamp,line:lineNumber})}}return decisions}function isDecisionStale(decision,currentPhase,threshold){if(decision.phase===null)return!decision.confirmed;let phaseDiff=currentPhase-decision.phase;if(phaseDiff>=threshold)return!0;if(phaseDiff===0&&!decision.confirmed)return!0;return!1}function findContradictions(decisions){let signals=[],contradictionPairs=[[["use","using","use ","adopt","implement","enable"],["not use","don't use","do not use","avoid","disable","remove"]],[["keep","retain","preserve"],["remove","delete","drop","eliminate"]],[["include","add","incorporate"],["exclude","skip","omit"]],[["require","mandatory","must"],["optional","skip","can skip"]],[["background","async"],["foreground","sync","synchronous"]]];for(let i=0;i<decisions.length;i++){let decisionA=decisions[i],textLower=decisionA.text.toLowerCase();for(let j=i+1;j<decisions.length;j++){let decisionB=decisions[j],textBLower=decisionB.text.toLowerCase();for(let[positiveKeywords,negativeKeywords]of contradictionPairs){let hasPositiveInA=positiveKeywords.some((k)=>textLower.includes(k)),hasNegativeInA=negativeKeywords.some((k)=>textLower.includes(k)),hasPositiveInB=positiveKeywords.some((k)=>textBLower.includes(k)),hasNegativeInB=negativeKeywords.some((k)=>textBLower.includes(k));if(hasPositiveInA&&hasNegativeInB||hasNegativeInA&&hasPositiveInB){let wordsA=textLower.split(/\s+/).slice(0,4).join(" "),wordsB=textBLower.split(/\s+/).slice(0,4).join(" ");if(wordsA.split(/\s+/).filter((w)=>w.length>2&&wordsB.includes(w)).length>0||wordsA.includes("file"))signals.push({id:`contradiction-${i}-${j}`,severity:"error",type:"contradiction",message:"Contradictory decisions detected",source:{file:"context.md",line:decisionA.line},relatedDecisions:[decisionA.text,decisionB.text],hint:"Review both decisions and clarify the intended approach."})}}}}return signals}function extractCurrentPhaseFromLegacy(planContent){if(!planContent)return null;let lines=planContent.split(`
5322
5357
  `);for(let i=0;i<Math.min(30,lines.length);i++){let progressMatch=lines[i].trim().match(/^## Phase (\d+):?\s*(.*?)\s*\[IN PROGRESS\]/i);if(progressMatch)return parseInt(progressMatch[1],10)}for(let i=0;i<Math.min(5,lines.length);i++){let phaseMatch=lines[i].trim().match(/Phase:\s*(\d+)/i);if(phaseMatch)return parseInt(phaseMatch[1],10)}return null}async function analyzeDecisionDrift(directory,config3={}){let effectiveConfig={...DEFAULT_DRIFT_CONFIG,...config3},signals=[],analyzedAt=new Date().toISOString();try{let plan=await loadPlan(directory),currentPhase=plan?.current_phase??1;if(!plan){let legacyPhase=extractCurrentPhaseFromLegacy(await readSwarmFileAsync(directory,"plan.md")??"");if(legacyPhase!==null)currentPhase=legacyPhase}let contextPath=path143.join(directory,".swarm","context.md"),contextContent="";try{if(fs78.existsSync(contextPath))contextContent=fs78.readFileSync(contextPath,"utf-8")}catch(error93){return log("[DecisionDriftAnalyzer] context file read failed",{error:error93 instanceof Error?error93.message:String(error93)}),{hasDrift:!1,signals:[],summary:"",analyzedAt}}if(!contextContent)return{hasDrift:!1,signals:[],summary:"",analyzedAt};let decisions=extractDecisionsFromContext(contextContent);if(decisions.length===0)return{hasDrift:!1,signals:[],summary:"",analyzedAt};for(let decision of decisions)if(isDecisionStale(decision,currentPhase,effectiveConfig.staleThresholdPhases)){let hint;if(decision.phase!==null&&decision.phase<currentPhase)hint=`Decision was from Phase ${decision.phase}, current is Phase ${currentPhase}.`;else if(!decision.confirmed)hint="Decision has not been confirmed. Consider confirming or revisiting.";signals.push({id:`stale-${decision.line}`,severity:decision.phase!==null&&decision.phase<currentPhase?"warning":"warning",type:"stale",message:`Stale decision: "${decision.text.substring(0,50)}${decision.text.length>50?"...":""}"`,source:{file:"context.md",line:decision.line},hint})}if(effectiveConfig.detectContradictions){let contradictions=findContradictions(decisions);signals.push(...contradictions)}let limitedSignals=signals.slice(0,effectiveConfig.maxSignals),summary=buildDriftSummary(limitedSignals);return{hasDrift:limitedSignals.length>0,signals:limitedSignals,summary,analyzedAt}}catch(error93){return log("[DecisionDriftAnalyzer] drift analysis failed",{error:error93 instanceof Error?error93.message:String(error93)}),{hasDrift:!1,signals:[],summary:"",analyzedAt}}}function buildDriftSummary(signals){if(signals.length===0)return"";let warnings=signals.filter((s)=>s.severity==="warning"),errors5=signals.filter((s)=>s.severity==="error"),lines=["[SWARM DECISION DRIFT]"];if(errors5.length>0){lines.push(`⚠️ ${errors5.length} contradiction(s) detected:`);for(let err of errors5.slice(0,2)){let related=err.relatedDecisions?` (${err.relatedDecisions[0].substring(0,30)}... vs ${err.relatedDecisions[1].substring(0,30)}...)`:"";lines.push(` - ${err.type}: ${err.message}${related}`)}}if(warnings.length>0){lines.push(`\uD83D\uDCA1 ${warnings.length} stale decision(s) found:`);for(let warn2 of warnings.slice(0,3)){let hint=warn2.hint?` - ${warn2.hint}`:"";lines.push(` - ${warn2.message.substring(0,60)}${hint}`)}}return lines.push("See .swarm/context.md for details."),lines.join(`
@@ -5532,7 +5567,7 @@ ${untracked.slice(0,100).map((f)=>`- ${f}`).join(`
5532
5567
  `,"utf-8");try{let lines=(await readFile31(filePath,"utf-8")).split(`
5533
5568
  `).filter((line)=>line.trim().length>0);if(lines.length>MAX_LEGACY_APPLICATION_LOG_ENTRIES){let trimmed=lines.slice(-MAX_LEGACY_APPLICATION_LOG_ENTRIES);await atomicWriteFile(filePath,`${trimmed.join(`
5534
5569
  `)}
5535
- `)}}catch(err){warn(`[knowledge-application] appendAudit cap failed: ${err instanceof Error?err.message:String(err)}`)}}finally{if(release)await release().catch(()=>{})}}async function bumpCountersBatch(directory,bumps){let filteredBumps=bumps.filter((b)=>b.ids.length>0);if(filteredBumps.length===0)return;let idToFields=new Map;for(let b of filteredBumps)for(let id of b.ids){let list=idToFields.get(id);if(list)list.push(b.field);else idToFields.set(id,[b.field])}let now=new Date().toISOString(),applyOne=(entries)=>{let updated=!1;for(let e of entries){let fields=idToFields.get(e.id);if(!fields)continue;let ro=e.retrieval_outcomes;for(let field of fields){if(ro[field]=(ro[field]??0)+1,field==="applied_explicit_count")e.last_applied_at=now;if(field==="acknowledged_count")e.last_acknowledged_at=now;updated=!0}}return updated?entries:null},swarmPath=resolveSwarmKnowledgePath(directory);await transactKnowledge(swarmPath,applyOne);let hivePath=resolveHiveKnowledgePath();if(existsSync83(hivePath))await transactKnowledge(hivePath,applyOne)}async function bumpCounters(directory,ids,field){return bumpCountersBatch(directory,[{ids,field}])}async function recordKnowledgeShown(directory,ids,ctx){if(ids.length===0)return;try{let ts=new Date().toISOString();for(let id of ids)await appendAudit(directory,{timestamp:ts,phase:ctx.phase,taskId:ctx.taskId,action:ctx.action,tool:ctx.tool,targetAgent:ctx.targetAgent,sessionId:ctx.sessionId,knowledgeId:id,result:"shown"});await bumpCounters(directory,ids,"shown_count")}catch(err){warn(`[knowledge-application] recordKnowledgeShown failed: ${err instanceof Error?err.message:String(err)}`)}}async function recordAcknowledgment(directory,ack,ctx){try{let result=ack.result==="n_a"?"acknowledged":ack.result;await appendAudit(directory,{timestamp:new Date().toISOString(),phase:ctx.phase,taskId:ctx.taskId,action:ctx.action,tool:ctx.tool,targetAgent:ctx.targetAgent,sessionId:ctx.sessionId,knowledgeId:ack.id,result,reason:ack.reason});let bumps=[{ids:[ack.id],field:"acknowledged_count"}];if(ack.result==="applied")bumps.push({ids:[ack.id],field:"applied_explicit_count"});else if(ack.result==="ignored")bumps.push({ids:[ack.id],field:"ignored_count"});else if(ack.result==="violated")bumps.push({ids:[ack.id],field:"violated_count"});await bumpCountersBatch(directory,bumps)}catch(err){warn(`[knowledge-application] recordAcknowledgment failed: ${err instanceof Error?err.message:String(err)}`)}}function utcDayKey(d=new Date){return d.toISOString().slice(0,10)}function buildAckDedupKey(sessionId,id,result,now=new Date){return`${sessionId}|${id}|${result}|${utcDayKey(now)}`}init_knowledge_escalator();init_knowledge_events();init_schema();init_manager();import{createHash as createHash19}from"node:crypto";import*as crypto11 from"node:crypto";import*as fs87 from"node:fs/promises";function sanitizeContextText(text){return text.split("").filter((char)=>{let code=char.charCodeAt(0);return code===9||code===10||code===13||code>31&&code!==127}).join("").replace(/[\u200B-\u200D\uFEFF]/g,"").replace(/[\u202A-\u202E\u2066-\u2069]/g,"").replace(/```/g,"` ` `").replace(/^system\s*:/gim,"[BLOCKED]:").replace(/<system\b[^>]*>/gi,"[BLOCKED-TAG]").replace(/<\/system>/gi,"[/BLOCKED-TAG]").replace(/<tool_call\b[^>]*>/gi,"[BLOCKED-TOOL]").replace(/<\/tool_call>/gi,"[/BLOCKED-TOOL]").replace(/<\/\w+>/g,"[/BLOCKED-TAG]")}init_utils2();init_path_security();var RUN_MEMORY_FILENAME="run-memory.jsonl",MAX_SUMMARY_TOKENS=500;function generateTaskFingerprint(taskId,fileTargets){let sortedFiles=[...fileTargets].sort().join(",");return crypto11.createHash("sha256").update(taskId+sortedFiles).digest("hex").slice(0,8)}async function recordOutcome(directory,entry){validateDirectory(directory);let resolvedPath=validateSwarmPath(directory,RUN_MEMORY_FILENAME),line=`${JSON.stringify(entry)}
5570
+ `)}}catch(err){warn(`[knowledge-application] appendAudit cap failed: ${err instanceof Error?err.message:String(err)}`)}}finally{if(release)await release().catch(()=>{})}}async function bumpCountersBatch(directory,bumps){let filteredBumps=bumps.filter((b)=>b.ids.length>0);if(filteredBumps.length===0)return;let idToFields=new Map;for(let b of filteredBumps)for(let id of b.ids){let list=idToFields.get(id);if(list)list.push(b.field);else idToFields.set(id,[b.field])}let now=new Date().toISOString(),applyOne=(entries)=>{let updated=!1;for(let e of entries){let fields=idToFields.get(e.id);if(!fields)continue;let ro=e.retrieval_outcomes;for(let field of fields){if(ro[field]=(ro[field]??0)+1,field==="applied_explicit_count")e.last_applied_at=now;if(field==="acknowledged_count")e.last_acknowledged_at=now;updated=!0}}return updated?entries:null},swarmPath=resolveSwarmKnowledgePath(directory);await transactKnowledge(swarmPath,applyOne);let hivePath=resolveHiveKnowledgePath();if(existsSync83(hivePath))await transactKnowledge(hivePath,applyOne)}async function bumpCounters(directory,ids,field){return bumpCountersBatch(directory,[{ids,field}])}async function recordKnowledgeShown(directory,ids,ctx){if(ids.length===0)return;try{let ts=new Date().toISOString();for(let id of ids)await appendAudit(directory,{timestamp:ts,phase:ctx.phase,taskId:ctx.taskId,action:ctx.action,tool:ctx.tool,targetAgent:ctx.targetAgent,sessionId:ctx.sessionId,knowledgeId:id,result:"shown"});await bumpCounters(directory,ids,"shown_count")}catch(err){warn(`[knowledge-application] recordKnowledgeShown failed: ${err instanceof Error?err.message:String(err)}`)}}async function recordAcknowledgment(directory,ack,ctx){try{let result=ack.result==="n_a"?"acknowledged":ack.result;await appendAudit(directory,{timestamp:new Date().toISOString(),phase:ctx.phase,taskId:ctx.taskId,action:ctx.action,tool:ctx.tool,targetAgent:ctx.targetAgent,sessionId:ctx.sessionId,knowledgeId:ack.id,result,reason:ack.reason});let bumps=[{ids:[ack.id],field:"acknowledged_count"}];if(ack.result==="applied")bumps.push({ids:[ack.id],field:"applied_explicit_count"});else if(ack.result==="ignored")bumps.push({ids:[ack.id],field:"ignored_count"});else if(ack.result==="violated")bumps.push({ids:[ack.id],field:"violated_count"});await bumpCountersBatch(directory,bumps)}catch(err){warn(`[knowledge-application] recordAcknowledgment failed: ${err instanceof Error?err.message:String(err)}`)}}function buildAckDedupKey(sessionId,id,result,_now=new Date){return`${sessionId}|${id}|${result}`}init_knowledge_escalator();init_knowledge_events();init_schema();init_manager();import{createHash as createHash19}from"node:crypto";import*as crypto11 from"node:crypto";import*as fs87 from"node:fs/promises";function sanitizeContextText(text){return text.split("").filter((char)=>{let code=char.charCodeAt(0);return code===9||code===10||code===13||code>31&&code!==127}).join("").replace(/[\u200B-\u200D\uFEFF]/g,"").replace(/[\u202A-\u202E\u2066-\u2069]/g,"").replace(/```/g,"` ` `").replace(/^system\s*:/gim,"[BLOCKED]:").replace(/<system\b[^>]*>/gi,"[BLOCKED-TAG]").replace(/<\/system>/gi,"[/BLOCKED-TAG]").replace(/<tool_call\b[^>]*>/gi,"[BLOCKED-TOOL]").replace(/<\/tool_call>/gi,"[/BLOCKED-TOOL]").replace(/<\/\w+>/g,"[/BLOCKED-TAG]")}init_utils2();init_path_security();var RUN_MEMORY_FILENAME="run-memory.jsonl",MAX_SUMMARY_TOKENS=500;function generateTaskFingerprint(taskId,fileTargets){let sortedFiles=[...fileTargets].sort().join(",");return crypto11.createHash("sha256").update(taskId+sortedFiles).digest("hex").slice(0,8)}async function recordOutcome(directory,entry){validateDirectory(directory);let resolvedPath=validateSwarmPath(directory,RUN_MEMORY_FILENAME),line=`${JSON.stringify(entry)}
5536
5571
  `;await fs87.appendFile(resolvedPath,line,{encoding:"utf-8"})}async function getTaskHistory(directory,taskId){validateDirectory(directory);let content=await readSwarmFileAsync(directory,RUN_MEMORY_FILENAME);if(!content)return[];let entries=[],lines=content.split(`
5537
5572
  `);for(let line of lines){if(!line.trim())continue;try{let entry=JSON.parse(line);if(entry.taskId===taskId)entries.push(entry)}catch{}}return entries}async function getFailures(directory){validateDirectory(directory);let content=await readSwarmFileAsync(directory,RUN_MEMORY_FILENAME);if(!content)return[];let entries=[],lines=content.split(`
5538
5573
  `);for(let line of lines){if(!line.trim())continue;try{let entry=JSON.parse(line);if(entry.outcome==="fail"||entry.outcome==="retry")entries.push(entry)}catch{}}return entries}function groupByTaskId(entries){let groups=new Map;for(let entry of entries){let existing=groups.get(entry.taskId)||[];existing.push(entry),groups.set(entry.taskId,existing)}return groups}function summarizeTask(taskId,entries){let failures=entries.filter((e)=>e.outcome==="fail"||e.outcome==="retry"),passes=entries.filter((e)=>e.outcome==="pass");if(failures.length===0)return null;failures.sort((a,b)=>new Date(b.timestamp).getTime()-new Date(a.timestamp).getTime());let lastFailure=failures[0];passes.sort((a,b)=>new Date(b.timestamp).getTime()-new Date(a.timestamp).getTime());let lastPass=passes[0],failCount=failures.length;if(lastPass){let passAttempt=lastPass.attemptNumber,failAttempt=lastFailure.attemptNumber,reason=sanitizeContextText(lastFailure.failureReason||"unknown");return`Task ${taskId}: FAILED attempt ${failAttempt} — ${reason}. Passed on attempt ${passAttempt}.`}else{let reason=sanitizeContextText(lastFailure.failureReason||"unknown");return`Task ${taskId}: FAILED ${failCount} times — last: ${reason}. Still failing.`}}async function getRunMemorySummary(directory){validateDirectory(directory);let content=await readSwarmFileAsync(directory,RUN_MEMORY_FILENAME);if(!content)return null;let entries=[],lines=content.split(`
@@ -5540,7 +5575,7 @@ ${untracked.slice(0,100).map((f)=>`- ${f}`).join(`
5540
5575
  ## RUN MEMORY — Previous Task Outcomes
5541
5576
  `,suffix=`
5542
5577
  Use this data to avoid repeating known failure patterns.`,summaryText=summaries.join(`
5543
- `),estimateTokens5=(text)=>{return Math.ceil(text.length*0.33)},totalText=prefix+summaryText+suffix;if(estimateTokens5(totalText)>MAX_SUMMARY_TOKENS){let prefixTokens=estimateTokens5(prefix),suffixTokens=estimateTokens5(suffix),availableContentTokens=MAX_SUMMARY_TOKENS-prefixTokens-suffixTokens;if(availableContentTokens>0){let maxContentChars=Math.floor(availableContentTokens/0.33);summaryText=summaryText.slice(0,maxContentChars)}else summaryText=""}return prefix+summaryText+suffix}var _internals89={generateTaskFingerprint,recordOutcome,getTaskHistory,getFailures,getRunMemorySummary,groupByTaskId,summarizeTask};init_state2();init_logger();init_curator_drift();init_extractors();init_knowledge_escalator();init_knowledge_events();init_knowledge_store();init_model_limits();init_search_knowledge();init_utils2();var INJECTION_SENTINEL=`${String.fromCharCode(8204)}[[KNOWLEDGE-INJECTED]]`,defaultSearchKnowledge=searchKnowledge;function buildKnowledgeBlock(entries,charBudget,cfg,currentProject){if(entries.length===0)return null;let maxDisplayChars=cfg.max_lesson_display_chars??120,lines=entries.map((entry)=>{let tier=entry.tier==="hive"?"[H]":"[S]",confirmedBy=entry.confirmed_by?.length??0,confirm=confirmedBy>=3?" ✓✓":confirmedBy>=1?" ✓":"",lessonText=sanitizeLessonForContext(entry.lesson);if(lessonText.length>maxDisplayChars)lessonText=`${lessonText.slice(0,maxDisplayChars)}…`;let rawSource=entry.tier==="hive"&&"source_project"in entry?entry.source_project??null:null,source=rawSource!==null&&rawSource!==currentProject?` (from: ${sanitizeLessonForContext(rawSource)})`:"";return`${tier} ${lessonText}${source}${confirm}`}),header=`\uD83D\uDCDA Lessons:
5578
+ `),estimateTokens5=(text)=>{return Math.ceil(text.length*0.33)},totalText=prefix+summaryText+suffix;if(estimateTokens5(totalText)>MAX_SUMMARY_TOKENS){let prefixTokens=estimateTokens5(prefix),suffixTokens=estimateTokens5(suffix),availableContentTokens=MAX_SUMMARY_TOKENS-prefixTokens-suffixTokens;if(availableContentTokens>0){let maxContentChars=Math.floor(availableContentTokens/0.33);summaryText=summaryText.slice(0,maxContentChars)}else summaryText=""}return prefix+summaryText+suffix}var _internals89={generateTaskFingerprint,recordOutcome,getTaskHistory,getFailures,getRunMemorySummary,groupByTaskId,summarizeTask};init_state2();init_logger();init_curator_drift();init_extractors();init_knowledge_escalator();init_knowledge_events();init_knowledge_store();init_model_limits();init_search_knowledge();init_utils2();var INJECTION_SENTINEL=`${String.fromCharCode(8204)}[[KNOWLEDGE-INJECTED]]`,defaultSearchKnowledge=searchKnowledge;function getRenderedEntryIds(entries,renderedBlock,cfg,currentProject){if(!renderedBlock)return[];let maxDisplayChars=cfg.max_lesson_display_chars??120,ids=[];for(let entry of entries){if(renderedBlock.includes(`- id: ${entry.id}`)){ids.push(entry.id);continue}let lessonText=sanitizeLessonForContext(entry.lesson);if(lessonText.length>maxDisplayChars)lessonText=`${lessonText.slice(0,maxDisplayChars)}…`;let rawSource=entry.tier==="hive"&&"source_project"in entry?entry.source_project??null:null,source=rawSource!==null&&rawSource!==currentProject?` (from: ${sanitizeLessonForContext(rawSource)})`:"";if(renderedBlock.includes(`${lessonText}${source}`))ids.push(entry.id)}return ids}function buildKnowledgeBlock(entries,charBudget,cfg,currentProject){if(entries.length===0)return null;let maxDisplayChars=cfg.max_lesson_display_chars??120,lines=entries.map((entry)=>{let tier=entry.tier==="hive"?"[H]":"[S]",confirmedBy=entry.confirmed_by?.length??0,confirm=confirmedBy>=3?" ✓✓":confirmedBy>=1?" ✓":"",lessonText=sanitizeLessonForContext(entry.lesson);if(lessonText.length>maxDisplayChars)lessonText=`${lessonText.slice(0,maxDisplayChars)}…`;let rawSource=entry.tier==="hive"&&"source_project"in entry?entry.source_project??null:null,source=rawSource!==null&&rawSource!==currentProject?` (from: ${sanitizeLessonForContext(rawSource)})`:"";return`${tier} ${lessonText}${source}${confirm}`}),header=`\uD83D\uDCDA Lessons:
5544
5579
  `,block=`${header}
5545
5580
  ${lines.join(`
5546
5581
  `)}`;while(block.length>charBudget&&lines.length>0)lines.pop(),block=`${header}
@@ -5549,13 +5584,13 @@ ${lines.join(`
5549
5584
  `);while(block.length>charBudget&&lines.length>3){let lastIdx=-1;for(let i=lines.length-2;i>=0;i--)if(lines[i].startsWith("- id:")){lastIdx=i;break}if(lastIdx<0)break;lines.splice(lastIdx,lines.length-1-lastIdx),block=lines.join(`
5550
5585
  `)}if(lines.length<=2)return null;return block}var sanitizeLessonForContext=sanitizeContextText,DELEGATE_DIRECTIVE_BLOCK_TAG="<delegate_knowledge_directives>";function buildDelegateDirectiveBlock(entries,cfg){if(entries.length===0)return null;let maxDisplay=cfg.max_lesson_display_chars??120,FIELD_CAP=240,renderList=(items)=>{if(!items||items.length===0)return null;let joined=items.map((s)=>sanitizeLessonForContext(s)).filter((s)=>s.length>0).join("; ");if(!joined)return null;return joined.length>FIELD_CAP?`${joined.slice(0,FIELD_CAP)}…`:joined},sorted=[...entries].sort((a,b)=>{let pr=directivePriorityRank(a.directive_priority)-directivePriorityRank(b.directive_priority);if(pr!==0)return pr;return a.id<b.id?-1:a.id>b.id?1:0}),lines=[];lines.push(DELEGATE_DIRECTIVE_BLOCK_TAG),lines.push("These directives were learned from prior swarm runs and scoped to your role. Apply them to the task below."),lines.push("ACK CONTRACT: end your FINAL message with one line per CRITICAL directive in this block:"),lines.push(" KNOWLEDGE_APPLIED:<id> — you applied it"),lines.push(" KNOWLEDGE_IGNORED:<id> reason=<short why> — you intentionally did not apply it"),lines.push(" KNOWLEDGE_N_A:<id> reason=<why> — it did not apply to your task"),lines.push("Omitting a critical id is a contract violation.");for(let e of sorted){let priority=e.directive_priority??"medium",lesson=sanitizeLessonForContext(e.lesson).slice(0,maxDisplay);lines.push(`- id: ${e.id}`),lines.push(` priority: ${priority}`),lines.push(` lesson: ${lesson}`);let forbidden=renderList(e.forbidden_actions);if(forbidden)lines.push(` forbidden: ${forbidden}`);let required3=renderList(e.required_actions);if(required3)lines.push(` required: ${required3}`);let verification=renderList(e.verification_checks);if(verification)lines.push(` verification: ${verification}`)}return lines.push("</delegate_knowledge_directives>"),lines.join(`
5551
5586
  `)}function parseDelegateDirectiveBlock(text){if(!text||!text.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))return[];let start=text.indexOf(DELEGATE_DIRECTIVE_BLOCK_TAG),endTag="</delegate_knowledge_directives>",endIdx=text.indexOf(endTag,start),body=endIdx>=0?text.slice(start,endIdx):text.slice(start),out=[];for(let line of body.split(`
5552
- `)){let idM=/^- id:\s*(\S+)\s*$/.exec(line);if(idM){out.push({id:idM[1],priority:"medium"});continue}let prM=/^\s+priority:\s*(low|medium|high|critical)\s*$/.exec(line);if(prM&&out.length>0)out[out.length-1].priority=prM[1]}return out}async function injectForDelegate(params){let{directory,agent,taskTitle,sessionId,config:config3}=params,cap2=config3.delegate_max_inject_count??8,expectedTools=params.expectedTools&&params.expectedTools.length>0?params.expectedTools:defaultExpectedToolsForAgent(agent);if(cap2<=0)return{entries:[],trace_id:""};let role=stripKnownSwarmPrefix(agent).toLowerCase(),firstTool=expectedTools.length>0?expectedTools[0]:void 0,context={currentPhase:taskTitle??"",taskTitle,lastUserMessage:taskTitle,targetAgent:agent,currentTool:firstTool,mode:"delegation"},searchFn=params.searchFn??(_internals91.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals91.searchKnowledge);try{let search=await searchFn({directory,config:config3,context,mode:"delegate_inject",agent,sessionId,tier:"all",applyScopeFilter:!0,applyRoleScope:!1,maxResults:Math.max(40,cap2*4),emitEvent:!1}),capped=search.results.filter((e)=>matchesDelegateScope(e,role,expectedTools)).slice(0,cap2);if(capped.length>0){let ranks={},scores={};capped.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore}),await _internals91.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId??"unknown",phase:params.phase??taskTitle,agent,query:taskTitle??"",retrieval_mode:"delegate_inject",result_ids:capped.map((e)=>e.id),ranks,scores})}return{entries:capped,trace_id:search.trace_id}}catch{return{entries:[],trace_id:""}}}async function injectForDelegateIntoMessages(directory,config3,output,agentName,sessionId){if(!output.messages||output.messages.length===0)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))))return;let taskTitle;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){taskTitle=t.slice(0,800);break}}}let{entries}=await injectForDelegate({directory,agent:agentName,expectedTools:defaultExpectedToolsForAgent(agentName),taskTitle,sessionId,config:config3}),block=buildDelegateDirectiveBlock(entries,config3);if(!block)return;injectKnowledgeMessage(output,block)}function isOrchestratorAgent(agentName){return stripKnownSwarmPrefix(agentName).toLowerCase()==="architect"}var DELEGATED_AGENTS=new Set(["coder","reviewer","test_engineer","sme","docs","designer","critic","curator"]);function isDelegatedAgent(agentName){let stripped=stripKnownSwarmPrefix(agentName).toLowerCase();return DELEGATED_AGENTS.has(stripped)}var DELEGATE_DEFAULT_TOOLS={coder:["edit","write","patch","bash"],reviewer:["read","grep","glob"],test_engineer:["edit","write","bash","read"],sme:["read","grep","glob","webfetch"],docs:["read","edit","write","grep"],designer:["read","write","edit"],critic:["read","grep","glob"],curator:["read","grep","glob"]};function defaultExpectedToolsForAgent(agentName){let role=stripKnownSwarmPrefix(agentName).toLowerCase();return[...DELEGATE_DEFAULT_TOOLS[role]??[]]}var DIRECTIVE_PRIORITY_RANK={critical:0,high:1,medium:2,low:3};function directivePriorityRank(p){return DIRECTIVE_PRIORITY_RANK[p??"medium"]??2}function matchesDelegateScope(entry,role,expectedTools){let agents=(entry.applies_to_agents??[]).map((a)=>stripKnownSwarmPrefix(a).toLowerCase()),tools=(entry.applies_to_tools??[]).map((t)=>t.toLowerCase());if(agents.length===0&&tools.length===0)return!0;let normRole=stripKnownSwarmPrefix(role).toLowerCase();if(agents.includes(normRole))return!0;let expected=expectedTools.map((t)=>t.toLowerCase());if(tools.some((t)=>expected.includes(t)))return!0;return!1}function injectKnowledgeMessage(output,text){if(!output.messages)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(INJECTION_SENTINEL))))return;let insertIdx=output.messages.length-1;for(let i=output.messages.length-1;i>=0;i--)if(output.messages[i].info?.role==="user"){insertIdx=i;break}let knowledgeMessage={info:{role:"system"},parts:[{type:"text",text:`${INJECTION_SENTINEL}${text}`}]};output.messages.splice(insertIdx,0,knowledgeMessage)}function createKnowledgeInjectorHook(directory,config3,modelLimitOverrides={},unifiedInjectionTokens=void 0){function buildContextCacheKey(phase,ctx){let parts=[String(phase),ctx.currentTool??"",ctx.currentAction??"",ctx.targetAgent??"",ctx.taskId??"",(ctx.filePaths??[]).slice(0,8).join(",")].join("|");return createHash19("sha1").update(parts).digest("hex").slice(0,16)}let lastSeenCacheKey=null,cachedInjectionText=null,cachedShownIds=[];return safeHook(async(_input,output)=>{if(!output.messages||output.messages.length===0)return;let plan=await loadPlan(directory),currentPhase=plan?.current_phase??1,CHARS_PER_TOKEN=3.0303030303030303,{modelID,providerID}=extractModelInfo(output.messages),modelLimitTokens=resolveModelLimit(modelID,providerID,modelLimitOverrides),MODEL_LIMIT_CHARS=Math.floor(modelLimitTokens*CHARS_PER_TOKEN),existingChars=output.messages.reduce((sum,msg)=>{return sum+(msg.parts?.reduce((s,p)=>s+(p.text?.length??0),0)??0)},0),headroomChars=MODEL_LIMIT_CHARS-existingChars,MIN_INJECT_CHARS=config3.context_budget_threshold??300;if(headroomChars<MIN_INJECT_CHARS){warn(`[knowledge-injector] Skipping: only ${headroomChars} chars of headroom remain (existing: ${existingChars}, limit: ${MODEL_LIMIT_CHARS})`);return}let maxInjectChars=config3.inject_char_budget??2000,effectiveBudget=headroomChars>=MODEL_LIMIT_CHARS*0.6?maxInjectChars:headroomChars>=MODEL_LIMIT_CHARS*0.2?Math.floor(maxInjectChars*0.5):Math.floor(maxInjectChars*0.25),systemMsg=output.messages.find((m)=>m.info?.role==="system"),agentName=systemMsg?.info?.agent;if(!agentName)return;if(unifiedInjectionTokens!==void 0){let sessionID2=systemMsg?.info?.sessionID,seDemand=sessionID2?getSystemEnhancerDemand(sessionID2):0,allocation=allocateInjectionBudget(seDemand,effectiveBudget,{totalBudgetTokens:unifiedInjectionTokens});effectiveBudget=Math.floor(allocation.knowledgeInjectorTokens/0.33)}if(isDelegatedAgent(agentName)){await injectForDelegateIntoMessages(directory,config3,output,agentName,systemMsg?.info?.sessionID);return}if(!isOrchestratorAgent(agentName))return;let phaseDescription=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${currentPhase}`:"Phase 0",projectName=plan?.title??"unknown",lastUserMessage;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){lastUserMessage=t.slice(0,800);break}}}let taskId=getCurrentTaskId(plan),retrievalCtx={projectName,currentPhase:phaseDescription,mode:"phase_start",lastUserMessage,taskId},cacheKey=buildContextCacheKey(currentPhase,retrievalCtx);if(cacheKey===lastSeenCacheKey&&cachedInjectionText!==null){injectKnowledgeMessage(output,cachedInjectionText);return}lastSeenCacheKey=cacheKey,cachedInjectionText=null;let _context={projectName,currentPhase:phaseDescription},search=await(_internals91.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals91.searchKnowledge)({directory,config:config3,context:retrievalCtx,mode:"auto_injection",agent:"architect",sessionId:systemMsg?.info?.sessionID,emitEvent:!1}),filteredEntries=search.results;cachedShownIds=filteredEntries.map((e)=>e.id);let freshPreamble=null;try{let driftReports=await readPriorDriftReports(directory);if(driftReports.length>0){let latestReport=driftReports[driftReports.length-1],driftText=buildDriftInjectionText(latestReport,500);if(driftText)freshPreamble=sanitizeContextText(driftText)}}catch{}try{let briefingContent=await readSwarmFileAsync(directory,"curator-briefing.md");if(briefingContent){let truncatedBriefing=sanitizeContextText(briefingContent).slice(0,500);freshPreamble=freshPreamble?`<curator_briefing>${truncatedBriefing}</curator_briefing>
5587
+ `)){let idM=/^- id:\s*(\S+)\s*$/.exec(line);if(idM){out.push({id:idM[1],priority:"medium"});continue}let prM=/^\s+priority:\s*(low|medium|high|critical)\s*$/.exec(line);if(prM&&out.length>0)out[out.length-1].priority=prM[1]}return out}async function injectForDelegate(params){let{directory,agent,taskTitle,sessionId,config:config3}=params,cap2=config3.delegate_max_inject_count??8,expectedTools=params.expectedTools&&params.expectedTools.length>0?params.expectedTools:defaultExpectedToolsForAgent(agent);if(cap2<=0)return{entries:[],trace_id:""};let role=stripKnownSwarmPrefix(agent).toLowerCase(),firstTool=expectedTools.length>0?expectedTools[0]:void 0,context={currentPhase:taskTitle??"",taskTitle,lastUserMessage:taskTitle,targetAgent:agent,currentTool:firstTool,mode:"delegation"},searchFn=params.searchFn??(_internals91.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals91.searchKnowledge);try{let search=await searchFn({directory,config:config3,context,mode:"delegate_inject",agent,sessionId,tier:"all",applyScopeFilter:!0,applyRoleScope:!1,maxResults:Math.max(40,cap2*4),emitEvent:!1}),capped=search.results.filter((e)=>matchesDelegateScope(e,role,expectedTools)).slice(0,cap2);if(capped.length>0){let ranks={},scores={};capped.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore}),await _internals91.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId??"unknown",phase:params.phase??taskTitle,agent,query:taskTitle??"",retrieval_mode:"delegate_inject",result_ids:capped.map((e)=>e.id),ranks,scores})}return{entries:capped,trace_id:search.trace_id}}catch{return{entries:[],trace_id:""}}}async function injectForDelegateIntoMessages(directory,config3,output,agentName,sessionId){if(!output.messages||output.messages.length===0)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))))return;let taskTitle;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){taskTitle=t.slice(0,800);break}}}let{entries}=await injectForDelegate({directory,agent:agentName,expectedTools:defaultExpectedToolsForAgent(agentName),taskTitle,sessionId,config:config3}),block=buildDelegateDirectiveBlock(entries,config3);if(!block)return;injectKnowledgeMessage(output,block)}function isOrchestratorAgent(agentName){return stripKnownSwarmPrefix(agentName).toLowerCase()==="architect"}var DELEGATED_AGENTS=new Set(["coder","reviewer","test_engineer","sme","docs","designer","critic","curator"]);function isDelegatedAgent(agentName){let stripped=stripKnownSwarmPrefix(agentName).toLowerCase();return DELEGATED_AGENTS.has(stripped)}var DELEGATE_DEFAULT_TOOLS={coder:["edit","write","patch","bash"],reviewer:["read","grep","glob"],test_engineer:["edit","write","bash","read"],sme:["read","grep","glob","webfetch"],docs:["read","edit","write","grep"],designer:["read","write","edit"],critic:["read","grep","glob"],curator:["read","grep","glob"]};function defaultExpectedToolsForAgent(agentName){let role=stripKnownSwarmPrefix(agentName).toLowerCase();return[...DELEGATE_DEFAULT_TOOLS[role]??[]]}var DIRECTIVE_PRIORITY_RANK={critical:0,high:1,medium:2,low:3};function directivePriorityRank(p){return DIRECTIVE_PRIORITY_RANK[p??"medium"]??2}function matchesDelegateScope(entry,role,expectedTools){let agents=(entry.applies_to_agents??[]).map((a)=>stripKnownSwarmPrefix(a).toLowerCase()),tools=(entry.applies_to_tools??[]).map((t)=>t.toLowerCase());if(agents.length===0&&tools.length===0)return!0;let normRole=stripKnownSwarmPrefix(role).toLowerCase();if(agents.includes(normRole))return!0;let expected=expectedTools.map((t)=>t.toLowerCase());if(tools.some((t)=>expected.includes(t)))return!0;return!1}function injectKnowledgeMessage(output,text){if(!output.messages)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(INJECTION_SENTINEL))))return;let insertIdx=output.messages.length-1;for(let i=output.messages.length-1;i>=0;i--)if(output.messages[i].info?.role==="user"){insertIdx=i;break}let knowledgeMessage={info:{role:"system"},parts:[{type:"text",text:`${INJECTION_SENTINEL}${text}`}]};output.messages.splice(insertIdx,0,knowledgeMessage)}function createKnowledgeInjectorHook(directory,config3,modelLimitOverrides={},unifiedInjectionTokens=void 0){function buildContextCacheKey(phase,ctx){let parts=[String(phase),ctx.currentTool??"",ctx.currentAction??"",ctx.targetAgent??"",ctx.taskId??"",(ctx.filePaths??[]).slice(0,8).join(","),ctx.lastUserMessage?createHash19("sha1").update(ctx.lastUserMessage).digest("hex").slice(0,16):""].join("|");return createHash19("sha1").update(parts).digest("hex").slice(0,16)}let lastSeenCacheKey=null,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[];return safeHook(async(_input,output)=>{if(!output.messages||output.messages.length===0)return;let plan=await loadPlan(directory),currentPhase=plan?.current_phase??1,CHARS_PER_TOKEN=3.0303030303030303,{modelID,providerID}=extractModelInfo(output.messages),modelLimitTokens=resolveModelLimit(modelID,providerID,modelLimitOverrides),MODEL_LIMIT_CHARS=Math.floor(modelLimitTokens*CHARS_PER_TOKEN),existingChars=output.messages.reduce((sum,msg)=>{return sum+(msg.parts?.reduce((s,p)=>s+(p.text?.length??0),0)??0)},0),headroomChars=MODEL_LIMIT_CHARS-existingChars,MIN_INJECT_CHARS=config3.context_budget_threshold??300;if(headroomChars<MIN_INJECT_CHARS){warn(`[knowledge-injector] Skipping: only ${headroomChars} chars of headroom remain (existing: ${existingChars}, limit: ${MODEL_LIMIT_CHARS})`);return}let maxInjectChars=config3.inject_char_budget??2000,effectiveBudget=headroomChars>=MODEL_LIMIT_CHARS*0.6?maxInjectChars:headroomChars>=MODEL_LIMIT_CHARS*0.2?Math.floor(maxInjectChars*0.5):Math.floor(maxInjectChars*0.25),systemMsg=output.messages.find((m)=>m.info?.role==="system"),agentName=systemMsg?.info?.agent;if(!agentName)return;if(unifiedInjectionTokens!==void 0){let sessionID2=systemMsg?.info?.sessionID,seDemand=sessionID2?getSystemEnhancerDemand(sessionID2):0,allocation=allocateInjectionBudget(seDemand,effectiveBudget,{totalBudgetTokens:unifiedInjectionTokens});effectiveBudget=Math.floor(allocation.knowledgeInjectorTokens/0.33)}if(isDelegatedAgent(agentName)){await injectForDelegateIntoMessages(directory,config3,output,agentName,systemMsg?.info?.sessionID);return}if(!isOrchestratorAgent(agentName))return;let phaseDescription=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${currentPhase}`:"Phase 0",projectName=plan?.title??"unknown",lastUserMessage;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){lastUserMessage=t.slice(0,800);break}}}let taskId=getCurrentTaskId(plan),retrievalCtx={projectName,currentPhase:phaseDescription,mode:"phase_start",lastUserMessage,taskId},cacheKey=buildContextCacheKey(currentPhase,retrievalCtx);if(cacheKey===lastSeenCacheKey&&cachedInjectionText!==null){injectKnowledgeMessage(output,cachedInjectionText);let sessionID2=systemMsg?.info?.sessionID;if(sessionID2)if(cachedCriticalIds.length>0)setCriticalShownIds(sessionID2,{ids:cachedCriticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID2);return}lastSeenCacheKey=cacheKey,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[];let _context={projectName,currentPhase:phaseDescription},search=await(_internals91.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals91.searchKnowledge)({directory,config:config3,context:retrievalCtx,mode:"auto_injection",agent:"architect",sessionId:systemMsg?.info?.sessionID,emitEvent:!1}),filteredEntries=search.results,freshPreamble=null;try{let driftReports=await readPriorDriftReports(directory);if(driftReports.length>0){let latestReport=driftReports[driftReports.length-1],driftText=buildDriftInjectionText(latestReport,500);if(driftText)freshPreamble=sanitizeContextText(driftText)}}catch{}try{let briefingContent=await readSwarmFileAsync(directory,"curator-briefing.md");if(briefingContent){let truncatedBriefing=sanitizeContextText(briefingContent).slice(0,500);freshPreamble=freshPreamble?`<curator_briefing>${truncatedBriefing}</curator_briefing>
5553
5588
 
5554
- ${freshPreamble}`:`<curator_briefing>${truncatedBriefing}</curator_briefing>`}}catch{}if(filteredEntries.length===0){if(freshPreamble===null)return;cachedInjectionText=freshPreamble,injectKnowledgeMessage(output,cachedInjectionText);return}let runMemory=await getRunMemorySummary(directory),isFullBudget=effectiveBudget===maxInjectChars,directiveBudget=Math.floor(effectiveBudget*0.45),lessonBudget=Math.floor(effectiveBudget*0.3),directiveEntries=filteredEntries.filter((e)=>e.triggers&&e.triggers.length>0||e.required_actions&&e.required_actions.length>0||e.forbidden_actions&&e.forbidden_actions.length>0||e.directive_priority==="critical"||e.directive_priority==="high"||e.generated_skill_path),directiveBlock=buildDirectiveBlock(directiveEntries,directiveBudget,config3),lessonBlock=buildKnowledgeBlock(filteredEntries,lessonBudget,config3,projectName),parts=[],remaining=effectiveBudget;try{let escalations=await readRecentEscalations(directory),escalationBriefing=buildEscalationBriefing(escalations);if(escalationBriefing&&escalationBriefing.length<=remaining)parts.push(escalationBriefing),remaining-=escalationBriefing.length}catch{}if(directiveBlock)parts.push(directiveBlock),remaining-=directiveBlock.length;if(lessonBlock)parts.push(lessonBlock),remaining-=lessonBlock.length;if(runMemory&&remaining>300){let sanitizedRunMemory=sanitizeContextText(runMemory);parts.push(sanitizedRunMemory),remaining-=sanitizedRunMemory.length}if(freshPreamble&&remaining>200){let preambleToUse=freshPreamble;if(!isFullBudget)preambleToUse=preambleToUse.replace(/<curator_briefing>[\s\S]*?<\/curator_briefing>\s*/g,"");if(preambleToUse.trim().length>0&&preambleToUse.length<=remaining)parts.push(preambleToUse),remaining-=preambleToUse.length}let rejected=await readRejectedLessons(directory);if(rejected.length>0&&remaining>150){let rejectedBlock=`⚠️ Previously rejected patterns (do not re-learn):
5589
+ ${freshPreamble}`:`<curator_briefing>${truncatedBriefing}</curator_briefing>`}}catch{}if(filteredEntries.length===0){let sessionID2=systemMsg?.info?.sessionID;if(sessionID2)clearCriticalShownIds(sessionID2);if(cachedShownIds=[],cachedCriticalIds=[],freshPreamble===null)return;cachedInjectionText=freshPreamble,injectKnowledgeMessage(output,cachedInjectionText);return}let runMemory=null;try{runMemory=await getRunMemorySummary(directory)}catch(err){warn(`[knowledge-injector] run memory summary unavailable: ${err instanceof Error?err.message:String(err)}`)}let isFullBudget=effectiveBudget===maxInjectChars,directiveBudget=Math.floor(effectiveBudget*0.45),lessonBudget=Math.floor(effectiveBudget*0.3),directiveEntries=filteredEntries.filter((e)=>e.triggers&&e.triggers.length>0||e.required_actions&&e.required_actions.length>0||e.forbidden_actions&&e.forbidden_actions.length>0||e.directive_priority==="critical"||e.directive_priority==="high"||e.generated_skill_path),directiveBlock=buildDirectiveBlock(directiveEntries,directiveBudget,config3),lessonBlock=buildKnowledgeBlock(filteredEntries,lessonBudget,config3,projectName),renderedDirectiveIds=getRenderedEntryIds(directiveEntries,directiveBlock,config3,projectName),renderedIdSet=new Set([...renderedDirectiveIds,...getRenderedEntryIds(filteredEntries,lessonBlock,config3,projectName)]),renderedDirectiveIdSet=new Set(renderedDirectiveIds);cachedShownIds=filteredEntries.map((entry)=>entry.id).filter((id)=>renderedIdSet.has(id));let parts=[],remaining=effectiveBudget;try{let escalations=await readRecentEscalations(directory),escalationBriefing=buildEscalationBriefing(escalations);if(escalationBriefing&&escalationBriefing.length<=remaining)parts.push(escalationBriefing),remaining-=escalationBriefing.length}catch{}if(directiveBlock)parts.push(directiveBlock),remaining-=directiveBlock.length;if(lessonBlock)parts.push(lessonBlock),remaining-=lessonBlock.length;if(runMemory&&remaining>300){let sanitizedRunMemory=sanitizeContextText(runMemory);parts.push(sanitizedRunMemory),remaining-=sanitizedRunMemory.length}if(freshPreamble&&remaining>200){let preambleToUse=freshPreamble;if(!isFullBudget)preambleToUse=preambleToUse.replace(/<curator_briefing>[\s\S]*?<\/curator_briefing>\s*/g,"");if(preambleToUse.trim().length>0&&preambleToUse.length<=remaining)parts.push(preambleToUse),remaining-=preambleToUse.length}try{let rejected=await readRejectedLessons(directory);if(rejected.length>0&&remaining>150){let rejectedBlock=`⚠️ Previously rejected patterns (do not re-learn):
5555
5590
  `+rejected.slice(-3).map((r)=>` ⚠️ REJECTED PATTERN: "${sanitizeLessonForContext(r.lesson).slice(0,80)}" — ${sanitizeLessonForContext(r.rejection_reason)}`).join(`
5556
- `);if(rejectedBlock.length<=remaining)parts.push(rejectedBlock)}cachedInjectionText=parts.join(`
5591
+ `);if(rejectedBlock.length<=remaining)parts.push(rejectedBlock)}}catch(err){warn(`[knowledge-injector] rejected pattern warnings unavailable: ${err instanceof Error?err.message:String(err)}`)}cachedInjectionText=parts.join(`
5557
5592
 
5558
- `),injectKnowledgeMessage(output,cachedInjectionText);let sessionID=systemMsg?.info?.sessionID;if(sessionID){let criticalIds=filteredEntries.filter((e)=>e.directive_priority==="critical"&&e.status!=="archived").map((e)=>e.id);if(criticalIds.length>0)setCriticalShownIds(sessionID,{ids:criticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID)}if(cachedShownIds.length>0){let phaseLabel=`Phase ${currentPhase}`,scoreById=new Map(filteredEntries.map((e)=>[e.id,e.finalScore])),ranks={},scores={};cachedShownIds.forEach((id,idx)=>{ranks[id]=idx+1,scores[id]=scoreById.get(id)??0}),await _internals91.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:systemMsg?.info?.sessionID??"unknown",phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",query:retrievalCtx.lastUserMessage??retrievalCtx.currentPhase??"",retrieval_mode:"auto_injection",result_ids:cachedShownIds,ranks,scores}),_internals91.recordKnowledgeShown(directory,cachedShownIds,{phase:phaseLabel,tool:retrievalCtx.currentTool,action:retrievalCtx.currentAction,targetAgent:retrievalCtx.targetAgent,taskId:retrievalCtx.taskId}).catch(()=>{})}})}var _internals91={searchKnowledge,recordKnowledgeEvent,recordKnowledgeShown};init_skill_propagation_gate();init_utils2();function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function extractTaskId2(prompt){let m=/\btask[_-]?id\s*[:=]\s*([A-Za-z0-9._-]{1,80})/i.exec(prompt);return m?m[1]:void 0}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await mkdir30(path153.dirname(filePath),{recursive:!0}),await appendFile16(filePath,`${JSON.stringify(record3)}
5593
+ `),injectKnowledgeMessage(output,cachedInjectionText);let sessionID=systemMsg?.info?.sessionID;if(sessionID){let criticalIds=filteredEntries.filter((e)=>renderedDirectiveIdSet.has(e.id)).filter((e)=>e.directive_priority==="critical"&&e.status!=="archived").map((e)=>e.id);if(cachedCriticalIds=criticalIds,criticalIds.length>0)setCriticalShownIds(sessionID,{ids:criticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID)}if(cachedShownIds.length>0){let phaseLabel=`Phase ${currentPhase}`,scoreById=new Map(filteredEntries.map((e)=>[e.id,e.finalScore])),ranks={},scores={};cachedShownIds.forEach((id,idx)=>{ranks[id]=idx+1,scores[id]=scoreById.get(id)??0}),await _internals91.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:systemMsg?.info?.sessionID??"unknown",phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",query:retrievalCtx.lastUserMessage??retrievalCtx.currentPhase??"",retrieval_mode:"auto_injection",result_ids:cachedShownIds,ranks,scores}),_internals91.recordKnowledgeShown(directory,cachedShownIds,{phase:phaseLabel,tool:retrievalCtx.currentTool,action:retrievalCtx.currentAction,targetAgent:retrievalCtx.targetAgent,taskId:retrievalCtx.taskId}).catch(()=>{})}})}var _internals91={searchKnowledge,recordKnowledgeEvent,recordKnowledgeShown};init_skill_propagation_gate();init_utils2();function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function extractTaskId2(prompt){let m=/\btask[_-]?id\s*[:=]\s*([A-Za-z0-9._-]{1,80})/i.exec(prompt);return m?m[1]:void 0}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await mkdir30(path153.dirname(filePath),{recursive:!0}),await appendFile16(filePath,`${JSON.stringify(record3)}
5559
5594
  `,"utf-8")}async function collectDelegateAcks(params){let result={emitted:[],unacknowledgedCriticals:[]};try{let shown=parseDelegateDirectiveBlock(params.prompt);if(shown.length===0)return result;let shownById=new Map(shown.map((d)=>[d.id,d])),criticalIds=shown.filter((d)=>d.priority==="critical").map((d)=>d.id),acks=parseAcknowledgments(params.transcript),ackedIds=new Set,violatedIds=new Set,sessionId=params.sessionId??"unknown",taskId=params.taskId??extractTaskId2(params.prompt),traceId=newTraceId();for(let ack of acks){if(!shownById.has(ack.id))continue;if(ackedIds.add(ack.id),await recordKnowledgeEvent(params.directory,{type:ack.result,trace_id:traceId,knowledge_id:ack.id,session_id:sessionId,task_id:taskId,agent:params.agent,reason:ack.reason}),ack.result==="violated")violatedIds.add(ack.id);result.emitted.push({id:ack.id,type:ack.result})}for(let id of criticalIds){if(ackedIds.has(id))continue;result.unacknowledgedCriticals.push(id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,reason:"unacknowledged"}),violatedIds.add(id),result.emitted.push({id,type:"violated"});try{await appendUnacknowledgedCritical(params.directory,{timestamp:new Date().toISOString(),knowledge_id:id,agent:params.agent,session_id:sessionId,task_id:taskId,reason:"unacknowledged"})}catch{}}if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}async function collectDelegateAcksAfter(directory,input,output){if(!isTaskTool3(input.tool))return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let agent=parseDelegationArgs(input.args)?.targetAgent??"unknown",sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await collectDelegateAcks({directory,prompt,transcript,agent,sessionId})}var DIRECTIVES_TO_VERIFY_TAG="<directives_to_verify>";var PRIORITY_RANK={critical:0,high:1,medium:2,low:3};function buildDirectiveComplianceBlock(directives){if(directives.length===0)return null;let sorted=[...directives].sort((a,b)=>{let pr=(PRIORITY_RANK[a.priority]??2)-(PRIORITY_RANK[b.priority]??2);if(pr!==0)return pr;return a.id<b.id?-1:a.id>b.id?1:0}),lines=[];lines.push("<directives_to_verify>"),lines.push("Produce a DIRECTIVE_COMPLIANCE verdict for EVERY id below. Run any verification_predicate provided.");for(let d of sorted){if(lines.push(`- id: ${d.id}`),lines.push(` priority: ${d.priority}`),d.lesson)lines.push(` lesson: ${d.lesson}`);if(d.verification_predicate)lines.push(` verification_predicate: ${d.verification_predicate}`)}return lines.push("</directives_to_verify>"),lines.push(""),lines.push(`DIRECTIVE_COMPLIANCE: one line per knowledge directive shown during this phase (the IDs are listed in the DIRECTIVES TO VERIFY block of your prompt). Use exactly one of:
5560
5595
  VERIFIED:<id> evidence=<file:line | predicate_passed>
5561
5596
  VIOLATED:<id> evidence=<file:line | failing_predicate>
@@ -5570,7 +5605,7 @@ ${promptRaw}`,entries.length}catch(err){return warn(`[delegate-directive-injecti
5570
5605
  `);try{injectAdvisory(architectSessionId,summary)}catch{}}}}var WRITE_TOOL_PATTERNS=["write","edit","patch","create","insert","replace","append","prepend"];function isWriteTool3(toolName){let normalized=normalizeToolNameLowerCase(toolName);return WRITE_TOOL_PATTERNS.some((p)=>normalized.includes(p))}var READ_TOOL_PATTERNS=["read","cat","view","fetch","get"];function isReadTool(toolName){let normalized=normalizeToolNameLowerCase(toolName);return READ_TOOL_PATTERNS.some((p)=>normalized.includes(p))}init_constants();init_schema();import*as fs90 from"node:fs";init_constants();import*as fs89 from"node:fs";import*as path154 from"node:path";var READ_ONLY_TOOLS=new Set(["check_gate_status","completion_verify","evidence_check","get_approved_plan","get_qa_gate_profile","diff","diff_summary","imports","symbols","batch_symbols","search","repo_map","retrieve_summary","knowledge_recall","knowledge_query","co_change_analyzer","complexity_hotspots","detect_domains","extract_code_blocks","gitingest","lint","lint_spec","pkg_audit","placeholder_scan","pre_check_batch","quality_budget","sast_scan","sbom_generate","schema_drift","secretscan","syntax_check","test_impact","todo_extract","doc_scan","doc_extract","req_coverage","req_coverage".toLowerCase(),"read","glob","grep","list","ls","view"]),WRITE_LIKE_TOOLS=new Set([...WRITE_TOOL_NAMES,"multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze","suggest_patch"]),SHELL_TOOLS=new Set(["bash","shell","exec","run"]),NETWORK_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request"]),SUBAGENT_TOOLS=new Set(["task","agent","delegate"]),HIGH_RISK_BUILD_PATHS=["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","src/tools/index.ts","package.json","package-lock.json","bun.lock","biome.json","tsconfig.json","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","dist/",".github/workflows/"],ALWAYS_PROTECTED_PREFIXES=[".git/",".git\\"],PROTECTED_PATH_DEFAULTS=[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json"],SAFE_SHELL_PATTERNS=[/^(?:cat|head|tail|less|more|file|stat|wc|sort|uniq|tr|cut|awk|sed)\b/,/^(?:ls|pwd|whoami|hostname|uname|env|date|which|type|tree)\b/,/^(?:echo|printf|true|false|test)\b/,/^(?:grep|rg|ag|find|fd|locate)\b/,/^git\s+(?:status|log|show|diff|branch|describe|rev-parse|rev-list|ls-files|config\s+--get|remote\s+-v|stash\s+list)/,/^(?:bun|npm|yarn|pnpm)\s+(?:run\s+(?:typecheck|lint|test|build)|test|typecheck|lint)\b/,/^node\s+(?:--version|-v|--input-type)/,/^bunx\s+biome\s+(?:ci|check|lint|format)\b/],DENY_SHELL_PATTERNS=[/\brm\s+(?:-[^\s]*\s+)*(?:\/|~|\.)?\s*$|\brm\s+-[rRf]+/i,/\bdd\s+if=/i,/\bmkfs\b/i,/\bshutdown\b|\breboot\b|\bhalt\b|\bpoweroff\b/i,/\b(?:chown|chmod)\s+-R\s+/i,/\bkill\s+-9\b/i,/\bpkill\b|\bkillall\b/i,/\bgit\s+push\s+--force(?!-with-lease)/i,/\bgit\s+push\s+(?:[^\s]+\s+)?(?:main|master|production|prod)\b/i,/\bgit\s+reset\s+--hard\b/i,/\bgit\s+clean\s+-(?:f|d|x)/i,/\bgit\s+branch\s+-D\b/i,/\bgit\s+checkout\s+\.|\bgit\s+restore\s+\./i,/\b(?:cat|head|tail|less|more)\s+[^\n]*(?:\.env|credentials|id_rsa|id_ed25519|\.pem|\.key)/i,/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i,/\bcurl\s+[^|]*\|\s*(?:sh|bash|zsh|fish)\b/i,/\bwget\s+[^|]*\|\s*(?:sh|bash|zsh|fish)\b/i,/\bsudo\s+(?:rm|chmod|chown|dd|mkfs|shutdown)/i,/\bnpm\s+publish\b/i,/\bbun\s+publish\b/i,/\bbunx?\s+publish\b/i,/\bterraform\s+(?:apply|destroy)\b/i,/\bkubectl\s+(?:delete|apply\s+-f)/i,/\bdrop\s+(?:database|table)\b/i,/\bsed\s+-i\b(?=[^\n]*\b(?:biome\.json|eslintrc|oxlintrc)\b)(?=[^\n]*\b(?:error|warn|off)\b)/i,/\b(?:cat|tee)\b[^\n]*>\s*[^\n]*\b(biome\.json|eslintrc|oxlintrc)\b[^\n]*\b(error|warn|off)\b/i],ESCALATE_SHELL_PATTERNS=[/\bcurl\b/i,/\bwget\b/i,/\bssh\b/i,/\bscp\b/i,/\brsync\b/i,/\bsudo\b/i,/\bchmod\b/i,/\bchown\b/i,/\bnpm\s+(?:install|i|add)\b/i,/\bbun\s+(?:install|i|add|remove|update)\b/i,/\byarn\s+(?:install|add|remove|upgrade)\b/i,/\bpnpm\s+(?:install|add|remove|update)\b/i,/\bpip\s+install\b/i,/\bgit\s+push\b/i,/\bgit\s+pull\b/i,/\bgit\s+rebase\b/i,/\bgit\s+merge\b/i,/\bgit\s+commit\b/i,/\b(sed\s+-i|echo\s+|printf\s+)[^\n]*\b(biome\.jsonc?|eslintrc|eslint\.config|oxlintrc|prettierrc|secretscanignore|golangci|tsconfig\.json|tsconfig\.[^.]+\.json)\b/i,/\b(?:cat|tee)\b[^\n]*>\s*[^\n]*\b(biome\.jsonc?|eslintrc|eslint\.config|oxlintrc|prettierrc|secretscanignore|golangci|tsconfig\.json|tsconfig\.[^.]+\.json)\b/i];function isReadOnlyTool(toolName){if(!toolName)return!1;return READ_ONLY_TOOLS.has(toolName.toLowerCase())}function isWriteLikeTool(toolName){if(!toolName)return!1;return WRITE_LIKE_TOOLS.has(toolName.toLowerCase())}function isSubagentDelegation(toolName,args2){let lower=toolName?.toLowerCase()??"";if(SUBAGENT_TOOLS.has(lower))return!0;if(lower==="task"&&args2&&typeof args2==="object")return!0;return!1}function isWithinDirectory(target,root){if(!target||!root)return!1;let resolvedTarget=path154.resolve(target),resolvedRoot=path154.resolve(root);if(resolvedTarget===resolvedRoot)return!0;let withSep=resolvedRoot.endsWith(path154.sep)?resolvedRoot:resolvedRoot+path154.sep;if(process.platform==="win32")return resolvedTarget.toLowerCase().startsWith(withSep.toLowerCase());return resolvedTarget.startsWith(withSep)}var SEGMENT_PROTECTED=new Set([".git",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json"]);function isProtectedPath2(filePath,config3){if(!filePath)return!1;let normalized=normalizePath(filePath);for(let prefix of ALWAYS_PROTECTED_PREFIXES){let np=normalizePath(prefix);if(normalized===np||normalized.startsWith(`${np}/`))return!0}let segments=normalized.split("/").filter(Boolean),allowDefaults=config3?.permission_policy?.allow_defaults!==!1;if(allowDefaults){for(let seg of segments)if(SEGMENT_PROTECTED.has(seg))return!0}let protectedList=[...allowDefaults?PROTECTED_PATH_DEFAULTS:[],...config3?.permission_policy?.protected_paths??[]];for(let candidate of protectedList){let c=normalizePath(candidate);if(!c)continue;if(normalized===c)return!0;if(normalized.startsWith(`${c}/`))return!0;if(!c.includes("/")&&segments.includes(c))return!0}return!1}function classifyPathRisk(filePath,context){if(!filePath)return{withinProjectRoot:!1,withinDeclaredScope:null,protected:!1,highRiskBuild:!1};let absolute=path154.isAbsolute(filePath)?filePath:path154.resolve(context.directory,filePath),resolvedAbsolute=(()=>{try{let candidate=absolute,depth=0;while(depth<32){if(fs89.existsSync(candidate)){if(isWithinDirectory(candidate,context.directory))try{return fs89.realpathSync(candidate)}catch{return candidate}return absolute}let parent=path154.dirname(candidate);if(parent===candidate)break;candidate=parent,depth+=1}return absolute}catch{return absolute}})(),withinProjectRoot=isWithinDirectory(absolute,context.directory)&&isWithinDirectory(resolvedAbsolute,context.directory),relative26=normalizePath(path154.relative(context.directory,absolute)),withinDeclaredScope=null;if(Array.isArray(context.declaredScope))withinDeclaredScope=context.declaredScope.length===0?!1:context.declaredScope.some((scope)=>{let s=normalizePath(scope);if(!s)return!1;return relative26===s||relative26.startsWith(`${s}/`)});let highRiskBuild=HIGH_RISK_BUILD_PATHS.some((entry)=>{let e=normalizePath(entry);if(e.endsWith("/"))return relative26.startsWith(e);return relative26===e||relative26.startsWith(`${e}/`)});return{withinProjectRoot,withinDeclaredScope,protected:!1,highRiskBuild}}var SHELL_METACHARACTER_PATTERN=/[|&;<>`$]|\$\(|\\\n/;function classifyCommandRisk(command,_cwd,_context){if(!command||typeof command!=="string")return{decision:"escalate_critic",reason:"shell command empty or non-string — cannot classify deterministically"};let trimmed=command.trim();for(let re of DENY_SHELL_PATTERNS)if(re.test(trimmed))return{decision:"deny",reason:`shell command matches deny pattern (${re.source})`};let hasMetacharacter=SHELL_METACHARACTER_PATTERN.test(trimmed);if(!hasMetacharacter){for(let re of SAFE_SHELL_PATTERNS)if(re.test(trimmed))return{decision:"allow",reason:"shell command matches deterministically safe pattern"}}for(let re of ESCALATE_SHELL_PATTERNS)if(re.test(trimmed))return{decision:"escalate_critic",reason:`shell command matches escalate pattern (${re.source})`};if(hasMetacharacter)return{decision:"escalate_critic",reason:"shell command contains metacharacters (|, &, ;, <, >, $, backtick) — verify with critic"};return{decision:"escalate_critic",reason:"shell command not in deterministic allow/deny set"}}var PATH_ARG_KEYS=["file_path","filepath","path","file","target","to","dest","destination","output_path"];function extractPathArgs(toolName,args2){if(!args2||typeof args2!=="object")return[];let found=[];for(let key of PATH_ARG_KEYS){let v=args2[key];if(typeof v==="string"&&v.trim())found.push(v)}let filesArg=args2.files;if(Array.isArray(filesArg)){for(let f of filesArg)if(typeof f==="string"&&f.trim())found.push(f);else if(f&&typeof f==="object"&&typeof f.path==="string")found.push(f.path)}let editsArg=args2.edits;if(Array.isArray(editsArg)){for(let e of editsArg)if(e&&typeof e==="object"&&typeof e.file_path==="string")found.push(e.file_path)}if(toolName==="declare_scope"&&Array.isArray(args2.files));return found}function extractCommandArg(args2){if(!args2||typeof args2!=="object")return;return typeof args2.command==="string"&&args2.command||typeof args2.cmd==="string"&&args2.cmd||typeof args2.script==="string"&&args2.script||void 0}function extractURLArg(args2){if(!args2||typeof args2!=="object")return;return typeof args2.url==="string"&&args2.url||typeof args2.uri==="string"&&args2.uri||typeof args2.endpoint==="string"&&args2.endpoint||void 0}function isTrustedDomain(url3,config3){let domains=config3?.permission_policy?.trusted_domains??[];if(domains.length===0)return!1;let host="";try{host=new URL(url3).hostname.toLowerCase()}catch{return!1}return domains.some((d)=>{let dl=d.toLowerCase();return host===dl||host.endsWith(`.${dl}`)})}function classifyFullAutoToolAction(input){let tool3=input.toolName?.toLowerCase()??"",config3=input.fullAutoConfig,mode=config3?.mode??"supervised";if(!(mode==="strict"||config3?.permission_policy?.enabled!==!1))return{action:"allow",reason:"permission policy disabled by config",tier:"local"};if(isReadOnlyTool(tool3))return{action:"allow",reason:"read-only tool",tier:"safe"};if(isSubagentDelegation(tool3,input.args)){let subagentName=typeof input.args?.subagent_type==="string"&&input.args.subagent_type||typeof input.args?.agent==="string"&&input.args.agent||"unknown";return{action:"escalate_critic",reason:"subagent delegation requires plan/scope verification",risk:"high",context:{tool:tool3,subagent:subagentName,currentTaskID:input.currentTaskID,currentPhase:input.currentPhase}}}if(tool3==="phase_complete")return{action:"escalate_critic",reason:"phase_complete requires Full-Auto approval evidence",risk:"high",context:{tool:tool3,currentPhase:input.currentPhase}};if(tool3==="update_task_status"){let status=typeof input.args?.status==="string"&&input.args.status||"";if(status==="completed"){if(mode==="strict"||config3?.oversight?.on_task_completion===!0)return{action:"escalate_critic",reason:"task completion requires Full-Auto critic verification",risk:"medium",context:{tool:tool3,status}}}else{if(mode==="strict")return{action:"escalate_critic",reason:`strict mode: update_task_status with status=${status} requires critic verification`,risk:"medium",context:{tool:tool3,status}};return{action:"allow",reason:`update_task_status with status=${status} is a routine state change`,tier:"local"}}}if(tool3==="save_plan")return{action:"escalate_critic",reason:"plan mutation requires Full-Auto critic verification",risk:"high",context:{tool:tool3}};if(NETWORK_TOOLS.has(tool3)){let url3=extractURLArg(input.args);if(url3&&isTrustedDomain(url3,config3))return{action:"allow",reason:"network tool with trusted domain",tier:"local"};return{action:"escalate_critic",reason:"network/web tool — verify intent and target",risk:"medium",context:{tool:tool3,url:url3}}}if(SHELL_TOOLS.has(tool3)){let command=extractCommandArg(input.args);if(!command)return{action:"deny",reason:"shell tool invoked without a command argument",code:"shell_no_command",recoverable:!0};let cmdRisk=classifyCommandRisk(command,input.workingDirectory??"",{directory:input.directory});if(cmdRisk.decision==="deny")return{action:"deny",reason:cmdRisk.reason,code:"shell_deny",recoverable:!0};if(cmdRisk.decision==="allow")return{action:"allow",reason:cmdRisk.reason,tier:"local"};return{action:"escalate_critic",reason:cmdRisk.reason,risk:"medium",context:{tool:tool3,command}}}if(isWriteLikeTool(tool3)||tool3==="patch"||tool3==="edit"){let paths=extractPathArgs(tool3,input.args);if(paths.length===0){if(new Set(["declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze"]).has(tool3))return{action:"allow",reason:`pathless plan/evidence tool '${tool3}' allowed under Full-Auto`,tier:"local"};return{action:"escalate_critic",reason:"write-like tool without explicit path — verify side effects",risk:"medium",context:{tool:tool3,args:input.args}}}for(let p of paths){let risk=classifyPathRisk(p,{directory:input.directory,declaredScope:input.declaredScope??null});if(!risk.withinProjectRoot)return{action:"deny",reason:`write target outside project root: ${p}`,code:"path_out_of_root",recoverable:!0};if(isProtectedPath2(path154.relative(input.directory,path154.resolve(input.directory,p)),config3))return{action:"escalate_critic",reason:`write to protected path requires critic approval: ${p}`,risk:"high",context:{tool:tool3,path:p}};if(risk.highRiskBuild)return{action:"escalate_critic",reason:`write to high-risk build/plugin path requires critic approval: ${p}`,risk:"high",context:{tool:tool3,path:p}};if(input.normalizedAgentName==="coder"&&Array.isArray(input.declaredScope)&&input.declaredScope.length>0&&risk.withinDeclaredScope===!1)return{action:"deny",reason:`coder write outside declared scope: ${p}`,code:"path_out_of_scope",recoverable:!0}}return{action:"allow",reason:"write within project root and declared scope",tier:"local"}}return{action:"escalate_critic",reason:`tool '${tool3||"<empty>"}' not deterministically classifiable`,risk:"medium",context:{tool:tool3}}}function buildStructuredDenial(decision,tool3){return{full_auto_denial:!0,tool:tool3,code:decision.code,reason:decision.reason,recoverable:decision.recoverable,guidance:decision.recoverable?"Choose a safer path: stay within the project root, respect declared scope, avoid destructive shell, and avoid protected paths. Consider declaring scope or escalating to a human.":"This action cannot be retried under Full-Auto. Ask a human to authorize it."}}init_state3();init_file_locks();init_state2();init_logger();init_normalize_tool_name();init_utils2();var RETURN_WARNING_PATTERNS=[{category:"skipped_tests",regex:/\b(?:skipped (?:the )?tests?|tests? (?:were |was )?skipped|did(?:n['']t)? run tests?|tests? not run|bypass(?:ed)? (?:the )?tests?|test (?:step|phase) (?:was )?bypass|tests? (?:are )?failing|tests? (?:are )?broken)\b/i},{category:"tool_timeout",regex:/\b(?:tool|process|command|test|build|lint)\s+(?:timed out|timeout|hung|killed|aborted|terminated|did not (?:complete|finish))/i},{category:"scope_changed",regex:/\b(?:expanded|changed|widened|exceeded|broke|extended|enlarged|grew|altered|adjusted) (?:the )?(?:declared |working |task |allowed )?(?:scope|file ?list|file ?set|working set|set of files)\b|\bscope (?:expansion|creep|drift|change)\b/i},{category:"external_instructions",regex:/\b(?:followed |received |applied |honored |obeyed )?(?:instructions|directives|guidance|orders|commands|hints) (?:from|in|per|according to) (?:the )?(?:tool output|web|search|fetched|fetch|external|untrusted|upstream|page|site|doc|documentation|response|prompt)\b|\bper (?:the )?(?:upstream|external|fetched|web|tool) (?:doc|documentation|page|response|content|guidance)\b/i},{category:"unable_to_verify",regex:/\b(?:unable|could ?n['']t|cannot|can ?not|wasn['']?t able) (?:to )?(?:verify|confirm|reproduce|test|check|validate|prove)\b|\bverification (?:deferred|skipped|postponed|incomplete|pending|impossible)\b/i},{category:"missing_evidence",regex:/\b(?:no |missing |without |lacking )(?:evidence|proof|verification|tests? passing|test results|coverage)\b|\bevidence (?:is )?(?:missing|absent|unavailable)\b/i},{category:"out_of_scope_files",regex:/\b(?:created|generated|wrote|modified|added|edited|patched|touched) (?:files? |code )?(?:outside|beyond|past|not in|that (?:are|were) outside) (?:the )?(?:declared |task |coder |allowed )?(?:scope|file ?list|file ?set|allowed (?:paths|files))\b/i}],SEVERE_CATEGORIES=new Set(["external_instructions","out_of_scope_files"]),CANONICAL_ROLES_LOWER=new Set(ALL_AGENT_NAMES.map((s)=>s.toLowerCase()));function isExactCanonicalRole(name){return CANONICAL_ROLES_LOWER.has(name.toLowerCase())}function isTaskTool5(toolName){let lower=toolName?.toLowerCase()??"";return lower==="task"||lower==="agent"||lower==="delegate"}function extractText(value){if(typeof value==="string")return value;if(value&&typeof value==="object"){let o=value;if(typeof o.output==="string")return o.output;if(typeof o.text==="string")return o.text;if(typeof o.summary==="string")return o.summary;try{return JSON.stringify(o)}catch{return""}}return""}function detectReturnWarnings(text){let warnings=[];if(!text)return warnings;let seen=new Set;for(let{category,regex}of RETURN_WARNING_PATTERNS){let m=text.match(regex);if(!m)continue;let key=`${category}:${m[0].toLowerCase()}`;if(seen.has(key))continue;seen.add(key),warnings.push({category,matched:m[0]})}return warnings}async function writeDelegationEvent(directory,event){let lockTaskId=`full-auto-delegation-${Date.now()}`,lockResult;try{lockResult=await tryAcquireLock(directory,"events.jsonl","full-auto-delegation",lockTaskId)}catch(error93){warn(`[full-auto/delegation] failed to acquire lock: ${error93 instanceof Error?error93.message:String(error93)}`)}try{let eventsPath=validateSwarmPath(directory,"events.jsonl");fs90.appendFileSync(eventsPath,`${JSON.stringify(event)}
5571
5606
  `,"utf-8")}catch(error93){throw error48(`[full-auto/delegation] failed to write event: ${error93 instanceof Error?error93.message:String(error93)}`),error93}finally{if(lockResult?.acquired&&lockResult.lock._release)try{await lockResult.lock._release()}catch(releaseError){error48("[full-auto/delegation] lock release failed:",releaseError)}}}function createFullAutoDelegationHook(options){let{config:config3,directory}=options;return{toolBefore:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!isTaskTool5(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let args2=output.args??{},subagentRaw=typeof args2.subagent_type==="string"&&args2.subagent_type||typeof args2.agent==="string"&&args2.agent||"",generatedAgentRegistry=swarmState.generatedAgentNames,canonicalRole=generatedAgentRegistry.length>0?resolveGeneratedAgentRole(subagentRaw,generatedAgentRegistry):getCanonicalAgentRole(subagentRaw);if(subagentRaw&&canonicalRole!==subagentRaw&&!isExactCanonicalRole(subagentRaw)){let prefix=subagentRaw.slice(0,subagentRaw.length-canonicalRole.length-1);if(!prefix||!/[A-Za-z0-9]/.test(prefix))throw Error(`FULL_AUTO_DELEGATION_DENY: subagent name '${subagentRaw}' has no valid prefix before the canonical role '${canonicalRole}'. Generated agent names must include a non-empty swarm prefix.`)}let promptText=typeof args2.prompt==="string"&&args2.prompt||typeof args2.message==="string"&&args2.message||typeof args2.task==="string"&&args2.task||"";if(incrementFullAutoCounter(directory,sessionID,"coderDelegations"),!subagentRaw||!isKnownCanonicalRole(canonicalRole))throw Error(`FULL_AUTO_DELEGATION_DENY: unknown subagent '${subagentRaw}' (canonical role '${canonicalRole}' is not a registered plugin role). Choose a generated agent whose suffix matches one of the canonical roles.`);if(canonicalRole==="coder"){let declared=swarmState.agentSessions.get(sessionID)?.declaredCoderScope,argScope=Array.isArray(args2.files)||Array.isArray(args2.scope);if((!declared||declared.length===0)&&!argScope)throw Error(`FULL_AUTO_DELEGATION_DENY: coder delegation '${subagentRaw}' requires declared scope. Call declare_scope first or include 'files' in the Task arguments.`)}if(promptText&&typeof promptText==="string"){let candidatePaths=promptText.match(/\b[A-Za-z0-9._/-]+\.(?:ts|tsx|js|jsx|json|md|yml|yaml|toml|lock|sh|env)\b/g);if(candidatePaths){for(let p of candidatePaths)if(isProtectedPath2(p,config3.full_auto))await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,subagent:subagentRaw,canonical_role:canonicalRole,phase:"outbound",category:"protected_path_in_prompt",matched:p})}}},toolAfter:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!isTaskTool5(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let text=extractText(output.output),warnings=detectReturnWarnings(text);if(warnings.length===0)return;let severe=warnings.some((w)=>SEVERE_CATEGORIES.has(w.category));if(await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,phase:"return",warnings,severe}),runState.counters.consecutiveNoProgressTurns=severe?runState.counters.consecutiveNoProgressTurns+1:runState.counters.consecutiveNoProgressTurns,saveFullAutoRunState(directory,runState),severe){let updated=loadFullAutoRunState(directory,sessionID);if(updated&&updated.status==="running")updated.status="paused",updated.pauseReason=`severe subagent return warning: ${warnings.filter((w)=>SEVERE_CATEGORIES.has(w.category)).map((w)=>w.category).join(",")}`,saveFullAutoRunState(directory,updated)}}}}import*as fs91 from"node:fs";var PATTERNS=[{category:"instruction_override",regex:/\bignore (?:all |any |the )?(?:previous|prior|earlier|above) (?:instructions|prompts|rules|directives)\b/i},{category:"instruction_override",regex:/\bdisregard (?:all |any |the )?(?:previous|prior|earlier|above) (?:instructions|prompts|rules)\b/i},{category:"instruction_override",regex:/\bforget (?:all |any |everything|the )?(?:previous|above|prior) (?:instructions|prompts|rules)\b/i},{category:"system_role_override",regex:/\b(?:you are now|act as|pretend to be|from now on you are)\s+(?:a |an |the )?(?:system|developer|root|admin|superuser)\b/i},{category:"system_role_override",regex:/\b<\|?(?:system|developer|im_start|imstart)\|?>/i},{category:"credential_request",regex:/\b(?:please |kindly |)(?:paste|share|reveal|send|provide|leak|print|echo|cat) (?:your |the |my )?(?:api[_ -]?key|password|token|secret|credentials|\.env)\b/i},{category:"credential_request",regex:/\b(?:show|dump|export) (?:env(?:ironment)?|secrets|credentials|keys?)\b/i},{category:"exfiltration_request",regex:/\b(?:upload|exfiltrate|send) (?:contents of |files? from |the )?(?:home|repo|workspace|project|secrets?|env(?:ironment)?)\b/i},{category:"exfiltration_request",regex:/\bcurl\s+-d\s+@/i},{category:"guardrail_disable_request",regex:/\bdisable (?:full[- ]auto|guardrails?|safety|policy|oversight|critic)\b/i},{category:"guardrail_disable_request",regex:/\bturn (?:off|disable) (?:full[- ]auto|guardrails?|safety|policy)\b/i},{category:"curl_pipe_shell",regex:/\bcurl\b[^|\n]*\|\s*(?:sh|bash|zsh|fish)\b/i},{category:"untrusted_run_command",regex:/\b(?:run|execute|paste) (?:this|the following) (?:command|script|bash|shell)\b/i}];function buildExcerpt(text,match){let idx=match.index??0,start=Math.max(0,idx-120),end=Math.min(text.length,idx+match[0].length+120),slice=text.slice(start,end).replace(/\s+/g," ").trim();return slice.length>280?`${slice.slice(0,280)}…`:slice}function probeFullAutoInput(text){let warnings=[];if(!text||typeof text!=="string")return{hasWarning:!1,warnings};let seen=new Set;for(let{category,regex}of PATTERNS){let m=text.match(regex);if(!m)continue;let key=`${category}:${m[0].toLowerCase()}`;if(seen.has(key))continue;seen.add(key),warnings.push({category,matched:m[0],excerpt:buildExcerpt(text,m)})}return{hasWarning:warnings.length>0,warnings}}var RISKY_FOLLOWUP_TOOLS=new Set(["bash","shell","exec","web_search","webfetch","web_fetch","fetch","http","request"]),SECRET_TOOL_PATTERNS=[/\b(?:cat|head|tail|less|more)\s+[^\n]*\.env/i,/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i];function shouldEscalateAfterWarning(toolName,commandOrUrl){let lower=toolName?.toLowerCase()??"";if(RISKY_FOLLOWUP_TOOLS.has(lower))return!0;if(typeof commandOrUrl==="string"){for(let re of SECRET_TOOL_PATTERNS)if(re.test(commandOrUrl))return!0}return!1}init_state3();init_file_locks();init_logger();init_normalize_tool_name();init_utils2();var PROBED_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request","doc_extract","doc_scan","gitingest","extract_code_blocks","retrieve_summary","retrieve_lane_output","search","read","view"]);async function writeWarningEvent(directory,sessionID,tool3,probe2){let event={type:"full_auto_input_warning",timestamp:new Date().toISOString(),session_id:sessionID,tool:tool3,warnings:probe2.warnings},lockTaskId=`full-auto-input-warning-${Date.now()}`,lockResult;try{lockResult=await tryAcquireLock(directory,"events.jsonl","full-auto-input-warning",lockTaskId)}catch(error93){warn(`[full-auto/input-probe] failed to acquire lock: ${error93 instanceof Error?error93.message:String(error93)}`)}try{let eventsPath=validateSwarmPath(directory,"events.jsonl");fs91.appendFileSync(eventsPath,`${JSON.stringify(event)}
5572
5607
  `,"utf-8")}catch(error93){error48(`[full-auto/input-probe] failed to write event: ${error93 instanceof Error?error93.message:String(error93)}`)}finally{if(lockResult?.acquired&&lockResult.lock._release)try{await lockResult.lock._release()}catch(releaseError){error48("[full-auto/input-probe] lock release failed:",releaseError)}}}function extractText2(out){if(typeof out==="string")return out;if(out&&typeof out==="object"){let candidate=out;if(typeof candidate.output==="string")return candidate.output;if(typeof candidate.text==="string")return candidate.text;if(typeof candidate.body==="string")return candidate.body;try{return JSON.stringify(candidate)}catch{return""}}return""}var MAX_TRACKED_SESSIONS4=256,WARNING_TTL_MS=300000,fullAutoInputWarningStash=new Map;function isExpired2(w,nowMs=Date.now()){let at=Date.parse(w.at);if(!Number.isFinite(at))return!0;return nowMs-at>WARNING_TTL_MS}function evictExpired(){let now=Date.now();for(let[sid,w]of fullAutoInputWarningStash)if(isExpired2(w,now))fullAutoInputWarningStash.delete(sid);while(fullAutoInputWarningStash.size>MAX_TRACKED_SESSIONS4){let firstKey=fullAutoInputWarningStash.keys().next().value;if(firstKey===void 0)break;fullAutoInputWarningStash.delete(firstKey)}}function setPendingInputWarning(sessionID,warning){fullAutoInputWarningStash.delete(sessionID),fullAutoInputWarningStash.set(sessionID,warning),evictExpired()}function consumePendingInputWarning(sessionID){let warning=fullAutoInputWarningStash.get(sessionID);if(warning)fullAutoInputWarningStash.delete(sessionID);if(warning&&isExpired2(warning))return;return warning}function peekPendingInputWarning(sessionID){let w=fullAutoInputWarningStash.get(sessionID);if(!w)return;if(isExpired2(w)){fullAutoInputWarningStash.delete(sessionID);return}return w}function createFullAutoInputProbeHook(options){let{directory}=options;return{toolAfter:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!PROBED_TOOLS.has(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let text=extractText2(output.output);if(!text)return;let probe2=probeFullAutoInput(text);if(!probe2.hasWarning)return;setPendingInputWarning(sessionID,{tool:tool3,at:new Date().toISOString(),categories:probe2.warnings.map((w)=>w.category)}),await writeWarningEvent(directory,sessionID,tool3,probe2)}}}init_constants();init_schema();init_state3();init_scope_persistence();init_state2();init_delegation_gate();init_normalize_tool_name();function createFullAutoPermissionHook(options){let{config:config3,directory}=options,fullAutoConfig=config3.full_auto;return{toolBefore:async(input,output)=>{let toolName=normalizeToolName(input.tool)??input.tool,sessionID=input.sessionID;if(!sessionID)return;let stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable){if(isReadOnlyTool(toolName))return;throw Error(`FULL_AUTO_STATE_UNREADABLE: tool '${toolName}' blocked because the Full-Auto durable state file is unreadable (${stateHealth.reason}). Restore .swarm/full-auto-state.json (or .bak) and re-run /swarm full-auto on.`)}let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status==="idle")return;if(runState.status==="paused"||runState.status==="terminated"){if(isReadOnlyTool(toolName))return;throw Error(`FULL_AUTO_${runState.status.toUpperCase()}: tool '${toolName}' blocked because Full-Auto run is ${runState.status} (${runState.pauseReason??runState.terminateReason??"no reason recorded"}). Re-enable with /swarm full-auto on after the underlying issue is resolved.`)}let session=swarmState.agentSessions.get(sessionID),activeAgent=swarmState.activeAgent.get(sessionID)??session?.agentName??ORCHESTRATOR_NAME,normalizedAgentName=stripKnownSwarmPrefix(activeAgent),taskId=session?.currentTaskId??null,declaredScope=resolveScopeWithFallbacks({directory,taskId,inMemoryScope:session?.declaredCoderScope,pendingMapScope:taskId?pendingCoderScopeByTaskId.get(taskId):null})??null,argsObj=output.args??void 0,lowerTool=toolName?.toLowerCase()??"",phaseFromArgs;if(lowerTool==="phase_complete"){if(phaseFromArgs=parsePhaseArg(argsObj),phaseFromArgs===void 0)throw Error("FULL_AUTO_DENY [phase_complete_invalid_phase]: phase_complete called without a valid 'phase' argument. Provide a positive integer phase before calling phase_complete.")}let effectivePhase=phaseFromArgs??runState.currentPhase,safeMode=["assisted","supervised","strict"].includes(runState.mode)?runState.mode:"strict",effectiveFullAutoConfig=fullAutoConfig?{...fullAutoConfig,mode:safeMode}:{mode:safeMode},classifierInput={sessionID,agentName:activeAgent,normalizedAgentName,toolName,args:argsObj,directory,declaredScope,currentTaskID:taskId,currentPhase:effectivePhase,planSummary:void 0,changedFiles:session?.modifiedFilesThisCoderTask,fullAutoConfig:effectiveFullAutoConfig},decision=classifyFullAutoToolAction(classifierInput),pendingWarning=peekPendingInputWarning(sessionID);if(pendingWarning){let commandOrUrl=typeof argsObj?.command==="string"&&argsObj.command||typeof argsObj?.url==="string"&&argsObj.url||void 0;if(shouldEscalateAfterWarning(toolName,commandOrUrl))decision={action:"escalate_critic",reason:`risky follow-up after prompt-injection warning (${pendingWarning.categories.join(",")})`,risk:"high",context:{tool:toolName,priorWarningTool:pendingWarning.tool,categories:pendingWarning.categories}},consumePendingInputWarning(sessionID)}if(decision.action==="allow"){tickAndMaybeDispatchCadence(directory,sessionID,"toolCalls",config3,{activeAgent}),resetFullAutoDenials(directory,sessionID);return}if(decision.action==="deny"){let denial=buildStructuredDenial(decision,toolName);recordFullAutoDenial(directory,sessionID,{tool:toolName,code:decision.code,reason:decision.reason});let updated2=loadFullAutoRunState(directory,sessionID);if(updated2){let pauseDecision=shouldPauseForDenials(updated2,fullAutoConfig);if(pauseDecision.pause)if(pauseDecision.mode==="terminate")terminateFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit");else pauseFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit")}throw Error(`FULL_AUTO_DENY [${decision.code}]: ${decision.reason}. ${JSON.stringify(denial)}`)}if(decision.action==="pause")throw pauseFullAutoRun(directory,sessionID,decision.reason),Error(`FULL_AUTO_PAUSE [${decision.code}]: ${decision.reason}`);if(decision.action==="escalate_human")throw terminateFullAutoRun(directory,sessionID,decision.reason),Error(`FULL_AUTO_ESCALATE_HUMAN [${decision.code}]: ${decision.reason}`);let triggerSource=mapTriggerSource(decision,toolName),criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle",oversightAgentName=resolveOversightAgentNameFromActive(activeAgent);if(lowerTool==="phase_complete"&&effectivePhase!==void 0){let stateForPhase=loadFullAutoRunState(directory,sessionID);if(stateForPhase&&stateForPhase.currentPhase!==effectivePhase){stateForPhase.currentPhase=effectivePhase;try{saveFullAutoRunState(directory,stateForPhase)}catch(persistErr){let msg=persistErr instanceof Error?persistErr.message:String(persistErr);throw Error(`FULL_AUTO_BLOCKED: failed to persist phase ${effectivePhase} to durable run state — ${msg}`)}}}let outcome;try{outcome=await dispatchFullAutoOversight({directory,sessionID,trigger:decision.reason,triggerSource,phase:effectivePhase,taskID:taskId??void 0,planID:runState.planID,architectOutput:output.args?JSON.stringify(output.args):void 0,actionContext:{tool:toolName,...decision.context??{}},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:fullAutoConfig?.fail_closed!==!1}})}catch(error93){let reason=error93 instanceof Error?error93.message:String(error93);throw pauseFullAutoRun(directory,sessionID,`oversight dispatcher exception: ${reason}`),Error(`FULL_AUTO_BLOCKED: oversight dispatch threw — ${reason}`)}if(outcome.decision==="allow"){tickAndMaybeDispatchCadence(directory,sessionID,"toolCalls",config3,{activeAgent}),resetFullAutoDenials(directory,sessionID);return}if(outcome.decision==="pause")throw Error(`FULL_AUTO_BLOCKED: critic verdict ${outcome.verdict} — ${outcome.reasoning}`);if(outcome.decision==="escalate_human")throw Error(`FULL_AUTO_ESCALATE_HUMAN: critic verdict ${outcome.verdict} — ${outcome.reasoning}`);recordFullAutoDenial(directory,sessionID,{tool:toolName,code:`critic_${outcome.verdict}`.toLowerCase(),reason:outcome.reasoning||`critic verdict ${outcome.verdict}`});let updated=loadFullAutoRunState(directory,sessionID);if(updated){let pauseDecision=shouldPauseForDenials(updated,fullAutoConfig);if(pauseDecision.pause)if(pauseDecision.mode==="terminate")terminateFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit");else pauseFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit")}throw Error(`FULL_AUTO_CRITIC_DENY: ${outcome.verdict} — ${outcome.reasoning}`)}}}function parsePhaseArg(args2){if(!args2)return;let raw=args2.phase,n;if(typeof raw==="number")n=raw;else if(typeof raw==="string"&&raw.trim()){let trimmed=raw.trim();if(!/^[1-9][0-9]*$/.test(trimmed))return;n=Number.parseInt(trimmed,10)}else return;if(!Number.isFinite(n)||!Number.isInteger(n)||n<1)return;if(n>Number.MAX_SAFE_INTEGER)return;return n}function mapTriggerSource(decision,toolName){if(decision.action!=="escalate_critic")return"tool_action";let lower=toolName?.toLowerCase()??"";if(lower==="phase_complete")return"phase_boundary";if(lower==="update_task_status")return"task_completion";if(decision.risk==="high")return"risk";return"tool_action"}function resolveOversightAgentNameFromActive(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME){let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`}return"critic_oversight"}init_guardrails2();init_hive_promoter();import*as fs92 from"node:fs";import*as path155 from"node:path";import*as child_process11 from"node:child_process";var WIN32_CMD_BINARIES=new Set(["npm","npx","pnpm","yarn"]);function spawnAsync(command,cwd,timeoutMs){return new Promise((resolve55)=>{try{let[rawCmd,...args2]=command,cmd=process.platform==="win32"&&WIN32_CMD_BINARIES.has(rawCmd)&&!rawCmd.includes(".")?`${rawCmd}.cmd`:rawCmd,proc=child_process11.spawn(cmd,args2,{cwd,stdio:["ignore","pipe","pipe"]}),stdout="",stderr="",done=!1,MAX_OUTPUT=524288;proc.stdout.on("data",(d)=>{if(stdout.length<MAX_OUTPUT){if(stdout+=d,stdout.length>=MAX_OUTPUT){stdout=stdout.slice(0,MAX_OUTPUT);try{proc.stdout.destroy()}catch{}}}}),proc.stderr.on("data",(d)=>{if(stderr.length<MAX_OUTPUT){if(stderr+=d,stderr.length>=MAX_OUTPUT){stderr=stderr.slice(0,MAX_OUTPUT);try{proc.stderr.destroy()}catch{}}}});let timer=setTimeout(()=>{if(done)return;done=!0;try{proc.stdout.destroy()}catch{}try{proc.stderr.destroy()}catch{}try{proc.kill()}catch{}resolve55(null)},timeoutMs);proc.on("close",(code)=>{if(done)return;done=!0,clearTimeout(timer),resolve55({exitCode:code??1,stdout,stderr})}),proc.on("error",()=>{if(done)return;done=!0,clearTimeout(timer),resolve55(null)})}catch{resolve55(null)}})}var emittedSkipAdvisories=new Set;function detectPackageManager(projectDir){if(fs92.existsSync(path155.join(projectDir,"bun.lockb")))return"bun";if(fs92.existsSync(path155.join(projectDir,"pnpm-lock.yaml")))return"pnpm";if(fs92.existsSync(path155.join(projectDir,"yarn.lock")))return"yarn";if(fs92.existsSync(path155.join(projectDir,"package-lock.json")))return"npm";return"bun"}function detectTypecheckCommand(projectDir){let pkgPath=path155.join(projectDir,"package.json");if(fs92.existsSync(pkgPath))try{let pkg=JSON.parse(fs92.readFileSync(pkgPath,"utf8")),scripts=pkg.scripts;if(scripts?.typecheck)return{command:[detectPackageManager(projectDir),"run","typecheck"],language:"typescript"};if(scripts?.["type-check"])return{command:[detectPackageManager(projectDir),"run","type-check"],language:"typescript"};let deps={...pkg.dependencies,...pkg.devDependencies};if(!deps?.typescript&&!fs92.existsSync(path155.join(projectDir,"tsconfig.json")));if(deps?.typescript||fs92.existsSync(path155.join(projectDir,"tsconfig.json")))return{command:["npx","tsc","--noEmit"],language:"typescript"}}catch{return null}if(fs92.existsSync(path155.join(projectDir,"go.mod")))return{command:["go","vet","./..."],language:"go"};if(fs92.existsSync(path155.join(projectDir,"Cargo.toml")))return{command:["cargo","check"],language:"rust"};if(fs92.existsSync(path155.join(projectDir,"pyproject.toml"))||fs92.existsSync(path155.join(projectDir,"requirements.txt"))||fs92.existsSync(path155.join(projectDir,"setup.py")))return{command:null,language:"python"};try{if(fs92.readdirSync(projectDir).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))return{command:["dotnet","build","--no-restore"],language:"csharp"}}catch{}return null}async function runWithTimeout(command,cwd,timeoutMs){let result=await spawnAsync(command,cwd,timeoutMs);if(result===null)return null;return{exitCode:result.exitCode,stderr:result.stderr}}function createIncrementalVerifyHook(config3,projectDir,injectMessage){return{toolAfter:async(input,output)=>{if(!config3.enabled)return;if(input.tool!=="Task")return;let args2=input.args??output.args,subagentType=typeof args2?.subagent_type==="string"?args2.subagent_type:"",agentName=subagentType.replace(/^[^_]+_/,"");if(!config3.triggerAgents.includes(agentName)&&!config3.triggerAgents.includes(subagentType))return;let commandToRun=null;if(config3.command!=null)if(Array.isArray(config3.command))commandToRun=config3.command;else commandToRun=config3.command.split(" ");else{let detected=detectTypecheckCommand(projectDir);if(detected===null)return;if(detected.command===null){let dedupKey=`${input.sessionID}:${detected.language}`;if(!emittedSkipAdvisories.has(dedupKey))emittedSkipAdvisories.add(dedupKey),injectMessage(input.sessionID,`POST-CODER CHECK SKIPPED: ${detected.language} project detected but no default checker available. Set incremental_verify.command in .swarm/config.json to enable.`);return}commandToRun=detected.command}if(commandToRun===null)return;let result=await runWithTimeout(commandToRun,projectDir,config3.timeoutMs);if(result===null)return;if(result.exitCode===0)injectMessage(input.sessionID,"POST-CODER CHECK PASSED: No type errors.");else{let errorSummary=result.stderr.slice(0,800);injectMessage(input.sessionID,`POST-CODER CHECK FAILED: Type errors detected after coder delegation. Address these before proceeding.
5573
- ${errorSummary}`)}}}}init_schema();init_state2();init_logger();import{appendFile as appendFile17,mkdir as mkdir31}from"node:fs/promises";import*as path156 from"node:path";var HIGH_RISK_TOOLS=new Set(["save_plan","update_task_status","phase_complete","task","Task","skill_regenerate","skill_retire"]);async function knowledgeApplicationGateBefore(directory,input,config3){if(!config3.enabled)return;let toolName=typeof input.tool==="string"?input.tool:"";if(!(config3.high_risk_tools?new Set(config3.high_risk_tools):HIGH_RISK_TOOLS).has(toolName))return;let agentRaw=typeof input.agent==="string"?input.agent:"";if(!agentRaw)return;if(stripKnownSwarmPrefix(agentRaw)!=="architect")return;let sessionID=typeof input.sessionID==="string"?input.sessionID:void 0;if(!sessionID){if(config3.mode==="enforce")throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: missing sessionID on tool.execute.before; refusing to evaluate critical-directive ack state");_internals92.writeWarnEvent(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,reason:"missing_sessionID",mode:config3.mode}).catch(()=>{});return}let cached3=swarmState.currentCriticalShownIds.get(sessionID);if(!cached3||cached3.ids.length===0)return;let dayKey=new Date().toISOString().slice(0,10),ackedIds=new Set;for(let id of cached3.ids)for(let result of["applied","ignored","violated"]){let key=buildAckDedupKey(sessionID,id,result);if(swarmState.knowledgeAckDedup.has(key)){ackedIds.add(id);break}}let unacked=cached3.ids.filter((id)=>!ackedIds.has(id));if(unacked.length===0)return;if(config3.mode==="enforce"&&config3.critical_requires_ack){let ids=unacked.join(", ");throw Error(`KNOWLEDGE_ENFORCE_GATE_DENY: ${toolName} blocked — critical knowledge directive(s) ${ids} require KNOWLEDGE_APPLIED:<id> or KNOWLEDGE_IGNORED:<id> reason=... before this action.`)}writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,sessionID,dayKey,unacknowledged_critical_ids:unacked}).catch(()=>{})}async function writeWarnEvent2(directory,record3){let filePath=path156.join(directory,".swarm","events.jsonl");await mkdir31(path156.dirname(filePath),{recursive:!0}),await appendFile17(filePath,`${JSON.stringify(record3)}
5608
+ ${errorSummary}`)}}}}init_schema();init_state2();init_logger();import{appendFile as appendFile17,mkdir as mkdir31}from"node:fs/promises";import*as path156 from"node:path";var HIGH_RISK_TOOLS=new Set(["save_plan","update_task_status","phase_complete","task","Task","skill_regenerate","skill_retire"]);async function knowledgeApplicationGateBefore(directory,input,config3){if(!config3.enabled)return;let toolName=typeof input.tool==="string"?input.tool:"";if(!(config3.high_risk_tools?new Set(config3.high_risk_tools):HIGH_RISK_TOOLS).has(toolName))return;let agentRaw=typeof input.agent==="string"?input.agent:"";if(!agentRaw)return;if(stripKnownSwarmPrefix(agentRaw)!=="architect")return;let sessionID=typeof input.sessionID==="string"?input.sessionID:void 0;if(!sessionID){if(config3.mode==="enforce")throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: missing sessionID on tool.execute.before; refusing to evaluate critical-directive ack state");_internals92.writeWarnEvent(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,reason:"missing_sessionID",mode:config3.mode}).catch(()=>{});return}let cached3=swarmState.currentCriticalShownIds.get(sessionID);if(!cached3||cached3.ids.length===0)return;let ackedIds=new Set;for(let id of cached3.ids)for(let result of["applied","ignored","violated"]){let key=buildAckDedupKey(sessionID,id,result);if(swarmState.knowledgeAckDedup.has(key)){ackedIds.add(id);break}}let unacked=cached3.ids.filter((id)=>!ackedIds.has(id));if(unacked.length===0)return;if(config3.mode==="enforce"&&config3.critical_requires_ack){let ids=unacked.join(", ");throw Error(`KNOWLEDGE_ENFORCE_GATE_DENY: ${toolName} blocked — critical knowledge directive(s) ${ids} require KNOWLEDGE_APPLIED:<id>, KNOWLEDGE_IGNORED:<id> reason=..., or KNOWLEDGE_VIOLATED:<id> reason=... before this action.`)}writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,sessionID,unacknowledged_critical_ids:unacked}).catch(()=>{})}async function writeWarnEvent2(directory,record3){let filePath=path156.join(directory,".swarm","events.jsonl");await mkdir31(path156.dirname(filePath),{recursive:!0}),await appendFile17(filePath,`${JSON.stringify(record3)}
5574
5609
  `,"utf-8")}async function knowledgeApplicationTransformScan(directory,output,sessionID){if(!output?.messages)return;if(!sessionID)return;let target;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i],agent=m.info?.agent;if(typeof agent==="string"&&stripKnownSwarmPrefix(agent)==="architect"){target=m;break}}if(!target)return;let text=(target.parts??[]).map((p)=>typeof p.text==="string"?p.text:"").join(`
5575
5610
  `);if(!text)return;let acks=parseAcknowledgments(text);if(acks.length===0)return;let ctx={sessionId:sessionID};for(let ack of acks){let key=buildAckDedupKey(sessionID,ack.id,ack.result);if(swarmState.knowledgeAckDedup.has(key))continue;addKnowledgeAckDedup(key);try{await recordAcknowledgment(directory,ack,ctx)}catch(err){warn(`[knowledge-application-gate] transform-scan record failed: ${err instanceof Error?err.message:String(err)}`)}}}var _internals92={knowledgeApplicationGateBefore,knowledgeApplicationTransformScan,HIGH_RISK_TOOLS,writeWarnEvent:writeWarnEvent2};init_knowledge_curator();init_micro_reflector();init_normalize_tool_name();init_schema();init_bun_compat();init_logger();import{existsSync as existsSync87}from"node:fs";import*as path157 from"node:path";var PREDICATE_TIMEOUT_MS=15000,TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"]);function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path157.resolve(directory),resolved=path157.resolve(baseDir,concrete),rel=path157.relative(baseDir,resolved);if(rel.startsWith("..")||path157.isAbsolute(rel))return null}return v}function findBinaryInPath(binary){let exeName=process.platform==="win32"?`${binary}.exe`:binary;for(let dir of(process.env.PATH??"").split(path157.delimiter)){if(!dir)continue;let candidate=path157.join(dir,exeName);if(existsSync87(candidate))return candidate}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve56)=>setTimeout(()=>resolve56("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let rg=findBinaryInPath("rg");if(!rg)return{result:"error",detail:"grep: ripgrep (rg) not found"};let res=await runArgv([rg,"--count-matches","--no-messages","--glob",glob,"--",regex,"."],directory);if(res.timedOut)return{result:"error",detail:"grep: timed out"};if(res.exitCode===1)return{result:"pass",detail:"grep: zero matches"};if(res.exitCode===0)return{result:"fail",detail:`grep: ${res.stdout.split(`
5576
5611
  `).map((l)=>Number.parseInt(l.split(":").pop()??"0",10)).filter((n)=>!Number.isNaN(n)).reduce((a,b)=>a+b,0)} match(es) found`};return{result:"error",detail:`grep: ripgrep error (exit ${res.exitCode}) ${res.stderr.slice(0,200)}`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git=findBinaryInPath("git");if(!git)return null;let res=await runArgv([git,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path157.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe=validateRepoRelativeGlob(directory,rest);if(safe===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed=await changedPaths(directory);if(changed===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path157.normalize(safe),isChanged=changed.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}init_knowledge_escalator();init_knowledge_events();init_skill_propagation_gate();var VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([A-Za-z0-9._-]{1,80})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi;function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),id=m[2],evidence=m[3]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({id,verdict,evidence})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[]};try{let verifyById=new Map(params.directivesToVerify.map((d)=>[d.id,d]));if(verifyById.size===0)return result;let verdicts=parseReviewerDirectiveCompliance(params.transcript),addressed=new Set,violatedIds=new Set,traceId=newTraceId(),sessionId=params.sessionId??"unknown",agent=params.agent??"reviewer";for(let v of verdicts){let directive=verifyById.get(v.id);if(!directive)continue;addressed.add(v.id);let type=verdictToEventType(v.verdict),predicateCheck;if(v.verdict==="violated"&&directive.verification_predicate){let outcome=await runDirectivePredicate(directive.verification_predicate,params.directory);predicateCheck={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}if(await recordKnowledgeEvent(params.directory,{type,trace_id:traceId,knowledge_id:v.id,session_id:sessionId,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:v.evidence,predicate_check:predicateCheck}),type==="violated")violatedIds.add(v.id);result.emitted.push({id:v.id,type,source:"reviewer"})}for(let d of params.directivesToVerify){if(d.priority!=="critical")continue;if(addressed.has(d.id))continue;result.omittedCriticals.push(d.id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:d.id,session_id:sessionId,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:"reviewer_omitted"}),violatedIds.add(d.id),result.emitted.push({id:d.id,type:"violated",source:"reviewer"})}if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}function isTaskTool6(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool6(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}init_constants();init_schema();init_scope_persistence();init_state2();init_delegation_gate();init_normalize_tool_name();import*as path158 from"node:path";var WRITE_TOOLS2=new Set(WRITE_TOOL_NAMES);function createScopeGuardHook(config3,directory,injectAdvisory){let enabled=config3.enabled??!0,_skipInTurbo=config3.skip_in_turbo??!1;return{toolBefore:async(input,output)=>{if(!enabled)return;let toolName=normalizeToolName(input.tool);if(!WRITE_TOOLS2.has(toolName))return;let sessionId=input.sessionID,activeAgent=swarmState.activeAgent.get(sessionId),session=swarmState.agentSessions.get(sessionId),agentName=activeAgent??session?.agentName??"unknown";if(stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME)return;let taskId=session?.currentTaskId??null,declaredScope=resolveScopeWithFallbacks({directory,taskId,inMemoryScope:session?.declaredCoderScope,pendingMapScope:taskId?pendingCoderScopeByTaskId.get(taskId):null});if(!declaredScope||declaredScope.length===0)return;let argsObj=output.args,candidatePaths=[],singlePathKeys=["path","filePath","file"];for(let key of singlePathKeys){let val=argsObj?.[key];if(typeof val==="string"&&val)candidatePaths.push(val)}let hasArrayKeys=!1,arrayPathKeys=["files","paths","targetFiles"];for(let key of arrayPathKeys){let val=argsObj?.[key];if(Array.isArray(val)){hasArrayKeys=!0;for(let item of val)if(typeof item==="string"&&item)candidatePaths.push(item)}}if(candidatePaths.length===0&&!hasArrayKeys)return;for(let rawPath of candidatePaths){let filePath=sanitizePath(rawPath);if(!isFileInScope(filePath,declaredScope,directory))reportScopeViolation(agentName,filePath,taskId,session,injectAdvisory,swarmState,declaredScope)}}}}function isFileInScope(filePath,scopeEntries,directory){let dir=directory??process.cwd(),resolvedFile=path158.resolve(dir,filePath);return scopeEntries.filter((scope)=>scope.length>0).some((scope)=>{let resolvedScope=path158.resolve(dir,scope);if(resolvedFile===resolvedScope)return!0;let rel=path158.relative(resolvedScope,resolvedFile);return rel.length>0&&!rel.startsWith("..")&&!path158.isAbsolute(rel)})}function sanitizePath(raw){let result="";for(let i=0;i<raw.length;i++){let c=raw.charCodeAt(i);if(c<=31||c===127||c>=128&&c<=159){result+="_";continue}result+=raw[i]}return result.replace(/\[[\d;]*m/g,"")}function reportScopeViolation(agentName,filePath,taskId,session,injectAdvisory,state,scopeEntries){let violationMessage=`SCOPE VIOLATION: ${agentName} attempted to modify '${filePath}' which is not in declared scope for task ${taskId??"unknown"}. Declared scope: [${scopeEntries.slice(0,3).join(", ")}${scopeEntries.length>3?"...":""}]`;if(session)session.lastScopeViolation=violationMessage,session.scopeViolationDetected=!0;if(injectAdvisory)for(let[archSessionId,archSession]of state.agentSessions){let archAgent=state.activeAgent.get(archSessionId)??archSession.agentName;if(stripKnownSwarmPrefix(archAgent)===ORCHESTRATOR_NAME){try{injectAdvisory(archSessionId,`[SCOPE GUARD] ${violationMessage}`)}catch{}break}}throw Error(violationMessage)}init_constants();init_schema();init_state2();init_normalize_tool_name();function createSelfReviewHook(config3,injectAdvisory){let enabled=config3.enabled??!0,skipInTurbo=config3.skip_in_turbo??!0;return{toolAfter:async(input,output)=>{if(!enabled)return;if(normalizeToolName(input.tool)!=="update_task_status")return;let args2=output.args;if(args2?.status!=="in_progress")return;let taskId=typeof args2?.task_id==="string"?args2.task_id:"unknown",sessionId=input.sessionID,agentName=swarmState.activeAgent.get(sessionId)??swarmState.agentSessions.get(sessionId)?.agentName??"";if(stripKnownSwarmPrefix(agentName)!==ORCHESTRATOR_NAME)return;if(skipInTurbo){let session=swarmState.agentSessions.get(sessionId);if(session&&session.turboMode===!0)return}let advisory=[`[SELF-REVIEW] Task ${taskId} is now delegated to coder.`,"After coder completes, review for:"," • Broken conditionals (inverted if/else, wrong comparisons)"," • Off-by-one errors (array bounds, loop indices)"," • Assumptions contradicting existing codebase patterns"," • Missing error handling (uncaught exceptions, unhandled promises)"," • Scope creep (changes outside the declared task spec)","Delegate to critic with self-review focus before marking complete."].join(`
@@ -5603,18 +5638,18 @@ Review before proceeding.`;injectSystemMessage(input.sessionID,message)}}}init_b
5603
5638
  `?resultContent.replace(/\n/g,`\r
5604
5639
  `):resultContent;finalContent=ensureFinalNewline(withLineEnding,originalEndsWithNewline)}if(finalContent===content)return{file:targetPath,status:"no-changes",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0};if(!dryRun)atomicWriteFileSync2(fullPath,finalContent);return{file:targetPath,status:"applied",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0}}function buildErrorResult(message){return{success:!1,files:[{file:"",status:"error",hunks:0,hunksApplied:0,hunksFailed:0,errors:[{hunkIndex:0,type:"context-mismatch",message}]}],summary:{totalFiles:0,applied:0,failed:1,totalHunks:0}}}function isUnsupportedPatchFormat(patchText){let trimmed=patchText.trimStart();return trimmed.startsWith("*** Begin Patch")||trimmed.startsWith("*** Update File")||trimmed.startsWith("*** Add File")||trimmed.startsWith("*** Delete File")||trimmed.startsWith("*** End Patch")}var swarmApplyPatch=createSwarmTool({description:"Apply a unified diff patch to workspace files. Validates paths, matches context exactly, and writes atomically. Coder-scoped write tool. Use standard unified diff format (--- a/file / +++ b/file / @@ hunks). Does NOT support *** Begin Patch / *** Update File payloads — use the native apply_patch tool for those.",args:{patch:exports_external.string().min(1).describe("Unified diff text to parse and apply"),files:exports_external.array(exports_external.string()).min(1).describe("Array of target file paths the patch is expected to touch. Every parsed target must appear in this list."),dryRun:exports_external.boolean().optional().default(!1).describe("Validate without writing files (default: false)"),allowCreates:exports_external.boolean().optional().default(!1).describe("Allow creating new files from patches with --- /dev/null (default: false)"),allowDeletes:exports_external.boolean().optional().default(!1).describe("Allow deleting files from patches with +++ /dev/null (default: false)")},execute:async(args2,directory)=>{if(!args2||typeof args2!=="object")return JSON.stringify(buildErrorResult("Could not parse swarm_apply_patch arguments"),null,2);let obj=args2,patchText=obj.patch??"",files=obj.files??[],dryRun=obj.dryRun??!1,allowCreates=obj.allowCreates??!1,allowDeletes=obj.allowDeletes??!1;if(!existsSync90(directory))return JSON.stringify(buildErrorResult("Workspace directory does not exist"),null,2);if(files.length===0)return JSON.stringify(buildErrorResult("files array cannot be empty"),null,2);if(!patchText||patchText.trim()==="")return JSON.stringify(buildErrorResult("patch text cannot be empty"),null,2);if(isUnsupportedPatchFormat(patchText))return JSON.stringify(buildErrorResult("Unsupported patch format: *** Begin Patch / *** Update File style payloads are not supported by swarm_apply_patch. Use the native apply_patch tool for this format, or provide a standard unified diff (--- a/file / +++ b/file / @@ hunks)."),null,2);for(let filePath of files){let validationError=validatePatchTargetPath(filePath,directory);if(validationError)return JSON.stringify(buildErrorResult(validationError),null,2)}let{files:parsedFiles,error:parseError}=parseUnifiedDiff(patchText);if(parseError)return JSON.stringify(buildErrorResult(parseError),null,2);if(parsedFiles.length===0)return JSON.stringify({success:!0,dryRun,files:[],summary:{totalFiles:0,applied:0,failed:0,totalHunks:0}},null,2);let declaredFileSet=new Set(files),undeclaredTargets=[];for(let fileDiff of parsedFiles){let targetPath=fileDiff.isDelete?fileDiff.oldPath:fileDiff.newPath;if(targetPath&&targetPath!=="/dev/null"&&!declaredFileSet.has(targetPath))undeclaredTargets.push(targetPath)}if(undeclaredTargets.length>0)return JSON.stringify(buildErrorResult(`Patch targets files not in the declared files array: ${undeclaredTargets.join(", ")}`),null,2);let parsedTargetSet=new Set(parsedFiles.map((fd)=>fd.isDelete?fd.oldPath:fd.newPath).filter(Boolean)),extraFiles=files.filter((f)=>!parsedTargetSet.has(f)),fileResults=[],totalApplied=0,totalFailed=0,totalHunks=0;for(let fileDiff of parsedFiles){let targetPath=fileDiff.isDelete?fileDiff.oldPath:fileDiff.newPath,fullPath=path162.resolve(directory,targetPath);totalHunks+=fileDiff.hunks.length;let result=processFileDiff(fileDiff,targetPath,fullPath,directory,dryRun,allowCreates,allowDeletes);if(fileResults.push(result),result.status==="applied"||result.status==="created")totalApplied++;else if(result.status==="error")totalFailed++}let output={success:totalFailed===0,dryRun,files:fileResults,summary:{totalFiles:fileResults.length,applied:totalApplied,failed:totalFailed,totalHunks}};if(extraFiles.length>0)return JSON.stringify({...output,warnings:[`files[] contains entries not targeted by the patch: ${extraFiles.join(", ")}`]},null,2);return JSON.stringify(output,null,2)}});init_zod();import*as fs97 from"node:fs";import*as path163 from"node:path";init_path_security();init_create_tool();var AST_GREP_TIMEOUT_MS=1e4,AST_GREP_MAX_STDOUT_BYTES=8388608,AST_GREP_MAX_STDERR_BYTES=65536,DEFAULT_MAX_RESULTS2=100,HARD_CAP_RESULTS2=1e4,MAX_PATTERN_LENGTH=20000;function splitGlobPatterns(value){return value?value.split(",").map((p)=>p.trim()).filter(Boolean):[]}function resolveAstGrepBinary(){return _internals95.resolveExecutableFromPath(["ast-grep","sg"])}function toWorkspaceRelativePath(filePath,workspace){try{let resolved=path163.resolve(workspace,filePath),realWorkspace=fs97.realpathSync(workspace),realResolved=fs97.realpathSync(resolved),relative31=path163.relative(realWorkspace,realResolved);if(!relative31||relative31.startsWith("..")||path163.isAbsolute(relative31))return null;return relative31.split(path163.sep).join("/")}catch{return null}}function parseAstGrepStream(stdout,workspace,maxResults){let matches=[],total=0;for(let line of stdout.split(`
5605
5640
  `)){if(!line.trim())continue;try{let entry=JSON.parse(line),relativePath=typeof entry.file==="string"?toWorkspaceRelativePath(entry.file,workspace):null;if(!relativePath)continue;if(total++,matches.length>=maxResults)continue;let start=entry.range?.start??{},end=entry.range?.end??{};matches.push({file:relativePath,lineNumber:typeof start.line==="number"?start.line+1:1,column:typeof start.column==="number"?start.column+1:1,endLineNumber:typeof end.line==="number"?end.line+1:1,endColumn:typeof end.column==="number"?end.column+1:1,text:typeof entry.text==="string"?entry.text:"",lines:typeof entry.lines==="string"?entry.lines.trimEnd():"",language:typeof entry.language==="string"?entry.language:void 0,metaVariables:entry.metaVariables&&typeof entry.metaVariables==="object"?entry.metaVariables:void 0})}catch{}}return{matches,total}}function validateGlobArg(kind,value){if(!value)return null;if(containsControlChars(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains invalid control characters`};if(containsPathTraversal(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains path traversal sequence`};return null}var ast_grep=createSwarmTool({description:"Read-only structural AST search using ast-grep. Searches code patterns with optional language and glob filters; does not rewrite files.",args:{pattern:exports_external.string().describe("ast-grep pattern to search for"),language:exports_external.string().optional().describe("Optional ast-grep language, e.g. ts, tsx, js, py, rust"),include:exports_external.string().optional().describe("Comma-separated include globs, passed to ast-grep --globs"),exclude:exports_external.string().optional().describe("Comma-separated exclude globs, passed to ast-grep as !glob"),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS2).describe("Maximum number of matches to return")},execute:async(args2,directory)=>{let pattern,language,include,exclude,maxResults=DEFAULT_MAX_RESULTS2;try{let obj=args2;pattern=typeof obj.pattern==="string"?obj.pattern:"",language=typeof obj.language==="string"?obj.language:void 0,include=typeof obj.include==="string"?obj.include:void 0,exclude=typeof obj.exclude==="string"?obj.exclude:void 0;let rawMaxResults=typeof obj.max_results==="number"?obj.max_results:DEFAULT_MAX_RESULTS2,sanitizedMaxResults=Number.isFinite(rawMaxResults)?rawMaxResults:DEFAULT_MAX_RESULTS2;maxResults=Math.min(Math.max(0,sanitizedMaxResults),HARD_CAP_RESULTS2)}catch{return JSON.stringify({error:!0,type:"invalid-pattern",message:"Could not parse ast_grep arguments"},null,2)}if(!pattern||pattern.trim()==="")return JSON.stringify({error:!0,type:"invalid-pattern",message:"Pattern cannot be empty"},null,2);if(pattern.length>MAX_PATTERN_LENGTH||containsControlChars(pattern))return JSON.stringify({error:!0,type:"invalid-pattern",message:`Pattern is invalid or exceeds ${MAX_PATTERN_LENGTH} characters`},null,2);if(language&&!/^[A-Za-z0-9_-]+$/.test(language))return JSON.stringify({error:!0,type:"invalid-pattern",message:"Language must contain only letters, numbers, _ or -"},null,2);let includeError=validateGlobArg("Include",include);if(includeError)return JSON.stringify(includeError,null,2);let excludeError=validateGlobArg("Exclude",exclude);if(excludeError)return JSON.stringify(excludeError,null,2);if(!fs97.existsSync(directory))return JSON.stringify({error:!0,type:"unknown",message:"Workspace directory does not exist"},null,2);let executable=_internals95.resolveAstGrepBinary();if(!executable)return JSON.stringify({error:!0,type:"ast-grep-not-found",message:"ast-grep executable not found. Install ast-grep and ensure ast-grep or sg is on PATH."},null,2);let sgArgs=["run","--pattern",pattern,"--json=stream","--color","never"];if(language)sgArgs.push("--lang",language);for(let glob of splitGlobPatterns(include))sgArgs.push("--globs",glob);for(let glob of splitGlobPatterns(exclude))sgArgs.push("--globs",`!${glob}`);sgArgs.push(".");let run=await _internals95.runExternalTool({executable,args:sgArgs,cwd:directory,timeoutMs:AST_GREP_TIMEOUT_MS,maxStdoutBytes:AST_GREP_MAX_STDOUT_BYTES,maxStderrBytes:AST_GREP_MAX_STDERR_BYTES});if(run.status==="timeout")return JSON.stringify({error:!0,type:"timeout",message:`ast-grep timed out after ${AST_GREP_TIMEOUT_MS}ms`},null,2);if(run.status==="spawn-error")return JSON.stringify({error:!0,type:"unknown",message:run.message??"ast-grep failed to start"},null,2);if(run.exitCode!==0&&run.stderr)return JSON.stringify({error:!0,type:"invalid-pattern",message:run.stderr.split(`
5606
- `)[0]},null,2);let{matches,total}=parseAstGrepStream(run.stdout,directory,maxResults);return JSON.stringify({matches,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,total,pattern,language,maxResults,outputTruncated:run.stdoutTruncated||run.stderrTruncated},null,2)}}),_internals95={resolveExecutableFromPath,resolveAstGrepBinary,runExternalTool,parseAstGrepStream};init_dist();init_create_tool();import*as fs98 from"node:fs";import*as path164 from"node:path";init_path_security();var WINDOWS_RESERVED_NAMES4=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks3(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES4.test(part))return!0;return!1}function isPathInWorkspace2(filePath,workspace){try{let resolvedPath=path164.resolve(workspace,filePath);if(!fs98.existsSync(resolvedPath))return!0;let realWorkspace=fs98.realpathSync(workspace),realResolvedPath=fs98.realpathSync(resolvedPath),relativePath=path164.relative(realWorkspace,realResolvedPath);if(relativePath.startsWith("..")||path164.isAbsolute(relativePath))return!1;return!0}catch{return!1}}function processFile(file3,cwd,exportedOnly){let ext=path164.extname(file3);if(containsControlChars(file3))return{file:file3,success:!1,error:"Path contains invalid control characters",errorType:"invalid-path"};if(containsPathTraversal(file3))return{file:file3,success:!1,error:"Path contains path traversal sequence",errorType:"path-traversal"};if(containsWindowsAttacks3(file3))return{file:file3,success:!1,error:"Path contains invalid Windows-specific sequence",errorType:"invalid-path"};if(!isPathInWorkspace2(file3,cwd))return{file:file3,success:!1,error:"Path is outside workspace",errorType:"path-outside-workspace"};let fullPath=path164.join(cwd,file3);if(!fs98.existsSync(fullPath))return{file:file3,success:!1,error:`File not found: ${file3}`,errorType:"file-not-found"};let syms;switch(ext){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(file3,cwd);break;case".py":syms=extractPythonSymbols(file3,cwd);break;default:return{file:file3,success:!1,error:`Unsupported file extension: ${ext}. Supported: .ts, .tsx, .js, .jsx, .mjs, .cjs, .py`,errorType:"unsupported-language"}}let isEmptyFile=!1;try{if(fs98.statSync(fullPath).size===0)isEmptyFile=!0}catch{}if(syms.length===0)try{if(fs98.readFileSync(fullPath,"utf-8").trim().length===0)isEmptyFile=!0}catch{}if(isEmptyFile)return{file:file3,success:!0,symbols:[],error:"empty-file",errorType:"empty-file"};if(exportedOnly)syms=syms.filter((s)=>s.exported);return{file:file3,success:!0,symbols:syms}}var batch_symbols=createSwarmTool({description:"Extract symbols from multiple files in a single batch call. Accepts an array of file paths and returns per-file symbol summaries. One bad file does not crash the batch. Use for surveying a module when you need symbol information from multiple files at once.",args:{files:tool.schema.array(tool.schema.string()).describe("Array of file paths to extract symbols from"),exported_only:tool.schema.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols.")},execute:async(args2,directory)=>{let files,exportedOnly=!0;try{let obj=args2;if(!Array.isArray(obj.files))return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: files must be an array"},null,2);files=obj.files.map((f)=>String(f)),exportedOnly=obj.exported_only===!0}catch{return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: could not extract files array"},null,2)}let cwd=directory,results=[];for(let file3 of files){let result=processFile(file3,cwd,exportedOnly);results.push(result)}let successCount=results.filter((r)=>r.success).length,failureCount=results.filter((r)=>!r.success).length,batchResult={results,totalFiles:files.length,successCount,failureCount};return JSON.stringify(batchResult,null,2)}});init_zod();init_discovery();init_manager2();init_bun_compat();init_create_tool();var DEFAULT_TIMEOUT_MS2=300000,MAX_OUTPUT_BYTES5=10240,MAX_OUTPUT_LINES=100;function truncateOutput(output,maxLines=MAX_OUTPUT_LINES,maxBytes=MAX_OUTPUT_BYTES5){if(!output)return"";let truncated=output;if(truncated.length>maxBytes)truncated=truncated.slice(-maxBytes);let lines=truncated.split(`
5641
+ `)[0]},null,2);let{matches,total}=parseAstGrepStream(run.stdout,directory,maxResults);return JSON.stringify({matches,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,total,pattern,language,maxResults,outputTruncated:run.stdoutTruncated||run.stderrTruncated},null,2)}}),_internals95={resolveExecutableFromPath,resolveAstGrepBinary,runExternalTool,parseAstGrepStream};init_dist();init_create_tool();import*as fs98 from"node:fs";import*as path164 from"node:path";init_path_security();var WINDOWS_RESERVED_NAMES4=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks3(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES4.test(part))return!0;return!1}function isPathInWorkspace2(filePath,workspace){try{let resolvedPath=path164.resolve(workspace,filePath);if(!fs98.existsSync(resolvedPath))return!0;let realWorkspace=fs98.realpathSync(workspace),realResolvedPath=fs98.realpathSync(resolvedPath),relativePath=path164.relative(realWorkspace,realResolvedPath);if(relativePath.startsWith("..")||path164.isAbsolute(relativePath))return!1;return!0}catch{return!1}}function processFile(file3,cwd,exportedOnly){let ext=path164.extname(file3);if(containsControlChars(file3))return{file:file3,success:!1,error:"Path contains invalid control characters",errorType:"invalid-path"};if(containsPathTraversal(file3))return{file:file3,success:!1,error:"Path contains path traversal sequence",errorType:"path-traversal"};if(containsWindowsAttacks3(file3))return{file:file3,success:!1,error:"Path contains invalid Windows-specific sequence",errorType:"invalid-path"};if(!isPathInWorkspace2(file3,cwd))return{file:file3,success:!1,error:"Path is outside workspace",errorType:"path-outside-workspace"};let fullPath=path164.join(cwd,file3);if(!fs98.existsSync(fullPath))return{file:file3,success:!1,error:`File not found: ${file3}`,errorType:"file-not-found"};let syms;switch(ext){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(file3,cwd);break;case".py":case".pyw":syms=extractPythonSymbols(file3,cwd);break;case".rs":syms=extractRustSymbols(file3,cwd);break;case".go":syms=extractGoSymbols(file3,cwd);break;default:return{file:file3,success:!1,error:`Unsupported file extension: ${ext}. Supported: .ts, .tsx, .js, .jsx, .mjs, .cjs, .py, .pyw, .rs, .go`,errorType:"unsupported-language"}}let isEmptyFile=!1;try{if(fs98.statSync(fullPath).size===0)isEmptyFile=!0}catch{}if(syms.length===0)try{if(fs98.readFileSync(fullPath,"utf-8").trim().length===0)isEmptyFile=!0}catch{}if(isEmptyFile)return{file:file3,success:!0,symbols:[],error:"empty-file",errorType:"empty-file"};if(exportedOnly)syms=syms.filter((s)=>s.exported);return{file:file3,success:!0,symbols:syms}}var batch_symbols=createSwarmTool({description:"Extract symbols from multiple files in a single batch call. Accepts an array of file paths and returns per-file symbol summaries. One bad file does not crash the batch. Use for surveying a module when you need symbol information from multiple files at once.",args:{files:tool.schema.array(tool.schema.string()).describe("Array of file paths to extract symbols from"),exported_only:tool.schema.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols.")},execute:async(args2,directory)=>{let files,exportedOnly=!0;try{let obj=args2;if(!Array.isArray(obj.files))return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: files must be an array"},null,2);files=obj.files.map((f)=>String(f)),exportedOnly=obj.exported_only!==!1}catch{return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: could not extract files array"},null,2)}let cwd=directory,results=[];for(let file3 of files){let result=processFile(file3,cwd,exportedOnly);results.push(result)}let successCount=results.filter((r)=>r.success).length,failureCount=results.filter((r)=>!r.success).length,batchResult={results,totalFiles:files.length,successCount,failureCount};return JSON.stringify(batchResult,null,2)}});init_zod();init_discovery();init_manager2();init_bun_compat();init_create_tool();var DEFAULT_TIMEOUT_MS2=300000,MAX_OUTPUT_BYTES5=10240,MAX_OUTPUT_LINES=100;function truncateOutput(output,maxLines=MAX_OUTPUT_LINES,maxBytes=MAX_OUTPUT_BYTES5){if(!output)return"";let truncated=output;if(truncated.length>maxBytes)truncated=truncated.slice(-maxBytes);let lines=truncated.split(`
5607
5642
  `);if(lines.length>maxLines)return lines.slice(-maxLines).join(`
5608
5643
  `);return truncated}function getCommandKind(command){let lower=command.toLowerCase();if(lower.includes("typecheck")||lower.includes("check")||lower.includes("analyze")||lower.includes("lint"))return"typecheck";if(lower.includes("test")||lower.includes("spec")||lower.includes("jest")||lower.includes("vitest")||lower.includes("mocha")||lower.includes("pytest"))return"test";return"build"}function filterByMode(commands,mode){if(mode==="both")return commands;return commands.filter((cmd)=>getCommandKind(cmd.command)===mode)}async function executeCommand(command){let startTime=Date.now(),kind=getCommandKind(command.command),isWindows=process.platform==="win32",cmd,args2;if(isWindows&&!command.command.includes(" "))cmd=[command.command],args2=[];else if(isWindows)cmd=["cmd","/c",command.command],args2=[];else cmd=["/bin/sh"],args2=["-c",command.command];let result=bunSpawn([...cmd,...args2],{cwd:command.cwd,stdout:"pipe",stderr:"pipe",timeout:DEFAULT_TIMEOUT_MS2}),[exitCode,stdout,stderr]=await Promise.all([result.exited,result.stdout.text(),result.stderr.text()]),duration_ms=Date.now()-startTime;return{kind,command:command.command,cwd:command.cwd,exit_code:exitCode??-1,duration_ms,stdout_tail:truncateOutput(stdout),stderr_tail:truncateOutput(stderr)}}async function runBuildCheck(workingDir,input){let scope=input.scope??"all",mode=input.mode??"both",changedFiles=input.changed_files??[],discoveryResult=await discoverBuildCommands(workingDir,{scope,changedFiles}),commands=filterByMode(discoveryResult.commands,mode),runs=[],failedCount=0;for(let cmd of commands)try{let run=await executeCommand(cmd);if(runs.push(run),run.exit_code!==0)failedCount++}catch(error93){runs.push({kind:getCommandKind(cmd.command),command:cmd.command,cwd:cmd.cwd,exit_code:-1,duration_ms:0,stdout_tail:"",stderr_tail:error93 instanceof Error?error93.message:"Unknown error"}),failedCount++}let verdict,skipped_reason;if(runs.length===0)if(verdict="info",discoveryResult.skipped.length>0)skipped_reason=discoveryResult.skipped.map((s)=>`${s.ecosystem}: ${s.reason}`).join("; ");else skipped_reason="No build commands discovered (no toolchains found)";else if(failedCount>0)verdict="fail";else verdict="pass";return{verdict,runs,summary:{files_scanned:changedFiles.length,runs_count:runs.length,failed_count:failedCount,skipped_reason}}}var build_check=createSwarmTool({description:"Discover and run build commands for various ecosystems in a project directory. Supports build, typecheck, and test commands.",args:{scope:exports_external.enum(["changed","all"]).describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changed_files:exports_external.array(exports_external.string()).optional().describe('List of changed files when scope is "changed"'),mode:exports_external.enum(["build","typecheck","both"]).optional().describe('Mode: "build" for build commands, "typecheck" for type checking, "both" for all (default: both)')},async execute(args2,directory){let obj=args2,scope=obj.scope??"all",changedFiles=obj.changed_files??[],mode=obj.mode??"both",workingDir=directory,result=await runBuildCheck(workingDir,{scope,changed_files:changedFiles,mode}),evidence={task_id:"build",type:"build",timestamp:new Date().toISOString(),agent:"build_check",verdict:result.verdict,summary:`${result.runs.length} build command(s) executed, ${result.summary.failed_count} failed`,runs:result.runs,files_scanned:result.summary.files_scanned,runs_count:result.summary.runs_count,failed_count:result.summary.failed_count,skipped_reason:result.summary.skipped_reason};try{await saveEvidence(workingDir,"build",evidence)}catch(error93){console.error("Failed to save build evidence:",error93 instanceof Error?error93.message:String(error93))}return JSON.stringify(result,null,2)}});init_zod();init_manager2();init_task_id();init_create_tool();init_resolve_working_directory();import*as fs99 from"node:fs";import*as path165 from"node:path";var EVIDENCE_DIR=".swarm/evidence";function isValidTaskId4(taskId){return isStrictTaskId(taskId)}function isPathWithinSwarm(filePath,workspaceRoot){let normalizedWorkspace=path165.resolve(workspaceRoot),swarmPath=path165.join(normalizedWorkspace,".swarm","evidence");return path165.resolve(filePath).startsWith(swarmPath)}function readEvidenceFile(evidencePath){if(!fs99.existsSync(evidencePath))return null;let content;try{content=fs99.readFileSync(evidencePath,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(content)}catch{return null}if(parsed&&typeof parsed==="object"&&Array.isArray(parsed.required_gates)&&typeof parsed.gates==="object"&&parsed.gates!==null)return parsed;return null}var check_gate_status=createSwarmTool({description:"Read-only tool to check the gate status of a specific task. Reads .swarm/evidence/{taskId}.json and returns structured JSON describing required, passed, and missing gates.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "1.2.3", "1.2.3.4")').describe('The task ID to check gate status for (e.g., "1.1", "2.3.1")'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/evidence/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let taskIdInput,workingDirInput;try{if(args2&&typeof args2==="object"){let obj=args2;taskIdInput=typeof obj.task_id==="string"?obj.task_id:void 0,workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}}catch{}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={taskId:taskIdInput??"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:dirResult.message,todo_scan:null};return JSON.stringify(errorResult,null,2)}if(directory=dirResult.directory,!taskIdInput)return JSON.stringify({taskId:"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid task_id: task_id is required",todo_scan:null},null,2);if(!isValidTaskId4(taskIdInput)){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`Invalid task_id format: "${taskIdInput}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3", "1.2.3.4")`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let evidencePath=path165.join(directory,EVIDENCE_DIR,`${taskIdInput}.json`);if(!isPathWithinSwarm(evidencePath,directory))return JSON.stringify({taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid path: evidence path validation failed",todo_scan:null},null,2);let evidenceData=readEvidenceFile(evidencePath);if(!evidenceData){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`No evidence file found for task "${taskIdInput}" at ${evidencePath}. Evidence file may be missing or invalid.`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let requiredGates=evidenceData.required_gates||[],gatesMap=evidenceData.gates||{},passedGates=[],missingGates=[];for(let requiredGate of requiredGates)if(gatesMap[requiredGate])passedGates.push(requiredGate);else missingGates.push(requiredGate);let status=missingGates.length===0?"all_passed":"incomplete",message;if(status==="all_passed")message=`All required gates have passed for task "${taskIdInput}".`;else message=`Task "${taskIdInput}" is incomplete. Missing gates: ${missingGates.join(", ")}.`;let secretscanVerdict="not_run";try{let evidenceResult=await loadEvidence(directory,taskIdInput);if(evidenceResult.status==="found"){let secretscanEntries=evidenceResult.bundle.entries.filter((entry)=>entry.type==="secretscan");if(secretscanEntries.length>0){let lastSecretscan=secretscanEntries[secretscanEntries.length-1];if(isSecretscanEvidence(lastSecretscan)){if(lastSecretscan.verdict==="fail"||lastSecretscan.verdict==="rejected"){if(secretscanVerdict="fail",missingGates.push("secretscan (BLOCKED — secrets detected)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan found secrets in prior scan. ${message}`}else if(lastSecretscan.verdict==="pass"||lastSecretscan.verdict==="approved"||lastSecretscan.verdict==="info")secretscanVerdict="pass"}}else message+=" Advisory: No secretscan evidence found for this task. Consider running secretscan."}}catch{}let todoScan=evidenceData.todo_scan;return JSON.stringify({taskId:taskIdInput,status,required_gates:requiredGates,passed_gates:passedGates,missing_gates:missingGates,gates:gatesMap,message,todo_scan:todoScan??null,secretscan_verdict:secretscanVerdict},null,2)}});init_checkpoint();init_co_change_analyzer();init_zod();init_utils2();init_state2();init_create_tool();init_resolve_working_directory();import*as fs100 from"node:fs";import*as path166 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=fs100.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 task of targetPhase.tasks){if(task.status!=="completed")continue;tasksChecked++;let fileTargets=parseFilePaths(task.description,task.files_touched),identifiers=parseIdentifiers(task.description);if(fileTargets.length===0){tasksSkipped++;continue}if(identifiers.length===0){blockedTasks.push({task_id:task.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=path166.resolve(directory,normalizedPath),projectRoot=path166.resolve(directory),relative33=path166.relative(projectRoot,resolvedPath);if(!(relative33===""||!relative33.startsWith("..")&&!path166.isAbsolute(relative33))){blockedTasks.push({task_id:task.id,identifier:"",file_path:filePath,reason:`File path '${filePath}' escapes the project directory — cannot verify completion`}),hasFileReadFailure=!0;continue}let fileContent;try{fileContent=fs100.readFileSync(resolvedPath,"utf-8")}catch{blockedTasks.push({task_id:task.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:task.id,identifier:"",file_path:"",reason:"No identifiers found in target files"});tasksBlocked++}}let now=new Date().toISOString(),result={success:tasksBlocked===0,phase,status:tasksBlocked===0?"passed":"blocked",reason:tasksBlocked>0?`COMPLETION_INCOMPLETE: ${tasksBlocked} task(s) blocked — missing identifiers or target files`:void 0,tasksChecked,tasksSkipped,tasksBlocked,blockedTasks};try{let evidenceDir=path166.join(directory,".swarm","evidence",`${phase}`),evidencePath=path166.join(evidenceDir,"completion-verify.json");fs100.mkdirSync(evidenceDir,{recursive:!0});let evidenceBundle={schema_version:"1.0.0",task_id:"completion-verify",created_at:now,entries:[{task_id:"completion-verify",type:"completion_verify",timestamp:now,agent:"completion_verify",verdict:tasksBlocked===0?"pass":"fail",summary:buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked),phase,tasks_checked:tasksChecked,tasks_skipped:tasksSkipped,tasks_blocked:tasksBlocked,blocked_tasks:blockedTasks}]};fs100.writeFileSync(evidencePath,JSON.stringify(evidenceBundle,null,2),"utf-8")}catch{}return JSON.stringify(result,null,2)}var completion_verify=createSwarmTool({description:"Deterministic pre-check verifying that plan task identifiers exist in their target source files before phase completion. Blocks if obviously incomplete.",args:{phase:exports_external.number().describe("The phase number to check"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},execute:async(args2,directory)=>{let parsedArgs;try{if(args2&&typeof args2==="object"){let obj=args2;parsedArgs={phase:typeof obj.phase==="number"?obj.phase:typeof obj.phase==="string"?Number(obj.phase):0,sessionID:typeof obj.sessionID==="string"?obj.sessionID:void 0,working_directory:typeof obj.working_directory==="string"?obj.working_directory:void 0}}else parsedArgs={phase:0}}catch{return JSON.stringify({success:!1,phase:0,status:"blocked",reason:"Invalid arguments",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let dirResult=resolveWorkingDirectory(parsedArgs.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:parsedArgs.phase,status:"blocked",reason:dirResult.message,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);return executeCompletionVerify(parsedArgs,dirResult.directory)}});init_zod();import*as fs102 from"node:fs";import*as path168 from"node:path";import*as fs101 from"node:fs";import*as path167 from"node:path";var MAX_FILE_SIZE_BYTES3=262144,MIN_DUPLICATION_LINES=10;function estimateCyclomaticComplexity(content){let processed=content.replace(/\/\*[\s\S]*?\*\//g,"");processed=processed.replace(/\/\/.*/g,""),processed=processed.replace(/#.*/g,""),processed=processed.replace(/'[^']*'/g,""),processed=processed.replace(/"[^"]*"/g,""),processed=processed.replace(/`[^`]*`/g,"");let complexity=1,decisionPatterns=[/\bif\b/g,/\belse\s+if\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\./g,/\?\?/g,/&&/g,/\|\|/g];for(let pattern of decisionPatterns){let matches=processed.match(pattern);if(matches)complexity+=matches.length}let ternaryMatches=processed.match(/\?[^:]/g);if(ternaryMatches)complexity+=ternaryMatches.length;return complexity}function getComplexityForFile(filePath){try{if(fs101.statSync(filePath).size>MAX_FILE_SIZE_BYTES3)return null;let content=fs101.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function computeComplexityDelta(files,workingDir){let totalComplexity=0,analyzedFiles=[];for(let file3 of files){let fullPath=path167.isAbsolute(file3)?file3:path167.join(workingDir,file3);if(!fs101.existsSync(fullPath))continue;let complexity=getComplexityForFile(fullPath);if(complexity!==null)totalComplexity+=complexity,analyzedFiles.push(file3)}return{delta:totalComplexity,analyzedFiles}}function countExportsInFile(content){let count=0,exportFunctionMatches=content.match(/export\s+function\s+\w+/g);if(exportFunctionMatches)count+=exportFunctionMatches.length;let exportClassMatches=content.match(/export\s+class\s+\w+/g);if(exportClassMatches)count+=exportClassMatches.length;let exportConstMatches=content.match(/export\s+const\s+\w+/g);if(exportConstMatches)count+=exportConstMatches.length;let exportLetMatches=content.match(/export\s+let\s+\w+/g);if(exportLetMatches)count+=exportLetMatches.length;let exportVarMatches=content.match(/export\s+var\s+\w+/g);if(exportVarMatches)count+=exportVarMatches.length;let exportNamedMatches=content.match(/export\s*\{[^}]+\}/g);if(exportNamedMatches)for(let match of exportNamedMatches){let names=match.match(/\b[a-zA-Z_$][a-zA-Z0-9_$]*\b/g),filteredNames=names?names.filter((n)=>n!=="export"):[];count+=filteredNames.length}let exportDefaultMatches=content.match(/export\s+default/g);if(exportDefaultMatches)count+=exportDefaultMatches.length;let exportTypeMatches=content.match(/export\s+(type|interface)\s+\w+/g);if(exportTypeMatches)count+=exportTypeMatches.length;let exportEnumMatches=content.match(/export\s+enum\s+\w+/g);if(exportEnumMatches)count+=exportEnumMatches.length;let exportEqualsMatches=content.match(/export\s+=/g);if(exportEqualsMatches)count+=exportEqualsMatches.length;return count}function countPythonExports(content){let count=0,noStrings=content.replace(/#.*/g,"").replace(/"[^"]*"/g,"").replace(/'[^']*'/g,""),functionMatches=noStrings.match(/^\s*def\s+\w+/gm);if(functionMatches)count+=functionMatches.length;let classMatches=noStrings.match(/^\s*class\s+\w+/gm);if(classMatches)count+=classMatches.length;let allMatchOriginal=content.match(/__all__\s*=\s*\[([^\]]+)\]/);if(allMatchOriginal?.[1]){let names=allMatchOriginal[1].match(/['"]?(\w+)['"]?/g);if(names){let cleanNames=names.map((n)=>n.replace(/['"]/g,""));count+=cleanNames.length}}return count}function countRustExports(content){let count=0,processed=content.replace(/\/\/.*/g,"");processed=processed.replace(/\/\*[\s\S]*?\*\//g,"");let pubFnMatches=processed.match(/pub\s+fn\s+\w+/g);if(pubFnMatches)count+=pubFnMatches.length;let pubStructMatches=processed.match(/pub\s+struct\s+\w+/g);if(pubStructMatches)count+=pubStructMatches.length;let pubEnumMatches=processed.match(/pub\s+enum\s+\w+/g);if(pubEnumMatches)count+=pubEnumMatches.length;let pubUseMatches=processed.match(/pub\s+use\s+/g);if(pubUseMatches)count+=pubUseMatches.length;let pubConstMatches=processed.match(/pub\s+const\s+\w+/g);if(pubConstMatches)count+=pubConstMatches.length;let pubModMatches=processed.match(/pub\s+mod\s+\w+/g);if(pubModMatches)count+=pubModMatches.length;let pubTypeMatches=processed.match(/pub\s+type\s+\w+/g);if(pubTypeMatches)count+=pubTypeMatches.length;return count}function countGoExports(content){let count=0,processed=content.replace(/\/\/.*/gm,"");processed=processed.replace(/\/\*[\s\S]*?\*\//g,"");let exportedFuncMatches=processed.match(/^\s*func\s+[A-Z]\w*/gm);if(exportedFuncMatches)count+=exportedFuncMatches.length;let exportedVarMatches=processed.match(/^\s*var\s+[A-Z]\w*/gm);if(exportedVarMatches)count+=exportedVarMatches.length;let exportedTypeMatches=processed.match(/^\s*type\s+[A-Z]\w*/gm);if(exportedTypeMatches)count+=exportedTypeMatches.length;let exportedConstMatches=processed.match(/^\s*const\s+[A-Z]\w*/gm);if(exportedConstMatches)count+=exportedConstMatches.length;if(processed.match(/^\s*package\s+\w+/m))count+=1;return count}function getExportCountForFile(filePath){try{let content=fs101.readFileSync(filePath,"utf-8");switch(path167.extname(filePath).toLowerCase()){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":return countExportsInFile(content);case".py":return countPythonExports(content);case".rs":return countRustExports(content);case".go":return countGoExports(content);default:return countExportsInFile(content)}}catch{return 0}}async function computePublicApiDelta(files,workingDir){let totalExports=0,analyzedFiles=[];for(let file3 of files){let fullPath=path167.isAbsolute(file3)?file3:path167.join(workingDir,file3);if(!fs101.existsSync(fullPath))continue;let exports=getExportCountForFile(fullPath);totalExports+=exports,analyzedFiles.push(file3)}return{delta:totalExports,analyzedFiles}}function findDuplicateLines(content,minLines){let lines=content.split(`
5609
5644
  `).filter((line)=>line.trim().length>0);if(lines.length<minLines)return 0;let lineCounts=new Map;for(let line of lines){let normalized=line.trim();lineCounts.set(normalized,(lineCounts.get(normalized)||0)+1)}let duplicateCount=0;for(let[_line,count]of lineCounts)if(count>1)duplicateCount+=count-1;return duplicateCount}async function computeDuplicationRatio(files,workingDir){let totalLines=0,duplicateLines=0,analyzedFiles=[];for(let file3 of files){let fullPath=path167.isAbsolute(file3)?file3:path167.join(workingDir,file3);if(!fs101.existsSync(fullPath))continue;try{if(fs101.statSync(fullPath).size>MAX_FILE_SIZE_BYTES3)continue;let content=fs101.readFileSync(fullPath,"utf-8"),lines=content.split(`
5610
5645
  `).filter((line)=>line.trim().length>0);if(lines.length<MIN_DUPLICATION_LINES){analyzedFiles.push(file3);continue}totalLines+=lines.length,duplicateLines+=findDuplicateLines(content,MIN_DUPLICATION_LINES),analyzedFiles.push(file3)}catch{}}return{ratio:totalLines>0?duplicateLines/totalLines:0,analyzedFiles}}function countCodeLines(content){let processed=content.replace(/\/\*[\s\S]*?\*\//g,"");return processed=processed.replace(/\/\/.*/g,""),processed=processed.replace(/#.*/g,""),processed.split(`
5611
- `).filter((line)=>line.trim().length>0).length}function isTestFile(filePath){let basename20=path167.basename(filePath),_ext=path167.extname(filePath).toLowerCase(),testPatterns=[".test.",".spec.",".tests.",".test.ts",".test.js",".spec.ts",".spec.js",".test.tsx",".test.jsx",".spec.tsx",".spec.jsx"];for(let pattern of testPatterns)if(basename20.includes(pattern))return!0;let normalizedPath=filePath.replace(/\\/g,"/");if(normalizedPath.includes("/tests/")||normalizedPath.includes("/test/"))return!0;if(normalizedPath.includes("/__tests__/"))return!0;return!1}function matchSegment(globSeg,pathSeg){if(globSeg==="**")return!1;if(globSeg===pathSeg)return!0;if(globSeg.includes("*")){let pattern=globSeg;return pattern=pattern.replace(/[[\](){}|+?^$.\\]/g,"\\$&"),pattern=pattern.replace(/\*/g,".*"),new RegExp(`^${pattern}$`).test(pathSeg)}return!1}function matchGlobSegment(globSegments,pathSegments){if(pathSegments.some((s)=>s===""))return!1;let gIndex=0,pIndex=0;while(gIndex<globSegments.length&&pIndex<pathSegments.length){let globSeg=globSegments[gIndex];if(globSeg==="**"){if(matchGlobSegment(globSegments.slice(gIndex+1),pathSegments.slice(pIndex)))return!0;for(let i=pIndex;i<pathSegments.length;i++)if(matchGlobSegment(globSegments.slice(gIndex+1),pathSegments.slice(i+1)))return!0;return!1}else if(globSeg==="*"){if(pathSegments[pIndex]==="")return!1;gIndex++,pIndex++}else{if(!matchSegment(globSeg,pathSegments[pIndex]))return!1;gIndex++,pIndex++}}while(gIndex<globSegments.length&&globSegments[gIndex]==="**")gIndex++;return gIndex===globSegments.length&&pIndex===pathSegments.length}function matchesGlobSegment(path168,glob){let normalizedPath=path168.replace(/\\/g,"/"),normalizedGlob=glob.replace(/\\/g,"/");if(normalizedPath.includes("//"))return!1;if(normalizedGlob.includes("//"))return!1;let pathSegments=normalizedPath.split("/").filter((s)=>s!==""),globSegments=normalizedGlob.split("/").filter((s)=>s!=="");if(globSegments.length===0)return!0;if(globSegments.length===1&&globSegments[0]==="**")return!0;return matchGlobSegment(globSegments,pathSegments)}function simpleGlobToRegex2(glob){if(!glob)return/.*/;let pattern=glob,regexMetacharacters=/[[\](){}|+?^$.\\]/g;return pattern=pattern.replace(regexMetacharacters,"\\$&"),pattern=pattern.replace(/\*/g,"[^/]+"),new RegExp(`^${pattern}$`)}function hasGlobstar(glob){return glob.includes("**")}function globMatches(path168,glob){let normalizedPath=path168.replace(/\\/g,"/");if(!glob||glob===""){if(normalizedPath.includes("//"))return!1;return!0}let normalizedGlob=glob.endsWith("\\")?glob.slice(0,-1):glob;if(normalizedPath.includes("//")||normalizedGlob.includes("//"))return!1;if(hasGlobstar(normalizedGlob))return matchesGlobSegment(normalizedPath,normalizedGlob);return simpleGlobToRegex2(normalizedGlob).test(normalizedPath)}function shouldExcludeFile(filePath,excludeGlobs){let normalizedPath=filePath.replace(/\\/g,"/");if(normalizedPath.includes("//"))return!1;for(let glob of excludeGlobs){if(glob.replace(/\\/g,"/").includes("//"))continue;if(globMatches(normalizedPath,glob))return!0}return!1}async function computeTestToCodeRatio(workingDir,enforceGlobs,excludeGlobs){let testLines=0,codeLines=0,srcDir=path167.join(workingDir,"src");if(fs101.existsSync(srcDir))await scanDirectoryForLines(srcDir,enforceGlobs,excludeGlobs,!1,(lines)=>{codeLines+=lines});let possibleSrcDirs=["lib","app","source","core"];for(let dir of possibleSrcDirs){let dirPath=path167.join(workingDir,dir);if(fs101.existsSync(dirPath))await scanDirectoryForLines(dirPath,enforceGlobs,excludeGlobs,!1,(lines)=>{codeLines+=lines})}let testsDir=path167.join(workingDir,"tests");if(fs101.existsSync(testsDir))await scanDirectoryForLines(testsDir,["**"],["node_modules","dist"],!0,(lines)=>{testLines+=lines});let possibleTestDirs=["test","__tests__","specs"];for(let dir of possibleTestDirs){let dirPath=path167.join(workingDir,dir);if(fs101.existsSync(dirPath)&&dirPath!==testsDir)await scanDirectoryForLines(dirPath,["**"],["node_modules","dist"],!0,(lines)=>{testLines+=lines})}let totalLines=testLines+codeLines;return{ratio:totalLines>0?testLines/totalLines:0,testLines,codeLines}}async function scanDirectoryForLines(dirPath,includeGlobs,excludeGlobs,isTestScan,callback){try{let entries=fs101.readdirSync(dirPath,{withFileTypes:!0});for(let entry of entries){let fullPath=path167.join(dirPath,entry.name);if(entry.isDirectory()){if(entry.name==="node_modules"||entry.name==="dist"||entry.name==="build"||entry.name===".git")continue;await scanDirectoryForLines(fullPath,includeGlobs,excludeGlobs,isTestScan,callback)}else if(entry.isFile()){let relativePath=fullPath.replace(`${dirPath}/`,""),ext=path167.extname(entry.name).toLowerCase();if(![".ts",".tsx",".js",".jsx",".py",".rs",".go",".java",".cs"].includes(ext))continue;if(isTestScan&&!isTestFile(fullPath))continue;if(!isTestScan&&isTestFile(fullPath))continue;if(shouldExcludeFile(relativePath,excludeGlobs))continue;if(!isTestScan&&includeGlobs.length>0&&!includeGlobs.includes("**")){let matches=!1;for(let glob of includeGlobs)if(globMatches(relativePath,glob)){matches=!0;break}if(!matches)continue}try{let content=fs101.readFileSync(fullPath,"utf-8"),lines=countCodeLines(content);callback(lines)}catch{}}}}catch{}}function detectViolations(metrics,thresholds){let violations=[];if(metrics.complexity_delta>thresholds.max_complexity_delta)violations.push({type:"complexity",message:`Complexity delta (${metrics.complexity_delta}) exceeds threshold (${thresholds.max_complexity_delta})`,severity:metrics.complexity_delta>thresholds.max_complexity_delta*1.5?"error":"warning",files:metrics.files_analyzed});if(metrics.public_api_delta>thresholds.max_public_api_delta)violations.push({type:"api",message:`Public API delta (${metrics.public_api_delta}) exceeds threshold (${thresholds.max_public_api_delta})`,severity:metrics.public_api_delta>thresholds.max_public_api_delta*1.5?"error":"warning",files:metrics.files_analyzed});if(metrics.duplication_ratio>thresholds.max_duplication_ratio)violations.push({type:"duplication",message:`Duplication ratio (${(metrics.duplication_ratio*100).toFixed(1)}%) exceeds threshold (${(thresholds.max_duplication_ratio*100).toFixed(1)}%)`,severity:metrics.duplication_ratio>thresholds.max_duplication_ratio*1.5?"error":"warning",files:metrics.files_analyzed});if(metrics.files_analyzed.length>0&&metrics.test_to_code_ratio<thresholds.min_test_to_code_ratio)violations.push({type:"test_ratio",message:`Test-to-code ratio (${(metrics.test_to_code_ratio*100).toFixed(1)}%) below threshold (${(thresholds.min_test_to_code_ratio*100).toFixed(1)}%)`,severity:metrics.test_to_code_ratio<thresholds.min_test_to_code_ratio*0.5?"error":"warning",files:metrics.files_analyzed});return violations}async function computeQualityMetrics(changedFiles,thresholds,workingDir){let config3={enabled:thresholds.enabled??!0,max_complexity_delta:thresholds.max_complexity_delta??5,max_public_api_delta:thresholds.max_public_api_delta??10,max_duplication_ratio:thresholds.max_duplication_ratio??0.05,min_test_to_code_ratio:thresholds.min_test_to_code_ratio??0.3,enforce_on_globs:thresholds.enforce_on_globs??["src/**"],exclude_globs:thresholds.exclude_globs??["docs/**","tests/**","**/*.test.*"]},filteredFiles=changedFiles.filter((file3)=>{let normalizedPath=file3.replace(/\\/g,"/");for(let glob of config3.enforce_on_globs)if(globMatches(normalizedPath,glob)){for(let exclude of config3.exclude_globs)if(globMatches(normalizedPath,exclude))return!1;return!0}return!1}),[complexityResult,apiResult,duplicationResult,testRatioResult]=await Promise.all([computeComplexityDelta(filteredFiles,workingDir),computePublicApiDelta(filteredFiles,workingDir),computeDuplicationRatio(filteredFiles,workingDir),computeTestToCodeRatio(workingDir,config3.enforce_on_globs,config3.exclude_globs)]),allAnalyzedFiles=[...new Set([...complexityResult.analyzedFiles,...apiResult.analyzedFiles,...duplicationResult.analyzedFiles])],violations=detectViolations({complexity_delta:complexityResult.delta,public_api_delta:apiResult.delta,duplication_ratio:duplicationResult.ratio,test_to_code_ratio:testRatioResult.ratio,files_analyzed:allAnalyzedFiles,thresholds:config3,violations:[]},config3);return{complexity_delta:complexityResult.delta,public_api_delta:apiResult.delta,duplication_ratio:duplicationResult.ratio,test_to_code_ratio:testRatioResult.ratio,files_analyzed:allAnalyzedFiles,thresholds:config3,violations}}init_bun_compat();init_create_tool();init_path_security();var MAX_FILE_SIZE_BYTES4=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}async function getGitChurn(days,directory){let churnMap=new Map,proc=bunSpawn(["git","log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",cwd:directory}),[stdout]=await Promise.all([proc.stdout.text(),proc.exited]),lines=stdout.split(/\r?\n/);for(let line of lines){let 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)}return churnMap}function getComplexityForFile2(filePath){try{if(fs102.statSync(filePath).size>MAX_FILE_SIZE_BYTES4)return null;let content=fs102.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory){let churnMap=await getGitChurn(days,directory),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count]of churnMap){let ext=path168.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs102.existsSync(fullPath))fullPath=path168.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_config();init_model_limits();init_utils2();init_state2();init_create_tool();var _internals96={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={}){let{modelID,providerID}=extractModelInfo(messages),modelLimit=resolveModelLimit(modelID,providerID,modelLimitsConfig),totalTokens=0;for(let message of messages){if(!message?.parts)continue;for(let part of message.parts)if(part?.type==="text"&&part.text)totalTokens+=estimateTokens(part.text)}let usagePercent=totalTokens/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:totalTokens,modelLimit,usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({description:"Report current context-window headroom for the active session. Returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only — no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",args:{},async execute(_args,directory,ctx){let config3=_internals96.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 _internals96.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig);return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;session.pendingAdvisoryMessages.push(`${header}
5646
+ `).filter((line)=>line.trim().length>0).length}function isTestFile(filePath){let basename22=path167.basename(filePath),_ext=path167.extname(filePath).toLowerCase(),testPatterns=[".test.",".spec.",".tests.",".test.ts",".test.js",".spec.ts",".spec.js",".test.tsx",".test.jsx",".spec.tsx",".spec.jsx"];for(let pattern of testPatterns)if(basename22.includes(pattern))return!0;let normalizedPath=filePath.replace(/\\/g,"/");if(normalizedPath.includes("/tests/")||normalizedPath.includes("/test/"))return!0;if(normalizedPath.includes("/__tests__/"))return!0;return!1}function matchSegment(globSeg,pathSeg){if(globSeg==="**")return!1;if(globSeg===pathSeg)return!0;if(globSeg.includes("*")){let pattern=globSeg;return pattern=pattern.replace(/[[\](){}|+?^$.\\]/g,"\\$&"),pattern=pattern.replace(/\*/g,".*"),new RegExp(`^${pattern}$`).test(pathSeg)}return!1}function matchGlobSegment(globSegments,pathSegments){if(pathSegments.some((s)=>s===""))return!1;let gIndex=0,pIndex=0;while(gIndex<globSegments.length&&pIndex<pathSegments.length){let globSeg=globSegments[gIndex];if(globSeg==="**"){if(matchGlobSegment(globSegments.slice(gIndex+1),pathSegments.slice(pIndex)))return!0;for(let i=pIndex;i<pathSegments.length;i++)if(matchGlobSegment(globSegments.slice(gIndex+1),pathSegments.slice(i+1)))return!0;return!1}else if(globSeg==="*"){if(pathSegments[pIndex]==="")return!1;gIndex++,pIndex++}else{if(!matchSegment(globSeg,pathSegments[pIndex]))return!1;gIndex++,pIndex++}}while(gIndex<globSegments.length&&globSegments[gIndex]==="**")gIndex++;return gIndex===globSegments.length&&pIndex===pathSegments.length}function matchesGlobSegment(path168,glob){let normalizedPath=path168.replace(/\\/g,"/"),normalizedGlob=glob.replace(/\\/g,"/");if(normalizedPath.includes("//"))return!1;if(normalizedGlob.includes("//"))return!1;let pathSegments=normalizedPath.split("/").filter((s)=>s!==""),globSegments=normalizedGlob.split("/").filter((s)=>s!=="");if(globSegments.length===0)return!0;if(globSegments.length===1&&globSegments[0]==="**")return!0;return matchGlobSegment(globSegments,pathSegments)}function simpleGlobToRegex2(glob){if(!glob)return/.*/;let pattern=glob,regexMetacharacters=/[[\](){}|+?^$.\\]/g;return pattern=pattern.replace(regexMetacharacters,"\\$&"),pattern=pattern.replace(/\*/g,"[^/]+"),new RegExp(`^${pattern}$`)}function hasGlobstar(glob){return glob.includes("**")}function globMatches(path168,glob){let normalizedPath=path168.replace(/\\/g,"/");if(!glob||glob===""){if(normalizedPath.includes("//"))return!1;return!0}let normalizedGlob=glob.endsWith("\\")?glob.slice(0,-1):glob;if(normalizedPath.includes("//")||normalizedGlob.includes("//"))return!1;if(hasGlobstar(normalizedGlob))return matchesGlobSegment(normalizedPath,normalizedGlob);return simpleGlobToRegex2(normalizedGlob).test(normalizedPath)}function shouldExcludeFile(filePath,excludeGlobs){let normalizedPath=filePath.replace(/\\/g,"/");if(normalizedPath.includes("//"))return!1;for(let glob of excludeGlobs){if(glob.replace(/\\/g,"/").includes("//"))continue;if(globMatches(normalizedPath,glob))return!0}return!1}async function computeTestToCodeRatio(workingDir,enforceGlobs,excludeGlobs){let testLines=0,codeLines=0,srcDir=path167.join(workingDir,"src");if(fs101.existsSync(srcDir))await scanDirectoryForLines(srcDir,enforceGlobs,excludeGlobs,!1,(lines)=>{codeLines+=lines});let possibleSrcDirs=["lib","app","source","core"];for(let dir of possibleSrcDirs){let dirPath=path167.join(workingDir,dir);if(fs101.existsSync(dirPath))await scanDirectoryForLines(dirPath,enforceGlobs,excludeGlobs,!1,(lines)=>{codeLines+=lines})}let testsDir=path167.join(workingDir,"tests");if(fs101.existsSync(testsDir))await scanDirectoryForLines(testsDir,["**"],["node_modules","dist"],!0,(lines)=>{testLines+=lines});let possibleTestDirs=["test","__tests__","specs"];for(let dir of possibleTestDirs){let dirPath=path167.join(workingDir,dir);if(fs101.existsSync(dirPath)&&dirPath!==testsDir)await scanDirectoryForLines(dirPath,["**"],["node_modules","dist"],!0,(lines)=>{testLines+=lines})}let totalLines=testLines+codeLines;return{ratio:totalLines>0?testLines/totalLines:0,testLines,codeLines}}async function scanDirectoryForLines(dirPath,includeGlobs,excludeGlobs,isTestScan,callback){try{let entries=fs101.readdirSync(dirPath,{withFileTypes:!0});for(let entry of entries){let fullPath=path167.join(dirPath,entry.name);if(entry.isDirectory()){if(entry.name==="node_modules"||entry.name==="dist"||entry.name==="build"||entry.name===".git")continue;await scanDirectoryForLines(fullPath,includeGlobs,excludeGlobs,isTestScan,callback)}else if(entry.isFile()){let relativePath=fullPath.replace(`${dirPath}/`,""),ext=path167.extname(entry.name).toLowerCase();if(![".ts",".tsx",".js",".jsx",".py",".rs",".go",".java",".cs"].includes(ext))continue;if(isTestScan&&!isTestFile(fullPath))continue;if(!isTestScan&&isTestFile(fullPath))continue;if(shouldExcludeFile(relativePath,excludeGlobs))continue;if(!isTestScan&&includeGlobs.length>0&&!includeGlobs.includes("**")){let matches=!1;for(let glob of includeGlobs)if(globMatches(relativePath,glob)){matches=!0;break}if(!matches)continue}try{let content=fs101.readFileSync(fullPath,"utf-8"),lines=countCodeLines(content);callback(lines)}catch{}}}}catch{}}function detectViolations(metrics,thresholds){let violations=[];if(metrics.complexity_delta>thresholds.max_complexity_delta)violations.push({type:"complexity",message:`Complexity delta (${metrics.complexity_delta}) exceeds threshold (${thresholds.max_complexity_delta})`,severity:metrics.complexity_delta>thresholds.max_complexity_delta*1.5?"error":"warning",files:metrics.files_analyzed});if(metrics.public_api_delta>thresholds.max_public_api_delta)violations.push({type:"api",message:`Public API delta (${metrics.public_api_delta}) exceeds threshold (${thresholds.max_public_api_delta})`,severity:metrics.public_api_delta>thresholds.max_public_api_delta*1.5?"error":"warning",files:metrics.files_analyzed});if(metrics.duplication_ratio>thresholds.max_duplication_ratio)violations.push({type:"duplication",message:`Duplication ratio (${(metrics.duplication_ratio*100).toFixed(1)}%) exceeds threshold (${(thresholds.max_duplication_ratio*100).toFixed(1)}%)`,severity:metrics.duplication_ratio>thresholds.max_duplication_ratio*1.5?"error":"warning",files:metrics.files_analyzed});if(metrics.files_analyzed.length>0&&metrics.test_to_code_ratio<thresholds.min_test_to_code_ratio)violations.push({type:"test_ratio",message:`Test-to-code ratio (${(metrics.test_to_code_ratio*100).toFixed(1)}%) below threshold (${(thresholds.min_test_to_code_ratio*100).toFixed(1)}%)`,severity:metrics.test_to_code_ratio<thresholds.min_test_to_code_ratio*0.5?"error":"warning",files:metrics.files_analyzed});return violations}async function computeQualityMetrics(changedFiles,thresholds,workingDir){let config3={enabled:thresholds.enabled??!0,max_complexity_delta:thresholds.max_complexity_delta??5,max_public_api_delta:thresholds.max_public_api_delta??10,max_duplication_ratio:thresholds.max_duplication_ratio??0.05,min_test_to_code_ratio:thresholds.min_test_to_code_ratio??0.3,enforce_on_globs:thresholds.enforce_on_globs??["src/**"],exclude_globs:thresholds.exclude_globs??["docs/**","tests/**","**/*.test.*"]},filteredFiles=changedFiles.filter((file3)=>{let normalizedPath=file3.replace(/\\/g,"/");for(let glob of config3.enforce_on_globs)if(globMatches(normalizedPath,glob)){for(let exclude of config3.exclude_globs)if(globMatches(normalizedPath,exclude))return!1;return!0}return!1}),[complexityResult,apiResult,duplicationResult,testRatioResult]=await Promise.all([computeComplexityDelta(filteredFiles,workingDir),computePublicApiDelta(filteredFiles,workingDir),computeDuplicationRatio(filteredFiles,workingDir),computeTestToCodeRatio(workingDir,config3.enforce_on_globs,config3.exclude_globs)]),allAnalyzedFiles=[...new Set([...complexityResult.analyzedFiles,...apiResult.analyzedFiles,...duplicationResult.analyzedFiles])],violations=detectViolations({complexity_delta:complexityResult.delta,public_api_delta:apiResult.delta,duplication_ratio:duplicationResult.ratio,test_to_code_ratio:testRatioResult.ratio,files_analyzed:allAnalyzedFiles,thresholds:config3,violations:[]},config3);return{complexity_delta:complexityResult.delta,public_api_delta:apiResult.delta,duplication_ratio:duplicationResult.ratio,test_to_code_ratio:testRatioResult.ratio,files_analyzed:allAnalyzedFiles,thresholds:config3,violations}}init_bun_compat();init_create_tool();init_path_security();var MAX_FILE_SIZE_BYTES4=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}async function getGitChurn(days,directory){let churnMap=new Map,proc=bunSpawn(["git","log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",cwd:directory}),[stdout]=await Promise.all([proc.stdout.text(),proc.exited]),lines=stdout.split(/\r?\n/);for(let line of lines){let 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)}return churnMap}function getComplexityForFile2(filePath){try{if(fs102.statSync(filePath).size>MAX_FILE_SIZE_BYTES4)return null;let content=fs102.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory){let churnMap=await getGitChurn(days,directory),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count]of churnMap){let ext=path168.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs102.existsSync(fullPath))fullPath=path168.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_config();init_model_limits();init_utils2();init_state2();init_create_tool();var _internals96={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={}){let{modelID,providerID}=extractModelInfo(messages),modelLimit=resolveModelLimit(modelID,providerID,modelLimitsConfig),totalTokens=0;for(let message of messages){if(!message?.parts)continue;for(let part of message.parts)if(part?.type==="text"&&part.text)totalTokens+=estimateTokens(part.text)}let usagePercent=totalTokens/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:totalTokens,modelLimit,usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({description:"Report current context-window headroom for the active session. Returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only — no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",args:{},async execute(_args,directory,ctx){let config3=_internals96.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 _internals96.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig);return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;session.pendingAdvisoryMessages.push(`${header}
5612
5647
  ${body}`)}init_zod();init_task_file();import{appendFileSync as appendFileSync18,existsSync as existsSync96,mkdirSync as mkdirSync44,readFileSync as readFileSync64}from"node:fs";import{join as join136}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()),_internals97={withTaskEvidenceLock},FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);function safeAssignOwnProps(target,source){for(let key of Object.keys(source)){if(FORBIDDEN_KEYS.has(key))continue;let value=source[key];if(value!==null&&typeof value==="object"&&!Array.isArray(value)){let nested=Object.create(null);safeAssignOwnProps(nested,value),target[key]=nested}else if(Array.isArray(value))target[key]=value.map((item)=>{if(item!==null&&typeof item==="object"&&!Array.isArray(item)){let nested=Object.create(null);return safeAssignOwnProps(nested,item),nested}return item});else target[key]=value}return target}async function writeCouncilEvidence(workingDir,synthesis){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=join136(workingDir,EVIDENCE_DIR2);mkdirSync44(dir,{recursive:!0});let filePath=taskEvidencePath(workingDir,synthesis.taskId);await _internals97.withTaskEvidenceLock(workingDir,synthesis.taskId,COUNCIL_AGENT_ID,async()=>{let existingRoot=Object.create(null);if(existsSync96(filePath))try{let parsed=EvidenceFileSchema.parse(JSON.parse(readFileSync64(filePath,"utf-8")));safeAssignOwnProps(existingRoot,parsed)}catch{}let existingGatesRaw=existingRoot.gates,mergedGates=Object.create(null);if(existingGatesRaw&&typeof existingGatesRaw==="object"&&!Array.isArray(existingGatesRaw))safeAssignOwnProps(mergedGates,existingGatesRaw);mergedGates[COUNCIL_GATE_NAME]={sessionId:synthesis.swarmId,timestamp:synthesis.timestamp,agent:COUNCIL_AGENT_ID,verdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,quorumSize:synthesis.quorumSize};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))});try{let councilDir=join136(workingDir,".swarm","council");mkdirSync44(councilDir,{recursive:!0});let auditLine=JSON.stringify({round:synthesis.roundNumber,verdict:synthesis.overallVerdict,timestamp:synthesis.timestamp,vetoedBy:synthesis.vetoedBy});appendFileSync18(join136(councilDir,`${synthesis.taskId}.rounds.jsonl`),`${auditLine}
5613
5648
  `)}catch(auditError){console.warn(`writeCouncilEvidence: failed to append round-history audit log: ${auditError instanceof Error?auditError.message:String(auditError)}`)}}var COUNCIL_DEFAULTS={enabled:!1,maxRounds:3,parallelTimeoutMs:30000,vetoPriority:!0,requireAllMembers:!1,minimumMembers:3,phaseConcernsAllowComplete:!0};function synthesizeCouncilVerdicts(taskId,swarmId,verdicts,criteria,roundNumber,config3={}){let cfg={...COUNCIL_DEFAULTS,...config3},timestamp=new Date().toISOString(),quorumSize=new Set(verdicts.map((v)=>v.agent)).size,rejectingMembers=verdicts.filter((v)=>v.verdict==="REJECT").map((v)=>v.agent),overallVerdict;if(cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="REJECT";else if(verdicts.some((v)=>v.verdict==="CONCERNS")||!cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="CONCERNS";else overallVerdict="APPROVE";let unresolvedConflicts=detectConflicts2(verdicts),rejectingSet=new Set(rejectingMembers),vetoFindings=verdicts.filter((v)=>rejectingSet.has(v.agent)).flatMap((v)=>v.findings),requiredFixes=vetoFindings.filter((f)=>f.severity==="CRITICAL"||f.severity==="HIGH"||f.severity==="MEDIUM"),advisoryFindings=[...vetoFindings.filter((f)=>f.severity==="LOW"),...verdicts.filter((v)=>!rejectingSet.has(v.agent)).flatMap((v)=>v.findings)],blockingConcernsCount=promoteBlockingConcerns(verdicts,rejectingSet,requiredFixes,advisoryFindings),allAssessedIds=new Set(verdicts.flatMap((v)=>v.criteriaAssessed)),allUnmetIds=new Set(verdicts.flatMap((v)=>v.criteriaUnmet)),allCriteriaMet=[...new Set((criteria?.criteria??[]).filter((c)=>c.mandatory).map((c)=>c.id))].every((id)=>allAssessedIds.has(id)&&!allUnmetIds.has(id)),unifiedFeedbackMd=buildUnifiedFeedback(taskId,overallVerdict,rejectingMembers,requiredFixes,advisoryFindings,unresolvedConflicts,roundNumber,cfg.maxRounds,blockingConcernsCount);return{taskId,swarmId,timestamp,overallVerdict,vetoedBy:rejectingMembers.length>0?rejectingMembers:null,memberVerdicts:verdicts,unresolvedConflicts,requiredFixes,advisoryFindings,unifiedFeedbackMd,roundNumber,allCriteriaMet,quorumSize,blockingConcernsCount,...verdicts.length===0&&{emptyVerdictsWarning:!0}}}function promoteBlockingConcerns(verdicts,rejectingSet,requiredFixes,advisoryFindings){let blocking=verdicts.filter((v)=>v.verdict==="CONCERNS"&&!rejectingSet.has(v.agent)).flatMap((v)=>v.findings).filter((f)=>f.severity==="CRITICAL"||f.severity==="HIGH");if(blocking.length===0)return 0;requiredFixes.push(...blocking);let blockingSet=new Set(blocking);for(let i=advisoryFindings.length-1;i>=0;i--)if(blockingSet.has(advisoryFindings[i]))advisoryFindings.splice(i,1);return blocking.length}function detectConflicts2(verdicts){let conflicts=[],locationMap=new Map;for(let verdict of verdicts)for(let finding of verdict.findings){let key=finding.location.toLowerCase();if(!key)continue;let entries=locationMap.get(key);if(entries)entries.push({agent:verdict.agent,detail:finding.detail});else locationMap.set(key,[{agent:verdict.agent,detail:finding.detail}])}for(let[location,entries]of locationMap){if(entries.length<2)continue;let addDirectives=entries.filter((e)=>/\badd\b|\binclude\b|\binsert\b/i.test(e.detail)),removeDirectives=entries.filter((e)=>/\bremove\b|\bdelete\b|\beliminate\b/i.test(e.detail));if(addDirectives.length>0&&removeDirectives.length>0)conflicts.push(`Conflict at ${location}: ${addDirectives.map((e)=>`${e.agent} says "${e.detail}"`).join(", ")} vs ${removeDirectives.map((e)=>`${e.agent} says "${e.detail}"`).join(", ")}`)}return conflicts}function buildUnifiedFeedback(taskId,verdict,vetoedBy,requiredFixes,advisoryFindings,conflicts,roundNumber,maxRounds,blockingConcernsCount=0){let lines=[`## Work Complete Council — Round ${roundNumber}/${maxRounds}`,`**Task:** ${taskId} **Overall verdict:** ${verdict}`,""];if(vetoedBy.length>0)lines.push(`> ⛔ **BLOCKED** by: ${vetoedBy.join(", ")}`),lines.push("");if(blockingConcernsCount>0)lines.push(`> ⚠️ **BLOCKING CONCERNS**: ${blockingConcernsCount} HIGH/CRITICAL finding(s) from CONCERNS members require investigation and resolution before advancement.`),lines.push("");if(requiredFixes.length>0){lines.push("### Required Fixes (must resolve before re-submission)");for(let f of requiredFixes)lines.push(`- **[${f.severity}]** \`${f.location}\` — ${f.detail}`,` _Evidence:_ ${f.evidence}`);lines.push("")}if(conflicts.length>0){lines.push("### Conflicts to Resolve"),lines.push("_The following reviewers gave contradictory instructions. Architect must resolve before sending to coder._");for(let c of conflicts)lines.push(`- ${c}`);lines.push("")}if(advisoryFindings.length>0){lines.push("### Advisory Findings (non-blocking)");for(let f of advisoryFindings)lines.push(`- **[${f.severity}]** \`${f.location}\` — ${f.detail}`);lines.push("")}if(verdict==="APPROVE")lines.push("> ✅ **All council members approved.** Work may advance to `complete`.");else if(roundNumber>=maxRounds)lines.push(`> ⚠️ **Max rounds (${maxRounds}) reached.** Escalate to user — do not auto-advance.`);return lines.join(`
5614
5649
  `)}function synthesizePhaseCouncilAdvisory(phaseNumber,phaseSummary,verdicts,roundNumber,config3={},_workingDir){let cfg={...COUNCIL_DEFAULTS,...config3},timestamp=new Date().toISOString(),scope="phase",quorumSize=new Set(verdicts.map((v)=>v.agent)).size,rejectingMembers=verdicts.filter((v)=>v.verdict==="REJECT").map((v)=>v.agent),overallVerdict;if(cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="REJECT";else if(verdicts.some((v)=>v.verdict==="CONCERNS")||!cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="CONCERNS";else overallVerdict="APPROVE";let unresolvedConflicts=detectConflicts2(verdicts),rejectingSet=new Set(rejectingMembers),vetoFindings=verdicts.filter((v)=>rejectingSet.has(v.agent)).flatMap((v)=>v.findings),requiredFixes=vetoFindings.filter((f)=>f.severity==="CRITICAL"||f.severity==="HIGH"||f.severity==="MEDIUM"),advisoryFindings=[...vetoFindings.filter((f)=>f.severity==="LOW"),...verdicts.filter((v)=>!rejectingSet.has(v.agent)).flatMap((v)=>v.findings)],blockingConcernsCount=promoteBlockingConcerns(verdicts,rejectingSet,requiredFixes,advisoryFindings),advisoryNotes=[];if(advisoryFindings.length>0)advisoryNotes.push(`Phase ${phaseNumber} council found ${advisoryFindings.length} advisory finding(s). Review before proceeding to next phase.`);if(verdicts.length<3)advisoryNotes.push(`Phase council quorum is ${verdicts.length} members — consider convening additional members for broader review coverage.`);let allCriteriaMet=new Set(verdicts.flatMap((v)=>v.criteriaUnmet)).size===0&&verdicts.length>0,unifiedFeedbackMd=buildPhaseCouncilFeedback(phaseNumber,phaseSummary,overallVerdict,rejectingMembers,requiredFixes,advisoryFindings,unresolvedConflicts,roundNumber,cfg.maxRounds,blockingConcernsCount),evidencePath=`.swarm/evidence/${phaseNumber}/phase-council.json`;return{phaseNumber,scope:"phase",timestamp,overallVerdict,vetoedBy:rejectingMembers.length>0?rejectingMembers:null,memberVerdicts:verdicts,unresolvedConflicts,requiredFixes,advisoryFindings,advisoryNotes,unifiedFeedbackMd,roundNumber,allCriteriaMet,quorumSize,blockingConcernsCount,evidencePath,phaseSummary}}function buildPhaseCouncilFeedback(phaseNumber,phaseSummary,verdict,vetoedBy,requiredFixes,advisoryFindings,conflicts,roundNumber,maxRounds,blockingConcernsCount=0){let lines=[`## Phase Council Review — Round ${roundNumber}/${maxRounds}`,`**Phase:** ${phaseNumber} **Overall verdict:** ${verdict}`,""];if(phaseSummary)lines.push(`**Phase Summary:** ${phaseSummary}`),lines.push("");if(vetoedBy.length>0)lines.push(`> ⛔ **BLOCKED** by: ${vetoedBy.join(", ")}`),lines.push("");if(blockingConcernsCount>0)lines.push(`> ⚠️ **BLOCKING CONCERNS**: ${blockingConcernsCount} HIGH/CRITICAL finding(s) from CONCERNS members require investigation and resolution before phase completion.`),lines.push("");if(requiredFixes.length>0){lines.push("### Required Fixes (must resolve before re-submission)");for(let f of requiredFixes)lines.push(`- **[${f.severity}]** \`${f.location}\` — ${f.detail}`,` _Evidence:_ ${f.evidence}`);lines.push("")}if(conflicts.length>0){lines.push("### Conflicts to Resolve"),lines.push("_The following reviewers gave contradictory instructions. Architect must resolve before sending to coder._");for(let c of conflicts)lines.push(`- ${c}`);lines.push("")}if(advisoryFindings.length>0){lines.push("### Advisory Findings (non-blocking)");for(let f of advisoryFindings)lines.push(`- **[${f.severity}]** \`${f.location}\` — ${f.detail}`);lines.push("")}if(verdict==="APPROVE")lines.push("> ✅ **Phase council approved.** Phase may proceed to completion.");else if(roundNumber>=maxRounds)lines.push(`> ⚠️ **Max rounds (${maxRounds}) reached.** Escalate to user — do not auto-advance.`);return lines.join(`
5615
5650
  `)}function synthesizeFinalCouncilAdvisory(projectSummary,verdicts,roundNumber,config3={}){let cfg={...COUNCIL_DEFAULTS,...config3},timestamp=new Date().toISOString(),quorumSize=new Set(verdicts.map((v)=>v.agent)).size,rejectingMembers=verdicts.filter((v)=>v.verdict==="REJECT").map((v)=>v.agent),overallVerdict;if(cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="REJECT";else if(verdicts.some((v)=>v.verdict==="CONCERNS")||!cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="CONCERNS";else overallVerdict="APPROVE";let unresolvedConflicts=detectConflicts2(verdicts),rejectingSet=new Set(rejectingMembers),vetoFindings=verdicts.filter((v)=>rejectingSet.has(v.agent)).flatMap((v)=>v.findings),requiredFixes=vetoFindings.filter((f)=>f.severity==="CRITICAL"||f.severity==="HIGH"||f.severity==="MEDIUM"),advisoryFindings=[...vetoFindings.filter((f)=>f.severity==="LOW"),...verdicts.filter((v)=>!rejectingSet.has(v.agent)).flatMap((v)=>v.findings)],blockingConcernsCount=promoteBlockingConcerns(verdicts,rejectingSet,requiredFixes,advisoryFindings),advisoryNotes=[];if(advisoryFindings.length>0)advisoryNotes.push(`Final council found ${advisoryFindings.length} advisory finding(s). Review before project close.`);if(quorumSize<3)advisoryNotes.push(`Final council quorum is ${quorumSize} members - dispatch additional project-scoped council members before closing the project.`);let allCriteriaMet=new Set(verdicts.flatMap((v)=>v.criteriaUnmet)).size===0&&verdicts.length>0,unifiedFeedbackMd=buildFinalCouncilFeedback(projectSummary,overallVerdict,rejectingMembers,requiredFixes,advisoryFindings,unresolvedConflicts,roundNumber,cfg.maxRounds,blockingConcernsCount);return{scope:"project",timestamp,overallVerdict,vetoedBy:rejectingMembers.length>0?rejectingMembers:null,memberVerdicts:verdicts,unresolvedConflicts,requiredFixes,advisoryFindings,advisoryNotes,unifiedFeedbackMd,roundNumber,allCriteriaMet,quorumSize,evidencePath:".swarm/evidence/final-council.json",blockingConcernsCount,projectSummary}}function buildFinalCouncilFeedback(projectSummary,verdict,vetoedBy,requiredFixes,advisoryFindings,conflicts,roundNumber,maxRounds,blockingConcernsCount=0){let lines=[`## Final Council Review - Round ${roundNumber}/${maxRounds}`,`**Scope:** completed project **Overall verdict:** ${verdict}`,""];if(projectSummary)lines.push(`**Project Summary:** ${projectSummary}`),lines.push("");if(blockingConcernsCount>0)lines.push(`> ⚠️ **BLOCKING CONCERNS**: ${blockingConcernsCount} HIGH/CRITICAL finding(s) from CONCERNS members require investigation and resolution before project close.`),lines.push("");if(vetoedBy.length>0)lines.push(`> BLOCKED: project close is blocked by ${vetoedBy.join(", ")}`),lines.push("");if(requiredFixes.length>0){lines.push("### Required Fixes (must resolve before project close)");for(let f of requiredFixes)lines.push(`- **[${f.severity}]** \`${f.location}\` - ${f.detail}`,` _Evidence:_ ${f.evidence}`);lines.push("")}if(conflicts.length>0){lines.push("### Conflicts to Resolve"),lines.push("_The following council members gave contradictory project-close instructions. Architect must resolve before closing the project._");for(let c of conflicts)lines.push(`- ${c}`);lines.push("")}if(advisoryFindings.length>0){lines.push("### Advisory Findings (non-blocking)");for(let f of advisoryFindings)lines.push(`- **[${f.severity}]** \`${f.location}\` - ${f.detail}`);lines.push("")}if(verdict==="APPROVE")lines.push("> Final council approved. Project may proceed to close.");else if(roundNumber>=maxRounds)lines.push(`> Max rounds (${maxRounds}) reached. Escalate to user - do not close the project automatically.`);return lines.join(`
5616
- `)}init_zod();init_task_file();import{existsSync as existsSync97,mkdirSync as mkdirSync45,readFileSync as readFileSync65}from"node:fs";import{join as join137}from"node:path";var COUNCIL_DIR=".swarm/council",CouncilCriteriaSchema=exports_external.object({taskId:exports_external.string(),criteria:exports_external.array(exports_external.object({id:exports_external.string(),description:exports_external.string(),mandatory:exports_external.boolean()})),declaredAt:exports_external.string()});async function writeCriteria(workingDir,taskId,criteria){let dir=join137(workingDir,COUNCIL_DIR);mkdirSync45(dir,{recursive:!0});let payload={taskId,criteria,declaredAt:new Date().toISOString()};await atomicWriteFile(join137(dir,`${safeId(taskId)}.json`),JSON.stringify(payload,null,2))}function readCriteria(workingDir,taskId){let filePath=join137(workingDir,COUNCIL_DIR,`${safeId(taskId)}.json`);if(!existsSync97(filePath))return null;try{return CouncilCriteriaSchema.parse(JSON.parse(readFileSync65(filePath,"utf-8")))}catch{return null}}function safeId(id){return id.replace(/[^a-zA-Z0-9_-]/g,"_")}init_state2();init_create_tool();init_resolve_working_directory();var FindingSchema=exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()}),VerdictSchema=exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(FindingSchema),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema=exports_external.object({taskId: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")'),swarmId:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).default(1),verdicts:exports_external.array(VerdictSchema).min(1).max(5),working_directory:exports_external.string().optional()}),submit_council_verdicts=createSwarmTool({description:"Submit pre-collected council member verdicts for synthesis. PREREQUISITE — "+"you MUST dispatch each council member (critic, reviewer, sme, test_engineer, explorer) as separate Agent tasks and collect their verdict responses BEFORE "+"calling this tool. This tool performs synthesis only — it does NOT dispatch, "+"invoke, or contact council members. Calling this tool without first collecting real verdicts from dispatched agents constitutes a council bypass. Returns the synthesized verdict, required fixes, and a quorum report showing which members voted and which were absent. Architect-only. Config-gated via council.enabled.",args:{taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format").describe('Task ID being evaluated, e.g. "1.1", "1.2.3"'),swarmId:exports_external.string().min(1).describe('Swarm identifier, e.g. "mega"'),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed round number. Defaults to 1."),verdicts:exports_external.array(exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number()})).min(1).max(5).describe("Array of CouncilMemberVerdict objects. Must include between 1 and 5 entries, one per participating member (critic, reviewer, sme, test_engineer, explorer)."),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/council/ and .swarm/evidence/ are resolved relative to this path instead of the plugin context directory.")},async execute(args2,directory,ctx){let parsed=ArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let input=parsed.data,dirResult=resolveWorkingDirectory(input.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,config3=loadPluginConfig(workingDir);if(!config3.council?.enabled)return JSON.stringify({success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},null,2);let effectiveMinimum=config3.council?.requireAllMembers?5:config3.council?.minimumMembers??3,ALL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],distinctMembers=new Set(input.verdicts.map((v)=>v.agent)),membersVoted=[...distinctMembers],membersAbsent=ALL_MEMBERS.filter((m)=>!distinctMembers.has(m)),sessionID=ctx?.sessionID,session=sessionID?getAgentSession(sessionID):void 0,requirementKey=`${input.taskId}:${input.roundNumber}`;if(session&&!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;let pendingRequirements=session?.pendingCouncilRequirements?.get(requirementKey);if(pendingRequirements&&pendingRequirements.size>0){let stillMissingMembers=[...pendingRequirements].filter((member)=>!distinctMembers.has(member));if(stillMissingMembers.length>0)return JSON.stringify({success:!1,reason:"cherry_pick_detected",message:`Incomplete re-dispatch: ${stillMissingMembers.join(", ")} were required from the previous insufficient_quorum response but are still absent. Dispatch ALL absent members in one parallel batch.`,stillMissingMembers,membersProvided:membersVoted},null,2)}if(membersVoted.length<effectiveMinimum){if(session?.pendingCouncilRequirements)session.pendingCouncilRequirements.set(requirementKey,new Set(membersAbsent));return JSON.stringify({success:!1,reason:"insufficient_quorum",message:`Council quorum not met: ${membersVoted.length} of ${effectiveMinimum} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members as Agent tasks and collect their verdicts before calling submit_council_verdicts.`,membersVoted,membersAbsent,quorumRequired:effectiveMinimum},null,2)}let staleVerdicts=input.roundNumber>1?input.verdicts.filter((v)=>(v.verdictRound??1)<input.roundNumber):[];if(staleVerdicts.length>0)return JSON.stringify({success:!1,reason:"stale_verdict_detected",message:`Round ${input.roundNumber} requires fresh verdicts. One or more submitted verdicts are from an older round.`,staleVerdicts:staleVerdicts.map((v)=>({agent:v.agent,verdictRound:v.verdictRound}))},null,2);let criteria=readCriteria(workingDir,input.taskId),verdicts=input.verdicts,synthesis=synthesizeCouncilVerdicts(input.taskId,input.swarmId,verdicts,criteria,input.roundNumber,config3.council),dissenters=synthesis.memberVerdicts.filter((v)=>v.verdict==="CONCERNS"||v.verdict==="REJECT").map((v)=>v.agent);if(session?.pendingCouncilRequirements){if(session.pendingCouncilRequirements.delete(requirementKey),dissenters.length>0){let nextRoundKey=`${input.taskId}:${input.roundNumber+1}`;session.pendingCouncilRequirements.set(nextRoundKey,new Set(dissenters))}}if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return JSON.stringify({success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the task can advance. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},null,2);await writeCouncilEvidence(workingDir,synthesis);try{if(sessionID){if(session)pushCouncilAdvisory(session,synthesis)}}catch{}return JSON.stringify({success:!0,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,membersVoted,membersAbsent,quorumSize:membersVoted.length,quorumMet:!0,unifiedFeedbackMd:synthesis.unifiedFeedbackMd},null,2)}});init_zod();init_loader();import*as fs103 from"node:fs";import*as path169 from"node:path";function pushGeneralCouncilAdvisory(session,result){if(!session)return;let body=renderAdvisoryBody(result);if(!body)return;session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.push(`[general_council] (advisory; not blocking)
5617
- ${body}`)}function renderAdvisoryBody(result){return result.synthesis.trim()}var EXPLICIT_DISAGREEMENT_MARKERS=["i disagree with","i would push back on","contrary to","this contradicts","unlike "],STRONG_RECOMMENDATION_MARKERS=["recommend","best approach","should use","i suggest","the answer is","the right choice is"];function tokenize2(text){return text.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((t)=>t.length>=3)}function termOverlap(a,b){let tokensA=new Set(tokenize2(a)),tokensB=new Set(tokenize2(b));if(tokensA.size===0||tokensB.size===0)return 0;let intersection3=0;for(let t of tokensA)if(tokensB.has(t))intersection3++;let union3=tokensA.size+tokensB.size-intersection3;return union3===0?0:intersection3/union3}function extractMarkerSentence(response,markers){let lower=response.toLowerCase(),sentences=response.split(/(?<=[.!?])\s+/);for(let sentence of sentences){let sentLower=sentence.toLowerCase();if(markers.some((m)=>sentLower.includes(m)))return sentence.trim()}for(let marker of markers){let idx=lower.indexOf(marker);if(idx!==-1){let slice=response.slice(idx,idx+200);return slice.split(/\n/)[0]?.trim()??slice.trim()}}return null}function dedupeByTopic(disagreements){let result=[];for(let d of disagreements){let topicLower=d.topic.toLowerCase(),existing=result.find((r)=>r.topic.toLowerCase().includes(topicLower)||topicLower.includes(r.topic.toLowerCase()));if(existing){for(let pos of d.positions)if(!existing.positions.some((p)=>p.memberId===pos.memberId))existing.positions.push(pos)}else result.push(d)}return result}function detectExplicitMarkers(responses){let out=[];for(let member of responses){let markerSentence=extractMarkerSentence(member.response,EXPLICIT_DISAGREEMENT_MARKERS);if(!markerSentence)continue;let position={memberId:member.memberId,claim:markerSentence,evidence:member.sources[0]?.url??"(no source cited in marker sentence)"};out.push({topic:markerSentence.slice(0,80),positions:[position]})}return out}function extractRecommendation(response){return extractMarkerSentence(response,STRONG_RECOMMENDATION_MARKERS)}function detectClaimDivergence(responses){let recommendations=[];for(let member of responses){let rec=extractRecommendation(member.response);if(!rec)continue;recommendations.push({memberId:member.memberId,text:rec,evidence:member.sources[0]?.url??"(no source cited)"})}let out=[];for(let i=0;i<recommendations.length;i++)for(let j=i+1;j<recommendations.length;j++){let a=recommendations[i],b=recommendations[j];if(!a||!b)continue;let topicOverlap=termOverlap(a.text,b.text);if(topicOverlap>0.4)continue;if(topicOverlap>0&&topicOverlap<0.3){let topic=`${a.text.slice(0,50)} vs ${b.text.slice(0,50)}`;out.push({topic,positions:[{memberId:a.memberId,claim:a.text,evidence:a.evidence},{memberId:b.memberId,claim:b.text,evidence:b.evidence}]})}}return out}function detectDisagreements(responses){if(!Array.isArray(responses)||responses.length<2)return[];let safeResponses=responses.filter((r)=>typeof r?.memberId==="string"&&typeof r?.response==="string"),explicit=detectExplicitMarkers(safeResponses),divergent=detectClaimDivergence(safeResponses),combined=[...explicit,...divergent];return dedupeByTopic(combined).slice(0,10)}var CONSENSUS_WEIGHT_THRESHOLD=0.6;function tokenize3(text){return text.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((t)=>t.length>=4)}function similarity(a,b){let tokensA=new Set(tokenize3(a)),tokensB=new Set(tokenize3(b));if(tokensA.size===0||tokensB.size===0)return 0;let intersection3=0;for(let t of tokensA)if(tokensB.has(t))intersection3++;let union3=tokensA.size+tokensB.size-intersection3;return union3===0?0:intersection3/union3}function extractClaims(response){return response.split(/(?<=[.!?])\s+/).map((s)=>s.trim()).filter((s)=>s.length>=30&&s.length<=400)}function buildConsensusClusters(responses){if(responses.length<2)return[];let totalMembers=responses.length,clusters=[];for(let member of responses){let confidence=clamp01(member.confidence??0.5),claims=extractClaims(member.response??"");for(let claim of claims){let assigned=!1;for(let cluster of clusters)if(similarity(cluster.representative,claim)>=0.5){if(!cluster.memberIds.has(member.memberId))cluster.weightedAgreement+=confidence,cluster.memberIds.add(member.memberId);if(claim.length>cluster.representative.length)cluster.representative=claim;assigned=!0;break}if(!assigned)clusters.push({representative:claim,weightedAgreement:confidence,memberIds:new Set([member.memberId])})}}return clusters.filter((c)=>c.memberIds.size>=2&&c.weightedAgreement/totalMembers>=CONSENSUS_WEIGHT_THRESHOLD).sort((a,b)=>b.weightedAgreement-a.weightedAgreement||b.memberIds.size-a.memberIds.size).map((c)=>c.representative)}function clamp01(n){if(typeof n!=="number"||Number.isNaN(n))return 0;if(n<0)return 0;if(n>1)return 1;return n}function computePersistingDisagreements(disagreements,round2){if(disagreements.length===0)return[];if(round2.length===0)return disagreements;return disagreements.filter((d)=>{let disputants=new Set(d.positions.map((p)=>p.memberId));return!round2.some((r)=>{if(!disputants.has(r.memberId))return!1;if(!r.disagreementTopics?.includes(d.topic))return!1;return/\bconcede\b/i.test(r.response??"")})})}function dedupeSources(round1,round2){let seen=new Set,out=[],allSources=[...round1,...round2].flatMap((r)=>r.sources??[]);for(let src of allSources){if(!src?.url)continue;if(seen.has(src.url))continue;seen.add(src.url),out.push(src)}return out}function renderSynthesisMarkdown(question,mode,roundsCompleted,members,consensusPoints,persistingDisagreements,allSources){let memberLines=members.map((m)=>`- ${m.memberId} (${m.model}, ${m.role})`).join(`
5651
+ `)}init_zod();init_task_file();import{existsSync as existsSync97,mkdirSync as mkdirSync45,readFileSync as readFileSync65}from"node:fs";import{join as join137}from"node:path";var COUNCIL_DIR=".swarm/council",CouncilCriteriaSchema=exports_external.object({taskId:exports_external.string(),criteria:exports_external.array(exports_external.object({id:exports_external.string(),description:exports_external.string(),mandatory:exports_external.boolean()})),declaredAt:exports_external.string()});async function writeCriteria(workingDir,taskId,criteria){let dir=join137(workingDir,COUNCIL_DIR);mkdirSync45(dir,{recursive:!0});let payload={taskId,criteria,declaredAt:new Date().toISOString()};await atomicWriteFile(join137(dir,`${safeId(taskId)}.json`),JSON.stringify(payload,null,2))}function readCriteria(workingDir,taskId){let filePath=join137(workingDir,COUNCIL_DIR,`${safeId(taskId)}.json`);if(!existsSync97(filePath))return null;try{return CouncilCriteriaSchema.parse(JSON.parse(readFileSync65(filePath,"utf-8")))}catch{return null}}function safeId(id){return id.replace(/[^a-zA-Z0-9_-]/g,"_")}init_reward();init_state2();init_create_tool();init_resolve_working_directory();var FindingSchema=exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()}),VerdictSchema=exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(FindingSchema),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative(),sessionId:exports_external.string().min(1).optional()}),ArgsSchema=exports_external.object({taskId: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")'),swarmId:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).default(1),verdicts:exports_external.array(VerdictSchema).min(1).max(5),working_directory:exports_external.string().optional(),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced the recall context (optional provenance for memory reward lookup)")}),submit_council_verdicts=createSwarmTool({description:"Submit pre-collected council member verdicts for synthesis. PREREQUISITE — "+"you MUST dispatch each council member (critic, reviewer, sme, test_engineer, explorer) as separate Agent tasks and collect their verdict responses BEFORE "+"calling this tool. This tool performs synthesis only — it does NOT dispatch, "+"invoke, or contact council members. Calling this tool without first collecting real verdicts from dispatched agents constitutes a council bypass. Returns the synthesized verdict, required fixes, and a quorum report showing which members voted and which were absent. Architect-only. Config-gated via council.enabled.",args:{taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format").describe('Task ID being evaluated, e.g. "1.1", "1.2.3"'),swarmId:exports_external.string().min(1).describe('Swarm identifier, e.g. "mega"'),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed round number. Defaults to 1."),verdicts:exports_external.array(exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number(),sessionId:exports_external.string().min(1).optional().describe("Session id of the dispatched agent that produced this verdict, if known — used so this member's own recall bundle is rewarded, not just the submitting session's.")})).min(1).max(5).describe("Array of CouncilMemberVerdict objects. Must include between 1 and 5 entries, one per participating member (critic, reviewer, sme, test_engineer, explorer)."),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/council/ and .swarm/evidence/ are resolved relative to this path instead of the plugin context directory.")},async execute(args2,directory,ctx){let parsed=ArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let input=parsed.data,dirResult=resolveWorkingDirectory(input.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,config3=loadPluginConfig(workingDir);if(!config3.council?.enabled)return JSON.stringify({success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},null,2);let effectiveMinimum=config3.council?.requireAllMembers?5:config3.council?.minimumMembers??3,ALL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],distinctMembers=new Set(input.verdicts.map((v)=>v.agent)),membersVoted=[...distinctMembers],membersAbsent=ALL_MEMBERS.filter((m)=>!distinctMembers.has(m)),sessionID=ctx?.sessionID,session=sessionID?getAgentSession(sessionID):void 0,requirementKey=`${input.taskId}:${input.roundNumber}`;if(session&&!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;let pendingRequirements=session?.pendingCouncilRequirements?.get(requirementKey);if(pendingRequirements&&pendingRequirements.size>0){let stillMissingMembers=[...pendingRequirements].filter((member)=>!distinctMembers.has(member));if(stillMissingMembers.length>0)return JSON.stringify({success:!1,reason:"cherry_pick_detected",message:`Incomplete re-dispatch: ${stillMissingMembers.join(", ")} were required from the previous insufficient_quorum response but are still absent. Dispatch ALL absent members in one parallel batch.`,stillMissingMembers,membersProvided:membersVoted},null,2)}if(membersVoted.length<effectiveMinimum){if(session?.pendingCouncilRequirements)session.pendingCouncilRequirements.set(requirementKey,new Set(membersAbsent));return JSON.stringify({success:!1,reason:"insufficient_quorum",message:`Council quorum not met: ${membersVoted.length} of ${effectiveMinimum} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members as Agent tasks and collect their verdicts before calling submit_council_verdicts.`,membersVoted,membersAbsent,quorumRequired:effectiveMinimum},null,2)}let staleVerdicts=input.roundNumber>1?input.verdicts.filter((v)=>(v.verdictRound??1)<input.roundNumber):[];if(staleVerdicts.length>0)return JSON.stringify({success:!1,reason:"stale_verdict_detected",message:`Round ${input.roundNumber} requires fresh verdicts. One or more submitted verdicts are from an older round.`,staleVerdicts:staleVerdicts.map((v)=>({agent:v.agent,verdictRound:v.verdictRound}))},null,2);let criteria=readCriteria(workingDir,input.taskId),verdicts=input.verdicts,synthesis=synthesizeCouncilVerdicts(input.taskId,input.swarmId,verdicts,criteria,input.roundNumber,config3.council),dissenters=synthesis.memberVerdicts.filter((v)=>v.verdict==="CONCERNS"||v.verdict==="REJECT").map((v)=>v.agent);if(session?.pendingCouncilRequirements){if(session.pendingCouncilRequirements.delete(requirementKey),dissenters.length>0){let nextRoundKey=`${input.taskId}:${input.roundNumber+1}`;session.pendingCouncilRequirements.set(nextRoundKey,new Set(dissenters))}}if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return JSON.stringify({success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the task can advance. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},null,2);await writeCouncilEvidence(workingDir,synthesis);let rewardRunIds=resolveRewardRunIds({trustedSessionIds:[ctx?.sessionID,sessionID],untrustedSessionIds:[input.provenanceSessionId,...input.verdicts.map((v)=>v.sessionId)],isKnownSession:(id)=>getAgentSession(id)!==void 0}),memoryReward=null;try{memoryReward=await applyRecallRewardForCouncil(workingDir,config3.memory,{runIds:rewardRunIds,verdict:synthesis.overallVerdict,verdictPayload:{taskId:synthesis.taskId,swarmId:synthesis.swarmId,roundNumber:synthesis.roundNumber,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length}})}catch(err){memoryReward={success:!1,outcome:councilVerdictToMemoryOutcome(synthesis.overallVerdict),memoryIds:[],reward:0,updatedMemoryIds:[],propagatedMemoryIds:[],reason:`reward_threw: ${err instanceof Error?err.message:String(err)}`}}try{if(sessionID){if(session)pushCouncilAdvisory(session,synthesis)}}catch{}return JSON.stringify({success:!0,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,membersVoted,membersAbsent,quorumSize:membersVoted.length,quorumMet:!0,memoryReward,...memoryReward?.success===!1&&memoryReward?.reason&&memoryReward.reason!=="memory_disabled"?{memoryRewardWarning:`memory reward lookup failed: ${memoryReward.reason}`}:{},unifiedFeedbackMd:synthesis.unifiedFeedbackMd},null,2)}});init_zod();init_loader();import*as fs103 from"node:fs";import*as path169 from"node:path";function pushGeneralCouncilAdvisory(session,result){if(!session)return;let body=renderAdvisoryBody(result);if(!body)return;session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.push(`[general_council] (advisory; not blocking)
5652
+ ${body}`)}function renderAdvisoryBody(result){return result.synthesis.trim()}var EXPLICIT_DISAGREEMENT_MARKERS=["i disagree with","i would push back on","contrary to","this contradicts","unlike "],STRONG_RECOMMENDATION_MARKERS=["recommend","best approach","should use","i suggest","the answer is","the right choice is"];function tokenize2(text){return text.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((t)=>t.length>=3)}function termOverlap(a,b){let tokensA=new Set(tokenize2(a)),tokensB=new Set(tokenize2(b));if(tokensA.size===0||tokensB.size===0)return 0;let intersection3=0;for(let t of tokensA)if(tokensB.has(t))intersection3++;let union3=tokensA.size+tokensB.size-intersection3;return union3===0?0:intersection3/union3}function extractMarkerSentence(response,markers){let lower=response.toLowerCase(),sentences=response.split(/(?<=[.!?])\s+/);for(let sentence of sentences){let sentLower=sentence.toLowerCase();if(markers.some((m)=>sentLower.includes(m)))return sentence.trim()}for(let marker of markers){let idx=lower.indexOf(marker);if(idx!==-1){let slice=response.slice(idx,idx+200);return slice.split(/\n/)[0]?.trim()??slice.trim()}}return null}function dedupeByTopic(disagreements){let result=[];for(let d of disagreements){let topicLower=d.topic.toLowerCase(),existing=result.find((r)=>r.topic.toLowerCase().includes(topicLower)||topicLower.includes(r.topic.toLowerCase()));if(existing){for(let pos of d.positions)if(!existing.positions.some((p)=>p.memberId===pos.memberId))existing.positions.push(pos)}else result.push(d)}return result}function detectExplicitMarkers(responses){let out=[];for(let member of responses){let markerSentence=extractMarkerSentence(member.response,EXPLICIT_DISAGREEMENT_MARKERS);if(!markerSentence)continue;let position={memberId:member.memberId,claim:markerSentence,evidence:member.sources[0]?.url??"(no source cited in marker sentence)"};out.push({topic:markerSentence.slice(0,80),positions:[position]})}return out}function extractRecommendation(response){return extractMarkerSentence(response,STRONG_RECOMMENDATION_MARKERS)}function detectClaimDivergence(responses){let recommendations=[];for(let member of responses){let rec=extractRecommendation(member.response);if(!rec)continue;recommendations.push({memberId:member.memberId,text:rec,evidence:member.sources[0]?.url??"(no source cited)"})}let out=[];for(let i=0;i<recommendations.length;i++)for(let j=i+1;j<recommendations.length;j++){let a=recommendations[i],b=recommendations[j];if(!a||!b)continue;let topicOverlap=termOverlap(a.text,b.text);if(topicOverlap>0.4)continue;if(topicOverlap>0&&topicOverlap<0.3){let topic=`${a.text.slice(0,50)} vs ${b.text.slice(0,50)}`;out.push({topic,positions:[{memberId:a.memberId,claim:a.text,evidence:a.evidence},{memberId:b.memberId,claim:b.text,evidence:b.evidence}]})}}return out}function detectDisagreements(responses){if(!Array.isArray(responses)||responses.length<2)return[];let safeResponses=responses.filter((r)=>typeof r?.memberId==="string"&&typeof r?.response==="string"),explicit=detectExplicitMarkers(safeResponses),divergent=detectClaimDivergence(safeResponses),combined=[...explicit,...divergent];return dedupeByTopic(combined).slice(0,10)}var CONSENSUS_WEIGHT_THRESHOLD=0.6;function tokenize3(text){return text.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((t)=>t.length>=4)}function similarity(a,b){let tokensA=new Set(tokenize3(a)),tokensB=new Set(tokenize3(b));if(tokensA.size===0||tokensB.size===0)return 0;let intersection3=0;for(let t of tokensA)if(tokensB.has(t))intersection3++;let union3=tokensA.size+tokensB.size-intersection3;return union3===0?0:intersection3/union3}function extractClaims(response){return response.split(/(?<=[.!?])\s+/).map((s)=>s.trim()).filter((s)=>s.length>=30&&s.length<=400)}function buildConsensusClusters(responses){if(responses.length<2)return[];let totalMembers=responses.length,clusters=[];for(let member of responses){let confidence=clamp013(member.confidence??0.5),claims=extractClaims(member.response??"");for(let claim of claims){let assigned=!1;for(let cluster of clusters)if(similarity(cluster.representative,claim)>=0.5){if(!cluster.memberIds.has(member.memberId))cluster.weightedAgreement+=confidence,cluster.memberIds.add(member.memberId);if(claim.length>cluster.representative.length)cluster.representative=claim;assigned=!0;break}if(!assigned)clusters.push({representative:claim,weightedAgreement:confidence,memberIds:new Set([member.memberId])})}}return clusters.filter((c)=>c.memberIds.size>=2&&c.weightedAgreement/totalMembers>=CONSENSUS_WEIGHT_THRESHOLD).sort((a,b)=>b.weightedAgreement-a.weightedAgreement||b.memberIds.size-a.memberIds.size).map((c)=>c.representative)}function clamp013(n){if(typeof n!=="number"||Number.isNaN(n))return 0;if(n<0)return 0;if(n>1)return 1;return n}function computePersistingDisagreements(disagreements,round2){if(disagreements.length===0)return[];if(round2.length===0)return disagreements;return disagreements.filter((d)=>{let disputants=new Set(d.positions.map((p)=>p.memberId));return!round2.some((r)=>{if(!disputants.has(r.memberId))return!1;if(!r.disagreementTopics?.includes(d.topic))return!1;return/\bconcede\b/i.test(r.response??"")})})}function dedupeSources(round1,round2){let seen=new Set,out=[],allSources=[...round1,...round2].flatMap((r)=>r.sources??[]);for(let src of allSources){if(!src?.url)continue;if(seen.has(src.url))continue;seen.add(src.url),out.push(src)}return out}function renderSynthesisMarkdown(question,mode,roundsCompleted,members,consensusPoints,persistingDisagreements,allSources){let memberLines=members.map((m)=>`- ${m.memberId} (${m.model}, ${m.role})`).join(`
5618
5653
  `),consensusBlock=consensusPoints.length>0?consensusPoints.map((c)=>`- ${c}`).join(`
5619
5654
  `):"_No consensus claims reached the weighted-agreement threshold._",disagreementsBlock=persistingDisagreements.length>0?persistingDisagreements.map((d)=>`- **${d.topic}**
5620
5655
  `+d.positions.map((p)=>` - ${p.memberId}: ${p.claim}`).join(`
@@ -5700,9 +5735,9 @@ ${scanResult.findings.filter((f)=>f.severity==="error").map((f)=>`- ${f.pattern}
5700
5735
 
5701
5736
  [Content follows with threats marked for LLM awareness]
5702
5737
 
5703
- ${scanResult.neutralized}`;return result}catch(error93){if(error93 instanceof DOMException&&(error93.name==="TimeoutError"||error93.name==="AbortError")){if(attempt>=GITINGEST_MAX_RETRIES)throw Error("gitingest request timed out");let backoff=200*2**attempt;await delay(backoff);continue}if(error93 instanceof Error&&error93.message.startsWith("gitingest "))throw error93;if(attempt<GITINGEST_MAX_RETRIES){let backoff=200*2**attempt;await delay(backoff);continue}throw error93}throw Error("gitingest request failed after retries")}var gitingest=createSwarmTool({description:"Fetch a GitHub repository's full content via gitingest.com. Returns summary, directory tree, and file contents optimized for LLM analysis. Use when you need to understand an external repository's structure or code.",args:{url:exports_external.string().describe("GitHub repository URL (e.g., https://github.com/owner/repo)"),maxFileSize:exports_external.number().optional().describe("Maximum file size in bytes to include (default: 50000)"),pattern:exports_external.string().optional().describe("Glob pattern to filter files (e.g., '*.ts' or 'src/**/*.py')"),patternType:exports_external.enum(["include","exclude"]).optional().describe("Whether pattern includes or excludes matching files (default: exclude)")},async execute(args2,_directory,_ctx){return fetchGitingest(args2)}});init_zod();init_create_tool();init_path_security();import*as fs113 from"node:fs";import*as path181 from"node:path";var MAX_FILE_PATH_LENGTH2=500,MAX_SYMBOL_LENGTH=256,MAX_FILE_SIZE_BYTES6=1048576,MAX_CONSUMERS=100,SUPPORTED_EXTENSIONS3=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],BINARY_SIGNATURES2=[0,2303741511,4292411360,1195984440,626017350,1347093252],BINARY_PREFIX_BYTES2=4,BINARY_NULL_CHECK_BYTES2=8192,BINARY_NULL_THRESHOLD2=0.1;function validateFileInput(file3){if(!file3||file3.length===0)return"file is required";if(file3.length>MAX_FILE_PATH_LENGTH2)return`file exceeds maximum length of ${MAX_FILE_PATH_LENGTH2}`;if(containsControlChars(file3))return"file contains control characters";if(containsPathTraversal(file3))return"file contains path traversal";return null}function validateSymbolInput(symbol3){if(symbol3===void 0||symbol3==="")return null;if(symbol3.length>MAX_SYMBOL_LENGTH)return`symbol exceeds maximum length of ${MAX_SYMBOL_LENGTH}`;if(containsControlChars(symbol3))return"symbol contains control characters";if(containsPathTraversal(symbol3))return"symbol contains path traversal";return null}function isBinaryFile3(filePath,buffer){let ext=path181.extname(filePath).toLowerCase();if(ext===".json"||ext===".md"||ext===".txt")return!1;if(buffer.length>=BINARY_PREFIX_BYTES2){let uint323=buffer.subarray(0,BINARY_PREFIX_BYTES2).readUInt32BE(0);for(let sig of BINARY_SIGNATURES2)if(uint323===sig)return!0}let nullCount=0,checkLen=Math.min(buffer.length,BINARY_NULL_CHECK_BYTES2);for(let i=0;i<checkLen;i++)if(buffer[i]===0)nullCount++;return nullCount>checkLen*BINARY_NULL_THRESHOLD2}function parseImports(content,targetFile,targetSymbol){let imports=[],_resolvedTarget;try{_resolvedTarget=path181.resolve(targetFile)}catch{_resolvedTarget=targetFile}let targetBasename=path181.basename(targetFile,path181.extname(targetFile)),targetWithExt=targetFile,targetWithoutExt=targetFile.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,""),normalizedTargetWithExt=path181.normalize(targetWithExt).replace(/\\/g,"/"),normalizedTargetWithoutExt=path181.normalize(targetWithoutExt).replace(/\\/g,"/"),importRegex=/import\s+(?:\{[\s\S]*?\}|(?:\*\s+as\s+\w+)|\w+)\s+from\s+['"`]([^'"`]+)['"`]|import\s+['"`]([^'"`]+)['"`]|require\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g;for(let match=importRegex.exec(content);match!==null;match=importRegex.exec(content)){let modulePath=match[1]||match[2]||match[3];if(!modulePath)continue;let lineNum=(content.substring(0,match.index).match(/\n/g)||[]).length+1,matchedString=match[0],importType="named";if(matchedString.includes("* as"))importType="namespace";else if(/^import\s+\{/.test(matchedString))importType="named";else if(/^import\s+\w+\s+from\s+['"`]/.test(matchedString))importType="default";else if(/^import\s+['"`]/m.test(matchedString))importType="sideeffect";else if(matchedString.includes("require("))importType="require";let _normalizedModule=modulePath.replace(/^\.\//,"").replace(/^\.\.\\/,"../"),isMatch=!1,_targetDir=path181.dirname(targetFile),targetExt=path181.extname(targetFile),targetBasenameNoExt=path181.basename(targetFile,targetExt),moduleNormalized=modulePath.replace(/\\/g,"/").replace(/^\.\//,""),moduleName=modulePath.split(/[/\\]/).pop()||"",moduleNameNoExt=moduleName.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,"");if(modulePath===targetBasename||modulePath===targetBasenameNoExt||modulePath===`./${targetBasename}`||modulePath===`./${targetBasenameNoExt}`||modulePath===`../${targetBasename}`||modulePath===`../${targetBasenameNoExt}`||moduleNormalized===normalizedTargetWithExt||moduleNormalized===normalizedTargetWithoutExt||modulePath.endsWith(`/${targetBasename}`)||modulePath.endsWith(`\\${targetBasename}`)||modulePath.endsWith(`/${targetBasenameNoExt}`)||modulePath.endsWith(`\\${targetBasenameNoExt}`)||moduleNameNoExt===targetBasenameNoExt||`./${moduleNameNoExt}`===targetBasenameNoExt||moduleName===targetBasename||moduleName===targetBasenameNoExt)isMatch=!0;if(isMatch&&targetSymbol)if(importType==="namespace"||importType==="sideeffect")isMatch=!1;else{let namedMatch=matchedString.match(/import\s+\{([\s\S]*?)\}\s+from/);if(namedMatch)isMatch=namedMatch[1].split(",").map((s)=>{let parts=s.trim().split(/\s+as\s+/i),originalName=parts[0].trim(),aliasName=parts[1]?.trim();return{original:originalName,alias:aliasName}}).some(({original,alias})=>original===targetSymbol||alias===targetSymbol);else if(importType==="default"){let defaultMatch=matchedString.match(/^import\s+(\w+)\s+from/m);if(defaultMatch)isMatch=defaultMatch[1]===targetSymbol}}if(isMatch)imports.push({line:lineNum,imports:modulePath,importType,raw:matchedString.trim()})}return imports}var SKIP_DIRECTORIES4=new Set(["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".cache","vendor",".svn",".hg"]);function findSourceFiles2(dir,files=[],stats2={skippedDirs:[],skippedFiles:0,fileErrors:[]}){let entries;try{entries=fs113.readdirSync(dir)}catch(e){return stats2.fileErrors.push({path:dir,reason:e instanceof Error?e.message:"readdir failed"}),files}entries.sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase()));for(let entry of entries){if(SKIP_DIRECTORIES4.has(entry)){stats2.skippedDirs.push(path181.join(dir,entry));continue}let fullPath=path181.join(dir,entry),stat14;try{stat14=fs113.statSync(fullPath)}catch(e){stats2.fileErrors.push({path:fullPath,reason:e instanceof Error?e.message:"stat failed"});continue}if(stat14.isDirectory())findSourceFiles2(fullPath,files,stats2);else if(stat14.isFile()){let ext=path181.extname(fullPath).toLowerCase();if(SUPPORTED_EXTENSIONS3.includes(ext))files.push(fullPath)}}return files}var imports=createSwarmTool({description:"Find all reverse dependencies (consumers) that import from a given file. Returns JSON with file path, line numbers, and import metadata for each consumer. Use this to understand who depends on a module before refactoring.",args:{file:exports_external.string().describe('Source file path to find importers for (e.g., "./src/utils.ts")'),symbol:exports_external.string().optional().describe('Optional specific symbol to filter imports (e.g., "MyClass")')},async execute(args2,_directory,_ctx){let typedArgs=args2,file3,symbol3;try{if(typedArgs&&typeof typedArgs==="object")file3=typedArgs.file,symbol3=typedArgs.symbol}catch{}if(file3===void 0)return JSON.stringify({error:"invalid arguments: file is required",target:"",symbol:void 0,consumers:[],count:0},null,2);let fileValidationError=validateFileInput(file3);if(fileValidationError){let errorResult={error:`invalid file: ${fileValidationError}`,target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}let symbolValidationError=validateSymbolInput(symbol3);if(symbolValidationError){let errorResult={error:`invalid symbol: ${symbolValidationError}`,target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}try{let targetFile=path181.resolve(file3);if(!fs113.existsSync(targetFile)){let errorResult={error:`target file not found: ${file3}`,target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}if(!fs113.statSync(targetFile).isFile())return JSON.stringify({error:"target must be a file, not a directory",target:file3,symbol:symbol3,consumers:[],count:0},null,2);let baseDir=path181.dirname(targetFile),filesToScan=findSourceFiles2(baseDir,[],{skippedDirs:[],skippedFiles:0,fileErrors:[]}).filter((f)=>f!==targetFile).sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase())).slice(0,MAX_CONSUMERS*10),consumers=[],skippedFileCount=0,totalMatchesFound=0;for(let filePath of filesToScan){if(consumers.length>=MAX_CONSUMERS)break;try{if(fs113.statSync(filePath).size>MAX_FILE_SIZE_BYTES6){skippedFileCount++;continue}let buffer=fs113.readFileSync(filePath);if(isBinaryFile3(filePath,buffer)){skippedFileCount++;continue}let content=buffer.toString("utf-8"),fileImports=parseImports(content,targetFile,symbol3);for(let imp of fileImports){if(totalMatchesFound++,consumers.length>=MAX_CONSUMERS)continue;if(consumers.some((c)=>c.file===filePath&&c.line===imp.line))continue;consumers.push({file:filePath,line:imp.line,imports:imp.imports,importType:imp.importType,raw:imp.raw})}}catch(_e){skippedFileCount++}}let result={target:file3,symbol:symbol3,consumers,count:consumers.length},parts=[];if(filesToScan.length>=MAX_CONSUMERS*10)parts.push(`Scanned ${filesToScan.length} files`);if(skippedFileCount>0)parts.push(`${skippedFileCount} skipped (size/binary/errors)`);if(consumers.length>=MAX_CONSUMERS){let hidden=totalMatchesFound-consumers.length;if(hidden>0)parts.push(`Results limited to ${MAX_CONSUMERS} consumers (${hidden} hidden)`);else parts.push(`Results limited to ${MAX_CONSUMERS} consumers`)}if(parts.length>0)result.message=`${parts.join("; ")}.`;return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`scan failed: ${e.message||"internal error"}`:"scan failed: unknown error",target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_validator();init_manager();init_create_tool();import{randomUUID as randomUUID13}from"node:crypto";var VALID_CATEGORIES2=["process","architecture","tooling","security","testing","debugging","performance","integration","todo","other"],knowledge_add=createSwarmTool({description:"Store a new lesson in the knowledge base for future reference. The lesson will be available for retrieval via knowledge_recall.",args:{lesson:exports_external.string().min(15).max(280).describe("The lesson to store (15-280 characters)"),category:exports_external.enum(VALID_CATEGORIES2).describe("Knowledge category for the lesson"),tags:exports_external.array(exports_external.string()).optional().describe("Optional tags for better searchability"),scope:exports_external.string().optional().describe("Scope of the lesson (global or stack:<name>)"),applies_to_agents:exports_external.array(exports_external.string()).optional().describe('Agent roles this lesson applies to (e.g. ["coder"]). REQUIRED (or applies_to_tools) for the lesson to become active.'),applies_to_tools:exports_external.array(exports_external.string()).optional().describe('Tool names this lesson applies to (e.g. ["edit","bash"]). REQUIRED (or applies_to_agents) for the lesson to become active.'),required_actions:exports_external.array(exports_external.string()).optional().describe("Concrete actions to always take. At least one predicate field (required_actions / forbidden_actions / verification_checks) is REQUIRED for the lesson to become active."),forbidden_actions:exports_external.array(exports_external.string()).optional().describe("Concrete actions to never take."),verification_checks:exports_external.array(exports_external.string()).optional().describe("Checks a reviewer can run to verify compliance.")},execute:async(args2,directory)=>{let lessonInput,categoryInput,tagsInput,scopeInput;try{if(args2&&typeof args2==="object"){let obj2=args2;lessonInput=obj2.lesson,categoryInput=obj2.category,tagsInput=obj2.tags,scopeInput=obj2.scope}}catch{}if(typeof lessonInput!=="string")return JSON.stringify({success:!1,error:"lesson must be a string"});let lesson=lessonInput;if(lesson.length<15||lesson.length>280)return JSON.stringify({success:!1,error:"lesson must be between 15 and 280 characters"});if(typeof categoryInput!=="string")return JSON.stringify({success:!1,error:"category must be a string"});let category=categoryInput;if(!VALID_CATEGORIES2.includes(category))return JSON.stringify({success:!1,error:`category must be one of: ${VALID_CATEGORIES2.join(", ")}`});let tags=[];if(tagsInput!==void 0){if(Array.isArray(tagsInput))tags=tagsInput.filter((t)=>typeof t==="string").slice(0,20)}let scope=typeof scopeInput==="string"&&scopeInput.length>0?scopeInput:"global",strArray=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string").slice(0,20):void 0,obj=args2&&typeof args2==="object"?args2:{},actionable={applies_to_agents:strArray(obj.applies_to_agents),applies_to_tools:strArray(obj.applies_to_tools),required_actions:strArray(obj.required_actions),forbidden_actions:strArray(obj.forbidden_actions),verification_checks:strArray(obj.verification_checks)},shape=validateActionableFields(actionable);if(!shape.valid)return JSON.stringify({success:!1,error:`invalid actionability fields: ${shape.errors.join("; ")}`});let project_name="",phase_number=1;try{let plan=await loadPlan(directory);if(project_name=plan?.title??"",typeof plan?.current_phase==="number")phase_number=plan.current_phase}catch{}let entry={id:randomUUID13(),tier:"swarm",lesson,category,tags,scope,confidence:0.5,status:"candidate",confirmed_by:[],project_name,retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:1,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),auto_generated:!1,hive_eligible:!1,...actionable},config3,dedupThreshold=0.6;try{if(config3=loadPluginConfigWithMeta(directory).config,dedupThreshold=config3.knowledge?.dedup_threshold??0.6,config3.knowledge?.validation_enabled!==!1){let validation2=validateLesson(lesson,[],{category,scope,confidence:0.5});if(!validation2.valid)return JSON.stringify({success:!1,error:`Validation failed: ${validation2.reason}`})}}catch{}let actionability=validateActionability(entry);if(!actionability.actionable){try{await appendUnactionable(directory,entry,actionability.reason??"unactionable")}catch{}return JSON.stringify({success:!1,quarantined:!0,id:entry.id,reason:actionability.reason,hint:"Provide at least one of required_actions/forbidden_actions/verification_checks AND at least one of applies_to_agents/applies_to_tools, then retry."})}try{let maxEntries=config3?.knowledge?.swarm_max_entries??100,duplicateResponse;if(await transactKnowledge(resolveSwarmKnowledgePath(directory),(existingEntries)=>{let activeDuplicate=findActiveSwarmNearDuplicate(lesson,existingEntries,dedupThreshold);if(activeDuplicate){let result=reinforceSwarmKnowledgeEntry(activeDuplicate,{phase_number,confirmed_at:new Date().toISOString(),project_name});return duplicateResponse={id:activeDuplicate.id,reinforced:result.reinforced,idempotent:result.reason==="already_confirmed_phase",inactive:!1},result.reinforced?existingEntries:null}let inactiveDuplicate=findNearDuplicate(lesson,existingEntries,dedupThreshold);if(inactiveDuplicate)return duplicateResponse={id:inactiveDuplicate.id,reinforced:!1,idempotent:!1,inactive:!0},null;let updated=[...existingEntries,entry];if(updated.length>maxEntries)return updated.slice(updated.length-maxEntries);return updated}),duplicateResponse){if(duplicateResponse.inactive)return JSON.stringify({success:!1,id:duplicateResponse.id,message:"near-duplicate of inactive existing entry"});return JSON.stringify({success:!0,id:duplicateResponse.id,reinforced:duplicateResponse.reinforced,idempotent:duplicateResponse.idempotent,message:duplicateResponse.reinforced?"near-duplicate reinforced existing entry":"near-duplicate already confirmed for this phase"})}}catch(err){let message=err instanceof Error?err.message:"Unknown error";return JSON.stringify({success:!1,error:message})}return JSON.stringify({success:!0,id:entry.id,category})}});init_zod();init_knowledge_events();init_knowledge_store();init_skill_generator();init_logger();init_create_tool();import*as path182 from"node:path";var MODES2=["archive","quarantine","purge"],TIERS=["swarm","hive"],knowledge_archive=createSwarmTool({description:"Archive (default), quarantine, or purge a swarm or hive knowledge entry by ID, appending an immutable audit tombstone. 'archive'/'quarantine' set the entry status reversibly and hide it from recall; 'purge' hard-deletes and requires allow_purge:true.",args:{id:exports_external.string().min(1).describe("UUID of the knowledge entry"),tier:exports_external.enum(TIERS).optional().describe("Knowledge tier to modify; default 'swarm'"),reason:exports_external.string().min(1).max(500).describe("Why the entry is being archived/quarantined/purged"),evidence:exports_external.string().max(1000).optional().describe('Supporting evidence (e.g. "ignored 8 times, contradicted by tests")'),mode:exports_external.enum(MODES2).optional().describe("Default 'archive'"),allow_purge:exports_external.boolean().optional().describe("Admin flag required when mode='purge'")},execute:async(args2,directory,ctx)=>{let a=args2??{},id=typeof a.id==="string"?a.id:"";if(!id)return JSON.stringify({success:!1,error:"id must be a non-empty string"});let reason=typeof a.reason==="string"?a.reason:"";if(!reason)return JSON.stringify({success:!1,error:"reason is required"});let evidence=typeof a.evidence==="string"?a.evidence:void 0,tier=a.tier==="hive"?"hive":"swarm",mode=a.mode==="quarantine"||a.mode==="purge"?a.mode:"archive";if(mode==="purge"&&a.allow_purge!==!0)return JSON.stringify({success:!1,error:"purge requires allow_purge:true (admin flag)"});let knowledgePath=tier==="hive"?resolveHiveKnowledgePath():resolveSwarmKnowledgePath(directory),found=!1,previousStatus,now=new Date().toISOString(),resultStatus;try{await transactKnowledge(knowledgePath,(entries)=>{let target=entries.find((e)=>e.id===id);if(!target)return null;if(found=!0,previousStatus=target.status,mode==="purge")return warn(`[knowledge_archive] PURGE: hard-deleting ${tier} entry id=${id} actor=${ctx?.agent??"unknown"} reason=${reason}`),resultStatus="purged",entries.filter((e)=>e.id!==id);let newStatus=mode==="quarantine"?"quarantined":"archived";return resultStatus=newStatus,entries.map((e)=>e.id===id?{...e,status:newStatus,updated_at:now}:e)})}catch(err){return JSON.stringify({success:!1,error:err instanceof Error?err.message:"Unknown error"})}if(!found)return JSON.stringify({success:!1,message:"entry not found"});let tombstone={type:"archived",entry_id:id,tier,actor:ctx?.agent??"unknown",reason,mode,evidence,previous_status:previousStatus};if(tier==="hive")await recordHiveKnowledgeEvent(tombstone);else await recordKnowledgeEvent(directory,tombstone);let allArchivedIds=await getArchivedKnowledgeIds(directory);return allArchivedIds.add(id),queueMicrotask(async()=>{try{let affectedSkillDirs=await findSkillsBySourceKnowledgeId(directory,id),staleSkillDirs=await findStaleSkillsBySourceKnowledgeId(directory,allArchivedIds),allSkillDirs=new Set([...affectedSkillDirs,...staleSkillDirs]);if(allSkillDirs.size===0)return;let slugSet=new Set,retiredCount=0,staleCount=0;for(let skillDir of allSkillDirs){let slug=path182.basename(skillDir);if(slugSet.has(slug))continue;if(slugSet.add(slug),(await retireOrMarkStale(directory,skillDir,allArchivedIds)).action==="retire")retiredCount++;else staleCount++}let batchEvent={type:"skill-stale-batch",skillIds:Array.from(slugSet),archivedIds:Array.from(allArchivedIds),retiredCount,staleCount};await recordKnowledgeEvent(directory,batchEvent)}catch(err){warn(`[knowledge-archive] post-archive skill invalidation failed: ${err instanceof Error?err.message:String(err)}`)}}),JSON.stringify({success:!0,id,tier,mode,previous_status:previousStatus,status:resultStatus})}});init_zod();init_config();init_knowledge_store();init_create_tool();import{existsSync as existsSync105}from"node:fs";var DEFAULT_LIMIT=10,MAX_LESSON_LENGTH=200,VALID_CATEGORIES3=["process","architecture","tooling","security","testing","debugging","performance","integration","todo","other"],VALID_STATUSES=["candidate","established","promoted","archived"],DEFAULT_QUERY_STATUSES=new Set(["established","promoted"]),VALID_TIERS=["swarm","hive","all"];function validateTierInput(tier){if(typeof tier!=="string")return null;let normalized=tier.toLowerCase().trim();if(VALID_TIERS.includes(normalized))return normalized;return null}function validateStatusInput(status){if(typeof status!=="string")return null;let normalized=status.toLowerCase().trim();if(VALID_STATUSES.includes(normalized))return normalized;return null}function validateCategoryInput(category){if(typeof category!=="string")return null;let normalized=category.toLowerCase().trim();if(VALID_CATEGORIES3.includes(normalized))return normalized;return null}function validateMinScore(score){if(typeof score==="number"&&!Number.isNaN(score))return Math.max(0,Math.min(1,score));if(typeof score==="string"){let parsed=Number.parseFloat(score);if(!Number.isNaN(parsed))return Math.max(0,Math.min(1,parsed))}return null}function validateLimit(limit){if(typeof limit==="number"&&!Number.isNaN(limit)&&limit>0)return Math.min(limit,100);if(typeof limit==="string"){let parsed=Number.parseInt(limit,10);if(!Number.isNaN(parsed)&&parsed>0)return Math.min(parsed,100)}return DEFAULT_LIMIT}async function readSwarmKnowledge(directory){let swarmPath=resolveSwarmKnowledgePath(directory);if(!existsSync105(swarmPath))return[];return readKnowledge(swarmPath)}async function readHiveKnowledge(){let hivePath=resolveHiveKnowledgePath();if(!existsSync105(hivePath))return[];return readKnowledge(hivePath)}function filterSwarmEntries(entries,filters,suppressedLessons,scopeFilter){return entries.filter((entry)=>{if(filters.status){if(entry.status!==filters.status)return!1}else if(!DEFAULT_QUERY_STATUSES.has(entry.status))return!1;if(filters.category&&entry.category!==filters.category)return!1;if(filters.minScore!==void 0&&entry.confidence<filters.minScore)return!1;if(scopeFilter&&scopeFilter.length>0){let entryScope=entry.scope??"global";if(!scopeFilter.some((pattern)=>entryScope===pattern))return!1}if(suppressedLessons.has(normalize5(entry.lesson)))return!1;return!0})}function filterHiveEntries(entries,filters,suppressedLessons){return entries.filter((entry)=>{if(filters.status){if(entry.status!==filters.status)return!1}else if(!DEFAULT_QUERY_STATUSES.has(entry.status))return!1;if(filters.category&&entry.category!==filters.category)return!1;if(filters.minScore!==void 0&&entry.confidence<filters.minScore)return!1;if(suppressedLessons.has(normalize5(entry.lesson)))return!1;return!0})}function truncateLesson3(lesson,maxLength){if(lesson.length<=maxLength)return lesson;return`${lesson.slice(0,maxLength-3)}...`}function formatSwarmEntry(entry){let lines=[];return lines.push(`[${entry.tier.toUpperCase()}] ${entry.id}`),lines.push(` Lesson: ${truncateLesson3(entry.lesson,MAX_LESSON_LENGTH)}`),lines.push(` Category: ${entry.category}`),lines.push(` Status: ${entry.status}`),lines.push(` Confidence: ${entry.confidence.toFixed(2)}`),lines.push(` Confirmed by: ${entry.confirmed_by.length} phase(s)`),lines.push(` Project: ${entry.project_name}`),lines.join(`
5738
+ ${scanResult.neutralized}`;return result}catch(error93){if(error93 instanceof DOMException&&(error93.name==="TimeoutError"||error93.name==="AbortError")){if(attempt>=GITINGEST_MAX_RETRIES)throw Error("gitingest request timed out");let backoff=200*2**attempt;await delay(backoff);continue}if(error93 instanceof Error&&error93.message.startsWith("gitingest "))throw error93;if(attempt<GITINGEST_MAX_RETRIES){let backoff=200*2**attempt;await delay(backoff);continue}throw error93}throw Error("gitingest request failed after retries")}var gitingest=createSwarmTool({description:"Fetch a GitHub repository's full content via gitingest.com. Returns summary, directory tree, and file contents optimized for LLM analysis. Use when you need to understand an external repository's structure or code.",args:{url:exports_external.string().describe("GitHub repository URL (e.g., https://github.com/owner/repo)"),maxFileSize:exports_external.number().optional().describe("Maximum file size in bytes to include (default: 50000)"),pattern:exports_external.string().optional().describe("Glob pattern to filter files (e.g., '*.ts' or 'src/**/*.py')"),patternType:exports_external.enum(["include","exclude"]).optional().describe("Whether pattern includes or excludes matching files (default: exclude)")},async execute(args2,_directory,_ctx){return fetchGitingest(args2)}});init_zod();init_create_tool();init_path_security();import*as fs113 from"node:fs";import*as path181 from"node:path";var MAX_FILE_PATH_LENGTH2=500,MAX_SYMBOL_LENGTH=256,MAX_FILE_SIZE_BYTES6=1048576,MAX_CONSUMERS=100,SUPPORTED_EXTENSIONS3=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],BINARY_SIGNATURES2=[0,2303741511,4292411360,1195984440,626017350,1347093252],BINARY_PREFIX_BYTES2=4,BINARY_NULL_CHECK_BYTES2=8192,BINARY_NULL_THRESHOLD2=0.1;function validateFileInput(file3){if(!file3||file3.length===0)return"file is required";if(file3.length>MAX_FILE_PATH_LENGTH2)return`file exceeds maximum length of ${MAX_FILE_PATH_LENGTH2}`;if(containsControlChars(file3))return"file contains control characters";if(containsPathTraversal(file3))return"file contains path traversal";return null}function validateSymbolInput(symbol3){if(symbol3===void 0||symbol3==="")return null;if(symbol3.length>MAX_SYMBOL_LENGTH)return`symbol exceeds maximum length of ${MAX_SYMBOL_LENGTH}`;if(containsControlChars(symbol3))return"symbol contains control characters";if(containsPathTraversal(symbol3))return"symbol contains path traversal";return null}function isBinaryFile3(filePath,buffer){let ext=path181.extname(filePath).toLowerCase();if(ext===".json"||ext===".md"||ext===".txt")return!1;if(buffer.length>=BINARY_PREFIX_BYTES2){let uint323=buffer.subarray(0,BINARY_PREFIX_BYTES2).readUInt32BE(0);for(let sig of BINARY_SIGNATURES2)if(uint323===sig)return!0}let nullCount=0,checkLen=Math.min(buffer.length,BINARY_NULL_CHECK_BYTES2);for(let i=0;i<checkLen;i++)if(buffer[i]===0)nullCount++;return nullCount>checkLen*BINARY_NULL_THRESHOLD2}function parseImports(content,targetFile,targetSymbol){let imports=[],_resolvedTarget;try{_resolvedTarget=path181.resolve(targetFile)}catch{_resolvedTarget=targetFile}let targetBasename=path181.basename(targetFile,path181.extname(targetFile)),targetWithExt=targetFile,targetWithoutExt=targetFile.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,""),normalizedTargetWithExt=path181.normalize(targetWithExt).replace(/\\/g,"/"),normalizedTargetWithoutExt=path181.normalize(targetWithoutExt).replace(/\\/g,"/"),importRegex=/import\s+(?:\{[\s\S]*?\}|(?:\*\s+as\s+\w+)|\w+)\s+from\s+['"`]([^'"`]+)['"`]|import\s+['"`]([^'"`]+)['"`]|require\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g;for(let match=importRegex.exec(content);match!==null;match=importRegex.exec(content)){let modulePath=match[1]||match[2]||match[3];if(!modulePath)continue;let lineNum=(content.substring(0,match.index).match(/\n/g)||[]).length+1,matchedString=match[0],importType="named";if(matchedString.includes("* as"))importType="namespace";else if(/^import\s+\{/.test(matchedString))importType="named";else if(/^import\s+\w+\s+from\s+['"`]/.test(matchedString))importType="default";else if(/^import\s+['"`]/m.test(matchedString))importType="sideeffect";else if(matchedString.includes("require("))importType="require";let _normalizedModule=modulePath.replace(/^\.\//,"").replace(/^\.\.\\/,"../"),isMatch=!1,_targetDir=path181.dirname(targetFile),targetExt=path181.extname(targetFile),targetBasenameNoExt=path181.basename(targetFile,targetExt),moduleNormalized=modulePath.replace(/\\/g,"/").replace(/^\.\//,""),moduleName=modulePath.split(/[/\\]/).pop()||"",moduleNameNoExt=moduleName.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,"");if(modulePath===targetBasename||modulePath===targetBasenameNoExt||modulePath===`./${targetBasename}`||modulePath===`./${targetBasenameNoExt}`||modulePath===`../${targetBasename}`||modulePath===`../${targetBasenameNoExt}`||moduleNormalized===normalizedTargetWithExt||moduleNormalized===normalizedTargetWithoutExt||modulePath.endsWith(`/${targetBasename}`)||modulePath.endsWith(`\\${targetBasename}`)||modulePath.endsWith(`/${targetBasenameNoExt}`)||modulePath.endsWith(`\\${targetBasenameNoExt}`)||moduleNameNoExt===targetBasenameNoExt||`./${moduleNameNoExt}`===targetBasenameNoExt||moduleName===targetBasename||moduleName===targetBasenameNoExt)isMatch=!0;if(isMatch&&targetSymbol)if(importType==="namespace"||importType==="sideeffect")isMatch=!1;else{let namedMatch=matchedString.match(/import\s+\{([\s\S]*?)\}\s+from/);if(namedMatch)isMatch=namedMatch[1].split(",").map((s)=>{let parts=s.trim().split(/\s+as\s+/i),originalName=parts[0].trim(),aliasName=parts[1]?.trim();return{original:originalName,alias:aliasName}}).some(({original,alias})=>original===targetSymbol||alias===targetSymbol);else if(importType==="default"){let defaultMatch=matchedString.match(/^import\s+(\w+)\s+from/m);if(defaultMatch)isMatch=defaultMatch[1]===targetSymbol}}if(isMatch)imports.push({line:lineNum,imports:modulePath,importType,raw:matchedString.trim()})}return imports}var SKIP_DIRECTORIES4=new Set(["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".cache","vendor",".svn",".hg"]);function findSourceFiles2(dir,files=[],stats2={skippedDirs:[],skippedFiles:0,fileErrors:[]}){let entries;try{entries=fs113.readdirSync(dir)}catch(e){return stats2.fileErrors.push({path:dir,reason:e instanceof Error?e.message:"readdir failed"}),files}entries.sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase()));for(let entry of entries){if(SKIP_DIRECTORIES4.has(entry)){stats2.skippedDirs.push(path181.join(dir,entry));continue}let fullPath=path181.join(dir,entry),stat14;try{stat14=fs113.statSync(fullPath)}catch(e){stats2.fileErrors.push({path:fullPath,reason:e instanceof Error?e.message:"stat failed"});continue}if(stat14.isDirectory())findSourceFiles2(fullPath,files,stats2);else if(stat14.isFile()){let ext=path181.extname(fullPath).toLowerCase();if(SUPPORTED_EXTENSIONS3.includes(ext))files.push(fullPath)}}return files}var imports=createSwarmTool({description:"Find all reverse dependencies (consumers) that import from a given file. Returns JSON with file path, line numbers, and import metadata for each consumer. Use this to understand who depends on a module before refactoring.",args:{file:exports_external.string().describe('Source file path to find importers for (e.g., "./src/utils.ts")'),symbol:exports_external.string().optional().describe('Optional specific symbol to filter imports (e.g., "MyClass")')},async execute(args2,_directory,_ctx){let typedArgs=args2,file3,symbol3;try{if(typedArgs&&typeof typedArgs==="object")file3=typedArgs.file,symbol3=typedArgs.symbol}catch{}if(file3===void 0)return JSON.stringify({error:"invalid arguments: file is required",target:"",symbol:void 0,consumers:[],count:0},null,2);let fileValidationError=validateFileInput(file3);if(fileValidationError){let errorResult={error:`invalid file: ${fileValidationError}`,target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}let symbolValidationError=validateSymbolInput(symbol3);if(symbolValidationError){let errorResult={error:`invalid symbol: ${symbolValidationError}`,target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}try{let targetFile=path181.resolve(file3);if(!fs113.existsSync(targetFile)){let errorResult={error:`target file not found: ${file3}`,target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}if(!fs113.statSync(targetFile).isFile())return JSON.stringify({error:"target must be a file, not a directory",target:file3,symbol:symbol3,consumers:[],count:0},null,2);let baseDir=path181.dirname(targetFile),filesToScan=findSourceFiles2(baseDir,[],{skippedDirs:[],skippedFiles:0,fileErrors:[]}).filter((f)=>f!==targetFile).sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase())).slice(0,MAX_CONSUMERS*10),consumers=[],skippedFileCount=0,totalMatchesFound=0;for(let filePath of filesToScan){if(consumers.length>=MAX_CONSUMERS)break;try{if(fs113.statSync(filePath).size>MAX_FILE_SIZE_BYTES6){skippedFileCount++;continue}let buffer=fs113.readFileSync(filePath);if(isBinaryFile3(filePath,buffer)){skippedFileCount++;continue}let content=buffer.toString("utf-8"),fileImports=parseImports(content,targetFile,symbol3);for(let imp of fileImports){if(totalMatchesFound++,consumers.length>=MAX_CONSUMERS)continue;if(consumers.some((c)=>c.file===filePath&&c.line===imp.line))continue;consumers.push({file:filePath,line:imp.line,imports:imp.imports,importType:imp.importType,raw:imp.raw})}}catch(_e){skippedFileCount++}}let result={target:file3,symbol:symbol3,consumers,count:consumers.length},parts=[];if(filesToScan.length>=MAX_CONSUMERS*10)parts.push(`Scanned ${filesToScan.length} files`);if(skippedFileCount>0)parts.push(`${skippedFileCount} skipped (size/binary/errors)`);if(consumers.length>=MAX_CONSUMERS){let hidden=totalMatchesFound-consumers.length;if(hidden>0)parts.push(`Results limited to ${MAX_CONSUMERS} consumers (${hidden} hidden)`);else parts.push(`Results limited to ${MAX_CONSUMERS} consumers`)}if(parts.length>0)result.message=`${parts.join("; ")}.`;return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`scan failed: ${e.message||"internal error"}`:"scan failed: unknown error",target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_validator();init_manager();init_create_tool();import{randomUUID as randomUUID13}from"node:crypto";var VALID_CATEGORIES2=["process","architecture","tooling","security","testing","debugging","performance","integration","todo","other"],knowledge_add=createSwarmTool({description:"Store a new lesson in the knowledge base for future reference. The lesson will be available for retrieval via knowledge_recall.",args:{lesson:exports_external.string().min(15).max(280).describe("The lesson to store (15-280 characters)"),category:exports_external.enum(VALID_CATEGORIES2).describe("Knowledge category for the lesson"),tags:exports_external.array(exports_external.string()).optional().describe("Optional tags for better searchability"),scope:exports_external.string().optional().describe("Scope of the lesson (global or stack:<name>)"),applies_to_agents:exports_external.array(exports_external.string()).optional().describe('Agent roles this lesson applies to (e.g. ["coder"]). REQUIRED (or applies_to_tools) for the lesson to become active.'),applies_to_tools:exports_external.array(exports_external.string()).optional().describe('Tool names this lesson applies to (e.g. ["edit","bash"]). REQUIRED (or applies_to_agents) for the lesson to become active.'),required_actions:exports_external.array(exports_external.string()).optional().describe("Concrete actions to always take. At least one predicate field (required_actions / forbidden_actions / verification_checks) is REQUIRED for the lesson to become active."),forbidden_actions:exports_external.array(exports_external.string()).optional().describe("Concrete actions to never take."),verification_checks:exports_external.array(exports_external.string()).optional().describe("Checks a reviewer can run to verify compliance.")},execute:async(args2,directory)=>{let lessonInput,categoryInput,tagsInput,scopeInput;try{if(args2&&typeof args2==="object"){let obj2=args2;lessonInput=obj2.lesson,categoryInput=obj2.category,tagsInput=obj2.tags,scopeInput=obj2.scope}}catch{}if(typeof lessonInput!=="string")return JSON.stringify({success:!1,error:"lesson must be a string"});let lesson=lessonInput;if(lesson.length<15||lesson.length>280)return JSON.stringify({success:!1,error:"lesson must be between 15 and 280 characters"});if(typeof categoryInput!=="string")return JSON.stringify({success:!1,error:"category must be a string"});let category=categoryInput;if(!VALID_CATEGORIES2.includes(category))return JSON.stringify({success:!1,error:`category must be one of: ${VALID_CATEGORIES2.join(", ")}`});let tags=[];if(tagsInput!==void 0){if(Array.isArray(tagsInput))tags=tagsInput.filter((t)=>typeof t==="string").slice(0,20)}let scope=typeof scopeInput==="string"&&scopeInput.length>0?scopeInput:"global",strArray=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string").slice(0,20):void 0,obj=args2&&typeof args2==="object"?args2:{},actionable={applies_to_agents:strArray(obj.applies_to_agents),applies_to_tools:strArray(obj.applies_to_tools),required_actions:strArray(obj.required_actions),forbidden_actions:strArray(obj.forbidden_actions),verification_checks:strArray(obj.verification_checks)},shape=validateActionableFields(actionable);if(!shape.valid)return JSON.stringify({success:!1,error:`invalid actionability fields: ${shape.errors.join("; ")}`});let project_name="",phase_number=1;try{let plan=await loadPlan(directory);if(project_name=plan?.title??"",typeof plan?.current_phase==="number")phase_number=plan.current_phase}catch{}let entry={id:randomUUID13(),tier:"swarm",lesson,category,tags,scope,confidence:0.5,status:"candidate",confirmed_by:[],project_name,retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:1,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),auto_generated:!1,hive_eligible:!1,...actionable},config3,dedupThreshold=0.6;try{if(config3=loadPluginConfigWithMeta(directory).config,dedupThreshold=config3.knowledge?.dedup_threshold??0.6,config3.knowledge?.validation_enabled!==!1){let validation2=validateLesson(lesson,[],{category,scope,confidence:0.5});if(!validation2.valid)return JSON.stringify({success:!1,error:`Validation failed: ${validation2.reason}`})}}catch{}let actionability=validateActionability(entry);if(!actionability.actionable){try{await appendUnactionable(directory,entry,actionability.reason??"unactionable")}catch{}return JSON.stringify({success:!1,quarantined:!0,id:entry.id,reason:actionability.reason,hint:"Provide at least one of required_actions/forbidden_actions/verification_checks AND at least one of applies_to_agents/applies_to_tools, then retry."})}try{let maxEntries=config3?.knowledge?.swarm_max_entries??100,duplicateResponse;if(await transactKnowledge(resolveSwarmKnowledgePath(directory),(existingEntries)=>{let activeDuplicate=findActiveSwarmNearDuplicate(lesson,existingEntries,dedupThreshold);if(activeDuplicate){let result=reinforceSwarmKnowledgeEntry(activeDuplicate,{phase_number,confirmed_at:new Date().toISOString(),project_name});return duplicateResponse={id:activeDuplicate.id,reinforced:result.reinforced,idempotent:result.reason==="already_confirmed_phase",inactive:!1},result.reinforced?existingEntries:null}let inactiveDuplicate=findNearDuplicate(lesson,existingEntries,dedupThreshold);if(inactiveDuplicate)return duplicateResponse={id:inactiveDuplicate.id,reinforced:!1,idempotent:!1,inactive:!0},null;let updated=[...existingEntries,entry];if(updated.length>maxEntries)return updated.slice(updated.length-maxEntries);return updated}),duplicateResponse){if(duplicateResponse.inactive)return JSON.stringify({success:!1,id:duplicateResponse.id,message:"near-duplicate of inactive existing entry"});return JSON.stringify({success:!0,id:duplicateResponse.id,reinforced:duplicateResponse.reinforced,idempotent:duplicateResponse.idempotent,message:duplicateResponse.reinforced?"near-duplicate reinforced existing entry":"near-duplicate already confirmed for this phase"})}}catch(err){let message=err instanceof Error?err.message:"Unknown error";return JSON.stringify({success:!1,error:message})}return JSON.stringify({success:!0,id:entry.id,category})}});init_zod();init_knowledge_events();init_knowledge_store();init_skill_generator();init_logger();init_create_tool();import*as path182 from"node:path";var MODES2=["archive","quarantine","purge"],TIERS=["swarm","hive"],knowledge_archive=createSwarmTool({description:"Archive (default), quarantine, or purge a swarm or hive knowledge entry by ID, appending an immutable audit tombstone. 'archive'/'quarantine' set the entry status reversibly and hide it from recall; 'purge' hard-deletes and requires allow_purge:true.",args:{id:exports_external.string().min(1).describe("UUID of the knowledge entry"),tier:exports_external.enum(TIERS).optional().describe("Knowledge tier to modify; default 'swarm'"),reason:exports_external.string().min(1).max(500).describe("Why the entry is being archived/quarantined/purged"),evidence:exports_external.string().max(1000).optional().describe('Supporting evidence (e.g. "ignored 8 times, contradicted by tests")'),mode:exports_external.enum(MODES2).optional().describe("Default 'archive'"),allow_purge:exports_external.boolean().optional().describe("Admin flag required when mode='purge'")},execute:async(args2,directory,ctx)=>{let a=args2??{},id=typeof a.id==="string"?a.id:"";if(!id)return JSON.stringify({success:!1,error:"id must be a non-empty string"});let reason=typeof a.reason==="string"?a.reason:"";if(!reason)return JSON.stringify({success:!1,error:"reason is required"});let evidence=typeof a.evidence==="string"?a.evidence:void 0,tier=a.tier==="hive"?"hive":"swarm",mode=a.mode==="quarantine"||a.mode==="purge"?a.mode:"archive";if(mode==="purge"&&a.allow_purge!==!0)return JSON.stringify({success:!1,error:"purge requires allow_purge:true (admin flag)"});let knowledgePath=tier==="hive"?resolveHiveKnowledgePath():resolveSwarmKnowledgePath(directory),found=!1,previousStatus,now=new Date().toISOString(),resultStatus;try{await transactKnowledge(knowledgePath,(entries)=>{let target=entries.find((e)=>e.id===id);if(!target)return null;if(found=!0,previousStatus=target.status,mode==="purge")return warn(`[knowledge_archive] PURGE: hard-deleting ${tier} entry id=${id} actor=${ctx?.agent??"unknown"} reason=${reason}`),resultStatus="purged",entries.filter((e)=>e.id!==id);let newStatus=mode==="quarantine"?"quarantined":"archived";return resultStatus=newStatus,entries.map((e)=>e.id===id?{...e,status:newStatus,updated_at:now}:e)})}catch(err){return JSON.stringify({success:!1,error:err instanceof Error?err.message:"Unknown error"})}if(!found)return JSON.stringify({success:!1,message:"entry not found"});let tombstone={type:"archived",entry_id:id,tier,actor:ctx?.agent??"unknown",reason,mode,evidence,previous_status:previousStatus};if(tier==="hive")await recordHiveKnowledgeEvent(tombstone);else await recordKnowledgeEvent(directory,tombstone);let allArchivedIds=await getArchivedKnowledgeIds(directory);return allArchivedIds.add(id),queueMicrotask(async()=>{try{let affectedSkillDirs=await findSkillsBySourceKnowledgeId(directory,id),staleSkillDirs=await findStaleSkillsBySourceKnowledgeId(directory,allArchivedIds),allSkillDirs=new Set([...affectedSkillDirs,...staleSkillDirs]);if(allSkillDirs.size===0)return;let slugSet=new Set,retiredCount=0,staleCount=0;for(let skillDir of allSkillDirs){let slug=path182.basename(skillDir);if(slugSet.has(slug))continue;if(slugSet.add(slug),(await retireOrMarkStale(directory,skillDir,allArchivedIds)).action==="retire")retiredCount++;else staleCount++}let batchEvent={type:"skill-stale-batch",skillIds:Array.from(slugSet),archivedIds:Array.from(allArchivedIds),retiredCount,staleCount};await recordKnowledgeEvent(directory,batchEvent)}catch(err){warn(`[knowledge-archive] post-archive skill invalidation failed: ${err instanceof Error?err.message:String(err)}`)}}),JSON.stringify({success:!0,id,tier,mode,previous_status:previousStatus,status:resultStatus})}});init_zod();init_config();init_knowledge_store();init_create_tool();import{existsSync as existsSync105}from"node:fs";var DEFAULT_LIMIT=10,MAX_LESSON_LENGTH=200,VALID_CATEGORIES3=["process","architecture","tooling","security","testing","debugging","performance","integration","todo","other"],VALID_STATUSES=["candidate","established","promoted","archived"],DEFAULT_QUERY_STATUSES=new Set(["established","promoted"]),VALID_TIERS=["swarm","hive","all"];function validateTierInput(tier){if(typeof tier!=="string")return null;let normalized=tier.toLowerCase().trim();if(VALID_TIERS.includes(normalized))return normalized;return null}function validateStatusInput(status){if(typeof status!=="string")return null;let normalized=status.toLowerCase().trim();if(VALID_STATUSES.includes(normalized))return normalized;return null}function validateCategoryInput(category){if(typeof category!=="string")return null;let normalized=category.toLowerCase().trim();if(VALID_CATEGORIES3.includes(normalized))return normalized;return null}function validateMinScore(score){if(typeof score==="number"&&!Number.isNaN(score))return Math.max(0,Math.min(1,score));if(typeof score==="string"){let parsed=Number.parseFloat(score);if(!Number.isNaN(parsed))return Math.max(0,Math.min(1,parsed))}return null}function validateLimit(limit){if(typeof limit==="number"&&!Number.isNaN(limit)&&limit>0)return Math.min(limit,100);if(typeof limit==="string"){let parsed=Number.parseInt(limit,10);if(!Number.isNaN(parsed)&&parsed>0)return Math.min(parsed,100)}return DEFAULT_LIMIT}async function readSwarmKnowledge(directory){let swarmPath=resolveSwarmKnowledgePath(directory);if(!existsSync105(swarmPath))return[];return readKnowledge(swarmPath)}async function readHiveKnowledge(){let hivePath=resolveHiveKnowledgePath();if(!existsSync105(hivePath))return[];return readKnowledge(hivePath)}function filterSwarmEntries(entries,filters,suppressedLessons,scopeFilter){return entries.filter((entry)=>{if(filters.status){if(entry.status!==filters.status)return!1}else if(!DEFAULT_QUERY_STATUSES.has(entry.status))return!1;if(filters.category&&entry.category!==filters.category)return!1;if(filters.minScore!==void 0&&entry.confidence<filters.minScore)return!1;if(scopeFilter&&scopeFilter.length>0){let entryScope=entry.scope??"global";if(!scopeFilter.some((pattern)=>entryScope===pattern))return!1}if(suppressedLessons.has(normalize5(entry.lesson)))return!1;return!0})}function filterHiveEntries(entries,filters,suppressedLessons,scopeFilter){return entries.filter((entry)=>{if(filters.status){if(entry.status!==filters.status)return!1}else if(!DEFAULT_QUERY_STATUSES.has(entry.status))return!1;if(filters.category&&entry.category!==filters.category)return!1;if(filters.minScore!==void 0&&entry.confidence<filters.minScore)return!1;if(scopeFilter&&scopeFilter.length>0){let entryScope=entry.scope??"global";if(!scopeFilter.some((pattern)=>entryScope===pattern))return!1}if(suppressedLessons.has(normalize5(entry.lesson)))return!1;return!0})}function truncateLesson3(lesson,maxLength){if(lesson.length<=maxLength)return lesson;return`${lesson.slice(0,maxLength-3)}...`}function formatSwarmEntry(entry){let lines=[];return lines.push(`[${entry.tier.toUpperCase()}] ${entry.id}`),lines.push(` Lesson: ${truncateLesson3(entry.lesson,MAX_LESSON_LENGTH)}`),lines.push(` Category: ${entry.category}`),lines.push(` Status: ${entry.status}`),lines.push(` Confidence: ${entry.confidence.toFixed(2)}`),lines.push(` Confirmed by: ${entry.confirmed_by.length} phase(s)`),lines.push(` Project: ${entry.project_name}`),lines.join(`
5704
5739
  `)}function formatHiveEntry(entry){let lines=[];return lines.push(`[${entry.tier.toUpperCase()}] ${entry.id}`),lines.push(` Lesson: ${truncateLesson3(entry.lesson,MAX_LESSON_LENGTH)}`),lines.push(` Category: ${entry.category}`),lines.push(` Status: ${entry.status}`),lines.push(` Confidence: ${entry.confidence.toFixed(2)}`),lines.push(` Encounter Score: ${entry.encounter_score?.toFixed(2)??"N/A"}`),lines.push(` Source Project: ${entry.source_project}`),lines.push(` Confirmed by: ${entry.confirmed_by.length} project(s)`),lines.join(`
5705
- `)}var knowledge_query=createSwarmTool({description:"Performs structured filter-based retrieval of swarm knowledge (project-level) or hive knowledge (cross-project). Returns formatted text for human inspection. This is the tool to use when the user knows the CATEGORY, STATUS, or SCORE they want to filter by. For semantic natural-language search, use `knowledge_recall` instead.",args:{tier:exports_external.string().optional().describe("Knowledge tier to query: 'swarm', 'hive', or 'all' (default: 'all')"),status:exports_external.string().optional().describe("Filter by status: 'candidate', 'established', 'promoted', or 'archived'"),category:exports_external.string().optional().describe("Filter by category: 'process', 'architecture', 'tooling', 'security', 'testing', 'debugging', 'performance', 'integration', 'todo', or 'other'"),min_score:exports_external.number().optional().describe("Minimum confidence score filter (0.0-1.0)"),limit:exports_external.number().optional().describe(`Maximum number of results to return (default: ${DEFAULT_LIMIT}, max: 100)`)},async execute(args2,directory){let tierInput,statusInput,categoryInput,minScoreInput,limitInput;try{if(args2&&typeof args2==="object"){let obj=args2;tierInput=obj.tier,statusInput=obj.status,categoryInput=obj.category,minScoreInput=obj.min_score,limitInput=obj.limit}}catch{}let tier=validateTierInput(tierInput)??"all",status=validateStatusInput(statusInput)??null,category=validateCategoryInput(categoryInput)??null,minScore=validateMinScore(minScoreInput)??null,limit=validateLimit(limitInput),filters={status:status??void 0,category:category??void 0,minScore:minScore??void 0},retractionRecords=await readRetractionRecords(directory),suppressedLessons=new Set(retractionRecords.map((record3)=>record3.normalized_lesson).filter((value)=>typeof value==="string"&&value.length>0)),results=[],scopeFilter;try{let{config:config3}=loadPluginConfigWithMeta(directory);scopeFilter=config3.knowledge?.scope_filter}catch{}if(tier==="swarm"||tier==="all"){let swarmEntries=await readSwarmKnowledge(directory),filtered=filterSwarmEntries(swarmEntries,filters,suppressedLessons,scopeFilter);for(let entry of filtered)results.push({entry,tier:"swarm"})}if(tier==="hive"||tier==="all"){let hiveEntries=await readHiveKnowledge(),filtered=filterHiveEntries(hiveEntries,filters,suppressedLessons);for(let entry of filtered)results.push({entry,tier:"hive"})}let limitedResults=results.slice(0,limit);if(limitedResults.length===0){let tierDesc=tier==="all"?"swarm or hive":tier,filterParts=[];if(status)filterParts.push(`status=${status}`);if(category)filterParts.push(`category=${category}`);if(minScore!==null)filterParts.push(`min_score=${minScore}`);let filterDesc=filterParts.length>0?` with filters: ${filterParts.join(", ")}`:"";return`No knowledge entries found for tier '${tierDesc}'${filterDesc}.`}let outputLines=[];outputLines.push(`=== Knowledge Query Results (${limitedResults.length} of ${results.length} shown) ===`),outputLines.push("");for(let{entry,tier:entryTier}of limitedResults){if(entryTier==="hive")outputLines.push(formatHiveEntry(entry));else outputLines.push(formatSwarmEntry(entry));outputLines.push("")}if(outputLines.push("---"),outputLines.push(`Total matched: ${results.length} | Tier: ${tier} | Limit: ${limit}`),status)outputLines.push(`Status filter: ${status}`);if(category)outputLines.push(`Category filter: ${category}`);if(minScore!==null)outputLines.push(`Min score filter: ${minScore}`);return outputLines.join(`
5740
+ `)}var knowledge_query=createSwarmTool({description:"Performs structured filter-based retrieval of swarm knowledge (project-level) or hive knowledge (cross-project). Returns formatted text for human inspection. This is the tool to use when the user knows the CATEGORY, STATUS, or SCORE they want to filter by. For semantic natural-language search, use `knowledge_recall` instead.",args:{tier:exports_external.string().optional().describe("Knowledge tier to query: 'swarm', 'hive', or 'all' (default: 'all')"),status:exports_external.string().optional().describe("Filter by status: 'candidate', 'established', 'promoted', or 'archived'"),category:exports_external.string().optional().describe("Filter by category: 'process', 'architecture', 'tooling', 'security', 'testing', 'debugging', 'performance', 'integration', 'todo', or 'other'"),min_score:exports_external.number().optional().describe("Minimum confidence score filter (0.0-1.0)"),limit:exports_external.number().optional().describe(`Maximum number of results to return (default: ${DEFAULT_LIMIT}, max: 100)`)},async execute(args2,directory){let tierInput,statusInput,categoryInput,minScoreInput,limitInput;try{if(args2&&typeof args2==="object"){let obj=args2;tierInput=obj.tier,statusInput=obj.status,categoryInput=obj.category,minScoreInput=obj.min_score,limitInput=obj.limit}}catch{}let tier=validateTierInput(tierInput)??"all",status=validateStatusInput(statusInput)??null,category=validateCategoryInput(categoryInput)??null,minScore=validateMinScore(minScoreInput)??null,limit=validateLimit(limitInput),filters={status:status??void 0,category:category??void 0,minScore:minScore??void 0},retractionRecords=await readRetractionRecords(directory),suppressedLessons=new Set(retractionRecords.map((record3)=>record3.normalized_lesson).filter((value)=>typeof value==="string"&&value.length>0)),results=[],scopeFilter;try{let{config:config3}=loadPluginConfigWithMeta(directory);scopeFilter=config3.knowledge?.scope_filter}catch{}if(tier==="swarm"||tier==="all"){let swarmEntries=await readSwarmKnowledge(directory),filtered=filterSwarmEntries(swarmEntries,filters,suppressedLessons,scopeFilter);for(let entry of filtered)results.push({entry,tier:"swarm"})}if(tier==="hive"||tier==="all"){let hiveEntries=await readHiveKnowledge(),filtered=filterHiveEntries(hiveEntries,filters,suppressedLessons,scopeFilter);for(let entry of filtered)results.push({entry,tier:"hive"})}let limitedResults=results.slice(0,limit);if(limitedResults.length===0){let tierDesc=tier==="all"?"swarm or hive":tier,filterParts=[];if(status)filterParts.push(`status=${status}`);if(category)filterParts.push(`category=${category}`);if(minScore!==null)filterParts.push(`min_score=${minScore}`);let filterDesc=filterParts.length>0?` with filters: ${filterParts.join(", ")}`:"";return`No knowledge entries found for tier '${tierDesc}'${filterDesc}.`}let outputLines=[];outputLines.push(`=== Knowledge Query Results (${limitedResults.length} of ${results.length} shown) ===`),outputLines.push("");for(let{entry,tier:entryTier}of limitedResults){if(entryTier==="hive")outputLines.push(formatHiveEntry(entry));else outputLines.push(formatSwarmEntry(entry));outputLines.push("")}if(outputLines.push("---"),outputLines.push(`Total matched: ${results.length} | Tier: ${tier} | Limit: ${limit}`),status)outputLines.push(`Status filter: ${status}`);if(category)outputLines.push(`Category filter: ${category}`);if(minScore!==null)outputLines.push(`Min score filter: ${minScore}`);return outputLines.join(`
5706
5741
  `)}});init_knowledge_recall();init_zod();init_knowledge_events();init_create_tool();var IGNORE_REASONS=["not_relevant","stale","superseded","unsafe","too_generic","already_satisfied","other"],PROPOSED_ACTIONS=["archive","revise","quarantine"],VERIFIED_BY=["reviewer","test_engineer","architect"],appliedItem=exports_external.object({id:exports_external.string().min(1),how:exports_external.string().min(1).max(500),evidence_files:exports_external.array(exports_external.string()).optional(),evidence_commands:exports_external.array(exports_external.string()).optional(),verified_by:exports_external.enum(VERIFIED_BY).optional()}),ignoredItem=exports_external.object({id:exports_external.string().min(1),reason:exports_external.enum(IGNORE_REASONS),note:exports_external.string().max(500).optional()}),contradictedItem=exports_external.object({id:exports_external.string().min(1),evidence:exports_external.string().min(1).max(500),proposed_action:exports_external.enum(PROPOSED_ACTIONS)}),newLessonItem=exports_external.object({lesson:exports_external.string().min(15).max(280),category:exports_external.string().min(1),evidence:exports_external.string().max(500).optional(),applies_to_agents:exports_external.array(exports_external.string()).optional(),applies_to_tools:exports_external.array(exports_external.string()).optional(),required_actions:exports_external.array(exports_external.string()).optional(),forbidden_actions:exports_external.array(exports_external.string()).optional(),verification_checks:exports_external.array(exports_external.string()).optional()}),knowledge_receipt=createSwarmTool({description:"File a receipt for knowledge surfaced by a retrieval (by trace_id): which entries were applied (with evidence), ignored (with reason), or contradicted (with proposed remediation), plus any new lessons. Each item is recorded as an immutable knowledge event. Set no_relevant_knowledge:true when a retrieval surfaced nothing useful.",args:{trace_id:exports_external.string().min(1).describe("trace_id from a prior knowledge_recall/injection, or 'none' if no retrieval occurred"),task_id:exports_external.string().optional(),phase:exports_external.string().optional(),applied:exports_external.array(appliedItem).optional(),ignored:exports_external.array(ignoredItem).optional(),contradicted:exports_external.array(contradictedItem).optional(),new_lessons:exports_external.array(newLessonItem).optional(),no_relevant_knowledge:exports_external.boolean().optional()},execute:async(args2,directory,ctx)=>{let a=args2??{},traceId=typeof a.trace_id==="string"?a.trace_id:"";if(!traceId)return JSON.stringify({recorded:!1,error:'trace_id is required (use "none" if no retrieval occurred)'});let taskId=typeof a.task_id==="string"?a.task_id:void 0,phase=typeof a.phase==="string"?a.phase:void 0,applied=Array.isArray(a.applied)?a.applied:[],ignored=Array.isArray(a.ignored)?a.ignored:[],contradicted=Array.isArray(a.contradicted)?a.contradicted:[],newLessons=Array.isArray(a.new_lessons)?a.new_lessons:[],noRelevant=a.no_relevant_knowledge===!0;if(applied.length===0&&ignored.length===0&&contradicted.length===0&&newLessons.length===0&&!noRelevant)return JSON.stringify({recorded:!1,error:"empty receipt: provide at least one applied/ignored/contradicted entry, a new lesson, or set no_relevant_knowledge:true"});let sessionId=ctx?.sessionID??"unknown",agent=ctx?.agent??"unknown",base={trace_id:traceId,session_id:sessionId,phase,task_id:taskId,agent},recordedEventIds=[],emit2=async(event)=>{let written=await recordKnowledgeEvent(directory,event);if(written&&written.event_id!==void 0)recordedEventIds.push(written.event_id)};for(let item of applied)await emit2({type:"applied",...base,knowledge_id:item.id,reason:item.how,evidence:{files:item.evidence_files,commands:item.evidence_commands,summary:item.verified_by?`verified_by=${item.verified_by}`:void 0}});for(let item of ignored)await emit2({type:"ignored",...base,knowledge_id:item.id,reason:item.note?`${item.reason}: ${item.note}`:item.reason});for(let item of contradicted)await emit2({type:"contradicted",...base,knowledge_id:item.id,reason:`${item.proposed_action}: ${item.evidence}`,evidence:{summary:item.evidence}});let newLessonResults=[];for(let item of newLessons){let raw=await knowledge_add.execute({lesson:item.lesson,category:item.category,applies_to_agents:item.applies_to_agents,applies_to_tools:item.applies_to_tools,required_actions:item.required_actions,forbidden_actions:item.forbidden_actions,verification_checks:item.verification_checks},ctx);try{let output=typeof raw==="string"?raw:typeof raw==="object"&&raw!==null&&("output"in raw)&&typeof raw.output==="string"?raw.output:"";newLessonResults.push(JSON.parse(output))}catch{newLessonResults.push({success:!1})}}return JSON.stringify({recorded:!0,trace_id:traceId,applied:applied.length,ignored:ignored.length,contradicted:contradicted.length,new_lessons:newLessonResults,no_relevant_knowledge:noRelevant,event_ids:recordedEventIds})}});init_zod();init_knowledge_events();init_knowledge_store();init_skill_generator();init_logger();init_create_tool();import*as path183 from"node:path";var knowledge_remove=createSwarmTool({description:"Delete an outdated swarm knowledge entry by ID (swarm tier only — does not affect hive). Promoted entries cannot be deleted. Double-deletion is idempotent — removing a non-existent entry returns a clear message without error.",args:{id:exports_external.string().min(1).describe("UUID of the knowledge entry to remove")},execute:async(args2,directory)=>{let idInput;try{if(args2&&typeof args2==="object")idInput=args2.id}catch{}if(typeof idInput!=="string"||idInput.length<1)return JSON.stringify({success:!1,error:"id must be a non-empty string"});let id=idInput,swarmPath=resolveSwarmKnowledgePath(directory),found=!1,remaining=0,isPromoted=!1;try{await transactKnowledge(swarmPath,(entries)=>{let entryToDelete=entries.find((entry)=>entry.id===id);if(!entryToDelete)return null;if(entryToDelete.status==="promoted")return isPromoted=!0,null;let filtered=entries.filter((entry)=>entry.id!==id);if(filtered.length===entries.length)return null;return found=!0,remaining=filtered.length,filtered})}catch(err){let message=err instanceof Error?err.message:"Unknown error";return JSON.stringify({success:!1,error:message})}if(isPromoted)return JSON.stringify({success:!1,message:"cannot delete promoted entry — this entry has been promoted to cross-project consensus"});if(!found)return JSON.stringify({success:!1,message:"entry not found"});let allArchivedIds=await getArchivedKnowledgeIds(directory);return allArchivedIds.add(id),queueMicrotask(async()=>{try{let affectedSkillDirs=await findSkillsBySourceKnowledgeId(directory,id),staleSkillDirs=await findStaleSkillsBySourceKnowledgeId(directory,allArchivedIds),allSkillDirs=new Set([...affectedSkillDirs,...staleSkillDirs]);if(allSkillDirs.size===0)return;let slugSet=new Set,retiredCount=0,staleCount=0;for(let skillDir of allSkillDirs){let slug=path183.basename(skillDir);if(slugSet.has(slug))continue;if(slugSet.add(slug),(await retireOrMarkStale(directory,skillDir,allArchivedIds)).action==="retire")retiredCount++;else staleCount++}let batchEvent={type:"skill-stale-batch",skillIds:Array.from(slugSet),archivedIds:Array.from(allArchivedIds),retiredCount,staleCount};await recordKnowledgeEvent(directory,batchEvent)}catch(err){warn(`[knowledge-remove] post-purge skill invalidation failed: ${err instanceof Error?err.message:String(err)}`)}}),JSON.stringify({success:!0,removed:1,remaining})}});init_zod();init_file_locks();init_create_tool();async function executeLeanTurboAcquireLocks(args2){let{directory,laneId,files,agent,taskId,sessionID}=args2;try{let result=await acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID);if(result.acquired)return{success:!0,locks:result.locks};else return{success:!1,conflicts:result.conflicts}}catch(error93){return{success:!1,errors:[error93 instanceof Error?error93.message:String(error93)]}}}var lean_turbo_acquire_locks=createSwarmTool({description:"Acquire file locks for all files in a lane (all-or-nothing). Wraps acquireLaneLocks from src/parallel/file-locks. If any file is already locked, releases all previously acquired locks.",args:{directory:exports_external.string().describe("Project root directory"),laneId:exports_external.string().describe('Unique lane identifier (e.g., "lane-1")'),files:exports_external.array(exports_external.string().min(1)).min(1).describe("Array of file paths to lock"),agent:exports_external.string().describe("Agent name acquiring the locks"),taskId:exports_external.string().describe('Task ID (e.g., "4.1")'),sessionID:exports_external.string().describe("Session ID for the Lean Turbo run")},execute:async(args2,_directory)=>{return JSON.stringify(await executeLeanTurboAcquireLocks({...args2,directory:_directory}),null,2)}});init_zod();init_constants();import*as fs114 from"node:fs";import*as path184 from"node:path";init_create_tool();function readPlanJson2(directory){let planPath=path184.join(directory,".swarm","plan.json");if(!fs114.existsSync(planPath))return null;try{return JSON.parse(fs114.readFileSync(planPath,"utf-8"))}catch{return null}}async function executeLeanTurboPlanLanes(args2){let{directory,phase,scopes}=args2,plan=readPlanJson2(directory);if(!plan)return{success:!1,errors:["plan.json not found in .swarm directory"]};let defaultConfig={...DEFAULT_LEAN_TURBO_CONFIG};try{let lanePlan=planLeanTurboLanes(directory,phase,plan,defaultConfig,scopes);return{success:!0,plan:lanePlan,lanes:lanePlan.lanes,degradedTasks:lanePlan.degradedTasks,serializedTasks:lanePlan.serializedTasks}}catch(error93){return{success:!1,errors:[error93 instanceof Error?error93.message:String(error93)]}}}var lean_turbo_plan_lanes=createSwarmTool({description:"Partition phase tasks into parallel lanes based on file-scope conflicts. Wraps planLeanTurboLanes for Lean Turbo lane planning.",args:{directory:exports_external.string().describe("Project root directory where .swarm/plan.json is located"),phase:exports_external.number().int().positive().describe("Phase number to plan"),scopes:exports_external.record(exports_external.string(),exports_external.array(exports_external.string())).optional().describe("Optional pre-loaded scopes map (taskId -> file paths)")},execute:async(args2,_directory)=>{return JSON.stringify(await executeLeanTurboPlanLanes({...args2,directory:_directory}),null,2)}});init_zod();init_config();init_create_tool();async function executeLeanTurboReview(args2){let{directory,phase,sessionID}=args2,requireDiffSummary=!0;try{let{config:config3}=loadPluginConfigWithMeta(directory);if(config3?.turbo?.lean?.integrated_diff_required!==void 0)requireDiffSummary=config3.turbo.lean.integrated_diff_required}catch{}try{let result=await dispatchPhaseReviewer(directory,phase,sessionID,{requireDiffSummary});return{success:!0,verdict:result.verdict,reason:result.reason,evidencePath:result.evidencePath}}catch(error93){return{success:!1,errors:[error93 instanceof Error?error93.message:String(error93)]}}}var lean_turbo_review=createSwarmTool({description:"Dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase. Wraps dispatchPhaseReviewer from src/turbo/lean/reviewer. Returns verdict (APPROVED/NEEDS_REVISION/REJECTED), reason, and evidence path.",args:{directory:exports_external.string().describe("Project root directory"),phase:exports_external.number().int().positive().describe("Phase number being reviewed"),sessionID:exports_external.string().describe("Lean Turbo session ID")},execute:async(args2,_directory)=>{return JSON.stringify(await executeLeanTurboReview({...args2,directory:_directory}),null,2)}});init_zod();init_config();init_state2();init_create_tool();var _internals114={LeanTurboRunner,loadPluginConfigWithMeta};async function executeLeanTurboRunPhase(args2){let{directory,phase,sessionID}=args2,runResult=null,runError=null,runner=null;try{let{config:config3}=_internals114.loadPluginConfigWithMeta(directory),leanConfig=config3.turbo?.strategy==="lean"?config3.turbo.lean:void 0;runner=new _internals114.LeanTurboRunner({directory,sessionID,opencodeClient:swarmState.opencodeClient??null,generatedAgentNames:swarmState.generatedAgentNames,leanConfig}),runResult=await runner.runPhase(phase)}catch(error93){runError=error93 instanceof Error?error93:Error(String(error93))}if(runner)try{if(runError||!runResult?.ok)await runner.cleanupAfterFailure();else await runner.cleanupAfterSuccess()}catch(cleanupError){console.error("[lean_turbo_run_phase] Cleanup failed:",cleanupError)}if(runError)return{success:!1,errors:[runError.message]};return{success:runResult.ok,lanes:runResult.lanes,degradedTasks:runResult.degradedTasks,serializedTasks:runResult.serializedTasks,mergeBackFailures:runResult.mergeBackFailures,reason:runResult.reason}}var lean_turbo_run_phase=createSwarmTool({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.",args:{directory:exports_external.string().describe("Project root directory"),phase:exports_external.number().int().positive().describe("Phase number to execute"),sessionID:exports_external.string().describe("Lean Turbo session ID")},execute:async(args2,_directory)=>{let{phase,sessionID}=args2;return JSON.stringify(await executeLeanTurboRunPhase({phase,sessionID,directory:_directory}),null,2)}});init_zod();init_state4();init_create_tool();async function executeLeanTurboRunnerStatus(args2){let{directory,sessionID}=args2;try{let runState=loadLeanTurboRunState(directory,sessionID);if(!runState)return{success:!1,errors:["No Lean Turbo run state found for this session"]};return{success:!0,status:runState.status,phase:runState.phase,lanes:runState.lanes,degradedTasks:runState.degradedTasks,maxParallelCoders:runState.maxParallelCoders,sessionID:runState.sessionID,strategy:runState.strategy}}catch(error93){return{success:!1,errors:[error93 instanceof Error?error93.message:String(error93)]}}}var lean_turbo_runner_status=createSwarmTool({description:"Read Lean Turbo run state from .swarm/turbo-state.json. Returns status, phase, lanes, degraded tasks, and max parallel coders.",args:{directory:exports_external.string().describe("Project root directory where .swarm/turbo-state.json is located"),sessionID:exports_external.string().describe("Session ID for the Lean Turbo run")},execute:async(args2,_directory)=>{return JSON.stringify(await executeLeanTurboRunnerStatus({...args2,directory:_directory}),null,2)}});init_zod();init_constants();init_state4();init_create_tool();async function executeLeanTurboStatus(args2){let{directory,sessionID}=args2;try{let runState=loadLeanTurboRunState(directory,sessionID),defaultConfig={max_parallel_coders:DEFAULT_LEAN_TURBO_CONFIG.max_parallel_coders,require_declared_scope:DEFAULT_LEAN_TURBO_CONFIG.require_declared_scope,degrade_on_risk:DEFAULT_LEAN_TURBO_CONFIG.degrade_on_risk,conflict_policy:DEFAULT_LEAN_TURBO_CONFIG.conflict_policy};if(runState)return{success:!0,strategy:"lean",leanActive:runState.status==="running",config:defaultConfig,status:runState.status,phase:runState.phase,lanes:runState.lanes.length,degradedTasks:runState.degradedTasks.length};return{success:!0,strategy:"lean",leanActive:!1,config:defaultConfig,status:"idle",phase:void 0,lanes:0,degradedTasks:0}}catch(error93){return{success:!1,errors:[error93 instanceof Error?error93.message:String(error93)]}}}var lean_turbo_status=createSwarmTool({description:"Returns Lean Turbo configuration and active status for the current session. Shows whether lean turbo is active, current status, and configuration values.",args:{directory:exports_external.string().describe("Project root directory"),sessionID:exports_external.string().describe("Session ID to check status for")},execute:async(args2,_directory)=>{return JSON.stringify(await executeLeanTurboStatus({...args2,directory:_directory}),null,2)}});init_lint();init_spec_schema();init_effective_spec();init_create_tool();var OBLIGATION_KEYWORDS=["MUST","SHALL","SHOULD","MAY"],FR_ID_PATTERN2=/\bFR-(?!000)\d{3}\b/,OBLIGATION_PATTERN2=/\b(MUST|SHALL|SHOULD|MAY)\b/g,SCENARIO_PATTERN=/^##\s+Scenario\s*:/gm,GIVEN_WHEN_THEN_PATTERN=/\b(Given|When|Then|And|But)[:\s]/gi;function countRequirementsByObligation(content){let counts={MUST:0,SHALL:0,SHOULD:0,MAY:0},lines=content.replace(/```[\s\S]*?```/g,"").replace(/`[^`]*`/g,"").split(`
5707
5742
  `);for(let line of lines){if(!line.match(FR_ID_PATTERN2))continue;let matches=line.matchAll(OBLIGATION_PATTERN2);for(let match of matches){let keyword=match[1];if(OBLIGATION_KEYWORDS.includes(keyword))counts[keyword]++}}return counts}function countScenarios(content){let scenarioCount=0,scenarioMatches=content.match(SCENARIO_PATTERN);if(scenarioMatches)scenarioCount+=scenarioMatches.length;let givenWhenThenMatches=content.match(GIVEN_WHEN_THEN_PATTERN);if(givenWhenThenMatches&&givenWhenThenMatches.length>0){if(scenarioCount===0)scenarioCount=(content.match(/\bWhen\s+/gi)||[]).length}return scenarioCount}var lint_spec=createSwarmTool({description:"Reads .swarm/spec.md, lints markdown spec for FR-IDs, obligations, and structure, and returns requirement counts by obligation level, scenario count, and any errors or warnings found.",args:{},async execute(_args,directory){let errors5=[],warnings=[],spec=readEffectiveSpecSync(directory);if(!spec)return JSON.stringify({valid:!1,specMtime:null,requirementCount:{MUST:0,SHALL:0,SHOULD:0,MAY:0,total:0},scenarioCount:0,errors:["spec.md not found and no valid OpenSpec-compatible projection available"],warnings:[]},null,2);let{mtime:specMtime,content}=spec,contentValidation=validateSpecContent(content);if(!contentValidation.valid)for(let issue3 of contentValidation.issues)errors5.push(`Line ${issue3.line}: ${issue3.message}`);let obligationCounts=countRequirementsByObligation(content),totalRequirements=Object.values(obligationCounts).reduce((sum,count)=>sum+count,0),scenarioCount=countScenarios(content),result={valid:errors5.length===0,specMtime,requirementCount:{...obligationCounts,total:totalRequirements},scenarioCount,errors:errors5,warnings:[...warnings,...spec.warnings]};return JSON.stringify(result,null,2)}});init_zod();import*as fs115 from"node:fs";import*as path186 from"node:path";import{spawnSync as spawnSync13}from"node:child_process";import{unlinkSync as unlinkSync28,writeFileSync as writeFileSync30}from"node:fs";import*as path185 from"node:path";function isStaticallyEquivalent(originalCode,mutatedCode){let stripCode=(code)=>{let inMultiLineComment=!1,afterMultiLine=[];for(let line of code.split(`
5708
5743
  `))if(!inMultiLineComment){let openIndex=line.indexOf("/*");if(openIndex!==-1){let closeIndex=line.indexOf("*/",openIndex+2);if(closeIndex!==-1)afterMultiLine.push(line.substring(0,openIndex)+line.substring(closeIndex+2));else afterMultiLine.push(line.substring(0,openIndex)),inMultiLineComment=!0}else afterMultiLine.push(line)}else{let closeIndex=line.indexOf("*/");if(closeIndex!==-1)afterMultiLine.push(line.substring(closeIndex+2)),inMultiLineComment=!1}let afterSingleLine=[];for(let line of afterMultiLine){let inString=null,commentStart=-1;for(let i=0;i<line.length;i++){let ch=line[i];if(inString){if(ch==="\\"){i++;continue}if(ch===inString)inString=null}else if(ch==="'"||ch==='"'||ch==="`")inString=ch;else if(ch==="/"&&i+1<line.length&&line[i+1]==="/"){commentStart=i;break}}let processed=commentStart>=0?line.substring(0,commentStart):line;processed=processed.trimEnd(),afterSingleLine.push(processed)}return afterSingleLine.filter((line)=>{let trimmedLower=line.toLowerCase().trim();if(/^console\.(log|debug)\s*(\(|$)/.test(trimmedLower))return!1;if(trimmedLower==="debugger;")return!1;return!0}).filter((line)=>line.trim()!=="").join(`
@@ -5734,7 +5769,7 @@ Regenerated on: save_plan and phase_complete.
5734
5769
  Findings: ${details.join("; ")}`:""},asBlocked=(reason,message)=>({blocked:!0,reason,message,agentsDispatched,agentsMissing:[],warnings:[]}),asEntry=null;try{asEntry=readSupervisorReportRaw(dir,phase)}catch(asError){return asBlocked("ARCH_SUPERVISOR_ERROR",`Phase ${phase} cannot be completed: architecture supervisor gate encountered an error. Error: ${String(asError)}`)}if(!asEntry)return asBlocked("ARCH_SUPERVISOR_REQUIRED",`Phase ${phase} cannot be completed: architectural_supervision gate mode is enabled and no architecture supervisor evidence was found at .swarm/evidence/${phase}/architecture-supervisor.json. Dispatch critic_architecture_supervisor with the phase + agent summaries, then call write_architecture_supervisor_evidence.`);let now=new Date,asTime=asEntry.timestamp?new Date(asEntry.timestamp):null;if(!asTime||Number.isNaN(asTime.getTime()))return asBlocked("ARCH_SUPERVISOR_INVALID_TIMESTAMP",`Phase ${phase} cannot be completed: architecture supervisor evidence has a missing or invalid timestamp.`);if(asTime.getTime()>now.getTime())return asBlocked("ARCH_SUPERVISOR_FUTURE_TIMESTAMP",`Phase ${phase} cannot be completed: architecture supervisor evidence timestamp is in the future.`);if(now.getTime()-asTime.getTime()>86400000)return asBlocked("ARCH_SUPERVISOR_STALE_EVIDENCE",`Phase ${phase} cannot be completed: architecture supervisor evidence is older than 24 hours. Re-run the supervisor for fresh review.`);if(typeof asEntry.phase_number!=="number"||asEntry.phase_number!==phase)return asBlocked("ARCH_SUPERVISOR_PHASE_MISMATCH",`Phase ${phase} cannot be completed: architecture supervisor evidence is for phase ${String(asEntry.phase_number)}, not phase ${phase}.`);let gateWarnings=[];if(asConfig?.provenance_verify===!0){let provenance=asEntry.provenance;if(!provenance||!provenance.agent_name&&!provenance.session_id)return asBlocked("ARCH_SUPERVISOR_MISSING_PROVENANCE",`Phase ${phase} cannot be completed: architecture supervisor evidence lacks provenance (agent_name or session_id). Evidence provenance verification is enabled.`)}else if(!asEntry.provenance||!asEntry.provenance.agent_name&&!asEntry.provenance.session_id){let msg=`Architecture supervisor evidence lacks provenance for phase ${phase}. Enable 'provenance_verify' in architectural_supervision config to enforce provenance verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}let asVerdict=asEntry.verdict;if(asVerdict==="REJECT")return asBlocked("ARCH_SUPERVISOR_REJECTED",`Phase ${phase} cannot be completed: architecture supervisor returned verdict 'REJECT'. Address the system-level findings before completing the phase.${summarizeFindings(asEntry.findings)}`);if(asVerdict==="CONCERNS"){if(asConfig?.allow_concerns_to_complete===!1)return asBlocked("ARCH_SUPERVISOR_CONCERNS",`Phase ${phase} cannot be completed: architecture supervisor returned verdict 'CONCERNS' and allow_concerns_to_complete is disabled.${summarizeFindings(asEntry.findings)}`);safeWarn(`[phase_complete] Architecture supervisor returned CONCERNS for phase ${phase} — proceeding (allow_concerns_to_complete is enabled)`,void 0)}else if(asVerdict!=="APPROVE")return asBlocked("ARCH_SUPERVISOR_INVALID",`Phase ${phase} cannot be completed: architecture supervisor evidence contains unrecognized verdict '${String(asVerdict)}'. Expected one of: APPROVE, CONCERNS, REJECT.`);return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}async function runCompletionVerifyGate(ctx){let{phase,dir,agentsDispatched,safeWarn}=ctx;try{let completionResultRaw=await executeCompletionVerify({phase},dir),completionResult=JSON.parse(completionResultRaw);if(completionResult.status==="blocked")return{blocked:!0,reason:"COMPLETION_INCOMPLETE",message:`Phase ${phase} cannot be completed: ${completionResult.reason}`,agentsDispatched,agentsMissing:[],warnings:completionResult.blockedTasks?[`Blocked tasks: ${completionResult.blockedTasks.map((t)=>t.task_id).join(", ")}`]:[]};return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}catch(completionError){return safeWarn("[phase_complete] Completion verify error (non-blocking):",completionError),{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}}init_effective_spec();import*as fs120 from"node:fs";import*as path193 from"node:path";init_qa_gate_profile();init_ledger();init_manager();init_utils3();init_state2();async function resolveGatePreamble(dir,sessionID){let plan=await loadPlan(dir);if(!plan)return{resolved:!1};let planId=derivePlanId(plan),planHash=computePlanHash(plan),profile=getProfile(dir,planId),overrides=(sessionID?swarmState.agentSessions.get(sessionID):void 0)?.qaGateSessionOverrides??{};if(!profile){let hasOverrides=Object.keys(overrides).length>0;return{resolved:hasOverrides,plan,planId,planHash,effectiveGates:hasOverrides?{...DEFAULT_QA_GATES,...overrides}:void 0}}let effective=getEffectiveGates(profile,overrides);return{resolved:!0,plan,planId,planHash,effectiveGates:effective}}async function runDriftGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,gateWarnings=[],driftCheckEnabled=!0,driftHasEffectiveSpec=!1;try{driftHasEffectiveSpec=readEffectiveSpecSync(dir)!==null;let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved)driftCheckEnabled=preamble.effectiveGates?.drift_check===!0}catch(gateLoadError){safeWarn("[phase_complete] QA gate profile load error, drift_check defaults to enabled:",gateLoadError)}if(!driftCheckEnabled)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`drift_check gate is disabled. Drift verification was skipped for phase ${phase}.`]};let phaseType;try{let planPath=path193.join(dir,".swarm","plan.json");if(fs120.existsSync(planPath)){let planRaw=fs120.readFileSync(planPath,"utf-8");phaseType=JSON.parse(planRaw).phases?.find((p)=>p.id===phase)?.type}}catch{}if(phaseType==="non-code")return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`Phase ${phase} is annotated as 'non-code'. Drift verification was skipped per phase type annotation.`]};try{let driftEvidencePath=path193.join(dir,".swarm","evidence",String(phase),"drift-verifier.json"),driftVerdictFound=!1,driftVerdictApproved=!1;try{let driftEvidenceContent=fs120.readFileSync(driftEvidencePath,"utf-8"),entries=JSON.parse(driftEvidenceContent).entries??[];for(let entry of entries)if(typeof entry.type==="string"&&entry.type.includes("drift")&&typeof entry.verdict==="string"){if(driftVerdictFound=!0,!entry.provenance||!entry.provenance.agent_name&&!entry.provenance.session_id){let msg=`Drift verification evidence lacks provenance for phase ${phase}. Evidence should include agent_name or session_id for verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}if(entry.verdict==="approved")driftVerdictApproved=!0;if(entry.verdict==="rejected"||typeof entry.summary==="string"&&entry.summary.includes("NEEDS_REVISION"))return{blocked:!0,reason:"DRIFT_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: drift verifier returned verdict '${entry.verdict}'. Address the drift issues before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readError){if(readError.code!=="ENOENT")safeWarn("[phase_complete] Drift verifier evidence unreadable:",readError);driftVerdictFound=!1}if(!driftVerdictFound)if(!driftHasEffectiveSpec){let incompleteTaskCount=0,planParseable=!1;try{let planPath=path193.join(dir,".swarm","plan.json");if(fs120.existsSync(planPath)){let planRaw=fs120.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);planParseable=!0;let planPhase=plan.phases?.find((p)=>p.id===phase);if(planPhase?.tasks)incompleteTaskCount=planPhase.tasks.filter((t)=>t.status!=="completed"&&t.status!=="closed").length}}catch{}if(!planParseable)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:["No effective spec found and drift verification evidence missing — consider running critic_drift_verifier before phase completion."]};else if(incompleteTaskCount>0)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`No effective spec found and drift verification evidence missing. Phase ${phase} has ${incompleteTaskCount} incomplete task(s) in plan.json — consider running critic_drift_verifier before phase completion.`]};else return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`No effective spec found. Phase ${phase} tasks are all completed in plan.json. Drift verification was skipped.`]}}else return{blocked:!0,reason:"DRIFT_VERIFICATION_MISSING",message:`Phase ${phase} cannot be completed: drift_check is enabled and drift verifier evidence not found at .swarm/evidence/${phase}/drift-verifier.json. Run drift verification before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!driftVerdictApproved&&driftVerdictFound)return{blocked:!0,reason:"DRIFT_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: drift verifier verdict is not approved.`,agentsDispatched,agentsMissing:[],warnings:[]};return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}catch(driftError){return{blocked:!0,reason:"DRIFT_VERIFICATION_ERROR",message:`Phase ${phase} cannot be completed: drift verification encountered an error: ${driftError instanceof Error?driftError.message:String(driftError)}. This is a hard block — resolve the error before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}init_qa_gate_profile();init_utils3();init_state2();import*as fs121 from"node:fs";import*as path194 from"node:path";function parseTimestampMs(value){if(typeof value!=="string")return null;let parsed=new Date(value).getTime();return Number.isNaN(parsed)?null:parsed}function latestRetroTimestampMsFromBundle(bundle,phase){if(!bundle)return null;let timestamps=[parseTimestampMs(bundle.created_at),parseTimestampMs(bundle.updated_at),...(bundle.entries??[]).filter((entry)=>entry.type==="retrospective"&&entry.phase_number===phase).map((entry)=>parseTimestampMs(entry.timestamp))].filter((timestamp)=>timestamp!==null);return timestamps.length>0?Math.max(...timestamps):null}function readLatestRetroTimestampMs(dir,phase){let baseDir=path194.normalize(path194.resolve(dir,".swarm")),retroPath=path194.normalize(path194.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path194.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path194.sep)||retroPath===baseDir))return null;try{let content=fs121.readFileSync(retroPath,"utf-8");return latestRetroTimestampMsFromBundle(JSON.parse(content),phase)}catch{return null}}function sessionHasEnabledFinalCouncil(sessionID){if(!sessionID)return!1;return swarmState.agentSessions.get(sessionID)?.qaGateSessionOverrides?.final_council===!0}async function runFinalCouncilGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,finalCouncilEnabled=!1,gateWarnings=[];try{let preamble=await resolveGatePreamble(dir,sessionID);if(!preamble.resolved||!preamble.plan){if(hasAnyProfileWithEnabledGate(dir,"final_council")||sessionHasEnabledFinalCouncil(sessionID))return{blocked:!0,reason:"FINAL_COUNCIL_PLAN_REQUIRED",message:`Phase ${phase} cannot be completed: final_council is enabled but plan.json is missing or invalid, so the final council gate cannot verify the current plan identity. Restore a valid .swarm/plan.json and re-run the final council.`,agentsDispatched,agentsMissing:[],warnings:[]};let warning="Final council gate: plan.json is missing and no enabled final_council profile was found. If final_council is required, the gate cannot be verified.";return gateWarnings.push(warning),safeWarn(`[phase_complete] ${warning}`,void 0),{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[warning]}}if(preamble.resolved&&preamble.plan){let lastPhaseId=preamble.plan.phases[preamble.plan.phases.length-1]?.id;if(lastPhaseId!==void 0&&phase===lastPhaseId){if(preamble.effectiveGates?.final_council===!0){finalCouncilEnabled=!0;let fcPath=path194.join(dir,".swarm","evidence","final-council.json"),fcVerdictFound=!1,_fcVerdict;try{let fcContent=fs121.readFileSync(fcPath,"utf-8"),fcBundle=JSON.parse(fcContent);for(let entry of fcBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="final-council"&&typeof entry.verdict==="string"){fcVerdictFound=!0,_fcVerdict=entry.verdict;let now=new Date,fcTimeMs=parseTimestampMs(entry.timestamp);if(fcTimeMs===null)return{blocked:!0,reason:"FINAL_COUNCIL_TIMESTAMP_REQUIRED",message:`Phase ${phase} cannot be completed: final council evidence is missing a valid timestamp. Re-run the final council to generate fresh evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(fcTimeMs>now.getTime())return{blocked:!0,reason:"FINAL_COUNCIL_FUTURE_TIMESTAMP",message:`Phase ${phase} cannot be completed: final council evidence timestamp is in the future.`,agentsDispatched,agentsMissing:[],warnings:[]};if(now.getTime()-fcTimeMs>86400000)return{blocked:!0,reason:"FINAL_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: final council evidence is older than 24 hours. Re-run the final council for fresh review.`,agentsDispatched,agentsMissing:[],warnings:[]};let latestRetroTimestampMs=latestRetroTimestampMsFromBundle(ctx.loadedRetroBundle,phase)??readLatestRetroTimestampMs(dir,phase);if(latestRetroTimestampMs!==null&&fcTimeMs<latestRetroTimestampMs)return{blocked:!0,reason:"FINAL_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: final council evidence predates the current phase retrospective. Re-run the final council after the latest project evidence is available.`,agentsDispatched,agentsMissing:[],warnings:[]};if(preamble.plan){let currentPlanId=preamble.planId;if(entry.plan_id&&entry.plan_id!==currentPlanId)return{blocked:!0,reason:"final_council_plan_mismatch",message:`Final council evidence belongs to a different plan (evidence: ${entry.plan_id}, current: ${currentPlanId}). Re-run the final council.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!entry.plan_id)return{blocked:!0,reason:"FINAL_COUNCIL_PLAN_ID_REQUIRED",message:`Phase ${phase} (last phase) cannot be completed: final council evidence is missing plan_id binding. Re-run the final council to generate evidence with plan identity.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.plan_hash!==preamble.planHash)return{blocked:!0,reason:entry.plan_hash?"FINAL_COUNCIL_STALE_PLAN":"FINAL_COUNCIL_PLAN_HASH_REQUIRED",message:entry.plan_hash?`Phase ${phase} cannot be completed: final council evidence was produced for an older plan hash. Re-run the final council for the current plan.`:`Phase ${phase} cannot be completed: final council evidence is missing plan_hash binding. Re-run the final council to generate evidence tied to the current plan content.`,agentsDispatched,agentsMissing:[],warnings:[]};let currentIdentityHash=derivePlanIdentityHash(preamble.plan);if(entry.plan_identity_hash!==currentIdentityHash)return{blocked:!0,reason:entry.plan_identity_hash?"FINAL_COUNCIL_PLAN_IDENTITY_MISMATCH":"FINAL_COUNCIL_PLAN_IDENTITY_REQUIRED",message:entry.plan_identity_hash?`Phase ${phase} cannot be completed: final council evidence belongs to a different raw plan identity. Re-run the final council.`:`Phase ${phase} cannot be completed: final council evidence is missing plan_identity_hash binding. Re-run the final council to generate collision-resistant plan identity evidence.`,agentsDispatched,agentsMissing:[],warnings:[]}}if(typeof entry.quorumSize!=="number"||!Number.isFinite(entry.quorumSize)||entry.quorumSize<5)return{blocked:!0,reason:"FINAL_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} (last phase) cannot be completed: final council evidence is missing valid quorum metadata. Re-run the project-scoped five-member final council and call write_final_council_evidence to generate quorumed evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};let requiredFinalCouncilMembers=["critic","reviewer","sme","test_engineer","explorer"],membersVoted=Array.isArray(entry.membersVoted)?entry.membersVoted.filter((member)=>typeof member==="string"):[],membersAbsent=Array.isArray(entry.membersAbsent)?entry.membersAbsent.filter((member)=>typeof member==="string"):[],distinctMembersVoted=new Set(membersVoted);if(!(requiredFinalCouncilMembers.every((member)=>distinctMembersVoted.has(member))&&distinctMembersVoted.size===requiredFinalCouncilMembers.length&&membersAbsent.length===0))return{blocked:!0,reason:"FINAL_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} (last phase) cannot be completed: final council evidence does not prove all five required members voted. Re-run the project-scoped five-member final council and call write_final_council_evidence to generate complete evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.verdict==="rejected"||entry.verdict==="REJECTED")return{blocked:!0,reason:"FINAL_COUNCIL_REJECTED",message:`Phase ${phase} (last phase) cannot be completed: final council returned verdict 'REJECTED'. Address the required fixes before completing the project.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.verdict==="concerns"||entry.verdict==="CONCERNS"){let advisoryNotes=Array.isArray(entry.advisoryNotes)?entry.advisoryNotes.filter((note)=>typeof note==="string"):[],warning=advisoryNotes.length>0?`Final council returned CONCERNS (non-blocking): ${advisoryNotes.join("; ")}`:"Final council returned CONCERNS (non-blocking).";gateWarnings.push(warning),safeWarn(`[phase_complete] ${warning}`,void 0)}if(entry.verdict!=="approved"&&entry.verdict!=="APPROVED"&&entry.verdict!=="concerns"&&entry.verdict!=="CONCERNS")return{blocked:!0,reason:"FINAL_COUNCIL_INVALID_VERDICT",message:`Phase ${phase} (last phase) cannot be completed: final council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: approved, concerns, rejected.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Final council evidence unreadable:",readErr);fcVerdictFound=!1}if(!fcVerdictFound)return{blocked:!0,reason:"FINAL_COUNCIL_REQUIRED",final_council_required:!0,message:`Phase ${phase} (last phase) cannot be completed: final_council is enabled and final council evidence not found at .swarm/evidence/final-council.json. Dispatch critic, reviewer, sme, test_engineer, and explorer with project-scoped context, collect their CouncilMemberVerdict JSON, and call write_final_council_evidence before completing the project. Do not use convene_general_council for this gate.`,agentsDispatched,agentsMissing:[],warnings:["Final council required - dispatch the five project-scoped council members, then call write_final_council_evidence to persist quorumed evidence."]}}}}}catch(fcError){if(finalCouncilEnabled)return{blocked:!0,reason:"FINAL_COUNCIL_ERROR",message:`Phase ${phase} (last phase) cannot be completed: final council gate encountered an error. Error: ${String(fcError)}`,agentsDispatched,agentsMissing:[],warnings:[`FINAL_COUNCIL_ERROR: ${String(fcError)}`]};else safeWarn("[phase_complete] Final council gate error (non-blocking):",fcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}import*as fs122 from"node:fs";import*as path195 from"node:path";async function runHallucinationGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.hallucination_guard===!0){let hgPath=path195.join(dir,".swarm","evidence",String(phase),"hallucination-guard.json"),hgVerdictFound=!1,hgVerdictApproved=!1;try{let hgContent=fs122.readFileSync(hgPath,"utf-8"),hgBundle=JSON.parse(hgContent);for(let entry of hgBundle.entries??[])if(typeof entry.type==="string"&&entry.type.includes("hallucination")&&typeof entry.verdict==="string"){if(hgVerdictFound=!0,entry.verdict==="approved")hgVerdictApproved=!0;if(entry.verdict==="rejected"||typeof entry.summary==="string"&&entry.summary.includes("NEEDS_REVISION"))return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: hallucination verifier returned verdict '${entry.verdict}'. Remove fabricated APIs/signatures and fix broken citations before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Hallucination guard evidence unreadable:",readErr);hgVerdictFound=!1}if(!hgVerdictFound)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_MISSING",message:`Phase ${phase} cannot be completed: hallucination_guard is enabled and evidence not found at .swarm/evidence/${phase}/hallucination-guard.json. Delegate to critic_hallucination_verifier and call write_hallucination_evidence before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!hgVerdictApproved)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: hallucination verifier verdict is not approved.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(hgError){safeWarn("[phase_complete] Hallucination guard error (non-blocking):",hgError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}import*as fs123 from"node:fs";import*as path196 from"node:path";async function runMutationGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.mutation_test===!0){let mgPath=path196.join(dir,".swarm","evidence",String(phase),"mutation-gate.json"),mgVerdictFound=!1,mgVerdict;try{let mgContent=fs123.readFileSync(mgPath,"utf-8"),mgBundle=JSON.parse(mgContent);for(let entry of mgBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="mutation-gate"&&typeof entry.verdict==="string"){if(mgVerdictFound=!0,mgVerdict=entry.verdict,entry.verdict==="fail")return{blocked:!0,reason:"MUTATION_GATE_FAIL",message:`Phase ${phase} cannot be completed: mutation gate returned verdict 'fail'. Resolve surviving mutants or lower the kill-rate threshold before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};else if(!["pass","warn","skip"].includes(entry.verdict))return{blocked:!0,reason:"MUTATION_GATE_FAIL",message:`Phase ${phase} cannot be completed: mutation gate evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: pass, warn, fail, skip.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Mutation gate evidence unreadable:",readErr);mgVerdictFound=!1}if(!mgVerdictFound)return{blocked:!0,reason:"MUTATION_GATE_MISSING",message:`Phase ${phase} cannot be completed: mutation_test is enabled and evidence not found at .swarm/evidence/${phase}/mutation-gate.json. Run mutation_test, then call write_mutation_evidence before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(mgVerdict==="warn")safeWarn(`[phase_complete] Mutation gate verdict is 'warn' for phase ${phase} — proceeding with warning`,void 0)}}catch(mgError){safeWarn("[phase_complete] Mutation gate error (non-blocking):",mgError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}import*as fs124 from"node:fs";import*as path197 from"node:path";async function runPhaseCouncilGate(ctx){let{phase,dir,sessionID,pluginConfig,agentsDispatched,safeWarn}=ctx,gateWarnings=[],councilModeEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.phase_council===!0&&pluginConfig.council?.enabled===!0){councilModeEnabled=!0;let pcPath=path197.join(dir,".swarm","evidence",String(phase),"phase-council.json"),pcVerdictFound=!1,_pcVerdict,pcQuorumSize,pcTimestamp,pcPhaseNumber;try{let pcContent=fs124.readFileSync(pcPath,"utf-8"),pcBundle=JSON.parse(pcContent);for(let entry of pcBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="phase-council"&&typeof entry.verdict==="string"){pcVerdictFound=!0,_pcVerdict=entry.verdict,pcQuorumSize=typeof entry.quorumSize==="number"?entry.quorumSize:void 0,pcTimestamp=typeof entry.timestamp==="string"?entry.timestamp:void 0,pcPhaseNumber=typeof entry.phase_number==="number"?entry.phase_number:typeof entry.phase==="number"?entry.phase:void 0;let now=new Date,pcTime=pcTimestamp?new Date(pcTimestamp):null;if(!pcTime||Number.isNaN(pcTime.getTime()))return{blocked:!0,reason:"PHASE_COUNCIL_INVALID_TIMESTAMP",message:`Phase ${phase} cannot be completed: phase council evidence has missing or invalid timestamp.`,agentsDispatched,agentsMissing:[],warnings:[]};let maxAge=86400000;if(pcTime.getTime()>now.getTime())return{blocked:!0,reason:"PHASE_COUNCIL_FUTURE_TIMESTAMP",message:`Phase ${phase} cannot be completed: phase council evidence timestamp is in the future.`,agentsDispatched,agentsMissing:[],warnings:[]};if(now.getTime()-pcTime.getTime()>maxAge)return{blocked:!0,reason:"PHASE_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: phase council evidence is older than 24 hours. Re-convene council for fresh review.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!entry.provenance||!entry.provenance.agent_name&&!entry.provenance.session_id){let msg=`Phase council evidence lacks provenance for phase ${phase}. Evidence should include agent_name or session_id for verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}if(entry.verdict==="REJECT"||entry.verdict==="reject"){let requiredFixes=entry.requiredFixes??entry.required_fixes??[],fixesDetail=Array.isArray(requiredFixes)&&requiredFixes.length>0?`
5735
5770
  Required fixes: ${requiredFixes.map((f)=>f.detail??JSON.stringify(f)).join("; ")}`:"";return{blocked:!0,reason:"PHASE_COUNCIL_REJECTED",message:`Phase ${phase} cannot be completed: phase council returned verdict 'REJECT'. Address the required fixes before completing the phase.${fixesDetail}`,agentsDispatched,agentsMissing:[],warnings:[]}}if(entry.verdict==="CONCERNS"||entry.verdict==="concerns"){if(!(pluginConfig.council?.phaseConcernsAllowComplete??!0)){let advisoryNotes=entry.advisoryNotes??entry.advisory_notes??[],notesDetail=Array.isArray(advisoryNotes)&&advisoryNotes.length>0?`
5736
5771
  Advisory notes: ${advisoryNotes.join("; ")}`:"";return{blocked:!0,reason:"PHASE_COUNCIL_CONCERNS",message:`Phase ${phase} cannot be completed: phase council returned verdict 'CONCERNS'.${notesDetail}`,agentsDispatched,agentsMissing:[],warnings:[]}}safeWarn(`[phase_complete] Phase council returned CONCERNS for phase ${phase} — proceeding (phaseConcernsAllowComplete is enabled)`,void 0)}if(entry.verdict!=="APPROVE"&&entry.verdict!=="approve"&&entry.verdict!=="CONCERNS"&&entry.verdict!=="concerns")return{blocked:!0,reason:"PHASE_COUNCIL_INVALID",message:`Phase ${phase} cannot be completed: phase council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: APPROVE, CONCERNS, REJECT.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Phase council evidence unreadable:",readErr);pcVerdictFound=!1}if(!pcVerdictFound)return{blocked:!0,reason:"PHASE_COUNCIL_REQUIRED",phase_council_required:!0,message:`Phase ${phase} cannot be completed: phase_council is enabled and phase council evidence not found at .swarm/evidence/${phase}/phase-council.json. Convene a phase-level council (dispatch 5 members, collect verdicts, call submit_phase_council_verdicts) before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:["Phase council required — convene 5 council members (critic, reviewer, sme, test_engineer, explorer) for holistic phase review. Call submit_phase_council_verdicts to synthesize verdicts and write phase-council.json evidence."]};if(pcQuorumSize===void 0||typeof pcQuorumSize!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} cannot be completed: phase council evidence is missing quorumSize field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcQuorumSize<3)return{blocked:!0,reason:"PHASE_COUNCIL_INSUFFICIENT_QUORUM",message:`Phase ${phase} cannot be completed: phase council quorum (${pcQuorumSize}) is below minimum (3). Re-convene council with sufficient members.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcPhaseNumber===void 0||typeof pcPhaseNumber!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_PHASE",message:`Phase ${phase} cannot be completed: phase council evidence is missing phase_number field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcPhaseNumber!==phase)return{blocked:!0,reason:"PHASE_COUNCIL_PHASE_MISMATCH",message:`Phase ${phase} cannot be completed: phase council evidence is for phase ${pcPhaseNumber}, not phase ${phase}. Run council for the correct phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(pcError){if(councilModeEnabled)return{blocked:!0,reason:"PHASE_COUNCIL_ERROR",message:`Phase ${phase} cannot be completed: phase council gate encountered an error when phase_council was enabled. Error: ${String(pcError)}`,agentsDispatched,agentsMissing:[],warnings:[`PHASE_COUNCIL_ERROR: ${String(pcError)}`]};else safeWarn("[phase_complete] Phase council gate error (non-blocking):",pcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}init_resolve_working_directory();function safeWarn(message,error93){try{warn(message,error93 instanceof Error?error93.message:String(error93))}catch{}}var MAX_OUTPUT_BYTES6=512000,TASK_GATE_INFERABLE_AGENTS=new Set(["coder","reviewer","test_engineer"]);function canInferMissingAgentsFromTaskGates(agentsMissing){return agentsMissing.every((agent)=>TASK_GATE_INFERABLE_AGENTS.has(agent))}async function allCompletedTasksHavePassedGateEvidence(directory,tasks){for(let task of tasks){if(task.status!=="completed")return!1;if(!await hasPassedAllGates(directory,task.id))return!1}return tasks.length>0}function collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,callerSessionId){let agents=new Set,contributorSessionIds=[],callerSession=swarmState.agentSessions.get(callerSessionId);if(callerSession){if(contributorSessionIds.push(callerSessionId),callerSession.phaseAgentsDispatched)for(let agent of callerSession.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(callerSessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}for(let[sessionId,session]of swarmState.agentSessions){if(sessionId===callerSessionId)continue;let hasRecentToolCalls=session.lastToolCallTime>=phaseReferenceTimestamp,hasRecentDelegations=swarmState.delegationChains.get(sessionId)?.some((d)=>d.timestamp>=phaseReferenceTimestamp)??!1,hasRestoredAgents=(session.phaseAgentsDispatched?.size??0)>0&&session.lastPhaseCompleteTimestamp===phaseReferenceTimestamp;if(hasRecentToolCalls||hasRecentDelegations||hasRestoredAgents){if(contributorSessionIds.push(sessionId),session.phaseAgentsDispatched)for(let agent of session.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(sessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}}return{agents,contributorSessionIds}}async function fallbackWritePlanWithTrace(dir,planPath,candidate,phase,warnings){let validation2=PlanSchema.safeParse(candidate);if(!validation2.success){let detail=validation2.error.issues.slice(0,5).map((issue3)=>`${issue3.path.join(".")||"<root>"}: ${issue3.message}`).join("; ");return warn("[phase_complete] Last-resort plan.json write aborted — mutated plan failed PlanSchema validation:",detail),warnings.push(`Warning: last-resort plan.json write skipped — mutated plan failed schema validation (${detail})`),!1}await atomicWriteFile(planPath,JSON.stringify(validation2.data,null,2));try{let traceEvent={event:"phase_complete_fallback_write",phase,timestamp:new Date().toISOString()},eventsPath=validateSwarmPath(dir,"events.jsonl");fs126.appendFileSync(eventsPath,`${JSON.stringify(traceEvent)}
5737
- `,"utf-8")}catch(eventError){warnings.push(`Warning: failed to record phase_complete_fallback_write trace event: ${eventError instanceof Error?eventError.message:String(eventError)}`)}return!0}function _getDelegationsSince(sessionID,sinceTimestamp){let chain=swarmState.delegationChains.get(sessionID);if(!chain)return[];if(sinceTimestamp===0)return chain;return chain.filter((entry)=>entry.timestamp>sinceTimestamp)}function isValidRetroEntry(entry,phase){return entry.type==="retrospective"&&"phase_number"in entry&&entry.phase_number===phase&&"verdict"in entry&&entry.verdict==="pass"}function blockedResult(phase,gateResult){let{reason,message,agentsDispatched,agentsMissing,warnings,blocked:_blocked,...extra}=gateResult;return JSON.stringify({success:!1,phase,status:"blocked",reason,message,agentsDispatched,agentsMissing,warnings,...extra},null,2)}async function executePhaseComplete(args2,workingDirectory,directory){let phase=Number(args2.phase),summary=args2.summary,sessionID=args2.sessionID;if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase)||!Number.isInteger(phase))return JSON.stringify({success:!1,phase,status:"blocked",message:"Invalid phase number",agentsDispatched:[],warnings:["Phase must be a positive number"]},null,2);if(!sessionID)return JSON.stringify({success:!1,phase,message:"Session ID is required",agentsDispatched:[],warnings:["sessionID parameter is required for phase completion tracking"]},null,2);let phaseReferenceTimestamp=ensureAgentSession(sessionID).lastPhaseCompleteTimestamp??0,warnings=[],crossSessionResult=collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,sessionID),agentsDispatched=Array.from(crossSessionResult.agents).sort(),dir=workingDirectory||directory,{config:config3}=loadPluginConfigWithMeta(dir),phaseCompleteConfig;try{phaseCompleteConfig=PhaseCompleteConfigSchema.parse(config3.phase_complete??{})}catch(parseError){return JSON.stringify({success:!1,phase,status:"incomplete",message:`Invalid phase_complete configuration: ${parseError instanceof Error?parseError.message:"Unknown error"}`,agentsDispatched,agentsMissing:[],warnings:["Configuration validation failed"]},null,2)}if(phaseCompleteConfig.enabled===!1)return JSON.stringify({success:!0,phase,status:"disabled",message:`Phase ${phase} complete (enforcement disabled)`,agentsDispatched,agentsMissing:[],warnings:[]},null,2);if(config3.knowledge?.enabled!==!1){let plan=await loadPlan(dir).catch(()=>null),phaseLabel=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase??phase}`:`Phase ${phase}`,requestedAccept=Array.isArray(args2.acceptViolations)?args2.acceptViolations.filter((s)=>typeof s==="string"&&s.length>0):[],justification=typeof args2.acceptViolationsJustification==="string"?args2.acceptViolationsJustification.trim():"",callerAgent=args2.callerAgent??swarmState.activeAgent.get(sessionID)??"architect",isArchitect=stripKnownSwarmPrefix(callerAgent).toLowerCase()==="architect";if(requestedAccept.length>0&&!isArchitect)return blockedResult(phase,{reason:"override_denied_non_architect",message:"accept_violations is architect-only — this caller may not override critical directive violations.",agentsDispatched,agentsMissing:[],warnings});if(requestedAccept.length>0&&justification.length<10)return blockedResult(phase,{reason:"override_requires_justification",message:"accept_violations requires accept_violations_justification (minimum 10 characters of substantive reasoning).",agentsDispatched,agentsMissing:[],warnings});let effectiveAccept=requestedAccept.length>0&&isArchitect&&justification.length>=10?requestedAccept:[],directiveGate=await evaluatePhaseCriticalDirectives({directory:dir,phaseLabel,acceptViolations:effectiveAccept});if(directiveGate.overridden.length>0)await recordDirectiveOverrides(dir,directiveGate.overridden,justification,sessionID);if(directiveGate.blocked)return blockedResult(phase,{reason:directiveGate.failedClosed?"directive_gate_failed_closed":"unresolved_critical_directives",message:directiveGate.failedClosed?"Critical-directive gate could not read knowledge events; failing closed.":formatDirectiveBlockMessage(directiveGate.unresolved),agentsDispatched,agentsMissing:[],warnings,unresolved_directives:directiveGate.unresolved})}let retroResult=await loadEvidence(dir,`retro-${phase}`),retroFound=!1,retroEntry=null,invalidSchemaErrors=[],loadedRetroTaskId=null,loadedRetroBundle=null,primaryRetroTaskId=`retro-${phase}`;if(retroResult.status==="found"){let validEntry=retroResult.bundle.entries?.find((entry)=>isValidRetroEntry(entry,phase));if(validEntry)retroFound=!0,retroEntry=validEntry,loadedRetroTaskId=primaryRetroTaskId,loadedRetroBundle=retroResult.bundle}else if(retroResult.status==="invalid_schema")invalidSchemaErrors=retroResult.errors;if(!retroFound){let retroTaskIds=(await listEvidenceTaskIds(dir)).filter((id)=>id.startsWith("retro-")&&/^retro-\d+$/.test(id));for(let taskId of retroTaskIds){let bundleResult=await loadEvidence(dir,taskId);if(bundleResult.status!=="found"){if(bundleResult.status==="invalid_schema")invalidSchemaErrors.push(...bundleResult.errors);continue}let validEntry=bundleResult.bundle.entries?.find((entry)=>isValidRetroEntry(entry,phase));if(validEntry){retroFound=!0,retroEntry=validEntry,loadedRetroTaskId=taskId,loadedRetroBundle=bundleResult.bundle;break}}}if(!retroFound){let schemaErrorDetail=invalidSchemaErrors.length>0?` Schema validation failed: ${invalidSchemaErrors.join("; ")}.`:"";return JSON.stringify({success:!1,phase,status:"blocked",reason:"RETROSPECTIVE_MISSING",message:`Phase ${phase} cannot be completed: no valid retrospective evidence found.${schemaErrorDetail} Write a retrospective bundle at .swarm/evidence/retro-${phase}/evidence.json before calling phase_complete.`,agentsDispatched,agentsMissing:[],warnings:[`Retrospective missing for phase ${phase}.${schemaErrorDetail} Use this template:`,JSON.stringify({schema_version:"1.0.0",task_id:`retro-${phase}`,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),entries:[{task_id:`retro-${phase}`,type:"retrospective",timestamp:new Date().toISOString(),agent:"architect",verdict:"pass",summary:`Phase ${phase} completed.`,phase_number:phase,total_tool_calls:0,coder_revisions:0,reviewer_rejections:0,test_failures:0,security_findings:0,integration_issues:0,task_count:1,task_complexity:"simple",top_rejection_reasons:[],lessons_learned:[]}]},null,2)]},null,2)}let gateCtx={phase,dir,sessionID,pluginConfig:config3,agentsDispatched,safeWarn,loadedRetroBundle,loadedRetroTaskId};if(hasActiveTurboMode(sessionID))warnings.push(`Turbo mode active — skipped completion-verify, drift-verifier, hallucination-guard, mutation-gate, and phase-council gates for phase ${phase}.`);else{{let gateResult2=await runCompletionVerifyGate(gateCtx);if(gateResult2.blocked)return blockedResult(phase,gateResult2);warnings.push(...gateResult2.warnings)}{let gateResult2=await runDriftGate(gateCtx);if(gateResult2.blocked)return blockedResult(phase,gateResult2);warnings.push(...gateResult2.warnings)}{let gateResult2=await runHallucinationGate(gateCtx);if(gateResult2.blocked)return blockedResult(phase,gateResult2);warnings.push(...gateResult2.warnings)}{let gateResult2=await runMutationGate(gateCtx);if(gateResult2.blocked)return blockedResult(phase,gateResult2);warnings.push(...gateResult2.warnings)}{let gateResult2=await runPhaseCouncilGate(gateCtx);if(gateResult2.blocked)return blockedResult(phase,gateResult2);warnings.push(...gateResult2.warnings)}}if(config3.architectural_supervision?.enabled&&config3.architectural_supervision.mode==="gate"){let gateResult2=await runArchitectureSupervisorGate(gateCtx);if(gateResult2.blocked)return blockedResult(phase,gateResult2);warnings.push(...gateResult2.warnings)}let gateResult=await runFinalCouncilGate(gateCtx);if(gateResult.blocked)return blockedResult(phase,gateResult);warnings.push(...gateResult.warnings);{let approval=verifyFullAutoPhaseApproval(dir,sessionID,phase,config3);if(!approval.ok)return JSON.stringify({success:!1,phase,status:"blocked",reason:"FULL_AUTO_APPROVAL_REQUIRED",message:`Phase ${phase} cannot be completed: ${approval.reason??"Full-Auto v2 approval missing"}`,agentsDispatched,agentsMissing:[],warnings:[`Full-Auto v2 active. Re-run critic_oversight with trigger_source=phase_boundary so an APPROVED record is written to .swarm/evidence/${phase}/full-auto-*.json before calling phase_complete again.`]},null,2)}let epicActiveForProject=isEpicModeActiveForProject(dir);if(hasActiveLeanTurbo(sessionID)&&!epicActiveForProject){let leanConfig=config3?.turbo?.lean,leanPhaseReadyConfig=leanConfig?{phase_reviewer:leanConfig.phase_reviewer,phase_critic:leanConfig.phase_critic,integrated_diff_required:leanConfig.integrated_diff_required}:void 0,leanCheck=_internals119.verifyLeanTurboPhaseReady(dir,phase,sessionID,leanPhaseReadyConfig);if(!leanCheck.ok)return JSON.stringify({success:!1,phase,status:"blocked",reason:"LEAN_TURBO_PHASE_NOT_READY",message:`Phase ${phase} cannot be completed: ${leanCheck.reason}`,agentsDispatched,agentsMissing:[],warnings:[`Lean Turbo phase readiness: ${leanCheck.reason}`]},null,2)}let knowledgeConfig;try{knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch(parseErr){warnings.push(`Knowledge config validation failed: ${String(parseErr)}`),knowledgeConfig=KnowledgeConfigSchema.parse({})}if(retroFound&&retroEntry?.lessons_learned&&retroEntry.lessons_learned.length>0)try{let projectName=path199.basename(dir),curationResult=await curateAndStoreSwarm(retroEntry.lessons_learned,projectName,{phase_number:phase},dir,knowledgeConfig,{llmDelegate:createCuratorLLMDelegate(dir,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});if(curationResult){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)sessionState.pendingAdvisoryMessages??=[],sessionState.pendingAdvisoryMessages.push(`[CURATOR] Knowledge curation: ${curationResult.stored} stored, ${curationResult.reinforced} reinforced, ${curationResult.skipped} skipped, ${curationResult.rejected} rejected, ${curationResult.quarantined} quarantined (unactionable).`)}await updateRetrievalOutcome(dir,`Phase ${phase}`,!0)}catch(error93){safeWarn("[phase_complete] Failed to curate lessons from retrospective:",error93)}let complianceWarnings=[];try{let curatorConfig=CuratorConfigSchema.parse(config3.curator??{});if(curatorConfig.enabled&&curatorConfig.phase_enabled){let llmDelegate=createCuratorLLMDelegate(dir,"phase",sessionID??void 0),curatorResult=await runCuratorPhase(dir,phase,agentsDispatched,curatorConfig,{},llmDelegate);{let scopeContent=curatorResult.digest?.summary??`Phase ${phase} curator analysis`,complianceWarnings2=curatorResult.compliance.filter((c)=>c.severity==="warning"),receipt=complianceWarnings2.length>0?buildRejectedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",blockingFindings:complianceWarnings2.map((c)=>({location:`phase-${c.phase}`,summary:c.description,severity:c.type==="missing_reviewer"?"high":"medium"})),evidenceReferences:[],passConditions:["resolve all compliance warnings before phase completion"]}):buildApprovedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",checkedAspects:["phase_compliance","knowledge_recommendations","phase_digest"],validatedClaims:[`phase: ${phase}`,`agents_dispatched: ${agentsDispatched.length}`,`knowledge_recommendations: ${curatorResult.knowledge_recommendations.length}`]});persistReviewReceipt(dir,receipt).catch(()=>{})}let knowledgeResult=await applyCuratorKnowledgeUpdates(dir,curatorResult.knowledge_recommendations,knowledgeConfig),callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){callerSessionState.pendingAdvisoryMessages??=[];let digestSummary=curatorResult.digest?.summary?curatorResult.digest.summary.slice(0,200):"Phase analysis complete",complianceNote=curatorResult.compliance.length>0?` (${curatorResult.compliance.length} compliance observation(s))`:"",analyzeHint=curatorResult.knowledge_recommendations.length>0?" Call curator_analyze with recommendations to apply knowledge updates from this phase.":"";callerSessionState.pendingAdvisoryMessages.push(`[CURATOR] Phase ${phase} digest: ${digestSummary}${complianceNote}. Knowledge: ${knowledgeResult.applied} applied, ${knowledgeResult.skipped} skipped.${analyzeHint}`);try{let{readPriorDriftReports:readPriorDriftReports2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift)),phaseReport=(await readPriorDriftReports2(dir)).filter((r)=>r.phase===phase).pop();if(phaseReport&&phaseReport.drift_score>0)callerSessionState.pendingAdvisoryMessages.push(`[CURATOR DRIFT DETECTED (phase ${phase}, score ${phaseReport.drift_score})]: Consider running critic_drift_verifier before phase completion to get a proper drift review. Review drift report for phase ${phase} and address spec alignment if applicable.`)}catch{}}if(curatorResult.compliance.length>0&&!curatorConfig.suppress_warnings)complianceWarnings=curatorResult.compliance.map((obs)=>`[${obs.severity.toUpperCase()}] ${obs.description}`).slice(0,5)}}catch(curatorError){safeWarn("[phase_complete] Curator pipeline error (non-blocking):",curatorError)}try{if(config3.design_docs?.enabled===!0){let outDir=config3.design_docs.out_dir??"docs",{runDesignDocDriftCheck:runDesignDocDriftCheck2}=await Promise.resolve().then(() => (init_design_doc_drift(),exports_design_doc_drift)),docReport=await runDesignDocDriftCheck2(dir,phase,outDir);if(docReport?.verdict==="DOC_STALE"){let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){callerSessionState.pendingAdvisoryMessages??=[];let staleIds=docReport.stale_sections.map((s)=>s.section_id).slice(0,8).join(", ");callerSessionState.pendingAdvisoryMessages.push(`[DESIGN-DOC DRIFT (phase ${phase})]: ${docReport.stale_sections.length} design-doc section(s) are stale (${staleIds}). Run /swarm design-docs --update to sync ${outDir}/ and append a design-changelog entry. Advisory only — does not block completion.`)}}}}catch(docDriftError){safeWarn("[phase_complete] Design-doc drift check error (non-blocking):",docDriftError)}try{let feedbackResult=await applySkillUsageFeedback(dir);if(feedbackResult.processed>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)sessionState.pendingAdvisoryMessages??=[],sessionState.pendingAdvisoryMessages.push(`[FEEDBACK] Skill usage feedback: ${feedbackResult.processed} skills processed, ${feedbackResult.bumps} confidence updates applied.`)}}catch(skillUsageError){safeWarn("[phase_complete] Skill usage feedback error (non-blocking):",skillUsageError)}try{pruneSkillUsageLog(dir,500)}catch(skillPruneError){safeWarn("[phase_complete] Skill usage log pruning error (non-blocking):",skillPruneError)}try{let verdictMarkerPath=validateSwarmPath(dir,"verdict-feedback-last-processed.json"),verdictSinceTimestamp;try{verdictSinceTimestamp=JSON.parse(fs126.readFileSync(verdictMarkerPath,"utf-8")).lastProcessedTimestamp}catch{}let verdictMarkerTimestamp=new Date().toISOString(),{applyKnowledgeVerdictFeedback:applyKnowledgeVerdictFeedback2}=await Promise.resolve().then(() => (init_knowledge_events(),exports_knowledge_events)),verdictResult=await applyKnowledgeVerdictFeedback2(dir,{sinceTimestamp:verdictSinceTimestamp});try{fs126.writeFileSync(verdictMarkerPath,JSON.stringify({lastProcessedTimestamp:verdictMarkerTimestamp}),"utf-8")}catch{}if(verdictResult.bumps>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)sessionState.pendingAdvisoryMessages??=[],sessionState.pendingAdvisoryMessages.push(`[FEEDBACK] Knowledge verdict feedback: ${verdictResult.processed} entries processed, ${verdictResult.bumps} confidence updates applied.`)}}catch(verdictError){safeWarn("[phase_complete] Knowledge verdict feedback error (non-blocking):",verdictError)}let phaseRequiredAgents;try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs126.readFileSync(planPath,"utf-8");phaseRequiredAgents=JSON.parse(planRaw).phases.find((p)=>p.id===phase)?.required_agents}catch{}let effectiveRequired=[...phaseRequiredAgents??phaseCompleteConfig.required_agents];if(phaseCompleteConfig.require_docs&&!effectiveRequired.includes("docs"))effectiveRequired.push("docs");let agentsMissing=effectiveRequired.filter((req)=>!crossSessionResult.agents.has(req));if(agentsMissing.length>0)try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs126.readFileSync(planPath,"utf-8"),targetPhase=JSON.parse(planRaw).phases.find((p)=>p.id===phase);if(targetPhase&&targetPhase.tasks.length>0&&canInferMissingAgentsFromTaskGates(agentsMissing)&&await allCompletedTasksHavePassedGateEvidence(dir,targetPhase.tasks))warnings.push(`Agent dispatch fallback: all ${targetPhase.tasks.length} tasks in phase ${phase} are completed in plan.json and durable gate evidence passed. Clearing missing agents: ${agentsMissing.join(", ")}.`),agentsMissing=[]}catch{}let VALID_TASK_COMPLEXITY=["trivial","simple","moderate","complex"],firstEntry=loadedRetroBundle?.entries?.[0];if(loadedRetroTaskId!==primaryRetroTaskId&&loadedRetroTaskId?.startsWith("retro-")&&loadedRetroBundle?.schema_version==="1.0.0"&&firstEntry?.task_complexity&&VALID_TASK_COMPLEXITY.includes(firstEntry.task_complexity))warnings.push(`Retrospective data for phase ${phase} may have been automatically migrated to current schema format.`);let success3=!0,status="success",safeSummary=summary?.trim().slice(0,500),message=safeSummary?`Phase ${phase} completed: ${safeSummary}`:`Phase ${phase} completed`;if(agentsMissing.length>0)if(phaseCompleteConfig.policy==="enforce")success3=!1,status="incomplete",message=`Phase ${phase} incomplete: missing required agents: ${agentsMissing.join(", ")}`;else status="warned",warnings.push(`Warning: phase ${phase} missing required agents: ${agentsMissing.join(", ")}`);let result={success:success3,phase,status,message,agentsDispatched,agentsMissing,warnings};if(phaseCompleteConfig.regression_sweep?.enforce)try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs126.readFileSync(planPath,"utf-8"),targetPhase=JSON.parse(planRaw).phases.find((p)=>p.id===phase);if(targetPhase){let sweepFound=!1;for(let task of targetPhase.tasks){let taskEvidenceResult=await loadEvidence(dir,task.id);if(taskEvidenceResult.status==="found"){let entries=taskEvidenceResult.bundle.entries??[];for(let entry of entries)if(entry.regression_sweep!==void 0){sweepFound=!0;break}}if(sweepFound)break}if(!sweepFound)warnings.push(`Warning: regression_sweep.enforce=true but no regression-sweep result found for any task in phase ${phase}. Run tests to populate regression-sweep results.`)}}catch{}let now=Date.now(),durationMs=now-phaseReferenceTimestamp,event={event:"phase_complete",phase,timestamp:new Date(now).toISOString(),agents_dispatched:agentsDispatched,agents_missing:agentsMissing,status,summary:safeSummary??null},lockTaskId=`phase-complete-${Date.now()}`,eventsFilePath="events.jsonl",agentName="phase-complete";for(let[,agent]of swarmState?.activeAgent??[]){agentName=agent;break}let lockResult;try{lockResult=await tryAcquireLock(dir,eventsFilePath,agentName,lockTaskId)}catch(error93){warnings.push(`Warning: failed to acquire lock for phase complete event: ${error93 instanceof Error?error93.message:String(error93)}`)}if(!lockResult?.acquired)warnings.push("Warning: could not acquire lock for events.jsonl write — proceeding without lock");try{let eventsPath=validateSwarmPath(dir,"events.jsonl");fs126.appendFileSync(eventsPath,`${JSON.stringify(event)}
5772
+ `,"utf-8")}catch(eventError){warnings.push(`Warning: failed to record phase_complete_fallback_write trace event: ${eventError instanceof Error?eventError.message:String(eventError)}`)}return!0}function _getDelegationsSince(sessionID,sinceTimestamp){let chain=swarmState.delegationChains.get(sessionID);if(!chain)return[];if(sinceTimestamp===0)return chain;return chain.filter((entry)=>entry.timestamp>sinceTimestamp)}function isValidRetroEntry(entry,phase){return entry.type==="retrospective"&&"phase_number"in entry&&entry.phase_number===phase&&"verdict"in entry&&entry.verdict==="pass"}function blockedResult(phase,gateResult){let{reason,message,agentsDispatched,agentsMissing,warnings,blocked:_blocked,...extra}=gateResult;return JSON.stringify({success:!1,phase,status:"blocked",reason,message,agentsDispatched,agentsMissing,warnings,...extra},null,2)}async function executePhaseComplete(args2,workingDirectory,directory){let phase=Number(args2.phase),summary=args2.summary,sessionID=args2.sessionID;if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase)||!Number.isInteger(phase))return JSON.stringify({success:!1,phase,status:"blocked",message:"Invalid phase number",agentsDispatched:[],warnings:["Phase must be a positive number"]},null,2);if(!sessionID)return JSON.stringify({success:!1,phase,message:"Session ID is required",agentsDispatched:[],warnings:["sessionID parameter is required for phase completion tracking"]},null,2);let phaseReferenceTimestamp=ensureAgentSession(sessionID).lastPhaseCompleteTimestamp??0,warnings=[],crossSessionResult=collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,sessionID),agentsDispatched=Array.from(crossSessionResult.agents).sort(),dir=workingDirectory||directory,{config:config3}=loadPluginConfigWithMeta(dir),phaseCompleteConfig;try{phaseCompleteConfig=PhaseCompleteConfigSchema.parse(config3.phase_complete??{})}catch(parseError){return JSON.stringify({success:!1,phase,status:"incomplete",message:`Invalid phase_complete configuration: ${parseError instanceof Error?parseError.message:"Unknown error"}`,agentsDispatched,agentsMissing:[],warnings:["Configuration validation failed"]},null,2)}if(phaseCompleteConfig.enabled===!1)return JSON.stringify({success:!0,phase,status:"disabled",message:`Phase ${phase} complete (enforcement disabled)`,agentsDispatched,agentsMissing:[],warnings:[]},null,2);if(config3.knowledge?.enabled!==!1){let plan=await loadPlan(dir).catch(()=>null),phaseLabel=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase??phase}`:`Phase ${phase}`,requestedAccept=Array.isArray(args2.acceptViolations)?args2.acceptViolations.filter((s)=>typeof s==="string"&&s.length>0):[],justification=typeof args2.acceptViolationsJustification==="string"?args2.acceptViolationsJustification.trim():"",callerAgent=args2.callerAgent??swarmState.activeAgent.get(sessionID)??"architect",isArchitect=stripKnownSwarmPrefix(callerAgent).toLowerCase()==="architect";if(requestedAccept.length>0&&!isArchitect)return blockedResult(phase,{reason:"override_denied_non_architect",message:"accept_violations is architect-only — this caller may not override critical directive violations.",agentsDispatched,agentsMissing:[],warnings});if(requestedAccept.length>0&&justification.length<10)return blockedResult(phase,{reason:"override_requires_justification",message:"accept_violations requires accept_violations_justification (minimum 10 characters of substantive reasoning).",agentsDispatched,agentsMissing:[],warnings});let effectiveAccept=requestedAccept.length>0&&isArchitect&&justification.length>=10?requestedAccept:[],directiveGate=await evaluatePhaseCriticalDirectives({directory:dir,phaseLabel,acceptViolations:effectiveAccept});if(directiveGate.overridden.length>0)await recordDirectiveOverrides(dir,directiveGate.overridden,justification,sessionID);if(directiveGate.blocked)return blockedResult(phase,{reason:directiveGate.failedClosed?"directive_gate_failed_closed":"unresolved_critical_directives",message:directiveGate.failedClosed?"Critical-directive gate could not read knowledge events; failing closed.":formatDirectiveBlockMessage(directiveGate.unresolved),agentsDispatched,agentsMissing:[],warnings,unresolved_directives:directiveGate.unresolved})}let retroResult=await loadEvidence(dir,`retro-${phase}`),retroFound=!1,retroEntry=null,invalidSchemaErrors=[],loadedRetroTaskId=null,loadedRetroBundle=null,primaryRetroTaskId=`retro-${phase}`;if(retroResult.status==="found"){let validEntry=retroResult.bundle.entries?.find((entry)=>isValidRetroEntry(entry,phase));if(validEntry)retroFound=!0,retroEntry=validEntry,loadedRetroTaskId=primaryRetroTaskId,loadedRetroBundle=retroResult.bundle}else if(retroResult.status==="invalid_schema")invalidSchemaErrors=retroResult.errors;if(!retroFound){let retroTaskIds=(await listEvidenceTaskIds(dir)).filter((id)=>id.startsWith("retro-")&&/^retro-\d+$/.test(id));for(let taskId of retroTaskIds){let bundleResult=await loadEvidence(dir,taskId);if(bundleResult.status!=="found"){if(bundleResult.status==="invalid_schema")invalidSchemaErrors.push(...bundleResult.errors);continue}let validEntry=bundleResult.bundle.entries?.find((entry)=>isValidRetroEntry(entry,phase));if(validEntry){retroFound=!0,retroEntry=validEntry,loadedRetroTaskId=taskId,loadedRetroBundle=bundleResult.bundle;break}}}if(!retroFound){let schemaErrorDetail=invalidSchemaErrors.length>0?` Schema validation failed: ${invalidSchemaErrors.join("; ")}.`:"";return JSON.stringify({success:!1,phase,status:"blocked",reason:"RETROSPECTIVE_MISSING",message:`Phase ${phase} cannot be completed: no valid retrospective evidence found.${schemaErrorDetail} Write a retrospective bundle at .swarm/evidence/retro-${phase}/evidence.json before calling phase_complete.`,agentsDispatched,agentsMissing:[],warnings:[`Retrospective missing for phase ${phase}.${schemaErrorDetail} Use this template:`,JSON.stringify({schema_version:"1.0.0",task_id:`retro-${phase}`,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),entries:[{task_id:`retro-${phase}`,type:"retrospective",timestamp:new Date().toISOString(),agent:"architect",verdict:"pass",summary:`Phase ${phase} completed.`,phase_number:phase,total_tool_calls:0,coder_revisions:0,reviewer_rejections:0,test_failures:0,security_findings:0,integration_issues:0,task_count:1,task_complexity:"simple",top_rejection_reasons:[],lessons_learned:[]}]},null,2)]},null,2)}let gateCtx={phase,dir,sessionID,pluginConfig:config3,agentsDispatched,safeWarn,loadedRetroBundle,loadedRetroTaskId};if(hasActiveTurboMode(sessionID))warnings.push(`Turbo mode active — skipped completion-verify, drift-verifier, hallucination-guard, mutation-gate, and phase-council gates for phase ${phase}.`);else{{let gateResult2=await runCompletionVerifyGate(gateCtx);if(gateResult2.blocked)return blockedResult(phase,gateResult2);warnings.push(...gateResult2.warnings)}{let gateResult2=await runDriftGate(gateCtx);if(gateResult2.blocked)return blockedResult(phase,gateResult2);warnings.push(...gateResult2.warnings)}{let gateResult2=await runHallucinationGate(gateCtx);if(gateResult2.blocked)return blockedResult(phase,gateResult2);warnings.push(...gateResult2.warnings)}{let gateResult2=await runMutationGate(gateCtx);if(gateResult2.blocked)return blockedResult(phase,gateResult2);warnings.push(...gateResult2.warnings)}{let gateResult2=await runPhaseCouncilGate(gateCtx);if(gateResult2.blocked)return blockedResult(phase,gateResult2);warnings.push(...gateResult2.warnings)}}if(config3.architectural_supervision?.enabled&&config3.architectural_supervision.mode==="gate"){let gateResult2=await runArchitectureSupervisorGate(gateCtx);if(gateResult2.blocked)return blockedResult(phase,gateResult2);warnings.push(...gateResult2.warnings)}let gateResult=await runFinalCouncilGate(gateCtx);if(gateResult.blocked)return blockedResult(phase,gateResult);warnings.push(...gateResult.warnings);{let approval=verifyFullAutoPhaseApproval(dir,sessionID,phase,config3);if(!approval.ok)return JSON.stringify({success:!1,phase,status:"blocked",reason:"FULL_AUTO_APPROVAL_REQUIRED",message:`Phase ${phase} cannot be completed: ${approval.reason??"Full-Auto v2 approval missing"}`,agentsDispatched,agentsMissing:[],warnings:[`Full-Auto v2 active. Re-run critic_oversight with trigger_source=phase_boundary so an APPROVED record is written to .swarm/evidence/${phase}/full-auto-*.json before calling phase_complete again.`]},null,2)}let epicActiveForProject=isEpicModeActiveForProject(dir);if(hasActiveLeanTurbo(sessionID)&&!epicActiveForProject){let leanConfig=config3?.turbo?.lean,leanPhaseReadyConfig=leanConfig?{phase_reviewer:leanConfig.phase_reviewer,phase_critic:leanConfig.phase_critic,integrated_diff_required:leanConfig.integrated_diff_required}:void 0,leanCheck=_internals119.verifyLeanTurboPhaseReady(dir,phase,sessionID,leanPhaseReadyConfig);if(!leanCheck.ok)return JSON.stringify({success:!1,phase,status:"blocked",reason:"LEAN_TURBO_PHASE_NOT_READY",message:`Phase ${phase} cannot be completed: ${leanCheck.reason}`,agentsDispatched,agentsMissing:[],warnings:[`Lean Turbo phase readiness: ${leanCheck.reason}`]},null,2)}let knowledgeConfig;try{knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch(parseErr){warnings.push(`Knowledge config validation failed: ${String(parseErr)}`),knowledgeConfig=KnowledgeConfigSchema.parse({})}if(retroFound&&retroEntry?.lessons_learned&&retroEntry.lessons_learned.length>0)try{let projectName=path199.basename(dir),curationResult=await curateAndStoreSwarm(retroEntry.lessons_learned,projectName,{phase_number:phase},dir,knowledgeConfig,{llmDelegate:createCuratorLLMDelegate(dir,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});if(curationResult){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)sessionState.pendingAdvisoryMessages??=[],sessionState.pendingAdvisoryMessages.push(`[CURATOR] Knowledge curation: ${curationResult.stored} stored, ${curationResult.reinforced} reinforced, ${curationResult.skipped} skipped, ${curationResult.rejected} rejected, ${curationResult.quarantined} quarantined (unactionable).`)}await updateRetrievalOutcome(dir,`Phase ${phase}`,!0)}catch(error93){safeWarn("[phase_complete] Failed to curate lessons from retrospective:",error93)}let complianceWarnings=[];try{let curatorConfig=CuratorConfigSchema.parse(config3.curator??{});if(curatorConfig.enabled&&curatorConfig.phase_enabled){let llmDelegate=createCuratorLLMDelegate(dir,"phase",sessionID??void 0),curatorResult=await runCuratorPhase(dir,phase,agentsDispatched,curatorConfig,{},llmDelegate);{let scopeContent=curatorResult.digest?.summary??`Phase ${phase} curator analysis`,complianceWarnings2=curatorResult.compliance.filter((c)=>c.severity==="warning"),receipt=complianceWarnings2.length>0?buildRejectedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",blockingFindings:complianceWarnings2.map((c)=>({location:`phase-${c.phase}`,summary:c.description,severity:c.type==="missing_reviewer"?"high":"medium"})),evidenceReferences:[],passConditions:["resolve all compliance warnings before phase completion"]}):buildApprovedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",checkedAspects:["phase_compliance","knowledge_recommendations","phase_digest"],validatedClaims:[`phase: ${phase}`,`agents_dispatched: ${agentsDispatched.length}`,`knowledge_recommendations: ${curatorResult.knowledge_recommendations.length}`]});persistReviewReceipt(dir,receipt).catch(()=>{})}let knowledgeResult=await applyCuratorKnowledgeUpdates(dir,curatorResult.knowledge_recommendations,knowledgeConfig),callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){callerSessionState.pendingAdvisoryMessages??=[];let digestSummary=curatorResult.digest?.summary?curatorResult.digest.summary.slice(0,200):"Phase analysis complete",complianceNote=curatorResult.compliance.length>0?` (${curatorResult.compliance.length} compliance observation(s))`:"",analyzeHint=curatorResult.knowledge_recommendations.length>0?" Call curator_analyze with recommendations to apply knowledge updates from this phase.":"";callerSessionState.pendingAdvisoryMessages.push(`[CURATOR] Phase ${phase} digest: ${digestSummary}${complianceNote}. Knowledge: ${knowledgeResult.applied} applied, ${knowledgeResult.skipped} skipped.${analyzeHint}`);try{let{readPriorDriftReports:readPriorDriftReports2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift)),phaseReport=(await readPriorDriftReports2(dir)).filter((r)=>r.phase===phase).pop();if(phaseReport&&phaseReport.drift_score>0)callerSessionState.pendingAdvisoryMessages.push(`[CURATOR DRIFT DETECTED (phase ${phase}, score ${phaseReport.drift_score})]: Consider running critic_drift_verifier before phase completion to get a proper drift review. Review drift report for phase ${phase} and address spec alignment if applicable.`)}catch{}}if(curatorResult.compliance.length>0&&!curatorConfig.suppress_warnings)complianceWarnings=curatorResult.compliance.map((obs)=>`[${obs.severity.toUpperCase()}] ${obs.description}`).slice(0,5)}}catch(curatorError){safeWarn("[phase_complete] Curator pipeline error (non-blocking):",curatorError)}try{if(config3.design_docs?.enabled===!0){let outDir=config3.design_docs.out_dir??"docs",{runDesignDocDriftCheck:runDesignDocDriftCheck2}=await Promise.resolve().then(() => (init_design_doc_drift(),exports_design_doc_drift)),docReport=await runDesignDocDriftCheck2(dir,phase,outDir);if(docReport?.verdict==="DOC_STALE"){let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){callerSessionState.pendingAdvisoryMessages??=[];let staleIds=docReport.stale_sections.map((s)=>s.section_id).slice(0,8).join(", ");callerSessionState.pendingAdvisoryMessages.push(`[DESIGN-DOC DRIFT (phase ${phase})]: ${docReport.stale_sections.length} design-doc section(s) are stale (${staleIds}). Run /swarm design-docs --update to sync ${outDir}/ and append a design-changelog entry. Advisory only — does not block completion.`)}}}}catch(docDriftError){safeWarn("[phase_complete] Design-doc drift check error (non-blocking):",docDriftError)}try{let feedbackResult=await applySkillUsageFeedback(dir);if(feedbackResult.processed>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)sessionState.pendingAdvisoryMessages??=[],sessionState.pendingAdvisoryMessages.push(`[FEEDBACK] Skill usage feedback: ${feedbackResult.processed} skills processed, ${feedbackResult.bumps} confidence updates applied.`)}}catch(skillUsageError){safeWarn("[phase_complete] Skill usage feedback error (non-blocking):",skillUsageError)}try{pruneSkillUsageLog(dir,500)}catch(skillPruneError){safeWarn("[phase_complete] Skill usage log pruning error (non-blocking):",skillPruneError)}try{let verdictMarkerPath=validateSwarmPath(dir,"verdict-feedback-last-processed.json"),verdictSinceTimestamp,verdictSinceEventId;try{let markerData=JSON.parse(fs126.readFileSync(verdictMarkerPath,"utf-8"));verdictSinceTimestamp=markerData.lastProcessedTimestamp,verdictSinceEventId=markerData.lastProcessedEventId}catch{}let{applyKnowledgeVerdictFeedback:applyKnowledgeVerdictFeedback2}=await Promise.resolve().then(() => (init_knowledge_events(),exports_knowledge_events)),verdictResult=await applyKnowledgeVerdictFeedback2(dir,{sinceTimestamp:verdictSinceTimestamp,sinceEventId:verdictSinceEventId});if(verdictResult.lastProcessedTimestamp)try{fs126.writeFileSync(verdictMarkerPath,JSON.stringify({lastProcessedTimestamp:verdictResult.lastProcessedTimestamp,lastProcessedEventId:verdictResult.lastProcessedEventId}),"utf-8")}catch{}if(verdictResult.bumps>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)sessionState.pendingAdvisoryMessages??=[],sessionState.pendingAdvisoryMessages.push(`[FEEDBACK] Knowledge verdict feedback: ${verdictResult.processed} entries processed, ${verdictResult.bumps} confidence updates applied.`)}}catch(verdictError){safeWarn("[phase_complete] Knowledge verdict feedback error (non-blocking):",verdictError)}let phaseRequiredAgents;try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs126.readFileSync(planPath,"utf-8");phaseRequiredAgents=JSON.parse(planRaw).phases.find((p)=>p.id===phase)?.required_agents}catch{}let effectiveRequired=[...phaseRequiredAgents??phaseCompleteConfig.required_agents];if(phaseCompleteConfig.require_docs&&!effectiveRequired.includes("docs"))effectiveRequired.push("docs");let agentsMissing=effectiveRequired.filter((req)=>!crossSessionResult.agents.has(req));if(agentsMissing.length>0)try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs126.readFileSync(planPath,"utf-8"),targetPhase=JSON.parse(planRaw).phases.find((p)=>p.id===phase);if(targetPhase&&targetPhase.tasks.length>0&&canInferMissingAgentsFromTaskGates(agentsMissing)&&await allCompletedTasksHavePassedGateEvidence(dir,targetPhase.tasks))warnings.push(`Agent dispatch fallback: all ${targetPhase.tasks.length} tasks in phase ${phase} are completed in plan.json and durable gate evidence passed. Clearing missing agents: ${agentsMissing.join(", ")}.`),agentsMissing=[]}catch{}let VALID_TASK_COMPLEXITY=["trivial","simple","moderate","complex"],firstEntry=loadedRetroBundle?.entries?.[0];if(loadedRetroTaskId!==primaryRetroTaskId&&loadedRetroTaskId?.startsWith("retro-")&&loadedRetroBundle?.schema_version==="1.0.0"&&firstEntry?.task_complexity&&VALID_TASK_COMPLEXITY.includes(firstEntry.task_complexity))warnings.push(`Retrospective data for phase ${phase} may have been automatically migrated to current schema format.`);let success3=!0,status="success",safeSummary=summary?.trim().slice(0,500),message=safeSummary?`Phase ${phase} completed: ${safeSummary}`:`Phase ${phase} completed`;if(agentsMissing.length>0)if(phaseCompleteConfig.policy==="enforce")success3=!1,status="incomplete",message=`Phase ${phase} incomplete: missing required agents: ${agentsMissing.join(", ")}`;else status="warned",warnings.push(`Warning: phase ${phase} missing required agents: ${agentsMissing.join(", ")}`);let result={success:success3,phase,status,message,agentsDispatched,agentsMissing,warnings};if(phaseCompleteConfig.regression_sweep?.enforce)try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs126.readFileSync(planPath,"utf-8"),targetPhase=JSON.parse(planRaw).phases.find((p)=>p.id===phase);if(targetPhase){let sweepFound=!1;for(let task of targetPhase.tasks){let taskEvidenceResult=await loadEvidence(dir,task.id);if(taskEvidenceResult.status==="found"){let entries=taskEvidenceResult.bundle.entries??[];for(let entry of entries)if(entry.regression_sweep!==void 0){sweepFound=!0;break}}if(sweepFound)break}if(!sweepFound)warnings.push(`Warning: regression_sweep.enforce=true but no regression-sweep result found for any task in phase ${phase}. Run tests to populate regression-sweep results.`)}}catch{}let now=Date.now(),durationMs=now-phaseReferenceTimestamp,event={event:"phase_complete",phase,timestamp:new Date(now).toISOString(),agents_dispatched:agentsDispatched,agents_missing:agentsMissing,status,summary:safeSummary??null},lockTaskId=`phase-complete-${Date.now()}`,eventsFilePath="events.jsonl",agentName="phase-complete";for(let[,agent]of swarmState?.activeAgent??[]){agentName=agent;break}let lockResult;try{lockResult=await tryAcquireLock(dir,eventsFilePath,agentName,lockTaskId)}catch(error93){warnings.push(`Warning: failed to acquire lock for phase complete event: ${error93 instanceof Error?error93.message:String(error93)}`)}if(!lockResult?.acquired)warnings.push("Warning: could not acquire lock for events.jsonl write — proceeding without lock");try{let eventsPath=validateSwarmPath(dir,"events.jsonl");fs126.appendFileSync(eventsPath,`${JSON.stringify(event)}
5738
5773
  `,"utf-8")}catch(writeError){warnings.push(`Warning: failed to write phase complete event: ${writeError instanceof Error?writeError.message:String(writeError)}`)}finally{if(lockResult?.acquired&&lockResult.lock._release)try{await lockResult.lock._release()}catch(releaseError){warn("[phase_complete] Lock release failed (non-blocking):",releaseError instanceof Error?releaseError.message:String(releaseError))}}if(success3){try{let skillConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{});if(skillConfig.enabled&&skillConfig.trigger==="scheduled")runSkillConsolidationFireAndForget({directory:dir,config:skillConfig,source:"phase_complete",sessionId:sessionID,enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},(consolidationResult)=>{if(!consolidationResult.started)return;let sessionState=swarmState.agentSessions.get(sessionID);if(!sessionState)return;sessionState.pendingAdvisoryMessages??=[],sessionState.pendingAdvisoryMessages.push(`[SKILL CONSOLIDATION] Scheduled skill_improver consolidation wrote ${consolidationResult.result?.proposalPath??"a proposal"} and auto-activated no skills.`)},(err)=>{safeWarn("[phase_complete] Scheduled skill consolidation error (non-blocking):",err)})}catch(skillConsolidationError){safeWarn("[phase_complete] Scheduled skill consolidation setup error (non-blocking):",skillConsolidationError)}try{let memoryConfig=config3.memory;if(memoryConfig?.enabled&&memoryConfig.consolidation?.enabled)runMemoryConsolidationFireAndForget({directory:dir,config:memoryConfig,phase,sessionId:sessionID},void 0,(err)=>{safeWarn("[phase_complete] Memory consolidation error (non-blocking):",err)})}catch(memoryConsolidationError){safeWarn("[phase_complete] Memory consolidation setup error (non-blocking):",memoryConsolidationError)}for(let contributorSessionId of crossSessionResult.contributorSessionIds){let contributorSession=swarmState.agentSessions.get(contributorSessionId);if(contributorSession){if(contributorSession.phaseAgentsDispatched.size>0)contributorSession.lastCompletedPhaseAgentsDispatched=new Set(contributorSession.phaseAgentsDispatched);contributorSession.phaseAgentsDispatched=new Set,contributorSession.fullAutoInteractionCount=0,contributorSession.fullAutoDeadlockCount=0,contributorSession.fullAutoLastQuestionHash=null,contributorSession.lastPhaseCompleteTimestamp=now;let oldPhase=contributorSession.lastPhaseCompletePhase;contributorSession.lastPhaseCompletePhase=phase,telemetry.phaseChanged(contributorSessionId,oldPhase??0,phase)}}try{if(knowledgeConfig.sweep_enabled){let swarmPath=resolveSwarmKnowledgePath(dir);if(await sweepAgedEntries(swarmPath,knowledgeConfig.default_max_phases),await sweepStaleTodos(swarmPath,knowledgeConfig.todo_max_phases),knowledgeConfig.hive_enabled){let hivePath=resolveHiveKnowledgePath();await sweepAgedEntries(hivePath,knowledgeConfig.default_max_phases),await sweepStaleTodos(hivePath,knowledgeConfig.todo_max_phases)}}}catch(err){let detail=String(err);if(detail.includes("ELOCKED"))detail="lock timeout (stale lock detected)";else if(detail.includes("ENOSPC"))detail="disk full";else if(detail.includes("EACCES"))detail="permission denied";warnings.push(`Knowledge sweep failed for phase ${phase}: ${detail}`)}let planLockTaskId=`phase-complete-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,planFilePath="plan.json",planLockResult;try{planLockResult=await tryAcquireLock(dir,planFilePath,agentName,planLockTaskId)}catch(error93){return JSON.stringify({success:!1,phase:args2.phase,status:"incomplete",message:`Failed to acquire lock for plan.json: ${error93 instanceof Error?error93.message:String(error93)}`,agentsDispatched,agentsMissing,warnings,errors:[error93 instanceof Error?error93.message:String(error93)],recovery_guidance:"Resolve the filesystem issue (permissions, disk space, or .swarm/locks/ directory) and retry phase_complete."})}if(!planLockResult?.acquired)return JSON.stringify({success:!1,phase:args2.phase,status:"incomplete",message:`Plan write blocked: plan.json is locked by ${planLockResult.existing?.agent??"another agent"}`,agentsDispatched,agentsMissing,warnings,errors:[`Concurrent plan write detected — lock held by ${planLockResult.existing?.agent??"another agent"} (task: ${planLockResult.existing?.taskId??"unknown"})`],recovery_guidance:"Wait a moment and retry phase_complete. The lock will expire automatically if the holding agent fails."});try{let plan=await loadPlan(dir),runtimePlan=plan;if(runtimePlan?._ledgerReplayStale===!0){let staleReason=runtimePlan._ledgerReplayStaleReason??"unknown reason";return JSON.stringify({success:!1,phase:args2.phase,status:"incomplete",message:`Plan write refused: plan.json is stale from a failed ledger replay (${staleReason}). Refusing to complete phase ${args2.phase} against a known-stale plan.`,agentsDispatched,agentsMissing,warnings,errors:[`Stale plan from failed ledger replay: ${staleReason}`],recovery_guidance:"The ledger replay failed and no critic-approved snapshot was available, so loadPlan fell back to a stale plan.json. Do NOT retry blindly. Recover first: re-verify the plan (re-run completion verification), reset the session, or restore from the latest checkpoint under .swarm/plan-export/, then retry phase_complete.",_ledgerReplayStaleReason:staleReason})}if(plan===null){if(await ledgerExists(dir))try{let rebuilt=await replayFromLedger(dir);if(rebuilt){let phaseObj=rebuilt.phases.find((p)=>p.id===phase);if(phaseObj){phaseObj.status="complete",await savePlanWithAutoAcknowledgedRemovals(dir,rebuilt,"phase_complete_rebuild_from_ledger","phase-complete rebuild from ledger");try{await takeSnapshotEvent(dir,rebuilt).catch(()=>{})}catch{}result.success=!0,result.status="success"}}}catch{}warnings.push("Warning: failed to update plan.json phase status");try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs126.readFileSync(planPath,"utf-8"),plan2=JSON.parse(planRaw),phaseObj=plan2.phases.find((p)=>p.id===phase);if(phaseObj)phaseObj.status="complete",await fallbackWritePlanWithTrace(dir,planPath,plan2,phase,warnings)}catch{}}else if(plan){let phaseObj=plan.phases.find((p)=>p.id===phase);if(phaseObj)phaseObj.status="complete",await savePlan(dir,plan,{preserveCompletedStatuses:!0});try{let plan2=await loadPlan(dir);if(plan2)await takeSnapshotEvent(dir,plan2).catch(()=>{})}catch{}}}catch(_error){if(await ledgerExists(dir))try{let rebuilt=await replayFromLedger(dir);if(rebuilt){let phaseObj=rebuilt.phases.find((p)=>p.id===phase);if(phaseObj){phaseObj.status="complete",await savePlanWithAutoAcknowledgedRemovals(dir,rebuilt,"phase_complete_rebuild_from_ledger","phase-complete rebuild from ledger");try{await takeSnapshotEvent(dir,rebuilt).catch(()=>{})}catch{}result.success=!0,result.status="success"}}}catch{}warnings.push("Warning: failed to update plan.json phase status");try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs126.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw),phaseObj=plan.phases.find((p)=>p.id===phase);if(phaseObj)phaseObj.status="complete",await fallbackWritePlanWithTrace(dir,planPath,plan,phase,warnings)}catch{}}finally{if(planLockResult?.acquired&&planLockResult.lock._release)try{await planLockResult.lock._release()}catch(releaseError){warn("[phase_complete] Plan lock release failed (non-blocking):",releaseError instanceof Error?releaseError.message:String(releaseError))}}}if(complianceWarnings.length>0)warnings.push(`Curator compliance: ${complianceWarnings.join("; ")}`);await flushPendingSnapshot(dir),await writeCheckpoint(dir).catch(()=>{});try{let curatorCfg=CuratorConfigSchema.parse(config3.curator??{});if(curatorCfg.enabled&&curatorCfg.postmortem_enabled){let finalPlan=await loadPlan(dir);if(finalPlan?.phases?.length){if(finalPlan.phases.every((p)=>p.status==="complete")){let{runCuratorPostMortem:runCuratorPostMortem2}=await Promise.resolve().then(() => (init_curator_postmortem(),exports_curator_postmortem)),pmResult=await runCuratorPostMortem2(dir,{llmDelegate:createCuratorLLMDelegate(dir,"postmortem",sessionID)});if(pmResult.success&&pmResult.summary)warnings.push(`[POST-MORTEM] ${pmResult.summary}`);if(pmResult.warnings.length>0)for(let w of pmResult.warnings)warnings.push(`[POST-MORTEM] ${w}`)}}}}catch{}let outputData={...result,timestamp:event.timestamp,duration_ms:durationMs};return _buildOutputJson(outputData)}function _buildOutputJson(outputData){let json3=JSON.stringify(outputData,null,2);if(json3.length>MAX_OUTPUT_BYTES6){let truncated={_truncated:!0,_truncation_reason:`Output exceeded MAX_OUTPUT_BYTES (${MAX_OUTPUT_BYTES6}) limit`,phase:outputData.phase,success:outputData.success,status:outputData.status,message:outputData.message,agentsDispatched:outputData.agentsDispatched?.slice(0,10),agentsMissing:outputData.agentsMissing?.slice(0,10),warnings:["(output truncated — full output exceeded size limit)"],timestamp:outputData.timestamp,duration_ms:outputData.duration_ms};json3=JSON.stringify(truncated,null,2)}return json3}var phase_complete=createSwarmTool({description:"Mark a phase as complete and track which agents were dispatched. Used for phase completion gating and tracking. Accepts phase number and optional summary. Returns list of agents that were dispatched.",args:{phase:exports_external.number().int().min(1).describe("The phase number being completed — a positive integer (e.g., 1, 2, 3)"),summary:exports_external.string().optional().describe("Optional summary of what was accomplished in this phase"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root."),accept_violations:exports_external.array(exports_external.string()).optional().describe("ARCHITECT ONLY. Critical knowledge-directive IDs to explicitly accept as unresolved. Requires accept_violations_justification. Each is logged as an override event."),accept_violations_justification:exports_external.string().optional().describe("Written justification required when accept_violations is provided.")},execute:async(args2,directory,ctx)=>{let phaseCompleteArgs,workingDirInput;try{phaseCompleteArgs={phase:Number(args2.phase),summary:args2.summary!==void 0?String(args2.summary):void 0,sessionID:ctx?.sessionID??(args2.sessionID!==void 0?String(args2.sessionID):void 0),acceptViolations:Array.isArray(args2.accept_violations)?args2.accept_violations.map((s)=>String(s)):void 0,acceptViolationsJustification:args2.accept_violations_justification!==void 0?String(args2.accept_violations_justification):void 0,callerAgent:ctx?.agent!==void 0?String(ctx.agent):void 0},workingDirInput=args2.working_directory!==void 0?String(args2.working_directory):void 0}catch{return JSON.stringify({success:!1,phase:0,message:"Invalid arguments",agentsDispatched:[],warnings:["Failed to parse arguments"]},null,2)}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:phaseCompleteArgs.phase,message:dirResult.message,agentsDispatched:[],warnings:[dirResult.message]},null,2);return executePhaseComplete(phaseCompleteArgs,dirResult.directory,dirResult.directory)}});init_zod();init_discovery();init_utils();init_bun_compat();init_create_tool();import*as fs127 from"node:fs";import*as path200 from"node:path";var MAX_OUTPUT_BYTES7=52428800,AUDIT_TIMEOUT_MS=120000;function isValidEcosystem(value){return typeof value==="string"&&["auto","npm","pip","cargo","go","dotnet","ruby","dart","composer"].includes(value)}function validateArgs3(args2){if(typeof args2!=="object"||args2===null)return!0;let obj=args2;if(obj.ecosystem!==void 0&&!isValidEcosystem(obj.ecosystem))return!1;return!0}function detectEcosystems(directory){let ecosystems=[],cwd=directory;if(fs127.existsSync(path200.join(cwd,"package.json")))ecosystems.push("npm");if(fs127.existsSync(path200.join(cwd,"pyproject.toml"))||fs127.existsSync(path200.join(cwd,"requirements.txt")))ecosystems.push("pip");if(fs127.existsSync(path200.join(cwd,"Cargo.toml")))ecosystems.push("cargo");if(fs127.existsSync(path200.join(cwd,"go.mod")))ecosystems.push("go");try{if(fs127.readdirSync(cwd).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))ecosystems.push("dotnet")}catch{}if(fs127.existsSync(path200.join(cwd,"Gemfile"))||fs127.existsSync(path200.join(cwd,"Gemfile.lock")))ecosystems.push("ruby");if(fs127.existsSync(path200.join(cwd,"pubspec.yaml")))ecosystems.push("dart");if(fs127.existsSync(path200.join(cwd,"composer.lock")))ecosystems.push("composer");return ecosystems}async function runNpmAudit(directory){let command=["npm","audit","--json"];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve73)=>setTimeout(()=>resolve73("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:`npm audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES7)stdout=stdout.slice(0,MAX_OUTPUT_BYTES7);if(await proc.exited===0)return{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let jsonOutput=stdout,jsonMatch=stdout.match(/\{[\s\S]*\}/)||stderr.match(/\{[\s\S]*\}/);if(jsonMatch)jsonOutput=jsonMatch[0];let response=JSON.parse(jsonOutput),findings=[];if(response.vulnerabilities)for(let[pkgName,vuln]of Object.entries(response.vulnerabilities)){let patchedVersion=null;if(vuln.fixAvailable&&typeof vuln.fixAvailable==="object")patchedVersion=vuln.fixAvailable.version;else if(vuln.fixAvailable===!0)patchedVersion="latest";let severity=mapNpmSeverity(vuln.severity);findings.push({package:pkgName,installedVersion:vuln.range,patchedVersion,severity,title:vuln.title||`Vulnerability in ${pkgName}`,cve:vuln.cves&&vuln.cves.length>0?vuln.cves[0]:null,url:vuln.url||null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"npm",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";if(errorMessage3.includes("audit")||errorMessage3.includes("command not found")||errorMessage3.includes("'npm' is not recognized"))return{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:"npm audit not available - npm may not be installed"};return{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:`Error running npm audit: ${errorMessage3}`}}}function mapNpmSeverity(severity){switch(severity.toLowerCase()){case"critical":return"critical";case"high":return"high";case"moderate":return"moderate";case"low":return"low";default:return"info"}}async function runPipAudit(directory){let command=["pip-audit","--format=json"];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve73)=>setTimeout(()=>resolve73("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:`pip-audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES7)stdout=stdout.slice(0,MAX_OUTPUT_BYTES7);if(await proc.exited===0&&!stdout.trim())return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let packages=[];try{let parsed=JSON.parse(stdout);if(Array.isArray(parsed))packages=parsed;else if(parsed.dependencies)packages=parsed.dependencies}catch{if(stderr.includes("not installed")||stdout.includes("not installed")||stderr.includes("command not found"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:`pip-audit output could not be parsed: ${stdout.slice(0,200)}`}}let findings=[];for(let pkg of packages)if(pkg.vulns&&pkg.vulns.length>0)for(let vuln of pkg.vulns){let severity=vuln.aliases&&vuln.aliases.length>0?"high":"moderate";findings.push({package:pkg.name,installedVersion:pkg.version,patchedVersion:vuln.fix_versions&&vuln.fix_versions.length>0?vuln.fix_versions[0]:null,severity,title:vuln.id,cve:vuln.aliases&&vuln.aliases.length>0?vuln.aliases[0]:null,url:vuln.id.startsWith("CVE-")?`https://nvd.nist.gov/vuln/detail/${vuln.id}`:null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"pip",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";if(errorMessage3.includes("not found")||errorMessage3.includes("not recognized")||errorMessage3.includes("pip-audit"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:`Error running pip-audit: ${errorMessage3}`}}}async function runCargoAudit(directory){let command=["cargo","audit","--json"];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve73)=>setTimeout(()=>resolve73("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:`cargo audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr:_stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES7)stdout=stdout.slice(0,MAX_OUTPUT_BYTES7);if(await proc.exited===0)return{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let findings=[],lines=stdout.split(`
5739
5774
  `).filter((line)=>line.trim());for(let line of lines)try{let obj=JSON.parse(line);if(obj.vulnerabilities?.list)for(let item of obj.vulnerabilities.list){let cvss=item.advisory.cvss||0,severity=mapCargoSeverity(cvss);findings.push({package:item.advisory.package,installedVersion:item.package.version,patchedVersion:item.versions.patched&&item.versions.patched.length>0?item.versions.patched[0]:null,severity,title:item.advisory.title,cve:item.advisory.aliases&&item.advisory.aliases.length>0?item.advisory.aliases[0]:item.advisory.id?item.advisory.id:null,url:item.advisory.url||null})}}catch{}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"cargo",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";if(errorMessage3.includes("not found")||errorMessage3.includes("not recognized")||errorMessage3.includes("cargo-audit"))return{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:"cargo-audit not installed. Install with: cargo install cargo-audit"};return{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:`Error running cargo audit: ${errorMessage3}`}}}function mapCargoSeverity(cvss){if(cvss>=9)return"critical";if(cvss>=7)return"high";if(cvss>=4)return"moderate";return"low"}async function runGoAudit(directory){let command=["govulncheck","-json","./..."];if(!isCommandAvailable("govulncheck"))return warn("[pkg-audit] govulncheck not found, skipping Go audit"),{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:"govulncheck not installed. Install with: go install golang.org/x/vuln/cmd/govulncheck@latest"};try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve73)=>setTimeout(()=>resolve73("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:`govulncheck timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES7)stdout=stdout.slice(0,MAX_OUTPUT_BYTES7);let exitCode=await proc.exited;if(exitCode!==0&&exitCode!==3)return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:`govulncheck exited with code ${exitCode}`};if(exitCode===0)return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let osvMap=new Map,goFindings=[],lines=stdout.split(`
5740
5775
  `).filter((line)=>line.trim());for(let line of lines)try{let obj=JSON.parse(line);if(obj.osv)osvMap.set(obj.osv.id,obj.osv);if(obj.finding)goFindings.push(obj.finding)}catch{}let findings=[];for(let finding of goFindings){let osv=osvMap.get(finding.osv),severity=osv?.aliases?.some((a)=>a.startsWith("CVE-"))??!1?"high":"moderate",cve=osv?.aliases?.find((a)=>a.startsWith("CVE-"))??null,url3=osv?.references?.find((r)=>r.type==="WEB")?.url??`https://pkg.go.dev/vuln/${finding.osv}`,trace0=finding.trace[0],pkgName=trace0?.module??finding.osv,installedVersion=trace0?.version??"unknown";findings.push({package:pkgName,installedVersion,patchedVersion:finding.fixed_by??null,severity,title:osv?.summary??finding.osv,cve,url:url3})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"go",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:`Error running govulncheck: ${errorMessage3}`}}}async function runDotnetAudit(directory){let command=["dotnet","list","package","--vulnerable","--include-transitive"];if(!isCommandAvailable("dotnet"))return warn("[pkg-audit] dotnet not found, skipping .NET audit"),{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:"dotnet CLI not installed. Install from: https://dotnet.microsoft.com/download"};try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve73)=>setTimeout(()=>resolve73("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:`dotnet list package timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES7)stdout=stdout.slice(0,MAX_OUTPUT_BYTES7);let exitCode=await proc.exited;if(exitCode!==0&&!stdout.includes("has the following vulnerable packages"))return{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:`dotnet list package exited with code ${exitCode}`};let vulnLinePattern=/^\s*>\s+(\S+)\s+\S+\s+(\S+)\s+(Critical|High|Moderate|Low)\s+(\S+)/i,findings=[],lines=stdout.split(`
@@ -5791,7 +5826,7 @@ ${paginatedContent}`;if(endLine<totalLines){let remaining=totalLines-endLine;res
5791
5826
  `);for(let i=0;i<lines.length;i++){let line=lines[i];if(regex.test(line)){if(total++,matches.length<opts.maxResults)matches.push({file:file3,lineNumber:i+1,lineText:truncateLine(line,opts.maxLines)});regex.lastIndex=0}}}return{matches,truncated:truncated||total>opts.maxResults,total,query:opts.query,mode:opts.mode,maxResults:opts.maxResults,engine:"fallback",warning:"Fallback search uses bounded filesystem traversal and does not fully emulate ripgrep gitignore behavior."}}var search=createSwarmTool({description:"Search for text within workspace files using ripgrep-style interface. Supports literal and regex search modes with glob include/exclude filtering. Returns structured JSON output with file paths, line numbers, and line content.",args:{query:exports_external.string().describe("Search query string (literal or regex depending on mode)"),mode:exports_external.enum(["literal","regex"]).default("literal").describe("Search mode: literal for exact string match, regex for regular expression"),include:exports_external.string().optional().describe('Glob pattern for files to include (e.g., "*.ts", "src/**/*.js")'),exclude:exports_external.string().optional().describe('Glob pattern for files to exclude (e.g., "node_modules/**", "*.test.ts")'),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS4).describe("Maximum number of matches to return"),max_lines:exports_external.number().default(DEFAULT_MAX_LINES).describe("Maximum characters per line in results")},execute:async(args2,directory)=>{let query,mode="literal",include,exclude,maxResults=DEFAULT_MAX_RESULTS4,maxLines=DEFAULT_MAX_LINES;try{let obj=args2;query=String(obj.query??""),mode=obj.mode==="regex"?"regex":"literal",include=typeof obj.include==="string"?obj.include:void 0,exclude=typeof obj.exclude==="string"?obj.exclude:void 0;let rawMaxResults=typeof obj.max_results==="number"?obj.max_results:DEFAULT_MAX_RESULTS4,sanitizedMaxResults=Number.isNaN(rawMaxResults)?DEFAULT_MAX_RESULTS4:rawMaxResults;maxResults=Math.min(Math.max(0,sanitizedMaxResults),HARD_CAP_RESULTS4);let rawMaxLines=typeof obj.max_lines==="number"?obj.max_lines:DEFAULT_MAX_LINES,sanitizedMaxLines=Number.isNaN(rawMaxLines)?DEFAULT_MAX_LINES:rawMaxLines;maxLines=Math.min(Math.max(0,sanitizedMaxLines),HARD_CAP_LINES)}catch{return JSON.stringify({error:!0,type:"invalid-query",message:"Could not parse search arguments"},null,2)}if(!query||query.trim()==="")return JSON.stringify({error:!0,type:"invalid-query",message:"Query cannot be empty"},null,2);if(query.length>MAX_QUERY_LENGTH)return JSON.stringify({error:!0,type:"invalid-query",message:`Query exceeds maximum length of ${MAX_QUERY_LENGTH} characters`},null,2);if(containsControlChars(query))return JSON.stringify({error:!0,type:"invalid-query",message:"Query contains invalid control characters"},null,2);if(include&&containsPathTraversal(include))return JSON.stringify({error:!0,type:"path-escape",message:"Include pattern contains path traversal sequence"},null,2);if(exclude&&containsPathTraversal(exclude))return JSON.stringify({error:!0,type:"path-escape",message:"Exclude pattern contains path traversal sequence"},null,2);if(include&&containsWindowsAttacks4(include))return JSON.stringify({error:!0,type:"path-escape",message:"Include pattern contains invalid Windows-specific sequence"},null,2);if(exclude&&containsWindowsAttacks4(exclude))return JSON.stringify({error:!0,type:"path-escape",message:"Exclude pattern contains invalid Windows-specific sequence"},null,2);if(!fs137.existsSync(directory))return JSON.stringify({error:!0,type:"unknown",message:"Workspace directory does not exist"},null,2);let result;if(_internals125.resolveRipgrepBinary())result=await ripgrepSearch({query,mode,include,exclude,maxResults,maxLines,workspace:directory});else result=await fallbackSearch({query,mode,include,exclude,maxResults,maxLines,workspace:directory});if("error"in result&&result.error)return JSON.stringify(result,null,2);return JSON.stringify(result,null,2)}}),_internals125={resolvePackagedRipgrep,resolveExecutableFromPath,resolveRipgrepBinary,runExternalTool,fallbackSearch};init_secretscan();init_zod();init_qa_gate_profile();init_manager();init_utils3();init_create_tool();async function executeSetQaGates(args2,directory){let plan=await loadPlanJsonOnly(directory);if(!plan)return{success:!1,reason:"plan_json_unavailable",message:"Cannot configure QA gates: plan.json is missing or invalid. Create a plan first (e.g. via /swarm specify or save_plan)."};let planId=derivePlanId(plan);getOrCreateProfile(directory,planId,args2.project_type);let partial3={};for(let key of["reviewer","test_engineer","council_mode","sme_enabled","critic_pre_plan","hallucination_guard","sast_enabled","mutation_test","phase_council","drift_check","final_council"])if(args2[key]!==void 0)partial3[key]=args2[key];try{let updated=setGates(directory,planId,partial3);return{success:!0,plan_id:planId,message:`QA gates updated for plan_id=${planId}`,profile:{plan_id:updated.plan_id,gates:{...updated.gates},locked_at:updated.locked_at,locked_by_snapshot_seq:updated.locked_by_snapshot_seq,profile_hash:computeProfileHash(updated)}}}catch(err2){let msg=err2 instanceof Error?err2.message:String(err2),lower=msg.toLowerCase(),reason="set_gates_failed";if(lower.includes("locked"))reason="profile_locked";else if(lower.includes("ratchet"))reason="ratchet_violation";return{success:!1,reason,message:msg,plan_id:planId}}}var set_qa_gates=createSwarmTool({description:"Configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter: can enable additional gates but cannot disable gates that are already enabled. Rejects all writes once the profile is locked (after critic approval). Creates the profile with defaults if none exists. plan_id is derived automatically from plan.json.",args:{reviewer:exports_external.boolean().optional().describe("Enable the reviewer gate (true) — cannot be disabled."),test_engineer:exports_external.boolean().optional().describe("Enable the test_engineer gate (true) — cannot be disabled once on."),council_mode:exports_external.boolean().optional().describe("Enable council mode — replaces per-task Stage B (reviewer + test_engineer) with the full 5-member council (critic, reviewer, sme, test_engineer, explorer) per task."),sme_enabled:exports_external.boolean().optional().describe("Enable SME consultation."),critic_pre_plan:exports_external.boolean().optional().describe("Enable critic_pre_plan review before plan approval."),hallucination_guard:exports_external.boolean().optional().describe("Enable hallucination_guard checks on plan and implementation claims."),sast_enabled:exports_external.boolean().optional().describe("Enable SAST scanning as a required QA gate."),mutation_test:exports_external.boolean().optional().describe("Enable the mutation-testing gate (default: off). Requires mutation tests to achieve a passing kill rate before phase completion; WARN verdict allows advancement, FAIL blocks."),phase_council:exports_external.boolean().optional().describe("Enable the phase_council gate (default: off). When on, a full 5-member council (critic, reviewer, sme, test_engineer, explorer) reviews all work completed in a phase holistically at phase_complete time. Requires council.enabled: true in config."),drift_check:exports_external.boolean().optional().describe("Enable drift verification gate (default: on). Blocks phase_complete until drift-verifier.json has an approved verdict. When disabled, drift verification is skipped entirely."),final_council:exports_external.boolean().optional().describe("Enable the final_council gate (default: off). When on, after all phases complete the architect dispatches critic, reviewer, sme, test_engineer, and explorer with project-scoped context, collects their CouncilMemberVerdict objects, and calls write_final_council_evidence. This is not General Council mode and does not require council.general.enabled."),project_type:exports_external.string().optional().describe('Project type label (e.g. "ts", "python"). Only applied when the profile is being created for the first time.')},execute:async(args2,directory)=>{return JSON.stringify(await executeSetQaGates(args2??{},directory),null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_apply=createSwarmTool({description:"Activate a draft skill proposal (.swarm/skills/proposals/<slug>.md) into .opencode/skills/generated/<slug>/SKILL.md.",args:{slug:exports_external.string().min(1).describe("Slug of the proposal to activate."),force:exports_external.boolean().optional().default(!1).describe("Overwrite an existing active SKILL.md even if it lacks the generator stamp. Default false."),evaluate:exports_external.boolean().optional().default(!1).describe("Validate the proposal against .swarm/skills/evals/<slug> before activation. Default false.")},execute:async(args2,directory)=>{let a=args2??{};if(!a.slug||typeof a.slug!=="string")return JSON.stringify({activated:!1,reason:"slug required"});let result=await activateProposal(directory,a.slug,a.force??!1,{evaluate:a.evaluate??!1});return JSON.stringify(result,null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_generate=createSwarmTool({description:'Compile mature knowledge entries into a SKILL.md. mode="draft" writes a proposal under .swarm/skills/proposals; mode="active" writes the live skill under .opencode/skills/generated and stamps source entries.',args:{source_knowledge_ids:exports_external.array(exports_external.string()).optional().describe("Optional explicit knowledge ids to compile. If omitted, all mature candidates are clustered and emitted."),slug:exports_external.string().optional().describe("Optional slug for the FIRST cluster. Sanitized; rejected if invalid."),mode:exports_external.enum(["draft","active"]).default("draft"),force:exports_external.boolean().optional().default(!1),evaluate:exports_external.boolean().optional().default(!1).describe("Validate generated skill content against .swarm/skills/evals/<slug> before writing. Default false."),min_confidence:exports_external.number().min(0).max(1).optional(),min_confirmations:exports_external.number().int().min(1).max(50).optional()},execute:async(args2,directory)=>{let a=args2??{},result=await generateSkills({directory,mode:a.mode??"draft",slug:a.slug,sourceKnowledgeIds:a.source_knowledge_ids,force:a.force??!1,evaluate:a.evaluate??!1,minConfidence:a.min_confidence,minConfirmations:a.min_confirmations});return JSON.stringify(result,null,2)}});init_zod();init_config();init_schema();init_skill_improver();init_create_tool();var skill_improve=createSwarmTool({description:'Run the skill_improver capability under daily quota. Writes a proposal under .swarm/skill-improver/proposals/<timestamp>.md. With mode="draft_skills" it also drafts SKILL.md proposals for mature clusters. Quota is enforced via .swarm/skill-improver-quota.json.',args:{targets:exports_external.array(exports_external.enum(["skills","spec","architect_prompt","knowledge"])).optional(),mode:exports_external.enum(["proposal","draft_skills"]).optional(),max_calls:exports_external.number().int().min(1).max(100).optional().describe("Override the per-run reservation count (capped by daily max)."),evaluate:exports_external.boolean().optional().default(!1).describe('When mode="draft_skills", validate generated draft skills before writing proposals. Default false.')},execute:async(args2,directory,ctx)=>{let a=args2??{},{config:config3}=loadPluginConfigWithMeta(directory),parsed=SkillImproverConfigSchema.parse(config3.skill_improver??{}),enrichmentConfig=KnowledgeConfigSchema.parse(config3.knowledge??{}).enrichment??{max_calls_per_day:30,quota_window:"utc"};if(!parsed.enabled)return JSON.stringify({ran:!1,reason:'skill_improver is disabled. Set "skill_improver.enabled": true in opencode-swarm config to use this tool.'},null,2);let result=await runSkillImprover({directory,config:parsed,targets:a.targets,mode:a.mode,maxCalls:a.max_calls,sessionId:ctx?.sessionID,enrichmentQuota:{maxCalls:enrichmentConfig.max_calls_per_day,window:enrichmentConfig.quota_window},evaluateDrafts:a.evaluate??!1});return JSON.stringify(result,null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_inspect=createSwarmTool({description:"Read a generated skill (active or draft) and return its full markdown body and metadata.",args:{slug:exports_external.string().min(1).describe("Slug of the skill to inspect."),prefer:exports_external.enum(["auto","proposal","active"]).optional().default("auto")},execute:async(args2,directory)=>{let a=args2??{};if(!a.slug||typeof a.slug!=="string")return JSON.stringify({found:!1,reason:"slug required"});let result=await inspectSkill(directory,a.slug,a.prefer??"auto");return JSON.stringify(result,null,2)}});init_skill_generator();init_create_tool();var skill_list=createSwarmTool({description:"List generated skill drafts (under .swarm/skills/proposals) and active generated skills (under .opencode/skills/generated).",args:{},execute:async(_args,directory)=>{let result=await listSkills(directory);return JSON.stringify(result,null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_regenerate=createSwarmTool({description:"Regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place.",args:{slug:exports_external.string().min(1).describe("Slug of the active skill to regenerate."),evaluate:exports_external.boolean().optional().default(!1).describe("Validate regenerated content against .swarm/skills/evals/<slug> before writing. Default false.")},execute:async(args2,directory)=>{let a=args2??{};if(!a.slug||typeof a.slug!=="string")return JSON.stringify({regenerated:!1,reason:"slug required"});let result=await regenerateSkill(directory,a.slug,{evaluate:a.evaluate??!1});return JSON.stringify(result,null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_retire=createSwarmTool({description:"Retire a generated skill by adding a retired.marker file. Retired skills are excluded from scoring and injection.",args:{slug:exports_external.string().min(1).describe("Slug of the active skill to retire."),reason:exports_external.string().optional().describe("Optional reason for retirement.")},execute:async(args2,directory)=>{let a=args2??{};if(!a.slug||typeof a.slug!=="string")return JSON.stringify({retired:!1,reason:"slug required"});let result=await retireSkill(directory,a.slug,a.reason);return JSON.stringify(result,null,2)}});init_zod();init_config();init_schema();init_create_tool();import{mkdir as mkdir34,rename as rename14,writeFile as writeFile23}from"node:fs/promises";import*as path212 from"node:path";var MAX_SPEC_BYTES2=262144,spec_write=createSwarmTool({description:"Write the canonical project spec to .swarm/spec.md. Atomic write, size-bounded (256 KiB), heading-required. Honors spec_writer.allow_spec_write.",args:{content:exports_external.string().min(20).max(MAX_SPEC_BYTES2),mode:exports_external.enum(["replace","append"]).optional().default("replace")},execute:async(args2,directory)=>{let a=args2??{},content=a.content,mode=a.mode??"replace";if(typeof content!=="string"||content.length<20)return JSON.stringify({written:!1,reason:"content must be a string >=20 chars"});if(content.length>MAX_SPEC_BYTES2)return JSON.stringify({written:!1,reason:`content exceeds ${MAX_SPEC_BYTES2} bytes`});let{config:config3}=loadPluginConfigWithMeta(directory);if(!SpecWriterConfigSchema.parse(config3.spec_writer??{}).allow_spec_write)return JSON.stringify({written:!1,reason:"spec_writer.allow_spec_write is false"},null,2);if(content.indexOf("\x00")!==-1)return JSON.stringify({written:!1,reason:"content contains null byte"},null,2);if(!/^#\s+/m.test(content))return JSON.stringify({written:!1,reason:'spec must contain at least one top-level "# Heading"'},null,2);let target=path212.join(directory,".swarm","spec.md");await mkdir34(path212.dirname(target),{recursive:!0});let tmp=`${target}.tmp-${process.pid}-${Date.now()}`,finalContent=content;if(mode==="append")try{if(finalContent=`${(await(await import("node:fs/promises")).readFile(target,"utf-8")).replace(/\s+$/,"")}
5792
5827
 
5793
5828
  ${content}
5794
- `,finalContent.length>MAX_SPEC_BYTES2)return JSON.stringify({written:!1,reason:"append would exceed max spec size (256 KiB); rewrite explicitly"},null,2)}catch{}return await writeFile23(tmp,finalContent,"utf-8"),await rename14(tmp,target),JSON.stringify({written:!0,path:target,bytes:finalContent.length},null,2)}});init_zod();init_knowledge_store();init_skill_generator();init_create_tool();import{existsSync as existsSync120}from"node:fs";import{readdir as readdir12,readFile as readFile33}from"node:fs/promises";import{join as join171}from"node:path";var run_stale_reconciliation=createSwarmTool({description:"Reconcile skills against the knowledge store. clear=false: mark skills stale when source knowledge is archived or deleted. clear=true: clear stale.marker on affected active skills (proposal files under .swarm/skills/proposals are scanned but not modified — they are drafts, not yet active skills).",args:{clear:exports_external.boolean().optional().default(!1).describe("If true, clear stale markers for affected skills. If false (default), mark affected skills stale.")},execute:async(args2,directory)=>{if(typeof directory!=="string"||!directory)return JSON.stringify({found:0,skills:[]},null,2);let archivedIds=await _internals126.getArchivedKnowledgeIds(directory),archivedSet=new Set(archivedIds),allKnownIds=new Set,swarmPath=_internals126.resolveSwarmKnowledgePath(directory),hivePath=_internals126.resolveHiveKnowledgePath();try{let swarmEntries=await _internals126.readKnowledge(swarmPath);for(let e of swarmEntries)allKnownIds.add(e.id)}catch{}try{let hiveEntries=await _internals126.readKnowledge(hivePath);for(let e of hiveEntries)allKnownIds.add(e.id)}catch{}let skillEntries=[];for(let dir of[join171(directory,".opencode","skills","generated"),join171(directory,".swarm","skills","proposals")]){if(!_internals126.existsSync(dir))continue;let entries=await _internals126.readdir(dir,{withFileTypes:!0});for(let entry of entries)if(entry.isDirectory())skillEntries.push({slug:entry.name,path:join171(dir,entry.name),isProposal:!1});else if(entry.name.endsWith(".md")){let slug=entry.name.replace(/\.md$/,"");skillEntries.push({slug,path:join171(dir,entry.name),isProposal:!0})}}let results=[];for(let{slug,path:path213,isProposal}of skillEntries){let skillMdPath=isProposal?path213:join171(path213,"SKILL.md");if(!_internals126.existsSync(skillMdPath))continue;let content=await _internals126.readFile(skillMdPath,"utf-8"),sourceIds=_internals126.parseDraftFrontmatter(content)?.sourceKnowledgeIds??[];if(sourceIds.length===0)continue;let affected=sourceIds.filter((id)=>archivedSet.has(id)||!allKnownIds.has(id));if(affected.length===0)continue;if(args2.clear){if(!isProposal){let markerPath=join171(path213,"stale.marker");if(_internals126.existsSync(markerPath))try{await _internals126.clearSkillStale(path213),results.push({slug,reason:affected.join(", "),action:"cleared"})}catch{}}}else if(!isProposal)try{await _internals126.retireOrMarkStale(directory,path213,archivedSet),results.push({slug,reason:affected.join(", "),action:"marked_stale"})}catch{}}return JSON.stringify({found:results.length,skills:results},null,2)}}),_internals126={run_stale_reconciliation,clearSkillStale,retireOrMarkStale,parseDraftFrontmatter,getArchivedKnowledgeIds,readKnowledge,resolveSwarmKnowledgePath,resolveHiveKnowledgePath,readdir:readdir12,readFile:readFile33,existsSync:existsSync120};init_zod();init_loader();import{existsSync as existsSync121,mkdirSync as mkdirSync53,readFileSync as readFileSync91,renameSync as renameSync32,unlinkSync as unlinkSync30,writeFileSync as writeFileSync36}from"node:fs";import path213 from"node:path";init_create_tool();init_resolve_working_directory();var VerdictSchema2=exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema4=exports_external.object({phaseNumber:exports_external.number().int().min(1),swarmId:exports_external.string().min(1),phaseSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema2).min(1).max(5),working_directory:exports_external.string().optional(),provenanceAgentName:exports_external.string().min(1).optional(),provenanceSessionId:exports_external.string().min(1).optional()}),submit_phase_council_verdicts=createSwarmTool({description:"Submit pre-collected council member verdicts for PHASE-LEVEL synthesis. "+"PREREQUISITE — you MUST dispatch each council member (critic, reviewer, sme, "+"test_engineer, explorer) as separate Agent tasks with PHASE-SCOPED context and collect their verdict responses BEFORE calling this tool. This tool performs "+"synthesis only — it does NOT dispatch, invoke, or contact council members. "+"Writes .swarm/evidence/{phase}/phase-council.json which is required by phase_complete Gate 5 when phase_council is enabled. Architect-only. Config-gated via council.enabled.",args:{phaseNumber:exports_external.number().int().min(1).describe("Phase number being reviewed (e.g. 1, 2, 3)"),swarmId:exports_external.string().min(1).describe('Swarm identifier, e.g. "mega"'),phaseSummary:exports_external.string().min(1).describe("2–4 sentence summary of what the phase accomplished"),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed round number. Defaults to 1."),verdicts:exports_external.array(exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number()})).min(1).max(5).describe("Collected CouncilMemberVerdict objects from all dispatched council members"),working_directory:exports_external.string().optional().describe("Working directory where the plan is located"),provenanceAgentName:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)"),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance)")},async execute(args2,directory){let parsed=ArgsSchema4.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let input=parsed.data,dirResult=resolveWorkingDirectory(input.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,config3=loadPluginConfig(workingDir);if(!config3.council?.enabled)return JSON.stringify({success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},null,2);let effectiveMinimum=config3.council?.requireAllMembers?5:config3.council?.minimumMembers??3,ALL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],distinctMembers=new Set(input.verdicts.map((v)=>v.agent)),membersVoted=[...distinctMembers],membersAbsent=ALL_MEMBERS.filter((m)=>!distinctMembers.has(m));if(membersVoted.length<effectiveMinimum)return JSON.stringify({success:!1,reason:"insufficient_quorum",message:`Phase council quorum not met: ${membersVoted.length} of ${effectiveMinimum} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members with phase-scoped context and collect their verdicts before calling submit_phase_council_verdicts.`,membersVoted,membersAbsent,quorumRequired:effectiveMinimum},null,2);let staleVerdicts=(input.roundNumber??1)>1?input.verdicts.filter((v)=>(v.verdictRound??1)<(input.roundNumber??1)):[];if(staleVerdicts.length>0)return JSON.stringify({success:!1,reason:"stale_verdict_detected",message:`Round ${input.roundNumber??1} requires fresh verdicts. One or more submitted verdicts are from an older round.`,staleVerdicts:staleVerdicts.map((v)=>({agent:v.agent,verdictRound:v.verdictRound}))},null,2);let synthesis=synthesizePhaseCouncilAdvisory(input.phaseNumber,input.phaseSummary,input.verdicts,input.roundNumber??1,config3.council,workingDir),mutationGapFinding=input.verdicts.some((verdict)=>verdict.findings.some((finding)=>finding.category==="mutation_gap"))?null:getPhaseMutationGapFinding(input.phaseNumber,workingDir);if(mutationGapFinding){if(addMutationGapFindingToSynthesis(synthesis,mutationGapFinding),mutationGapFinding.severity==="CRITICAL"||mutationGapFinding.severity==="HIGH")synthesis.blockingConcernsCount++}if(synthesis.blockingConcernsCount>0)return JSON.stringify({success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Phase council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the phase can complete. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},null,2);let provenance=input.provenanceAgentName||input.provenanceSessionId?{agent_name:input.provenanceAgentName,session_id:input.provenanceSessionId,captured_at:new Date().toISOString()}:void 0;return writePhaseCouncilEvidence(workingDir,synthesis,provenance),JSON.stringify({success:!0,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes?.length??0,advisoryFindingsCount:synthesis.advisoryFindings?.length??0,unresolvedConflictsCount:synthesis.unresolvedConflicts?.length??0,advisoryNotes:synthesis.advisoryNotes??[],mutationGapEmitted:mutationGapFinding!==null,membersVoted,membersAbsent,quorumSize:membersVoted.length,quorumMet:!0,evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd},null,2)}});function getPhaseMutationGapFinding(phaseNumber,workingDir){let mutationGatePath=path213.join(workingDir,".swarm","evidence",String(phaseNumber),"mutation-gate.json");try{let raw=readFileSync91(mutationGatePath,"utf-8"),gateEntry=(JSON.parse(raw).entries??[]).find((entry)=>entry?.type==="mutation-gate");if(!gateEntry)return{severity:"HIGH",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate evidence is missing a mutation-gate entry for this phase.",evidence:'Expected entries[].type="mutation-gate" with verdict in mutation-gate.json.'};if(gateEntry.verdict==="skip")return{severity:"MEDIUM",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation testing was skipped for this phase; coverage is unverified.",evidence:'mutation-gate.json recorded verdict="skip". Run mutation_test and write_mutation_evidence.'};if(gateEntry.verdict==="warn")return{severity:"LOW",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate reported WARN; mutation coverage may be insufficient.",evidence:'mutation-gate.json recorded verdict="warn" indicating below-pass mutation quality.'};if(gateEntry.verdict==="fail")return{severity:"HIGH",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate reported FAIL; mutation testing quality is below the required threshold.",evidence:'mutation-gate.json recorded verdict="fail" indicating insufficient mutation kill rate.'};return null}catch(error93){if(error93.code==="ENOENT")return{severity:"HIGH",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate evidence file is missing for this phase, so mutation coverage cannot be verified.",evidence:"No .swarm/evidence/{phase}/mutation-gate.json was found at council synthesis time."};return{severity:"MEDIUM",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate evidence could not be read, so mutation coverage cannot be verified.",evidence:error93 instanceof Error?error93.message:String(error93)}}}function writePhaseCouncilEvidence(workingDir,synthesis,provenance){let evidenceDir=path213.join(workingDir,".swarm","evidence",String(synthesis.phaseNumber));mkdirSync53(evidenceDir,{recursive:!0});let evidenceFile=path213.join(evidenceDir,"phase-council.json"),evidenceBundle={entries:[{type:"phase-council",phase_number:synthesis.phaseNumber,scope:"phase",timestamp:synthesis.timestamp,verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,phaseSummary:synthesis.phaseSummary??"",requiredFixes:synthesis.requiredFixes.map((finding)=>({severity:finding.severity,category:finding.category,location:finding.location,detail:finding.detail,evidence:finding.evidence})),advisoryNotes:synthesis.advisoryNotes,advisoryFindings:synthesis.advisoryFindings.map((finding)=>({severity:finding.severity,category:finding.category,location:finding.location,detail:finding.detail,evidence:finding.evidence})),roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,...provenance?{provenance}:{}}]},tempFile=`${evidenceFile}.tmp-${Date.now()}`;try{writeFileSync36(tempFile,JSON.stringify(evidenceBundle,null,2),"utf-8"),renameSync32(tempFile,evidenceFile)}finally{if(existsSync121(tempFile))unlinkSync30(tempFile)}}function addMutationGapFindingToSynthesis(synthesis,finding){if(finding.severity==="CRITICAL"||finding.severity==="HIGH"||finding.severity==="MEDIUM")synthesis.requiredFixes.push(finding);else synthesis.advisoryFindings.push(finding);synthesis.unifiedFeedbackMd+=formatMutationGapFeedback(finding)}function formatMutationGapFeedback(finding){return`
5829
+ `,finalContent.length>MAX_SPEC_BYTES2)return JSON.stringify({written:!1,reason:"append would exceed max spec size (256 KiB); rewrite explicitly"},null,2)}catch{}return await writeFile23(tmp,finalContent,"utf-8"),await rename14(tmp,target),JSON.stringify({written:!0,path:target,bytes:finalContent.length},null,2)}});init_zod();init_knowledge_store();init_skill_generator();init_create_tool();import{existsSync as existsSync120}from"node:fs";import{readdir as readdir12,readFile as readFile33}from"node:fs/promises";import{join as join171}from"node:path";var run_stale_reconciliation=createSwarmTool({description:"Reconcile skills against the knowledge store. clear=false: mark skills stale when source knowledge is archived or deleted. clear=true: clear stale.marker on affected active skills (proposal files under .swarm/skills/proposals are scanned but not modified — they are drafts, not yet active skills).",args:{clear:exports_external.boolean().optional().default(!1).describe("If true, clear stale markers for affected skills. If false (default), mark affected skills stale.")},execute:async(args2,directory)=>{if(typeof directory!=="string"||!directory)return JSON.stringify({found:0,skills:[]},null,2);let archivedIds=await _internals126.getArchivedKnowledgeIds(directory),archivedSet=new Set(archivedIds),allKnownIds=new Set,swarmPath=_internals126.resolveSwarmKnowledgePath(directory),hivePath=_internals126.resolveHiveKnowledgePath();try{let swarmEntries=await _internals126.readKnowledge(swarmPath);for(let e of swarmEntries)allKnownIds.add(e.id)}catch{}try{let hiveEntries=await _internals126.readKnowledge(hivePath);for(let e of hiveEntries)allKnownIds.add(e.id)}catch{}let skillEntries=[];for(let dir of[join171(directory,".opencode","skills","generated"),join171(directory,".swarm","skills","proposals")]){if(!_internals126.existsSync(dir))continue;let entries=await _internals126.readdir(dir,{withFileTypes:!0});for(let entry of entries)if(entry.isDirectory())skillEntries.push({slug:entry.name,path:join171(dir,entry.name),isProposal:!1});else if(entry.name.endsWith(".md")){let slug=entry.name.replace(/\.md$/,"");skillEntries.push({slug,path:join171(dir,entry.name),isProposal:!0})}}let results=[];for(let{slug,path:path213,isProposal}of skillEntries){let skillMdPath=isProposal?path213:join171(path213,"SKILL.md");if(!_internals126.existsSync(skillMdPath))continue;let content=await _internals126.readFile(skillMdPath,"utf-8"),sourceIds=_internals126.parseDraftFrontmatter(content)?.sourceKnowledgeIds??[];if(sourceIds.length===0)continue;let affected=sourceIds.filter((id)=>archivedSet.has(id)||!allKnownIds.has(id));if(affected.length===0)continue;if(args2.clear){if(!isProposal){let markerPath=join171(path213,"stale.marker");if(_internals126.existsSync(markerPath))try{await _internals126.clearSkillStale(path213),results.push({slug,reason:affected.join(", "),action:"cleared"})}catch{}}}else if(!isProposal)try{await _internals126.retireOrMarkStale(directory,path213,archivedSet),results.push({slug,reason:affected.join(", "),action:"marked_stale"})}catch{}}return JSON.stringify({found:results.length,skills:results},null,2)}}),_internals126={run_stale_reconciliation,clearSkillStale,retireOrMarkStale,parseDraftFrontmatter,getArchivedKnowledgeIds,readKnowledge,resolveSwarmKnowledgePath,resolveHiveKnowledgePath,readdir:readdir12,readFile:readFile33,existsSync:existsSync120};init_zod();init_loader();import{existsSync as existsSync121,mkdirSync as mkdirSync53,readFileSync as readFileSync91,renameSync as renameSync32,unlinkSync as unlinkSync30,writeFileSync as writeFileSync36}from"node:fs";import path213 from"node:path";init_reward();init_state2();init_create_tool();init_resolve_working_directory();var VerdictSchema2=exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative(),sessionId:exports_external.string().min(1).optional()}),ArgsSchema4=exports_external.object({phaseNumber:exports_external.number().int().min(1),swarmId:exports_external.string().min(1),phaseSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema2).min(1).max(5),working_directory:exports_external.string().optional(),provenanceAgentName:exports_external.string().min(1).optional(),provenanceSessionId:exports_external.string().min(1).optional()}),submit_phase_council_verdicts=createSwarmTool({description:"Submit pre-collected council member verdicts for PHASE-LEVEL synthesis. "+"PREREQUISITE — you MUST dispatch each council member (critic, reviewer, sme, "+"test_engineer, explorer) as separate Agent tasks with PHASE-SCOPED context and collect their verdict responses BEFORE calling this tool. This tool performs "+"synthesis only — it does NOT dispatch, invoke, or contact council members. "+"Writes .swarm/evidence/{phase}/phase-council.json which is required by phase_complete Gate 5 when phase_council is enabled. Architect-only. Config-gated via council.enabled.",args:{phaseNumber:exports_external.number().int().min(1).describe("Phase number being reviewed (e.g. 1, 2, 3)"),swarmId:exports_external.string().min(1).describe('Swarm identifier, e.g. "mega"'),phaseSummary:exports_external.string().min(1).describe("2–4 sentence summary of what the phase accomplished"),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed round number. Defaults to 1."),verdicts:exports_external.array(exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number(),sessionId:exports_external.string().min(1).optional().describe("Session id of the dispatched agent that produced this verdict, if known — used so this member's own recall bundle is rewarded, not just the submitting session's.")})).min(1).max(5).describe("Collected CouncilMemberVerdict objects from all dispatched council members"),working_directory:exports_external.string().optional().describe("Working directory where the plan is located"),provenanceAgentName:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)"),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance)")},async execute(args2,directory,ctx){let parsed=ArgsSchema4.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let input=parsed.data,dirResult=resolveWorkingDirectory(input.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,config3=loadPluginConfig(workingDir);if(!config3.council?.enabled)return JSON.stringify({success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},null,2);let effectiveMinimum=config3.council?.requireAllMembers?5:config3.council?.minimumMembers??3,ALL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],distinctMembers=new Set(input.verdicts.map((v)=>v.agent)),membersVoted=[...distinctMembers],membersAbsent=ALL_MEMBERS.filter((m)=>!distinctMembers.has(m));if(membersVoted.length<effectiveMinimum)return JSON.stringify({success:!1,reason:"insufficient_quorum",message:`Phase council quorum not met: ${membersVoted.length} of ${effectiveMinimum} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members with phase-scoped context and collect their verdicts before calling submit_phase_council_verdicts.`,membersVoted,membersAbsent,quorumRequired:effectiveMinimum},null,2);let staleVerdicts=(input.roundNumber??1)>1?input.verdicts.filter((v)=>(v.verdictRound??1)<(input.roundNumber??1)):[];if(staleVerdicts.length>0)return JSON.stringify({success:!1,reason:"stale_verdict_detected",message:`Round ${input.roundNumber??1} requires fresh verdicts. One or more submitted verdicts are from an older round.`,staleVerdicts:staleVerdicts.map((v)=>({agent:v.agent,verdictRound:v.verdictRound}))},null,2);let synthesis=synthesizePhaseCouncilAdvisory(input.phaseNumber,input.phaseSummary,input.verdicts,input.roundNumber??1,config3.council,workingDir),mutationGapFinding=input.verdicts.some((verdict)=>verdict.findings.some((finding)=>finding.category==="mutation_gap"))?null:getPhaseMutationGapFinding(input.phaseNumber,workingDir);if(mutationGapFinding){if(addMutationGapFindingToSynthesis(synthesis,mutationGapFinding),mutationGapFinding.severity==="CRITICAL"||mutationGapFinding.severity==="HIGH")synthesis.blockingConcernsCount++}if(synthesis.blockingConcernsCount>0)return JSON.stringify({success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Phase council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the phase can complete. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},null,2);let provenance=input.provenanceAgentName||input.provenanceSessionId?{agent_name:input.provenanceAgentName,session_id:input.provenanceSessionId,captured_at:new Date().toISOString()}:void 0;writePhaseCouncilEvidence(workingDir,synthesis,provenance);let rewardRunIds=resolveRewardRunIds({trustedSessionIds:[ctx?.sessionID],untrustedSessionIds:[input.provenanceSessionId,...input.verdicts.map((v)=>v.sessionId)],isKnownSession:(id)=>getAgentSession(id)!==void 0}),memoryReward=null;try{memoryReward=await applyRecallRewardForCouncil(workingDir,config3.memory,{runIds:rewardRunIds,verdict:synthesis.overallVerdict,verdictPayload:{phaseNumber:synthesis.phaseNumber,swarmId:input.swarmId,roundNumber:synthesis.roundNumber,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes?.length??0,advisoryFindingsCount:synthesis.advisoryFindings?.length??0}})}catch(err2){memoryReward={success:!1,outcome:councilVerdictToMemoryOutcome(synthesis.overallVerdict),memoryIds:[],reward:0,updatedMemoryIds:[],propagatedMemoryIds:[],reason:`reward_threw: ${err2 instanceof Error?err2.message:String(err2)}`}}return JSON.stringify({success:!0,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes?.length??0,advisoryFindingsCount:synthesis.advisoryFindings?.length??0,unresolvedConflictsCount:synthesis.unresolvedConflicts?.length??0,advisoryNotes:synthesis.advisoryNotes??[],mutationGapEmitted:mutationGapFinding!==null,membersVoted,membersAbsent,quorumSize:membersVoted.length,quorumMet:!0,memoryReward,...memoryReward?.success===!1&&memoryReward?.reason&&memoryReward.reason!=="memory_disabled"?{memoryRewardWarning:`memory reward lookup failed: ${memoryReward.reason}`}:{},evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd},null,2)}});function getPhaseMutationGapFinding(phaseNumber,workingDir){let mutationGatePath=path213.join(workingDir,".swarm","evidence",String(phaseNumber),"mutation-gate.json");try{let raw=readFileSync91(mutationGatePath,"utf-8"),gateEntry=(JSON.parse(raw).entries??[]).find((entry)=>entry?.type==="mutation-gate");if(!gateEntry)return{severity:"HIGH",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate evidence is missing a mutation-gate entry for this phase.",evidence:'Expected entries[].type="mutation-gate" with verdict in mutation-gate.json.'};if(gateEntry.verdict==="skip")return{severity:"MEDIUM",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation testing was skipped for this phase; coverage is unverified.",evidence:'mutation-gate.json recorded verdict="skip". Run mutation_test and write_mutation_evidence.'};if(gateEntry.verdict==="warn")return{severity:"LOW",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate reported WARN; mutation coverage may be insufficient.",evidence:'mutation-gate.json recorded verdict="warn" indicating below-pass mutation quality.'};if(gateEntry.verdict==="fail")return{severity:"HIGH",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate reported FAIL; mutation testing quality is below the required threshold.",evidence:'mutation-gate.json recorded verdict="fail" indicating insufficient mutation kill rate.'};return null}catch(error93){if(error93.code==="ENOENT")return{severity:"HIGH",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate evidence file is missing for this phase, so mutation coverage cannot be verified.",evidence:"No .swarm/evidence/{phase}/mutation-gate.json was found at council synthesis time."};return{severity:"MEDIUM",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate evidence could not be read, so mutation coverage cannot be verified.",evidence:error93 instanceof Error?error93.message:String(error93)}}}function writePhaseCouncilEvidence(workingDir,synthesis,provenance){let evidenceDir=path213.join(workingDir,".swarm","evidence",String(synthesis.phaseNumber));mkdirSync53(evidenceDir,{recursive:!0});let evidenceFile=path213.join(evidenceDir,"phase-council.json"),evidenceBundle={entries:[{type:"phase-council",phase_number:synthesis.phaseNumber,scope:"phase",timestamp:synthesis.timestamp,verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,phaseSummary:synthesis.phaseSummary??"",requiredFixes:synthesis.requiredFixes.map((finding)=>({severity:finding.severity,category:finding.category,location:finding.location,detail:finding.detail,evidence:finding.evidence})),advisoryNotes:synthesis.advisoryNotes,advisoryFindings:synthesis.advisoryFindings.map((finding)=>({severity:finding.severity,category:finding.category,location:finding.location,detail:finding.detail,evidence:finding.evidence})),roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,...provenance?{provenance}:{}}]},tempFile=`${evidenceFile}.tmp-${Date.now()}`;try{writeFileSync36(tempFile,JSON.stringify(evidenceBundle,null,2),"utf-8"),renameSync32(tempFile,evidenceFile)}finally{if(existsSync121(tempFile))unlinkSync30(tempFile)}}function addMutationGapFindingToSynthesis(synthesis,finding){if(finding.severity==="CRITICAL"||finding.severity==="HIGH"||finding.severity==="MEDIUM")synthesis.requiredFixes.push(finding);else synthesis.advisoryFindings.push(finding);synthesis.unifiedFeedbackMd+=formatMutationGapFeedback(finding)}function formatMutationGapFeedback(finding){return`
5795
5830
 
5796
5831
  ### Mutation Coverage Gap
5797
5832
  - **[${finding.severity}]** \`${finding.location}\` (${finding.category}) — ${finding.detail}