opencode-swarm 7.190.0 → 7.190.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/cli/{auto-checkpoint-qvk04fya.js → auto-checkpoint-26m3h5f4.js} +4 -4
- package/dist/cli/{checkpoint-9q2r5c3j.js → checkpoint-7a0achpv.js} +8 -8
- package/dist/cli/{coder-settlement-xcparbf3.js → coder-settlement-dsb1t39t.js} +3 -3
- package/dist/cli/{config-doctor-by0ak49m.js → config-doctor-9txawzng.js} +7 -7
- package/dist/cli/{core-b1b3kxzy.js → core-kv7jz9ty.js} +1 -1
- package/dist/cli/{curator-d7b88mzr.js → curator-26yzg8wp.js} +25 -25
- package/dist/cli/{curator-drift-6v604220.js → curator-drift-kxn5sk3z.js} +5 -5
- package/dist/cli/{curator-llm-factory-yvbktznk.js → curator-llm-factory-hs2y9kmw.js} +25 -25
- package/dist/cli/{doctor-knowledge-receipt-phase-id-kwrvnps9.js → doctor-knowledge-receipt-phase-id-z8wea03e.js} +4 -4
- package/dist/cli/{evidence-summary-service-mzr2q4bn.js → evidence-summary-service-bg5zq78s.js} +9 -9
- package/dist/cli/{gate-evidence-78jes9kq.js → gate-evidence-0beg9c7r.js} +2 -2
- package/dist/cli/{guardrail-explain-8kt2mxmw.js → guardrail-explain-n8bm0hpm.js} +26 -26
- package/dist/cli/{guardrail-log-2sthykag.js → guardrail-log-r2zazmbn.js} +3 -3
- package/dist/cli/{guardrail-reset-2n746rzv.js → guardrail-reset-0q54t44w.js} +25 -25
- package/dist/cli/{hive-promoter-s7a5gwhz.js → hive-promoter-7dr5b9zv.js} +25 -25
- package/dist/cli/{index-s92a5ta3.js → index-0gve0mkj.js} +3 -3
- package/dist/cli/{index-49e65y51.js → index-0yrg10jx.js} +2 -2
- package/dist/cli/{index-zyg1m9d0.js → index-0z8vdkvg.js} +1 -1
- package/dist/cli/{index-ffgcdf49.js → index-1f084tqn.js} +157 -80
- package/dist/cli/{index-a5ca62vt.js → index-26e2s6r1.js} +1 -1
- package/dist/cli/{index-h0xhec3d.js → index-2c47efpt.js} +2 -2
- package/dist/cli/{index-npe10823.js → index-4a15347d.js} +1 -1
- package/dist/cli/{index-xyvrfram.js → index-67a6mk20.js} +1 -1
- package/dist/cli/{index-t73adn9b.js → index-ay8ggtgr.js} +2 -2
- package/dist/cli/{index-0qc7a88d.js → index-bcwmn4d7.js} +1 -1
- package/dist/cli/{index-tkhenmms.js → index-bfyh3gpe.js} +3 -3
- package/dist/cli/{index-fb5s32c2.js → index-cewpxcwm.js} +5 -5
- package/dist/cli/{index-ej1hdw16.js → index-dbdkh7pq.js} +2 -2
- package/dist/cli/{index-rgkzcw2a.js → index-dnp4qtpf.js} +1 -1
- package/dist/cli/{index-ejk34dnw.js → index-efztf4yw.js} +1 -1
- package/dist/cli/{index-9xxqdzp4.js → index-enq166kw.js} +1 -1
- package/dist/cli/{index-1s95jrgc.js → index-f46dbyew.js} +2 -2
- package/dist/cli/{index-sm01zpqe.js → index-fthhppnc.js} +27 -27
- package/dist/cli/{index-vhn4e6rm.js → index-gqb8etv4.js} +3 -3
- package/dist/cli/{index-t0gj8s46.js → index-ha0w0a7t.js} +1 -1
- package/dist/cli/{index-9gcqmgbc.js → index-hx1fmywk.js} +1 -1
- package/dist/cli/{index-mseerehd.js → index-m28dzyy8.js} +3 -3
- package/dist/cli/{index-mp1s7b0n.js → index-rjzn7hf0.js} +4 -4
- package/dist/cli/{index-ajzgeb2s.js → index-s9cgnd2z.js} +1 -1
- package/dist/cli/{index-dmq7p8s9.js → index-sc7t1tev.js} +6 -6
- package/dist/cli/{index-3t9t9q2q.js → index-sfjpbnqs.js} +25 -25
- package/dist/cli/{index-p69k8v0e.js → index-spgfs5y7.js} +1 -1
- package/dist/cli/{index-69tgdm9t.js → index-v3j9fk16.js} +1 -1
- package/dist/cli/{index-2kpqqcch.js → index-xdq6mak1.js} +1 -1
- package/dist/cli/{index-kp8k95v9.js → index-yy5yyyst.js} +3 -3
- package/dist/cli/index.js +26 -26
- package/dist/cli/{knowledge-escalator-n1ezv1zp.js → knowledge-escalator-hdrqt5pj.js} +7 -7
- package/dist/cli/{knowledge-events-nyqk3mr7.js → knowledge-events-ttebc8gn.js} +5 -5
- package/dist/cli/{knowledge-store-mnxqcyet.js → knowledge-store-8cxv6w2n.js} +1 -1
- package/dist/cli/{knowledge-validator-z30113mp.js → knowledge-validator-kr5xmqpa.js} +2 -2
- package/dist/cli/{mcp-mnbqw2s5.js → mcp-jtk79ygp.js} +1 -1
- package/dist/cli/{model-preflight-ex482fsy.js → model-preflight-d6tt7479.js} +25 -25
- package/dist/cli/{pending-delegations-j18afz5z.js → pending-delegations-ttk09f50.js} +2 -2
- package/dist/cli/{pr-subscriptions-yngda8mz.js → pr-subscriptions-2kbeezsr.js} +1 -1
- package/dist/cli/{pr-workflow-gate-0vt614f0.js → pr-workflow-gate-3ra6p7k4.js} +25 -25
- package/dist/cli/{scan-cursor-8pwfg5g9.js → scan-cursor-zzccy117.js} +2 -2
- package/dist/cli/{schema-e58ytmqt.js → schema-9prswg1x.js} +1 -1
- package/dist/cli/{scope-persistence-9qfx6ext.js → scope-persistence-eqm8vwnx.js} +5 -5
- package/dist/cli/{server-wxcfwsdx.js → server-swjre81h.js} +25 -25
- package/dist/cli/{skill-generator-tbd4tq9r.js → skill-generator-d8dk9vps.js} +8 -8
- package/dist/cli/{snapshot-coordination-init-sckyzb94.js → snapshot-coordination-init-f49y0zr0.js} +25 -25
- package/dist/cli/{speckit-checkoff-k5jm0abh.js → speckit-checkoff-pnb6q9gd.js} +3 -3
- package/dist/cli/{worktree-collision-ownership-3wwfc72t.js → worktree-collision-ownership-3c7xyc4p.js} +2 -2
- package/dist/cli/{worktree-isolation-zfk7zk6a.js → worktree-isolation-jggdf28m.js} +25 -25
- package/dist/index.js +6 -6
- 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.190.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",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_next_wave:{description:"Epic Mode: the single, idempotent way forward while an epic is open. Closes the active wave once every task is resolved (recording per-task outcomes and declared-vs-actual divergence, which Epic learning uses to plan later waves), keeps phases in order, and issues the next wave of disjoint tasks with dispatch instructions. Returns a status: dispatch | declare-scopes | in-progress | blocked | phase-ready-for-review | epic-complete | refused. Requires `epic.mode.enabled: true` and an epic opened by `/swarm epic start`.",agents:[]},epic_phase_review:{description:"Epic Mode phase readiness: dispatch a read-only phase reviewer, then (only if it APPROVES) a read-only phase critic over the completed phase; parse both verdicts from the agents and record them to .swarm/evidence/{phase}/epic-phase-review.json. Required by phase_complete while an epic is open for the current plan; re-run after any fix (evidence is bound to the plan and phase task evidence).",agents:[]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,EPIC_TOOL_NAMES,EPIC_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.190.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_next_wave:{description:"Epic Mode: the single, idempotent way forward while an epic is open. Closes the active wave once every task is resolved (recording per-task outcomes and declared-vs-actual divergence, which Epic learning uses to plan later waves), keeps phases in order, and issues the next wave of disjoint tasks with dispatch instructions. Returns a status: dispatch | declare-scopes | in-progress | blocked | phase-ready-for-review | epic-complete | refused. Requires `epic.mode.enabled: true` and an epic opened by `/swarm epic start`.",agents:[]},epic_phase_review:{description:"Epic Mode phase readiness: dispatch a read-only phase reviewer, then (only if it APPROVES) a read-only phase critic over the completed phase; parse both verdicts from the agents and record them to .swarm/evidence/{phase}/epic-phase-review.json. Required by phase_complete while an epic is open for the current plan; re-run after any fix (evidence is bound to the plan and phase task evidence).",agents:[]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,EPIC_TOOL_NAMES,EPIC_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -3443,7 +3443,7 @@ ${ctxJSON.length>3000?`${ctxJSON.slice(0,3000)}
|
|
|
3443
3443
|
REASONING: Critic returned empty response
|
|
3444
3444
|
EVIDENCE_CHECKED: none
|
|
3445
3445
|
ANTI_PATTERNS_DETECTED: empty_response
|
|
3446
|
-
ESCALATION_NEEDED: NO`,error:void 0};return{ok:!0,response,error:void 0}}}}catch(err){lastError2=err}return{ok:!1,response:"",error:lastError2}}let lastError;for(let attempt=0;attempt<=maxRetries;attempt++){if(remainingMs(deadlineMs)<=0){lastError=timeoutError("oversight total",totalTimeoutMs),dispatchFailureWasTransient=!1,dispatchError=lastError;break}let result=await attemptDispatch(attempt,modelOverride);if(result.ok){criticResponse=result.response,dispatchError=void 0;break}if(lastError=result.error,dispatchFailureWasTransient=isTransientDispatchError(lastError),warn(`[full-auto/oversight] dispatch attempt ${attempt+1}/${maxRetries+1} failed: ${lastError instanceof Error?lastError.message:String(lastError)}`),dispatchFailureWasTransient&&attempt<maxRetries){dispatchError=void 0;let advanced=advanceInlineFallback({resolveFallback:resolveOversightFallback,index:modelFallbackIndex,lastError,onAdopt:({toModel,fallbackIndex,reason})=>{warn(`[full-auto/oversight] failing over critic to fallback model "${toModel}" (fallback ${fallbackIndex}, reason=${reason})`),telemetry.modelFallback(input.sessionID,input.oversightAgentName,input.criticModel,toModel,reason)}});if(modelFallbackIndex=advanced.nextIndex,advanced.adopted)modelOverride=advanced.adopted.override,modelUsedLabel=advanced.adopted.modelString}else{dispatchError=lastError;break}}if(promptController.abort(),await cleanupEphemeralSessionWithinBudget(client,ephemeralSessionId,deadlineMs,cleanupTimeoutMs),ephemeralSessionId=void 0,deadlineTimer!==void 0)_internals164.clearTimer(deadlineTimer);if(modelFallbackIndex>0)baseEvent.critic_model=modelUsedLabel;if(dispatchError){let infraReason=dispatchFailureWasTransient?`oversight infrastructure failure after ${maxRetries+1} attempt(s): ${dispatchError instanceof Error?dispatchError.message:String(dispatchError)}`:`oversight dispatch failed without retry: ${dispatchError instanceof Error?dispatchError.message:String(dispatchError)}`,consecutive=0;if(dispatchFailureWasTransient)consecutive=incrementOversightFailureCounter(input.directory,input.sessionID);else resetOversightFailureCounter(input.directory,input.sessionID);if(consecutive>=maxConsecutiveFailures&&maxConsecutiveFailures>0){let degradeReason=`auto-degraded to manual mode after ${consecutive} consecutive oversight infrastructure failures`;terminateFullAutoRun(input.directory,input.sessionID,degradeReason),error48(`[full-auto/oversight] ${degradeReason}`);let event3={...baseEvent,verdict:"BLOCKED",reasoning:infraReason,decision:"pause",full_auto_status_after:"terminated"};await writeFullAutoOversightEvent(input.directory,event3);let evidencePath3=await writeFullAutoOversightEvidence(input.directory,input.phase,event3);return recordFullAutoOversight(input.directory,input.sessionID,"BLOCKED",infraReason),{verdict:"BLOCKED",reasoning:infraReason,evidenceChecked:[],antiPatternsDetected:[],escalationNeeded:!1,rawResponse:"",decision:"pause",event:event3,evidencePath:evidencePath3}}pauseFullAutoRun(input.directory,input.sessionID,infraReason);let event2={...baseEvent,verdict:"BLOCKED",reasoning:infraReason,decision:"pause",full_auto_status_after:"paused"};await writeFullAutoOversightEvent(input.directory,event2);let evidencePath2=await writeFullAutoOversightEvidence(input.directory,input.phase,event2);return recordFullAutoOversight(input.directory,input.sessionID,"BLOCKED",infraReason),{verdict:"BLOCKED",reasoning:infraReason,evidenceChecked:[],antiPatternsDetected:[],escalationNeeded:!1,rawResponse:"",decision:"pause",event:event2,evidencePath:evidencePath2}}resetOversightFailureCounter(input.directory,input.sessionID);let parsed=parseFullAutoCriticResponse(criticResponse),decision=decisionFromVerdict(parsed.verdict,parsed.escalationNeeded),afterStatus=beforeStatus;if(decision==="pause")pauseFullAutoRun(input.directory,input.sessionID,`critic verdict ${parsed.verdict}`),afterStatus="paused";else if(decision==="escalate_human")terminateFullAutoRun(input.directory,input.sessionID,"critic ESCALATE_TO_HUMAN"),afterStatus="terminated";let event={...baseEvent,verdict:parsed.verdict,reasoning:parsed.reasoning,evidence_checked:parsed.evidenceChecked,anti_patterns_detected:parsed.antiPatternsDetected,escalation_needed:parsed.escalationNeeded,decision,full_auto_status_after:afterStatus},failClosed=input.fullAutoConfig?.fail_closed!==!1,persistError,evidencePath;try{await writeFullAutoOversightEvent(input.directory,event)}catch(error93){persistError=error93 instanceof Error?error93.message:String(error93)}if(!persistError)try{evidencePath=await writeFullAutoOversightEvidence(input.directory,input.phase,event)}catch(error93){persistError=error93 instanceof Error?error93.message:String(error93)}if(persistError){if(failClosed)pauseFullAutoRun(input.directory,input.sessionID,`oversight persistence failure: ${persistError}`);let failedEvent={...event,verdict:"BLOCKED",reasoning:`oversight persistence failed: ${persistError}`,decision:"pause",full_auto_status_after:"paused"};try{recordFullAutoOversight(input.directory,input.sessionID,"BLOCKED",`oversight-persistence-failure:${persistError}`)}catch{}return{verdict:"BLOCKED",reasoning:failedEvent.reasoning,evidenceChecked:[],antiPatternsDetected:[],escalationNeeded:!1,rawResponse:criticResponse,decision:"pause",event:failedEvent,evidencePath:void 0}}return recordFullAutoOversight(input.directory,input.sessionID,parsed.verdict,input.trigger),{...parsed,decision,event,evidencePath}}async function probeFullAutoOversightHealth(input){let client=_internals96.swarmState.opencodeClient;if(!client)return{healthy:!1,attempts:0,reason:"opencodeClient unavailable"};let totalTimeoutMs=input.totalTimeoutMs??15000,cleanupTimeoutMs=input.cleanupTimeoutMs??1000,deadlineMs=_internals164.now()+totalTimeoutMs,sessionId;try{let created=await runWithinBudget(client.session.create({...input.sessionID?{body:{parentID:input.sessionID,title:"full_auto_oversight health probe"}}:{},query:{directory:input.directory}}),totalTimeoutMs,"oversight health probe");if(!created.data?.id)return{healthy:!1,attempts:1,reason:`health probe create failed: ${JSON.stringify(created.error)}`};return sessionId=created.data.id,{healthy:!0,attempts:1,reason:"session create/delete succeeded"}}catch(error93){return{healthy:!1,attempts:1,reason:error93 instanceof Error?error93.message:String(error93)}}finally{await cleanupEphemeralSessionWithinBudget(client,sessionId,deadlineMs,cleanupTimeoutMs)}}var DEFAULT_TOTAL_TIMEOUT_MS=120000,DEFAULT_CLEANUP_TIMEOUT_MS=2000,_internals164;var init_oversight=__esm(()=>{init_critic();init_agents2();init_schema();init_core_events();init_invocation_failure();init_utils2();init_state();init_telemetry();init_bun_compat();init_ephemeral_session_teardown();init_inline_fallback_advancer();init_logger();init_swarm_artifact_cache();init_critic_response_parser();init_evidence_names();init_state2();_internals164={now:()=>performance.now(),sleep,setTimer:setTimeout,clearTimer:clearTimeout,teardownEphemeralSession}});async function handleFullAutoCommand(directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Full-Auto Mode requires an active session. Use /swarm-full-auto from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Full-Auto Mode requires an active session to operate.";let parsedCommand=parseFullAutoCommandArgs(args2,{allowToggle:!0});if(parsedCommand.kind==="invalid")return`Error: ${parsedCommand.message}`;if(parsedCommand.kind==="status")return buildStatusReport(directory,sessionID,session.fullAutoMode);let newFullAutoMode,modeOverride;if(parsedCommand.kind==="retry_oversight"){let runState=loadFullAutoRunState(directory,sessionID);if(!canRetryOversight(runState))return"Error: retry-oversight is only valid for a paused Full-Auto run whose pause reason is oversight infrastructure or deadline failure.";let{config:config3}=loadPluginConfigWithMeta(directory),totalTimeoutMs=config3.full_auto?.oversight?.total_timeout_ms??15000,cleanupTimeoutMs=config3.full_auto?.oversight?.cleanup_timeout_ms??1000,probe2=await probeFullAutoOversightHealth({directory,sessionID,totalTimeoutMs:Math.min(totalTimeoutMs,15000),cleanupTimeoutMs:Math.min(cleanupTimeoutMs,1000)}),checkedAt=new Date().toISOString(),expiresAt=new Date(Date.now()+300000).toISOString();return recordFullAutoRecoveryProbe(directory,sessionID,{pauseGeneration:runState.pauseGeneration??0,checkedAt,expiresAt,attempts:probe2.attempts,outcome:probe2.healthy?"healthy":"unhealthy",reason:probe2.reason}),probe2.healthy?`Full-Auto oversight recovery probe succeeded for pause generation ${runState.pauseGeneration??0}. The transport path is healthy, but no denied action was replayed. Use \`/swarm full-auto resume\` within 5 minutes to create a new run generation and re-issue the original action for fresh review.`:`Full-Auto oversight recovery probe failed: ${probe2.reason}`}if(parsedCommand.kind==="resume"){let runState=loadFullAutoRunState(directory,sessionID);if(!canResumeFromProbe(runState))return"Error: resume requires a paused infrastructure/deadline run with a recent successful matching retry-oversight probe. Policy, containment, sandbox, or severe-evidence pauses cannot be resumed by probe.";let blockers=getFullAutoRecoveryBlockers({directory,sessionID});if(blockers.length>0)return`Error: resume refused because active policy/sandbox/action blockers remain for the paused action: ${blockers.join(", ")}. Clear the exact blocker, then retry.`;return startFullAutoRun(directory,sessionID,{mode:runState.mode}),session.fullAutoMode=!0,`Full-Auto Mode resumed (new run generation=${loadFullAutoRunState(directory,sessionID)?.runGeneration??"unknown"}, prior pause generation=${runState.pauseGeneration??0}). Re-issue the blocked action so it can be re-reviewed.`}if(parsedCommand.kind==="abort")return terminateFullAutoRun(directory,sessionID,"manual abort via /swarm full-auto abort"),session.fullAutoMode=!1,"Full-Auto Mode aborted. Durable run-state is terminated; risky actions remain blocked until you explicitly re-enable with `/swarm full-auto on`.";if(parsedCommand.kind==="enable")newFullAutoMode=!0,modeOverride=parsedCommand.mode;else if(parsedCommand.kind==="disable")newFullAutoMode=!1;else newFullAutoMode=!session.fullAutoMode;let v2Status="unavailable",modeLabel="supervised",denialMaxConsecutive=3,denialMaxTotal=20,failClosed=!0,durableError,criticModelAdvisory="";try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory),fullAutoConfig=config3.full_auto;if(newFullAutoMode&&configHadErrors)return"Error: Full-Auto Mode cannot be enabled — a swarm plugin config file exists but could not be loaded, so full_auto.locked cannot be verified. Fix the config file (see warnings above) and retry.";if(newFullAutoMode&&fullAutoConfig?.locked===!0)return"Error: Full-Auto Mode is locked for this project (full_auto.locked is true in the swarm plugin config). Runtime activation is disabled by configuration; remove the lock to use /swarm full-auto on.";let effectiveMode=modeOverride??fullAutoConfig?.mode??"supervised";if(modeLabel=effectiveMode,denialMaxConsecutive=fullAutoConfig?.denials?.max_consecutive??3,denialMaxTotal=fullAutoConfig?.denials?.max_total??20,failClosed=fullAutoConfig?.fail_closed!==!1,newFullAutoMode){startFullAutoRun(directory,sessionID,fullAutoConfig?{...fullAutoConfig,mode:effectiveMode}:void 0),v2Status="running";let criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model,architectModel=config3.agents?.architect?.model;if(criticModel&&architectModel&&criticModel===architectModel)criticModelAdvisory=" WARNING: critic model matches architect model — set full_auto.critic_model (or agents.critic.model) to a different model for independent oversight."}else{if(!disarmFullAutoRun(directory,sessionID,"/swarm full-auto off"))terminateFullAutoRun(directory,sessionID,"never started");v2Status="idle"}}catch(error93){durableError=error93 instanceof Error?error93.message:String(error93),error48(`[full-auto] durable run-state write failed: ${durableError}`)}if(durableError){if(newFullAutoMode)return["Error: Full-Auto Mode could NOT be enabled — durable run-state write failed.",`Reason: ${durableError}.`,"Inspect .swarm/ permissions and disk space, then retry."].join(" ");return["Error: Full-Auto Mode could NOT be disabled — durable run-state write failed.",`Reason: ${durableError}.`,"Keep the current mode until .swarm/ is writable and retry."].join(" ")}if(session.fullAutoMode=newFullAutoMode,!newFullAutoMode)session.fullAutoInteractionCount=0,session.fullAutoDeadlockCount=0,session.fullAutoLastQuestionHash=null;if(!newFullAutoMode)return["Full-Auto Mode disabled",`(v2 run-state: ${v2Status}; mode=${modeLabel})`].join(" ");return["Full-Auto Mode enabled",`(v2 mode=${modeLabel}, fail_closed=${failClosed},`,`denials max ${denialMaxConsecutive} consecutive / ${denialMaxTotal} total)`].join(" ")+criticModelAdvisory}function buildStatusReport(directory,sessionID,sessionFlag){let lines=[];lines.push(`Full-Auto session flag: ${sessionFlag?"on":"off"}`);try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory);if(configHadErrors)lines.push("Config: UNREADABLE (a config file exists but could not be loaded; `full_auto.locked` cannot be verified, so runtime activation refuses by fail-closed default). Fix the config file to restore normal status.");if(config3.full_auto?.locked===!0)lines.push("Config: locked (runtime activation disabled via full_auto.locked)")}catch{}try{let runState=loadFullAutoRunState(directory,sessionID),stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable)lines.push(`Durable run-state: UNREADABLE (${stateHealth.reason}). Non-read-only tools are blocked fail-closed until .swarm/full-auto-state.json (or .bak) is restored or deleted.`);else if(!runState)lines.push("Durable run-state: none (no Full-Auto run for this session)");else{if(lines.push(`Durable run-state: ${runState.status} (mode=${runState.mode})`),runState.pauseReason){if(lines.push(`Pause reason: ${runState.pauseReason}`),runState.pauseReason&&isInfrastructurePauseReason(runState.pauseReason))lines.push("Pause category: oversight infrastructure/deadline — `retry-oversight` and `resume` may be available.")}if(runState.terminateReason)lines.push(`Terminate reason: ${runState.terminateReason}`);if(lines.push(`Counters: ${runState.counters.toolCalls} tool calls, ${runState.counters.architectTurns} architect turns, ${runState.counters.oversightChecks} oversight checks`),lines.push(`Denials: ${runState.denialCounters.consecutive} consecutive / ${runState.denialCounters.total} total`),runState.lastOversightVerdict)lines.push(`Last oversight verdict: ${runState.lastOversightVerdict}${runState.lastOversightAt?` at ${runState.lastOversightAt}`:""}`);if(runState.lastRecoveryProbe)lines.push(`Last recovery probe: ${runState.lastRecoveryProbe.outcome} at ${runState.lastRecoveryProbe.checkedAt} (expires ${runState.lastRecoveryProbe.expiresAt}; pause_generation=${runState.lastRecoveryProbe.pauseGeneration}; attempts=${runState.lastRecoveryProbe.attempts})`)}}catch(error93){lines.push(`Durable run-state: unreadable (${error93 instanceof Error?error93.message:String(error93)})`)}return lines.join(`
|
|
3446
|
+
ESCALATION_NEEDED: NO`,error:void 0};return{ok:!0,response,error:void 0}}}}catch(err){lastError2=err}return{ok:!1,response:"",error:lastError2}}let lastError;for(let attempt=0;attempt<=maxRetries;attempt++){if(remainingMs(deadlineMs)<=0){lastError=timeoutError("oversight total",totalTimeoutMs),dispatchFailureWasTransient=!1,dispatchError=lastError;break}let result=await attemptDispatch(attempt,modelOverride);if(result.ok){criticResponse=result.response,dispatchError=void 0;break}if(lastError=result.error,dispatchFailureWasTransient=isTransientDispatchError(lastError),warn(`[full-auto/oversight] dispatch attempt ${attempt+1}/${maxRetries+1} failed: ${lastError instanceof Error?lastError.message:String(lastError)}`),dispatchFailureWasTransient&&attempt<maxRetries){dispatchError=void 0;let advanced=advanceInlineFallback({resolveFallback:resolveOversightFallback,index:modelFallbackIndex,lastError,onAdopt:({toModel,fallbackIndex,reason})=>{warn(`[full-auto/oversight] failing over critic to fallback model "${toModel}" (fallback ${fallbackIndex}, reason=${reason})`),telemetry.modelFallback(input.sessionID,input.oversightAgentName,input.criticModel,toModel,reason)}});if(modelFallbackIndex=advanced.nextIndex,advanced.adopted)modelOverride=advanced.adopted.override,modelUsedLabel=advanced.adopted.modelString}else{dispatchError=lastError;break}}if(promptController.abort(),await cleanupEphemeralSessionWithinBudget(client,ephemeralSessionId,deadlineMs,cleanupTimeoutMs),ephemeralSessionId=void 0,deadlineTimer!==void 0)_internals164.clearTimer(deadlineTimer);if(modelFallbackIndex>0)baseEvent.critic_model=modelUsedLabel;if(dispatchError){let infraReason=dispatchFailureWasTransient?`oversight infrastructure failure after ${maxRetries+1} attempt(s): ${dispatchError instanceof Error?dispatchError.message:String(dispatchError)}`:`oversight dispatch failed without retry: ${dispatchError instanceof Error?dispatchError.message:String(dispatchError)}`,consecutive=0;if(dispatchFailureWasTransient)consecutive=incrementOversightFailureCounter(input.directory,input.sessionID);else resetOversightFailureCounter(input.directory,input.sessionID);if(consecutive>=maxConsecutiveFailures&&maxConsecutiveFailures>0){let degradeReason=`auto-degraded to manual mode after ${consecutive} consecutive oversight infrastructure failures`;terminateFullAutoRun(input.directory,input.sessionID,degradeReason),error48(`[full-auto/oversight] ${degradeReason}`);let event3={...baseEvent,verdict:"BLOCKED",reasoning:infraReason,decision:"pause",full_auto_status_after:"terminated"};await writeFullAutoOversightEvent(input.directory,event3);let evidencePath3=await writeFullAutoOversightEvidence(input.directory,input.phase,event3);return recordFullAutoOversight(input.directory,input.sessionID,"BLOCKED",infraReason),{verdict:"BLOCKED",reasoning:infraReason,evidenceChecked:[],antiPatternsDetected:[],escalationNeeded:!1,rawResponse:"",decision:"pause",event:event3,evidencePath:evidencePath3}}pauseFullAutoRun(input.directory,input.sessionID,infraReason);let event2={...baseEvent,verdict:"BLOCKED",reasoning:infraReason,decision:"pause",full_auto_status_after:"paused"};await writeFullAutoOversightEvent(input.directory,event2);let evidencePath2=await writeFullAutoOversightEvidence(input.directory,input.phase,event2);return recordFullAutoOversight(input.directory,input.sessionID,"BLOCKED",infraReason),{verdict:"BLOCKED",reasoning:infraReason,evidenceChecked:[],antiPatternsDetected:[],escalationNeeded:!1,rawResponse:"",decision:"pause",event:event2,evidencePath:evidencePath2}}resetOversightFailureCounter(input.directory,input.sessionID);let parsed=parseFullAutoCriticResponse(criticResponse),decision=decisionFromVerdict(parsed.verdict,parsed.escalationNeeded),afterStatus=beforeStatus;if(decision==="pause")pauseFullAutoRun(input.directory,input.sessionID,`critic verdict ${parsed.verdict}`),afterStatus="paused";else if(decision==="escalate_human")terminateFullAutoRun(input.directory,input.sessionID,"critic ESCALATE_TO_HUMAN"),afterStatus="terminated";let event={...baseEvent,verdict:parsed.verdict,reasoning:parsed.reasoning,evidence_checked:parsed.evidenceChecked,anti_patterns_detected:parsed.antiPatternsDetected,escalation_needed:parsed.escalationNeeded,decision,full_auto_status_after:afterStatus},failClosed=input.fullAutoConfig?.fail_closed!==!1,persistError,evidencePath;try{await writeFullAutoOversightEvent(input.directory,event)}catch(error93){persistError=error93 instanceof Error?error93.message:String(error93)}if(!persistError)try{evidencePath=await writeFullAutoOversightEvidence(input.directory,input.phase,event)}catch(error93){persistError=error93 instanceof Error?error93.message:String(error93)}if(persistError){if(failClosed)pauseFullAutoRun(input.directory,input.sessionID,`oversight persistence failure: ${persistError}`);let failedEvent={...event,verdict:"BLOCKED",reasoning:`oversight persistence failed: ${persistError}`,decision:"pause",full_auto_status_after:"paused"};try{recordFullAutoOversight(input.directory,input.sessionID,"BLOCKED",`oversight-persistence-failure:${persistError}`)}catch{}return{verdict:"BLOCKED",reasoning:failedEvent.reasoning,evidenceChecked:[],antiPatternsDetected:[],escalationNeeded:!1,rawResponse:criticResponse,decision:"pause",event:failedEvent,evidencePath:void 0}}return recordFullAutoOversight(input.directory,input.sessionID,parsed.verdict,input.trigger),{...parsed,decision,event,evidencePath}}async function probeFullAutoOversightHealth(input){let client=_internals96.swarmState.opencodeClient;if(!client)return{healthy:!1,attempts:0,reason:"opencodeClient unavailable"};let totalTimeoutMs=input.totalTimeoutMs??15000,cleanupTimeoutMs=input.cleanupTimeoutMs??1000,deadlineMs=_internals164.now()+totalTimeoutMs,sessionId;try{let created=await runWithinBudget(client.session.create({...input.sessionID?{body:{parentID:input.sessionID,title:"full_auto_oversight health probe"}}:{},query:{directory:input.directory}}),totalTimeoutMs,"oversight health probe");if(!created.data?.id)return{healthy:!1,attempts:1,reason:`health probe create failed: ${JSON.stringify(created.error)}`};return sessionId=created.data.id,{healthy:!0,attempts:1,reason:"session create/delete succeeded"}}catch(error93){return{healthy:!1,attempts:1,reason:error93 instanceof Error?error93.message:String(error93)}}finally{await cleanupEphemeralSessionWithinBudget(client,sessionId,deadlineMs,cleanupTimeoutMs)}}var DEFAULT_TOTAL_TIMEOUT_MS=120000,DEFAULT_CLEANUP_TIMEOUT_MS=2000,_internals164;var init_oversight=__esm(()=>{init_critic();init_agents2();init_schema();init_core_events();init_invocation_failure();init_utils2();init_state();init_telemetry();init_bun_compat();init_ephemeral_session_teardown();init_inline_fallback_advancer();init_logger();init_swarm_artifact_cache();init_critic_response_parser();init_evidence_names();init_state2();_internals164={now:()=>performance.now(),sleep,setTimer:setTimeout,clearTimer:clearTimeout,teardownEphemeralSession}});function authorizeFullAuto(directory){let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory);if(configHadErrors)return{authorized:!1,message:"Error: Full-Auto Mode cannot be enabled — a swarm plugin config file exists but could not be loaded, so full_auto.locked cannot be verified. Fix the config file (see warnings above) and retry.",config:config3,configHadErrors};if(config3.full_auto?.locked===!0)return{authorized:!1,message:"Error: Full-Auto Mode is locked for this project (full_auto.locked is true in the swarm plugin config). Runtime activation is disabled by configuration; remove the lock to use /swarm full-auto on.",config:config3,configHadErrors};return{authorized:!0,config:config3,configHadErrors}}async function handleFullAutoCommand(directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Full-Auto Mode requires an active session. Use /swarm-full-auto from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Full-Auto Mode requires an active session to operate.";let parsedCommand=parseFullAutoCommandArgs(args2,{allowToggle:!0});if(parsedCommand.kind==="invalid")return`Error: ${parsedCommand.message}`;if(parsedCommand.kind==="status")return buildStatusReport(directory,sessionID,session.fullAutoMode);let newFullAutoMode,modeOverride;if(parsedCommand.kind==="retry_oversight"){let runState=loadFullAutoRunState(directory,sessionID);if(!canRetryOversight(runState))return"Error: retry-oversight is only valid for a paused Full-Auto run whose pause reason is oversight infrastructure or deadline failure.";let{config:config3}=loadPluginConfigWithMeta(directory),totalTimeoutMs=config3.full_auto?.oversight?.total_timeout_ms??15000,cleanupTimeoutMs=config3.full_auto?.oversight?.cleanup_timeout_ms??1000,probe2=await probeFullAutoOversightHealth({directory,sessionID,totalTimeoutMs:Math.min(totalTimeoutMs,15000),cleanupTimeoutMs:Math.min(cleanupTimeoutMs,1000)}),checkedAt=new Date().toISOString(),expiresAt=new Date(Date.now()+300000).toISOString();return recordFullAutoRecoveryProbe(directory,sessionID,{pauseGeneration:runState.pauseGeneration??0,checkedAt,expiresAt,attempts:probe2.attempts,outcome:probe2.healthy?"healthy":"unhealthy",reason:probe2.reason}),probe2.healthy?`Full-Auto oversight recovery probe succeeded for pause generation ${runState.pauseGeneration??0}. The transport path is healthy, but no denied action was replayed. Use \`/swarm full-auto resume\` within 5 minutes to create a new run generation and re-issue the original action for fresh review.`:`Full-Auto oversight recovery probe failed: ${probe2.reason}`}if(parsedCommand.kind==="resume"){let auth=authorizeFullAuto(directory);if(!auth.authorized)return auth.message;let runState=loadFullAutoRunState(directory,sessionID);if(!canResumeFromProbe(runState))return"Error: resume requires a paused infrastructure/deadline run with a recent successful matching retry-oversight probe. Policy, containment, sandbox, or severe-evidence pauses cannot be resumed by probe.";let blockers=getFullAutoRecoveryBlockers({directory,sessionID});if(blockers.length>0)return`Error: resume refused because active policy/sandbox/action blockers remain for the paused action: ${blockers.join(", ")}. Clear the exact blocker, then retry.`;return startFullAutoRun(directory,sessionID,{mode:runState.mode}),session.fullAutoMode=!0,`Full-Auto Mode resumed (new run generation=${loadFullAutoRunState(directory,sessionID)?.runGeneration??"unknown"}, prior pause generation=${runState.pauseGeneration??0}). Re-issue the blocked action so it can be re-reviewed.`}if(parsedCommand.kind==="abort")return terminateFullAutoRun(directory,sessionID,"manual abort via /swarm full-auto abort"),session.fullAutoMode=!1,"Full-Auto Mode aborted. Durable run-state is terminated; risky actions remain blocked until you explicitly re-enable with `/swarm full-auto on`.";if(parsedCommand.kind==="enable")newFullAutoMode=!0,modeOverride=parsedCommand.mode;else if(parsedCommand.kind==="disable")newFullAutoMode=!1;else newFullAutoMode=!session.fullAutoMode;let v2Status="unavailable",modeLabel="supervised",denialMaxConsecutive=3,denialMaxTotal=20,failClosed=!0,durableError,criticModelAdvisory="";try{let auth=authorizeFullAuto(directory),config3=auth.config,fullAutoConfig=config3.full_auto;if(newFullAutoMode&&!auth.authorized)return auth.message;let effectiveMode=modeOverride??fullAutoConfig?.mode??"supervised";if(modeLabel=effectiveMode,denialMaxConsecutive=fullAutoConfig?.denials?.max_consecutive??3,denialMaxTotal=fullAutoConfig?.denials?.max_total??20,failClosed=fullAutoConfig?.fail_closed!==!1,newFullAutoMode){startFullAutoRun(directory,sessionID,fullAutoConfig?{...fullAutoConfig,mode:effectiveMode}:void 0),v2Status="running";let criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model,architectModel=config3.agents?.architect?.model;if(criticModel&&architectModel&&criticModel===architectModel)criticModelAdvisory=" WARNING: critic model matches architect model — set full_auto.critic_model (or agents.critic.model) to a different model for independent oversight."}else{if(!disarmFullAutoRun(directory,sessionID,"/swarm full-auto off"))terminateFullAutoRun(directory,sessionID,"never started");v2Status="idle"}}catch(error93){durableError=error93 instanceof Error?error93.message:String(error93),error48(`[full-auto] durable run-state write failed: ${durableError}`)}if(durableError){if(newFullAutoMode)return["Error: Full-Auto Mode could NOT be enabled — durable run-state write failed.",`Reason: ${durableError}.`,"Inspect .swarm/ permissions and disk space, then retry."].join(" ");return["Error: Full-Auto Mode could NOT be disabled — durable run-state write failed.",`Reason: ${durableError}.`,"Keep the current mode until .swarm/ is writable and retry."].join(" ")}if(session.fullAutoMode=newFullAutoMode,!newFullAutoMode)session.fullAutoInteractionCount=0,session.fullAutoDeadlockCount=0,session.fullAutoLastQuestionHash=null;if(!newFullAutoMode)return["Full-Auto Mode disabled",`(v2 run-state: ${v2Status}; mode=${modeLabel})`].join(" ");return["Full-Auto Mode enabled",`(v2 mode=${modeLabel}, fail_closed=${failClosed},`,`denials max ${denialMaxConsecutive} consecutive / ${denialMaxTotal} total)`].join(" ")+criticModelAdvisory}function buildStatusReport(directory,sessionID,sessionFlag){let lines=[];lines.push(`Full-Auto session flag: ${sessionFlag?"on":"off"}`);try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory);if(configHadErrors)lines.push("Config: UNREADABLE (a config file exists but could not be loaded; `full_auto.locked` cannot be verified, so runtime activation refuses by fail-closed default). Fix the config file to restore normal status.");if(config3.full_auto?.locked===!0)lines.push("Config: locked (runtime activation disabled via full_auto.locked)")}catch{}try{let runState=loadFullAutoRunState(directory,sessionID),stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable)lines.push(`Durable run-state: UNREADABLE (${stateHealth.reason}). Non-read-only tools are blocked fail-closed until .swarm/full-auto-state.json (or .bak) is restored or deleted.`);else if(!runState)lines.push("Durable run-state: none (no Full-Auto run for this session)");else{if(lines.push(`Durable run-state: ${runState.status} (mode=${runState.mode})`),runState.pauseReason){if(lines.push(`Pause reason: ${runState.pauseReason}`),runState.pauseReason&&isInfrastructurePauseReason(runState.pauseReason))lines.push("Pause category: oversight infrastructure/deadline — `retry-oversight` and `resume` may be available.")}if(runState.terminateReason)lines.push(`Terminate reason: ${runState.terminateReason}`);if(lines.push(`Counters: ${runState.counters.toolCalls} tool calls, ${runState.counters.architectTurns} architect turns, ${runState.counters.oversightChecks} oversight checks`),lines.push(`Denials: ${runState.denialCounters.consecutive} consecutive / ${runState.denialCounters.total} total`),runState.lastOversightVerdict)lines.push(`Last oversight verdict: ${runState.lastOversightVerdict}${runState.lastOversightAt?` at ${runState.lastOversightAt}`:""}`);if(runState.lastRecoveryProbe)lines.push(`Last recovery probe: ${runState.lastRecoveryProbe.outcome} at ${runState.lastRecoveryProbe.checkedAt} (expires ${runState.lastRecoveryProbe.expiresAt}; pause_generation=${runState.lastRecoveryProbe.pauseGeneration}; attempts=${runState.lastRecoveryProbe.attempts})`)}}catch(error93){lines.push(`Durable run-state: unreadable (${error93 instanceof Error?error93.message:String(error93)})`)}return lines.join(`
|
|
3447
3447
|
`)}var init_full_auto=__esm(()=>{init_config2();init_oversight();init_recovery2();init_state2();init_state();init_logger()});import*as fs108 from"node:fs";import*as path196 from"node:path";function resolveTier1FixtureRoot(packageRoot){return resolveContainedExistingPath(packageRoot,"evaluation-fixtures/tier1")}function listTier1FixtureManifests(packageRoot){let root=resolveTier1FixtureRoot(packageRoot),expected=new Set(TIER1_FIXTURE_IDS),actual=fs108.readdirSync(root,{withFileTypes:!0}).filter((entry)=>entry.isDirectory()&&expected.has(entry.name)).map((entry)=>entry.name).sort();if(actual.length!==TIER1_FIXTURE_IDS.length)throw Error(`Tier-1 evaluation fixture package is incomplete: expected ${TIER1_FIXTURE_IDS.length}, found ${actual.length}`);return actual.map((id)=>resolveContainedExistingPath(root,path196.join(id,"manifest.json")))}async function loadTier1EvaluationTasks(packageRoot){return Promise.all(listTier1FixtureManifests(packageRoot).map(async(manifestPath2)=>{let raw=JSON.parse(fs108.readFileSync(manifestPath2,"utf8")),id=raw.id;if(typeof id!=="string"||!TIER1_FIXTURE_IDS.includes(id))throw Error(`Unknown Tier-1 fixture id in ${manifestPath2}`);let prefix=path196.posix.join("evaluation-fixtures","tier1",id),instructionPath=raw.instructionPath,environment=raw.environment,scorer=raw.scorer;if(typeof instructionPath!=="string"||typeof environment?.path!=="string")throw Error(`Malformed Tier-1 fixture paths in ${manifestPath2}`);let rebased={...raw,instructionPath:path196.posix.join(prefix,instructionPath),environment:{...environment,path:path196.posix.join(prefix,environment.path)},scorer:scorer?.kind==="project"&&Array.isArray(scorer.argv)?{...scorer,argv:[path196.posix.join(prefix,String(scorer.argv[0])),...scorer.argv.slice(1)]}:scorer},task=EvaluationTaskV1Schema.parse(rebased);if(await computeTaskInputContentHash(packageRoot,task)!==task.contentHash)throw Error(`Tier-1 fixture ${id} failed its content hash`);return task}))}var TIER1_FIXTURE_IDS;var init_fixtures=__esm(()=>{init_contracts();init_hashing();TIER1_FIXTURE_IDS=["mutation-off-by-one","null-substitution","operator-swap","guard-removal","branch-swap","side-effect-deletion","curated-off-by-one","missing-await","swallowed-error","injection-prone-string","missing-auth-check","boundary-error"]});class Node{value;next;constructor(value){this.value=value}}var Queue;var init_yocto_queue=__esm(()=>{Queue=class Queue{#head;#tail;#size;constructor(){this.clear()}enqueue(value){let node=new Node(value);if(this.#head)this.#tail.next=node,this.#tail=node;else this.#head=node,this.#tail=node;this.#size++}dequeue(){let current=this.#head;if(!current)return;if(this.#head=this.#head.next,this.#size--,!this.#head)this.#tail=void 0;return current.value}peek(){if(!this.#head)return;return this.#head.value}clear(){this.#head=void 0,this.#tail=void 0,this.#size=0}get size(){return this.#size}*[Symbol.iterator](){let current=this.#head;while(current)yield current.value,current=current.next}*drain(){while(this.#head)yield this.dequeue()}}});function pLimit(concurrency){let rejectOnClear=!1;if(typeof concurrency==="object")({concurrency,rejectOnClear=!1}=concurrency);if(validateConcurrency(concurrency),typeof rejectOnClear!=="boolean")throw TypeError("Expected `rejectOnClear` to be a boolean");let queue=new Queue,activeCount=0,resumeNext=()=>{if(activeCount<concurrency&&queue.size>0)activeCount++,queue.dequeue().run()},next=()=>{activeCount--,resumeNext()},run=async(function_,resolve73,arguments_)=>{let result=(async()=>function_(...arguments_))();resolve73(result);try{await result}catch{}next()},enqueue=(function_,resolve73,reject2,arguments_)=>{let queueItem={reject:reject2};if(new Promise((internalResolve)=>{queueItem.run=internalResolve,queue.enqueue(queueItem)}).then(run.bind(void 0,function_,resolve73,arguments_)),activeCount<concurrency)resumeNext()},generator=(function_,...arguments_)=>new Promise((resolve73,reject2)=>{enqueue(function_,resolve73,reject2,arguments_)});return Object.defineProperties(generator,{activeCount:{get:()=>activeCount},pendingCount:{get:()=>queue.size},clearQueue:{value(){if(!rejectOnClear){queue.clear();return}let abortError=AbortSignal.abort().reason;while(queue.size>0)queue.dequeue().reject(abortError)}},concurrency:{get:()=>concurrency,set(newConcurrency){validateConcurrency(newConcurrency),concurrency=newConcurrency,queueMicrotask(()=>{while(activeCount<concurrency&&queue.size>0)resumeNext()})}},map:{async value(iterable,function_){let promises12=Array.from(iterable,(value,index)=>this(function_,value,index));return Promise.all(promises12)}}}),generator}function validateConcurrency(concurrency){if(!((Number.isInteger(concurrency)||concurrency===Number.POSITIVE_INFINITY)&&concurrency>0))throw TypeError("Expected `concurrency` to be a number from 1 and up")}var init_p_limit=__esm(()=>{init_yocto_queue()});var MAX_SAFE_TEST_FILES=50,IMPACT_CACHE_VERSION=2;function commentFamilyForLanguage(languageHint){if(!languageHint)return DEFAULT_COMMENT_FAMILY;let hint=languageHint.toLowerCase();switch(hint.includes(".")?hint.slice(hint.lastIndexOf(".")+1):hint){case"py":case"pyi":case"python":case"rb":case"ruby":case"sh":case"bash":case"zsh":case"yaml":case"yml":case"toml":case"r":case"makefile":return{lineTokens:["#"],blockComments:!1};case"php":return{lineTokens:["//","#"],blockComments:!0};case"sql":case"lua":return{lineTokens:["--"],blockComments:!1};case"pl":case"perl":return{lineTokens:["#"],blockComments:!0};default:return DEFAULT_COMMENT_FAMILY}}function isStaticallyEquivalent(originalCode,mutatedCode,languageHint){let family=commentFamilyForLanguage(languageHint),extension=languageHint?languageHint.toLowerCase().slice(languageHint.lastIndexOf(".")+1):"",isJavaScriptFamily=languageHint===void 0||new Set(["cjs","cts","js","jsx","mjs","mts","svelte","ts","tsx","vue"]).has(extension),stripCode=(code)=>{let sourceCode=extension==="rb"||extension==="rake"?(()=>{let lines=[],inRubyComment=!1;for(let line of code.split(`
|
|
3448
3448
|
`)){let trimmed=line.trim();if(!inRubyComment&&/^=begin(?:\s|$)/.test(trimmed)){inRubyComment=!0;continue}if(inRubyComment){if(/^=end(?:\s|$)/.test(trimmed))inRubyComment=!1;continue}lines.push(line)}return lines.join(`
|
|
3449
3449
|
`)})():code,inMultiLineComment=!1,afterMultiLine=[];for(let line of family.blockComments?sourceCode.split(`
|
|
@@ -4067,13 +4067,13 @@ ${fs131.readFileSync(path246.join(dir,file3),"utf-8")}`}catch{}return detectFram
|
|
|
4067
4067
|
`||current==="\r"?current:" ";continue}if(state2==="string"||state2==="template"){if(out+=current,escaped)escaped=!1;else if(current==="\\")escaped=!0;else if(state2==="string"&¤t===stringQuote||state2==="template"&¤t==="`")state2="normal",stringQuote=void 0;continue}if(current==="/"&&next==="/")out+=" ",index++,state2="line";else if(current==="/"&&next==="*")out+=" ",index++,state2="block";else if(out+=current,current==='"'||current==="'")state2="string",stringQuote=current;else if(current==="`")state2="template"}return out}function normalizePath2(p){return p.replace(/\\/g,"/")}function sharedTrailingSegments(a,b){let aParts=normalizePath2(a).split("/").filter(Boolean),bParts=normalizePath2(b).split("/").filter(Boolean),i=aParts.length-1,j=bParts.length-1,shared=0;while(i>=0&&j>=0&&aParts[i]===bParts[j])shared++,i--,j--;return shared}function digestContent(content){return createHash93("sha256").update(content).digest("hex")}function scanTestFilesSync(cwd){let result={files:[],totalBytes:0,exceeded:!1},visitedRealPaths=new Set,visitedEntries=0;function walk(dir,depth){if(result.exceeded)return;if(depth>MAX_IMPACT_SCAN_DEPTH){result.exceeded=!0;return}let directory;try{directory=fs134.opendirSync(dir)}catch{return}try{let realPath;try{realPath=normalizePath2(fs134.realpathSync.native(dir))}catch{return}let directoryKey=process.platform==="win32"?realPath.toLowerCase():realPath;if(visitedRealPaths.has(directoryKey))return;visitedRealPaths.add(directoryKey);while(!0){let entry=directory.readSync();if(entry===null)break;if(++visitedEntries>MAX_IMPACT_WALK_ENTRIES){result.exceeded=!0;return}if(entry.isDirectory()){if(!SKIP_TEST_SCAN_DIRS.has(entry.name))walk(path249.join(dir,entry.name),depth+1);if(result.exceeded)return;continue}if(!entry.isFile())continue;let name=entry.name,isTsTest=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(name)||dir.includes("__tests__")&&/\.(ts|tsx|js|jsx)$/.test(name),isPyTest=/^test_.+\.py$/.test(name)||/.+_test\.py$/.test(name)||dir.includes(`${path249.sep}tests${path249.sep}`)&&name.endsWith(".py"),isGoTest=/.+_test\.go$/.test(name);if(!isTsTest&&!isPyTest&&!isGoTest)continue;let size;try{size=fs134.statSync(path249.join(dir,name)).size}catch{continue}if(size>MAX_IMPACT_TEST_FILE_BYTES||result.files.length>=MAX_IMPACT_TEST_FILES||result.totalBytes+size>MAX_IMPACT_SCAN_BYTES){result.exceeded=!0;return}result.totalBytes+=size,result.files.push(normalizePath2(path249.join(dir,name)))}}catch{}finally{try{directory.closeSync()}catch{}}}return walk(cwd,0),result}function getBoundedTestFiles(cwd){let scan=scanTestFilesSync(cwd);if(scan.exceeded)throw new ImpactScanLimitError;return scan.files}function readBoundedTestFile(testFile,state2){let fd;try{fd=fs134.openSync(testFile,"r");let stat23=fs134.fstatSync(fd),remainingBudget=MAX_IMPACT_SCAN_BYTES-state2.totalBytes,allowedBytes=Math.min(MAX_IMPACT_TEST_FILE_BYTES,remainingBudget);if(stat23.size>allowedBytes)throw new ImpactScanLimitError;let chunks=[],totalBytes=0;while(!0){let remaining=allowedBytes+1-totalBytes;if(remaining<=0)throw new ImpactScanLimitError;let chunk=Buffer.allocUnsafe(Math.min(65536,remaining)),bytesRead=fs134.readSync(fd,chunk,0,chunk.length,totalBytes);if(bytesRead===0)break;if(totalBytes+=bytesRead,totalBytes>allowedBytes)throw new ImpactScanLimitError;chunks.push(chunk.subarray(0,bytesRead))}return state2.totalBytes+=totalBytes,Buffer.concat(chunks,totalBytes).toString("utf8")}finally{if(fd!==void 0)try{fs134.closeSync(fd)}catch{}}}function readBoundedUtf8File(filePath,maxBytes){let fd;try{fd=fs134.openSync(filePath,"r");let initial=fs134.fstatSync(fd);if(!initial.isFile()||initial.size>maxBytes)return null;let chunks=[],chunk=Buffer.allocUnsafe(65536),totalBytes=0;while(totalBytes<=maxBytes){let bytesToRead=Math.min(chunk.length,maxBytes+1-totalBytes),bytesRead=fs134.readSync(fd,chunk,0,bytesToRead,totalBytes);if(bytesRead===0)break;if(totalBytes+=bytesRead,totalBytes>maxBytes)return null;chunks.push(Buffer.from(chunk.subarray(0,bytesRead)))}let final=fs134.fstatSync(fd);if(!final.isFile()||final.size>maxBytes||final.size!==totalBytes||final.dev!==initial.dev||final.ino!==initial.ino)return null;return Buffer.concat(chunks,totalBytes).toString("utf8")}catch{return null}finally{if(fd!==void 0)try{fs134.closeSync(fd)}catch{}}}function buildTestFileManifest(cwd,testFiles){let manifest=[],files=testFiles??getBoundedTestFiles(cwd);if(files.length>MAX_IMPACT_TEST_FILES)throw new ImpactScanLimitError;let state2={totalBytes:0};for(let testFile of files.sort())try{let stat23=fs134.statSync(testFile),content=readBoundedTestFile(testFile,state2);manifest.push({path:normalizePath2(testFile),size:stat23.size,mtimeMs:stat23.mtimeMs,digest:digestContent(content)})}catch(error93){if(error93 instanceof ImpactScanLimitError)throw error93}return manifest}function testManifestChanged(cached3,cwd){if(cached3.length>MAX_IMPACT_TEST_FILES)throw new ImpactScanLimitError;let scan=scanTestFilesSync(cwd);if(scan.exceeded)throw new ImpactScanLimitError;let currentFiles=scan.files.map(normalizePath2).sort(),cachedFiles=cached3.map((entry)=>normalizePath2(entry.path)).sort();if(currentFiles.length!==cachedFiles.length||currentFiles.some((file3,index)=>file3!==cachedFiles[index]))return!0;let cachedByPath=new Map(cached3.map((entry)=>[normalizePath2(entry.path),entry])),state2={totalBytes:0};for(let file3 of currentFiles){let previous=cachedByPath.get(file3);if(!previous)return!0;try{let content=readBoundedTestFile(file3,state2),stat23=fs134.statSync(file3);if(stat23.size!==previous.size||stat23.mtimeMs!==previous.mtimeMs||digestContent(content)!==previous.digest)return!0}catch(error93){if(error93 instanceof ImpactScanLimitError)throw error93;return!0}}return!1}function isCacheStale(impactMap,generatedAtMs,testFiles,cwd){if(testFiles&&cwd&&testManifestChanged(testFiles,cwd))return!0;let sourceCount=0;for(let sourcePath in impactMap){if(!Object.hasOwn(impactMap,sourcePath))continue;if(++sourceCount>MAX_IMPACT_MAP_SOURCES)throw new ImpactScanLimitError;try{if(fs134.statSync(sourcePath).mtimeMs>generatedAtMs)return!0}catch{return!0}}return!1}function resolveRelativeImport(fromDir,importPath){if(!importPath.startsWith("."))return null;let resolved=path249.resolve(fromDir,importPath);if(path249.extname(resolved)){if(fs134.existsSync(resolved)&&fs134.statSync(resolved).isFile())return normalizePath2(resolved)}else for(let ext of EXTENSIONS_TO_TRY){let withExt=resolved+ext;if(fs134.existsSync(withExt)&&fs134.statSync(withExt).isFile())return normalizePath2(withExt)}return null}function resolvePythonImport(fromDir,module){if(!module.startsWith("."))return null;let leadingDots=module.match(/^\.+/)?.[0].length??0,baseDir=fromDir;for(let i=1;i<leadingDots;i++)baseDir=path249.dirname(baseDir);let rest=module.slice(leadingDots);if(rest.length===0){let initPath=path249.join(baseDir,"__init__.py");if(fs134.existsSync(initPath)&&fs134.statSync(initPath).isFile())return normalizePath2(initPath);return null}let subpath=rest.replace(/\./g,path249.sep),candidates=[`${path249.join(baseDir,subpath)}.py`,path249.join(baseDir,subpath,"__init__.py")];for(let c of candidates)if(fs134.existsSync(c)&&fs134.statSync(c).isFile())return normalizePath2(c);return null}function findGoModule(fromDir){let cur=path249.resolve(fromDir),walked=[];for(let i=0;i<16;i++){let cached3=goModuleCache.get(cur);if(cached3!==void 0){for(let d of walked)goModuleCache.set(d,cached3);return cached3}walked.push(cur);try{let goMod=path249.join(cur,"go.mod"),content=readBoundedUtf8File(goMod,MAX_IMPACT_GO_MOD_BYTES);if(content===null)throw Error("go.mod unavailable or oversized");let moduleMatch=content.match(/^\s*module\s+"?([^"\s/]+(?:\/[^"\s]+)*)"?/m);if(moduleMatch){let result={moduleRoot:cur,modulePath:moduleMatch[1]};for(let d of walked)goModuleCache.set(d,result);return result}}catch{}try{fs134.accessSync(path249.join(cur,".git"));break}catch{}let parent=path249.dirname(cur);if(parent===cur)break;cur=parent}for(let d of walked)goModuleCache.set(d,null);return null}function resolveGoImport(fromDir,importPath){let dir=null;if(importPath.startsWith("."))dir=path249.resolve(fromDir,importPath);else{let mod=findGoModule(fromDir);if(mod&&(importPath===mod.modulePath||importPath.startsWith(`${mod.modulePath}/`))){let subpath=importPath.slice(mod.modulePath.length);dir=path249.join(mod.moduleRoot,subpath)}}if(dir===null)return[];if(!fs134.existsSync(dir)||!fs134.statSync(dir).isDirectory())return[];let directory;try{directory=fs134.opendirSync(dir);let files=[],entries2=0;while(!0){let entry=directory.readSync();if(entry===null)break;if(++entries2>MAX_IMPACT_WALK_ENTRIES)return[];if(entry.isFile()&&entry.name.endsWith(".go")&&!entry.name.endsWith("_test.go"))files.push(normalizePath2(path249.join(dir,entry.name)))}return files}catch{return[]}finally{directory?.closeSync()}}function _clearGoModuleCache(){goModuleCache.clear()}function findTestFilesSync(cwd){return scanTestFilesSync(cwd).files}function extractImports4(content){function execRegex(regex,content2){let results=[];regex.lastIndex=0;let match;while((match=regex.exec(content2))!==null)results.push(match[1]);return results}let sourceWithoutComments=stripTsComments(content);return[...execRegex(IMPORT_REGEX_ES_SIDE_EFFECT,sourceWithoutComments),...execRegex(IMPORT_REGEX_ES_FROM,sourceWithoutComments),...execRegex(IMPORT_REGEX_REQUIRE,sourceWithoutComments),...execRegex(IMPORT_REGEX_REEXPORT,sourceWithoutComments)]}function addImpactEdgesForTestFile(testFile,content,impactMap){let ext=path249.extname(testFile).toLowerCase(),testDir=path249.dirname(testFile);function addEdge3(source){if(!impactMap[source])impactMap[source]=[];if(!impactMap[source].includes(testFile))impactMap[source].push(testFile)}if(TS_EXTENSIONS.has(ext)){let imports=extractImports4(content);for(let importPath of imports){let resolved=resolveRelativeImport(testDir,importPath);if(resolved!==null)addEdge3(resolved)}return}if(PYTHON_EXTENSIONS.has(ext)){let modules=_internals206.extractImports(testFile,content);for(let mod of modules){let resolved=resolvePythonImport(testDir,mod);if(resolved!==null)addEdge3(resolved)}return}if(GO_EXTENSIONS.has(ext)){let imports=_internals205.extractImports(testFile,content);for(let importPath of imports){let sourceFiles=resolveGoImport(testDir,importPath);for(let source of sourceFiles)addEdge3(source)}return}}async function buildImpactMapInternal(cwd,testFilesOverride){_clearGoModuleCache();let testFiles=testFilesOverride??getBoundedTestFiles(cwd);if(testFiles.length>MAX_IMPACT_TEST_FILES)throw new ImpactScanLimitError;let impactMap={},state2={totalBytes:0};for(let testFile of testFiles){let content;try{content=readBoundedTestFile(testFile,state2)}catch(error93){if(error93 instanceof ImpactScanLimitError)throw error93;continue}if(content.substring(0,8192).includes("\x00"))continue;addImpactEdgesForTestFile(testFile,content,impactMap)}return impactMap}function validateImpactMap(value){if(value===null||typeof value!=="object"||Array.isArray(value))return"invalid";let sourceCount=0,referenceCount=0;for(let sourcePath in value){if(!Object.hasOwn(value,sourcePath))continue;if(++sourceCount>MAX_IMPACT_MAP_SOURCES)return"overflow";let tests=value[sourcePath];if(!Array.isArray(tests))return"invalid";for(let test of tests){if(++referenceCount>MAX_IMPACT_MAP_REFERENCES)return"overflow";if(typeof test!=="string")return"invalid"}}return"valid"}function unverifiedStatus(status2){if(status2==="fresh"||status2==="stale")return"fresh_unverified";if(status2==="missing")return"missing_unverified";if(status2==="corrupt")return"corrupt_unverified";if(status2==="legacy")return"legacy_unverified";if(status2==="overflow")return"overflow_unverified";return status2}function readBoundedCacheText(filePath){let fd;try{fd=fs134.openSync(filePath,"r");let initial=fs134.fstatSync(fd);if(initial.size>MAX_IMPACT_CACHE_BYTES)return{status:"overflow"};let chunks=[],chunk=Buffer.allocUnsafe(65536),totalBytes=0;while(totalBytes<=MAX_IMPACT_CACHE_BYTES){let bytesToRead=Math.min(chunk.length,MAX_IMPACT_CACHE_BYTES+1-totalBytes),bytesRead=fs134.readSync(fd,chunk,0,bytesToRead,totalBytes);if(bytesRead===0)break;if(chunks.push(Buffer.from(chunk.subarray(0,bytesRead))),totalBytes+=bytesRead,totalBytes>MAX_IMPACT_CACHE_BYTES)return{status:"overflow"}}let final=fs134.fstatSync(fd);if(final.size>MAX_IMPACT_CACHE_BYTES||totalBytes>MAX_IMPACT_CACHE_BYTES)return{status:"overflow"};if(final.size!==totalBytes||final.dev!==initial.dev||final.ino!==initial.ino)return{status:"unstable"};return{status:"ok",text:Buffer.concat(chunks,totalBytes).toString("utf8")}}catch(error93){return{status:error93.code==="ENOENT"?"missing":"unavailable"}}finally{if(fd!==void 0)try{fs134.closeSync(fd)}catch{}}}function readImpactCache(cwd,verify=!0){let cachePath=path249.join(cwd,".swarm","cache","impact-map.json"),boundedRead=readBoundedCacheText(cachePath);if(boundedRead.status==="missing")return{envelope:null,status:verify?"missing":"missing_unverified"};if(boundedRead.status==="overflow")return{envelope:null,status:verify?"overflow":"overflow_unverified"};if(boundedRead.status!=="ok")return{envelope:null,status:verify?"corrupt":"corrupt_unverified"};try{let data=JSON.parse(boundedRead.text),mapStatus=validateImpactMap(data.map);if(data.version!==IMPACT_CACHE_VERSION||typeof data.generatedAt!=="string"||mapStatus!=="valid"||typeof data.fileCount!=="number"||!Array.isArray(data.testFiles)||data.testFiles.length>MAX_IMPACT_TEST_FILES||!data.testFiles.every((entry)=>typeof entry==="object"&&entry!==null&&typeof entry.path==="string"&&typeof entry.size==="number"&&typeof entry.mtimeMs==="number"&&typeof entry.digest==="string")){if(mapStatus==="overflow"||Array.isArray(data.testFiles)&&data.testFiles.length>MAX_IMPACT_TEST_FILES)return{envelope:null,status:verify?"overflow":"overflow_unverified"};let status2=data.map!==void 0&&(data.version===void 0||typeof data.version==="number"&&data.version<IMPACT_CACHE_VERSION)?"legacy":"corrupt";return{envelope:null,status:verify?status2:unverifiedStatus(status2)}}let envelope=data,generatedAtMs=new Date(envelope.generatedAt).getTime();if(!Number.isFinite(generatedAtMs))return{envelope:null,status:verify?"corrupt":"corrupt_unverified"};if(!verify)return{envelope,status:"fresh_unverified"};try{if(_internals207.isCacheStale(envelope.map,generatedAtMs,envelope.testFiles,cwd))return{envelope,status:"stale"}}catch(error93){if(error93 instanceof ImpactScanLimitError)return{envelope:null,status:"overflow"};throw error93}return{envelope,status:"fresh"}}catch(error93){if(error93 instanceof ImpactScanLimitError)return{envelope:null,status:verify?"overflow":"overflow_unverified"};return{envelope:null,status:verify?"corrupt":"corrupt_unverified"}}}function getImpactCacheStatus(cwd,options){let cachePath=path249.join(cwd,".swarm","cache","impact-map.json");return{status:readImpactCache(cwd,options?.verify??!0).status,cachePath}}async function buildImpactMap(cwd){let testFiles=getBoundedTestFiles(cwd),impactMap=await _internals207.buildImpactMapInternal(cwd,testFiles);return await _internals207.saveImpactMap(cwd,impactMap,testFiles),impactMap}function rebuiltCacheStatus(status2){if(status2==="missing"||status2==="corrupt"||status2==="legacy"||status2==="stale")return`rebuilt_${status2}`;return status2}async function loadImpactMapWithStatus(cwd,options){let inspection=readImpactCache(cwd,!options?.skipRebuild);if(inspection.envelope){if(inspection.status==="fresh"||options?.skipRebuild)return{map:inspection.envelope.map,status:inspection.status}}if(options?.skipRebuild)return{map:{},status:inspection.status};try{return{map:await _internals207.buildImpactMap(cwd),status:rebuiltCacheStatus(inspection.status)}}catch(error93){if(error93 instanceof ImpactScanLimitError)return{map:{},status:"overflow"};throw error93}}async function loadImpactMap(cwd,options){return(await loadImpactMapWithStatus(cwd,options)).map}async function saveImpactMap(cwd,impactMap,testFiles){if(!path249.isAbsolute(cwd))throw Error(`saveImpactMap requires an absolute project root path, got: "${cwd}"`);let mapStatus=validateImpactMap(impactMap);if(mapStatus!=="valid")throw Error(mapStatus==="overflow"?"saveImpactMap impact map exceeds bounded source/reference limits":"saveImpactMap received an invalid impact map");_internals207.validateProjectRoot(cwd);let cacheDir2=path249.join(cwd,".swarm","cache"),cachePath=path249.join(cacheDir2,"impact-map.json");if(!fs134.existsSync(cacheDir2))fs134.mkdirSync(cacheDir2,{recursive:!0});let data={version:IMPACT_CACHE_VERSION,generatedAt:new Date().toISOString(),fileCount:Object.keys(impactMap).length,map:impactMap,testFiles:buildTestFileManifest(cwd,testFiles)};await atomicWriteSwarmFile(cachePath,JSON.stringify(data,null,2))}async function analyzeImpact(changedFiles,cwd,budget,impactMapOverride){if(!Array.isArray(changedFiles))return{impactedTests:[],unrelatedTests:[],untestedFiles:[],impactMap:{}};let validFiles=changedFiles.filter((f)=>typeof f==="string"&&f.length>0&&!f.includes("\x00")),impactMap=impactMapOverride??await _internals207.loadImpactMap(cwd),impactedTestsSet=new Set,impactedTestKeys=new Set,untestedFiles=[],budgetExceeded=!1,traversedReferences=0,traversedSources=0,testKey=(test)=>{let resolved=path249.isAbsolute(test)?test:path249.resolve(cwd,test),normalized=normalizePath2(resolved);return process.platform==="win32"?normalized.toLowerCase():normalized},addImpactedTest=(test)=>{if(++traversedReferences>MAX_IMPACT_MAP_REFERENCES)return budgetExceeded=!0,!1;let key2=testKey(test);if(impactedTestKeys.has(key2))return!0;if(budget!==void 0&&impactedTestKeys.size>=budget)return budgetExceeded=!0,!1;return impactedTestKeys.add(key2),impactedTestsSet.add(test),!0};for(let changedFile of validFiles){let normalizedChanged=normalizePath2(path249.resolve(cwd,changedFile)),tests=impactMap[normalizedChanged];if(tests&&tests.length>0){for(let test of tests)if(addImpactedTest(test),budgetExceeded)break;if(budgetExceeded)break}else{let changedDir=normalizePath2(path249.dirname(normalizedChanged)),changedInputDir=normalizePath2(path249.dirname(changedFile)),suffixMatches=[];for(let sourcePath in impactMap){if(!Object.hasOwn(impactMap,sourcePath))continue;if(++traversedSources>MAX_IMPACT_MAP_SOURCES){budgetExceeded=!0;break}let tests2=impactMap[sourcePath];if(!Array.isArray(tests2))continue;if(sourcePath.endsWith(changedFile)||changedFile.endsWith(sourcePath)||sourcePath.endsWith(normalizedChanged)||normalizedChanged.endsWith(sourcePath))suffixMatches.push([sourcePath,tests2])}if(budgetExceeded)break;suffixMatches.sort(([sourceA],[sourceB])=>{let sourceDirA=normalizePath2(path249.dirname(sourceA)),sourceDirB=normalizePath2(path249.dirname(sourceB)),exactA=sourceDirA===changedDir||changedInputDir!=="."&&(sourceDirA===changedInputDir||sourceDirA.endsWith(`/${changedInputDir}`)),exactB=sourceDirB===changedDir||changedInputDir!=="."&&(sourceDirB===changedInputDir||sourceDirB.endsWith(`/${changedInputDir}`));if(exactA!==exactB)return exactA?-1:1;let sharedA=Math.max(sharedTrailingSegments(sourceDirA,changedDir),changedInputDir==="."?0:sharedTrailingSegments(sourceDirA,changedInputDir)),sharedB=Math.max(sharedTrailingSegments(sourceDirB,changedDir),changedInputDir==="."?0:sharedTrailingSegments(sourceDirB,changedInputDir)),nearestA=sharedA>0,nearestB=sharedB>0;if(nearestA!==nearestB)return nearestA?-1:1;if(sharedA!==sharedB)return sharedB-sharedA;return sourceA.localeCompare(sourceB)});let found=suffixMatches.length>0;for(let[,tests2]of suffixMatches){for(let test of tests2)if(addImpactedTest(test),budgetExceeded)break;if(budgetExceeded)break}if(budgetExceeded)break;if(!found)untestedFiles.push(changedFile)}}let impactedTests=[...impactedTestsSet],allTestFiles=new Map;if(!budgetExceeded)traversedReferences=0,traversedSources=0;for(let sourcePath in impactMap){if(budgetExceeded)break;if(!Object.hasOwn(impactMap,sourcePath))continue;if(++traversedSources>MAX_IMPACT_MAP_SOURCES){budgetExceeded=!0;break}let tests=impactMap[sourcePath];if(!Array.isArray(tests))continue;for(let test of tests){if(++traversedReferences>MAX_IMPACT_MAP_REFERENCES){budgetExceeded=!0;break}if(typeof test!=="string")continue;let key2=testKey(test);if(!allTestFiles.has(key2))allTestFiles.set(key2,test)}}let unrelatedTests=[...allTestFiles.entries()].filter(([key2])=>!impactedTestKeys.has(key2)).map(([,test])=>test);return{impactedTests,unrelatedTests,untestedFiles,impactMap,budgetExceeded}}var MAX_IMPACT_TEST_FILES=4096,MAX_IMPACT_TEST_FILE_BYTES=4194304,MAX_IMPACT_GO_MOD_BYTES=1048576,MAX_IMPACT_SCAN_BYTES=134217728,MAX_IMPACT_WALK_ENTRIES=1e5,MAX_IMPACT_SCAN_DEPTH=32,MAX_IMPACT_CACHE_BYTES=33554432,MAX_IMPACT_MAP_SOURCES=1e4,MAX_IMPACT_MAP_REFERENCES=1e5,ImpactScanLimitError,IMPORT_REGEX_ES_SIDE_EFFECT,IMPORT_REGEX_ES_FROM,IMPORT_REGEX_REQUIRE,IMPORT_REGEX_REEXPORT,TS_EXTENSIONS,PYTHON_EXTENSIONS,GO_EXTENSIONS,EXTENSIONS_TO_TRY,SKIP_TEST_SCAN_DIRS,goModuleCache,_internals207;var init_analyzer=__esm(()=>{init_manager2();init_go2();init_python2();init_atomic_write();ImpactScanLimitError=class ImpactScanLimitError extends Error{code="IMPACT_SCAN_LIMIT";constructor(){super("impact analysis scan limits exceeded");this.name="ImpactScanLimitError"}};IMPORT_REGEX_ES_SIDE_EFFECT=/\bimport\s*['"]([^'"]+)['"]/g,IMPORT_REGEX_ES_FROM=/\bimport\s+(?:(?!\b(?:import|export)\b)[^;])*?\s+from\s+['"]([^'"]+)['"]/g,IMPORT_REGEX_REQUIRE=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,IMPORT_REGEX_REEXPORT=/export\s+(?:\{[^}]*\}|\*)\s+from\s+['"]([^'"]+)['"]/g;TS_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),PYTHON_EXTENSIONS=new Set([".py"]),GO_EXTENSIONS=new Set([".go"]),EXTENSIONS_TO_TRY=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];SKIP_TEST_SCAN_DIRS=new Set(["node_modules","dist",".git",".swarm",".cache"]);goModuleCache=new Map;_internals207={validateProjectRoot,normalizePath:normalizePath2,isCacheStale,resolveRelativeImport,findTestFilesSync,extractImports:extractImports4,findGoModule,buildImpactMapInternal,buildImpactMap,loadImpactMap,loadImpactMapWithStatus,saveImpactMap,analyzeImpact,getImpactCacheStatus,_clearGoModuleCache}});function computeCombinedFlakyScore(recent){let totalRuns=recent.length;if(totalRuns<2)return{alternationCount:0,flakyScore:0};let alternationCount=0,passCount=0;for(let i=0;i<recent.length;i++){if(recent[i].result==="pass")passCount++;if(i>0&&recent[i].result!==recent[i-1].result)alternationCount++}let alternationScore=alternationCount/totalRuns,passRate=passCount/totalRuns,passRateVarianceScore=4*passRate*(1-passRate);return{alternationCount,flakyScore:(alternationScore+passRateVarianceScore)/2}}function detectFlakyTests(allHistory){let grouped=new Map;for(let record3 of allHistory){let key2=`${record3.testFile.toLowerCase()}\x00${record3.testName.toLowerCase()}`;if(!grouped.has(key2))grouped.set(key2,{records:[],originalFile:record3.testFile,originalName:record3.testName});grouped.get(key2).records.push(record3)}let results=[];for(let[_key,entry]of grouped){let records=entry.records;if(records.length===0)continue;let recent=records.slice().sort((a,b)=>new Date(a.timestamp).getTime()-new Date(b.timestamp).getTime()).slice(-20),totalRuns=recent.length;if(totalRuns<2)continue;let{alternationCount,flakyScore}=computeCombinedFlakyScore(recent),isQuarantined=flakyScore>0.3&&totalRuns>=5,recentResults=recent.map((r)=>r.result),testFile=entry.originalFile,testName=entry.originalName,recommendation;if(isQuarantined){if(alternationCount===totalRuns-1)recommendation="Highly unstable — investigate test isolation issues, mock cleanup, or shared state";else if(flakyScore>0.5)recommendation="Severely flaky — consider quarantining and rewriting test with proper isolation";else if(flakyScore>0.3)recommendation="Moderately flaky — review for timing dependencies, async issues, or environmental factors"}results.push({testFile,testName,flakyScore,totalRuns,alternationCount,isQuarantined,recentResults,recommendation})}return results}import fs135 from"node:fs";import path250 from"node:path";function normalizedTestKey(rec){return`${rec.testFile.toLowerCase()}|${rec.testName.toLowerCase()}`}function enforceGlobalHistoryCaps(records){let entryCap=resolveRetentionCap("MAX_TEST_HISTORY_ENTRIES",MAX_TEST_HISTORY_ENTRIES),keyCap=resolveRetentionCap("MAX_TEST_HISTORY_KEYS",MAX_TEST_HISTORY_KEYS),out=records;if(out.length>entryCap)out=out.slice(out.length-entryCap);if(out.length===0)return out;let lastSeenIndex=new Map;for(let i=0;i<out.length;i++)lastSeenIndex.set(normalizedTestKey(out[i]),i);if(lastSeenIndex.size<=keyCap)return out;let keysByRecency=[...lastSeenIndex.entries()].sort((a,b)=>a[1]-b[1]).map(([key2])=>key2),dropKeys=new Set(keysByRecency.slice(0,lastSeenIndex.size-keyCap));if(out=out.filter((rec)=>!dropKeys.has(normalizedTestKey(rec))),out.length>entryCap)out=out.slice(out.length-entryCap);return out}function getHistoryPath(workingDir){if(!workingDir)throw Error("getHistoryPath requires a working directory — project root must be provided by the caller");if(!path250.isAbsolute(workingDir))throw Error(`getHistoryPath requires an absolute project root path, got: "${workingDir}"`);return path250.join(workingDir,".swarm","cache","test-history.jsonl")}function sanitizeErrorMessage(errorMessage2){if(errorMessage2===void 0)return;if(errorMessage2.length>MAX_ERROR_LENGTH)return errorMessage2.substring(0,MAX_ERROR_LENGTH);return errorMessage2}function sanitizeStackPrefix(stackPrefix){if(stackPrefix===void 0)return;if(stackPrefix.length>MAX_STACK_LENGTH)return stackPrefix.substring(0,MAX_STACK_LENGTH);return stackPrefix}function sanitizeChangedFiles(changedFiles){return changedFiles.filter((f)=>typeof f==="string"&&f.length>0&&!DANGEROUS_PROPERTY_NAMES.has(f)).slice(0,MAX_CHANGED_FILES)}function isTestRunResult(value){return value==="pass"||value==="fail"||value==="skip"}function parseStoredRecord(value){if(typeof value!=="object"||value===null)return null;let record3=value;if(typeof record3.testFile!=="string"||record3.testFile.length===0)return null;if(typeof record3.testName!=="string"||record3.testName.length===0)return null;if(typeof record3.taskId!=="string"||record3.taskId.length===0)return null;if(!isTestRunResult(record3.result))return null;if(typeof record3.durationMs!=="number"||!Number.isFinite(record3.durationMs))return null;if(typeof record3.timestamp!=="string"||Number.isNaN(Date.parse(record3.timestamp)))return null;return{timestamp:record3.timestamp,taskId:record3.taskId,testFile:record3.testFile,testName:record3.testName,result:record3.result,durationMs:Math.max(0,record3.durationMs),errorMessage:typeof record3.errorMessage==="string"?sanitizeErrorMessage(record3.errorMessage):void 0,stackPrefix:typeof record3.stackPrefix==="string"?sanitizeStackPrefix(record3.stackPrefix):void 0,changedFiles:sanitizeChangedFiles(Array.isArray(record3.changedFiles)?record3.changedFiles:[])}}function batchAppendTestRuns(records,workingDir){if(records.length===0)return;for(let record3 of records){if(typeof record3.testFile!=="string"||record3.testFile.length===0)throw TypeError("testFile must be a non-empty string");if(typeof record3.testName!=="string"||record3.testName.length===0)throw TypeError("testName must be a non-empty string");if(typeof record3.taskId!=="string"||record3.taskId.length===0)throw TypeError("taskId must be a non-empty string");if(record3.result!=="pass"&&record3.result!=="fail"&&record3.result!=="skip")throw TypeError('result must be "pass", "fail", or "skip"');if(typeof record3.durationMs!=="number"||!Number.isFinite(record3.durationMs))throw TypeError("durationMs must be a finite number");if(record3.timestamp!==void 0&&Number.isNaN(Date.parse(record3.timestamp)))throw TypeError("timestamp must be a valid ISO 8601 string");if(record3.changedFiles!==void 0&&!Array.isArray(record3.changedFiles))throw TypeError("changedFiles must be an array")}let historyPath=getHistoryPath(workingDir),historyDir=path250.dirname(historyPath);if(_internals208.validateProjectRoot(workingDir),!fs135.existsSync(historyDir))fs135.mkdirSync(historyDir,{recursive:!0});withHistoryWriteLock(historyPath,()=>{let existingRecords=readAllRecords(historyPath),sanitizedRecords=records.map((record3)=>({...record3,timestamp:record3.timestamp||new Date().toISOString(),durationMs:Math.max(0,record3.durationMs),errorMessage:sanitizeErrorMessage(record3.errorMessage),stackPrefix:sanitizeStackPrefix(record3.stackPrefix),changedFiles:sanitizeChangedFiles(record3.changedFiles||[])}));existingRecords.push(...sanitizedRecords);let recordsByTest=new Map;for(let rec of existingRecords){let normalizedKey=`${rec.testFile.toLowerCase()}|${rec.testName.toLowerCase()}`;if(!recordsByTest.has(normalizedKey))recordsByTest.set(normalizedKey,[]);recordsByTest.get(normalizedKey).push(rec)}let prunedRecords=[];for(let[,recs]of recordsByTest){recs.sort((a,b)=>new Date(a.timestamp).getTime()-new Date(b.timestamp).getTime());let toKeep=recs.slice(-MAX_HISTORY_PER_TEST);prunedRecords.push(...toKeep)}prunedRecords.sort((a,b)=>new Date(a.timestamp).getTime()-new Date(b.timestamp).getTime());let cappedRecords=enforceGlobalHistoryCaps(prunedRecords);try{let content=`${cappedRecords.map((rec)=>JSON.stringify(rec)).join(`
|
|
4068
4068
|
`)}
|
|
4069
4069
|
`,tempPath=`${historyPath}.tmp`;fs135.writeFileSync(tempPath,content,"utf-8"),fs135.renameSync(tempPath,historyPath)}catch(err){try{let tempPath=`${historyPath}.tmp`;if(fs135.existsSync(tempPath))fs135.unlinkSync(tempPath)}catch{}throw Error(`Failed to write test history: ${err instanceof Error?err.message:String(err)}`)}})}function withHistoryWriteLock(historyPath,fn2){let lockPath=`${historyPath}.write-lock`,deadline=Date.now()+HISTORY_WRITE_LOCK_TIMEOUT_MS;while(!0)try{fs135.mkdirSync(lockPath);break}catch(error93){if((error93 instanceof Error&&"code"in error93?error93.code:void 0)!=="EEXIST")throw Error(`Failed to acquire test history lock: ${error93 instanceof Error?error93.message:String(error93)}`);if(Date.now()>=deadline)throw Error(`Timed out waiting for test history lock: ${historyPath}`);try{let lockStat=fs135.statSync(lockPath);if(Date.now()-lockStat.mtimeMs>=HISTORY_WRITE_LOCK_STALE_MS){fs135.rmSync(lockPath,{recursive:!0,force:!0});continue}}catch{}let remainingMs2=Math.max(0,deadline-Date.now()),sleepMs=Math.min(HISTORY_WRITE_LOCK_BACKOFF_MS,remainingMs2);if(sleepMs>0)sleepSync4(sleepMs)}try{return fn2()}finally{try{fs135.rmSync(lockPath,{recursive:!0,force:!0})}catch{}}function sleepSync4(ms2){let until=Date.now()+ms2;while(Date.now()<until);}}function readAllRecords(historyPath){if(!fs135.existsSync(historyPath))return[];try{let lines=fs135.readFileSync(historyPath,"utf-8").split(`
|
|
4070
|
-
`),records=[];for(let line of lines){let trimmed=line.trim();if(trimmed.length===0)continue;try{let parsed=JSON.parse(trimmed),record3=parseStoredRecord(parsed);if(record3)records.push(record3)}catch{}}return records}catch(err){throw Error(`Failed to read test history: ${err instanceof Error?err.message:String(err)}`)}}function getAllHistory(workingDir){let historyPath=getHistoryPath(workingDir),records=readAllRecords(historyPath);return records.sort((a,b)=>new Date(a.timestamp).getTime()-new Date(b.timestamp).getTime()),records}var MAX_HISTORY_PER_TEST=20,MAX_ERROR_LENGTH=500,MAX_STACK_LENGTH=200,MAX_CHANGED_FILES=50,HISTORY_WRITE_LOCK_TIMEOUT_MS=5000,HISTORY_WRITE_LOCK_STALE_MS=60000,HISTORY_WRITE_LOCK_BACKOFF_MS=10,MAX_TEST_HISTORY_ENTRIES=5000,MAX_TEST_HISTORY_KEYS=1000,DANGEROUS_PROPERTY_NAMES,_internals208;var init_history_store=__esm(()=>{init_manager2();init_caps();DANGEROUS_PROPERTY_NAMES=new Set(["__proto__","constructor","prototype"]);_internals208={validateProjectRoot}});class LanguageBackendRegistry{backends=new Map;register(backend){let existing=this.backends.get(backend.id);if(existing&&existing!==backend)throw Error(`LanguageBackendRegistry: backend id "${backend.id}" registered twice. Each LanguageBackend.id must be unique.`);this.backends.set(backend.id,backend)}get(id){return this.backends.get(id)}getOrDefault(id){let registered=this.backends.get(id);if(registered)return registered;let profile=LANGUAGE_REGISTRY.get(id);if(!profile)return;return defaultBackendFor(profile)}unregister(id){this.backends.delete(id)}}var LANGUAGE_BACKEND_REGISTRY;var init_registry_backend=__esm(()=>{init_default_backend();init_profiles();LANGUAGE_BACKEND_REGISTRY=new LanguageBackendRegistry});import*as fs136 from"node:fs";import*as path251 from"node:path";function detectLaravelProject(directory){let signals=getLaravelSignals(directory);return[signals.hasArtisanFile,signals.hasLaravelFrameworkDep,signals.hasConfigApp].filter(Boolean).length>=2}function getLaravelSignals(directory){let hasArtisanFile=checkArtisanFile(directory),hasLaravelFrameworkDep=checkLaravelFrameworkDep(directory),hasConfigApp=checkConfigApp(directory);return{hasArtisanFile,hasLaravelFrameworkDep,hasConfigApp}}function checkArtisanFile(directory){let artisanPath=path251.join(directory,"artisan");if(!fs136.existsSync(artisanPath))return!1;try{return fs136.statSync(artisanPath).isFile()}catch{return!1}}function checkLaravelFrameworkDep(directory){let composerPath=path251.join(directory,"composer.json");if(!fs136.existsSync(composerPath))return!1;try{let content=fs136.readFileSync(composerPath,"utf-8");return typeof(JSON.parse(content)?.require??{})["laravel/framework"]==="string"}catch{return!1}}function checkConfigApp(directory){return fs136.existsSync(path251.join(directory,"config","app.php"))}function isLarastanConfigured(directory){let neonPath=path251.join(directory,"phpstan.neon");if(!fs136.existsSync(neonPath))return!1;try{let fd=fs136.openSync(neonPath,"r");try{let buf=Buffer.alloc(4096),bytesRead=fs136.readSync(fd,buf,0,4096,0),content=buf.subarray(0,bytesRead).toString("utf-8");return content.includes("nunomaduro/larastan")||content.includes("larastan/larastan")}finally{fs136.closeSync(fd)}}catch{return!1}}function getLaravelCommandOverlay(directory){if(!detectLaravelProject(directory))return null;let lintCommand=null;if(fs136.existsSync(path251.join(directory,"pint.json")))lintCommand="vendor/bin/pint --test";else if(fs136.existsSync(path251.join(directory,".php-cs-fixer.php")))lintCommand="vendor/bin/php-cs-fixer fix --dry-run --diff";let staticAnalysisCommand=null,staticAnalysisTool=null,hasPhpstanNeon=fs136.existsSync(path251.join(directory,"phpstan.neon")),hasPhpstanNeonDist=fs136.existsSync(path251.join(directory,"phpstan.neon.dist"));if(hasPhpstanNeon||hasPhpstanNeonDist)staticAnalysisCommand="vendor/bin/phpstan analyse",staticAnalysisTool=isLarastanConfigured(directory)?"larastan":"phpstan";return{testCommand:"php artisan test",lintCommand,staticAnalysisCommand,staticAnalysisTool,auditCommand:"composer audit --locked --format=json",supportsParallel:!0}}var init_framework_detector=()=>{};import*as fs137 from"node:fs";import*as path252 from"node:path";async function selectFramework4(dir){if(detectLaravelProject(dir))return{name:"laravel",detectedVia:"Laravel signals (artisan / composer.json / config/app.php)"};return null}async function selectTestFramework2(dir){if(detectLaravelProject(dir))return{name:"php-artisan",cmd:["php","artisan","test"],cwd:dir,detectedVia:"Laravel signals (artisan / composer.json / config/app.php)"};if(fs137.existsSync(path252.join(dir,"Pest.php")))return{name:"pest",cmd:buildPhpVendorCommand(dir,"pest"),cwd:dir,detectedVia:"Pest.php"};if(fs137.existsSync(path252.join(dir,"phpunit.xml")))return{name:"phpunit",cmd:buildPhpVendorCommand(dir,"phpunit"),cwd:dir,detectedVia:"phpunit.xml"};if(fs137.existsSync(path252.join(dir,"phpunit.xml.dist")))return{name:"phpunit",cmd:buildPhpVendorCommand(dir,"phpunit"),cwd:dir,detectedVia:"phpunit.xml.dist"};return null}function buildPhpBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)throw Error("buildPhpBackend: php profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...defaultBackendFor(profile),selectFramework:selectFramework4,selectTestFramework:selectTestFramework2}}var PROFILE_ID4="php";var init_php2=__esm(()=>{init_default_backend();init_framework_detector();init_profiles()});import*as fs138 from"node:fs";import*as path253 from"node:path";function readPackageJsonRaw(dir){try{let content=fs138.readFileSync(path253.join(dir,"package.json"),"utf-8");return JSON.parse(content)}catch{return null}}function readPackageJson(dir){return _internals209.readPackageJsonRaw(dir)}function readPackageJsonTestScript(dir){return readPackageJson(dir)?.scripts?.test??null}function frameworkFromScriptsTest(script){if(script.includes("vitest"))return"vitest";if(script.includes("jest"))return"jest";if(script.includes("mocha"))return"mocha";if(script.includes("bun test"))return"bun:test";return null}function frameworkFromDevDeps(devDeps){if(!devDeps)return null;if(devDeps.vitest||devDeps["@vitest/ui"])return"vitest";if(devDeps.jest||devDeps["@types/jest"])return"jest";if(devDeps.mocha||devDeps["@types/mocha"])return"mocha";return null}function selectionFromFramework(profile,fwName,dir,detectedVia){let fw=profile.test.frameworks.find((f)=>f.name===fwName);if(!fw)return null;let argv=tokenizeCommand(fw.cmd);if(argv.length===0)return null;return{name:fw.name,cmd:argv,cwd:dir,detectedVia,filesIgnored:!1}}async function selectTestFramework3(dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)return null;let pkg=readPackageJson(dir),script=pkg?.scripts?.test;if(script){let fwName=frameworkFromScriptsTest(script);if(fwName){let sel=selectionFromFramework(profile,fwName,dir,"package.json#scripts.test");if(sel)return sel}}let devDepsFw=frameworkFromDevDeps(pkg?.devDependencies);if(devDepsFw){let sel=selectionFromFramework(profile,devDepsFw,dir,"package.json#devDependencies");if(sel)return sel}return defaultSelectTestFramework(profile,dir)}function buildTestCommand2(framework,files,dir,opts){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)return null;return defaultBuildTestCommand(profile,framework,files,dir,opts)}function parseTestOutput(framework,stdout,stderr,exitCode){return defaultParseTestOutput(framework,stdout,stderr,exitCode)}async function selectFramework5(dir){let pkg=readPackageJson(dir);if(!pkg)return null;let deps={...pkg.dependencies,...pkg.devDependencies},order=[["next","next"],["nuxt","nuxt"],["@angular/core","angular"],["svelte","svelte"],["react","react"],["vue","vue"],["express","express"],["fastify","fastify"],["@nestjs/core","nestjs"]];for(let[pkgName,displayName]of order)if(deps[pkgName])return{name:displayName,detectedVia:`package.json#dependencies.${pkgName}`};return null}async function selectEntryPoints4(dir){let pkg=readPackageJson(dir);if(!pkg)return[];let points=[],obj=pkg;if(obj.bin)if(typeof obj.bin==="string")points.push(obj.bin);else for(let v of Object.values(obj.bin))points.push(v);if(obj.main)points.push(obj.main);if(obj.module&&obj.module!==obj.main)points.push(obj.module);if(obj.exports&&typeof obj.exports==="object"){let root=obj.exports["."];if(typeof root==="string"&&!points.includes(root))points.push(root)}return[...new Set(points.filter((p)=>p.length>0))]}function extractImports5(_sourceFile,source){let out=new Set;for(let re of[IMPORT_REGEX_ES,IMPORT_REGEX_BARE,IMPORT_REGEX_REQUIRE2,IMPORT_REGEX_DYNAMIC,IMPORT_REGEX_REEXPORT2]){re.lastIndex=0;let m=re.exec(source);while(m!==null)out.add(m[1]),m=re.exec(source)}return[...out]}async function selectBuildCommand(dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)return null;return defaultSelectBuildCommand(profile,dir)}async function testFilesFor(sourceFile,dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)return[];return defaultTestFilesFor(profile,sourceFile,dir)}function buildTypescriptBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)throw Error("buildTypescriptBackend: typescript profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...profile,selectTestFramework:selectTestFramework3,buildTestCommand:buildTestCommand2,parseTestOutput,extractImports:extractImports5,selectBuildCommand,testFilesFor,selectFramework:selectFramework5,selectEntryPoints:selectEntryPoints4}}var PROFILE_ID5="typescript",IMPORT_REGEX_ES,IMPORT_REGEX_BARE,IMPORT_REGEX_REQUIRE2,IMPORT_REGEX_DYNAMIC,IMPORT_REGEX_REEXPORT2,_internals209;var init_typescript=__esm(()=>{init_default_backend();init_profiles();IMPORT_REGEX_ES=/import\s+[\s\S]*?\s+from\s+['"]([^'"]+)['"]/g,IMPORT_REGEX_BARE=/import\s+['"]([^'"]+)['"]/g,IMPORT_REGEX_REQUIRE2=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,IMPORT_REGEX_DYNAMIC=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,IMPORT_REGEX_REEXPORT2=/export\s+(?:\{[^}]*\}|\*)\s+from\s+['"]([^'"]+)['"]/g;_internals209={readPackageJsonRaw,readPackageJsonTestScript,frameworkFromScriptsTest}});function registerAllBackends(){if(registered)return;LANGUAGE_BACKEND_REGISTRY.register(buildTypescriptBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildPythonBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildGoBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildJavaBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildPhpBackend()),registered=!0}var registered=!1;var init_backends=__esm(()=>{init_registry_backend();init_go2();init_java2();init_php2();init_python2();init_typescript();registerAllBackends()});import*as fs139 from"node:fs";import*as path254 from"node:path";function hasManifestInDirectory(directory){try{return fs139.readdirSync(directory).some((entry)=>MANIFEST_SET.has(entry))}catch{return!1}}function findGitMarkerAncestor(start){let current=path254.resolve(start);for(let depth=0;depth<32;depth++){let marker=path254.join(current,".git");try{if(!fs139.lstatSync(marker).isSymbolicLink())return current}catch(error93){let code=error93.code;if(code!=="ENOENT"&&code!=="ENOTDIR")return}let parent=path254.dirname(current);if(parent===current)return null;current=parent}return}function hasManifestAncestor(start){let resolved=path254.resolve(start),gitRoot=findGitMarkerAncestor(resolved);if(gitRoot===void 0)return!0;if(gitRoot===null)return hasManifestInDirectory(resolved);let current=resolved;for(let depth=0;depth<32;depth++){if(hasManifestInDirectory(current))return!0;if(current===gitRoot)return!1;let parent=path254.dirname(current);if(parent===current)return!1;current=parent}return!0}function hasGitMarkerAncestor(start){return findGitMarkerAncestor(start)!==null}function hasSwarmState(start){try{return fs139.lstatSync(path254.join(path254.resolve(start),".swarm")),!0}catch(error93){let code=error93.code;return code!=="ENOENT"&&code!=="ENOTDIR"}}var MANIFEST_FILES,MANIFEST_SET;var init_manifest_files=__esm(()=>{MANIFEST_FILES=["package.json","tsconfig.json","pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","Cargo.toml","go.mod","pom.xml","build.gradle","build.gradle.kts","build.zig","CMakeLists.txt","Makefile","meson.build","Package.swift","pubspec.yaml","Gemfile","composer.json"],MANIFEST_SET=new Set(MANIFEST_FILES)});var exports_dispatch={};__export(exports_dispatch,{pickedProfiles:()=>pickedProfiles,pickBackend:()=>pickBackend,clearDispatchCache:()=>clearDispatchCache,_internals:()=>_internals210});import*as fs140 from"node:fs";import*as path255 from"node:path";async function tryReadDirectoryAsync(dir){try{return new Set(await fs140.promises.readdir(dir))}catch{return null}}async function manifestHash(dir,signal){let entries2=await tryReadDirectoryAsync(dir);if(throwIfAborted3(signal),entries2===null||entries2.size===0)return"";let names=MANIFEST_FILES.filter((name)=>entries2.has(name)),parts=await Promise.all(names.map(async(name)=>{try{let stat23=await fs140.promises.stat(path255.join(dir,name));return`${name}:${stat23.size}:${stat23.mtimeMs}:${stat23.ino}`}catch{return null}}));return throwIfAborted3(signal),parts.filter((part)=>part!==null).join("|")}function cacheProfileKey(input,cacheKey){let key2=canonicalRootKeyLexical(input);profileCacheKeyByInput.delete(key2),profileCacheKeyByInput.set(key2,cacheKey);while(profileCacheKeyByInput.size>_internals210.cacheCapacity){let oldest=profileCacheKeyByInput.keys().next().value;if(oldest===void 0)break;profileCacheKeyByInput.delete(oldest)}}async function directoryFingerprint(dir){try{let stat23=await fs140.promises.stat(dir);if(!stat23.isDirectory())return null;return{directory:dir,dev:stat23.dev,ino:stat23.ino,size:stat23.size,mtimeMs:stat23.mtimeMs,ctimeMs:stat23.ctimeMs}}catch{return null}}function fingerprintsMatch(expected,actual){return expected.dev===actual.dev&&expected.ino===actual.ino&&expected.size===actual.size&&expected.mtimeMs===actual.mtimeMs&&expected.ctimeMs===actual.ctimeMs}async function readDirectoryForManifestWalk(dir){let entries2=await tryReadDirectoryAsync(dir),fingerprint2=await directoryFingerprint(dir),after=await tryReadDirectoryAsync(dir);if(entries2===null||fingerprint2===null||after===null)return{entries:null,complete:!1,stopAtCurrent:!0};if(entries2.size!==after.size||[...entries2].some((entry)=>!after.has(entry)))return{entries:null,complete:!1,stopAtCurrent:!1};return{entries:entries2,fingerprint:fingerprint2,complete:!0}}async function isManifestRootCacheEntryValid(entry){for(let fingerprint2 of entry.trace){let current=await directoryFingerprint(fingerprint2.directory);if(current===null||!fingerprintsMatch(fingerprint2,current))return!1}return!0}async function isSelectedRootObservationStillValid(resolution,hash5,signal){let currentHash=await manifestHash(resolution.root,signal);if(throwIfAborted3(signal),currentHash!==hash5||resolution.rootHadManifest&¤tHash==="")return!1;return!0}function evictManifestRootCacheIfNeeded(){if(manifestRootCache.size<=_internals210.cacheCapacity)return;let oldestKey,oldestOrder=1/0;for(let[key2,value]of manifestRootCache)if(value.insertOrder<oldestOrder)oldestKey=key2,oldestOrder=value.insertOrder;if(oldestKey!==void 0)manifestRootCache.delete(oldestKey)}function cacheManifestRoot(key2,root,rootHadManifest,trace,cacheable,signal){if(!cacheable||signal?.aborted)return;manifestRootCache.set(key2,{root,rootHadManifest,trace,insertOrder:manifestRootInsertCounter++}),evictManifestRootCacheIfNeeded()}function throwIfAborted3(signal){if(signal?.aborted)throw signal.reason??Error("manifest-root lookup aborted")}async function findManifestRoot(start,signal){throwIfAborted3(signal);let resolved=path255.resolve(start),key2=await canonicalRootKeyFreshAsync(resolved);throwIfAborted3(signal);let cached3=manifestRootCache.get(key2);if(cached3!==void 0){if(await isManifestRootCacheEntryValid(cached3))return throwIfAborted3(signal),{root:cached3.root,rootHadManifest:cached3.rootHadManifest,key:key2,trace:[],cacheable:!1};manifestRootCache.delete(key2)}let cur=resolved,trace=[],cacheable=!0;for(let i=0;i<MAX_MANIFEST_SEARCH_DEPTH;i++){let snapshot=await readDirectoryForManifestWalk(cur);if(throwIfAborted3(signal),!snapshot.complete){if(snapshot.stopAtCurrent)return{root:cur,rootHadManifest:!1,key:key2,trace,cacheable:!1};cacheable=!1}else trace.push(snapshot.fingerprint);let{entries:entries2}=snapshot;if(entries2!==null){if(entries2.size>0){for(let name of MANIFEST_FILES)if(entries2.has(name))return{root:cur,rootHadManifest:!0,key:key2,trace,cacheable};if(entries2.has(".git"))return{root:cur,rootHadManifest:!1,key:key2,trace,cacheable}}}let parent=path255.dirname(cur);if(parent===cur)break;cur=parent}return{root:start,rootHadManifest:!1,key:key2,trace,cacheable}}function evictIfNeeded(){if(cache5.size<=_internals210.cacheCapacity)return;let oldestKey,oldestOrder=1/0;for(let[k,v]of cache5.entries())if(v.insertOrder<oldestOrder)oldestOrder=v.insertOrder,oldestKey=k;if(oldestKey!==void 0)cache5.delete(oldestKey)}async function pickBackend(dir,signal){for(let attempt=0;attempt<2;attempt++){let resolution=await findManifestRoot(dir,signal),{root}=resolution;throwIfAborted3(signal);let hash5=await manifestHash(root,signal);if(throwIfAborted3(signal),resolution.rootHadManifest&&hash5===""){if(manifestRootCache.delete(resolution.key),attempt===0)continue;return profileCacheKeyByInput.delete(canonicalRootKeyLexical(dir)),null}let cacheKey=await canonicalRootKeyFreshAsync(root);throwIfAborted3(signal);let cached3=cache5.get(cacheKey);if(cached3&&cached3.hash===hash5)return cacheManifestRoot(resolution.key,root,resolution.rootHadManifest,resolution.trace,resolution.cacheable,signal),cacheProfileKey(dir,cacheKey),cached3.backend;if(hash5==="")return cacheManifestRoot(resolution.key,root,resolution.rootHadManifest,resolution.trace,resolution.cacheable,signal),cache5.set(cacheKey,{hash:hash5,backend:null,profiles:[],insertOrder:insertCounter++}),evictIfNeeded(),cacheProfileKey(dir,cacheKey),null;let profiles=await _internals210.detectProjectLanguages(root);if(throwIfAborted3(signal),!await isSelectedRootObservationStillValid(resolution,hash5,signal)){if(manifestRootCache.delete(resolution.key),attempt===0)continue;return profileCacheKeyByInput.delete(canonicalRootKeyLexical(dir)),null}if(cacheManifestRoot(resolution.key,root,resolution.rootHadManifest,resolution.trace,resolution.cacheable,signal),profiles.length===0)return cache5.set(cacheKey,{hash:hash5,backend:null,profiles:[],insertOrder:insertCounter++}),evictIfNeeded(),cacheProfileKey(dir,cacheKey),null;let winner=profiles[0],backend=LANGUAGE_BACKEND_REGISTRY.getOrDefault(winner.id)??null;return cache5.set(cacheKey,{hash:hash5,backend,profiles:profiles.map((p)=>({id:p.id})),insertOrder:insertCounter++}),evictIfNeeded(),cacheProfileKey(dir,cacheKey),backend}return null}function pickedProfiles(dir){let cacheKey=profileCacheKeyByInput.get(canonicalRootKeyLexical(dir));if(cacheKey===void 0)return[];return cache5.get(cacheKey)?.profiles??[]}function clearDispatchCache(){cache5.clear(),manifestRootCache.clear(),profileCacheKeyByInput.clear(),insertCounter=0,manifestRootInsertCounter=0}var _internals210,cache5,insertCounter=0,MAX_MANIFEST_SEARCH_DEPTH=32,manifestRootCache,manifestRootInsertCounter=0,profileCacheKeyByInput;var init_dispatch=__esm(()=>{init_backends();init_canonical_root();init_detector();init_manifest_files();init_registry_backend();_internals210={detectProjectLanguages,cacheCapacity:64,get manifestRootCacheSize(){return manifestRootCache.size}},cache5=new Map;manifestRootCache=new Map,profileCacheKeyByInput=new Map});import*as fs141 from"node:fs";import*as path256 from"node:path";async function estimateFanOut(sourceFiles,cwd){try{let impactMap=await _internals211.loadImpactMap(cwd,{skipRebuild:!0}),uniqueTestFiles=new Set;for(let sourceFile of sourceFiles){let normalizedPath=path256.resolve(cwd,sourceFile).replace(/\\/g,"/"),testFiles=impactMap[normalizedPath];if(testFiles)for(let testFile of testFiles){let normalized=testFile.replace(/\\/g,"/");uniqueTestFiles.add(process.platform==="win32"?normalized.toLowerCase():normalized)}}return{estimatedCount:uniqueTestFiles.size,status:"advisory"}}catch{return{estimatedCount:0,status:"unavailable"}}}function normalizeSelectionFiles(files,workingDir){let seen=new Set,normalized=[];for(let file3 of files){let absolute=path256.resolve(workingDir,file3),relative61=path256.relative(workingDir,absolute),output=(path256.isAbsolute(relative61)?absolute:relative61).replace(/\\/g,"/"),key2=process.platform==="win32"?output.toLowerCase():output;if(!seen.has(key2))seen.add(key2),normalized.push(output)}return normalized}function makeResolution(requestedScope,effectiveScope,sourceFiles,resolvedFiles,decision,workingDir,options){let estimateCount=options?.estimate?.estimatedCount??0,estimateStatus=options?.estimate?.status??"not_run",fallbackReason=options?.fallbackReason??(options?.cacheStatus?.startsWith("rebuilt_")?`impact cache rebuild completed (${options.cacheStatus}) before resolution`:null);return{requestedScope,effectiveScope,sourceFiles:normalizeSelectionFiles(sourceFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1),resolvedFiles:normalizeSelectionFiles(resolvedFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1),cap:MAX_SAFE_TEST_FILES2,decision,estimate:{count:estimateCount,status:estimateStatus},estimateCount,estimateStatus,...options?.cacheStatus&&{cacheStatus:options.cacheStatus},fallbackReason,evaluable:decision==="execute"}}function resolutionFields(resolution){return{resolved_test_files:resolution.resolvedFiles,cap_decision:{decision:resolution.decision==="scope_exceeded"?"cap_exceeded":"within_cap",resolved_test_count:resolution.resolvedFiles.length,limit:resolution.cap},...resolution.fallbackReason?{fallback_reason:resolution.fallbackReason}:{}}}function cacheStatusAfterRebuild(before,after){let normalize25=(status2)=>status2.endsWith("_unverified")?status2.slice(0,-11):status2,beforeState=normalize25(before),afterState=normalize25(after);if(afterState==="fresh"){if(beforeState==="missing"||beforeState==="corrupt"||beforeState==="legacy"||beforeState==="stale")return`rebuilt_${beforeState}`}return afterState===beforeState?afterState:after}async function loadImpactMapForImpactScope(workingDir){if(_internals211.loadImpactMap!==DEFAULT_LOAD_IMPACT_MAP){let before=getImpactCacheStatus(workingDir,{verify:!1}).status,map3=await _internals211.loadImpactMap(workingDir),after=getImpactCacheStatus(workingDir,{verify:!1}).status;return{map:map3,status:cacheStatusAfterRebuild(before,after)}}return _internals211.loadImpactMapWithStatus(workingDir)}function cacheStatusForAdvisory(status2){if(status2==="missing")return"missing_unverified";if(status2==="corrupt")return"corrupt_unverified";if(status2==="legacy")return"legacy_unverified";return status2}function isAbsolutePath(str){if(str.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test(str))return!0;if(/^\\\\/.test(str))return!0;if(/^\\\\\.\\/.test(str))return!0;return!1}function containsPowerShellMetacharacters(str){return POWERSHELL_METACHARACTERS.test(str)}function containsShellMetacharacters(str){return SHELL_METACHARACTERS2.test(str)}function validateArgs2(args2){if(typeof args2!=="object"||args2===null)return!1;let obj=args2;if(obj.scope!==void 0){if(obj.scope!=="all"&&obj.scope!=="convention"&&obj.scope!=="graph"&&obj.scope!=="impact"&&obj.scope!=="target")return!1}if(obj.native_target!==void 0){if(typeof obj.native_target!=="object"||obj.native_target===null)return!1;let target=obj.native_target;if(target.framework!=="go-test"&&target.framework!=="ctest")return!1;if(typeof target.name!=="string"||typeof target.path!=="string")return!1;if(target.name.length===0||target.name.length>256)return!1;if(target.path.length===0||target.path.length>1024)return!1;if(containsControlChars(target.name)||containsControlChars(target.path))return!1;if(target.framework==="go-test"&&target.name.split("/").some((p)=>!p))return!1;if(isAbsolutePath(target.path)||containsPathTraversal(target.path))return!1}if(obj.scope==="target"){if(obj.native_target===void 0)return!1;if(Array.isArray(obj.files)&&obj.files.length>0)return!1;if(obj.coverage===!0||obj.bail===!0)return!1}else if(obj.native_target!==void 0)return!1;if(obj.files!==void 0){if(!Array.isArray(obj.files))return!1;if(obj.files.length>MAX_RAW_FILE_ENTRIES)return!1;for(let f of obj.files){if(typeof f!=="string")return!1;if(f.length===0||f.length>MAX_FILE_PATH_LENGTH2)return!1;if(isAbsolutePath(f))return!1;if(containsPathTraversal(f))return!1;if(containsControlChars(f))return!1;if(containsPowerShellMetacharacters(f))return!1}}if(obj.targets!==void 0){if(!Array.isArray(obj.targets))return!1;for(let t of obj.targets){if(typeof t!=="string")return!1;if(t.length===0)return!1;if(isAbsolutePath(t))return!1;if(containsPathTraversal(t))return!1;if(containsControlChars(t))return!1;if(containsShellMetacharacters(t))return!1}}if(obj.coverage!==void 0){if(typeof obj.coverage!=="boolean")return!1}if(obj.bail!==void 0){if(typeof obj.bail!=="boolean")return!1}if(obj.timeout_ms!==void 0){if(typeof obj.timeout_ms!=="number")return!1;if(obj.timeout_ms<0||obj.timeout_ms>MAX_TIMEOUT_MS3)return!1}return!0}function validateNativeTargetInput(target){if(target.framework!=="go-test"&&target.framework!=="ctest")return'Native target framework must be "go-test" or "ctest"';if(typeof target.name!=="string"||target.name.length===0||target.name.length>256)return"Native target name must be a non-empty string up to 256 characters";if(typeof target.path!=="string"||target.path.length===0||target.path.length>1024)return"Native target path must be a non-empty string up to 1024 characters";if(containsControlChars(target.name)||containsControlChars(target.path))return"Native target values must not contain control characters";if(target.framework==="go-test"&&target.name.split("/").some((p)=>!p))return"Go native target name must not contain empty slash-separated segments";if(isAbsolutePath(target.path))return"Native target path must be workspace-relative, not absolute";if(containsPathTraversal(target.path))return"Native target path escapes project root";return}function resolveNativeTarget(target,workingDir){let rootReal,targetReal;try{if(rootReal=fs141.realpathSync(workingDir),targetReal=fs141.realpathSync(path256.resolve(rootReal,target.path)),!fs141.statSync(targetReal).isDirectory())return{success:!1,error:"Native target path must be a directory"}}catch{return{success:!1,error:"Native target path does not exist"}}let relative61=path256.relative(rootReal,targetReal);if(relative61.startsWith("..")||path256.isAbsolute(relative61))return{success:!1,error:"Native target path escapes project root"};if(!_internals211.isCommandAvailable(target.framework==="go-test"?"go":"ctest"))return{success:!1,error:`Native target framework "${target.framework}" is unavailable`};let executionDirectory=rootReal,commandRelative=relative61;if(target.framework==="go-test"){let hasRootWorkspace=fs141.existsSync(path256.join(rootReal,"go.work")),moduleRoot;for(let current=targetReal;;current=path256.dirname(current)){if(fs141.existsSync(path256.join(current,"go.mod"))){moduleRoot=current;break}if(current===rootReal)break;let parent=path256.dirname(current);if(parent===current||path256.relative(rootReal,parent).startsWith(".."))break}if(!hasRootWorkspace&&!moduleRoot)return{success:!1,error:"Go native target requires an enclosing go.mod or go.work at the project root"};if(!hasRootWorkspace&&moduleRoot)executionDirectory=moduleRoot,commandRelative=path256.relative(moduleRoot,targetReal)}else if(!fs141.existsSync(path256.join(targetReal,"CMakeCache.txt")))return{success:!1,error:"CTest native target requires CMakeCache.txt in the target directory"};return{success:!0,target:{...target,path:commandRelative.length===0?".":commandRelative.replace(/\\/g,"/")},executionDirectory,historyPath:relative61.length===0?".":relative61.replace(/\\/g,"/")}}function hasPackageJsonDependency(deps,...patterns){for(let pattern of patterns)if(deps[pattern])return!0;return!1}function hasDevDependency(devDeps,...patterns){if(!devDeps)return!1;return hasPackageJsonDependency(devDeps,...patterns)}function detectGoTest(cwd){return _internals211.existsSync(path256.join(cwd,"go.mod"))&&_internals211.isCommandAvailable("go")}function detectJavaMaven(cwd){return _internals211.existsSync(path256.join(cwd,"pom.xml"))&&_internals211.isCommandAvailable("mvn")}function detectGradle(cwd){let hasBuildFile=_internals211.existsSync(path256.join(cwd,"build.gradle"))||_internals211.existsSync(path256.join(cwd,"build.gradle.kts")),hasGradlew=_internals211.existsSync(path256.join(cwd,"gradlew"))||_internals211.existsSync(path256.join(cwd,"gradlew.bat"));return hasBuildFile&&(hasGradlew||_internals211.isCommandAvailable("gradle"))}function detectDotnetTest(cwd){try{return _internals211.readdirSync(cwd).some((f)=>f.endsWith(".csproj"))&&_internals211.isCommandAvailable("dotnet")}catch{return!1}}function detectCTest(cwd){let hasSource=_internals211.existsSync(path256.join(cwd,"CMakeLists.txt")),hasBuildCache=_internals211.existsSync(path256.join(cwd,"CMakeCache.txt"))||_internals211.existsSync(path256.join(cwd,"build","CMakeCache.txt"));return(hasSource||hasBuildCache)&&_internals211.isCommandAvailable("ctest")}function detectSwiftTest(cwd){return _internals211.existsSync(path256.join(cwd,"Package.swift"))&&_internals211.isCommandAvailable("swift")}function detectDartTest(cwd){return _internals211.existsSync(path256.join(cwd,"pubspec.yaml"))&&(_internals211.isCommandAvailable("dart")||_internals211.isCommandAvailable("flutter"))}function detectRSpec(cwd){let hasRSpecFile=_internals211.existsSync(path256.join(cwd,".rspec")),hasGemfile=_internals211.existsSync(path256.join(cwd,"Gemfile")),hasSpecDir=_internals211.existsSync(path256.join(cwd,"spec"));return(hasRSpecFile||hasGemfile&&hasSpecDir)&&(_internals211.isCommandAvailable("bundle")||_internals211.isCommandAvailable("rspec"))}function detectMinitest(cwd){return _internals211.existsSync(path256.join(cwd,"test"))&&(_internals211.existsSync(path256.join(cwd,"Gemfile"))||_internals211.existsSync(path256.join(cwd,"Rakefile")))&&_internals211.isCommandAvailable("ruby")}async function detectTestFrameworkViaDispatch(cwd){try{let{pickBackend:pickBackend2}=await Promise.resolve().then(() => (init_dispatch(),exports_dispatch)),backend=await pickBackend2(cwd);if(!backend?.selectTestFramework)return"none";let sel=await backend.selectTestFramework(cwd);if(!sel)return"none";return DISPATCH_FRAMEWORK_MAP[sel.name]??"none"}catch{return"none"}}async function buildTestCommandViaDispatch(framework,scope,files,coverage,baseDir,bail,targets,nativeTarget){if(framework==="none")return null;try{let{pickBackend:pickBackend2}=await Promise.resolve().then(() => (init_dispatch(),exports_dispatch)),backend=await pickBackend2(baseDir);if(backend?.buildTestCommand){let cmd=backend.buildTestCommand(framework,files,baseDir,{scope,coverage,bail,targets,nativeTarget});if(cmd)return cmd}return null}catch{return null}}async function parseTestOutputViaDispatch(framework,output,baseDir){if(framework==="none")return null;try{let{pickBackend:pickBackend2}=await Promise.resolve().then(() => (init_dispatch(),exports_dispatch)),backend=await pickBackend2(baseDir);if(!backend?.parseTestOutput)return null;let summary=backend.parseTestOutput(framework,output,"",0),passed=summary.passed??0,failed=summary.failed??0,skipped=summary.skipped??0,total=summary.total??passed+failed+skipped,result={totals:{passed,failed,skipped,total}};if(summary.coveragePercent!==void 0)result.coveragePercent=summary.coveragePercent;return result}catch{return null}}function relativeEscapesRoot(relative61){return relative61===".."||relative61.startsWith(`..${path256.sep}`)||path256.isAbsolute(relative61)}function resolveMavenModuleDir(root,files){let resolvedRoot=path256.resolve(root),rootReal,isContainedModuleDir=(dir)=>{if(rootReal===void 0)try{rootReal=_internals211.realpathSync(resolvedRoot)}catch{rootReal=null}if(rootReal===null)return!1;let dirReal;try{dirReal=_internals211.realpathSync(dir)}catch{return!1}return!relativeEscapesRoot(path256.relative(rootReal,dirReal))};if(files&&files.length>0){for(let file3 of files){let resolvedFile=path256.resolve(resolvedRoot,file3),relativeToRoot=path256.relative(resolvedRoot,resolvedFile);if(relativeEscapesRoot(relativeToRoot))continue;let current=path256.dirname(resolvedFile);while(!0){if(_internals211.existsSync(path256.join(current,"pom.xml"))&&isContainedModuleDir(current))return current;if(current===resolvedRoot)break;let parent=path256.dirname(current);if(parent===current)break;if(relativeEscapesRoot(path256.relative(resolvedRoot,parent)))break;current=parent}}return null}let entries2;try{entries2=_internals211.readdirSync(resolvedRoot)}catch{return null}entries2.sort((a,b)=>a.localeCompare(b));let inspected=0;for(let entry of entries2){if(entry.startsWith(".")||entry==="node_modules")continue;if(inspected>=MAX_MAVEN_MODULE_PROBE_ENTRIES)break;inspected++;let candidate2=path256.join(resolvedRoot,entry);if(_internals211.existsSync(path256.join(candidate2,"pom.xml"))&&isContainedModuleDir(candidate2))return candidate2}return null}function resolveNestedMavenModuleDir(root,files){if(_internals211.existsSync(path256.join(root,"pom.xml")))return null;return resolveMavenModuleDir(root,files)}async function detectTestFramework(cwd,files){let baseDir=cwd;try{let packageJsonPath=path256.join(baseDir,"package.json");if(_internals211.existsSync(packageJsonPath)){let content=_internals211.readFileSync(packageJsonPath,"utf-8"),pkg=JSON.parse(content),_deps=pkg.dependencies||{},devDeps=pkg.devDependencies||{},scripts=pkg.scripts||{};if(scripts.test?.includes("vitest"))return"vitest";if(scripts.test?.includes("jest"))return"jest";if(scripts.test?.includes("mocha"))return"mocha";if(scripts.test?.includes("bun test"))return"bun";if(hasDevDependency(devDeps,"vitest","@vitest/ui"))return"vitest";if(hasDevDependency(devDeps,"jest","@types/jest"))return"jest";if(hasDevDependency(devDeps,"mocha","@types/mocha"))return"mocha";if(_internals211.existsSync(path256.join(baseDir,"bun.lockb"))||_internals211.existsSync(path256.join(baseDir,"bun.lock"))){if(scripts.test?.includes("bun"))return"bun"}}}catch{}try{let pyprojectTomlPath=path256.join(baseDir,"pyproject.toml"),setupCfgPath=path256.join(baseDir,"setup.cfg"),requirementsTxtPath=path256.join(baseDir,"requirements.txt");if(_internals211.existsSync(pyprojectTomlPath)){let content=_internals211.readFileSync(pyprojectTomlPath,"utf-8");if(content.includes("[tool.pytest"))return"pytest";if(content.includes("pytest"))return"pytest"}if(_internals211.existsSync(setupCfgPath)){if(_internals211.readFileSync(setupCfgPath,"utf-8").includes("[pytest]"))return"pytest"}if(_internals211.existsSync(requirementsTxtPath)){if(_internals211.readFileSync(requirementsTxtPath,"utf-8").includes("pytest"))return"pytest"}}catch{}try{let cargoTomlPath=path256.join(baseDir,"Cargo.toml");if(_internals211.existsSync(cargoTomlPath)){let content=_internals211.readFileSync(cargoTomlPath,"utf-8");if(content.includes("[dev-dependencies]")){if(content.includes("tokio")||content.includes("mockall")||content.includes("pretty_assertions"))return"cargo"}}}catch{}try{let pesterConfigPath=path256.join(baseDir,"pester.config.ps1"),pesterConfigJsonPath=path256.join(baseDir,"pester.config.ps1.json"),pesterPs1Path=path256.join(baseDir,"tests.ps1");if(_internals211.existsSync(pesterConfigPath)||_internals211.existsSync(pesterConfigJsonPath)||_internals211.existsSync(pesterPs1Path))return"pester"}catch{}let phpFramework=detectPhpTest(baseDir);if(phpFramework)return phpFramework;if(detectGoTest(baseDir))return"go-test";if(detectJavaMaven(baseDir))return"maven";if(detectGradle(baseDir))return"gradle";if(detectDotnetTest(baseDir))return"dotnet-test";if(detectCTest(baseDir))return"ctest";if(detectSwiftTest(baseDir))return"swift-test";if(detectDartTest(baseDir))return"dart-test";if(detectRSpec(baseDir))return"rspec";if(detectMinitest(baseDir))return"minitest";let mavenModuleDir=resolveNestedMavenModuleDir(baseDir,files);if(mavenModuleDir&&(_internals211.isCommandAvailable("mvn")||resolveMavenWrapperCommand(mavenModuleDir,["test"])!==null))return"maven";return"none"}function detectPhpTest(cwd){if(_internals211.existsSync(path256.join(cwd,"artisan"))&&_internals211.existsSync(path256.join(cwd,"composer.json")))return"php-artisan";if(_internals211.existsSync(path256.join(cwd,"Pest.php")))return"pest";if(_internals211.existsSync(path256.join(cwd,"phpunit.xml"))||_internals211.existsSync(path256.join(cwd,"phpunit.xml.dist")))return"phpunit";return null}function isTestDirectoryPath(normalizedPath){return normalizedPath.split("/").some((segment)=>TEST_DIRECTORY_NAMES.includes(segment))}function resolveWorkspacePath(file3,workingDir){return path256.isAbsolute(file3)?path256.resolve(file3):path256.resolve(workingDir,file3)}function toWorkspaceOutputPath(absolutePath2,workingDir,preferRelative){if(!preferRelative)return absolutePath2;return path256.relative(workingDir,absolutePath2)}function dedupePush(target,value){if(!target.includes(value))target.push(value)}function buildLanguageSpecificTestNames(nameWithoutExt,ext){switch(ext){case".go":return[`${nameWithoutExt}_test.go`];case".py":return[`test_${nameWithoutExt}.py`,`${nameWithoutExt}_test.py`];case".rb":return[`${nameWithoutExt}_spec.rb`];case".java":return[`${nameWithoutExt}Test.java`,`${nameWithoutExt}Tests.java`,`Test${nameWithoutExt}.java`,`${nameWithoutExt}IT.java`];case".cs":return[`${nameWithoutExt}Test.cs`,`${nameWithoutExt}Tests.cs`];case".kt":return[`${nameWithoutExt}Test.kt`,`${nameWithoutExt}Tests.kt`,`Test${nameWithoutExt}.kt`];case".php":return[`${nameWithoutExt}Test.php`,`${nameWithoutExt}Tests.php`,`Test${nameWithoutExt}.php`];case".ps1":return[`${nameWithoutExt}.Tests.ps1`,`${nameWithoutExt}.tests.ps1`];default:return[]}}function getRepoLevelCandidateDirectories(workingDir,relativePath2,ext){let relativeDir=path256.dirname(relativePath2),nestedRelativeDir=relativeDir==="."?"":relativeDir,directories=TEST_DIRECTORY_NAMES.flatMap((dirName)=>{let rootDir2=path256.join(workingDir,dirName);return nestedRelativeDir?[rootDir2,path256.join(rootDir2,nestedRelativeDir)]:[rootDir2]}),normalizedRelativePath=relativePath2.replace(/\\/g,"/");if(ext===".java"&&normalizedRelativePath.startsWith("src/main/java/"))directories.push(path256.join(workingDir,"src/test/java",path256.dirname(normalizedRelativePath.slice(14))));if((ext===".kt"||ext===".java")&&normalizedRelativePath.startsWith("src/main/kotlin/"))directories.push(path256.join(workingDir,"src/test/kotlin",path256.dirname(normalizedRelativePath.slice(16))));return[...new Set(directories)]}function hasCompoundTestExtension(filename){let lower=filename.toLowerCase();return COMPOUND_TEST_EXTENSIONS.some((ext)=>lower.endsWith(ext))}function isLanguageSpecificTestFile(basename45){let lower=basename45.toLowerCase();if(lower.endsWith("_test.go"))return!0;if(lower.endsWith(".py")&&(lower.startsWith("test_")||lower.endsWith("_test.py")))return!0;if(lower.endsWith("_spec.rb"))return!0;if(lower.endsWith(".java")&&(/^Test[A-Z]/.test(basename45)||basename45.endsWith("Test.java")||basename45.endsWith("Tests.java")||lower.endsWith("it.java")))return!0;if(lower.endsWith(".cs")&&(lower.endsWith("test.cs")||lower.endsWith("tests.cs")))return!0;if(lower.endsWith(".kt")&&(/^Test[A-Z]/.test(basename45)||lower.endsWith("test.kt")||lower.endsWith("tests.kt")))return!0;if(lower.endsWith(".php")&&(/^Test[A-Z]/.test(basename45)||basename45.endsWith("Test.php")||basename45.endsWith("Tests.php")))return!0;if(lower.endsWith(".tests.ps1"))return!0;return!1}function isConventionTestFilePath(filePath){let normalizedPath=filePath.replace(/\\/g,"/"),basename45=path256.basename(filePath);return hasCompoundTestExtension(basename45)||basename45.includes(".spec.")||basename45.includes(".test.")||isLanguageSpecificTestFile(basename45)||isTestDirectoryPath(normalizedPath)}function getTestFilesFromConvention(sourceFiles,workingDir=process.cwd()){let testFiles=[];for(let file3 of sourceFiles){let absoluteFile=resolveWorkspacePath(file3,workingDir),relativeFile=path256.relative(workingDir,absoluteFile),basename45=path256.basename(absoluteFile),dirname102=path256.dirname(absoluteFile),preferRelativeOutput=!path256.isAbsolute(file3);if(isConventionTestFilePath(relativeFile)||isConventionTestFilePath(file3)){dedupePush(testFiles,toWorkspaceOutputPath(absoluteFile,workingDir,preferRelativeOutput));continue}let nameWithoutExt=basename45.replace(/\.[^.]+$/,""),ext=path256.extname(basename45),genericTestNames=[`${nameWithoutExt}.spec${ext}`,`${nameWithoutExt}.test${ext}`],languageSpecificTestNames=buildLanguageSpecificTestNames(nameWithoutExt,ext),colocatedCandidates=[...genericTestNames,...languageSpecificTestNames].map((candidateName)=>path256.join(dirname102,candidateName)),testDirectoryNames=[basename45,...genericTestNames,...languageSpecificTestNames],repoLevelDirectories=getRepoLevelCandidateDirectories(workingDir,relativeFile,ext),possibleTestFiles=[...colocatedCandidates,...TEST_DIRECTORY_NAMES.flatMap((dirName)=>testDirectoryNames.map((candidateName)=>path256.join(dirname102,dirName,candidateName))),...repoLevelDirectories.flatMap((candidateDir3)=>testDirectoryNames.map((candidateName)=>path256.join(candidateDir3,candidateName)))];for(let testFile of possibleTestFiles)if(fs141.existsSync(testFile))dedupePush(testFiles,toWorkspaceOutputPath(testFile,workingDir,preferRelativeOutput))}return testFiles}async function getTestFilesFromGraph(sourceFiles,workingDir,maxFiles=MAX_SAFE_TEST_FILES2+1){let testFiles=[],absoluteSourceFiles=sourceFiles.map((sourceFile)=>resolveWorkspacePath(sourceFile,workingDir)),candidateTestFiles=getTestFilesFromConvention(sourceFiles,workingDir);if(sourceFiles.length===0)return testFiles;for(let testFile of candidateTestFiles)try{let absoluteTestFile=resolveWorkspacePath(testFile,workingDir);if(fs141.statSync(absoluteTestFile).size>MAX_GRAPH_FILE_BYTES)continue;let content=fs141.readFileSync(absoluteTestFile,"utf-8");if(Buffer.byteLength(content,"utf8")>MAX_GRAPH_FILE_BYTES)continue;let testDir=path256.dirname(absoluteTestFile),importRegex=/import\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g,match;match=importRegex.exec(content);while(match!==null){let importPath=match[1],resolvedImport;if(importPath.startsWith(".")){if(resolvedImport=path256.resolve(testDir,importPath),!path256.extname(resolvedImport))for(let extToTry of[".ts",".tsx",".js",".jsx",".mjs",".cjs"]){let withExt=resolvedImport+extToTry;if(absoluteSourceFiles.includes(withExt)||fs141.existsSync(withExt)){resolvedImport=withExt;break}}}else{let nextIndex=match.index+Math.max(match[0].length,1);if(importRegex.lastIndex<=match.index)importRegex.lastIndex=nextIndex;match=importRegex.exec(content);continue}let importBasename=path256.basename(resolvedImport,path256.extname(resolvedImport)),importDir=path256.dirname(resolvedImport);for(let sourceFile of absoluteSourceFiles){let sourceDir=path256.dirname(sourceFile),sourceBasename=path256.basename(sourceFile,path256.extname(sourceFile)),isRelatedDir=importDir===sourceDir||importDir===path256.join(sourceDir,"__tests__")||importDir===path256.join(sourceDir,"tests")||importDir===path256.join(sourceDir,"test")||importDir===path256.join(sourceDir,"spec");if(resolvedImport===sourceFile||importBasename===sourceBasename&&isRelatedDir){if(dedupePush(testFiles,testFile),testFiles.length>=maxFiles)return testFiles;break}}match=importRegex.exec(content)}let requireRegex=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;match=requireRegex.exec(content);while(match!==null){let importPath=match[1];if(importPath.startsWith(".")){let resolvedImport=path256.resolve(testDir,importPath);if(!path256.extname(resolvedImport))for(let extToTry of[".ts",".tsx",".js",".jsx",".mjs",".cjs"]){let withExt=resolvedImport+extToTry;if(absoluteSourceFiles.includes(withExt)||fs141.existsSync(withExt)){resolvedImport=withExt;break}}let importDir=path256.dirname(resolvedImport),importBasename=path256.basename(resolvedImport,path256.extname(resolvedImport));for(let sourceFile of absoluteSourceFiles){let sourceDir=path256.dirname(sourceFile),sourceBasename=path256.basename(sourceFile,path256.extname(sourceFile)),isRelatedDir=importDir===sourceDir||importDir===path256.join(sourceDir,"__tests__")||importDir===path256.join(sourceDir,"tests")||importDir===path256.join(sourceDir,"test")||importDir===path256.join(sourceDir,"spec");if(resolvedImport===sourceFile||importBasename===sourceBasename&&isRelatedDir){if(dedupePush(testFiles,testFile),testFiles.length>=maxFiles)return testFiles;break}}}match=requireRegex.exec(content)}}catch{}return testFiles}function getTargetedExecutionUnsupportedReason(framework){switch(framework){case"go-test":return"go test targets packages, not individual test files";case"cargo":return"cargo test targets crates, targets, or test names rather than file paths";case"maven":return"maven test selection is class-based, not file-path based";case"gradle":return"gradle test selection is class-based, not file-path based";case"dotnet-test":return"dotnet test filters by fully qualified names, not file paths";case"ctest":return"ctest filters named tests from the build tree, not source test files";case"swift-test":return"swift test filters test names, not file paths";default:return null}}function buildTestCommand3(framework,scope,files,coverage,baseDir,bail,targets,nativeTarget){if(nativeTarget)return nativeTarget.framework===framework?buildNativeTargetCommand(nativeTarget):null;switch(framework){case"bun":{let args2=["bun","test"];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"vitest":{let args2=_internals211.resolveLocalNodeTool("vitest",["run","--reporter=json","--outputFile",VITEST_JSON_OUTPUT_RELATIVE_PATH],baseDir,process.platform,_internals211.isCommandAvailable);if(!args2)return null;if(coverage)args2.push("--coverage");if(bail)args2.push("--bail=1");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"jest":{let args2=_internals211.resolveLocalNodeTool("jest",["--json"],baseDir,process.platform,_internals211.isCommandAvailable);if(!args2)return null;if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"mocha":{let args2=_internals211.resolveLocalNodeTool("mocha",[],baseDir,process.platform,_internals211.isCommandAvailable);if(!args2)return null;if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"pytest":{let args2=process.platform==="win32"?["python","-m","pytest"]:["python3","-m","pytest"];if(coverage)args2.push("--cov=.","--cov-report=term-missing");if(bail)args2.push("-x");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"cargo":{let args2=["cargo","test"];if(targets&&targets.length>0)args2.push("--",...targets);else if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"pester":{if(scope!=="all"&&files.length>0){let psCommand=`Invoke-Pester -Path @('${files.map((f)=>f.replace(/'/g,"''").replace(/`/g,"``").replace(/\$/g,"`$")).join("','")}')`;return["pwsh","-EncodedCommand",Buffer.from(psCommand,"utf16le").toString("base64")]}return["pwsh","-Command","Invoke-Pester"]}case"go-test":{let args2=["go","test"];if(targets&&targets.length>0)args2.push("-run",targets.join("|"));return args2.push("./..."),args2}case"maven":return buildMavenTestCommand(baseDir,targets);case"gradle":return buildGradleTestCommand(baseDir,targets);case"dotnet-test":{let args2=["dotnet","test"];if(targets&&targets.length>0)args2.push("--filter",targets.join("|"));return args2}case"ctest":{let args2=["ctest","--test-dir",["build","_build","cmake-build-debug","cmake-build-release","out"].find((d)=>fs141.existsSync(path256.join(baseDir,d,"CMakeCache.txt")))??"build"];if(targets&&targets.length>0)args2.push("-R",targets.join("|"));return args2}case"swift-test":{let args2=["swift","test"];if(targets&&targets.length>0)for(let target of targets)args2.push("--filter",target);return args2}case"dart-test":return _internals211.isCommandAvailable("flutter")?["flutter","test",...files]:["dart","test",...files];case"rspec":{let args2=_internals211.isCommandAvailable("bundle")?["bundle","exec","rspec"]:["rspec"];if(bail)args2.push("--fail-fast");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"minitest":if(scope!=="all"&&files.length>0)return["ruby","-Itest","-e",files.map((f)=>`require_relative '${f.replace(/\\/g,"/").replace(/'/g,"\\'")}'`).join("; ")];return["ruby","-Itest","-e",'Dir.glob("test/**/*_test.rb").sort.each { |f| require_relative f }'];case"pest":return buildPhpVendorCommand(baseDir,"pest",scope!=="all"&&files.length>0?files:[]);case"phpunit":return buildPhpVendorCommand(baseDir,"phpunit",scope!=="all"&&files.length>0?files:[]);case"php-artisan":{let args2=["php","artisan","test"];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}default:return null}}function mapFrameworkStatusToResult(status2){if(typeof status2!=="string")return null;let normalized=status2.toLowerCase();if(normalized==="pass"||normalized==="passed")return"pass";if(normalized==="fail"||normalized==="failed")return"fail";if(normalized==="skip"||normalized==="skipped"||normalized==="pending"||normalized==="todo")return"skip";return null}function firstLine(value){if(typeof value!=="string")return;let line=value.split(`
|
|
4070
|
+
`),records=[];for(let line of lines){let trimmed=line.trim();if(trimmed.length===0)continue;try{let parsed=JSON.parse(trimmed),record3=parseStoredRecord(parsed);if(record3)records.push(record3)}catch{}}return records}catch(err){throw Error(`Failed to read test history: ${err instanceof Error?err.message:String(err)}`)}}function getAllHistory(workingDir){let historyPath=getHistoryPath(workingDir),records=readAllRecords(historyPath);return records.sort((a,b)=>new Date(a.timestamp).getTime()-new Date(b.timestamp).getTime()),records}var MAX_HISTORY_PER_TEST=20,MAX_ERROR_LENGTH=500,MAX_STACK_LENGTH=200,MAX_CHANGED_FILES=50,HISTORY_WRITE_LOCK_TIMEOUT_MS=5000,HISTORY_WRITE_LOCK_STALE_MS=60000,HISTORY_WRITE_LOCK_BACKOFF_MS=10,MAX_TEST_HISTORY_ENTRIES=5000,MAX_TEST_HISTORY_KEYS=1000,DANGEROUS_PROPERTY_NAMES,_internals208;var init_history_store=__esm(()=>{init_manager2();init_caps();DANGEROUS_PROPERTY_NAMES=new Set(["__proto__","constructor","prototype"]);_internals208={validateProjectRoot}});class LanguageBackendRegistry{backends=new Map;register(backend){let existing=this.backends.get(backend.id);if(existing&&existing!==backend)throw Error(`LanguageBackendRegistry: backend id "${backend.id}" registered twice. Each LanguageBackend.id must be unique.`);this.backends.set(backend.id,backend)}get(id){return this.backends.get(id)}getOrDefault(id){let registered=this.backends.get(id);if(registered)return registered;let profile=LANGUAGE_REGISTRY.get(id);if(!profile)return;return defaultBackendFor(profile)}unregister(id){this.backends.delete(id)}}var LANGUAGE_BACKEND_REGISTRY;var init_registry_backend=__esm(()=>{init_default_backend();init_profiles();LANGUAGE_BACKEND_REGISTRY=new LanguageBackendRegistry});import*as fs136 from"node:fs";import*as path251 from"node:path";function detectLaravelProject(directory){let signals=getLaravelSignals(directory);return[signals.hasArtisanFile,signals.hasLaravelFrameworkDep,signals.hasConfigApp].filter(Boolean).length>=2}function getLaravelSignals(directory){let hasArtisanFile=checkArtisanFile(directory),hasLaravelFrameworkDep=checkLaravelFrameworkDep(directory),hasConfigApp=checkConfigApp(directory);return{hasArtisanFile,hasLaravelFrameworkDep,hasConfigApp}}function checkArtisanFile(directory){let artisanPath=path251.join(directory,"artisan");if(!fs136.existsSync(artisanPath))return!1;try{return fs136.statSync(artisanPath).isFile()}catch{return!1}}function checkLaravelFrameworkDep(directory){let composerPath=path251.join(directory,"composer.json");if(!fs136.existsSync(composerPath))return!1;try{let content=fs136.readFileSync(composerPath,"utf-8");return typeof(JSON.parse(content)?.require??{})["laravel/framework"]==="string"}catch{return!1}}function checkConfigApp(directory){return fs136.existsSync(path251.join(directory,"config","app.php"))}function isLarastanConfigured(directory){let neonPath=path251.join(directory,"phpstan.neon");if(!fs136.existsSync(neonPath))return!1;try{let fd=fs136.openSync(neonPath,"r");try{let buf=Buffer.alloc(4096),bytesRead=fs136.readSync(fd,buf,0,4096,0),content=buf.subarray(0,bytesRead).toString("utf-8");return content.includes("nunomaduro/larastan")||content.includes("larastan/larastan")}finally{fs136.closeSync(fd)}}catch{return!1}}function getLaravelCommandOverlay(directory){if(!detectLaravelProject(directory))return null;let lintCommand=null;if(fs136.existsSync(path251.join(directory,"pint.json")))lintCommand="vendor/bin/pint --test";else if(fs136.existsSync(path251.join(directory,".php-cs-fixer.php")))lintCommand="vendor/bin/php-cs-fixer fix --dry-run --diff";let staticAnalysisCommand=null,staticAnalysisTool=null,hasPhpstanNeon=fs136.existsSync(path251.join(directory,"phpstan.neon")),hasPhpstanNeonDist=fs136.existsSync(path251.join(directory,"phpstan.neon.dist"));if(hasPhpstanNeon||hasPhpstanNeonDist)staticAnalysisCommand="vendor/bin/phpstan analyse",staticAnalysisTool=isLarastanConfigured(directory)?"larastan":"phpstan";return{testCommand:"php artisan test",lintCommand,staticAnalysisCommand,staticAnalysisTool,auditCommand:"composer audit --locked --format=json",supportsParallel:!0}}var init_framework_detector=()=>{};import*as fs137 from"node:fs";import*as path252 from"node:path";async function selectFramework4(dir){if(detectLaravelProject(dir))return{name:"laravel",detectedVia:"Laravel signals (artisan / composer.json / config/app.php)"};return null}async function selectTestFramework2(dir){if(detectLaravelProject(dir))return{name:"php-artisan",cmd:["php","artisan","test"],cwd:dir,detectedVia:"Laravel signals (artisan / composer.json / config/app.php)"};if(fs137.existsSync(path252.join(dir,"Pest.php")))return{name:"pest",cmd:buildPhpVendorCommand(dir,"pest"),cwd:dir,detectedVia:"Pest.php"};if(fs137.existsSync(path252.join(dir,"phpunit.xml")))return{name:"phpunit",cmd:buildPhpVendorCommand(dir,"phpunit"),cwd:dir,detectedVia:"phpunit.xml"};if(fs137.existsSync(path252.join(dir,"phpunit.xml.dist")))return{name:"phpunit",cmd:buildPhpVendorCommand(dir,"phpunit"),cwd:dir,detectedVia:"phpunit.xml.dist"};return null}function buildPhpBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID4);if(!profile)throw Error("buildPhpBackend: php profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...defaultBackendFor(profile),selectFramework:selectFramework4,selectTestFramework:selectTestFramework2}}var PROFILE_ID4="php";var init_php2=__esm(()=>{init_default_backend();init_framework_detector();init_profiles()});import*as fs138 from"node:fs";import*as path253 from"node:path";function readPackageJsonRaw(dir){try{let content=fs138.readFileSync(path253.join(dir,"package.json"),"utf-8");return JSON.parse(content)}catch{return null}}function readPackageJson(dir){return _internals209.readPackageJsonRaw(dir)}function readPackageJsonTestScript(dir){return readPackageJson(dir)?.scripts?.test??null}function frameworkFromScriptsTest(script){if(script.includes("vitest"))return"vitest";if(script.includes("jest"))return"jest";if(script.includes("mocha"))return"mocha";if(script.includes("bun test"))return"bun:test";return null}function frameworkFromDevDeps(devDeps){if(!devDeps)return null;if(devDeps.vitest||devDeps["@vitest/ui"])return"vitest";if(devDeps.jest||devDeps["@types/jest"])return"jest";if(devDeps.mocha||devDeps["@types/mocha"])return"mocha";return null}function selectionFromFramework(profile,fwName,dir,detectedVia){let fw=profile.test.frameworks.find((f)=>f.name===fwName);if(!fw)return null;let argv=tokenizeCommand(fw.cmd);if(argv.length===0)return null;return{name:fw.name,cmd:argv,cwd:dir,detectedVia,filesIgnored:!1}}async function selectTestFramework3(dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)return null;let pkg=readPackageJson(dir),script=pkg?.scripts?.test;if(script){let fwName=frameworkFromScriptsTest(script);if(fwName){let sel=selectionFromFramework(profile,fwName,dir,"package.json#scripts.test");if(sel)return sel}}let devDepsFw=frameworkFromDevDeps(pkg?.devDependencies);if(devDepsFw){let sel=selectionFromFramework(profile,devDepsFw,dir,"package.json#devDependencies");if(sel)return sel}return defaultSelectTestFramework(profile,dir)}function buildTestCommand2(framework,files,dir,opts){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)return null;return defaultBuildTestCommand(profile,framework,files,dir,opts)}function parseTestOutput(framework,stdout,stderr,exitCode){return defaultParseTestOutput(framework,stdout,stderr,exitCode)}async function selectFramework5(dir){let pkg=readPackageJson(dir);if(!pkg)return null;let deps={...pkg.dependencies,...pkg.devDependencies},order=[["next","next"],["nuxt","nuxt"],["@angular/core","angular"],["svelte","svelte"],["react","react"],["vue","vue"],["express","express"],["fastify","fastify"],["@nestjs/core","nestjs"]];for(let[pkgName,displayName]of order)if(deps[pkgName])return{name:displayName,detectedVia:`package.json#dependencies.${pkgName}`};return null}async function selectEntryPoints4(dir){let pkg=readPackageJson(dir);if(!pkg)return[];let points=[],obj=pkg;if(obj.bin)if(typeof obj.bin==="string")points.push(obj.bin);else for(let v of Object.values(obj.bin))points.push(v);if(obj.main)points.push(obj.main);if(obj.module&&obj.module!==obj.main)points.push(obj.module);if(obj.exports&&typeof obj.exports==="object"){let root=obj.exports["."];if(typeof root==="string"&&!points.includes(root))points.push(root)}return[...new Set(points.filter((p)=>p.length>0))]}function extractImports5(_sourceFile,source){let out=new Set;for(let re of[IMPORT_REGEX_ES,IMPORT_REGEX_BARE,IMPORT_REGEX_REQUIRE2,IMPORT_REGEX_DYNAMIC,IMPORT_REGEX_REEXPORT2]){re.lastIndex=0;let m=re.exec(source);while(m!==null)out.add(m[1]),m=re.exec(source)}return[...out]}async function selectBuildCommand(dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)return null;return defaultSelectBuildCommand(profile,dir)}async function testFilesFor(sourceFile,dir){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)return[];return defaultTestFilesFor(profile,sourceFile,dir)}function buildTypescriptBackend(){let profile=LANGUAGE_REGISTRY.get(PROFILE_ID5);if(!profile)throw Error("buildTypescriptBackend: typescript profile not in LANGUAGE_REGISTRY. profiles.ts must be imported before this backend.");return{...profile,selectTestFramework:selectTestFramework3,buildTestCommand:buildTestCommand2,parseTestOutput,extractImports:extractImports5,selectBuildCommand,testFilesFor,selectFramework:selectFramework5,selectEntryPoints:selectEntryPoints4}}var PROFILE_ID5="typescript",IMPORT_REGEX_ES,IMPORT_REGEX_BARE,IMPORT_REGEX_REQUIRE2,IMPORT_REGEX_DYNAMIC,IMPORT_REGEX_REEXPORT2,_internals209;var init_typescript=__esm(()=>{init_default_backend();init_profiles();IMPORT_REGEX_ES=/import\s+[\s\S]*?\s+from\s+['"]([^'"]+)['"]/g,IMPORT_REGEX_BARE=/import\s+['"]([^'"]+)['"]/g,IMPORT_REGEX_REQUIRE2=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,IMPORT_REGEX_DYNAMIC=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,IMPORT_REGEX_REEXPORT2=/export\s+(?:\{[^}]*\}|\*)\s+from\s+['"]([^'"]+)['"]/g;_internals209={readPackageJsonRaw,readPackageJsonTestScript,frameworkFromScriptsTest}});function registerAllBackends(){if(registered)return;LANGUAGE_BACKEND_REGISTRY.register(buildTypescriptBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildPythonBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildGoBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildJavaBackend()),LANGUAGE_BACKEND_REGISTRY.register(buildPhpBackend()),registered=!0}var registered=!1;var init_backends=__esm(()=>{init_registry_backend();init_go2();init_java2();init_php2();init_python2();init_typescript();registerAllBackends()});import*as fs139 from"node:fs";import*as path254 from"node:path";function hasManifestInDirectory(directory){try{return fs139.readdirSync(directory).some((entry)=>MANIFEST_SET.has(entry))}catch{return!1}}function findGitMarkerAncestor(start){let current=path254.resolve(start);for(let depth=0;depth<32;depth++){let marker=path254.join(current,".git");try{if(!fs139.lstatSync(marker).isSymbolicLink())return current}catch(error93){let code=error93.code;if(code!=="ENOENT"&&code!=="ENOTDIR")return}let parent=path254.dirname(current);if(parent===current)return null;current=parent}return}function hasManifestAncestor(start){let resolved=path254.resolve(start),gitRoot=findGitMarkerAncestor(resolved);if(gitRoot===void 0)return!0;if(gitRoot===null)return hasManifestInDirectory(resolved);let current=resolved;for(let depth=0;depth<32;depth++){if(hasManifestInDirectory(current))return!0;if(current===gitRoot)return!1;let parent=path254.dirname(current);if(parent===current)return!1;current=parent}return!0}function hasGitMarkerAncestor(start){return findGitMarkerAncestor(start)!==null}function hasSwarmState(start){try{return fs139.lstatSync(path254.join(path254.resolve(start),".swarm")),!0}catch(error93){let code=error93.code;return code!=="ENOENT"&&code!=="ENOTDIR"}}var MANIFEST_FILES,MANIFEST_SET;var init_manifest_files=__esm(()=>{MANIFEST_FILES=["package.json","tsconfig.json","pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","Cargo.toml","go.mod","pom.xml","build.gradle","build.gradle.kts","build.zig","CMakeLists.txt","Makefile","meson.build","Package.swift","pubspec.yaml","Gemfile","composer.json"],MANIFEST_SET=new Set(MANIFEST_FILES)});var exports_dispatch={};__export(exports_dispatch,{pickedProfiles:()=>pickedProfiles,pickBackend:()=>pickBackend,clearDispatchCache:()=>clearDispatchCache,_internals:()=>_internals210});import*as fs140 from"node:fs";import*as path255 from"node:path";async function tryReadDirectoryAsync(dir){try{return new Set(await fs140.promises.readdir(dir))}catch{return null}}async function manifestHash(dir,signal){let entries2=await tryReadDirectoryAsync(dir);if(throwIfAborted3(signal),entries2===null||entries2.size===0)return"";let names=MANIFEST_FILES.filter((name)=>entries2.has(name)),parts=await Promise.all(names.map(async(name)=>{try{let stat23=await fs140.promises.stat(path255.join(dir,name));return`${name}:${stat23.size}:${stat23.mtimeMs}:${stat23.ino}`}catch{return null}}));return throwIfAborted3(signal),parts.filter((part)=>part!==null).join("|")}function cacheProfileKey(input,cacheKey){let key2=canonicalRootKeyLexical(input);profileCacheKeyByInput.delete(key2),profileCacheKeyByInput.set(key2,cacheKey);while(profileCacheKeyByInput.size>_internals210.cacheCapacity){let oldest=profileCacheKeyByInput.keys().next().value;if(oldest===void 0)break;profileCacheKeyByInput.delete(oldest)}}async function directoryFingerprint(dir){try{let stat23=await fs140.promises.stat(dir);if(!stat23.isDirectory())return null;return{directory:dir,dev:stat23.dev,ino:stat23.ino,size:stat23.size,mtimeMs:stat23.mtimeMs,ctimeMs:stat23.ctimeMs}}catch{return null}}function fingerprintsMatch(expected,actual){return expected.dev===actual.dev&&expected.ino===actual.ino&&expected.size===actual.size&&expected.mtimeMs===actual.mtimeMs&&expected.ctimeMs===actual.ctimeMs}async function readDirectoryForManifestWalk(dir){let entries2=await tryReadDirectoryAsync(dir),fingerprint2=await directoryFingerprint(dir),after=await tryReadDirectoryAsync(dir);if(entries2===null||fingerprint2===null||after===null)return{entries:null,complete:!1,stopAtCurrent:!0};if(entries2.size!==after.size||[...entries2].some((entry)=>!after.has(entry)))return{entries:null,complete:!1,stopAtCurrent:!1};return{entries:entries2,fingerprint:fingerprint2,complete:!0}}async function isManifestRootCacheEntryValid(entry){for(let fingerprint2 of entry.trace){let current=await directoryFingerprint(fingerprint2.directory);if(current===null||!fingerprintsMatch(fingerprint2,current))return!1}return!0}async function isSelectedRootObservationStillValid(resolution,hash5,signal){let currentHash=await manifestHash(resolution.root,signal);if(throwIfAborted3(signal),currentHash!==hash5||resolution.rootHadManifest&¤tHash==="")return!1;return!0}function evictManifestRootCacheIfNeeded(){if(manifestRootCache.size<=_internals210.cacheCapacity)return;let oldestKey,oldestOrder=1/0;for(let[key2,value]of manifestRootCache)if(value.insertOrder<oldestOrder)oldestKey=key2,oldestOrder=value.insertOrder;if(oldestKey!==void 0)manifestRootCache.delete(oldestKey)}function cacheManifestRoot(key2,root,rootHadManifest,trace,cacheable,signal){if(!cacheable||signal?.aborted)return;manifestRootCache.set(key2,{root,rootHadManifest,trace,insertOrder:manifestRootInsertCounter++}),evictManifestRootCacheIfNeeded()}function throwIfAborted3(signal){if(signal?.aborted)throw signal.reason??Error("manifest-root lookup aborted")}async function findManifestRoot(start,signal){throwIfAborted3(signal);let resolved=path255.resolve(start),key2=await canonicalRootKeyFreshAsync(resolved);throwIfAborted3(signal);let cached3=manifestRootCache.get(key2);if(cached3!==void 0){if(await isManifestRootCacheEntryValid(cached3))return throwIfAborted3(signal),{root:cached3.root,rootHadManifest:cached3.rootHadManifest,key:key2,trace:[],cacheable:!1};manifestRootCache.delete(key2)}let cur=resolved,trace=[],cacheable=!0;for(let i=0;i<MAX_MANIFEST_SEARCH_DEPTH;i++){let snapshot=await readDirectoryForManifestWalk(cur);if(throwIfAborted3(signal),!snapshot.complete){if(snapshot.stopAtCurrent)return{root:cur,rootHadManifest:!1,key:key2,trace,cacheable:!1};cacheable=!1}else trace.push(snapshot.fingerprint);let{entries:entries2}=snapshot;if(entries2!==null){if(entries2.size>0){for(let name of MANIFEST_FILES)if(entries2.has(name))return{root:cur,rootHadManifest:!0,key:key2,trace,cacheable};if(entries2.has(".git"))return{root:cur,rootHadManifest:!1,key:key2,trace,cacheable}}}let parent=path255.dirname(cur);if(parent===cur)break;cur=parent}return{root:start,rootHadManifest:!1,key:key2,trace,cacheable}}function evictIfNeeded(){if(cache5.size<=_internals210.cacheCapacity)return;let oldestKey,oldestOrder=1/0;for(let[k,v]of cache5.entries())if(v.insertOrder<oldestOrder)oldestOrder=v.insertOrder,oldestKey=k;if(oldestKey!==void 0)cache5.delete(oldestKey)}async function pickBackend(dir,signal){for(let attempt=0;attempt<2;attempt++){let resolution=await findManifestRoot(dir,signal),{root}=resolution;throwIfAborted3(signal);let hash5=await manifestHash(root,signal);if(throwIfAborted3(signal),resolution.rootHadManifest&&hash5===""){if(manifestRootCache.delete(resolution.key),attempt===0)continue;return profileCacheKeyByInput.delete(canonicalRootKeyLexical(dir)),null}let cacheKey=await canonicalRootKeyFreshAsync(root);throwIfAborted3(signal);let cached3=cache5.get(cacheKey);if(cached3&&cached3.hash===hash5)return cacheManifestRoot(resolution.key,root,resolution.rootHadManifest,resolution.trace,resolution.cacheable,signal),cacheProfileKey(dir,cacheKey),cached3.backend;if(hash5==="")return cacheManifestRoot(resolution.key,root,resolution.rootHadManifest,resolution.trace,resolution.cacheable,signal),cache5.set(cacheKey,{hash:hash5,backend:null,profiles:[],insertOrder:insertCounter++}),evictIfNeeded(),cacheProfileKey(dir,cacheKey),null;let profiles=await _internals210.detectProjectLanguages(root);if(throwIfAborted3(signal),!await isSelectedRootObservationStillValid(resolution,hash5,signal)){if(manifestRootCache.delete(resolution.key),attempt===0)continue;return profileCacheKeyByInput.delete(canonicalRootKeyLexical(dir)),null}if(cacheManifestRoot(resolution.key,root,resolution.rootHadManifest,resolution.trace,resolution.cacheable,signal),profiles.length===0)return cache5.set(cacheKey,{hash:hash5,backend:null,profiles:[],insertOrder:insertCounter++}),evictIfNeeded(),cacheProfileKey(dir,cacheKey),null;let winner=profiles[0],backend=LANGUAGE_BACKEND_REGISTRY.getOrDefault(winner.id)??null;return cache5.set(cacheKey,{hash:hash5,backend,profiles:profiles.map((p)=>({id:p.id})),insertOrder:insertCounter++}),evictIfNeeded(),cacheProfileKey(dir,cacheKey),backend}return null}function pickedProfiles(dir){let cacheKey=profileCacheKeyByInput.get(canonicalRootKeyLexical(dir));if(cacheKey===void 0)return[];return cache5.get(cacheKey)?.profiles??[]}function clearDispatchCache(){cache5.clear(),manifestRootCache.clear(),profileCacheKeyByInput.clear(),insertCounter=0,manifestRootInsertCounter=0}var _internals210,cache5,insertCounter=0,MAX_MANIFEST_SEARCH_DEPTH=32,manifestRootCache,manifestRootInsertCounter=0,profileCacheKeyByInput;var init_dispatch=__esm(()=>{init_backends();init_canonical_root();init_detector();init_manifest_files();init_registry_backend();_internals210={detectProjectLanguages,cacheCapacity:64,get manifestRootCacheSize(){return manifestRootCache.size}},cache5=new Map;manifestRootCache=new Map,profileCacheKeyByInput=new Map});import*as fs141 from"node:fs";import*as path256 from"node:path";async function estimateFanOut(sourceFiles,cwd){try{let impactMap=await _internals211.loadImpactMap(cwd,{skipRebuild:!0}),uniqueTestFiles=new Set;for(let sourceFile of sourceFiles){let normalizedPath=path256.resolve(cwd,sourceFile).replace(/\\/g,"/"),testFiles=impactMap[normalizedPath];if(testFiles)for(let testFile of testFiles){let normalized=testFile.replace(/\\/g,"/");uniqueTestFiles.add(process.platform==="win32"?normalized.toLowerCase():normalized)}}return{estimatedCount:uniqueTestFiles.size,status:"advisory"}}catch{return{estimatedCount:0,status:"unavailable"}}}function normalizeSelectionFiles(files,workingDir){let seen=new Set,normalized=[];for(let file3 of files){let absolute=path256.resolve(workingDir,file3),relative61=path256.relative(workingDir,absolute),output=(path256.isAbsolute(relative61)?absolute:relative61).replace(/\\/g,"/"),key2=process.platform==="win32"?output.toLowerCase():output;if(!seen.has(key2))seen.add(key2),normalized.push(output)}return normalized}function makeResolution(requestedScope,effectiveScope,sourceFiles,resolvedFiles,decision,workingDir,options){let estimateCount=options?.estimate?.estimatedCount??0,estimateStatus=options?.estimate?.status??"not_run",fallbackReason=options?.fallbackReason??(options?.cacheStatus?.startsWith("rebuilt_")?`impact cache rebuild completed (${options.cacheStatus}) before resolution`:null);return{requestedScope,effectiveScope,sourceFiles:normalizeSelectionFiles(sourceFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1),resolvedFiles:normalizeSelectionFiles(resolvedFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1),cap:MAX_SAFE_TEST_FILES2,decision,estimate:{count:estimateCount,status:estimateStatus},estimateCount,estimateStatus,...options?.cacheStatus&&{cacheStatus:options.cacheStatus},fallbackReason,evaluable:decision==="execute"}}function resolutionFields(resolution){return{resolved_test_files:resolution.resolvedFiles,cap_decision:{decision:resolution.decision==="scope_exceeded"?"cap_exceeded":"within_cap",resolved_test_count:resolution.resolvedFiles.length,limit:resolution.cap},...resolution.fallbackReason?{fallback_reason:resolution.fallbackReason}:{}}}function cacheStatusAfterRebuild(before,after){let normalize25=(status2)=>status2.endsWith("_unverified")?status2.slice(0,-11):status2,beforeState=normalize25(before),afterState=normalize25(after);if(afterState==="fresh"){if(beforeState==="missing"||beforeState==="corrupt"||beforeState==="legacy"||beforeState==="stale")return`rebuilt_${beforeState}`}return afterState===beforeState?afterState:after}async function loadImpactMapForImpactScope(workingDir){if(_internals211.loadImpactMap!==DEFAULT_LOAD_IMPACT_MAP){let before=getImpactCacheStatus(workingDir,{verify:!1}).status,map3=await _internals211.loadImpactMap(workingDir),after=getImpactCacheStatus(workingDir,{verify:!1}).status;return{map:map3,status:cacheStatusAfterRebuild(before,after)}}return _internals211.loadImpactMapWithStatus(workingDir)}function cacheStatusForAdvisory(status2){if(status2==="missing")return"missing_unverified";if(status2==="corrupt")return"corrupt_unverified";if(status2==="legacy")return"legacy_unverified";return status2}function isAbsolutePath(str){if(str.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test(str))return!0;if(/^\\\\/.test(str))return!0;if(/^\\\\\.\\/.test(str))return!0;return!1}function containsPowerShellMetacharacters(str){return POWERSHELL_METACHARACTERS.test(str)}function containsShellMetacharacters(str){return SHELL_METACHARACTERS2.test(str)}function validateArgs2(args2){if(typeof args2!=="object"||args2===null)return!1;let obj=args2;if(obj.scope!==void 0){if(obj.scope!=="all"&&obj.scope!=="convention"&&obj.scope!=="graph"&&obj.scope!=="impact"&&obj.scope!=="target")return!1}if(obj.native_target!==void 0){if(typeof obj.native_target!=="object"||obj.native_target===null)return!1;let target=obj.native_target;if(target.framework!=="go-test"&&target.framework!=="ctest")return!1;if(typeof target.name!=="string"||typeof target.path!=="string")return!1;if(target.name.length===0||target.name.length>256)return!1;if(target.path.length===0||target.path.length>1024)return!1;if(containsControlChars(target.name)||containsControlChars(target.path))return!1;if(target.framework==="go-test"&&target.name.split("/").some((p)=>!p))return!1;if(isAbsolutePath(target.path)||containsPathTraversal(target.path))return!1}if(obj.scope==="target"){if(obj.native_target===void 0)return!1;if(Array.isArray(obj.files)&&obj.files.length>0)return!1;if(obj.coverage===!0||obj.bail===!0)return!1}else if(obj.native_target!==void 0)return!1;if(obj.files!==void 0){if(!Array.isArray(obj.files))return!1;if(obj.files.length>MAX_RAW_FILE_ENTRIES)return!1;for(let f of obj.files){if(typeof f!=="string")return!1;if(f.length===0||f.length>MAX_FILE_PATH_LENGTH2)return!1;if(isAbsolutePath(f))return!1;if(containsPathTraversal(f))return!1;if(containsControlChars(f))return!1;if(containsPowerShellMetacharacters(f))return!1}}if(obj.targets!==void 0){if(!Array.isArray(obj.targets))return!1;for(let t of obj.targets){if(typeof t!=="string")return!1;if(t.length===0)return!1;if(isAbsolutePath(t))return!1;if(containsPathTraversal(t))return!1;if(containsControlChars(t))return!1;if(containsShellMetacharacters(t))return!1}}if(obj.coverage!==void 0){if(typeof obj.coverage!=="boolean")return!1}if(obj.bail!==void 0){if(typeof obj.bail!=="boolean")return!1}if(obj.timeout_ms!==void 0){if(typeof obj.timeout_ms!=="number")return!1;if(obj.timeout_ms<0||obj.timeout_ms>MAX_TIMEOUT_MS3)return!1}return!0}function validateNativeTargetInput(target){if(target.framework!=="go-test"&&target.framework!=="ctest")return'Native target framework must be "go-test" or "ctest"';if(typeof target.name!=="string"||target.name.length===0||target.name.length>256)return"Native target name must be a non-empty string up to 256 characters";if(typeof target.path!=="string"||target.path.length===0||target.path.length>1024)return"Native target path must be a non-empty string up to 1024 characters";if(containsControlChars(target.name)||containsControlChars(target.path))return"Native target values must not contain control characters";if(target.framework==="go-test"&&target.name.split("/").some((p)=>!p))return"Go native target name must not contain empty slash-separated segments";if(isAbsolutePath(target.path))return"Native target path must be workspace-relative, not absolute";if(containsPathTraversal(target.path))return"Native target path escapes project root";return}function resolveNativeTarget(target,workingDir){let rootReal,targetReal;try{if(rootReal=fs141.realpathSync(workingDir),targetReal=fs141.realpathSync(path256.resolve(rootReal,target.path)),!fs141.statSync(targetReal).isDirectory())return{success:!1,error:"Native target path must be a directory"}}catch{return{success:!1,error:"Native target path does not exist"}}let relative61=path256.relative(rootReal,targetReal);if(relative61.startsWith("..")||path256.isAbsolute(relative61))return{success:!1,error:"Native target path escapes project root"};if(!_internals211.isCommandAvailable(target.framework==="go-test"?"go":"ctest"))return{success:!1,error:`Native target framework "${target.framework}" is unavailable`};let executionDirectory=rootReal,commandRelative=relative61;if(target.framework==="go-test"){let hasRootWorkspace=fs141.existsSync(path256.join(rootReal,"go.work")),moduleRoot;for(let current=targetReal;;current=path256.dirname(current)){if(fs141.existsSync(path256.join(current,"go.mod"))){moduleRoot=current;break}if(current===rootReal)break;let parent=path256.dirname(current);if(parent===current||path256.relative(rootReal,parent).startsWith(".."))break}if(!hasRootWorkspace&&!moduleRoot)return{success:!1,error:"Go native target requires an enclosing go.mod or go.work at the project root"};if(!hasRootWorkspace&&moduleRoot)executionDirectory=moduleRoot,commandRelative=path256.relative(moduleRoot,targetReal)}else if(!fs141.existsSync(path256.join(targetReal,"CMakeCache.txt")))return{success:!1,error:"CTest native target requires CMakeCache.txt in the target directory"};return{success:!0,target:{...target,path:commandRelative.length===0?".":commandRelative.replace(/\\/g,"/")},executionDirectory,historyPath:relative61.length===0?".":relative61.replace(/\\/g,"/")}}function hasPackageJsonDependency(deps,...patterns){for(let pattern of patterns)if(deps[pattern])return!0;return!1}function hasDevDependency(devDeps,...patterns){if(!devDeps)return!1;return hasPackageJsonDependency(devDeps,...patterns)}function detectGoTest(cwd){return _internals211.existsSync(path256.join(cwd,"go.mod"))&&_internals211.isCommandAvailable("go")}function detectJavaMaven(cwd){return _internals211.existsSync(path256.join(cwd,"pom.xml"))&&_internals211.isCommandAvailable("mvn")}function detectGradle(cwd){let hasBuildFile=_internals211.existsSync(path256.join(cwd,"build.gradle"))||_internals211.existsSync(path256.join(cwd,"build.gradle.kts")),hasGradlew=_internals211.existsSync(path256.join(cwd,"gradlew"))||_internals211.existsSync(path256.join(cwd,"gradlew.bat"));return hasBuildFile&&(hasGradlew||_internals211.isCommandAvailable("gradle"))}function detectDotnetTest(cwd){try{return _internals211.readdirSync(cwd).some((f)=>f.endsWith(".csproj"))&&_internals211.isCommandAvailable("dotnet")}catch{return!1}}function detectCTest(cwd){let hasSource=_internals211.existsSync(path256.join(cwd,"CMakeLists.txt")),hasBuildCache=_internals211.existsSync(path256.join(cwd,"CMakeCache.txt"))||_internals211.existsSync(path256.join(cwd,"build","CMakeCache.txt"));return(hasSource||hasBuildCache)&&_internals211.isCommandAvailable("ctest")}function detectSwiftTest(cwd){return _internals211.existsSync(path256.join(cwd,"Package.swift"))&&_internals211.isCommandAvailable("swift")}function detectDartTest(cwd){return _internals211.existsSync(path256.join(cwd,"pubspec.yaml"))&&(_internals211.isCommandAvailable("dart")||_internals211.isCommandAvailable("flutter"))}function detectRSpec(cwd){let hasRSpecFile=_internals211.existsSync(path256.join(cwd,".rspec")),hasGemfile=_internals211.existsSync(path256.join(cwd,"Gemfile")),hasSpecDir=_internals211.existsSync(path256.join(cwd,"spec"));return(hasRSpecFile||hasGemfile&&hasSpecDir)&&(_internals211.isCommandAvailable("bundle")||_internals211.isCommandAvailable("rspec"))}function detectMinitest(cwd){return _internals211.existsSync(path256.join(cwd,"test"))&&(_internals211.existsSync(path256.join(cwd,"Gemfile"))||_internals211.existsSync(path256.join(cwd,"Rakefile")))&&_internals211.isCommandAvailable("ruby")}async function detectTestFrameworkViaDispatch(cwd){try{let{pickBackend:pickBackend2}=await Promise.resolve().then(() => (init_dispatch(),exports_dispatch)),backend=await pickBackend2(cwd);if(!backend?.selectTestFramework)return"none";let sel=await backend.selectTestFramework(cwd);if(!sel)return"none";return DISPATCH_FRAMEWORK_MAP[sel.name]??"none"}catch{return"none"}}async function buildTestCommandViaDispatch(framework,scope,files,coverage,baseDir,bail,targets,nativeTarget){if(framework==="none")return null;try{let{pickBackend:pickBackend2}=await Promise.resolve().then(() => (init_dispatch(),exports_dispatch)),backend=await pickBackend2(baseDir);if(backend?.buildTestCommand){let cmd=backend.buildTestCommand(framework,files,baseDir,{scope,coverage,bail,targets,nativeTarget});if(cmd)return cmd}return null}catch{return null}}async function parseTestOutputViaDispatch(framework,output,baseDir){if(framework==="none")return null;try{let{pickBackend:pickBackend2}=await Promise.resolve().then(() => (init_dispatch(),exports_dispatch)),backend=await pickBackend2(baseDir);if(!backend?.parseTestOutput)return null;let summary=backend.parseTestOutput(framework,output,"",0),passed=summary.passed??0,failed=summary.failed??0,skipped=summary.skipped??0,total=summary.total??passed+failed+skipped,result={totals:{passed,failed,skipped,total}};if(summary.coveragePercent!==void 0)result.coveragePercent=summary.coveragePercent;return result}catch{return null}}function relativeEscapesRoot(relative61){return relative61===".."||relative61.startsWith(`..${path256.sep}`)||path256.isAbsolute(relative61)}function resolveModuleDirByMarkers(root,files,markerNames){let hasMarker=(dir)=>markerNames.some((marker)=>_internals211.existsSync(path256.join(dir,marker))),resolvedRoot=path256.resolve(root),rootReal,isContainedModuleDir=(dir)=>{if(rootReal===void 0)try{rootReal=_internals211.realpathSync(resolvedRoot)}catch{rootReal=null}if(rootReal===null)return!1;let dirReal;try{dirReal=_internals211.realpathSync(dir)}catch{return!1}return!relativeEscapesRoot(path256.relative(rootReal,dirReal))};if(files&&files.length>0){for(let file3 of files){let resolvedFile=path256.resolve(resolvedRoot,file3),relativeToRoot=path256.relative(resolvedRoot,resolvedFile);if(relativeEscapesRoot(relativeToRoot))continue;let current=path256.dirname(resolvedFile);while(!0){if(hasMarker(current)&&isContainedModuleDir(current))return current;if(current===resolvedRoot)break;let parent=path256.dirname(current);if(parent===current)break;if(relativeEscapesRoot(path256.relative(resolvedRoot,parent)))break;current=parent}}return null}let entries2;try{entries2=_internals211.readdirSync(resolvedRoot)}catch{return null}entries2.sort((a,b)=>a.localeCompare(b));let inspected=0;for(let entry of entries2){if(entry.startsWith(".")||entry==="node_modules")continue;if(inspected>=MAX_MAVEN_MODULE_PROBE_ENTRIES)break;inspected++;let candidate2=path256.join(resolvedRoot,entry);if(hasMarker(candidate2)&&isContainedModuleDir(candidate2))return candidate2}return null}function resolveNestedModuleDir(root,files,markerNames){if(markerNames.some((marker)=>_internals211.existsSync(path256.join(root,marker))))return null;return resolveModuleDirByMarkers(root,files,markerNames)}function resolveNestedMavenModuleDir(root,files){return resolveNestedModuleDir(root,files,MAVEN_BUILD_FILES)}function resolveNestedGradleModuleDir(root,files){return resolveNestedModuleDir(root,files,GRADLE_BUILD_FILES)}async function detectTestFramework(cwd,files){let baseDir=cwd;try{let packageJsonPath=path256.join(baseDir,"package.json");if(_internals211.existsSync(packageJsonPath)){let content=_internals211.readFileSync(packageJsonPath,"utf-8"),pkg=JSON.parse(content),_deps=pkg.dependencies||{},devDeps=pkg.devDependencies||{},scripts=pkg.scripts||{};if(scripts.test?.includes("vitest"))return"vitest";if(scripts.test?.includes("jest"))return"jest";if(scripts.test?.includes("mocha"))return"mocha";if(scripts.test?.includes("bun test"))return"bun";if(hasDevDependency(devDeps,"vitest","@vitest/ui"))return"vitest";if(hasDevDependency(devDeps,"jest","@types/jest"))return"jest";if(hasDevDependency(devDeps,"mocha","@types/mocha"))return"mocha";if(_internals211.existsSync(path256.join(baseDir,"bun.lockb"))||_internals211.existsSync(path256.join(baseDir,"bun.lock"))){if(scripts.test?.includes("bun"))return"bun"}}}catch{}try{let pyprojectTomlPath=path256.join(baseDir,"pyproject.toml"),setupCfgPath=path256.join(baseDir,"setup.cfg"),requirementsTxtPath=path256.join(baseDir,"requirements.txt");if(_internals211.existsSync(pyprojectTomlPath)){let content=_internals211.readFileSync(pyprojectTomlPath,"utf-8");if(content.includes("[tool.pytest"))return"pytest";if(content.includes("pytest"))return"pytest"}if(_internals211.existsSync(setupCfgPath)){if(_internals211.readFileSync(setupCfgPath,"utf-8").includes("[pytest]"))return"pytest"}if(_internals211.existsSync(requirementsTxtPath)){if(_internals211.readFileSync(requirementsTxtPath,"utf-8").includes("pytest"))return"pytest"}}catch{}try{let cargoTomlPath=path256.join(baseDir,"Cargo.toml");if(_internals211.existsSync(cargoTomlPath)){let content=_internals211.readFileSync(cargoTomlPath,"utf-8");if(content.includes("[dev-dependencies]")){if(content.includes("tokio")||content.includes("mockall")||content.includes("pretty_assertions"))return"cargo"}}}catch{}try{let pesterConfigPath=path256.join(baseDir,"pester.config.ps1"),pesterConfigJsonPath=path256.join(baseDir,"pester.config.ps1.json"),pesterPs1Path=path256.join(baseDir,"tests.ps1");if(_internals211.existsSync(pesterConfigPath)||_internals211.existsSync(pesterConfigJsonPath)||_internals211.existsSync(pesterPs1Path))return"pester"}catch{}let phpFramework=detectPhpTest(baseDir);if(phpFramework)return phpFramework;if(detectGoTest(baseDir))return"go-test";if(detectJavaMaven(baseDir))return"maven";if(detectGradle(baseDir))return"gradle";if(detectDotnetTest(baseDir))return"dotnet-test";if(detectCTest(baseDir))return"ctest";if(detectSwiftTest(baseDir))return"swift-test";if(detectDartTest(baseDir))return"dart-test";if(detectRSpec(baseDir))return"rspec";if(detectMinitest(baseDir))return"minitest";let mavenModuleDir=resolveNestedMavenModuleDir(baseDir,files);if(mavenModuleDir&&(_internals211.isCommandAvailable("mvn")||resolveMavenWrapperCommand(mavenModuleDir,["test"])!==null))return"maven";let gradleModuleDir=resolveNestedGradleModuleDir(baseDir,files);if(gradleModuleDir&&(_internals211.isCommandAvailable("gradle")||_internals211.existsSync(path256.join(gradleModuleDir,"gradlew"))||_internals211.existsSync(path256.join(gradleModuleDir,"gradlew.bat"))))return"gradle";return"none"}function detectPhpTest(cwd){if(_internals211.existsSync(path256.join(cwd,"artisan"))&&_internals211.existsSync(path256.join(cwd,"composer.json")))return"php-artisan";if(_internals211.existsSync(path256.join(cwd,"Pest.php")))return"pest";if(_internals211.existsSync(path256.join(cwd,"phpunit.xml"))||_internals211.existsSync(path256.join(cwd,"phpunit.xml.dist")))return"phpunit";return null}function isTestDirectoryPath(normalizedPath){return normalizedPath.split("/").some((segment)=>TEST_DIRECTORY_NAMES.includes(segment))}function resolveWorkspacePath(file3,workingDir){return path256.isAbsolute(file3)?path256.resolve(file3):path256.resolve(workingDir,file3)}function toWorkspaceOutputPath(absolutePath2,workingDir,preferRelative){if(!preferRelative)return absolutePath2;return path256.relative(workingDir,absolutePath2)}function dedupePush(target,value){if(!target.includes(value))target.push(value)}function buildLanguageSpecificTestNames(nameWithoutExt,ext){switch(ext){case".go":return[`${nameWithoutExt}_test.go`];case".py":return[`test_${nameWithoutExt}.py`,`${nameWithoutExt}_test.py`];case".rb":return[`${nameWithoutExt}_spec.rb`];case".java":return[`${nameWithoutExt}Test.java`,`${nameWithoutExt}Tests.java`,`Test${nameWithoutExt}.java`,`${nameWithoutExt}IT.java`];case".cs":return[`${nameWithoutExt}Test.cs`,`${nameWithoutExt}Tests.cs`];case".kt":return[`${nameWithoutExt}Test.kt`,`${nameWithoutExt}Tests.kt`,`Test${nameWithoutExt}.kt`];case".php":return[`${nameWithoutExt}Test.php`,`${nameWithoutExt}Tests.php`,`Test${nameWithoutExt}.php`];case".ps1":return[`${nameWithoutExt}.Tests.ps1`,`${nameWithoutExt}.tests.ps1`];default:return[]}}function findPathSegmentIndex(normalizedPath,segment){for(let index=normalizedPath.indexOf(segment);index!==-1;index=normalizedPath.indexOf(segment,index+1))if(index===0||normalizedPath[index-1]==="/")return index;return-1}function getRepoLevelCandidateDirectories(workingDir,relativePath2,ext){let relativeDir=path256.dirname(relativePath2),nestedRelativeDir=relativeDir==="."?"":relativeDir,directories=TEST_DIRECTORY_NAMES.flatMap((dirName)=>{let rootDir2=path256.join(workingDir,dirName);return nestedRelativeDir?[rootDir2,path256.join(rootDir2,nestedRelativeDir)]:[rootDir2]}),normalizedRelativePath=relativePath2.replace(/\\/g,"/");if(ext===".java"){let index=findPathSegmentIndex(normalizedRelativePath,"src/main/java/");if(index!==-1)directories.push(path256.join(workingDir,normalizedRelativePath.slice(0,index),"src/test/java",path256.dirname(normalizedRelativePath.slice(index+14))))}if(ext===".kt"||ext===".java"){let index=findPathSegmentIndex(normalizedRelativePath,"src/main/kotlin/");if(index!==-1)directories.push(path256.join(workingDir,normalizedRelativePath.slice(0,index),"src/test/kotlin",path256.dirname(normalizedRelativePath.slice(index+16))))}return[...new Set(directories)]}function hasCompoundTestExtension(filename){let lower=filename.toLowerCase();return COMPOUND_TEST_EXTENSIONS.some((ext)=>lower.endsWith(ext))}function isLanguageSpecificTestFile(basename45){let lower=basename45.toLowerCase();if(lower.endsWith("_test.go"))return!0;if(lower.endsWith(".py")&&(lower.startsWith("test_")||lower.endsWith("_test.py")))return!0;if(lower.endsWith("_spec.rb"))return!0;if(lower.endsWith(".java")&&(/^Test[A-Z]/.test(basename45)||basename45.endsWith("Test.java")||basename45.endsWith("Tests.java")||lower.endsWith("it.java")))return!0;if(lower.endsWith(".cs")&&(lower.endsWith("test.cs")||lower.endsWith("tests.cs")))return!0;if(lower.endsWith(".kt")&&(/^Test[A-Z]/.test(basename45)||lower.endsWith("test.kt")||lower.endsWith("tests.kt")))return!0;if(lower.endsWith(".php")&&(/^Test[A-Z]/.test(basename45)||basename45.endsWith("Test.php")||basename45.endsWith("Tests.php")))return!0;if(lower.endsWith(".tests.ps1"))return!0;return!1}function isConventionTestFilePath(filePath){let normalizedPath=filePath.replace(/\\/g,"/"),basename45=path256.basename(filePath);return hasCompoundTestExtension(basename45)||basename45.includes(".spec.")||basename45.includes(".test.")||isLanguageSpecificTestFile(basename45)||isTestDirectoryPath(normalizedPath)}function getTestFilesFromConvention(sourceFiles,workingDir=process.cwd()){let testFiles=[];for(let file3 of sourceFiles){let absoluteFile=resolveWorkspacePath(file3,workingDir),relativeFile=path256.relative(workingDir,absoluteFile),basename45=path256.basename(absoluteFile),dirname102=path256.dirname(absoluteFile),preferRelativeOutput=!path256.isAbsolute(file3);if(isConventionTestFilePath(relativeFile)||isConventionTestFilePath(file3)){dedupePush(testFiles,toWorkspaceOutputPath(absoluteFile,workingDir,preferRelativeOutput));continue}let nameWithoutExt=basename45.replace(/\.[^.]+$/,""),ext=path256.extname(basename45),genericTestNames=[`${nameWithoutExt}.spec${ext}`,`${nameWithoutExt}.test${ext}`],languageSpecificTestNames=buildLanguageSpecificTestNames(nameWithoutExt,ext),colocatedCandidates=[...genericTestNames,...languageSpecificTestNames].map((candidateName)=>path256.join(dirname102,candidateName)),testDirectoryNames=[basename45,...genericTestNames,...languageSpecificTestNames],repoLevelDirectories=getRepoLevelCandidateDirectories(workingDir,relativeFile,ext),possibleTestFiles=[...colocatedCandidates,...TEST_DIRECTORY_NAMES.flatMap((dirName)=>testDirectoryNames.map((candidateName)=>path256.join(dirname102,dirName,candidateName))),...repoLevelDirectories.flatMap((candidateDir3)=>testDirectoryNames.map((candidateName)=>path256.join(candidateDir3,candidateName)))];for(let testFile of possibleTestFiles)if(fs141.existsSync(testFile))dedupePush(testFiles,toWorkspaceOutputPath(testFile,workingDir,preferRelativeOutput))}return testFiles}async function getTestFilesFromGraph(sourceFiles,workingDir,maxFiles=MAX_SAFE_TEST_FILES2+1){let testFiles=[],absoluteSourceFiles=sourceFiles.map((sourceFile)=>resolveWorkspacePath(sourceFile,workingDir)),candidateTestFiles=getTestFilesFromConvention(sourceFiles,workingDir);if(sourceFiles.length===0)return testFiles;for(let testFile of candidateTestFiles)try{let absoluteTestFile=resolveWorkspacePath(testFile,workingDir);if(fs141.statSync(absoluteTestFile).size>MAX_GRAPH_FILE_BYTES)continue;let content=fs141.readFileSync(absoluteTestFile,"utf-8");if(Buffer.byteLength(content,"utf8")>MAX_GRAPH_FILE_BYTES)continue;let testDir=path256.dirname(absoluteTestFile),importRegex=/import\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g,match;match=importRegex.exec(content);while(match!==null){let importPath=match[1],resolvedImport;if(importPath.startsWith(".")){if(resolvedImport=path256.resolve(testDir,importPath),!path256.extname(resolvedImport))for(let extToTry of[".ts",".tsx",".js",".jsx",".mjs",".cjs"]){let withExt=resolvedImport+extToTry;if(absoluteSourceFiles.includes(withExt)||fs141.existsSync(withExt)){resolvedImport=withExt;break}}}else{let nextIndex=match.index+Math.max(match[0].length,1);if(importRegex.lastIndex<=match.index)importRegex.lastIndex=nextIndex;match=importRegex.exec(content);continue}let importBasename=path256.basename(resolvedImport,path256.extname(resolvedImport)),importDir=path256.dirname(resolvedImport);for(let sourceFile of absoluteSourceFiles){let sourceDir=path256.dirname(sourceFile),sourceBasename=path256.basename(sourceFile,path256.extname(sourceFile)),isRelatedDir=importDir===sourceDir||importDir===path256.join(sourceDir,"__tests__")||importDir===path256.join(sourceDir,"tests")||importDir===path256.join(sourceDir,"test")||importDir===path256.join(sourceDir,"spec");if(resolvedImport===sourceFile||importBasename===sourceBasename&&isRelatedDir){if(dedupePush(testFiles,testFile),testFiles.length>=maxFiles)return testFiles;break}}match=importRegex.exec(content)}let requireRegex=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;match=requireRegex.exec(content);while(match!==null){let importPath=match[1];if(importPath.startsWith(".")){let resolvedImport=path256.resolve(testDir,importPath);if(!path256.extname(resolvedImport))for(let extToTry of[".ts",".tsx",".js",".jsx",".mjs",".cjs"]){let withExt=resolvedImport+extToTry;if(absoluteSourceFiles.includes(withExt)||fs141.existsSync(withExt)){resolvedImport=withExt;break}}let importDir=path256.dirname(resolvedImport),importBasename=path256.basename(resolvedImport,path256.extname(resolvedImport));for(let sourceFile of absoluteSourceFiles){let sourceDir=path256.dirname(sourceFile),sourceBasename=path256.basename(sourceFile,path256.extname(sourceFile)),isRelatedDir=importDir===sourceDir||importDir===path256.join(sourceDir,"__tests__")||importDir===path256.join(sourceDir,"tests")||importDir===path256.join(sourceDir,"test")||importDir===path256.join(sourceDir,"spec");if(resolvedImport===sourceFile||importBasename===sourceBasename&&isRelatedDir){if(dedupePush(testFiles,testFile),testFiles.length>=maxFiles)return testFiles;break}}}match=requireRegex.exec(content)}}catch{}return testFiles}function getTargetedExecutionUnsupportedReason(framework){switch(framework){case"go-test":return"go test targets packages, not individual test files";case"cargo":return"cargo test targets crates, targets, or test names rather than file paths";case"maven":return"maven test selection is class-based, not file-path based";case"gradle":return"gradle test selection is class-based, not file-path based";case"dotnet-test":return"dotnet test filters by fully qualified names, not file paths";case"ctest":return"ctest filters named tests from the build tree, not source test files";case"swift-test":return"swift test filters test names, not file paths";default:return null}}function deriveClassBasedTargets(files){let derived=[],seen=new Set;for(let file3 of files){let ext=path256.extname(file3);if(!CLASS_BASED_TEST_EXTENSIONS.has(ext.toLowerCase()))return[];let className=path256.basename(file3,ext);if(!className||seen.has(className))continue;seen.add(className),derived.push(className)}return derived}function buildTestCommand3(framework,scope,files,coverage,baseDir,bail,targets,nativeTarget){if(nativeTarget)return nativeTarget.framework===framework?buildNativeTargetCommand(nativeTarget):null;switch(framework){case"bun":{let args2=["bun","test"];if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"vitest":{let args2=_internals211.resolveLocalNodeTool("vitest",["run","--reporter=json","--outputFile",VITEST_JSON_OUTPUT_RELATIVE_PATH],baseDir,process.platform,_internals211.isCommandAvailable);if(!args2)return null;if(coverage)args2.push("--coverage");if(bail)args2.push("--bail=1");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"jest":{let args2=_internals211.resolveLocalNodeTool("jest",["--json"],baseDir,process.platform,_internals211.isCommandAvailable);if(!args2)return null;if(coverage)args2.push("--coverage");if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"mocha":{let args2=_internals211.resolveLocalNodeTool("mocha",[],baseDir,process.platform,_internals211.isCommandAvailable);if(!args2)return null;if(bail)args2.push("--bail");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"pytest":{let args2=process.platform==="win32"?["python","-m","pytest"]:["python3","-m","pytest"];if(coverage)args2.push("--cov=.","--cov-report=term-missing");if(bail)args2.push("-x");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"cargo":{let args2=["cargo","test"];if(targets&&targets.length>0)args2.push("--",...targets);else if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"pester":{if(scope!=="all"&&files.length>0){let psCommand=`Invoke-Pester -Path @('${files.map((f)=>f.replace(/'/g,"''").replace(/`/g,"``").replace(/\$/g,"`$")).join("','")}')`;return["pwsh","-EncodedCommand",Buffer.from(psCommand,"utf16le").toString("base64")]}return["pwsh","-Command","Invoke-Pester"]}case"go-test":{let args2=["go","test"];if(targets&&targets.length>0)args2.push("-run",targets.join("|"));return args2.push("./..."),args2}case"maven":return buildMavenTestCommand(baseDir,targets);case"gradle":return buildGradleTestCommand(baseDir,targets);case"dotnet-test":{let args2=["dotnet","test"];if(targets&&targets.length>0)args2.push("--filter",targets.join("|"));return args2}case"ctest":{let args2=["ctest","--test-dir",["build","_build","cmake-build-debug","cmake-build-release","out"].find((d)=>fs141.existsSync(path256.join(baseDir,d,"CMakeCache.txt")))??"build"];if(targets&&targets.length>0)args2.push("-R",targets.join("|"));return args2}case"swift-test":{let args2=["swift","test"];if(targets&&targets.length>0)for(let target of targets)args2.push("--filter",target);return args2}case"dart-test":return _internals211.isCommandAvailable("flutter")?["flutter","test",...files]:["dart","test",...files];case"rspec":{let args2=_internals211.isCommandAvailable("bundle")?["bundle","exec","rspec"]:["rspec"];if(bail)args2.push("--fail-fast");if(scope!=="all"&&files.length>0)args2.push(...files);return args2}case"minitest":if(scope!=="all"&&files.length>0)return["ruby","-Itest","-e",files.map((f)=>`require_relative '${f.replace(/\\/g,"/").replace(/'/g,"\\'")}'`).join("; ")];return["ruby","-Itest","-e",'Dir.glob("test/**/*_test.rb").sort.each { |f| require_relative f }'];case"pest":return buildPhpVendorCommand(baseDir,"pest",scope!=="all"&&files.length>0?files:[]);case"phpunit":return buildPhpVendorCommand(baseDir,"phpunit",scope!=="all"&&files.length>0?files:[]);case"php-artisan":{let args2=["php","artisan","test"];if(scope!=="all"&&files.length>0)args2.push(...files);return args2}default:return null}}function mapFrameworkStatusToResult(status2){if(typeof status2!=="string")return null;let normalized=status2.toLowerCase();if(normalized==="pass"||normalized==="passed")return"pass";if(normalized==="fail"||normalized==="failed")return"fail";if(normalized==="skip"||normalized==="skipped"||normalized==="pending"||normalized==="todo")return"skip";return null}function firstLine(value){if(typeof value!=="string")return;let line=value.split(`
|
|
4071
4071
|
`).find((part)=>part.trim().length>0)?.trim();return line&&line.length>0?line:void 0}function parseJestLikeJsonTestResults(payload){if(typeof payload!=="object"||payload===null)return[];let rawSuites=payload.testResults;if(!Array.isArray(rawSuites))return[];let parsed=[];for(let suite of rawSuites){if(typeof suite!=="object"||suite===null)continue;let suiteObj=suite,rawFile=typeof suiteObj.name==="string"?suiteObj.name:typeof suiteObj.testFilePath==="string"?suiteObj.testFilePath:void 0;if(!rawFile)continue;let testFile=rawFile.replace(/\\/g,"/"),assertionResults=suiteObj.assertionResults;if(!Array.isArray(assertionResults))continue;for(let assertion of assertionResults){if(typeof assertion!=="object"||assertion===null)continue;let assertionObj=assertion,result=mapFrameworkStatusToResult(assertionObj.status),testName=typeof assertionObj.fullName==="string"?assertionObj.fullName:typeof assertionObj.title==="string"?assertionObj.title:void 0;if(!result||!testName||testName.length===0)continue;let firstFailure=(Array.isArray(assertionObj.failureMessages)?assertionObj.failureMessages:[]).find((entry)=>typeof entry==="string"&&entry.length>0),durationMs=typeof assertionObj.duration==="number"&&Number.isFinite(assertionObj.duration)?Math.max(assertionObj.duration,0):0;parsed.push({testFile,testName,result,durationMs,errorMessage:firstLine(firstFailure),stackPrefix:firstLine(firstFailure)})}}return parsed}function parseBunJsonLines(output){let parsed=[];for(let line of output.split(`
|
|
4072
4072
|
`)){let trimmed=line.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))continue;try{let obj=JSON.parse(trimmed),rawFile=typeof obj.file==="string"?obj.file:typeof obj.testFile==="string"?obj.testFile:typeof obj.path==="string"?obj.path:void 0,rawName=typeof obj.testName==="string"?obj.testName:typeof obj.fullName==="string"?obj.fullName:typeof obj.name==="string"?obj.name:void 0,result=mapFrameworkStatusToResult(typeof obj.status==="string"?obj.status:obj.result);if(!rawFile||!rawName||!result)continue;let errorObj=typeof obj.error==="object"&&obj.error!==null?obj.error:void 0,durationMs=typeof obj.durationMs==="number"&&Number.isFinite(obj.durationMs)?Math.max(obj.durationMs,0):typeof obj.duration==="number"&&Number.isFinite(obj.duration)?Math.max(obj.duration,0):0;parsed.push({testFile:rawFile.replace(/\\/g,"/"),testName:rawName,result,durationMs,errorMessage:firstLine(errorObj?.message??obj.errorMessage),stackPrefix:firstLine(errorObj?.stack)})}catch{}}return parsed}function parseFrameworkJsonTestResults(framework,output){let jsonMatch=output.match(/\{[\s\S]*"testResults"[\s\S]*\}/);if(jsonMatch)try{let parsed=JSON.parse(jsonMatch[0]),testResults=parseJestLikeJsonTestResults(parsed);if(testResults.length>0)return testResults}catch{}for(let line of output.split(`
|
|
4073
|
-
`)){let trimmed=line.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))continue;try{let parsed=JSON.parse(trimmed),testResults=parseJestLikeJsonTestResults(parsed);if(testResults.length>0)return testResults}catch{}}if(framework==="bun")return parseBunJsonLines(output);return[]}function parseTestOutput2(framework,output){let totals={passed:0,failed:0,skipped:0,total:0},coveragePercent;switch(framework){case"vitest":case"jest":case"bun":{let jsonMatch=output.match(/\{[\s\S]*"testResults"[\s\S]*\}/);if(jsonMatch)try{let parsed=JSON.parse(jsonMatch[0]);if(parsed.numTotalTests!==void 0)totals.passed=parsed.numPassedTests||0,totals.failed=parsed.numFailedTests||0,totals.skipped=parsed.numPendingTests||0,totals.total=parsed.numTotalTests||0;if(parsed.coverage!==void 0)coveragePercent=parsed.coverage}catch{}if(totals.total===0){let passMatch=output.match(/(\d+)\s+pass(ing|ed)?/),failMatch=output.match(/(\d+)\s+fail(ing|ed)?/),skipMatch=output.match(/(\d+)\s+skip(ping|ped)?/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped}let coverageMatch=output.match(/All files[^\d]*(\d+\.?\d*)\s*%/);if(!coveragePercent&&coverageMatch)coveragePercent=parseFloat(coverageMatch[1]);break}case"mocha":{let passMatch=output.match(/(\d+)\s+passing/),failMatch=output.match(/(\d+)\s+failing/),pendingMatch=output.match(/(\d+)\s+pending/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(pendingMatch)totals.skipped=parseInt(pendingMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"pytest":{let passMatch=output.match(/(\d+)\s+passed/),failMatch=output.match(/(\d+)\s+failed/),skipMatch=output.match(/(\d+)\s+skipped/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;let coverageMatch=output.match(/TOTAL\s+(\d+\.?\d*)\s*%/);if(coverageMatch)coveragePercent=parseFloat(coverageMatch[1]);break}case"cargo":{let passMatch=output.match(/test result: ok\. (\d+) passed/),failMatch=output.match(/test result: FAILED\. (\d+) passed; (\d+) failed/);if(failMatch)totals.passed=parseInt(failMatch[1],10),totals.failed=parseInt(failMatch[2],10);else if(passMatch)totals.passed=parseInt(passMatch[1],10);totals.total=totals.passed+totals.failed;break}case"pester":{let passMatch=output.match(/Passed:\s*(\d+)/),failMatch=output.match(/Failed:\s*(\d+)/),skipMatch=output.match(/Skipped:\s*(\d+)/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"go-test":{let passMatches=[...output.matchAll(/--- PASS:/g)],failMatches=[...output.matchAll(/--- FAIL:/g)],skipMatches=[...output.matchAll(/--- SKIP:/g)];totals.passed=passMatches.length,totals.failed=failMatches.length,totals.skipped=skipMatches.length,totals.total=totals.passed+totals.failed+totals.skipped;let covMatch=output.match(/coverage:\s*(\d+\.?\d*)\s*%/);if(covMatch)coveragePercent=parseFloat(covMatch[1]);break}case"maven":{let mavenMatch=output.match(/Tests run:\s*(\d+),\s*Failures:\s*(\d+),\s*Errors:\s*(\d+),\s*Skipped:\s*(\d+)/);if(mavenMatch){let total=parseInt(mavenMatch[1],10),failures=parseInt(mavenMatch[2],10),errors5=parseInt(mavenMatch[3],10),skipped=parseInt(mavenMatch[4],10);totals.failed=failures+errors5,totals.skipped=skipped,totals.passed=total-totals.failed-skipped,totals.total=total}break}case"gradle":{let gradleMatch=output.match(/(\d+) tests? completed(?:,\s*(\d+) failed)?(?:,\s*(\d+) skipped)?/);if(gradleMatch)totals.total=parseInt(gradleMatch[1],10),totals.failed=gradleMatch[2]?parseInt(gradleMatch[2],10):0,totals.skipped=gradleMatch[3]?parseInt(gradleMatch[3],10):0,totals.passed=totals.total-totals.failed-totals.skipped;break}case"dotnet-test":{let passMatch=output.match(/Passed[!:]?\s*(\d+)/i),failMatch=output.match(/Failed[!:]?\s*(\d+)/i),skipMatch=output.match(/Skipped[!:]?\s*(\d+)/i);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"ctest":{let disabledCount=[...output.matchAll(/\*{3}Not Run\s+\(Disabled\)/gi)].length;totals.skipped=disabledCount;let ctestMatch=output.match(/(\d+) tests? failed out of (\d+)/);if(ctestMatch){totals.failed=parseInt(ctestMatch[1],10);let executedTotal=parseInt(ctestMatch[2],10);totals.total=executedTotal+disabledCount,totals.passed=executedTotal-totals.failed}else{let allPassMatch=output.match(/100% tests passed.*?(\d+) tests?/);if(allPassMatch){let executedTotal=parseInt(allPassMatch[1],10);totals.total=executedTotal+disabledCount,totals.passed=executedTotal}else if(disabledCount>0)totals.total=disabledCount}break}case"swift-test":{let swiftMatch=output.match(/Executed (\d+) tests?,\s*with (\d+) failures?/);if(swiftMatch)totals.total=parseInt(swiftMatch[1],10),totals.failed=parseInt(swiftMatch[2],10),totals.passed=totals.total-totals.failed;break}case"dart-test":{let dartPassMatch=output.match(/\+(\d+):\s*All tests passed/),dartMixMatch=output.match(/\+(\d+)\s+-(\d+):/);if(dartPassMatch)totals.passed=parseInt(dartPassMatch[1],10),totals.total=totals.passed;else if(dartMixMatch)totals.passed=parseInt(dartMixMatch[1],10),totals.failed=parseInt(dartMixMatch[2],10),totals.total=totals.passed+totals.failed;break}case"rspec":{let rspecMatch=output.match(/(\d+) examples?,\s*(\d+) failures?(?:,\s*(\d+) pending)?/);if(rspecMatch)totals.total=parseInt(rspecMatch[1],10),totals.failed=parseInt(rspecMatch[2],10),totals.skipped=rspecMatch[3]?parseInt(rspecMatch[3],10):0,totals.passed=totals.total-totals.failed-totals.skipped;break}case"minitest":{let minitestMatch=output.match(/(\d+) runs?,\s*\d+ assertions?,\s*(\d+) failures?,\s*(\d+) errors?,\s*(\d+) skips?/);if(minitestMatch)totals.total=parseInt(minitestMatch[1],10),totals.failed=parseInt(minitestMatch[2],10)+parseInt(minitestMatch[3],10),totals.skipped=parseInt(minitestMatch[4],10),totals.passed=totals.total-totals.failed-totals.skipped;break}case"pest":case"phpunit":case"php-artisan":{let phpunitMatch=output.match(/Tests:\s*(\d+),\s*Assertions:\s*\d+(?:,\s*Failures:\s*(\d+))?(?:,\s*Errors:\s*(\d+))?(?:,\s*Skipped:\s*(\d+))?/),okMatch=output.match(/OK\s*\((\d+)\s+tests?/);if(phpunitMatch){totals.total=parseInt(phpunitMatch[1],10);let failures=phpunitMatch[2]?parseInt(phpunitMatch[2],10):0,errors5=phpunitMatch[3]?parseInt(phpunitMatch[3],10):0;totals.skipped=phpunitMatch[4]?parseInt(phpunitMatch[4],10):0,totals.failed=failures+errors5,totals.passed=totals.total-totals.failed-totals.skipped}else if(okMatch)totals.total=parseInt(okMatch[1],10),totals.passed=totals.total;break}default:break}return{totals,coveragePercent}}async function readBoundedStream2(stream,maxBytes){let reader=stream.getReader(),chunks=[],totalBytes=0,truncated=!1;try{while(!0){let{done,value}=await reader.read();if(done)break;if(totalBytes+value.length>maxBytes){let remaining=maxBytes-totalBytes;if(remaining>0)chunks.push(value.slice(0,remaining));totalBytes=maxBytes,truncated=!0,reader.cancel().catch(()=>{});break}chunks.push(value),totalBytes+=value.length}}catch{}finally{try{reader.releaseLock()}catch{}}let decoder=new TextDecoder("utf-8",{fatal:!1}),combined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)combined.set(chunk,offset),offset+=chunk.length;return{text:decoder.decode(combined),truncated}}function formatPassingMessage(framework,totals,coveragePercent){let message=totals.total>0&&totals.passed===0&&totals.failed===0&&totals.skipped===totals.total?`${framework} tests completed with ${totals.skipped} skipped (${totals.total} total)`:`${framework} tests passed (${totals.passed}/${totals.total})`;if(coveragePercent!==void 0)message+=` with ${coveragePercent}% coverage`;return message}function formatNativeHistoryTestFile(target,historyPath){return`native:${target.framework}:path=${encodeURIComponent(historyPath)}#name=${encodeURIComponent(target.name)}`}async function runTests(framework,scope,files,coverage,timeout_ms,cwd,bail,targets,nativeTarget){let executionCwd=cwd,resolvedNativeTarget=nativeTarget;if(scope==="target"&&!nativeTarget||scope!=="target"&&nativeTarget!==void 0||nativeTarget!==void 0&&nativeTarget.framework!==framework)return{success:!1,framework,scope,error:"Invalid native target pairing; refusing broad test fallback",message:'scope "target" requires one matching native target, and native targets are not valid with other scopes.',outcome:"error"};if(scope==="target"){if(files.length>0||coverage||bail)return{success:!1,framework,scope,error:'scope "target" cannot be combined with files, coverage, or bail',message:"Native target mode runs one exact framework-native name only. Omit files and leave coverage and bail disabled.",outcome:"error"};let nativeTargetError=validateNativeTargetInput(nativeTarget);if(nativeTargetError)return{success:!1,framework,scope,error:nativeTargetError,outcome:"error"};let resolvedTarget=resolveNativeTarget(nativeTarget,cwd);if(!resolvedTarget.success)return{success:!1,framework,scope,error:resolvedTarget.error,outcome:"error"};resolvedNativeTarget=resolvedTarget.target,executionCwd=resolvedTarget.executionDirectory}if(scope!=="all"&&scope!=="target"&&files.length>0&&!(targets&&targets.length>0)){let unsupportedReason=getTargetedExecutionUnsupportedReason(framework);if(unsupportedReason)return{success:!1,framework,scope,error:`Framework "${framework}" does not support targeted test-file execution`,message:`The resolved test selection cannot be run safely because ${unsupportedReason}. Use a framework-native selector manually or let the architect handle the broader sweep.`,outcome:"error"}}let command=process.env.SWARM_LANG_BACKEND!=="legacy"?await buildTestCommandViaDispatch(framework,scope,files,coverage,executionCwd,bail,targets,resolvedNativeTarget)??buildTestCommand3(framework,scope,files,coverage,executionCwd,bail,targets,resolvedNativeTarget):buildTestCommand3(framework,scope,files,coverage,executionCwd,bail,targets,resolvedNativeTarget);if(!command)return{success:!1,framework,scope,error:`No test command available for framework: ${framework}`,message:"Install a supported test framework to run tests",outcome:"error"};if(command.join(" ").length>MAX_COMMAND_LENGTH2)return{success:!1,framework,scope,command,error:"Command exceeds maximum allowed length",outcome:"error"};let startTime=Date.now(),vitestJsonOutputPath=framework==="vitest"?path256.join(executionCwd,".swarm","cache","test-runner-vitest.json"):void 0,proc,timeoutHandle,timedOutByDeadline=!1;try{if(vitestJsonOutputPath)try{if(fs141.mkdirSync(path256.dirname(vitestJsonOutputPath),{recursive:!0}),fs141.existsSync(vitestJsonOutputPath))fs141.unlinkSync(vitestJsonOutputPath)}catch{}let timeoutPromise=new Promise((resolve100)=>{timeoutHandle=setTimeout(()=>{resolve100({kind:"timeout"})},timeout_ms)});proc=_internals211.bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:executionCwd,timeout:timeout_ms,killProcessTree:!0,...isWindowsCommandInterpreterLaunch(command)?{windowsVerbatimArguments:!0}:{}});let stdoutPromise=readBoundedStream2(proc.stdout,MAX_OUTPUT_BYTES5),stderrPromise=readBoundedStream2(proc.stderr,MAX_OUTPUT_BYTES5),raceResult=await Promise.race([proc.exited.then((exitCode2)=>({kind:"exit",exitCode:exitCode2})),timeoutPromise]);if(timedOutByDeadline=raceResult.kind==="timeout",timeoutHandle!==void 0)clearTimeout(timeoutHandle),timeoutHandle=void 0;let[stdoutResult,stderrResult]=await Promise.all([stdoutPromise,stderrPromise]),exitCode=raceResult.kind==="timeout"?-1:raceResult.exitCode,duration_ms=Date.now()-startTime,output=stdoutResult.text;if(stderrResult.text)output+=(output?`
|
|
4073
|
+
`)){let trimmed=line.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))continue;try{let parsed=JSON.parse(trimmed),testResults=parseJestLikeJsonTestResults(parsed);if(testResults.length>0)return testResults}catch{}}if(framework==="bun")return parseBunJsonLines(output);return[]}function parseTestOutput2(framework,output){let totals={passed:0,failed:0,skipped:0,total:0},coveragePercent;switch(framework){case"vitest":case"jest":case"bun":{let jsonMatch=output.match(/\{[\s\S]*"testResults"[\s\S]*\}/);if(jsonMatch)try{let parsed=JSON.parse(jsonMatch[0]);if(parsed.numTotalTests!==void 0)totals.passed=parsed.numPassedTests||0,totals.failed=parsed.numFailedTests||0,totals.skipped=parsed.numPendingTests||0,totals.total=parsed.numTotalTests||0;if(parsed.coverage!==void 0)coveragePercent=parsed.coverage}catch{}if(totals.total===0){let passMatch=output.match(/(\d+)\s+pass(ing|ed)?/),failMatch=output.match(/(\d+)\s+fail(ing|ed)?/),skipMatch=output.match(/(\d+)\s+skip(ping|ped)?/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped}let coverageMatch=output.match(/All files[^\d]*(\d+\.?\d*)\s*%/);if(!coveragePercent&&coverageMatch)coveragePercent=parseFloat(coverageMatch[1]);break}case"mocha":{let passMatch=output.match(/(\d+)\s+passing/),failMatch=output.match(/(\d+)\s+failing/),pendingMatch=output.match(/(\d+)\s+pending/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(pendingMatch)totals.skipped=parseInt(pendingMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"pytest":{let passMatch=output.match(/(\d+)\s+passed/),failMatch=output.match(/(\d+)\s+failed/),skipMatch=output.match(/(\d+)\s+skipped/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;let coverageMatch=output.match(/TOTAL\s+(\d+\.?\d*)\s*%/);if(coverageMatch)coveragePercent=parseFloat(coverageMatch[1]);break}case"cargo":{let passMatch=output.match(/test result: ok\. (\d+) passed/),failMatch=output.match(/test result: FAILED\. (\d+) passed; (\d+) failed/);if(failMatch)totals.passed=parseInt(failMatch[1],10),totals.failed=parseInt(failMatch[2],10);else if(passMatch)totals.passed=parseInt(passMatch[1],10);totals.total=totals.passed+totals.failed;break}case"pester":{let passMatch=output.match(/Passed:\s*(\d+)/),failMatch=output.match(/Failed:\s*(\d+)/),skipMatch=output.match(/Skipped:\s*(\d+)/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"go-test":{let passMatches=[...output.matchAll(/--- PASS:/g)],failMatches=[...output.matchAll(/--- FAIL:/g)],skipMatches=[...output.matchAll(/--- SKIP:/g)];totals.passed=passMatches.length,totals.failed=failMatches.length,totals.skipped=skipMatches.length,totals.total=totals.passed+totals.failed+totals.skipped;let covMatch=output.match(/coverage:\s*(\d+\.?\d*)\s*%/);if(covMatch)coveragePercent=parseFloat(covMatch[1]);break}case"maven":{let mavenMatch=output.match(/Tests run:\s*(\d+),\s*Failures:\s*(\d+),\s*Errors:\s*(\d+),\s*Skipped:\s*(\d+)/);if(mavenMatch){let total=parseInt(mavenMatch[1],10),failures=parseInt(mavenMatch[2],10),errors5=parseInt(mavenMatch[3],10),skipped=parseInt(mavenMatch[4],10);totals.failed=failures+errors5,totals.skipped=skipped,totals.passed=total-totals.failed-skipped,totals.total=total}break}case"gradle":{let gradleMatch=output.match(/(\d+) tests? completed(?:,\s*(\d+) failed)?(?:,\s*(\d+) skipped)?/);if(gradleMatch)totals.total=parseInt(gradleMatch[1],10),totals.failed=gradleMatch[2]?parseInt(gradleMatch[2],10):0,totals.skipped=gradleMatch[3]?parseInt(gradleMatch[3],10):0,totals.passed=totals.total-totals.failed-totals.skipped;break}case"dotnet-test":{let passMatch=output.match(/Passed[!:]?\s*(\d+)/i),failMatch=output.match(/Failed[!:]?\s*(\d+)/i),skipMatch=output.match(/Skipped[!:]?\s*(\d+)/i);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"ctest":{let disabledCount=[...output.matchAll(/\*{3}Not Run\s+\(Disabled\)/gi)].length;totals.skipped=disabledCount;let ctestMatch=output.match(/(\d+) tests? failed out of (\d+)/);if(ctestMatch){totals.failed=parseInt(ctestMatch[1],10);let executedTotal=parseInt(ctestMatch[2],10);totals.total=executedTotal+disabledCount,totals.passed=executedTotal-totals.failed}else{let allPassMatch=output.match(/100% tests passed.*?(\d+) tests?/);if(allPassMatch){let executedTotal=parseInt(allPassMatch[1],10);totals.total=executedTotal+disabledCount,totals.passed=executedTotal}else if(disabledCount>0)totals.total=disabledCount}break}case"swift-test":{let swiftMatch=output.match(/Executed (\d+) tests?,\s*with (\d+) failures?/);if(swiftMatch)totals.total=parseInt(swiftMatch[1],10),totals.failed=parseInt(swiftMatch[2],10),totals.passed=totals.total-totals.failed;break}case"dart-test":{let dartPassMatch=output.match(/\+(\d+):\s*All tests passed/),dartMixMatch=output.match(/\+(\d+)\s+-(\d+):/);if(dartPassMatch)totals.passed=parseInt(dartPassMatch[1],10),totals.total=totals.passed;else if(dartMixMatch)totals.passed=parseInt(dartMixMatch[1],10),totals.failed=parseInt(dartMixMatch[2],10),totals.total=totals.passed+totals.failed;break}case"rspec":{let rspecMatch=output.match(/(\d+) examples?,\s*(\d+) failures?(?:,\s*(\d+) pending)?/);if(rspecMatch)totals.total=parseInt(rspecMatch[1],10),totals.failed=parseInt(rspecMatch[2],10),totals.skipped=rspecMatch[3]?parseInt(rspecMatch[3],10):0,totals.passed=totals.total-totals.failed-totals.skipped;break}case"minitest":{let minitestMatch=output.match(/(\d+) runs?,\s*\d+ assertions?,\s*(\d+) failures?,\s*(\d+) errors?,\s*(\d+) skips?/);if(minitestMatch)totals.total=parseInt(minitestMatch[1],10),totals.failed=parseInt(minitestMatch[2],10)+parseInt(minitestMatch[3],10),totals.skipped=parseInt(minitestMatch[4],10),totals.passed=totals.total-totals.failed-totals.skipped;break}case"pest":case"phpunit":case"php-artisan":{let phpunitMatch=output.match(/Tests:\s*(\d+),\s*Assertions:\s*\d+(?:,\s*Failures:\s*(\d+))?(?:,\s*Errors:\s*(\d+))?(?:,\s*Skipped:\s*(\d+))?/),okMatch=output.match(/OK\s*\((\d+)\s+tests?/);if(phpunitMatch){totals.total=parseInt(phpunitMatch[1],10);let failures=phpunitMatch[2]?parseInt(phpunitMatch[2],10):0,errors5=phpunitMatch[3]?parseInt(phpunitMatch[3],10):0;totals.skipped=phpunitMatch[4]?parseInt(phpunitMatch[4],10):0,totals.failed=failures+errors5,totals.passed=totals.total-totals.failed-totals.skipped}else if(okMatch)totals.total=parseInt(okMatch[1],10),totals.passed=totals.total;break}default:break}return{totals,coveragePercent}}async function readBoundedStream2(stream,maxBytes){let reader=stream.getReader(),chunks=[],totalBytes=0,truncated=!1;try{while(!0){let{done,value}=await reader.read();if(done)break;if(totalBytes+value.length>maxBytes){let remaining=maxBytes-totalBytes;if(remaining>0)chunks.push(value.slice(0,remaining));totalBytes=maxBytes,truncated=!0,reader.cancel().catch(()=>{});break}chunks.push(value),totalBytes+=value.length}}catch{}finally{try{reader.releaseLock()}catch{}}let decoder=new TextDecoder("utf-8",{fatal:!1}),combined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)combined.set(chunk,offset),offset+=chunk.length;return{text:decoder.decode(combined),truncated}}function formatPassingMessage(framework,totals,coveragePercent){let message=totals.total>0&&totals.passed===0&&totals.failed===0&&totals.skipped===totals.total?`${framework} tests completed with ${totals.skipped} skipped (${totals.total} total)`:`${framework} tests passed (${totals.passed}/${totals.total})`;if(coveragePercent!==void 0)message+=` with ${coveragePercent}% coverage`;return message}function formatNativeHistoryTestFile(target,historyPath){return`native:${target.framework}:path=${encodeURIComponent(historyPath)}#name=${encodeURIComponent(target.name)}`}async function runTests(framework,scope,files,coverage,timeout_ms,cwd,bail,targets,nativeTarget){let executionCwd=cwd,resolvedNativeTarget=nativeTarget;if(scope==="target"&&!nativeTarget||scope!=="target"&&nativeTarget!==void 0||nativeTarget!==void 0&&nativeTarget.framework!==framework)return{success:!1,framework,scope,error:"Invalid native target pairing; refusing broad test fallback",message:'scope "target" requires one matching native target, and native targets are not valid with other scopes.',outcome:"error"};if(scope==="target"){if(files.length>0||coverage||bail)return{success:!1,framework,scope,error:'scope "target" cannot be combined with files, coverage, or bail',message:"Native target mode runs one exact framework-native name only. Omit files and leave coverage and bail disabled.",outcome:"error"};let nativeTargetError=validateNativeTargetInput(nativeTarget);if(nativeTargetError)return{success:!1,framework,scope,error:nativeTargetError,outcome:"error"};let resolvedTarget=resolveNativeTarget(nativeTarget,cwd);if(!resolvedTarget.success)return{success:!1,framework,scope,error:resolvedTarget.error,outcome:"error"};resolvedNativeTarget=resolvedTarget.target,executionCwd=resolvedTarget.executionDirectory}let effectiveTargets=targets;if(scope!=="all"&&scope!=="target"&&files.length>0&&!(targets&&targets.length>0)&&(framework==="maven"||framework==="gradle")){let derivedTargets=deriveClassBasedTargets(files);if(derivedTargets.length>0)effectiveTargets=derivedTargets}if(scope!=="all"&&scope!=="target"&&files.length>0&&!(effectiveTargets&&effectiveTargets.length>0)){let unsupportedReason=getTargetedExecutionUnsupportedReason(framework);if(unsupportedReason)return{success:!1,framework,scope,error:`Framework "${framework}" does not support targeted test-file execution`,message:`The resolved test selection cannot be run safely because ${unsupportedReason}. Use a framework-native selector manually or let the architect handle the broader sweep.`,outcome:"error"}}let command=process.env.SWARM_LANG_BACKEND!=="legacy"?await buildTestCommandViaDispatch(framework,scope,files,coverage,executionCwd,bail,effectiveTargets,resolvedNativeTarget)??buildTestCommand3(framework,scope,files,coverage,executionCwd,bail,effectiveTargets,resolvedNativeTarget):buildTestCommand3(framework,scope,files,coverage,executionCwd,bail,effectiveTargets,resolvedNativeTarget);if(!command)return{success:!1,framework,scope,error:`No test command available for framework: ${framework}`,message:"Install a supported test framework to run tests",outcome:"error"};if(command.join(" ").length>MAX_COMMAND_LENGTH2)return{success:!1,framework,scope,command,error:"Command exceeds maximum allowed length",outcome:"error"};let startTime=Date.now(),vitestJsonOutputPath=framework==="vitest"?path256.join(executionCwd,".swarm","cache","test-runner-vitest.json"):void 0,proc,timeoutHandle,timedOutByDeadline=!1;try{if(vitestJsonOutputPath)try{if(fs141.mkdirSync(path256.dirname(vitestJsonOutputPath),{recursive:!0}),fs141.existsSync(vitestJsonOutputPath))fs141.unlinkSync(vitestJsonOutputPath)}catch{}let timeoutPromise=new Promise((resolve100)=>{timeoutHandle=setTimeout(()=>{resolve100({kind:"timeout"})},timeout_ms)});proc=_internals211.bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:executionCwd,timeout:timeout_ms,killProcessTree:!0,...isWindowsCommandInterpreterLaunch(command)?{windowsVerbatimArguments:!0}:{}});let stdoutPromise=readBoundedStream2(proc.stdout,MAX_OUTPUT_BYTES5),stderrPromise=readBoundedStream2(proc.stderr,MAX_OUTPUT_BYTES5),raceResult=await Promise.race([proc.exited.then((exitCode2)=>({kind:"exit",exitCode:exitCode2})),timeoutPromise]);if(timedOutByDeadline=raceResult.kind==="timeout",timeoutHandle!==void 0)clearTimeout(timeoutHandle),timeoutHandle=void 0;let[stdoutResult,stderrResult]=await Promise.all([stdoutPromise,stderrPromise]),exitCode=raceResult.kind==="timeout"?-1:raceResult.exitCode,duration_ms=Date.now()-startTime,output=stdoutResult.text;if(stderrResult.text)output+=(output?`
|
|
4074
4074
|
`:"")+stderrResult.text;if(vitestJsonOutputPath)try{if(fs141.existsSync(vitestJsonOutputPath)){let vitestJsonOutput=fs141.readFileSync(vitestJsonOutputPath,"utf-8");if(vitestJsonOutput.trim().length>0)output+=(output?`
|
|
4075
4075
|
`:"")+vitestJsonOutput}}catch{}if(stdoutResult.truncated||stderrResult.truncated)output+=`
|
|
4076
|
-
... (output truncated at stream read limit)`;let parsed=process.env.SWARM_LANG_BACKEND!=="legacy"?await parseTestOutputViaDispatch(framework,output,executionCwd)??parseTestOutput2(framework,output):parseTestOutput2(framework,output),parsedTestCases=parseFrameworkJsonTestResults(framework,output),totals={...parsed.totals},{coveragePercent}=parsed;if(totals.total===0&&parsedTestCases.length>0){for(let entry of parsedTestCases)if(entry.result==="pass")totals.passed++;else if(entry.result==="fail")totals.failed++;else totals.skipped++;totals.total=parsedTestCases.length}let isTimeout=timedOutByDeadline,spawnFailure=proc.spawnError,nativeTargetObserved=resolvedNativeTarget?didExecuteNativeTarget(resolvedNativeTarget,output):!0;if(exitCode===0&&!isTimeout&&!spawnFailure&&totals.failed===0&&nativeTargetObserved){let result={success:!0,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,outcome:"pass",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;return result.message=formatPassingMessage(framework,totals,coveragePercent),result}else{let result={success:!1,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,error:spawnFailure?`Test command failed to launch: ${spawnFailure.message}`:isTimeout?`Tests timed out after ${timeout_ms}ms`:!nativeTargetObserved?`Native target "${resolvedNativeTarget?.name}" did not execute`:`Tests failed with ${totals.failed} failures`,message:spawnFailure?`${framework} test process could not be started: ${spawnFailure.message} — a launch failure (for example a missing executable or unusable working directory), not a test regression. Check the command, PATH, and cwd instead of the tests.`:isTimeout?`${framework} tests timed out after ${timeout_ms}ms`:!nativeTargetObserved?`${framework} did not report the exact requested native target; refusing a false-green 0/0 result`:`${framework} tests failed (${totals.failed}/${totals.total} failed)`,outcome:spawnFailure||isTimeout?"error":"regression",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;return result}}catch(error93){let duration_ms=Date.now()-startTime;return{success:!1,framework,scope,command,timeout_ms,duration_ms,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error",outcome:"error"}}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(proc?.exitCode===null&&!timedOutByDeadline)try{if(proc.killTree)await proc.killTree("SIGKILL");else proc.kill("SIGKILL")}catch{}}}function escapeRegexForMatch(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function didExecuteNativeTarget(target,output){if(target.framework==="go-test")return[...output.matchAll(/^\s*--- (?:PASS|FAIL|SKIP):\s+(.+?)(?:\s+\(|$)/gm)].some((match)=>match[1]===target.name);let exactName=escapeRegexForMatch(target.name);return new RegExp(`(?:Start\\s+\\d+:\\s*|Test\\s+#\\d+:\\s*)${exactName}(?=\\s|$)`,"m").test(output)}function normalizeHistoryTestFile(testFile,workingDir){let normalized=testFile.replace(/\\/g,"/");if(!path256.isAbsolute(testFile))return normalized;let relative61=path256.relative(workingDir,testFile);if(relative61.startsWith("..")||path256.isAbsolute(relative61))return normalized;return relative61.replace(/\\/g,"/")}function combineAggregateResult(current,next){if(current==="fail"||next==="fail")return"fail";if(current==="pass"||next==="pass")return"pass";return"skip"}function recordAndAnalyzeResults(result,testFiles,workingDir,sourceFiles,parsedTestCases){if(!result.totals||result.totals.total===0)return;let now2=new Date().toISOString(),changedFiles=(sourceFiles!==void 0?sourceFiles:testFiles).map((f)=>f.replace(/\\/g,"/")),aggregateResultsByFile=new Map,validParsedCases=parsedTestCases?.filter((parsedCase)=>parsedCase.testFile.length>0&&parsedCase.testName.length>0)??[],allRecords=[];for(let parsedCase of validParsedCases){let normalizedTestFile=normalizeHistoryTestFile(parsedCase.testFile,workingDir);allRecords.push({timestamp:now2,taskId:"auto",testFile:normalizedTestFile,testName:parsedCase.testName,result:parsedCase.result,durationMs:parsedCase.durationMs,errorMessage:parsedCase.errorMessage,stackPrefix:parsedCase.stackPrefix,changedFiles}),aggregateResultsByFile.set(normalizedTestFile,combineAggregateResult(aggregateResultsByFile.get(normalizedTestFile),parsedCase.result))}if(aggregateResultsByFile.size===0){let aggregateResult=result.success?"pass":"fail";for(let testFile of testFiles)aggregateResultsByFile.set(testFile.replace(/\\/g,"/"),aggregateResult)}for(let[testFile,aggregateResult]of aggregateResultsByFile)allRecords.push({timestamp:now2,taskId:"auto",testFile,testName:AGGREGATE_TEST_NAME,result:aggregateResult,durationMs:result.duration_ms||0,changedFiles});try{batchAppendTestRuns(allRecords,workingDir)}catch{}}function selectHistoryForAnalysis(history){let filesWithIndividualRecords=new Set;for(let record3 of history)if(record3.testName!==AGGREGATE_TEST_NAME)filesWithIndividualRecords.add(record3.testFile.toLowerCase());if(filesWithIndividualRecords.size===0)return history;return history.filter((record3)=>record3.testName!==AGGREGATE_TEST_NAME||!filesWithIndividualRecords.has(record3.testFile.toLowerCase()))}function analyzeFailures(workingDir){let report={flakyTests:[],failureClusters:[],quarantinedFailures:[]};try{let history=selectHistoryForAnalysis(getAllHistory(workingDir));if(history.length===0)return report;report.flakyTests=detectFlakyTests(history);let failingResults=history.filter((r)=>r.result==="fail");if(failingResults.length>0){let{clusters}=classifyAndCluster(failingResults,history);report.failureClusters=clusters.map((c)=>({rootCause:c.rootCause,affectedFiles:c.affectedTestFiles,classification:c.classification}))}for(let entry of report.flakyTests)if(entry.isQuarantined)report.quarantinedFailures.push(`${entry.testFile}: ${entry.testName}`)}catch{}return report}var MAX_OUTPUT_BYTES5=512000,MAX_COMMAND_LENGTH2=500,DEFAULT_TIMEOUT_MS3=60000,MAX_TIMEOUT_MS3=300000,MAX_SAFE_TEST_FILES2,MAX_SAFE_SOURCE_FILES=1,MAX_RAW_FILE_ENTRIES=512,MAX_FILE_PATH_LENGTH2=4096,MAX_GRAPH_FILE_BYTES=4194304,MAX_MAVEN_MODULE_PROBE_ENTRIES=100,DEFAULT_LOAD_IMPACT_MAP,AGGREGATE_TEST_NAME="(aggregate)",VITEST_JSON_OUTPUT_RELATIVE_PATH=".swarm/cache/test-runner-vitest.json",POWERSHELL_METACHARACTERS,SHELL_METACHARACTERS2,DISPATCH_FRAMEWORK_MAP,COMPOUND_TEST_EXTENSIONS,TEST_DIRECTORY_NAMES,SOURCE_EXTENSIONS,test_runner,_internals211;var init_test_runner=__esm(()=>{init_zod();init_command_resolution();init_discovery();init_java2();init_default_backend();init_analyzer();init_failure_classifier();init_history_store();init_bun_compat();init_path_security();init_windows_batch();init_create_tool();init_resolve_working_directory();MAX_SAFE_TEST_FILES2=MAX_SAFE_TEST_FILES,DEFAULT_LOAD_IMPACT_MAP=loadImpactMap;POWERSHELL_METACHARACTERS=/[|;&`$(){}[\]<>"'#*?\x00-\x1f]/;SHELL_METACHARACTERS2=/[;&`$(){}<>"'\x00-\x1f]/;DISPATCH_FRAMEWORK_MAP={bun:"bun",vitest:"vitest",jest:"jest",mocha:"mocha",pytest:"pytest",cargo:"cargo",pester:"pester","go-test":"go-test",maven:"maven",gradle:"gradle","dotnet-test":"dotnet-test",ctest:"ctest","swift-test":"swift-test","dart-test":"dart-test",rspec:"rspec",minitest:"minitest",pest:"pest",phpunit:"phpunit","php-artisan":"php-artisan","bun:test":"bun","xcodebuild-test":"swift-test","flutter test":"dart-test","dart test":"dart-test",Pest:"pest",PHPUnit:"phpunit"};COMPOUND_TEST_EXTENSIONS=[".test.ts",".test.tsx",".test.js",".test.jsx",".tests.ps1",".spec.ts",".spec.tsx",".spec.js",".spec.jsx",".test.ps1",".spec.ps1"],TEST_DIRECTORY_NAMES=["__tests__","tests","test","spec"];SOURCE_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".ps1",".psm1",".go",".java",".kt",".kts",".cs",".c",".h",".cpp",".hpp",".cc",".cxx",".php",".swift",".dart",".rb",".pyi"]);test_runner=createSwarmTool({description:'Run project tests with automatic framework detection for bun, vitest, jest, mocha, pytest, cargo, pester, go test, maven, gradle, dotnet test, ctest, swift test, dart test, rspec, minitest, pest, phpunit, or php-artisan. Returns JSON with success, framework, scope, command, timeout_ms, duration_ms, totals, outcome, and optional coveragePercent, rawOutput, testCases, and message fields. Scope "target" runs one exact Go test/subtest or CTest name via native_target using a workspace-relative package/build directory, with no broad fallback, coverage, or bail. The "targets" array passes framework-native test name patterns to cargo, go-test, maven, gradle, dotnet-test, ctest, and swift-test.',args:{scope:exports_external.enum(["all","convention","graph","impact","target"]).optional().describe('Test scope: "all" runs the full suite, "convention"/"graph"/"impact" resolve files, and "target" runs one exact Go or CTest native name without file fallback.'),native_target:exports_external.object({framework:exports_external.enum(["go-test","ctest"]),name:exports_external.string(),path:exports_external.string()}).optional().describe('For scope "target": exact framework-native test name plus a workspace-relative package/build directory. Absolute paths, traversal, coverage, bail, and broad fallback are rejected.'),files:exports_external.array(exports_external.string().min(1).max(MAX_FILE_PATH_LENGTH2)).max(MAX_RAW_FILE_ENTRIES).optional().describe('Specific files to test. For "convention", pass source files or direct test files. For "graph" and "impact", pass source files only.'),targets:exports_external.array(exports_external.string()).optional().describe("Framework-native test names or patterns to filter which tests run. Supported by cargo, go-test, maven, gradle, dotnet-test, ctest, and swift-test. Each entry is passed as-is to the framework's native filter flag. Targets only filter a files-driven selection — provide a non-empty files array for the convention, graph, and impact scopes; targets alone cannot drive discovery."),coverage:exports_external.boolean().optional().describe("Enable coverage reporting if supported"),bail:exports_external.boolean().optional().describe("Stop running tests after the first failure. Default false. Note: coverage may be incomplete when bail=true with coverage=true."),timeout_ms:exports_external.number().int().min(1).default(DEFAULT_TIMEOUT_MS3).describe("Timeout in milliseconds (default 60000, max 300000)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, tests run relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let workingDirInput;if(args2&&typeof args2==="object"){let obj=args2;workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={success:!1,framework:"none",scope:"all",error:dirResult.message,outcome:"error"};return JSON.stringify(errorResult,null,2)}let workingDir=dirResult.directory;if(workingDir.length>4096)return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(/^[/\\]{2}/.test(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsControlChars(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsPathTraversal(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(!validateArgs2(args2))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid arguments",message:'scope must be "all", "convention", "graph", "impact", or "target"; files and targets must be string arrays with safe values; target scope requires one valid native_target and cannot be combined with files, coverage, or bail',outcome:"error"},null,2);let scope=args2.scope||"all",nativeTarget,nativeExecutionDirectory=workingDir,nativeHistoryPath;if(scope==="target"){let resolvedTarget=resolveNativeTarget(args2.native_target,workingDir);if(!resolvedTarget.success)return JSON.stringify({success:!1,framework:args2.native_target.framework,scope,error:resolvedTarget.error,outcome:"error"},null,2);nativeTarget=resolvedTarget.target,nativeExecutionDirectory=resolvedTarget.executionDirectory,nativeHistoryPath=resolvedTarget.historyPath}if(scope==="all"){if(!process.env.SWARM_ALLOW_FULL_SUITE)return JSON.stringify({success:!1,framework:"none",scope:"all",error:'scope "all" is blocked for agent use. Use scope "convention" with specific test files, or scope "graph" with up to 50 normalized source files.',message:'The full test suite is blocked in agent context. Use scope "convention" with specific test files, or scope "graph" with up to 50 normalized source files. Example: { scope: "graph", files: ["src/tools/test-runner.ts"] }',outcome:"error"},null,2)}if((scope==="convention"||scope==="graph"||scope==="impact")&&(!args2.files||args2.files.length===0)){let errorResult={success:!1,framework:"none",scope,error:'scope "convention", "graph", and "impact" require a non-empty files array - targets only filter which tests run and cannot substitute for files (omitting files causes unsafe full-project discovery)',message:'When using scope "convention", "graph", or "impact", provide at least one source or direct-test file in "files"; "targets" only filter which tests run within that selection and cannot drive discovery on their own. Example: { scope: "convention", files: ["tests/test_calc.py"] }',outcome:"error",resolution:makeResolution(scope,scope,[],[],"skip",workingDir)};return JSON.stringify(errorResult,null,2)}let _files=args2.files||[],coverage=args2.coverage||!1,bail=args2.bail||!1,timeout_ms=Math.min(args2.timeout_ms||DEFAULT_TIMEOUT_MS3,MAX_TIMEOUT_MS3),useDispatch=process.env.SWARM_LANG_BACKEND!=="legacy",framework;if(nativeTarget)framework=nativeTarget.framework;else if(useDispatch){if(framework=await detectTestFrameworkViaDispatch(workingDir),framework==="none")framework=await detectTestFramework(workingDir,_files)}else framework=await detectTestFramework(workingDir,_files);if(framework==="none"){let result2={success:!1,framework:"none",scope,error:"No test framework detected",message:"No supported test framework found. Install bun, vitest, jest, mocha, pytest, cargo, pester, or a supported language test runner (go test, maven, gradle, dotnet test, ctest, swift test, dart test, rspec, minitest).",totals:{passed:0,failed:0,skipped:0,total:0},outcome:"error",...scope==="graph"||scope==="impact"?{resolution:makeResolution(scope,scope,[],[],"skip",workingDir)}:{}};return JSON.stringify(result2,null,2)}if(scope!=="target"&&framework==="maven"){let mavenModuleDir=resolveNestedMavenModuleDir(workingDir,_files);if(mavenModuleDir)nativeExecutionDirectory=mavenModuleDir}let testFiles=[],graphFallbackReason,effectiveScope=scope,selectionEstimate,selectionCacheStatus,selectionSourceFiles=[];if(scope==="target");else if(scope==="all");else if(scope==="convention"){let directTestFiles=_files.filter((file3)=>isConventionTestFilePath(file3)),sourceFiles=_files.filter((file3)=>{if(directTestFiles.includes(file3))return!1;let ext=path256.extname(file3).toLowerCase();return SOURCE_EXTENSIONS.has(ext)}),invalidFiles=_files.filter((file3)=>!directTestFiles.includes(file3)&&!sourceFiles.includes(file3));if(directTestFiles.length===0&&sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no recognized source files or direct test files",message:"The files array must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.) or a direct test file in a supported test location/naming convention.",outcome:"error"},null,2);if(invalidFiles.length>0){let errorResult={success:!1,framework,scope,error:"Provided files include entries that are neither recognized source files nor direct test files",message:`These files are not valid for targeted test discovery: ${invalidFiles.join(", ")}`,outcome:"error"};return JSON.stringify(errorResult,null,2)}if(selectionSourceFiles=normalizeSelectionFiles(_files,workingDir),sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "convention" accepts at most ${MAX_SAFE_SOURCE_FILES} source file for discovery (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "convention" discovery (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or pass direct test file paths instead of source files.`,outcome:"scope_exceeded",resolution:makeResolution(scope,scope,selectionSourceFiles,[],"scope_exceeded",workingDir)};return JSON.stringify(errorResult,null,2)}testFiles=[...directTestFiles,...getTestFilesFromConvention(sourceFiles,workingDir)].filter((file3,index,items)=>items.indexOf(file3)===index)}else if(scope==="graph"){let sourceFiles=normalizeSelectionFiles(_files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path256.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)}),workingDir);if(selectionSourceFiles=sourceFiles,sourceFiles.length===0){let errorResult={success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "graph" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error",resolution:makeResolution(scope,scope,[],[],"skip",workingDir)};return JSON.stringify(errorResult,null,2)}if(sourceFiles.length>MAX_SAFE_TEST_FILES2){let errorResult={success:!1,framework,scope,error:`scope "graph" accepts at most ${MAX_SAFE_TEST_FILES2} normalized source files (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "graph" (${sourceFiles.length} provided, limit is ${MAX_SAFE_TEST_FILES2}).`,outcome:"scope_exceeded",resolution:makeResolution(scope,scope,sourceFiles,[],"scope_exceeded",workingDir)};return JSON.stringify(errorResult,null,2)}selectionEstimate=await estimateFanOut(sourceFiles,workingDir),selectionCacheStatus=cacheStatusForAdvisory(getImpactCacheStatus(workingDir,{verify:!1}).status);let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir,MAX_SAFE_TEST_FILES2+1);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1)}else if(scope==="impact"){let sourceFiles=normalizeSelectionFiles(_files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path256.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)}),workingDir);if(selectionSourceFiles=sourceFiles,sourceFiles.length===0){let errorResult={success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "impact" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error",resolution:makeResolution(scope,scope,[],[],"skip",workingDir)};return JSON.stringify(errorResult,null,2)}if(sourceFiles.length>MAX_SAFE_TEST_FILES2){let errorResult={success:!1,framework,scope,error:`scope "impact" accepts at most ${MAX_SAFE_TEST_FILES2} normalized source files (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "impact" (${sourceFiles.length} provided, limit is ${MAX_SAFE_TEST_FILES2}).`,outcome:"scope_exceeded",resolution:makeResolution(scope,scope,sourceFiles,[],"scope_exceeded",workingDir)};return JSON.stringify(errorResult,null,2)}selectionEstimate=await estimateFanOut(sourceFiles,workingDir);try{let impactLoad=await loadImpactMapForImpactScope(workingDir);selectionCacheStatus=impactLoad.status;let impactResult=await _internals211.analyzeImpact(sourceFiles,workingDir,MAX_SAFE_TEST_FILES2+1,impactLoad.map);if(impactResult.budgetExceeded){let resolution=makeResolution(scope,scope,sourceFiles,impactResult.impactedTests,"scope_exceeded",workingDir,{estimate:selectionEstimate,cacheStatus:selectionCacheStatus}),errorResult={success:!1,framework,scope,error:"Budget exceeded during impact analysis",message:`Impact analysis exceeded safe budget of ${MAX_SAFE_TEST_FILES2} test files.`,outcome:"scope_exceeded",resolution,...resolutionFields(resolution)};return JSON.stringify(errorResult,null,2)}if(impactResult.impactedTests.length>0)testFiles=impactResult.impactedTests.map((testPath)=>{if(!path256.isAbsolute(testPath))return testPath;let relativePath2=path256.relative(workingDir,testPath);return path256.isAbsolute(relativePath2)?testPath:relativePath2});else{graphFallbackReason="no impacted tests found via impact analysis, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir,MAX_SAFE_TEST_FILES2+1);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1)}}catch{graphFallbackReason="impact analysis failed, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir,MAX_SAFE_TEST_FILES2+1);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1)}}if(scope==="convention"||scope==="graph"||scope==="impact")testFiles=normalizeSelectionFiles(testFiles,workingDir);if(scope!=="all"&&scope!=="target"&&testFiles.length===0&&!(args2.targets&&args2.targets.length>0)){let resolution=makeResolution(scope,effectiveScope,selectionSourceFiles,[],"skip",workingDir,{estimate:selectionEstimate,cacheStatus:selectionCacheStatus,fallbackReason:graphFallbackReason}),errorResult={success:!1,framework,scope:effectiveScope,error:"Provided source files resolved to zero test files",message:graphFallbackReason?`No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/). (${graphFallbackReason})`:"No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/).",outcome:scope==="impact"||scope==="graph"?"no_impacted_tests":"skip",...scope==="graph"&&{attempted_scope:"graph"},...scope==="impact"&&{attempted_scope:"graph"},resolution,...resolutionFields(resolution)};return JSON.stringify(errorResult,null,2)}if(scope!=="all"&&scope!=="target"&&testFiles.length>MAX_SAFE_TEST_FILES2){let sampleFiles=testFiles.slice(0,5),resolution=makeResolution(scope,effectiveScope,selectionSourceFiles,testFiles,"scope_exceeded",workingDir,{estimate:selectionEstimate,cacheStatus:selectionCacheStatus,fallbackReason:graphFallbackReason}),errorResult={success:!1,framework,scope:effectiveScope,error:`Resolved test file count (${testFiles.length}) exceeds safe maximum (${MAX_SAFE_TEST_FILES2})`,message:`Too many test files resolved (${testFiles.length}). Maximum allowed is ${MAX_SAFE_TEST_FILES2}. Treat this as SKIP without retry. Provide more specific source files to narrow down test scope. First few resolved: ${sampleFiles.join(", ")}`,outcome:"scope_exceeded",resolution,...resolutionFields(resolution)};return JSON.stringify(errorResult,null,2)}let result=await runTests(framework,effectiveScope,testFiles,coverage,timeout_ms,nativeExecutionDirectory,bail,args2.targets,nativeTarget);if(scope==="convention"||scope==="graph"||scope==="impact"){let resolution=makeResolution(scope,effectiveScope,selectionSourceFiles,testFiles,"execute",workingDir,{estimate:selectionEstimate,cacheStatus:selectionCacheStatus,fallbackReason:graphFallbackReason});result.resolution=resolution,Object.assign(result,resolutionFields(resolution))}let historyTestFiles=nativeTarget?[formatNativeHistoryTestFile(nativeTarget,nativeHistoryPath)]:testFiles;recordAndAnalyzeResults(result,historyTestFiles,workingDir,nativeTarget?[]:_files.length>0?_files:void 0,result.testCases);let historyReport;if(!result.success&&result.totals&&result.totals.failed>0){if(historyReport=analyzeFailures(workingDir),historyReport.quarantinedFailures.length>0)result.message=(result.message||"")+` | QUARANTINED (flaky): ${historyReport.quarantinedFailures.join(", ")}`;if(historyReport.failureClusters.length>0){let clusterSummary=historyReport.failureClusters.slice(0,3).map((c)=>`${c.classification}: ${c.rootCause.substring(0,80)}`).join("; ");result.message=`${result.message||""} | FAILURE ANALYSIS: ${clusterSummary}`}}if(graphFallbackReason&&result.message)result.message=`${result.message} (${graphFallbackReason})`;if(bail&&coverage&&result.message)result.message=`${result.message} (coverage may be incomplete: bail=true stopped early)`;return JSON.stringify(result,null,2)}}),_internals211={analyzeImpact,loadImpactMap,loadImpactMapWithStatus,getImpactCacheStatus,isCommandAvailable,existsSync:fs141.existsSync,readdirSync:fs141.readdirSync,readFileSync:fs141.readFileSync,realpathSync:fs141.realpathSync,resolveLocalNodeTool,bunSpawn,buildNativeTargetCommand,formatNativeHistoryTestFile,selectHistoryForAnalysis,AGGREGATE_TEST_NAME}});import*as fs142 from"node:fs";import*as path257 from"node:path";function formatSecretscanIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function validateDirectoryPath(dir){if(!dir||typeof dir!=="string")throw Error("Directory path is required");if(dir.includes(".."))throw Error("Directory path must not contain path traversal sequences");let normalized=path257.normalize(dir);return path257.isAbsolute(normalized)?normalized:path257.resolve(normalized)}function validateTimeout(timeoutMs,defaultValue){if(timeoutMs===void 0)return defaultValue;if(typeof timeoutMs!=="number"||!Number.isFinite(timeoutMs))throw Error("Timeout must be a finite number");if(timeoutMs<=0)throw Error("Timeout must be greater than 0");if(timeoutMs<MIN_CHECK_TIMEOUT_MS)throw Error(`Timeout must be at least ${MIN_CHECK_TIMEOUT_MS}ms (5 seconds)`);if(timeoutMs>MAX_CHECK_TIMEOUT_MS)throw Error(`Timeout must not exceed ${MAX_CHECK_TIMEOUT_MS}ms (5 minutes)`);return timeoutMs}function getPackageVersion(dir){try{let packagePath=path257.join(dir,"package.json");if(fs142.existsSync(packagePath)){let content=fs142.readFileSync(packagePath,"utf-8");return JSON.parse(content).version??null}}catch{}return null}function getChangelogVersion(dir){try{let changelogPath=path257.join(dir,"CHANGELOG.md");if(fs142.existsSync(changelogPath)){let match=fs142.readFileSync(changelogPath,"utf-8").match(/^##\s*\[?(\d+\.\d+\.\d+)\]?/m);if(match)return match[1]}}catch{}return null}function getVersionFileVersion(dir){let possibleFiles=["VERSION.txt","version.txt","VERSION","version"];for(let file3 of possibleFiles){let filePath=path257.join(dir,file3);if(fs142.existsSync(filePath))try{let match=fs142.readFileSync(filePath,"utf-8").trim().match(/(\d+\.\d+\.\d+)/);if(match)return match[1]}catch{}}return null}async function runVersionCheck2(dir,_timeoutMs){let startTime=Date.now();try{let packageVersion=_internals212.getPackageVersion(dir),changelogVersion=_internals212.getChangelogVersion(dir),versionFileVersion=_internals212.getVersionFileVersion(dir),versions3=[];if(packageVersion)versions3.push(`package.json: ${packageVersion}`);if(changelogVersion)versions3.push(`CHANGELOG.md: ${changelogVersion}`);if(versionFileVersion)versions3.push(`version file: ${versionFileVersion}`);if(new Set([packageVersion,changelogVersion,versionFileVersion].filter(Boolean)).size<=1){if(versions3.length===0)return{type:"version",status:"skip",message:"No version information found to check",details:{},durationMs:Date.now()-startTime};return{type:"version",status:"pass",message:`Version consistent: ${versions3.join(", ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}return{type:"version",status:"fail",message:`Version mismatch: ${versions3.join("; ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}catch(error93){return{type:"version",status:"error",message:`Version check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runLintCheck(dir,linter,timeoutMs){let startTime=Date.now();try{let lintPromise=runLint(linter,"check",dir),timeoutId,timeoutPromise=new Promise((_,reject2)=>{timeoutId=setTimeout(()=>{reject2(Error(`Lint check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([lintPromise,timeoutPromise]).finally(()=>clearTimeout(timeoutId));if(!result.success)return{type:"lint",status:"error",message:result.error??"Lint check failed",details:{linter,success:result.success},durationMs:Date.now()-startTime};if(result.exitCode!==0){let issueMatch=result.output.match(/(\d+)\s+(issues?|errors?)/i),issueCount=issueMatch?parseInt(issueMatch[1],10):void 0;return{type:"lint",status:"fail",message:issueCount?`Lint found ${issueCount} issue(s)`:"Lint found issues",details:{linter,exitCode:result.exitCode,issueCount,hasOutput:result.output.length>0},durationMs:Date.now()-startTime}}return{type:"lint",status:"pass",message:"Lint check passed",details:{linter,exitCode:result.exitCode},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))return{type:"lint",status:"error",message:error93.message,details:{linter},durationMs:Date.now()-startTime};return{type:"lint",status:"error",message:`Lint check failed: ${error93 instanceof Error?error93.message:String(error93)}`,details:{linter},durationMs:Date.now()-startTime}}}async function runTestsCheck(_dir,scope,timeoutMs){let startTime=Date.now();try{let detectedFramework=await detectTestFrameworkViaDispatch(_dir);if(detectedFramework!=="none")return{type:"tests",status:"pass",message:`Test framework detected: ${detectedFramework}`,details:{framework:detectedFramework,scope,detectedOnly:!0},durationMs:Date.now()-startTime};let result=await runTests("none",scope,[],!1,timeoutMs,_dir,!1);if(!result.success)return{type:"tests",status:"error",message:result.error??"Tests check failed",details:{framework:result.framework,scope,success:result.success},durationMs:Date.now()-startTime};if(result.totals.failed>0)return{type:"tests",status:"fail",message:`Tests failed: ${result.totals.failed}/${result.totals.total} failed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime};if(result.totals.total===0)return{type:"tests",status:"skip",message:"No tests found to run",details:{framework:result.framework,scope},durationMs:Date.now()-startTime};return{type:"tests",status:"pass",message:`Tests passed: ${result.totals.passed} passed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&(error93.message.includes("timeout")||error93.message.includes("ETIMEDOUT")))return{type:"tests",status:"error",message:`Tests check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"tests",status:"error",message:`Tests check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runSecretsCheck(dir,timeoutMs){let startTime=Date.now();try{let secretsPromise=_internals212.runSecretscan(dir),timeoutPromise=new Promise((_,reject2)=>{setTimeout(()=>{reject2(Error(`Secrets check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([secretsPromise,timeoutPromise]);if("error"in result)return{type:"secrets",status:"fail",message:`Secrets check failed: ${result.error}`,details:{error:result.error,filesScanned:result.files_scanned,incompleteFiles:0,incompletePaths:[]},durationMs:Date.now()-startTime};let findingsCount=Math.max(result.count,result.findings.length);if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{type:"secrets",status:"fail",message:"Secrets check failed: scanner returned incomplete coverage metadata",details:{filesScanned:result.files_scanned},durationMs:Date.now()-startTime};let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=result,hasCountMismatch=result.count!==result.findings.length,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasZeroCoverage=result.files_scanned===0,failures=[];if(findingsCount>0){let critical=result.findings.filter((f)=>f.severity==="critical").length,high=result.findings.filter((f)=>f.severity==="high").length;failures.push(`Found ${findingsCount} secret(s): ${critical} critical, ${high} high`)}if(hasIncompleteCoverage){let incompleteSummary=incompletePaths.length>0?`; incomplete paths: ${formatSecretscanIncompletePaths(incompletePaths)}`:"";failures.push(`${incompleteFiles} incomplete file(s)${incompleteSummary}`)}if(hasCountMismatch)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(hasZeroCoverage)failures.push("zero requested files scanned");if(failures.length>0)return{type:"secrets",status:"fail",message:`Secrets check failed: ${failures.join("; ")}`,details:{count:findingsCount,reportedCount:result.count,critical:result.findings.filter((f)=>f.severity==="critical").length,high:result.findings.filter((f)=>f.severity==="high").length,filesScanned:result.files_scanned,skippedFiles:result.skipped_files,incompleteFiles,incompletePaths},durationMs:Date.now()-startTime};return{type:"secrets",status:"pass",message:"No secrets detected",details:{filesScanned:result.files_scanned,skippedFiles:result.skipped_files,incompleteFiles,incompletePaths},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.name==="AbortError")return{type:"secrets",status:"error",message:`Secrets check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"secrets",status:"error",message:`Secrets check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runEvidenceCheck(dir){let startTime=Date.now();try{let plan=await loadPlan(dir);if(!plan)return{type:"evidence",status:"skip",message:"No plan found to check evidence against",details:{},durationMs:Date.now()-startTime};let completedTaskIds=[];for(let phase of plan.phases)for(let task2 of phase.tasks)if(task2.status==="completed")completedTaskIds.push(task2.id);if(completedTaskIds.length===0)return{type:"evidence",status:"skip",message:"No completed tasks yet",details:{completedTasks:0},durationMs:Date.now()-startTime};let evidenceTaskIds=new Set(await listEvidenceTaskIds(dir)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(dir,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}let completedWithEvidence=completedTaskIds.length-missingEvidence.length;if(missingEvidence.length>0)return{type:"evidence",status:"fail",message:`${missingEvidence.length} completed task(s) missing evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence,missingTasks:missingEvidence.slice(0,10),missingCount:missingEvidence.length},durationMs:Date.now()-startTime};return{type:"evidence",status:"pass",message:`All ${completedTaskIds.length} completed tasks have evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence},durationMs:Date.now()-startTime}}catch(error93){return{type:"evidence",status:"error",message:`Evidence check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runRequirementCoverageCheck(dir,currentPhase){let startTime=Date.now();try{if(readEffectiveSpecSync(dir)===null)return{type:"req_coverage",status:"skip",message:"No effective spec found, requirement coverage not required",details:{},durationMs:Date.now()-startTime};let coverage=await checkRequirementCoverage(currentPhase,dir);if(!coverage.exists)return{type:"req_coverage",status:"fail",message:"Requirement coverage report missing but effective spec exists",details:{expectedPath:coverage.path},durationMs:Date.now()-startTime};let raw;try{let stat23=await fs142.promises.stat(coverage.path);if(stat23.size>REQ_COVERAGE_MAX_JSON_BYTES)return{type:"req_coverage",status:"fail",message:`Requirement coverage report exceeds ${REQ_COVERAGE_MAX_JSON_BYTES} byte cap and cannot be validated`,details:{path:coverage.path,sizeBytes:stat23.size},durationMs:Date.now()-startTime};raw=await fs142.promises.readFile(coverage.path,"utf-8")}catch(readError){return{type:"req_coverage",status:"fail",message:`Requirement coverage report unreadable: ${readError instanceof Error?readError.message:String(readError)}`,details:{path:coverage.path},durationMs:Date.now()-startTime}}let trimmed=raw.trim();if(trimmed.length===0)return{type:"req_coverage",status:"fail",message:"Requirement coverage report is empty",details:{path:coverage.path},durationMs:Date.now()-startTime};let parsed;try{parsed=JSON.parse(trimmed)}catch(parseError){return{type:"req_coverage",status:"fail",message:`Requirement coverage report is not valid JSON: ${parseError instanceof Error?parseError.message:String(parseError)}`,details:{path:coverage.path},durationMs:Date.now()-startTime}}let report=ReqCoverageReportSchema.safeParse(parsed);if(!report.success)return{type:"req_coverage",status:"fail",message:"Requirement coverage report does not match the expected report shape",details:{path:coverage.path},durationMs:Date.now()-startTime};let{success:success3,phase,totalRequirements,coveredCount,missingCount,requirements}=report.data;if(!success3)return{type:"req_coverage",status:"fail",message:"Requirement coverage report indicates the coverage run itself failed (success: false)",details:{path:coverage.path},durationMs:Date.now()-startTime};if(phase!==currentPhase)return{type:"req_coverage",status:"fail",message:`Requirement coverage report phase (${phase}) does not match the current phase (${currentPhase})`,details:{path:coverage.path,reportPhase:phase,currentPhase},durationMs:Date.now()-startTime};if(totalRequirements===0)return{type:"req_coverage",status:"fail",message:"Requirement coverage report contains no requirements (totalRequirements is 0) but effective spec exists",details:{path:coverage.path,totalRequirements},durationMs:Date.now()-startTime};if(coveredCount+missingCount!==totalRequirements)return{type:"req_coverage",status:"fail",message:`Requirement coverage report counts are inconsistent: coveredCount (${coveredCount}) + missingCount (${missingCount}) !== totalRequirements (${totalRequirements})`,details:{path:coverage.path,totalRequirements,coveredCount,missingCount},durationMs:Date.now()-startTime};if(requirements.length!==totalRequirements)return{type:"req_coverage",status:"fail",message:`Requirement coverage report requirements array length (${requirements.length}) does not match totalRequirements (${totalRequirements})`,details:{path:coverage.path,totalRequirements,requirementsLength:requirements.length},durationMs:Date.now()-startTime};if(missingCount>0)return{type:"req_coverage",status:"fail",message:`Requirement coverage report has ${missingCount} uncovered requirement(s)`,details:{path:coverage.path,totalRequirements,coveredCount,missingCount},durationMs:Date.now()-startTime};return{type:"req_coverage",status:"pass",message:`Requirement coverage report found: ${coveredCount}/${totalRequirements} requirement(s) covered`,details:{path:coverage.path,totalRequirements,coveredCount,missingCount},durationMs:Date.now()-startTime}}catch(error93){return{type:"req_coverage",status:"error",message:`Requirement coverage check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runPreflight(dir,phase,config3){let startTime=Date.now(),reportId=`preflight-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,validatedDir;try{validatedDir=_internals212.validateDirectoryPath(dir)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid directory: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid directory"}}let validatedTimeout;try{validatedTimeout=_internals212.validateTimeout(config3?.checkTimeoutMs,DEFAULT_CONFIG.checkTimeoutMs)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid config: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid configuration"}}let cfg={checkTimeoutMs:validatedTimeout,skipTests:config3?.skipTests??DEFAULT_CONFIG.skipTests,skipSecrets:config3?.skipSecrets??DEFAULT_CONFIG.skipSecrets,skipEvidence:config3?.skipEvidence??DEFAULT_CONFIG.skipEvidence,skipVersion:config3?.skipVersion??DEFAULT_CONFIG.skipVersion,testScope:config3?.testScope??DEFAULT_CONFIG.testScope,linter:config3?.linter??DEFAULT_CONFIG.linter};log("[Preflight] Starting preflight checks",{reportId,phase,config:{skipTests:cfg.skipTests,skipSecrets:cfg.skipSecrets,skipEvidence:cfg.skipEvidence,skipVersion:cfg.skipVersion,testScope:cfg.testScope,linter:cfg.linter}});let checks5=[];log("[Preflight] Running lint check...");let lintResult=await _internals212.runLintCheck(validatedDir,cfg.linter,cfg.checkTimeoutMs);if(checks5.push(lintResult),log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`),!cfg.skipTests){log("[Preflight] Running tests check...");let testsResult=await _internals212.runTestsCheck(validatedDir,cfg.testScope,cfg.checkTimeoutMs);checks5.push(testsResult),log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`)}else checks5.push({type:"tests",status:"skip",message:"Tests check skipped by configuration"});if(!cfg.skipSecrets){log("[Preflight] Running secrets check...");let secretsResult=await _internals212.runSecretsCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(secretsResult),log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`)}else checks5.push({type:"secrets",status:"skip",message:"Secrets check skipped by configuration"});if(!cfg.skipEvidence){log("[Preflight] Running evidence check...");let evidenceResult=await _internals212.runEvidenceCheck(validatedDir);checks5.push(evidenceResult),log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`)}else checks5.push({type:"evidence",status:"skip",message:"Evidence check skipped by configuration"});log("[Preflight] Running requirement coverage check...");let reqCoverageResult=await _internals212.runRequirementCoverageCheck(validatedDir,phase);if(checks5.push(reqCoverageResult),log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`),!cfg.skipVersion){log("[Preflight] Running version check...");let versionResult=await _internals212.runVersionCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(versionResult),log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`)}else checks5.push({type:"version",status:"skip",message:"Version check skipped by configuration"});let totalDurationMs=Date.now()-startTime,failedChecks=checks5.filter((c)=>c.status==="fail").length,errorChecks=checks5.filter((c)=>c.status==="error").length,skippedChecks=checks5.filter((c)=>c.status==="skip").length,overall,message;if(errorChecks>0)overall="fail",message=`Preflight failed with ${errorChecks} error(s)`;else if(failedChecks>0)overall="fail",message=`Preflight failed: ${failedChecks} check(s) failed`;else if(skippedChecks===checks5.length)overall="skipped",message="All checks were skipped";else overall="pass",message="Preflight passed all checks";let testsDetectedOnlyForMessage=checks5.find((c)=>c.type==="tests")?.details?.detectedOnly===!0;if(overall==="pass"&&testsDetectedOnlyForMessage)message="Preflight passed all checks except tests (detected only — not executed)";return log(`[Preflight] Complete: ${overall} ${message}`),{id:reportId,timestamp:startTime,phase,overall,checks:checks5,totalDurationMs,message}}function formatPreflightMarkdown(report){let testsDetectedOnlyOverall=report.checks.some((c)=>c.type==="tests"&&c.details?.detectedOnly===!0),lines=["## Preflight Report","",`**Phase**: ${report.phase}`,`**Overall**: ${report.overall==="fail"?"❌ FAIL":report.overall==="skipped"?"⏭️ SKIPPED":testsDetectedOnlyOverall?"⏭️ PARTIAL (tests detected only)":"✅ PASS"}`,`**Duration**: ${(report.totalDurationMs/1000).toFixed(2)}s`,"","### Checks",""];for(let check3 of report.checks){let detectedOnly=check3.type==="tests"&&check3.details?.detectedOnly===!0,icon=detectedOnly?"⏭️":check3.status==="pass"?"✅":check3.status==="fail"?"❌":check3.status==="error"?"⚠️":"⏭️",message=detectedOnly?"detected only — tests not executed":check3.message;lines.push(`- ${icon} **${check3.type}**: ${message}`)}return lines.push(""),lines.push(report.message),lines.join(`
|
|
4076
|
+
... (output truncated at stream read limit)`;let parsed=process.env.SWARM_LANG_BACKEND!=="legacy"?await parseTestOutputViaDispatch(framework,output,executionCwd)??parseTestOutput2(framework,output):parseTestOutput2(framework,output),parsedTestCases=parseFrameworkJsonTestResults(framework,output),totals={...parsed.totals},{coveragePercent}=parsed;if(totals.total===0&&parsedTestCases.length>0){for(let entry of parsedTestCases)if(entry.result==="pass")totals.passed++;else if(entry.result==="fail")totals.failed++;else totals.skipped++;totals.total=parsedTestCases.length}let isTimeout=timedOutByDeadline,spawnFailure=proc.spawnError,nativeTargetObserved=resolvedNativeTarget?didExecuteNativeTarget(resolvedNativeTarget,output):!0;if(exitCode===0&&!isTimeout&&!spawnFailure&&totals.failed===0&&nativeTargetObserved){let result={success:!0,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,outcome:"pass",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;return result.message=formatPassingMessage(framework,totals,coveragePercent),result}else{let result={success:!1,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,error:spawnFailure?`Test command failed to launch: ${spawnFailure.message}`:isTimeout?`Tests timed out after ${timeout_ms}ms`:!nativeTargetObserved?`Native target "${resolvedNativeTarget?.name}" did not execute`:`Tests failed with ${totals.failed} failures`,message:spawnFailure?`${framework} test process could not be started: ${spawnFailure.message} — a launch failure (for example a missing executable or unusable working directory), not a test regression. Check the command, PATH, and cwd instead of the tests.`:isTimeout?`${framework} tests timed out after ${timeout_ms}ms`:!nativeTargetObserved?`${framework} did not report the exact requested native target; refusing a false-green 0/0 result`:`${framework} tests failed (${totals.failed}/${totals.total} failed)`,outcome:spawnFailure||isTimeout?"error":"regression",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;return result}}catch(error93){let duration_ms=Date.now()-startTime;return{success:!1,framework,scope,command,timeout_ms,duration_ms,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error",outcome:"error"}}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(proc?.exitCode===null&&!timedOutByDeadline)try{if(proc.killTree)await proc.killTree("SIGKILL");else proc.kill("SIGKILL")}catch{}}}function escapeRegexForMatch(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function didExecuteNativeTarget(target,output){if(target.framework==="go-test")return[...output.matchAll(/^\s*--- (?:PASS|FAIL|SKIP):\s+(.+?)(?:\s+\(|$)/gm)].some((match)=>match[1]===target.name);let exactName=escapeRegexForMatch(target.name);return new RegExp(`(?:Start\\s+\\d+:\\s*|Test\\s+#\\d+:\\s*)${exactName}(?=\\s|$)`,"m").test(output)}function normalizeHistoryTestFile(testFile,workingDir){let normalized=testFile.replace(/\\/g,"/");if(!path256.isAbsolute(testFile))return normalized;let relative61=path256.relative(workingDir,testFile);if(relative61.startsWith("..")||path256.isAbsolute(relative61))return normalized;return relative61.replace(/\\/g,"/")}function combineAggregateResult(current,next){if(current==="fail"||next==="fail")return"fail";if(current==="pass"||next==="pass")return"pass";return"skip"}function recordAndAnalyzeResults(result,testFiles,workingDir,sourceFiles,parsedTestCases){if(!result.totals||result.totals.total===0)return;let now2=new Date().toISOString(),changedFiles=(sourceFiles!==void 0?sourceFiles:testFiles).map((f)=>f.replace(/\\/g,"/")),aggregateResultsByFile=new Map,validParsedCases=parsedTestCases?.filter((parsedCase)=>parsedCase.testFile.length>0&&parsedCase.testName.length>0)??[],allRecords=[];for(let parsedCase of validParsedCases){let normalizedTestFile=normalizeHistoryTestFile(parsedCase.testFile,workingDir);allRecords.push({timestamp:now2,taskId:"auto",testFile:normalizedTestFile,testName:parsedCase.testName,result:parsedCase.result,durationMs:parsedCase.durationMs,errorMessage:parsedCase.errorMessage,stackPrefix:parsedCase.stackPrefix,changedFiles}),aggregateResultsByFile.set(normalizedTestFile,combineAggregateResult(aggregateResultsByFile.get(normalizedTestFile),parsedCase.result))}if(aggregateResultsByFile.size===0){let aggregateResult=result.success?"pass":"fail";for(let testFile of testFiles)aggregateResultsByFile.set(testFile.replace(/\\/g,"/"),aggregateResult)}for(let[testFile,aggregateResult]of aggregateResultsByFile)allRecords.push({timestamp:now2,taskId:"auto",testFile,testName:AGGREGATE_TEST_NAME,result:aggregateResult,durationMs:result.duration_ms||0,changedFiles});try{batchAppendTestRuns(allRecords,workingDir)}catch{}}function selectHistoryForAnalysis(history){let filesWithIndividualRecords=new Set;for(let record3 of history)if(record3.testName!==AGGREGATE_TEST_NAME)filesWithIndividualRecords.add(record3.testFile.toLowerCase());if(filesWithIndividualRecords.size===0)return history;return history.filter((record3)=>record3.testName!==AGGREGATE_TEST_NAME||!filesWithIndividualRecords.has(record3.testFile.toLowerCase()))}function analyzeFailures(workingDir){let report={flakyTests:[],failureClusters:[],quarantinedFailures:[]};try{let history=selectHistoryForAnalysis(getAllHistory(workingDir));if(history.length===0)return report;report.flakyTests=detectFlakyTests(history);let failingResults=history.filter((r)=>r.result==="fail");if(failingResults.length>0){let{clusters}=classifyAndCluster(failingResults,history);report.failureClusters=clusters.map((c)=>({rootCause:c.rootCause,affectedFiles:c.affectedTestFiles,classification:c.classification}))}for(let entry of report.flakyTests)if(entry.isQuarantined)report.quarantinedFailures.push(`${entry.testFile}: ${entry.testName}`)}catch{}return report}var MAX_OUTPUT_BYTES5=512000,MAX_COMMAND_LENGTH2=500,DEFAULT_TIMEOUT_MS3=60000,MAX_TIMEOUT_MS3=300000,MAX_SAFE_TEST_FILES2,MAX_SAFE_SOURCE_FILES=1,MAX_RAW_FILE_ENTRIES=512,MAX_FILE_PATH_LENGTH2=4096,MAX_GRAPH_FILE_BYTES=4194304,MAX_MAVEN_MODULE_PROBE_ENTRIES=100,DEFAULT_LOAD_IMPACT_MAP,AGGREGATE_TEST_NAME="(aggregate)",VITEST_JSON_OUTPUT_RELATIVE_PATH=".swarm/cache/test-runner-vitest.json",POWERSHELL_METACHARACTERS,SHELL_METACHARACTERS2,DISPATCH_FRAMEWORK_MAP,MAVEN_BUILD_FILES,GRADLE_BUILD_FILES,COMPOUND_TEST_EXTENSIONS,TEST_DIRECTORY_NAMES,CLASS_BASED_TEST_EXTENSIONS,SOURCE_EXTENSIONS,test_runner,_internals211;var init_test_runner=__esm(()=>{init_zod();init_command_resolution();init_discovery();init_java2();init_default_backend();init_analyzer();init_failure_classifier();init_history_store();init_bun_compat();init_path_security();init_windows_batch();init_create_tool();init_resolve_working_directory();MAX_SAFE_TEST_FILES2=MAX_SAFE_TEST_FILES,DEFAULT_LOAD_IMPACT_MAP=loadImpactMap;POWERSHELL_METACHARACTERS=/[|;&`$(){}[\]<>"'#*?\x00-\x1f]/;SHELL_METACHARACTERS2=/[;&`$(){}<>"'\x00-\x1f]/;DISPATCH_FRAMEWORK_MAP={bun:"bun",vitest:"vitest",jest:"jest",mocha:"mocha",pytest:"pytest",cargo:"cargo",pester:"pester","go-test":"go-test",maven:"maven",gradle:"gradle","dotnet-test":"dotnet-test",ctest:"ctest","swift-test":"swift-test","dart-test":"dart-test",rspec:"rspec",minitest:"minitest",pest:"pest",phpunit:"phpunit","php-artisan":"php-artisan","bun:test":"bun","xcodebuild-test":"swift-test","flutter test":"dart-test","dart test":"dart-test",Pest:"pest",PHPUnit:"phpunit"};MAVEN_BUILD_FILES=["pom.xml"],GRADLE_BUILD_FILES=["build.gradle","build.gradle.kts"];COMPOUND_TEST_EXTENSIONS=[".test.ts",".test.tsx",".test.js",".test.jsx",".tests.ps1",".spec.ts",".spec.tsx",".spec.js",".spec.jsx",".test.ps1",".spec.ps1"],TEST_DIRECTORY_NAMES=["__tests__","tests","test","spec"];CLASS_BASED_TEST_EXTENSIONS=new Set([".java",".kt",".groovy"]);SOURCE_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".ps1",".psm1",".go",".java",".kt",".kts",".cs",".c",".h",".cpp",".hpp",".cc",".cxx",".php",".swift",".dart",".rb",".pyi"]);test_runner=createSwarmTool({description:'Run project tests with automatic framework detection for bun, vitest, jest, mocha, pytest, cargo, pester, go test, maven, gradle, dotnet test, ctest, swift test, dart test, rspec, minitest, pest, phpunit, or php-artisan. Returns JSON with success, framework, scope, command, timeout_ms, duration_ms, totals, outcome, and optional coveragePercent, rawOutput, testCases, and message fields. Scope "target" runs one exact Go test/subtest or CTest name via native_target using a workspace-relative package/build directory, with no broad fallback, coverage, or bail. The "targets" array passes framework-native test name patterns to cargo, go-test, maven, gradle, dotnet-test, ctest, and swift-test.',args:{scope:exports_external.enum(["all","convention","graph","impact","target"]).optional().describe('Test scope: "all" runs the full suite, "convention"/"graph"/"impact" resolve files, and "target" runs one exact Go or CTest native name without file fallback.'),native_target:exports_external.object({framework:exports_external.enum(["go-test","ctest"]),name:exports_external.string(),path:exports_external.string()}).optional().describe('For scope "target": exact framework-native test name plus a workspace-relative package/build directory. Absolute paths, traversal, coverage, bail, and broad fallback are rejected.'),files:exports_external.array(exports_external.string().min(1).max(MAX_FILE_PATH_LENGTH2)).max(MAX_RAW_FILE_ENTRIES).optional().describe('Specific files to test. For "convention", pass source files or direct test files. For "graph" and "impact", pass source files only.'),targets:exports_external.array(exports_external.string()).optional().describe("Framework-native test names or patterns to filter which tests run. Supported by cargo, go-test, maven, gradle, dotnet-test, ctest, and swift-test. Each entry is passed as-is to the framework's native filter flag. Targets only filter a files-driven selection — provide a non-empty files array for the convention, graph, and impact scopes; targets alone cannot drive discovery."),coverage:exports_external.boolean().optional().describe("Enable coverage reporting if supported"),bail:exports_external.boolean().optional().describe("Stop running tests after the first failure. Default false. Note: coverage may be incomplete when bail=true with coverage=true."),timeout_ms:exports_external.number().int().min(1).default(DEFAULT_TIMEOUT_MS3).describe("Timeout in milliseconds (default 60000, max 300000)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, tests run relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let workingDirInput;if(args2&&typeof args2==="object"){let obj=args2;workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={success:!1,framework:"none",scope:"all",error:dirResult.message,outcome:"error"};return JSON.stringify(errorResult,null,2)}let workingDir=dirResult.directory;if(workingDir.length>4096)return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(/^[/\\]{2}/.test(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsControlChars(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsPathTraversal(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(!validateArgs2(args2))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid arguments",message:'scope must be "all", "convention", "graph", "impact", or "target"; files and targets must be string arrays with safe values; target scope requires one valid native_target and cannot be combined with files, coverage, or bail',outcome:"error"},null,2);let scope=args2.scope||"all",nativeTarget,nativeExecutionDirectory=workingDir,nativeHistoryPath;if(scope==="target"){let resolvedTarget=resolveNativeTarget(args2.native_target,workingDir);if(!resolvedTarget.success)return JSON.stringify({success:!1,framework:args2.native_target.framework,scope,error:resolvedTarget.error,outcome:"error"},null,2);nativeTarget=resolvedTarget.target,nativeExecutionDirectory=resolvedTarget.executionDirectory,nativeHistoryPath=resolvedTarget.historyPath}if(scope==="all"){if(!process.env.SWARM_ALLOW_FULL_SUITE)return JSON.stringify({success:!1,framework:"none",scope:"all",error:'scope "all" is blocked for agent use. Use scope "convention" with specific test files, or scope "graph" with up to 50 normalized source files.',message:'The full test suite is blocked in agent context. Use scope "convention" with specific test files, or scope "graph" with up to 50 normalized source files. Example: { scope: "graph", files: ["src/tools/test-runner.ts"] }',outcome:"error"},null,2)}if((scope==="convention"||scope==="graph"||scope==="impact")&&(!args2.files||args2.files.length===0)){let errorResult={success:!1,framework:"none",scope,error:'scope "convention", "graph", and "impact" require a non-empty files array - targets only filter which tests run and cannot substitute for files (omitting files causes unsafe full-project discovery)',message:'When using scope "convention", "graph", or "impact", provide at least one source or direct-test file in "files"; "targets" only filter which tests run within that selection and cannot drive discovery on their own. Example: { scope: "convention", files: ["tests/test_calc.py"] }',outcome:"error",resolution:makeResolution(scope,scope,[],[],"skip",workingDir)};return JSON.stringify(errorResult,null,2)}let _files=args2.files||[],coverage=args2.coverage||!1,bail=args2.bail||!1,timeout_ms=Math.min(args2.timeout_ms||DEFAULT_TIMEOUT_MS3,MAX_TIMEOUT_MS3),useDispatch=process.env.SWARM_LANG_BACKEND!=="legacy",framework;if(nativeTarget)framework=nativeTarget.framework;else if(useDispatch){if(framework=await detectTestFrameworkViaDispatch(workingDir),framework==="none")framework=await detectTestFramework(workingDir,_files)}else framework=await detectTestFramework(workingDir,_files);if(framework==="none"){let result2={success:!1,framework:"none",scope,error:"No test framework detected",message:"No supported test framework found. Install bun, vitest, jest, mocha, pytest, cargo, pester, or a supported language test runner (go test, maven, gradle, dotnet test, ctest, swift test, dart test, rspec, minitest).",totals:{passed:0,failed:0,skipped:0,total:0},outcome:"error",...scope==="graph"||scope==="impact"?{resolution:makeResolution(scope,scope,[],[],"skip",workingDir)}:{}};return JSON.stringify(result2,null,2)}if(scope!=="target"&&framework==="maven"){let mavenModuleDir=resolveNestedMavenModuleDir(workingDir,_files);if(mavenModuleDir)nativeExecutionDirectory=mavenModuleDir}else if(scope!=="target"&&framework==="gradle"){let gradleModuleDir=resolveNestedGradleModuleDir(workingDir,_files);if(gradleModuleDir)nativeExecutionDirectory=gradleModuleDir}let testFiles=[],graphFallbackReason,effectiveScope=scope,selectionEstimate,selectionCacheStatus,selectionSourceFiles=[];if(scope==="target");else if(scope==="all");else if(scope==="convention"){let directTestFiles=_files.filter((file3)=>isConventionTestFilePath(file3)),sourceFiles=_files.filter((file3)=>{if(directTestFiles.includes(file3))return!1;let ext=path256.extname(file3).toLowerCase();return SOURCE_EXTENSIONS.has(ext)}),invalidFiles=_files.filter((file3)=>!directTestFiles.includes(file3)&&!sourceFiles.includes(file3));if(directTestFiles.length===0&&sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no recognized source files or direct test files",message:"The files array must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.) or a direct test file in a supported test location/naming convention.",outcome:"error"},null,2);if(invalidFiles.length>0){let errorResult={success:!1,framework,scope,error:"Provided files include entries that are neither recognized source files nor direct test files",message:`These files are not valid for targeted test discovery: ${invalidFiles.join(", ")}`,outcome:"error"};return JSON.stringify(errorResult,null,2)}if(selectionSourceFiles=normalizeSelectionFiles(_files,workingDir),sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "convention" accepts at most ${MAX_SAFE_SOURCE_FILES} source file for discovery (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "convention" discovery (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or pass direct test file paths instead of source files.`,outcome:"scope_exceeded",resolution:makeResolution(scope,scope,selectionSourceFiles,[],"scope_exceeded",workingDir)};return JSON.stringify(errorResult,null,2)}testFiles=[...directTestFiles,...getTestFilesFromConvention(sourceFiles,workingDir)].filter((file3,index,items)=>items.indexOf(file3)===index)}else if(scope==="graph"){let sourceFiles=normalizeSelectionFiles(_files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path256.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)}),workingDir);if(selectionSourceFiles=sourceFiles,sourceFiles.length===0){let errorResult={success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "graph" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error",resolution:makeResolution(scope,scope,[],[],"skip",workingDir)};return JSON.stringify(errorResult,null,2)}if(sourceFiles.length>MAX_SAFE_TEST_FILES2){let errorResult={success:!1,framework,scope,error:`scope "graph" accepts at most ${MAX_SAFE_TEST_FILES2} normalized source files (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "graph" (${sourceFiles.length} provided, limit is ${MAX_SAFE_TEST_FILES2}).`,outcome:"scope_exceeded",resolution:makeResolution(scope,scope,sourceFiles,[],"scope_exceeded",workingDir)};return JSON.stringify(errorResult,null,2)}selectionEstimate=await estimateFanOut(sourceFiles,workingDir),selectionCacheStatus=cacheStatusForAdvisory(getImpactCacheStatus(workingDir,{verify:!1}).status);let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir,MAX_SAFE_TEST_FILES2+1);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1)}else if(scope==="impact"){let sourceFiles=normalizeSelectionFiles(_files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path256.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)}),workingDir);if(selectionSourceFiles=sourceFiles,sourceFiles.length===0){let errorResult={success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "impact" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error",resolution:makeResolution(scope,scope,[],[],"skip",workingDir)};return JSON.stringify(errorResult,null,2)}if(sourceFiles.length>MAX_SAFE_TEST_FILES2){let errorResult={success:!1,framework,scope,error:`scope "impact" accepts at most ${MAX_SAFE_TEST_FILES2} normalized source files (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "impact" (${sourceFiles.length} provided, limit is ${MAX_SAFE_TEST_FILES2}).`,outcome:"scope_exceeded",resolution:makeResolution(scope,scope,sourceFiles,[],"scope_exceeded",workingDir)};return JSON.stringify(errorResult,null,2)}selectionEstimate=await estimateFanOut(sourceFiles,workingDir);try{let impactLoad=await loadImpactMapForImpactScope(workingDir);selectionCacheStatus=impactLoad.status;let impactResult=await _internals211.analyzeImpact(sourceFiles,workingDir,MAX_SAFE_TEST_FILES2+1,impactLoad.map);if(impactResult.budgetExceeded){let resolution=makeResolution(scope,scope,sourceFiles,impactResult.impactedTests,"scope_exceeded",workingDir,{estimate:selectionEstimate,cacheStatus:selectionCacheStatus}),errorResult={success:!1,framework,scope,error:"Budget exceeded during impact analysis",message:`Impact analysis exceeded safe budget of ${MAX_SAFE_TEST_FILES2} test files.`,outcome:"scope_exceeded",resolution,...resolutionFields(resolution)};return JSON.stringify(errorResult,null,2)}if(impactResult.impactedTests.length>0)testFiles=impactResult.impactedTests.map((testPath)=>{if(!path256.isAbsolute(testPath))return testPath;let relativePath2=path256.relative(workingDir,testPath);return path256.isAbsolute(relativePath2)?testPath:relativePath2});else{graphFallbackReason="no impacted tests found via impact analysis, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir,MAX_SAFE_TEST_FILES2+1);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1)}}catch{graphFallbackReason="impact analysis failed, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir,MAX_SAFE_TEST_FILES2+1);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir).slice(0,MAX_SAFE_TEST_FILES2+1)}}if(scope==="convention"||scope==="graph"||scope==="impact")testFiles=normalizeSelectionFiles(testFiles,workingDir);if(scope!=="all"&&scope!=="target"&&testFiles.length===0&&!(args2.targets&&args2.targets.length>0)){let resolution=makeResolution(scope,effectiveScope,selectionSourceFiles,[],"skip",workingDir,{estimate:selectionEstimate,cacheStatus:selectionCacheStatus,fallbackReason:graphFallbackReason}),errorResult={success:!1,framework,scope:effectiveScope,error:"Provided source files resolved to zero test files",message:graphFallbackReason?`No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/). (${graphFallbackReason})`:"No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/).",outcome:scope==="impact"||scope==="graph"?"no_impacted_tests":"skip",...scope==="graph"&&{attempted_scope:"graph"},...scope==="impact"&&{attempted_scope:"graph"},resolution,...resolutionFields(resolution)};return JSON.stringify(errorResult,null,2)}if(scope!=="all"&&scope!=="target"&&testFiles.length>MAX_SAFE_TEST_FILES2){let sampleFiles=testFiles.slice(0,5),resolution=makeResolution(scope,effectiveScope,selectionSourceFiles,testFiles,"scope_exceeded",workingDir,{estimate:selectionEstimate,cacheStatus:selectionCacheStatus,fallbackReason:graphFallbackReason}),errorResult={success:!1,framework,scope:effectiveScope,error:`Resolved test file count (${testFiles.length}) exceeds safe maximum (${MAX_SAFE_TEST_FILES2})`,message:`Too many test files resolved (${testFiles.length}). Maximum allowed is ${MAX_SAFE_TEST_FILES2}. Treat this as SKIP without retry. Provide more specific source files to narrow down test scope. First few resolved: ${sampleFiles.join(", ")}`,outcome:"scope_exceeded",resolution,...resolutionFields(resolution)};return JSON.stringify(errorResult,null,2)}let result=await runTests(framework,effectiveScope,testFiles,coverage,timeout_ms,nativeExecutionDirectory,bail,args2.targets,nativeTarget);if(scope==="convention"||scope==="graph"||scope==="impact"){let resolution=makeResolution(scope,effectiveScope,selectionSourceFiles,testFiles,"execute",workingDir,{estimate:selectionEstimate,cacheStatus:selectionCacheStatus,fallbackReason:graphFallbackReason});result.resolution=resolution,Object.assign(result,resolutionFields(resolution))}let historyTestFiles=nativeTarget?[formatNativeHistoryTestFile(nativeTarget,nativeHistoryPath)]:testFiles;recordAndAnalyzeResults(result,historyTestFiles,workingDir,nativeTarget?[]:_files.length>0?_files:void 0,result.testCases);let historyReport;if(!result.success&&result.totals&&result.totals.failed>0){if(historyReport=analyzeFailures(workingDir),historyReport.quarantinedFailures.length>0)result.message=(result.message||"")+` | QUARANTINED (flaky): ${historyReport.quarantinedFailures.join(", ")}`;if(historyReport.failureClusters.length>0){let clusterSummary=historyReport.failureClusters.slice(0,3).map((c)=>`${c.classification}: ${c.rootCause.substring(0,80)}`).join("; ");result.message=`${result.message||""} | FAILURE ANALYSIS: ${clusterSummary}`}}if(graphFallbackReason&&result.message)result.message=`${result.message} (${graphFallbackReason})`;if(bail&&coverage&&result.message)result.message=`${result.message} (coverage may be incomplete: bail=true stopped early)`;return JSON.stringify(result,null,2)}}),_internals211={analyzeImpact,loadImpactMap,loadImpactMapWithStatus,getImpactCacheStatus,isCommandAvailable,existsSync:fs141.existsSync,readdirSync:fs141.readdirSync,readFileSync:fs141.readFileSync,realpathSync:fs141.realpathSync,resolveLocalNodeTool,bunSpawn,buildNativeTargetCommand,formatNativeHistoryTestFile,selectHistoryForAnalysis,AGGREGATE_TEST_NAME}});import*as fs142 from"node:fs";import*as path257 from"node:path";function formatSecretscanIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function validateDirectoryPath(dir){if(!dir||typeof dir!=="string")throw Error("Directory path is required");if(dir.includes(".."))throw Error("Directory path must not contain path traversal sequences");let normalized=path257.normalize(dir);return path257.isAbsolute(normalized)?normalized:path257.resolve(normalized)}function validateTimeout(timeoutMs,defaultValue){if(timeoutMs===void 0)return defaultValue;if(typeof timeoutMs!=="number"||!Number.isFinite(timeoutMs))throw Error("Timeout must be a finite number");if(timeoutMs<=0)throw Error("Timeout must be greater than 0");if(timeoutMs<MIN_CHECK_TIMEOUT_MS)throw Error(`Timeout must be at least ${MIN_CHECK_TIMEOUT_MS}ms (5 seconds)`);if(timeoutMs>MAX_CHECK_TIMEOUT_MS)throw Error(`Timeout must not exceed ${MAX_CHECK_TIMEOUT_MS}ms (5 minutes)`);return timeoutMs}function getPackageVersion(dir){try{let packagePath=path257.join(dir,"package.json");if(fs142.existsSync(packagePath)){let content=fs142.readFileSync(packagePath,"utf-8");return JSON.parse(content).version??null}}catch{}return null}function getChangelogVersion(dir){try{let changelogPath=path257.join(dir,"CHANGELOG.md");if(fs142.existsSync(changelogPath)){let match=fs142.readFileSync(changelogPath,"utf-8").match(/^##\s*\[?(\d+\.\d+\.\d+)\]?/m);if(match)return match[1]}}catch{}return null}function getVersionFileVersion(dir){let possibleFiles=["VERSION.txt","version.txt","VERSION","version"];for(let file3 of possibleFiles){let filePath=path257.join(dir,file3);if(fs142.existsSync(filePath))try{let match=fs142.readFileSync(filePath,"utf-8").trim().match(/(\d+\.\d+\.\d+)/);if(match)return match[1]}catch{}}return null}async function runVersionCheck2(dir,_timeoutMs){let startTime=Date.now();try{let packageVersion=_internals212.getPackageVersion(dir),changelogVersion=_internals212.getChangelogVersion(dir),versionFileVersion=_internals212.getVersionFileVersion(dir),versions3=[];if(packageVersion)versions3.push(`package.json: ${packageVersion}`);if(changelogVersion)versions3.push(`CHANGELOG.md: ${changelogVersion}`);if(versionFileVersion)versions3.push(`version file: ${versionFileVersion}`);if(new Set([packageVersion,changelogVersion,versionFileVersion].filter(Boolean)).size<=1){if(versions3.length===0)return{type:"version",status:"skip",message:"No version information found to check",details:{},durationMs:Date.now()-startTime};return{type:"version",status:"pass",message:`Version consistent: ${versions3.join(", ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}return{type:"version",status:"fail",message:`Version mismatch: ${versions3.join("; ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}catch(error93){return{type:"version",status:"error",message:`Version check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runLintCheck(dir,linter,timeoutMs){let startTime=Date.now();try{let lintPromise=runLint(linter,"check",dir),timeoutId,timeoutPromise=new Promise((_,reject2)=>{timeoutId=setTimeout(()=>{reject2(Error(`Lint check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([lintPromise,timeoutPromise]).finally(()=>clearTimeout(timeoutId));if(!result.success)return{type:"lint",status:"error",message:result.error??"Lint check failed",details:{linter,success:result.success},durationMs:Date.now()-startTime};if(result.exitCode!==0){let issueMatch=result.output.match(/(\d+)\s+(issues?|errors?)/i),issueCount=issueMatch?parseInt(issueMatch[1],10):void 0;return{type:"lint",status:"fail",message:issueCount?`Lint found ${issueCount} issue(s)`:"Lint found issues",details:{linter,exitCode:result.exitCode,issueCount,hasOutput:result.output.length>0},durationMs:Date.now()-startTime}}return{type:"lint",status:"pass",message:"Lint check passed",details:{linter,exitCode:result.exitCode},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))return{type:"lint",status:"error",message:error93.message,details:{linter},durationMs:Date.now()-startTime};return{type:"lint",status:"error",message:`Lint check failed: ${error93 instanceof Error?error93.message:String(error93)}`,details:{linter},durationMs:Date.now()-startTime}}}async function runTestsCheck(_dir,scope,timeoutMs){let startTime=Date.now();try{let detectedFramework=await detectTestFrameworkViaDispatch(_dir);if(detectedFramework!=="none")return{type:"tests",status:"pass",message:`Test framework detected: ${detectedFramework}`,details:{framework:detectedFramework,scope,detectedOnly:!0},durationMs:Date.now()-startTime};let result=await runTests("none",scope,[],!1,timeoutMs,_dir,!1);if(!result.success)return{type:"tests",status:"error",message:result.error??"Tests check failed",details:{framework:result.framework,scope,success:result.success},durationMs:Date.now()-startTime};if(result.totals.failed>0)return{type:"tests",status:"fail",message:`Tests failed: ${result.totals.failed}/${result.totals.total} failed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime};if(result.totals.total===0)return{type:"tests",status:"skip",message:"No tests found to run",details:{framework:result.framework,scope},durationMs:Date.now()-startTime};return{type:"tests",status:"pass",message:`Tests passed: ${result.totals.passed} passed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&(error93.message.includes("timeout")||error93.message.includes("ETIMEDOUT")))return{type:"tests",status:"error",message:`Tests check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"tests",status:"error",message:`Tests check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runSecretsCheck(dir,timeoutMs){let startTime=Date.now();try{let secretsPromise=_internals212.runSecretscan(dir),timeoutPromise=new Promise((_,reject2)=>{setTimeout(()=>{reject2(Error(`Secrets check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([secretsPromise,timeoutPromise]);if("error"in result)return{type:"secrets",status:"fail",message:`Secrets check failed: ${result.error}`,details:{error:result.error,filesScanned:result.files_scanned,incompleteFiles:0,incompletePaths:[]},durationMs:Date.now()-startTime};let findingsCount=Math.max(result.count,result.findings.length);if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{type:"secrets",status:"fail",message:"Secrets check failed: scanner returned incomplete coverage metadata",details:{filesScanned:result.files_scanned},durationMs:Date.now()-startTime};let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=result,hasCountMismatch=result.count!==result.findings.length,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasZeroCoverage=result.files_scanned===0,failures=[];if(findingsCount>0){let critical=result.findings.filter((f)=>f.severity==="critical").length,high=result.findings.filter((f)=>f.severity==="high").length;failures.push(`Found ${findingsCount} secret(s): ${critical} critical, ${high} high`)}if(hasIncompleteCoverage){let incompleteSummary=incompletePaths.length>0?`; incomplete paths: ${formatSecretscanIncompletePaths(incompletePaths)}`:"";failures.push(`${incompleteFiles} incomplete file(s)${incompleteSummary}`)}if(hasCountMismatch)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(hasZeroCoverage)failures.push("zero requested files scanned");if(failures.length>0)return{type:"secrets",status:"fail",message:`Secrets check failed: ${failures.join("; ")}`,details:{count:findingsCount,reportedCount:result.count,critical:result.findings.filter((f)=>f.severity==="critical").length,high:result.findings.filter((f)=>f.severity==="high").length,filesScanned:result.files_scanned,skippedFiles:result.skipped_files,incompleteFiles,incompletePaths},durationMs:Date.now()-startTime};return{type:"secrets",status:"pass",message:"No secrets detected",details:{filesScanned:result.files_scanned,skippedFiles:result.skipped_files,incompleteFiles,incompletePaths},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.name==="AbortError")return{type:"secrets",status:"error",message:`Secrets check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"secrets",status:"error",message:`Secrets check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runEvidenceCheck(dir){let startTime=Date.now();try{let plan=await loadPlan(dir);if(!plan)return{type:"evidence",status:"skip",message:"No plan found to check evidence against",details:{},durationMs:Date.now()-startTime};let completedTaskIds=[];for(let phase of plan.phases)for(let task2 of phase.tasks)if(task2.status==="completed")completedTaskIds.push(task2.id);if(completedTaskIds.length===0)return{type:"evidence",status:"skip",message:"No completed tasks yet",details:{completedTasks:0},durationMs:Date.now()-startTime};let evidenceTaskIds=new Set(await listEvidenceTaskIds(dir)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(dir,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}let completedWithEvidence=completedTaskIds.length-missingEvidence.length;if(missingEvidence.length>0)return{type:"evidence",status:"fail",message:`${missingEvidence.length} completed task(s) missing evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence,missingTasks:missingEvidence.slice(0,10),missingCount:missingEvidence.length},durationMs:Date.now()-startTime};return{type:"evidence",status:"pass",message:`All ${completedTaskIds.length} completed tasks have evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence},durationMs:Date.now()-startTime}}catch(error93){return{type:"evidence",status:"error",message:`Evidence check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runRequirementCoverageCheck(dir,currentPhase){let startTime=Date.now();try{if(readEffectiveSpecSync(dir)===null)return{type:"req_coverage",status:"skip",message:"No effective spec found, requirement coverage not required",details:{},durationMs:Date.now()-startTime};let coverage=await checkRequirementCoverage(currentPhase,dir);if(!coverage.exists)return{type:"req_coverage",status:"fail",message:"Requirement coverage report missing but effective spec exists",details:{expectedPath:coverage.path},durationMs:Date.now()-startTime};let raw;try{let stat23=await fs142.promises.stat(coverage.path);if(stat23.size>REQ_COVERAGE_MAX_JSON_BYTES)return{type:"req_coverage",status:"fail",message:`Requirement coverage report exceeds ${REQ_COVERAGE_MAX_JSON_BYTES} byte cap and cannot be validated`,details:{path:coverage.path,sizeBytes:stat23.size},durationMs:Date.now()-startTime};raw=await fs142.promises.readFile(coverage.path,"utf-8")}catch(readError){return{type:"req_coverage",status:"fail",message:`Requirement coverage report unreadable: ${readError instanceof Error?readError.message:String(readError)}`,details:{path:coverage.path},durationMs:Date.now()-startTime}}let trimmed=raw.trim();if(trimmed.length===0)return{type:"req_coverage",status:"fail",message:"Requirement coverage report is empty",details:{path:coverage.path},durationMs:Date.now()-startTime};let parsed;try{parsed=JSON.parse(trimmed)}catch(parseError){return{type:"req_coverage",status:"fail",message:`Requirement coverage report is not valid JSON: ${parseError instanceof Error?parseError.message:String(parseError)}`,details:{path:coverage.path},durationMs:Date.now()-startTime}}let report=ReqCoverageReportSchema.safeParse(parsed);if(!report.success)return{type:"req_coverage",status:"fail",message:"Requirement coverage report does not match the expected report shape",details:{path:coverage.path},durationMs:Date.now()-startTime};let{success:success3,phase,totalRequirements,coveredCount,missingCount,requirements}=report.data;if(!success3)return{type:"req_coverage",status:"fail",message:"Requirement coverage report indicates the coverage run itself failed (success: false)",details:{path:coverage.path},durationMs:Date.now()-startTime};if(phase!==currentPhase)return{type:"req_coverage",status:"fail",message:`Requirement coverage report phase (${phase}) does not match the current phase (${currentPhase})`,details:{path:coverage.path,reportPhase:phase,currentPhase},durationMs:Date.now()-startTime};if(totalRequirements===0)return{type:"req_coverage",status:"fail",message:"Requirement coverage report contains no requirements (totalRequirements is 0) but effective spec exists",details:{path:coverage.path,totalRequirements},durationMs:Date.now()-startTime};if(coveredCount+missingCount!==totalRequirements)return{type:"req_coverage",status:"fail",message:`Requirement coverage report counts are inconsistent: coveredCount (${coveredCount}) + missingCount (${missingCount}) !== totalRequirements (${totalRequirements})`,details:{path:coverage.path,totalRequirements,coveredCount,missingCount},durationMs:Date.now()-startTime};if(requirements.length!==totalRequirements)return{type:"req_coverage",status:"fail",message:`Requirement coverage report requirements array length (${requirements.length}) does not match totalRequirements (${totalRequirements})`,details:{path:coverage.path,totalRequirements,requirementsLength:requirements.length},durationMs:Date.now()-startTime};if(missingCount>0)return{type:"req_coverage",status:"fail",message:`Requirement coverage report has ${missingCount} uncovered requirement(s)`,details:{path:coverage.path,totalRequirements,coveredCount,missingCount},durationMs:Date.now()-startTime};return{type:"req_coverage",status:"pass",message:`Requirement coverage report found: ${coveredCount}/${totalRequirements} requirement(s) covered`,details:{path:coverage.path,totalRequirements,coveredCount,missingCount},durationMs:Date.now()-startTime}}catch(error93){return{type:"req_coverage",status:"error",message:`Requirement coverage check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runPreflight(dir,phase,config3){let startTime=Date.now(),reportId=`preflight-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,validatedDir;try{validatedDir=_internals212.validateDirectoryPath(dir)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid directory: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid directory"}}let validatedTimeout;try{validatedTimeout=_internals212.validateTimeout(config3?.checkTimeoutMs,DEFAULT_CONFIG.checkTimeoutMs)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid config: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid configuration"}}let cfg={checkTimeoutMs:validatedTimeout,skipTests:config3?.skipTests??DEFAULT_CONFIG.skipTests,skipSecrets:config3?.skipSecrets??DEFAULT_CONFIG.skipSecrets,skipEvidence:config3?.skipEvidence??DEFAULT_CONFIG.skipEvidence,skipVersion:config3?.skipVersion??DEFAULT_CONFIG.skipVersion,testScope:config3?.testScope??DEFAULT_CONFIG.testScope,linter:config3?.linter??DEFAULT_CONFIG.linter};log("[Preflight] Starting preflight checks",{reportId,phase,config:{skipTests:cfg.skipTests,skipSecrets:cfg.skipSecrets,skipEvidence:cfg.skipEvidence,skipVersion:cfg.skipVersion,testScope:cfg.testScope,linter:cfg.linter}});let checks5=[];log("[Preflight] Running lint check...");let lintResult=await _internals212.runLintCheck(validatedDir,cfg.linter,cfg.checkTimeoutMs);if(checks5.push(lintResult),log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`),!cfg.skipTests){log("[Preflight] Running tests check...");let testsResult=await _internals212.runTestsCheck(validatedDir,cfg.testScope,cfg.checkTimeoutMs);checks5.push(testsResult),log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`)}else checks5.push({type:"tests",status:"skip",message:"Tests check skipped by configuration"});if(!cfg.skipSecrets){log("[Preflight] Running secrets check...");let secretsResult=await _internals212.runSecretsCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(secretsResult),log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`)}else checks5.push({type:"secrets",status:"skip",message:"Secrets check skipped by configuration"});if(!cfg.skipEvidence){log("[Preflight] Running evidence check...");let evidenceResult=await _internals212.runEvidenceCheck(validatedDir);checks5.push(evidenceResult),log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`)}else checks5.push({type:"evidence",status:"skip",message:"Evidence check skipped by configuration"});log("[Preflight] Running requirement coverage check...");let reqCoverageResult=await _internals212.runRequirementCoverageCheck(validatedDir,phase);if(checks5.push(reqCoverageResult),log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`),!cfg.skipVersion){log("[Preflight] Running version check...");let versionResult=await _internals212.runVersionCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(versionResult),log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`)}else checks5.push({type:"version",status:"skip",message:"Version check skipped by configuration"});let totalDurationMs=Date.now()-startTime,failedChecks=checks5.filter((c)=>c.status==="fail").length,errorChecks=checks5.filter((c)=>c.status==="error").length,skippedChecks=checks5.filter((c)=>c.status==="skip").length,overall,message;if(errorChecks>0)overall="fail",message=`Preflight failed with ${errorChecks} error(s)`;else if(failedChecks>0)overall="fail",message=`Preflight failed: ${failedChecks} check(s) failed`;else if(skippedChecks===checks5.length)overall="skipped",message="All checks were skipped";else overall="pass",message="Preflight passed all checks";let testsDetectedOnlyForMessage=checks5.find((c)=>c.type==="tests")?.details?.detectedOnly===!0;if(overall==="pass"&&testsDetectedOnlyForMessage)message="Preflight passed all checks except tests (detected only — not executed)";return log(`[Preflight] Complete: ${overall} ${message}`),{id:reportId,timestamp:startTime,phase,overall,checks:checks5,totalDurationMs,message}}function formatPreflightMarkdown(report){let testsDetectedOnlyOverall=report.checks.some((c)=>c.type==="tests"&&c.details?.detectedOnly===!0),lines=["## Preflight Report","",`**Phase**: ${report.phase}`,`**Overall**: ${report.overall==="fail"?"❌ FAIL":report.overall==="skipped"?"⏭️ SKIPPED":testsDetectedOnlyOverall?"⏭️ PARTIAL (tests detected only)":"✅ PASS"}`,`**Duration**: ${(report.totalDurationMs/1000).toFixed(2)}s`,"","### Checks",""];for(let check3 of report.checks){let detectedOnly=check3.type==="tests"&&check3.details?.detectedOnly===!0,icon=detectedOnly?"⏭️":check3.status==="pass"?"✅":check3.status==="fail"?"❌":check3.status==="error"?"⚠️":"⏭️",message=detectedOnly?"detected only — tests not executed":check3.message;lines.push(`- ${icon} **${check3.type}**: ${message}`)}return lines.push(""),lines.push(report.message),lines.join(`
|
|
4077
4077
|
`)}async function handlePreflightCommand(directory,_args){let plan=await loadPlan(directory),phase=plan?getCurrentPhase(plan):1,report=await _internals212.runPreflight(directory,phase);return _internals212.formatPreflightMarkdown(report)}var MIN_CHECK_TIMEOUT_MS=5000,MAX_CHECK_TIMEOUT_MS=300000,DEFAULT_CONFIG,ReqCoverageReportSchema,REQ_COVERAGE_MAX_JSON_BYTES=512000,_internals212;var init_preflight_service=__esm(()=>{init_zod();init_plan_schema();init_gate_bridge();init_manager2();init_manager();init_effective_spec();init_lint();init_secretscan();init_test_runner();init_utils();DEFAULT_CONFIG={checkTimeoutMs:60000,skipTests:!1,skipSecrets:!1,skipEvidence:!1,skipVersion:!1,testScope:"convention",linter:"biome"};ReqCoverageReportSchema=exports_external.object({success:exports_external.boolean(),phase:exports_external.number().int().nonnegative(),totalRequirements:exports_external.number().int().nonnegative(),coveredCount:exports_external.number().int().nonnegative(),missingCount:exports_external.number().int().nonnegative(),requirements:exports_external.array(exports_external.unknown())});_internals212={runPreflight,formatPreflightMarkdown,handlePreflightCommand,validateDirectoryPath,validateTimeout,getPackageVersion,getChangelogVersion,getVersionFileVersion,runVersionCheck:runVersionCheck2,runLintCheck,runTestsCheck,runSecretscan,runSecretsCheck,runEvidenceCheck,runRequirementCoverageCheck}});var init_preflight=__esm(()=>{init_preflight_service()});function parsePromoteArgs(args2){let category,lessonId,lessonText,force=!1,reason,actionable={};for(let i=0;i<args2.length;i++){let arg=args2[i],actionabilityField=ACTIONABILITY_LIST_FLAGS.get(arg);if(arg==="--category"&&i+1<args2.length)category=args2[i+1],i++;else if(arg==="--from-swarm"&&i+1<args2.length)lessonId=args2[i+1],i++;else if(arg==="--force")force=!0;else if(arg==="--reason"&&i+1<args2.length)reason=args2[i+1],i++;else if(actionabilityField!==void 0&&i+1<args2.length){let supplied=args2[i+1].split(",").map((v)=>v.trim()).filter((v)=>v.length>0);actionable[actionabilityField]=dedupeCapped([...actionable[actionabilityField]??[],...supplied],{cap:ACTIONABILITY_FIELD_CAP}),i++}else if(!arg.startsWith("--")){lessonText=args2.slice(i).join(" ");break}}return{category,lessonId,lessonText,force,reason,actionable}}async function handlePromoteCommand(directory,args2){let{category,lessonId,lessonText,force,reason,actionable}=parsePromoteArgs(args2);if(!lessonText&&!lessonId)return`Usage: /swarm promote "<lesson text>" or /swarm promote --from-swarm <id>
|
|
4078
4078
|
Options: --category <cat>, --force --reason "<why>" (audited policy override)
|
|
4079
4079
|
Actionability (direct text only; required unless knowledge.promotion_require_actionable=false):
|
|
@@ -4378,7 +4378,7 @@ Subcommands:
|
|
|
4378
4378
|
`+` turbo standard on — force standard turbo (disables lean even if config says lean)
|
|
4379
4379
|
`+` turbo standard off — disable all turbo modes (standard + lean)
|
|
4380
4380
|
`+` turbo status — show detailed status including active strategy and lanes
|
|
4381
|
-
`+"\nEpic Mode is not a Turbo strategy: start it with `/swarm epic start` (it enables neither Lean nor Turbo, and per-task QA is never waived). `turbo epic [on|off]` replies with that redirect and changes nothing. While an epic is open, every Turbo-enabling subcommand is refused (`epic-open`) until `/swarm epic close`; turning Turbo off always works.\n\n"+"Session-scoped — resets on new session.",category:"utility",toolPolicy:"none"},"full-auto":{handler:(ctx)=>handleFullAutoCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Control Full-Auto Mode for the active session [on [mode]|off|exit|status|retry-oversight|resume|abort]",args:"on [assisted|supervised|strict], off|exit, status, retry-oversight, resume, abort",details:'First-class toggle for Full-Auto Mode — a critic gate reviewing escalations on your behalf (the architect still plans and delegates; full-auto never executes tasks itself). 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. `retry-oversight` performs a transport-only health probe for an infrastructure/deadline pause and never replays the denied action. `resume` requires a recent successful matching probe and no active recovery blockers. `abort` terminates the durable run immediately. The run state is durable (.swarm/full-auto-state.json) and survives restarts; toggle with no argument flips the current state. Composes with an open epic (Epic Mode): both the Full-Auto phase approval and the epic_phase_readiness gate apply at phase_complete.",category:"utility",toolPolicy:"human-only"},"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 or archived knowledge entry <id>",subcommandOf:"knowledge",details:"Restores a quarantined or archived knowledge entry back to the active knowledge store by ID. Dispatches by current status: an 'archived' entry is restored to its pre-archive status; a 'quarantined' entry is restored from the quarantine sidecar. Validates entry ID format (1-64 alphanumeric/hyphen/underscore).",args:"<entry-id>",category:"utility"},"knowledge hive-quarantine":{handler:(ctx)=>handleKnowledgeHiveQuarantineCommand(ctx.directory,ctx.args),description:"Human-only exact-ID quarantine of hive-store entries with backup and rollback",subcommandOf:"knowledge",details:"Issue #2033 operator maintenance for the machine-global hive knowledge store. `preview <id>[,<id>...]` shows exact candidate IDs with per-line hashes, provenance, status, and a store fingerprint, and issues a short-lived confirmation token. "+"`commit --token <t> [--reason <text>]` writes and hash-verifies a complete backup plus manifest BEFORE any mutation (outside the hive lock), then re-verifies the live store against that backup inside one fast transaction (any drift — concurrent append, entry change, version bump, or duplicate-id ambiguity — aborts with no mutation and cleans up the orphaned backup), moving EXACTLY the selected entries to shared-learnings-quarantined.jsonl, with counts verified afterwards and an honestly-reported automatic restore on failure. "+"`rollback --token <token12> | --latest` restores the exact original bytes idempotently. "+"Selection is exact-ID only — never by text, substring, cohort, age, or blacklist, and never in bulk. "+"Human-only: refused for agents via swarm_command, chat fallback, and the shell guardrail.",args:"<preview|commit|rollback|status> ...",category:"utility",toolPolicy:"human-only"},"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, --instruction-pairing, --fixtures <directory>, --profiles <list>, --manifest <file>",category:"diagnostics",toolPolicy:"agent"},"memory audit-verify":{handler:(ctx)=>handleMemoryAuditVerifyCommand(ctx.directory,ctx.args),description:"Verify the memory audit-log hash chain (tamper detection)",subcommandOf:"memory",args:"--json",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 link":{handler:(ctx)=>handleMemoryLinkCommand(ctx.directory,ctx.args),description:"Share this worktree memory across linked sibling worktrees via the cohort identity (requires memory.link.enabled). Independently opt-in from /swarm link.",subcommandOf:"memory",args:"[name]",category:"utility",toolPolicy:"agent"},"memory link status":{handler:(ctx)=>handleMemoryLinkCommand(ctx.directory,["status"]),description:"Show whether this worktree shares memory via a cohort link",subcommandOf:"memory",args:"",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"memory unlink":{handler:(ctx)=>handleMemoryUnlinkCommand(ctx.directory,ctx.args),description:"Stop sharing memory; copies the cohort memory family back to local .swarm/memory/. The cohort store is never deleted.",subcommandOf:"memory",args:"[--no-copy]",category:"utility",toolPolicy:"agent"},"memory-status":{description:"Show Swarm memory provider, JSONL, and migration status",aliasOf:"memory status",deprecated:!0},"memory-export":{description:"Export current Swarm memory to JSONL files",aliasOf:"memory export",deprecated:!0},"memory-import":{description:"Import legacy JSONL memory into SQLite",aliasOf:"memory import",deprecated:!0},"memory-migrate":{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 git checkpoint. restore: hard-resets tracked files to the checkpoint; when uncommitted tracked work would be destroyed it previews first and requires the --confirm token from that preview (or --yes to confirm in one step); destroyed bytes are backed up to .swarm/rollback-backups/ (#2946). delete: removes checkpoint metadata. list: shows all checkpoints with timestamps. All subcommands require a label except list.",args:"<save|restore|delete|list> <label> [--confirm <token>] [--yes]",category:"utility",clashesWithNativeCcCommand:"/checkpoint",toolPolicy:"restricted"}},VALID_COMMANDS=Object.keys(COMMAND_REGISTRY);_internals86={handleHelpCommand,validateAliases,validateToolPolicy,emitValidationWarnings,resolveCommand,levenshteinDistance:levenshteinDistance2,findSimilarCommands,buildDetailedHelp},validation=_internals86.validateAliases();if(!validation.valid)throw Error(`COMMAND_REGISTRY alias validation failed:
|
|
4381
|
+
`+"\nEpic Mode is not a Turbo strategy: start it with `/swarm epic start` (it enables neither Lean nor Turbo, and per-task QA is never waived). `turbo epic [on|off]` replies with that redirect and changes nothing. While an epic is open, every Turbo-enabling subcommand is refused (`epic-open`) until `/swarm epic close`; turning Turbo off always works.\n\n"+"Session-scoped — resets on new session.",category:"utility",toolPolicy:"none"},"full-auto":{handler:(ctx)=>handleFullAutoCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Control Full-Auto Mode for the active session [on [mode]|off|exit|status|retry-oversight|resume|abort]",args:"on [assisted|supervised|strict], off|exit, status, retry-oversight, resume, abort",details:'First-class toggle for Full-Auto Mode — a critic gate reviewing escalations on your behalf (the architect still plans and delegates; full-auto never executes tasks itself). 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. `retry-oversight` performs a transport-only health probe for an infrastructure/deadline pause and never replays the denied action. `resume` runs the same authorization preflight as `on` first (readable config; `full_auto.locked` refuses), then requires a recent successful matching probe and no active recovery blockers. `abort` terminates the durable run immediately. The run state is durable (.swarm/full-auto-state.json) and survives restarts; toggle with no argument flips the current state. Composes with an open epic (Epic Mode): both the Full-Auto phase approval and the epic_phase_readiness gate apply at phase_complete.",category:"utility",toolPolicy:"human-only"},"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 or archived knowledge entry <id>",subcommandOf:"knowledge",details:"Restores a quarantined or archived knowledge entry back to the active knowledge store by ID. Dispatches by current status: an 'archived' entry is restored to its pre-archive status; a 'quarantined' entry is restored from the quarantine sidecar. Validates entry ID format (1-64 alphanumeric/hyphen/underscore).",args:"<entry-id>",category:"utility"},"knowledge hive-quarantine":{handler:(ctx)=>handleKnowledgeHiveQuarantineCommand(ctx.directory,ctx.args),description:"Human-only exact-ID quarantine of hive-store entries with backup and rollback",subcommandOf:"knowledge",details:"Issue #2033 operator maintenance for the machine-global hive knowledge store. `preview <id>[,<id>...]` shows exact candidate IDs with per-line hashes, provenance, status, and a store fingerprint, and issues a short-lived confirmation token. "+"`commit --token <t> [--reason <text>]` writes and hash-verifies a complete backup plus manifest BEFORE any mutation (outside the hive lock), then re-verifies the live store against that backup inside one fast transaction (any drift — concurrent append, entry change, version bump, or duplicate-id ambiguity — aborts with no mutation and cleans up the orphaned backup), moving EXACTLY the selected entries to shared-learnings-quarantined.jsonl, with counts verified afterwards and an honestly-reported automatic restore on failure. "+"`rollback --token <token12> | --latest` restores the exact original bytes idempotently. "+"Selection is exact-ID only — never by text, substring, cohort, age, or blacklist, and never in bulk. "+"Human-only: refused for agents via swarm_command, chat fallback, and the shell guardrail.",args:"<preview|commit|rollback|status> ...",category:"utility",toolPolicy:"human-only"},"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, --instruction-pairing, --fixtures <directory>, --profiles <list>, --manifest <file>",category:"diagnostics",toolPolicy:"agent"},"memory audit-verify":{handler:(ctx)=>handleMemoryAuditVerifyCommand(ctx.directory,ctx.args),description:"Verify the memory audit-log hash chain (tamper detection)",subcommandOf:"memory",args:"--json",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 link":{handler:(ctx)=>handleMemoryLinkCommand(ctx.directory,ctx.args),description:"Share this worktree memory across linked sibling worktrees via the cohort identity (requires memory.link.enabled). Independently opt-in from /swarm link.",subcommandOf:"memory",args:"[name]",category:"utility",toolPolicy:"agent"},"memory link status":{handler:(ctx)=>handleMemoryLinkCommand(ctx.directory,["status"]),description:"Show whether this worktree shares memory via a cohort link",subcommandOf:"memory",args:"",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"memory unlink":{handler:(ctx)=>handleMemoryUnlinkCommand(ctx.directory,ctx.args),description:"Stop sharing memory; copies the cohort memory family back to local .swarm/memory/. The cohort store is never deleted.",subcommandOf:"memory",args:"[--no-copy]",category:"utility",toolPolicy:"agent"},"memory-status":{description:"Show Swarm memory provider, JSONL, and migration status",aliasOf:"memory status",deprecated:!0},"memory-export":{description:"Export current Swarm memory to JSONL files",aliasOf:"memory export",deprecated:!0},"memory-import":{description:"Import legacy JSONL memory into SQLite",aliasOf:"memory import",deprecated:!0},"memory-migrate":{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 git checkpoint. restore: hard-resets tracked files to the checkpoint; when uncommitted tracked work would be destroyed it previews first and requires the --confirm token from that preview (or --yes to confirm in one step); destroyed bytes are backed up to .swarm/rollback-backups/ (#2946). delete: removes checkpoint metadata. list: shows all checkpoints with timestamps. All subcommands require a label except list.",args:"<save|restore|delete|list> <label> [--confirm <token>] [--yes]",category:"utility",clashesWithNativeCcCommand:"/checkpoint",toolPolicy:"restricted"}},VALID_COMMANDS=Object.keys(COMMAND_REGISTRY);_internals86={handleHelpCommand,validateAliases,validateToolPolicy,emitValidationWarnings,resolveCommand,levenshteinDistance:levenshteinDistance2,findSimilarCommands,buildDetailedHelp},validation=_internals86.validateAliases();if(!validation.valid)throw Error(`COMMAND_REGISTRY alias validation failed:
|
|
4382
4382
|
${validation.errors.join(`
|
|
4383
4383
|
`)}`);_internals86.emitValidationWarnings("COMMAND_REGISTRY alias warnings",validation.warnings);try{let toolPolicyValidation=_internals86.validateToolPolicy();_internals86.emitValidationWarnings("COMMAND_REGISTRY toolPolicy warnings",toolPolicyValidation.warnings)}catch(e){warn(`COMMAND_REGISTRY toolPolicy validation failed (non-fatal): ${e.message}`)}});function estimateModelTokens(text){return Math.ceil(text.length/4)}function measureArchitectPromptBudget(prompt){let chars=prompt.length;return{chars,tokenEstimate:estimateModelTokens(prompt),withinBudget:chars<ARCHITECT_PROMPT_BUDGET_CHARS}}function budgetAdvisorySignature(error93){return error93.replace(/\d+/g,"N")}function warnArchitectPromptBudgetExceededOnce(error93){let signature=budgetAdvisorySignature(error93);if(emittedBudgetAdvisories.has(signature))return;if(emittedBudgetAdvisories.size>=MAX_ARCHITECT_BUDGET_SIGNATURES){let oldest=emittedBudgetAdvisories.values().next().value;if(oldest!==void 0)emittedBudgetAdvisories.delete(oldest)}emittedBudgetAdvisories.add(signature),advisoryWarn(error93)}function resetArchitectPromptBudgetAdvisories(){emittedBudgetAdvisories.clear()}function enforceArchitectPromptBudget(label,prompt){let metrics=measureArchitectPromptBudget(prompt);if(metrics.withinBudget)return{ok:!0,chars:metrics.chars,tokenEstimate:metrics.tokenEstimate};return{ok:!1,error:`ARCHITECT_PROMPT_BUDGET_EXCEEDED: composed architect prompt for '${label.slice(0,200)}' is ${metrics.chars} chars (> ${ARCHITECT_PROMPT_BUDGET_CHARS} ceiling, ~${metrics.tokenEstimate} model-token estimate). The full prompt is kept (guidance is never dropped silently); shorten user-variable inputs (e.g. swarm names) or trim feature prose.`.slice(0,400),chars:metrics.chars,tokenEstimate:metrics.tokenEstimate}}function buildArchitectureSupervisionWorkflow(arch){if(arch?.enabled!==!0)return"";return`## ARCHITECTURE SUPERVISION (summary-level cross-task review)
|
|
4384
4384
|
|