opencode-swarm 7.129.1 → 7.129.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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.129.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight"],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_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_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"],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","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","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_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","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"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},prepare_pr_workflow_checkout:{description:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_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"]},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","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_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","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","coder","test_engineer"]},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],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"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.129.3",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight"],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_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_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"],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","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","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_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","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"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},prepare_pr_workflow_checkout:{description:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_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"]},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","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_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","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","coder","test_engineer"]},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],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"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -165,11 +165,13 @@ ${append}`;return base}import{randomUUID}from"node:crypto";import*as fsp from"no
165
165
  `}function laneOutputRelativePath(ref){let[,batchDigest,laneDigest,outputDigest]=ref.split(":");return path6.join("lane-results",batchDigest,laneDigest,`${outputDigest}.json`)}function hasValidArtifactIntegrity(artifact,expectedRef){let digest=digestText(artifact.text);if(artifact.digest!==digest)return!1;if(artifact.chars!==artifact.text.length)return!1;if(artifact.bytes!==Buffer.byteLength(artifact.text,"utf-8"))return!1;let batchDigest=digestText(artifact.batchId),laneDigest=digestText(artifact.laneId),expectedArtifactRef=`${LANE_OUTPUT_REF_PREFIX}:${batchDigest}:${laneDigest}:${digest}`;return artifact.ref===expectedRef&&artifact.ref===expectedArtifactRef}function artifactIdentityMatchesInput(artifact,input){return artifact.agent===input.agent&&artifact.role===input.role&&artifact.sessionId===input.sessionId&&artifact.parentSessionId===input.parentSessionId&&artifact.mode===input.mode&&artifact.workflowLane===input.workflowLane&&artifact.prHeadSha===input.prHeadSha&&artifact.gitHead===input.gitHead&&artifact.revisionDigest===input.revisionDigest&&artifact.scope===input.scope&&artifact.source===input.source}function writeAtomicJson(absPath,value){mkdirSync(path6.dirname(absPath),{recursive:!0});let tempFile=`${absPath}.tmp-${Date.now()}-${process.pid}`;try{writeFileSync(tempFile,JSON.stringify(value,null,2),"utf-8");let lastRenameError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES2;attempt++)try{renameSync(tempFile,absPath),lastRenameError=void 0;break}catch(err){lastRenameError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break}if(lastRenameError)throw lastRenameError}finally{if(existsSync3(tempFile))try{unlinkSync(tempFile)}catch{}}}function digestText(text){return createHash("sha256").update(text).digest("hex")}var LANE_OUTPUT_REF_PREFIX="L1",MAX_LANE_OUTPUT_STORED_BYTES=10485760,LANE_OUTPUT_SCHEMA_VERSION=1,REF_RE,LaneOutputArtifactSchema,WINDOWS_RENAME_MAX_RETRIES2=3;var init_lane_output_store=__esm(()=>{init_zod();init_utils2();REF_RE=/^L1:[a-f0-9]{64}:[a-f0-9]{64}:[a-f0-9]{64}$/,LaneOutputArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(LANE_OUTPUT_SCHEMA_VERSION),ref:exports_external.string().regex(REF_RE),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1),agent:exports_external.string().min(1),role:exports_external.string().min(1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),mode:exports_external.string().min(1).optional(),workflowLane:exports_external.string().min(1).optional(),prHeadSha:exports_external.string().min(1).optional(),gitHead:exports_external.string().min(1).optional(),revisionDigest:exports_external.string().min(1).optional(),scope:exports_external.string().min(1).optional(),source:exports_external.enum(["dispatch_lanes","collect_lane_results"]),text:exports_external.string(),chars:exports_external.number().int().nonnegative(),bytes:exports_external.number().int().nonnegative(),digest:exports_external.string().regex(/^[a-f0-9]{64}$/),messageCount:exports_external.number().int().nonnegative().optional(),transcriptIncomplete:exports_external.boolean().optional(),createdAt:exports_external.string(),updatedAt:exports_external.string()}).strict()});var require_polyfills=__commonJS((exports,module)=>{var constants2=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!cwd)cwd=origCwd.call(process);return cwd};try{process.cwd()}catch(er){}if(typeof process.chdir==="function"){if(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,chdir)}var chdir;module.exports=patch;function patch(fs4){if(constants2.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./))patchLchmod(fs4);if(!fs4.lutimes)patchLutimes(fs4);if(fs4.chown=chownFix(fs4.chown),fs4.fchown=chownFix(fs4.fchown),fs4.lchown=chownFix(fs4.lchown),fs4.chmod=chmodFix(fs4.chmod),fs4.fchmod=chmodFix(fs4.fchmod),fs4.lchmod=chmodFix(fs4.lchmod),fs4.chownSync=chownFixSync(fs4.chownSync),fs4.fchownSync=chownFixSync(fs4.fchownSync),fs4.lchownSync=chownFixSync(fs4.lchownSync),fs4.chmodSync=chmodFixSync(fs4.chmodSync),fs4.fchmodSync=chmodFixSync(fs4.fchmodSync),fs4.lchmodSync=chmodFixSync(fs4.lchmodSync),fs4.stat=statFix(fs4.stat),fs4.fstat=statFix(fs4.fstat),fs4.lstat=statFix(fs4.lstat),fs4.statSync=statFixSync(fs4.statSync),fs4.fstatSync=statFixSync(fs4.fstatSync),fs4.lstatSync=statFixSync(fs4.lstatSync),fs4.chmod&&!fs4.lchmod)fs4.lchmod=function(path7,mode,cb){if(cb)process.nextTick(cb)},fs4.lchmodSync=function(){};if(fs4.chown&&!fs4.lchown)fs4.lchown=function(path7,uid,gid,cb){if(cb)process.nextTick(cb)},fs4.lchownSync=function(){};if(platform==="win32")fs4.rename=typeof fs4.rename!=="function"?fs4.rename:function(fs$rename){function rename3(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<60000){if(setTimeout(function(){fs4.stat(to,function(stater,st){if(stater&&stater.code==="ENOENT")fs$rename(from,to,CB);else cb(er)})},backoff),backoff<100)backoff+=10;return}if(cb)cb(er)})}if(Object.setPrototypeOf)Object.setPrototypeOf(rename3,fs$rename);return rename3}(fs4.rename);fs4.read=typeof fs4.read!=="function"?fs4.read:function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_==="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs4,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs4,fd,buffer,offset,length,position,callback)}if(Object.setPrototypeOf)Object.setPrototypeOf(read,fs$read);return read}(fs4.read),fs4.readSync=typeof fs4.readSync!=="function"?fs4.readSync:function(fs$readSync){return function(fd,buffer,offset,length,position){var eagCounter=0;while(!0)try{return fs$readSync.call(fs4,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}}(fs4.readSync);function patchLchmod(fs5){fs5.lchmod=function(path7,mode,callback){fs5.open(path7,constants2.O_WRONLY|constants2.O_SYMLINK,mode,function(err,fd){if(err){if(callback)callback(err);return}fs5.fchmod(fd,mode,function(err2){fs5.close(fd,function(err22){if(callback)callback(err2||err22)})})})},fs5.lchmodSync=function(path7,mode){var fd=fs5.openSync(path7,constants2.O_WRONLY|constants2.O_SYMLINK,mode),threw=!0,ret;try{ret=fs5.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs5.closeSync(fd)}catch(er){}else fs5.closeSync(fd)}return ret}}function patchLutimes(fs5){if(constants2.hasOwnProperty("O_SYMLINK")&&fs5.futimes)fs5.lutimes=function(path7,at,mt,cb){fs5.open(path7,constants2.O_SYMLINK,function(er,fd){if(er){if(cb)cb(er);return}fs5.futimes(fd,at,mt,function(er2){fs5.close(fd,function(er22){if(cb)cb(er2||er22)})})})},fs5.lutimesSync=function(path7,at,mt){var fd=fs5.openSync(path7,constants2.O_SYMLINK),ret,threw=!0;try{ret=fs5.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs5.closeSync(fd)}catch(er){}else fs5.closeSync(fd)}return ret};else if(fs5.futimes)fs5.lutimes=function(_a2,_b,_c,cb){if(cb)process.nextTick(cb)},fs5.lutimesSync=function(){}}function chmodFix(orig){if(!orig)return orig;return function(target,mode,cb){return orig.call(fs4,target,mode,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chmodFixSync(orig){if(!orig)return orig;return function(target,mode){try{return orig.call(fs4,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){if(!orig)return orig;return function(target,uid,gid,cb){return orig.call(fs4,target,uid,gid,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chownFixSync(orig){if(!orig)return orig;return function(target,uid,gid){try{return orig.call(fs4,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){if(!orig)return orig;return function(target,options,cb){if(typeof options==="function")cb=options,options=null;function callback(er,stats2){if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}if(cb)cb.apply(this,arguments)}return options?orig.call(fs4,target,options,callback):orig.call(fs4,target,callback)}}function statFixSync(orig){if(!orig)return orig;return function(target,options){var stats2=options?orig.call(fs4,target,options):orig.call(fs4,target);if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}return stats2}}function chownErOk(er){if(!er)return!0;if(er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;if(nonroot){if(er.code==="EINVAL"||er.code==="EPERM")return!0}return!1}}});var require_legacy_streams=__commonJS((exports,module)=>{var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs4){return{ReadStream,WriteStream};function ReadStream(path7,options){if(!(this instanceof ReadStream))return new ReadStream(path7,options);Stream.call(this);var self=this;this.path=path7,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding)this.setEncoding(this.encoding);if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!=="number")throw TypeError("end must be a Number");if(this.start>this.end)throw Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs4.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path7,options){if(!(this instanceof WriteStream))return new WriteStream(path7,options);Stream.call(this),this.path=path7,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.start<0)throw Error("start must be >= zero");this.pos=this.start}if(this.busy=!1,this._queue=[],this.fd===null)this._open=fs4.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush()}}});var require_clone=__commonJS((exports,module)=>{module.exports=clone2;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone2(obj){if(obj===null||typeof obj!=="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}});var require_graceful_fs=__commonJS((exports,module)=>{var fs4=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone2=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;if(typeof Symbol==="function"&&typeof Symbol.for==="function")gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous");else gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous";function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;if(util.debuglog)debug=util.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
166
166
  GFS4: `),console.error(m)};if(!fs4[gracefulQueue]){if(queue=global[gracefulQueue]||[],publishQueue(fs4,queue),fs4.close=function(fs$close){function close(fd,cb){return fs$close.call(fs4,fd,function(err){if(!err)resetQueue();if(typeof cb==="function")cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close}(fs4.close),fs4.closeSync=function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs4,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync}(fs4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){debug(fs4[gracefulQueue]),__require("assert").equal(fs4[gracefulQueue].length,0)})}var queue;if(!global[gracefulQueue])publishQueue(global,fs4[gracefulQueue]);module.exports=patch(clone2(fs4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs4.__patched)module.exports=patch(fs4),fs4.__patched=!0;function patch(fs5){polyfills(fs5),fs5.gracefulify=patch,fs5.createReadStream=createReadStream,fs5.createWriteStream=createWriteStream;var fs$readFile=fs5.readFile;fs5.readFile=readFile4;function readFile4(path7,options,cb){if(typeof options==="function")cb=options,options=null;return go$readFile(path7,options,cb);function go$readFile(path8,options2,cb2,startTime){return fs$readFile(path8,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readFile,[path8,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$writeFile=fs5.writeFile;fs5.writeFile=writeFile3;function writeFile3(path7,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$writeFile(path7,data,options,cb);function go$writeFile(path8,data2,options2,cb2,startTime){return fs$writeFile(path8,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$writeFile,[path8,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$appendFile=fs5.appendFile;if(fs$appendFile)fs5.appendFile=appendFile;function appendFile(path7,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$appendFile(path7,data,options,cb);function go$appendFile(path8,data2,options2,cb2,startTime){return fs$appendFile(path8,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$appendFile,[path8,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$copyFile=fs5.copyFile;if(fs$copyFile)fs5.copyFile=copyFile2;function copyFile2(src,dest,flags,cb){if(typeof flags==="function")cb=flags,flags=0;return go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$readdir=fs5.readdir;fs5.readdir=readdir2;var noReaddirOptionVersions=/^v[0-5]\./;function readdir2(path7,options,cb){if(typeof options==="function")cb=options,options=null;var go$readdir=noReaddirOptionVersions.test(process.version)?function(path8,options2,cb2,startTime){return fs$readdir(path8,fs$readdirCallback(path8,options2,cb2,startTime))}:function(path8,options2,cb2,startTime){return fs$readdir(path8,options2,fs$readdirCallback(path8,options2,cb2,startTime))};return go$readdir(path7,options,cb);function fs$readdirCallback(path8,options2,cb2,startTime){return function(err,files){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readdir,[path8,options2,cb2],err,startTime||Date.now(),Date.now()]);else{if(files&&files.sort)files.sort();if(typeof cb2==="function")cb2.call(this,err,files)}}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs5);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs5.ReadStream;if(fs$ReadStream)ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open;var fs$WriteStream=fs5.WriteStream;if(fs$WriteStream)WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open;Object.defineProperty(fs5,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs5,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs5,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs5,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path7,options){if(this instanceof ReadStream)return fs$ReadStream.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open2(that.path,that.flags,that.mode,function(err,fd){if(err){if(that.autoClose)that.destroy();that.emit("error",err)}else that.fd=fd,that.emit("open",fd),that.read()})}function WriteStream(path7,options){if(this instanceof WriteStream)return fs$WriteStream.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open2(that.path,that.flags,that.mode,function(err,fd){if(err)that.destroy(),that.emit("error",err);else that.fd=fd,that.emit("open",fd)})}function createReadStream(path7,options){return new fs5.ReadStream(path7,options)}function createWriteStream(path7,options){return new fs5.WriteStream(path7,options)}var fs$open=fs5.open;fs5.open=open2;function open2(path7,flags,mode,cb){if(typeof mode==="function")cb=mode,mode=null;return go$open(path7,flags,mode,cb);function go$open(path8,flags2,mode2,cb2,startTime){return fs$open(path8,flags2,mode2,function(err,fd){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$open,[path8,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}return fs5}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs4[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){var now=Date.now();for(var i=0;i<fs4[gracefulQueue].length;++i)if(fs4[gracefulQueue][i].length>2)fs4[gracefulQueue][i][3]=now,fs4[gracefulQueue][i][4]=now;retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs4[gracefulQueue].length===0)return;var elem=fs4[gracefulQueue].shift(),fn2=elem[0],args2=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn2.name,args2),fn2.apply(null,args2);else if(Date.now()-startTime>=60000){debug("TIMEOUT",fn2.name,args2);var cb=args2.pop();if(typeof cb==="function")cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);if(sinceAttempt>=desiredDelay)debug("RETRY",fn2.name,args2),fn2.apply(null,args2.concat([startTime]));else fs4[gracefulQueue].push(elem)}if(retryTimer===void 0)retryTimer=setTimeout(retry,0)}});var require_retry_operation=__commonJS((exports,module)=>{function RetryOperation(timeouts,options){if(typeof options==="boolean")options={forever:options};if(this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout)clearTimeout(this._timeout);if(!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){if(self._attempts++,self._operationTimeoutCb){if(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref)self._timeout.unref()}self._fn(self._attempts)},timeout);if(this._options.unref)timer.unref();return!0};RetryOperation.prototype.attempt=function(fn2,timeoutOps){if(this._fn=fn2,timeoutOps){if(timeoutOps.timeout)this._operationTimeout=timeoutOps.timeout;if(timeoutOps.cb)this._operationTimeoutCb=timeoutOps.cb}var self=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn2){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=function(fn2){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;var counts={},mainError=null,mainErrorCount=0;for(var i=0;i<this._errors.length;i++){var error49=this._errors[i],message=error49.message,count=(counts[message]||0)+1;if(counts[message]=count,count>=mainErrorCount)mainError=error49,mainErrorCount=count}return mainError}});var require_retry=__commonJS((exports)=>{var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var timeouts=[];for(var i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));if(options&&options.forever&&!timeouts.length)timeouts.push(this.createTimeout(i,opts));return timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array)methods=options,options=null;if(!methods){methods=[];for(var key in obj)if(typeof obj[key]==="function")methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args2=Array.prototype.slice.call(arguments,1),callback=args2.pop();args2.push(function(err){if(op.retry(err))return;if(err)arguments[0]=op.mainError();callback.apply(this,arguments)}),op.attempt(function(){original2.apply(obj,args2)})}.bind(obj,original),obj[method].options=options}}});var require_signals=__commonJS((exports,module)=>{module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var require_signal_exit=__commonJS((exports,module)=>{var process3=global.process,processOk=function(process4){return process4&&typeof process4==="object"&&typeof process4.removeListener==="function"&&typeof process4.emit==="function"&&typeof process4.reallyExit==="function"&&typeof process4.listeners==="function"&&typeof process4.kill==="function"&&typeof process4.pid==="number"&&typeof process4.on==="function"};if(!processOk(process3))module.exports=function(){return function(){}};else{if(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!=="function")EE=EE.EventEmitter;if(process3.__signal_exit_emitter__)emitter=process3.__signal_exit_emitter__;else emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={};if(!emitter.infinite)emitter.setMaxListeners(1/0),emitter.infinite=!0;module.exports=function(cb,opts){if(!processOk(global.process))return function(){};if(assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1)load();var ev="exit";if(opts&&opts.alwaysLast)ev="afterexit";var remove=function(){if(emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0)unload()};return emitter.on(ev,cb),remove},unload=function(){if(!loaded||!processOk(global.process))return;loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch(er){}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1},module.exports.unload=unload,emit=function(event,code,signal){if(emitter.emitted[event])return;emitter.emitted[event]=!0,emitter.emit(event,code,signal)},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(!processOk(global.process))return;var listeners=process3.listeners(sig);if(listeners.length===emitter.count){if(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP")sig="SIGINT";process3.kill(process3.pid,sig)}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){if(loaded||!processOk(global.process))return;loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch(er){return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){if(!processOk(global.process))return;process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode)},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){if(arg!==void 0)process3.exitCode=arg;var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}}var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit});var require_mtime_precision=__commonJS((exports,module)=>{var cacheSymbol=Symbol();function probe(file2,fs4,callback){let cachedPrecision=fs4[cacheSymbol];if(cachedPrecision)return fs4.stat(file2,(err,stat5)=>{if(err)return callback(err);callback(null,stat5.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1000)*1000+5);fs4.utimes(file2,mtime,mtime,(err)=>{if(err)return callback(err);fs4.stat(file2,(err2,stat5)=>{if(err2)return callback(err2);let precision=stat5.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(fs4,cacheSymbol,{value:precision}),callback(null,stat5.mtime,precision)})})}function getMtime(precision){let now=Date.now();if(precision==="s")now=Math.ceil(now/1000)*1000;return new Date(now)}exports.probe=probe;exports.getMtime=getMtime});var require_lockfile=__commonJS((exports,module)=>{var path7=__require("path"),fs4=require_graceful_fs(),retry=require_retry(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file2,options){return options.lockfilePath||`${file2}.lock`}function resolveCanonicalPath(file2,options,callback){if(!options.realpath)return callback(null,path7.resolve(file2));options.fs.realpath(file2,callback)}function acquireLock(file2,options,callback){let lockfilePath=getLockFile(file2,options);options.fs.mkdir(lockfilePath,(err)=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));options.fs.stat(lockfilePath,(err2,stat5)=>{if(err2){if(err2.code==="ENOENT")return acquireLock(file2,{...options,stale:0},callback);return callback(err2)}if(!isLockStale(stat5,options))return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));removeLock(file2,options,(err3)=>{if(err3)return callback(err3);acquireLock(file2,{...options,stale:0},callback)})})})}function isLockStale(stat5,options){return stat5.mtime.getTime()<Date.now()-options.stale}function removeLock(file2,options,callback){options.fs.rmdir(getLockFile(file2,options),(err)=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file2,options){let lock2=locks[file2];if(lock2.updateTimeout)return;if(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat5)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err){if(err.code==="ENOENT"||isOverThreshold)return setLockAsCompromised(file2,lock2,Object.assign(err,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}if(lock2.mtime.getTime()!==stat5.mtime.getTime())return setLockAsCompromised(file2,lock2,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,(err2)=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(lock2.released)return;if(err2){if(err2.code==="ENOENT"||isOverThreshold2)return setLockAsCompromised(file2,lock2,Object.assign(err2,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file2,options)})})},lock2.updateDelay),lock2.updateTimeout.unref)lock2.updateTimeout.unref()}function setLockAsCompromised(file2,lock2,err){if(lock2.released=!0,lock2.updateTimeout)clearTimeout(lock2.updateTimeout);if(locks[file2]===lock2)delete locks[file2];lock2.options.onCompromised(err)}function lock(file2,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs:fs4,onCompromised:(err)=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries==="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2000),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file3,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file3]={lockfilePath:getLockFile(file3,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file3,options),callback(null,(releasedCallback)=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));unlock(file3,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file2,options,callback){options={fs:fs4,realpath:!0,...options},resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let lock2=locks[file3];if(!lock2)return callback(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file3],removeLock(file3,options,callback)})}function check2(file2,options,callback){options={stale:1e4,realpath:!0,fs:fs4,...options},options.stale=Math.max(options.stale||0,2000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);options.fs.stat(getLockFile(file3,options),(err2,stat5)=>{if(err2)return err2.code==="ENOENT"?callback(null,!1):callback(err2);return callback(null,!isLockStale(stat5,options))})})}function getLocks(){return locks}onExit(()=>{for(let file2 in locks){let options=locks[file2].options;try{options.fs.rmdirSync(getLockFile(file2,options))}catch(e){}}});exports.lock=lock;exports.unlock=unlock;exports.check=check2;exports.getLocks=getLocks});var require_adapter=__commonJS((exports,module)=>{var fs4=require_graceful_fs();function createSyncFs(fs5){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs5};return methods.forEach((method)=>{newFs[method]=(...args2)=>{let callback=args2.pop(),ret;try{ret=fs5[`${method}Sync`](...args2)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args2)=>new Promise((resolve4,reject)=>{args2.push((err,result)=>{if(err)reject(err);else resolve4(result)}),method(...args2)})}function toSync(method){return(...args2)=>{let err,result;if(args2.push((_err,_result)=>{err=_err,result=_result}),method(...args2),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs4),typeof options.retries==="number"&&options.retries>0||options.retries&&typeof options.retries.retries==="number"&&options.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}});var require_proper_lockfile=__commonJS((exports,module)=>{var lockfile=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file2,options){let release=await toPromise(lockfile.lock)(file2,options);return toPromise(release)}function lockSync(file2,options){let release=toSync(lockfile.lock)(file2,toSyncOptions(options));return toSync(release)}function unlock(file2,options){return toPromise(lockfile.unlock)(file2,options)}function unlockSync(file2,options){return toSync(lockfile.unlock)(file2,toSyncOptions(options))}function check2(file2,options){return toPromise(lockfile.check)(file2,options)}function checkSync(file2,options){return toSync(lockfile.check)(file2,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check2;module.exports.checkSync=checkSync});import*as crypto2 from"node:crypto";import*as fs4 from"node:fs";import*as path7 from"node:path";function getLockFilePath(directory,filePath){let normalized=path7.resolve(directory,filePath),baseDir=path7.resolve(directory)+path7.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path7.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path7.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs4.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals4.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs4.promises.rename(tmpPath,metaPath)}catch(err){try{await fs4.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs4.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path7.dirname(lockPath);if(!fs4.existsSync(locksDir))fs4.mkdirSync(locksDir,{recursive:!0});if(!fs4.existsSync(lockPath))fs4.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs4.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs4.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path7.join(directory,LOCKS_DIR),locks=[];if(!fs4.existsSync(locksDir))return locks;let files=fs4.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path7.join(locksDir,file2);try{if(fs4.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs4.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs4.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:file2,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs4.unlinkSync(metaPath2)}catch{}try{fs4.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs4.unlinkSync(mp)}catch{}try{fs4.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs4.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path7.join(directory,LOCKS_DIR);if(!fs4.existsSync(locksDir))return 0;let files=fs4.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path7.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile.default.unlock(lockPath,{realpath:!1})}catch{}try{fs4.unlinkSync(lockPath)}catch{}try{fs4.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals4;var init_file_locks=__esm(()=>{import_proper_lockfile=__toESM(require_proper_lockfile(),1),_internals4={tryAcquireLock,writeFile:fs4.promises.writeFile}});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,initTelemetry:()=>initTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals5,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs5 from"node:fs";import{createWriteStream}from"node:fs";import*as os2 from"node:os";import*as path8 from"node:path";function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_writeStream!==null||_disabled)return;try{_projectDirectory=projectDirectory;let swarmDir=path8.join(projectDirectory,".swarm");if(!fs5.existsSync(swarmDir))fs5.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path8.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}catch{_disabled=!0,_writeStream=null}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let line=JSON.stringify({timestamp:new Date().toISOString(),event,...data})+os2.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals5.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path8.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs5.existsSync(telemetryPath))return;if(fs5.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path8.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs5.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals5;var init_telemetry=__esm(()=>{_listeners=[];telemetry={sessionStarted(sessionId,agentName){_internals5.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals5.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals5.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals5.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals5.emit("delegation_end",{sessionId,agentName,taskId,result,tokens_input:costFields?.tokens_input??0,tokens_output:costFields?.tokens_output??0,tokens_reasoning:costFields?.tokens_reasoning??0,tokens_cache:costFields?.tokens_cache??0,cost_usd:costFields?.cost_usd??null,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},taskStateChanged(sessionId,taskId,newState,oldState){_internals5.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals5.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals5.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals5.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals5.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals5.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals5.emit("budget_updated",{sessionId,budgetPct,agentName})},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals5.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},hardLimitHit(sessionId,agentName,limitType,value){_internals5.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals5.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals5.emit("loop_detected",{sessionId,agentName,loopType})},scopeViolation(sessionId,agentName,file2,reason){_internals5.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals5.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals5.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals5.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals5.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals5.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals5.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals5.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals5.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals5.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})}},_internals5={telemetry,emit,rotateTelemetryIfNeeded}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve5)=>setTimeout(resolve5,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});var exports_pending_delegations={};__export(exports_pending_delegations,{sweepStaleDelegations:()=>sweepStaleDelegations,recordPendingDelegation:()=>recordPendingDelegation,readDelegations:()=>readDelegations,findOpenAsyncLaneBatches:()=>findOpenAsyncLaneBatches,findByCorrelationId:()=>findByCorrelationId,findByBatchId:()=>findByBatchId,buildPromptSnapshot:()=>buildPromptSnapshot,appendDelegationTransition:()=>appendDelegationTransition,BACKGROUND_DELEGATIONS_FILE:()=>BACKGROUND_DELEGATIONS_FILE});import{createHash as createHash3}from"node:crypto";import*as fs6 from"node:fs";import*as path9 from"node:path";function storePath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_FILE)}function ensureSwarmDir(directory){fs6.mkdirSync(path9.resolve(directory,".swarm"),{recursive:!0})}function readDelegations(directory){let raw;try{raw=fs6.readFileSync(storePath(directory),"utf-8")}catch(err){if(err.code==="ENOENT")return[];return warn(`[background] readDelegations failed: ${err instanceof Error?err.message:String(err)}`),[]}let folded=new Map;for(let line of raw.split(`
167
167
  `)){let trimmed=line.trim();if(trimmed.length===0)continue;let parsedJson;try{parsedJson=JSON.parse(trimmed)}catch{continue}let result=RecordSchema.safeParse(parsedJson);if(!result.success)continue;folded.set(result.data.correlationId,result.data)}return[...folded.values()]}function findByCorrelationId(directory,correlationId){if(!correlationId)return null;for(let record2 of readDelegations(directory))if(record2.correlationId===correlationId)return record2;return null}function appendRecord(directory,record2){ensureSwarmDir(directory),fs6.appendFileSync(storePath(directory),`${JSON.stringify(record2)}
168
- `,"utf-8")}async function recordPendingDelegation(directory,input,options={}){let now=Date.now(),record2={schemaVersion:input.batchId?2:1,correlationId:input.correlationId,jobId:input.jobId,subagentSessionId:input.subagentSessionId,parentSessionId:input.parentSessionId,callID:input.callID,normalizedAgent:input.normalizedAgent,swarmPrefixedAgent:input.swarmPrefixedAgent,planTaskId:input.planTaskId,evidenceTaskId:input.evidenceTaskId,status:"pending",createdAt:now,updatedAt:now,...input.batchId?{batchId:input.batchId}:{},...input.laneId?{laneId:input.laneId}:{},...input.mode?{mode:input.mode}:{},...input.workflowLane?{workflowLane:input.workflowLane}:{},...input.ownedWorkflowLanes?.length?{ownedWorkflowLanes:[...input.ownedWorkflowLanes]}:{},...input.promptHash?{promptHash:input.promptHash}:{},...input.workspace?{workspace:input.workspace}:{},...input.taskChangeContext?{taskChangeContext:input.taskChangeContext}:{},...input.prompt?{prompt:input.prompt}:{},...input.generation!==void 0?{generation:input.generation}:{}};try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(options.staleTimeoutMs&&options.staleTimeoutMs>0)sweepStaleLocked(directory,options.staleTimeoutMs,now);appendRecord(directory,record2)}),record2}catch(err){return warn(`[background] recordPendingDelegation failed: ${err instanceof Error?err.message:String(err)}`),null}}function buildPromptSnapshot(text,maxChars){let boundedMax=Math.max(0,Math.min(maxChars,20000)),truncated=text.length>boundedMax;return{text:truncated?text.slice(0,boundedMax):text,chars:text.length,truncated,digest:createHash3("sha256").update(text).digest("hex")}}async function appendDelegationTransition(directory,correlationId,transition){let now=Date.now();try{let next=null;return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let current=findByCorrelationId(directory,correlationId);if(!current)return;if(isTerminal(current.status)&&transition.status!=="consumed"&&transition.status!=="ingestion_error"){next=current;return}next={...current,schemaVersion:current.schemaVersion===1?2:current.schemaVersion,status:transition.status,updatedAt:now,...transition.completedAt!==void 0?{completedAt:transition.completedAt}:transition.status==="completed"||transition.status==="error"?{completedAt:now}:{},...transition.result?{result:transition.result}:{}},appendRecord(directory,next)}),next}catch(err){return warn(`[background] appendDelegationTransition failed: ${err instanceof Error?err.message:String(err)}`),null}}function findByBatchId(directory,batchId,opts){if(!batchId)return[];return readDelegations(directory).filter((record2)=>record2.batchId===batchId&&(opts?.parentSessionId===void 0||record2.parentSessionId===opts.parentSessionId))}function findOpenAsyncLaneBatches(directory){return readDelegations(directory).filter((record2)=>record2.batchId!==void 0&&(record2.status==="pending"||record2.status==="running"))}function isTerminal(status){return status==="completed"||status==="error"||status==="cancelled"||status==="stale"||status==="consumed"}function sweepStaleLocked(directory,timeoutMs,now){let swept=0;for(let record2 of readDelegations(directory)){if(record2.status!=="pending"&&record2.status!=="running"&&record2.status!=="ingestion_error")continue;if(now-record2.updatedAt<=timeoutMs)continue;appendRecord(directory,{...record2,status:"stale",updatedAt:now}),swept+=1}return swept}async function sweepStaleDelegations(directory,timeoutMs){if(!timeoutMs||timeoutMs<=0)return 0;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>sweepStaleLocked(directory,timeoutMs,Date.now()))}catch(err){return warn(`[background] sweepStaleDelegations failed: ${err instanceof Error?err.message:String(err)}`),0}}var BACKGROUND_DELEGATIONS_FILE="background-delegations.jsonl",STORE_LOCK_AGENT="background",STORE_LOCK_TASK="background-delegations",ResultSchema,WorkspaceSchema,TaskChangeContextSchema,PromptSchema,RecordSchema;var init_pending_delegations=__esm(()=>{init_zod();init_lock();init_utils2();init_logger();ResultSchema=exports_external.object({text:exports_external.string().optional(),error:exports_external.string().optional(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string(),outputRef:exports_external.string().optional(),outputPreviewChars:exports_external.number().optional(),outputDegraded:exports_external.boolean().optional(),outputArtifactError:exports_external.string().optional(),transcriptIncomplete:exports_external.boolean().optional(),messageCount:exports_external.number().optional()}).strict(),WorkspaceSchema=exports_external.object({directory:exports_external.string(),gitHead:exports_external.string().nullable(),dirtyHash:exports_external.string().nullable(),changedFiles:exports_external.array(exports_external.string()).nullable().optional(),prHeadSha:exports_external.string().nullable(),scope:exports_external.string().nullable()}).strict(),TaskChangeContextSchema=exports_external.object({declaredFiles:exports_external.array(exports_external.string()).nullable(),baseline:WorkspaceSchema}).strict(),PromptSchema=exports_external.object({text:exports_external.string(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string()}).strict(),RecordSchema=exports_external.object({schemaVersion:exports_external.union([exports_external.literal(1),exports_external.literal(2)]),correlationId:exports_external.string().min(1),jobId:exports_external.string().nullable(),subagentSessionId:exports_external.string().min(1),parentSessionId:exports_external.string().min(1),callID:exports_external.string(),normalizedAgent:exports_external.string(),swarmPrefixedAgent:exports_external.string(),planTaskId:exports_external.string().nullable(),evidenceTaskId:exports_external.string().nullable(),status:exports_external.enum(["pending","running","ingestion_error","completed","error","cancelled","stale","consumed"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),batchId:exports_external.string().optional(),laneId:exports_external.string().optional(),mode:exports_external.string().optional(),workflowLane:exports_external.string().optional(),ownedWorkflowLanes:exports_external.array(exports_external.string().min(1).max(120)).min(1).max(11).optional(),promptHash:exports_external.string().optional(),workspace:WorkspaceSchema.optional(),taskChangeContext:TaskChangeContextSchema.optional(),prompt:PromptSchema.optional(),generation:exports_external.number().optional(),result:ResultSchema.optional(),completedAt:exports_external.number().optional()}).strict()});var exports_workspace_snapshot={};__export(exports_workspace_snapshot,{workspaceSnapshotMatches:()=>workspaceSnapshotMatches,resolveRemoteRefsContainingHead:()=>resolveRemoteRefsContainingHead,resolvePrWorkflowRevisionDigestAsync:()=>resolvePrWorkflowRevisionDigestAsync,resolvePrWorkflowRevisionDigest:()=>resolvePrWorkflowRevisionDigest,resolvePrReviewDiffStats:()=>resolvePrReviewDiffStats,resolveIsWorkingTreeClean:()=>resolveIsWorkingTreeClean,resolveIsExactSingleChildCommit:()=>resolveIsExactSingleChildCommit,resolveGitControlStateDigest:()=>resolveGitControlStateDigest,resolveExactRemoteBranchHead:()=>resolveExactRemoteBranchHead,resolveExactMergeBase:()=>resolveExactMergeBase,resolveCurrentUpstreamRemoteRef:()=>resolveCurrentUpstreamRemoteRef,resolveCurrentUpstreamPushTarget:()=>resolveCurrentUpstreamPushTarget,resolveCurrentGitHead:()=>resolveCurrentGitHead,resolveCommitCountSince:()=>resolveCommitCountSince,readGitTextAtRevision:()=>readGitTextAtRevision,parsePorcelainPaths:()=>parsePorcelainPaths,digest:()=>digest,compareWorkspaceSnapshots:()=>compareWorkspaceSnapshots,compareWorkspaceSnapshot:()=>compareWorkspaceSnapshot,changedFilesSinceSnapshot:()=>changedFilesSinceSnapshot,captureWorkspaceSnapshot:()=>captureWorkspaceSnapshot,_internals:()=>_internals6});import*as child_process from"node:child_process";import{createHash as createHash4}from"node:crypto";import*as fs7 from"node:fs";import*as path10 from"node:path";function runGit(directory,args2,timeoutMs=GIT_SNAPSHOT_TIMEOUT_MS){let result=_internals6.spawnSync("git",["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0)return null;return typeof result.stdout==="string"?result.stdout.trimEnd():null}async function runGitAsync(directory,args2,timeoutMs=GIT_SNAPSHOT_TIMEOUT_MS){return await new Promise((resolve7)=>{let settled=!1,stdout="",stderrBytes=0,timeout,child,finish=(value)=>{if(settled)return;if(settled=!0,timeout)clearTimeout(timeout);try{child?.kill()}catch{}resolve7(value)};try{child=child_process.spawn("git",["-C",directory,...args2],{cwd:directory,stdio:["ignore","pipe","pipe"],windowsHide:!0})}catch{finish(null);return}timeout=setTimeout(()=>finish(null),timeoutMs),child.stdout?.setEncoding("utf-8"),child.stdout?.on("data",(chunk)=>{if(stdout+=chunk,Buffer.byteLength(stdout,"utf-8")>GIT_SNAPSHOT_MAX_BUFFER)finish(null)}),child.stderr?.on("data",(chunk)=>{if(stderrBytes+=chunk.length,stderrBytes>GIT_SNAPSHOT_MAX_BUFFER)finish(null)}),child.once("error",()=>finish(null)),child.once("close",(code)=>finish(code===0?stdout.trimEnd():null))})}function readGitTextAtRevision(directory,revision,relativePath){if(!isSafeGitRevisionToken(revision)||!/^\.?(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)*[A-Za-z0-9][A-Za-z0-9._-]*$/.test(relativePath)||relativePath.split("/").includes(".."))return null;let result=_internals6.spawnSync("git",["-C",directory,"show",`${revision}:${relativePath}`],{cwd:directory,encoding:"utf-8",timeout:GIT_SNAPSHOT_TIMEOUT_MS,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0||typeof result.stdout!=="string")return null;return result.stdout}function resolveCurrentGitHead(directory){return runGit(directory,["rev-parse","--verify","HEAD^{commit}"])}function resolveExactMergeBase(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=runGit(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}function resolvePrReviewDiffStats(directory,baseSha,prHeadSha){if(!isSafeGitRevisionToken(baseSha)||!isSafeGitRevisionToken(prHeadSha))return null;let range=`${baseSha}...${prHeadSha}`,output=runGit(directory,["diff","--no-renames","--numstat",range]);if(output===null)return null;let changedLines=0,changedFiles=0;for(let line of output.split(`
168
+ `,"utf-8")}async function recordPendingDelegation(directory,input,options={}){let now=Date.now(),record2={schemaVersion:input.batchId?2:1,correlationId:input.correlationId,jobId:input.jobId,subagentSessionId:input.subagentSessionId,parentSessionId:input.parentSessionId,callID:input.callID,normalizedAgent:input.normalizedAgent,swarmPrefixedAgent:input.swarmPrefixedAgent,planTaskId:input.planTaskId,evidenceTaskId:input.evidenceTaskId,status:"pending",createdAt:now,updatedAt:now,...input.batchId?{batchId:input.batchId}:{},...input.laneId?{laneId:input.laneId}:{},...input.mode?{mode:input.mode}:{},...input.workflowLane?{workflowLane:input.workflowLane}:{},...input.ownedWorkflowLanes?.length?{ownedWorkflowLanes:[...input.ownedWorkflowLanes]}:{},...input.promptHash?{promptHash:input.promptHash}:{},...input.workspace?{workspace:input.workspace}:{},...input.taskChangeContext?{taskChangeContext:input.taskChangeContext}:{},...input.prompt?{prompt:input.prompt}:{},...input.generation!==void 0?{generation:input.generation}:{}};try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(options.staleTimeoutMs&&options.staleTimeoutMs>0)sweepStaleLocked(directory,options.staleTimeoutMs,now);appendRecord(directory,record2)}),record2}catch(err){return warn(`[background] recordPendingDelegation failed: ${err instanceof Error?err.message:String(err)}`),null}}function buildPromptSnapshot(text,maxChars){let boundedMax=Math.max(0,Math.min(maxChars,20000)),truncated=text.length>boundedMax;return{text:truncated?text.slice(0,boundedMax):text,chars:text.length,truncated,digest:createHash3("sha256").update(text).digest("hex")}}async function appendDelegationTransition(directory,correlationId,transition){let now=Date.now();try{let next=null;return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let current=findByCorrelationId(directory,correlationId);if(!current)return;if(isTerminal(current.status)&&transition.status!=="consumed"&&transition.status!=="ingestion_error"){next=current;return}next={...current,schemaVersion:current.schemaVersion===1?2:current.schemaVersion,status:transition.status,updatedAt:now,...transition.completedAt!==void 0?{completedAt:transition.completedAt}:transition.status==="completed"||transition.status==="error"?{completedAt:now}:{},...transition.result?{result:transition.result}:{}},appendRecord(directory,next)}),next}catch(err){return warn(`[background] appendDelegationTransition failed: ${err instanceof Error?err.message:String(err)}`),null}}function findByBatchId(directory,batchId,opts){if(!batchId)return[];return readDelegations(directory).filter((record2)=>record2.batchId===batchId&&(opts?.parentSessionId===void 0||record2.parentSessionId===opts.parentSessionId))}function findOpenAsyncLaneBatches(directory){return readDelegations(directory).filter((record2)=>record2.batchId!==void 0&&(record2.status==="pending"||record2.status==="running"))}function isTerminal(status){return status==="completed"||status==="error"||status==="cancelled"||status==="stale"||status==="consumed"}function sweepStaleLocked(directory,timeoutMs,now){let swept=0;for(let record2 of readDelegations(directory)){if(record2.status!=="pending"&&record2.status!=="running"&&record2.status!=="ingestion_error")continue;if(now-record2.updatedAt<=timeoutMs)continue;appendRecord(directory,{...record2,status:"stale",updatedAt:now}),swept+=1}return swept}async function sweepStaleDelegations(directory,timeoutMs){if(!timeoutMs||timeoutMs<=0)return 0;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>sweepStaleLocked(directory,timeoutMs,Date.now()))}catch(err){return warn(`[background] sweepStaleDelegations failed: ${err instanceof Error?err.message:String(err)}`),0}}var BACKGROUND_DELEGATIONS_FILE="background-delegations.jsonl",STORE_LOCK_AGENT="background",STORE_LOCK_TASK="background-delegations",ResultSchema,WorkspaceSchema,TaskChangeContextSchema,PromptSchema,RecordSchema;var init_pending_delegations=__esm(()=>{init_zod();init_lock();init_utils2();init_logger();ResultSchema=exports_external.object({text:exports_external.string().optional(),error:exports_external.string().optional(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string(),outputRef:exports_external.string().optional(),outputPreviewChars:exports_external.number().optional(),outputDegraded:exports_external.boolean().optional(),outputArtifactError:exports_external.string().optional(),transcriptIncomplete:exports_external.boolean().optional(),messageCount:exports_external.number().optional()}).strict(),WorkspaceSchema=exports_external.object({directory:exports_external.string(),gitHead:exports_external.string().nullable(),dirtyHash:exports_external.string().nullable(),changedFiles:exports_external.array(exports_external.string()).nullable().optional(),prHeadSha:exports_external.string().nullable(),scope:exports_external.string().nullable()}).strict(),TaskChangeContextSchema=exports_external.object({declaredFiles:exports_external.array(exports_external.string()).nullable(),baseline:WorkspaceSchema}).strict(),PromptSchema=exports_external.object({text:exports_external.string(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string()}).strict(),RecordSchema=exports_external.object({schemaVersion:exports_external.union([exports_external.literal(1),exports_external.literal(2)]),correlationId:exports_external.string().min(1),jobId:exports_external.string().nullable(),subagentSessionId:exports_external.string().min(1),parentSessionId:exports_external.string().min(1),callID:exports_external.string(),normalizedAgent:exports_external.string(),swarmPrefixedAgent:exports_external.string(),planTaskId:exports_external.string().nullable(),evidenceTaskId:exports_external.string().nullable(),status:exports_external.enum(["pending","running","ingestion_error","completed","error","cancelled","stale","consumed"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),batchId:exports_external.string().optional(),laneId:exports_external.string().optional(),mode:exports_external.string().optional(),workflowLane:exports_external.string().optional(),ownedWorkflowLanes:exports_external.array(exports_external.string().min(1).max(120)).min(1).max(11).optional(),promptHash:exports_external.string().optional(),workspace:WorkspaceSchema.optional(),taskChangeContext:TaskChangeContextSchema.optional(),prompt:PromptSchema.optional(),generation:exports_external.number().optional(),result:ResultSchema.optional(),completedAt:exports_external.number().optional()}).strict()});var exports_workspace_snapshot={};__export(exports_workspace_snapshot,{workspaceSnapshotMatches:()=>workspaceSnapshotMatches,resolveRemoteRefsContainingHeadAsync:()=>resolveRemoteRefsContainingHeadAsync,resolveRemoteRefsContainingHead:()=>resolveRemoteRefsContainingHead,resolvePrWorkflowRevisionDigestAsync:()=>resolvePrWorkflowRevisionDigestAsync,resolvePrWorkflowRevisionDigest:()=>resolvePrWorkflowRevisionDigest,resolvePrReviewDiffStatsAsync:()=>resolvePrReviewDiffStatsAsync,resolvePrReviewDiffStats:()=>resolvePrReviewDiffStats,resolveIsWorkingTreeCleanAsync:()=>resolveIsWorkingTreeCleanAsync,resolveIsWorkingTreeClean:()=>resolveIsWorkingTreeClean,resolveIsExactSingleChildCommitAsync:()=>resolveIsExactSingleChildCommitAsync,resolveIsExactSingleChildCommit:()=>resolveIsExactSingleChildCommit,resolveGitControlStateDigestAsync:()=>resolveGitControlStateDigestAsync,resolveGitControlStateDigest:()=>resolveGitControlStateDigest,resolveExactRemoteBranchHeadAsync:()=>resolveExactRemoteBranchHeadAsync,resolveExactRemoteBranchHead:()=>resolveExactRemoteBranchHead,resolveExactMergeBaseAsync:()=>resolveExactMergeBaseAsync,resolveExactMergeBase:()=>resolveExactMergeBase,resolveCurrentUpstreamRemoteRef:()=>resolveCurrentUpstreamRemoteRef,resolveCurrentUpstreamPushTargetAsync:()=>resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamPushTarget:()=>resolveCurrentUpstreamPushTarget,resolveCurrentGitHeadAsync:()=>resolveCurrentGitHeadAsync,resolveCurrentGitHead:()=>resolveCurrentGitHead,resolveCommitCountSinceAsync:()=>resolveCommitCountSinceAsync,resolveCommitCountSince:()=>resolveCommitCountSince,readGitTextAtRevision:()=>readGitTextAtRevision,parsePorcelainPaths:()=>parsePorcelainPaths,digest:()=>digest,compareWorkspaceSnapshots:()=>compareWorkspaceSnapshots,compareWorkspaceSnapshot:()=>compareWorkspaceSnapshot,changedFilesSinceSnapshot:()=>changedFilesSinceSnapshot,captureWorkspaceSnapshot:()=>captureWorkspaceSnapshot,_internals:()=>_internals6});import*as child_process from"node:child_process";import{createHash as createHash4}from"node:crypto";import*as fs7 from"node:fs";import*as path10 from"node:path";function runGit(directory,args2,timeoutMs=GIT_SNAPSHOT_TIMEOUT_MS){let result=_internals6.spawnSync("git",["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0)return null;return typeof result.stdout==="string"?result.stdout.trimEnd():null}async function runGitAsync(directory,args2,timeoutMs=GIT_SNAPSHOT_TIMEOUT_MS){return await new Promise((resolve7)=>{let settled=!1,stdout="",stderrBytes=0,timeout,child,finish=(value)=>{if(settled)return;if(settled=!0,timeout)clearTimeout(timeout);try{child?.kill()}catch{}resolve7(value)};try{child=child_process.spawn("git",["-C",directory,...args2],{cwd:directory,stdio:["ignore","pipe","pipe"],windowsHide:!0})}catch{finish(null);return}timeout=setTimeout(()=>finish(null),timeoutMs),child.stdout?.setEncoding("utf-8"),child.stdout?.on("data",(chunk)=>{if(stdout+=chunk,Buffer.byteLength(stdout,"utf-8")>GIT_SNAPSHOT_MAX_BUFFER)finish(null)}),child.stderr?.on("data",(chunk)=>{if(stderrBytes+=chunk.length,stderrBytes>GIT_SNAPSHOT_MAX_BUFFER)finish(null)}),child.once("error",()=>finish(null)),child.once("close",(code)=>finish(code===0?stdout.trimEnd():null))})}function readGitTextAtRevision(directory,revision,relativePath){if(!isSafeGitRevisionToken(revision)||!/^\.?(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)*[A-Za-z0-9][A-Za-z0-9._-]*$/.test(relativePath)||relativePath.split("/").includes(".."))return null;let result=_internals6.spawnSync("git",["-C",directory,"show",`${revision}:${relativePath}`],{cwd:directory,encoding:"utf-8",timeout:GIT_SNAPSHOT_TIMEOUT_MS,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0||typeof result.stdout!=="string")return null;return result.stdout}function resolveCurrentGitHead(directory){return runGit(directory,["rev-parse","--verify","HEAD^{commit}"])}async function resolveCurrentGitHeadAsync(directory){return await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"])}function resolveExactMergeBase(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=runGit(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}async function resolveExactMergeBaseAsync(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=await runGitAsync(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}function resolvePrReviewDiffStats(directory,baseSha,prHeadSha){if(!isSafeGitRevisionToken(baseSha)||!isSafeGitRevisionToken(prHeadSha))return null;let range=`${baseSha}...${prHeadSha}`,output=runGit(directory,["diff","--no-renames","--numstat",range]);if(output===null)return null;let changedLines=0,changedFiles=0;for(let line of output.split(`
169
169
  `)){let trimmed=line.trim();if(trimmed.length===0)continue;let fields=trimmed.split("\t");if(fields.length<3)return null;let added=fields[0]==="-"?0:Number.parseInt(fields[0],10),deleted=fields[1]==="-"?0:Number.parseInt(fields[1],10);if(Number.isNaN(added)||Number.isNaN(deleted))return null;changedFiles+=1,changedLines+=added+deleted}let rawOutput=runGit(directory,["diff","--raw",range]);if(rawOutput===null)return null;let hasSubmoduleChange=rawOutput.split(`
170
- `).some((line)=>GITLINK_MODE_PATTERN.test(line.trim()));return{changedLines,changedFiles,hasSubmoduleChange}}function isSafeGitRevisionToken(value){return/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")}function resolveCurrentUpstreamRemoteRef(directory){let upstream=runGit(directory,["rev-parse","--symbolic-full-name","@{upstream}"]);if(!upstream?.startsWith("refs/remotes/")||upstream.endsWith("/HEAD"))return null;return upstream}function resolveCurrentUpstreamPushTarget(directory){let localBranchRef=runGit(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=runGit(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}function resolveExactRemoteBranchHead(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=runGit(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}function resolveGitControlStateDigest(directory){let head=runGit(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=runGit(directory,["symbolic-ref","--quiet","HEAD"]),upstream=resolveCurrentUpstreamPushTarget(directory),refs=runGit(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=runGit(directory,["config","--null","--show-origin","--show-scope","--list"]),index=runGit(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}function resolveIsWorkingTreeClean(directory){let status=runGit(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}function resolveCommitCountSince(directory,baseHeadSha,currentHeadSha){let output=runGit(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}function resolveIsExactSingleChildCommit(directory,baseHeadSha,currentHeadSha){let base=runGit(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),current=runGit(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`]);if(!base||!current)return null;let commitAndParents=runGit(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}function resolveRemoteRefsContainingHead(directory,headSha){let output=runGit(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}function resolvePrWorkflowRevisionDigest(directory,baseHeadSha){let projectRoot=path10.resolve(directory),baseHead=runGit(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),diffNames=runGit(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha]),porcelain=runGit(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!baseHead||diffNames===null||porcelain===null)return null;let porcelainPaths=parsePorcelainPaths(porcelain);if(!porcelainPaths)return null;let changedPaths=[...new Set([...parseNulPaths(diffNames),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>REVISION_MAX_FILES)return null;let hash2=createHash4("sha256");hash2.update(`base\x00${baseHead}\x00`);let totalBytes=0;for(let relativePath of changedPaths){let resolvedPath=path10.resolve(projectRoot,relativePath),relativeToRoot=path10.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path10.isAbsolute(relativeToRoot))return null;hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=fs7.lstatSync(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return null}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${fs7.readlinkSync(resolvedPath)}\x00`);continue}catch{return null}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>REVISION_MAX_TOTAL_BYTES)return null;try{hash2.update(`file\x00${stats2.mode}\x00`),hash2.update(fs7.readFileSync(resolvedPath)),hash2.update("\x00")}catch{return null}}return hash2.digest("hex")}async function resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha){let projectRoot=path10.resolve(directory),[baseHead,diffNames,porcelain]=await Promise.all([runGitAsync(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),runGitAsync(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha]),runGitAsync(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])]);if(!baseHead||diffNames===null||porcelain===null)return null;let porcelainPaths=parsePorcelainPaths(porcelain);if(!porcelainPaths)return null;let changedPaths=[...new Set([...parseNulPaths(diffNames),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>REVISION_MAX_FILES)return null;let hash2=createHash4("sha256");hash2.update(`base\x00${baseHead}\x00`);let totalBytes=0,chunksSinceYield=0;for(let relativePath of changedPaths){let resolvedPath=path10.resolve(projectRoot,relativePath),relativeToRoot=path10.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path10.isAbsolute(relativeToRoot))return null;hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=await fs7.promises.lstat(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return null}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${await fs7.promises.readlink(resolvedPath)}\x00`);continue}catch{return null}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>REVISION_MAX_TOTAL_BYTES)return null;hash2.update(`file\x00${stats2.mode}\x00`);let handle;try{handle=await fs7.promises.open(resolvedPath,"r");let buffer=Buffer.allocUnsafe(REVISION_READ_CHUNK_BYTES);for(let position=0;position<stats2.size;){let length=Math.min(REVISION_READ_CHUNK_BYTES,stats2.size-position),{bytesRead}=await handle.read(buffer,0,length,position);if(bytesRead<=0)return null;if(hash2.update(buffer.subarray(0,bytesRead)),position+=bytesRead,chunksSinceYield++,chunksSinceYield>=REVISION_YIELD_EVERY_CHUNKS)chunksSinceYield=0,await _internals6.yieldControl()}hash2.update("\x00")}catch{return null}finally{await handle?.close().catch(()=>{return})}}return hash2.digest("hex")}function parseNulPaths(output){return output.split("\x00").filter((entry)=>entry.length>0)}function parsePorcelainPaths(output){let entries=parseNulPaths(output),paths=[];for(let index=0;index<entries.length;index++){let entry=entries[index];if(entry.length<4||entry[2]!==" ")return null;let status=entry.slice(0,2),changedPath=entry.slice(3);if(!changedPath)return null;if(paths.push(changedPath),status.includes("R")||status.includes("C")){let originalPath=entries[++index];if(!originalPath)return null;paths.push(originalPath)}}return[...new Set(paths)]}function parsePorcelainV2Snapshot(output){let records=output.split("\x00"),headers=[];while(records[0]?.startsWith("# "))headers.push(records.shift());let oidMatch=headers.join(`
171
- `).match(/^# branch\.oid (.+)$/m);if(!oidMatch)return null;let gitHead=/^[0-9a-f]{6,64}$/i.test(oidMatch[1])?oidMatch[1]:oidMatch[1]==="(initial)"?null:null,paths=[];for(let index=0;index<records.length;index++){let record2=records[index];if(!record2)continue;if(record2.startsWith("? ")){paths.push(record2.slice(2));continue}if(record2.startsWith("1 ")){let changedPath=porcelainV2PathAfterFields(record2,8);if(!changedPath)return null;paths.push(changedPath);continue}if(record2.startsWith("2 ")){let changedPath=porcelainV2PathAfterFields(record2,9),originalPath=records[++index];if(!changedPath||!originalPath)return null;paths.push(changedPath,originalPath);continue}if(record2.startsWith("u ")){let changedPath=porcelainV2PathAfterFields(record2,10);if(!changedPath)return null;paths.push(changedPath);continue}return null}return{gitHead,changedFiles:[...new Set(paths)]}}function porcelainV2PathAfterFields(record2,fields){let offset=0;for(let index=0;index<fields;index++){let delimiter=record2.indexOf(" ",offset);if(delimiter<0)return null;offset=delimiter+1}return record2.slice(offset)||null}function captureWorkspaceSnapshot(directory,optionsOrScope=null,prHeadShaArg=null){let scope=typeof optionsOrScope==="object"&&optionsOrScope!==null?optionsOrScope.scope??null:optionsOrScope,configuredPrHeadSha=(()=>{if(typeof optionsOrScope!=="object"||optionsOrScope===null)return prHeadShaArg;return optionsOrScope.prHeadSha??null})(),resolveCurrentPrHeadSha=typeof optionsOrScope==="object"&&optionsOrScope!==null&&optionsOrScope.resolveCurrentPrHeadSha===!0,upstreamBefore=resolveCurrentPrHeadSha?runGit(directory,["rev-parse","@{upstream}"]):null,porcelain=runGit(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),snapshot=porcelain===null?null:parsePorcelainV2Snapshot(porcelain),upstreamAfter=resolveCurrentPrHeadSha?runGit(directory,["rev-parse","@{upstream}"]):null,prHeadSha=resolveCurrentPrHeadSha?upstreamBefore&&upstreamBefore===upstreamAfter?upstreamBefore:null:configuredPrHeadSha;return{directory:path10.resolve(directory),gitHead:snapshot?.gitHead??null,dirtyHash:porcelain===null?null:digest(porcelain),changedFiles:snapshot?.changedFiles??null,prHeadSha,scope}}function changedFilesSinceSnapshot(directory,baseline){if(!baseline?.gitHead||baseline.changedFiles==null)return null;if(baseline.changedFiles.length>0)return null;let current=captureWorkspaceSnapshot(directory);if(!current.gitHead||current.changedFiles==null)return null;let changed=new Set(current.changedFiles);if(baseline.gitHead!==current.gitHead){let committed=runGit(directory,["diff","--name-only","-z",baseline.gitHead,current.gitHead]);if(committed===null)return null;for(let changedPath of parseNulPaths(committed))changed.add(changedPath)}return[...changed]}function workspaceSnapshotMatches(expected,current){if(!expected)return{ok:!0};if(path10.resolve(expected.directory)!==path10.resolve(current.directory))return{ok:!1,reason:`directory changed: expected ${expected.directory}, got ${current.directory}`};let checks3=["gitHead","dirtyHash","prHeadSha"];for(let key of checks3){let expectedValue=expected[key];if(expectedValue===null)continue;if(current[key]!==expectedValue)return{ok:!1,reason:`${key} changed: expected ${expectedValue}, got ${current[key]??"unknown"}`}}return{ok:!0}}function compareWorkspaceSnapshots(expected,current){let result=workspaceSnapshotMatches(expected,current);if(result.ok)return{stale:!1};return{stale:!0,reason:result.reason}}function digest(text){return createHash4("sha256").update(text).digest("hex")}var GIT_SNAPSHOT_TIMEOUT_MS=3000,GIT_SNAPSHOT_MAX_BUFFER=524288,REVISION_MAX_FILES=5000,REVISION_MAX_TOTAL_BYTES=67108864,REVISION_READ_CHUNK_BYTES=65536,REVISION_YIELD_EVERY_CHUNKS=16,GITLINK_MODE_PATTERN,compareWorkspaceSnapshot,_internals6;var init_workspace_snapshot=__esm(()=>{GITLINK_MODE_PATTERN=/^:\d{6} 160000 |^:160000 \d{6} /;compareWorkspaceSnapshot=workspaceSnapshotMatches;_internals6={spawnSync:child_process.spawnSync,yieldControl:()=>new Promise((resolve7)=>setImmediate(resolve7)),parsePorcelainV2Snapshot}});import{createHash as createHash5,randomUUID as randomUUID2}from"node:crypto";import{readFileSync as readFileSync6}from"node:fs";import*as fsp2 from"node:fs/promises";import*as path11 from"node:path";function computePrReviewDepthTier(stats2){if(!stats2)return"L";if(stats2.hasSubmoduleChange)return"L";if(stats2.changedLines<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.smallMaxChangedLines&&stats2.changedFiles<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.smallMaxChangedFiles)return"S";if(stats2.changedLines<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.mediumMaxChangedLines&&stats2.changedFiles<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.mediumMaxChangedFiles)return"M";return"L"}async function activatePrWorkflow(directory,sessionID,mode,options={}){let normalizedSessionID=normalizeSessionID(sessionID),existing=await readPrWorkflowGateState(directory,normalizedSessionID);if(existing?.mode===mode)return options.prHeadSha?bindPrWorkflowHead(directory,normalizedSessionID,options.prHeadSha):existing;if(existing)throw Error(`BLOCKED: session "${normalizedSessionID}" already has an active ${existing.mode} workflow; complete it before starting ${mode}`);let initialHead=options.prHeadSha?assertCurrentCheckoutHead(directory,options.prHeadSha):void 0,timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:0,sessionID:normalizedSessionID,mode,activatedAt:timestamp,updatedAt:timestamp,...initialHead?{prHeadSha:initialHead}:{}};return await persistState(directory,nextState),nextState}async function readPrWorkflowGateState(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),state=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(state)rememberState(directory,state);else trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID));return state}async function withPrWorkflowCheckoutPreparationLock(directory,sessionID,action){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizedSessionID}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (which activates PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (which activates PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*". Run the appropriate command first, then retry checkout preparation.`);if(state.prHeadSha)throw Error(`BLOCKED: ${state.mode} checkout preparation is allowed only before the PR head is bound`);return action(state)})}async function clearPrWorkflowGateState(directory,sessionID,expectedRevision){let normalizedSessionID=normalizeSessionID(sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{if(expectedRevision!==void 0){let current=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(!current||current.revision!==expectedRevision)throw Error("BLOCKED: PR workflow gate state changed during terminal completion; revalidate the current session state before retrying")}try{await fsp2.rm(workflowGateStatePath(directory,normalizedSessionID),{force:!0})}catch(error49){if(error49.code!=="ENOENT")throw error49}trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID))})}async function abortPrWorkflow(directory,sessionID,options={}){let state=await requireAnyActiveState(directory,sessionID);if(options.expectedMode&&state.mode!==options.expectedMode)throw wrongModeError(state,options.expectedMode);if(state.prFeedbackReadyToPublish)throw Error(`BLOCKED: ${state.mode} is armed for publication; abort is blocked. Complete the workflow with complete_pr_workflow (or push the bound commit first) before aborting.`);let openLanes=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(openLanes.length>0){let laneIds=openLanes.map((record2)=>record2.laneId??record2.subagentSessionId??"unknown").filter(Boolean).slice(0,10).join(", ");throw Error(`BLOCKED: ${state.mode} abort refused while ${openLanes.length} PR workflow lane(s) are still in flight (lane ids: ${laneIds}). Collect their results or let them settle before aborting.`)}let sanitizedReason=typeof options.reason==="string"?options.reason.trim().slice(0,500):void 0,abortEvent={type:"pr_workflow_aborted",timestamp:isoNow(),sessionID:state.sessionID,mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:openLanes.length,...sanitizedReason?{reason:sanitizedReason}:{}};try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp2.appendFile(eventsPath,`${JSON.stringify(abortEvent)}
172
- `,"utf-8")}catch{}return await clearPrWorkflowGateState(directory,sessionID,state.revision),{mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:openLanes.length}}async function bindPrWorkflowHead(directory,sessionID,prHeadSha){let state=await requireAnyActiveState(directory,sessionID),normalizedHead=normalizePrHeadSha(prHeadSha);if(assertCurrentCheckoutHead(directory,normalizedHead),!state.prHeadSha)assertPrReviewCleanCheckout(directory,state.mode);if(!state.prHeadSha&&state.mode==="PR_FEEDBACK")assertPrFeedbackTrackingCheckout(directory,normalizedHead);if(state.prHeadSha&&state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: active ${state.mode} workflow is bound to PR head "${state.prHeadSha}"; received "${normalizedHead}"`);if(state.prHeadSha===normalizedHead)return state;let nextState={...state,prHeadSha:normalizedHead,updatedAt:isoNow()};return await persistState(directory,nextState),nextState}async function bindPrReviewBase(directory,sessionID,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw Error("BLOCKED: only PR_REVIEW can bind a review merge base");let baseRef=options.baseRef.trim(),baseSha=normalizePrHeadSha(options.baseSha).toLowerCase();if(!baseRef)throw Error("BLOCKED: PR_REVIEW base_ref must not be empty");if(state.prReviewBaseRef&&state.prReviewBaseRef!==baseRef||state.prReviewBaseSha&&state.prReviewBaseSha!==baseSha)throw Error(`BLOCKED: active PR_REVIEW is bound to merge-base scope "${state.prReviewBaseRef??"(unbound)"}" at "${state.prReviewBaseSha??"(unbound)"}"; received "${baseRef}" at "${baseSha}"`);if(state.prReviewBaseRef===baseRef&&state.prReviewBaseSha===baseSha)return state;let prHeadSha=normalizePrHeadSha(options.prHeadSha).toLowerCase(),diffStats=_test_exports.resolvePrReviewDiffStats(directory,baseSha,prHeadSha);return state={...state,prReviewBaseRef:baseRef,prReviewBaseSha:baseSha,prReviewDepthTier:computePrReviewDepthTier(diffStats),...diffStats?{prReviewDiffStats:diffStats}:{},updatedAt:isoNow()},await persistState(directory,state),state}function assertCurrentCheckoutHead(directory,expectedHead){let normalizedExpected=normalizePrHeadSha(expectedHead),currentHead=_test_exports.resolveCurrentGitHead(directory)?.trim();if(!currentHead)throw Error(`BLOCKED: cannot resolve the current Git HEAD in "${directory}" to verify against PR head "${normalizedExpected}". This means Git could not resolve HEAD (the working directory may not be a Git repository, HEAD may be unborn, the commit object may be missing in a shallow clone, the Git binary may not be on PATH, or the bounded Git invocation may have timed out). Verify with: git -C "${directory}" rev-parse --verify HEAD^{commit}`);if(currentHead.toLowerCase()!==normalizedExpected.toLowerCase())throw Error(`BLOCKED: current checkout HEAD "${currentHead}" does not match PR head "${normalizedExpected}" (working directory: "${directory}"). Check out the exact PR head with: git -C "${directory}" switch --detach ${normalizedExpected}`);return normalizedExpected}function assertPrReviewCleanCheckout(directory,mode="PR_REVIEW"){if(_test_exports.resolveIsWorkingTreeClean(directory)!==!0)throw Error(`BLOCKED: ${mode} requires a clean index and working tree at the exact PR head`)}function assertPrFeedbackTrackingCheckout(directory,prHeadSha){let upstream=_test_exports.resolveCurrentUpstreamPushTarget(directory);if(!upstream)throw Error("BLOCKED: PR_FEEDBACK requires a current local branch bound to an exact remote name, remote branch ref, and remote-tracking ref before the first head bind; detached or non-tracking checkouts are not allowed");if(!_test_exports.resolveRemoteRefsContainingHead(directory,prHeadSha)?.includes(upstream.remoteTrackingRef))throw Error(`BLOCKED: PR_FEEDBACK upstream "${upstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}" before the first head bind`)}async function enforcePrWorkflowDispatchLanesAsync(directory,sessionID,toolName){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return null;if(toolName===DISPATCH_TOOL_NAME)return state;if(toolName===BLOCKING_DISPATCH_TOOL_NAME)throw Error(`BLOCKED: active ${state.mode} workflow for session "${state.sessionID}" requires ${DISPATCH_TOOL_NAME}; ${BLOCKING_DISPATCH_TOOL_NAME} is not allowed`);return state}async function enforcePrReviewBaseDimensions(directory,sessionID,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");let normalizedLanes=normalizeWorkflowLanes(lanes),claimedDimensionIds=normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]);if(claimedDimensionIds.filter((laneId)=>!PR_REVIEW_BASE_DIMENSION_IDS.includes(laneId)).length>0){let expected=PR_REVIEW_BASE_DIMENSION_IDS.join(", "),received=claimedDimensionIds.join(", ")||"(none)";throw Error(`BLOCKED: PR_REVIEW base dispatch lane ids must be drawn from: ${expected}. Received: ${received}`)}if((state.prReviewDepthTier??"L")==="L"&&normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier L requires one dedicated lane per dimension; consolidated owned_workflow_lanes are allowed only at tiers S and M");let batchId=normalizeBatchId(options.batchId),previous=state.prReviewBaseDispatches??[];if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW base batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW base batch limit reached");let record2={batchId,lanes:normalizedLanes.map((lane)=>({laneId:lane.laneId,workflowLane:lane.workflowLane,...lane.ownedWorkflowLanes?{ownedWorkflowLanes:lane.ownedWorkflowLanes}:{}})),validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prReviewBaseDispatches:[...previous,record2],prReviewBaseDispatch:record2};return await persistState(directory,nextState),nextState}async function assertPrReviewBaseCoverageSettled(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),batches=state.prReviewBaseDispatches??[];if(batches.length===0)throw Error("BLOCKED: PR_REVIEW requires at least one base batch");let covered=new Set;for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt);for(let obligation of successful)covered.add(obligation)}let missing=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!covered.has(dimension));if(missing.length>0||covered.size!==PR_REVIEW_BASE_DIMENSION_IDS.length)throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete; missing dimensions: ${missing.join(", ")||"(none)"}`);return state}async function recordPrReviewValidationBatch(directory,sessionID,phase,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW validation dispatch requires a completed trigger evaluation");if(phase==="reviewer"&&(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state=await assertPrReviewValidationSettled(directory,sessionID,"council");else if(phase==="critic")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer");let normalizedLanes=normalizeWorkflowLanes(lanes);if((phase==="reviewer"||phase==="critic")&&normalizedLanes.some((lane)=>!lane.reviewItemIds?.length))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes require non-empty review_item_ids ownership`);if(phase==="reviewer"||phase==="critic"){assertNoDuplicates(normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),`PR_REVIEW ${phase} review item ownership`);let assigned=normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),required2=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state):derivePrReviewCriticInventory(directory,state);assertExactStringSet(assigned,required2,`PR_REVIEW ${phase} ownership`)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewValidationBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW validation batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached");let record2={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"):previous,nextState={...state,updatedAt:isoNow(),prReviewValidationBatches:[...retained,record2]};return await persistState(directory,nextState),nextState}async function assertPrReviewValidationSettled(directory,sessionID,phase){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),declaredPhases=new Set((state.prReviewValidationBatches??[]).map((batch)=>batch.phase)),phases=phase?[phase]:["council","reviewer","critic"].filter((candidate)=>declaredPhases.has(candidate));for(let requiredPhase of phases){let validationBatches=state.prReviewValidationBatches??[],forbiddenSubagentSessionIds=new Set;if(requiredPhase==="critic")for(let reviewerBatch of validationBatches.filter((batch)=>batch.phase==="reviewer"))for(let record2 of findByBatchId(directory,reviewerBatch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)forbiddenSubagentSessionIds.add(subagentSessionId)}let batches=validationBatches.filter((batch)=>batch.phase===requiredPhase);if(requiredPhase==="reviewer"){let latestCouncilIndex=-1;for(let index=0;index<validationBatches.length;index++)if(validationBatches[index]?.phase==="council")latestCouncilIndex=index;if(latestCouncilIndex>=0)batches=validationBatches.slice(latestCouncilIndex+1).filter((batch)=>batch.phase==="reviewer")}if(batches.length===0)throw Error(requiredPhase==="reviewer"&&declaredPhases.has("council")?"BLOCKED: PR_REVIEW requires at least one reviewer batch after the latest council batch":`BLOCKED: PR_REVIEW requires at least one ${requiredPhase} batch`);let allObligations=new Set(batches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane))),settled=new Set,hasFullySuccessfulExactBatch=!1;for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${requiredPhase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds);if(successful.size===batch.lanes.length&&batch.lanes.every((lane)=>successful.has(lane.workflowLane)))hasFullySuccessfulExactBatch=!0;for(let obligation of successful)settled.add(obligation)}if((requiredPhase==="reviewer"||requiredPhase==="critic")&&!hasFullySuccessfulExactBatch)throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} requires one fully successful exact batch; complementary partial retries are not a coherent verdict set`);let missing=[...allObligations].filter((obligation)=>!settled.has(obligation));if(missing.length>0)throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} obligations lack successful exact artifacts: ${missing.join(", ")}`)}return state}async function declarePrFeedbackInventory(directory,sessionID,inventoryIds,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let normalizedInventory=normalizeInventoryIds(inventoryIds);if(state.prFeedbackInventory){if(!sameStringArray(state.prFeedbackInventory,normalizedInventory))throw Error("BLOCKED: PR_FEEDBACK inventory is immutable after declaration");return state}let nextState={...state,updatedAt:isoNow(),prFeedbackInventory:normalizedInventory,prFeedbackVerifications:[]};return await persistState(directory,nextState),nextState}async function enforcePrFeedbackVerificationOwnership(directory,sessionID,ownership,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory||inventory.length===0)throw Error(`BLOCKED: PR_FEEDBACK verification for session "${state.sessionID}" requires a declared feedback inventory before dispatch`);let normalizedOwnership=normalizeOwnership(ownership),inventorySet=new Set(inventory),claimedByItemId=new Map,previous=state.prFeedbackVerifications??[],batchId=normalizeBatchId(options.batchId);if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK verification batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached");for(let record3 of previous)for(let lane of record3.ownership)for(let itemId of lane.ownedItemIds)claimedByItemId.set(itemId,lane.laneId);for(let lane of normalizedOwnership)for(let itemId of lane.ownedItemIds){if(!inventorySet.has(itemId))throw Error(`BLOCKED: PR_FEEDBACK verification lane "${lane.laneId}" owns undeclared item "${itemId}"`);let previousLane=claimedByItemId.get(itemId);if(previousLane&&previousLane!==lane.laneId)throw Error(`BLOCKED: PR_FEEDBACK verification item "${itemId}" is owned by both "${previousLane}" and "${lane.laneId}"`);claimedByItemId.set(itemId,lane.laneId)}let record2={batchId,ownership:normalizedOwnership,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackVerifications:[...previous,record2],prFeedbackVerification:record2};return await persistState(directory,nextState),nextState}async function assertPrFeedbackVerificationSettled(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state),inventory=state.prFeedbackInventory,batches=state.prFeedbackVerifications??[];if(!inventory||batches.length===0)throw Error("BLOCKED: PR_FEEDBACK requires an immutable inventory and verification batches");let covered=new Set;for(let batch of batches){let successfulLaneIds=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.ownership.map((lane)=>({laneId:lane.laneId,workflowLane:lane.laneId})),"swarm-pr-feedback:verification",batch.validatedAt,!1,new Set,currentDigest);for(let lane of batch.ownership){if(!successfulLaneIds.has(lane.laneId))continue;if(!feedbackArtifactCoversItems(directory,state,batch.batchId,lane.laneId,lane.ownedItemIds))continue;for(let itemId of lane.ownedItemIds)covered.add(itemId)}}let missing=inventory.filter((itemId)=>!covered.has(itemId));if(missing.length>0||covered.size!==inventory.length)throw Error(`BLOCKED: PR_FEEDBACK verification ownership is incomplete; missing inventory items: ${missing.join(", ")||"(none)"}`);return state}async function recordPrFeedbackStageA(directory,sessionID,revisionDigest,checks3,options={}){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK Stage A receipt is stale because the working-tree revision changed during validation");if(checks3.length<2||checks3.length>258)throw Error("BLOCKED: PR_FEEDBACK Stage A requires two to 258 controller-created check receipts");let optionalCategoryOrder=["build","typecheck","lint"],applicableCategories=options.applicableCategories??optionalCategoryOrder.filter((category)=>checks3.some((check2)=>check2.category===category));if(assertNoDuplicates(applicableCategories,"PR_FEEDBACK Stage A applicable categories"),applicableCategories.some((category)=>!optionalCategoryOrder.includes(category)))throw Error("BLOCKED: PR_FEEDBACK Stage A applicability may contain only build, typecheck, and lint");let required2=new Set(["diff-check","reproduction",...applicableCategories]),singletonSeen=new Set,applicableObligations=[...options.applicableObligations??[]];assertNoDuplicates(applicableObligations.map(({id})=>id),"PR_FEEDBACK Stage A applicable obligations");let requiredObligationIds=new Set(applicableObligations.map(({id})=>id)),commandDigests=new Set,reproductionFeedbackItemIds=[];for(let check2 of checks3){if(["diff-check","reproduction"].includes(check2.category)&&singletonSeen.has(check2.category))throw Error(`BLOCKED: PR_FEEDBACK Stage A contains duplicate category "${check2.category}"`);if(singletonSeen.add(check2.category),required2.delete(check2.category),check2.obligationId){let obligation=applicableObligations.find((candidate)=>candidate.id===check2.obligationId);if(!obligation||obligation.category!==check2.category||obligation.workingDirectory!==(check2.workingDirectory??".")||!requiredObligationIds.delete(check2.obligationId))throw Error(`BLOCKED: PR_FEEDBACK Stage A receipt does not match one exact applicable obligation: ${check2.obligationId}`);let sourceContract=obligation.source.includes(".pr-validation.json#")?{path:obligation.source.slice(0,obligation.source.lastIndexOf("#")),id:obligation.source.slice(obligation.source.lastIndexOf("#")+1)}:void 0,requiredContract=obligation.validatorContract??sourceContract;if(requiredContract&&(check2.validatorContract?.path!==requiredContract.path||check2.validatorContract.id!==requiredContract.id))throw Error(`BLOCKED: PR_FEEDBACK Stage A obligation ${obligation.id} requires exact validator contract provenance`)}let commandDigest=createHash5("sha256").update(`${check2.obligationId??check2.category}\x00${check2.workingDirectory??"."}\x00${check2.command.join("\x00")}`).digest("hex");if(commandDigests.has(commandDigest))throw Error("BLOCKED: PR_FEEDBACK Stage A cannot reuse one command as multiple check receipts");if(commandDigests.add(commandDigest),check2.category==="diff-check"&&!sameStringArray(check2.command,["git","diff","--check"]))throw Error("BLOCKED: PR_FEEDBACK Stage A diff-check receipt is not the exact git diff --check command");if(check2.category==="reproduction"&&(!check2.targets?.length||!check2.feedbackTargets?.length||check2.targets.some((target)=>!check2.command.join(" ").includes(target))))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction receipt requires exact selected targets");if(check2.category==="reproduction"){if(reproductionFeedbackItemIds=check2.feedbackTargets.map((mapping)=>mapping.feedbackItemId),assertNoDuplicates(reproductionFeedbackItemIds,"PR_FEEDBACK Stage A reproduction feedback item mappings"),check2.feedbackTargets.some((mapping)=>!check2.targets.includes(mapping.target)))throw Error("BLOCKED: PR_FEEDBACK Stage A feedback mappings must reference exact executed reproduction targets")}}if(required2.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing required checks: ${[...required2].join(", ")}`);if(requiredObligationIds.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing applicable workspace obligations: ${[...requiredObligationIds].join(", ")}`);if(!sameStringArray(reproductionFeedbackItemIds,state.prFeedbackInventory??[]))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction must map every immutable feedback item exactly once and in declared order");let nextState={...state,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks3],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:optionalCategoryOrder.filter((category)=>applicableCategories.includes(category)),applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:[],prFeedbackReadyToPublish:void 0};return await persistState(directory,nextState),nextState}async function recordPrFeedbackGateBatch(directory,sessionID,phase,lane,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory?.length)throw Error("BLOCKED: PR_FEEDBACK ordered gates require an immutable feedback inventory");let normalized=normalizeOwnership([lane])[0];if(!sameStringArray(normalized.ownedItemIds,inventory))throw Error(`BLOCKED: PR_FEEDBACK ${phase} must own every inventory item exactly once and in declared order`);let phaseIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(phase),prerequisite=PR_FEEDBACK_PHASE_ORDER[phaseIndex-1];if(prerequisite)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,prerequisite);let{prFeedbackStageA:stageA,prFeedbackInventory:refreshedInventory}=state,currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(!stageA||!refreshedInventory||stageA.revisionDigest!==currentDigest||!sameStringArray(stageA.feedbackItemIds??[],refreshedInventory)||options.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires fresh Stage A checks on the current revision`);let batchId=normalizeBatchId(options.batchId),previous=state.prFeedbackGateBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK gate batch id "${batchId}" is already recorded`);let retained=previous.filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<phaseIndex),record2={batchId,phase,laneId:normalized.laneId,itemIds:normalized.ownedItemIds,revisionDigest:currentDigest,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackGateBatches:[...retained,record2]};return await persistState(directory,nextState),nextState}async function assertPrFeedbackGatePhaseSettled(directory,sessionID,phase){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(state.prFeedbackStageA?.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} cannot use stale Stage A evidence`);if(!sameStringArray(state.prFeedbackStageA?.feedbackItemIds??[],state.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} Stage A reproduction is not bound to the exact immutable feedback inventory`);let batch=[...state.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===phase);if(!batch||batch.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} has no validation batch on the current revision`);if(!successfulObligationsFromExactBatch(directory,state,batch.batchId,[{laneId:batch.laneId,workflowLane:phase,reviewItemIds:batch.itemIds}],`swarm-pr-feedback:${phase}`,batch.validatedAt,!0,new Set,currentDigest).has(phase))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires one complete, non-degraded positive verdict row per inventory item`);if(findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===batch.laneId)?.workspace?.dirtyHash!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} artifact is not bound to the current revision digest`);return assertIndependentFeedbackGateSessions(directory,state,phase),state}function assertIndependentFeedbackGateSessions(directory,state,throughPhase){let throughIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(throughPhase),batches=(state.prFeedbackGateBatches??[]).filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<=throughIndex),seenSessions=new Set;for(let batch of batches){let matching=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).filter((record3)=>record3.laneId===batch.laneId);if(matching.length!==1)throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} must resolve from exactly one durable child session`);let record2=matching[0],expectedRole=PR_FEEDBACK_PHASE_ROLE[batch.phase];if(!(record2.normalizedAgent===expectedRole||expectedRole==="critic"&&record2.normalizedAgent.startsWith("critic_")))throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} requires role ${expectedRole}, received ${record2.normalizedAgent||"(unknown)"}`);if(seenSessions.has(record2.subagentSessionId))throw Error(`BLOCKED: PR_FEEDBACK independent phases reused child session "${record2.subagentSessionId}"`);seenSessions.add(record2.subagentSessionId)}}async function assertPrFeedbackReadyToPublish(directory,sessionID){let state=await assertPrFeedbackVerificationSettled(directory,sessionID);for(let phase of PR_FEEDBACK_PHASE_ORDER)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,phase);return state}async function assertPrFeedbackPublicationArmed(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),armed=state.prFeedbackReadyToPublish;if(!armed)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK changed after publication was armed; rerun Stage A and every independent gate");if(_test_exports.resolveCurrentGitHead(directory)?.trim()!==armed.localHead)throw Error("BLOCKED: PR_FEEDBACK current Git HEAD changed after publication was armed");if(_test_exports.resolveIsWorkingTreeClean(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK working tree changed after publication was armed");let currentTarget=_test_exports.resolveCurrentUpstreamPushTarget(directory);if(!currentTarget||currentTarget.remoteName!==armed.remoteName||currentTarget.remoteBranchRef!==armed.remoteBranchRef||currentTarget.remoteTrackingRef!==armed.remoteRef)throw Error("BLOCKED: PR_FEEDBACK upstream publication target changed after publication was armed");return state}async function markPrReviewTriggerEvaluationComplete(directory,sessionID,artifactPath){let state=await assertPrReviewBaseCoverageSettled(directory,sessionID),normalizedPath=artifactPath.trim();if(!normalizedPath)throw Error("BLOCKED: PR_REVIEW trigger artifact path is required");let nextState={...state,updatedAt:isoNow(),prReviewTriggerEvalPath:normalizedPath};return await persistState(directory,nextState),nextState}async function assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW findings persistence requires the trigger evaluation artifact");let persistedBoundaries=state.prReviewArtifactBoundaries??[],boundaryOrder=["post_explorer","post_reviewer","post_critic"],boundaryIndex=boundaryOrder.indexOf(boundary),requiredPriorBoundary=boundaryOrder[boundaryIndex-1];if(requiredPriorBoundary&&!persistedBoundaries.includes(requiredPriorBoundary))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings require the prior ${requiredPriorBoundary} checkpoint`);if(persistedBoundaries.some((persisted)=>boundaryOrder.indexOf(persisted)>boundaryIndex))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings cannot be persisted after a later checkpoint`);if(boundary==="post_reviewer")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer");else if(boundary==="post_critic"){if(await assertPrReviewValidationSettled(directory,sessionID,"reviewer"),derivePrReviewCriticInventory(directory,state).length>0)state=await assertPrReviewValidationSettled(directory,sessionID,"critic")}if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==runId)throw Error(`BLOCKED: PR_REVIEW artifacts are already bound to run "${state.prReviewArtifactRunId}"`);let expectedFindingIds=derivePrReviewCandidateInventory(directory,state),normalizedFindingIds=[...new Set(findingIds)].sort();if(normalizedFindingIds.length!==findingIds.length||JSON.stringify(normalizedFindingIds)!==JSON.stringify([...expectedFindingIds].sort()))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings must exactly cover the discovered candidate inventory`);return state}async function assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,boundary,records){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(boundary==="post_explorer"){for(let record2 of records)if(record2.status!=="PENDING"||record2.next_action!=="route_to_reviewer")throw Error(`BLOCKED: PR_REVIEW post_explorer record ${record2.finding_id} must remain PENDING and route_to_reviewer`);return}let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state),criticVerdicts=boundary==="post_critic"?deriveLatestPrReviewCriticVerdicts(directory,state):void 0;for(let record2 of records){let reviewer=reviewerVerdicts.get(record2.finding_id);if(!reviewer)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} has no authoritative reviewer verdict`);if(record2.severity&&record2.severity!==reviewer.severity)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} severity differs from its reviewer verdict`);let requiresCritic=reviewer.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(reviewer.severity);if(boundary==="post_reviewer"){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification;if(record2.status!==expectedStatus)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} status differs from its reviewer verdict`);let expectedAction=requiresCritic?"route_to_critic":reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} action does not match reviewer disposition`);continue}if(!requiresCritic){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification,expectedAction=reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.status!==expectedStatus||record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} cannot override its non-critic reviewer disposition`);continue}let critic=criticVerdicts?.get(record2.finding_id);if(!critic)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} has no authoritative critic verdict`);if(record2.severity&&record2.severity!==critic.severity)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} severity differs from its critic verdict`);if(critic.status==="DISPROVED"){if(record2.status!=="DISPROVED"||record2.next_action!=="suppress_with_reason")throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} must preserve the critic DISPROVED disposition`)}else if(record2.status!=="CONFIRMED"||!["report","handoff_to_feedback"].includes(record2.next_action))throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} action does not match its critic verdict`)}}async function markPrReviewArtifactBoundary(directory,sessionID,runId,boundary,artifactPath,findingIds,handoffRequired){let state=await assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds),boundaries=new Set(state.prReviewArtifactBoundaries??[]);boundaries.add(boundary);let nextState={...state,updatedAt:isoNow(),prReviewArtifactRunId:runId,prReviewFindingsPath:artifactPath,prReviewArtifactBoundaries:[...boundaries],prReviewHandoffRequired:handoffRequired};return await persistState(directory,nextState),nextState}async function markPrReviewHandoffComplete(directory,sessionID,runId,artifactPath){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(state.prReviewArtifactRunId!==runId||!(state.prReviewArtifactBoundaries??[]).includes("post_critic"))throw Error("BLOCKED: PR_REVIEW handoff requires the final findings boundary for the same run");let nextState={...state,updatedAt:isoNow(),prReviewHandoffPath:artifactPath};return await persistState(directory,nextState),nextState}async function declarePrFeedbackScope(directory,sessionID,taskId,files){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state),previous=state.prFeedbackScopes??[];if(previous.find((entry)=>entry.taskId===taskId)?.consumedByCallId)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed; use a fresh task_id for any retry`);let record2={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record2]};return await persistState(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_FEEDBACK")return null;let declaration=(state.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID){let declaration=await resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId);if(!declaration)return null;if(declaration.consumedByCallId&&declaration.consumedByCallId!==callID)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed by another Task call`);if(declaration.consumedByCallId===callID)return declaration;let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),nextState={...state,updatedAt:isoNow(),prFeedbackScopes:(state.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?{...entry,consumedByCallId:callID}:entry)};return await persistState(directory,nextState),{...declaration,consumedByCallId:callID}}async function validatePrFeedbackScopeBinding(directory,binding){if(!binding.workflowSessionId||!binding.workflowRevisionDigest)return!1;let declaration=await resolvePrFeedbackScopeDeclaration(directory,binding.workflowSessionId,binding.taskId);return Boolean(declaration&&declaration.consumedByCallId===binding.dispatchCallId&&declaration.revisionDigest===binding.workflowRevisionDigest&&JSON.stringify(declaration.files)===JSON.stringify(binding.files))}async function enforcePrWorkflowToolBefore(directory,sessionID,toolName,args2,generatedAgentNames=[]){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedRoles=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)).map((field)=>{let value=args2?.[field];if(typeof value!=="string"||!value.trim())return"";return resolveGeneratedAgentRole(value.trim(),generatedAgentNames)}),isDirectWrite=WRITE_TOOL_NAMES.includes(normalizedTool),command=typeof args2?.command==="string"?args2.command.trim():"",serializedArgs=JSON.stringify(args2??{}),referencesProtectedWorkflowEvidence=containsProtectedWorkflowPath(command||serializedArgs),isInternalWorkflowTool=isPrWorkflowControllerTool(state.mode,normalizedTool),isShellTool=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=isShellTool&&command.length>0&&isAllowedPrWorkflowReadOnlyShell(command,{allowCheckout:!state.prHeadSha,allowFetch:!state.prHeadSha,allowTrackingFetch:Boolean(state.prHeadSha),trackingFetchTarget:state.prHeadSha?_test_exports.resolveCurrentUpstreamPushTarget(directory):null}),isNamedReadOnlyTool=getPrWorkflowToolCapability(normalizedTool,state.mode)!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{});if(referencesProtectedWorkflowEvidence&&!isInternalWorkflowTool&&!isNamedReadOnlyTool&&!isReadOnlyShell)throw Error(`BLOCKED: active ${state.mode} workflow evidence under .swarm is controller-owned and cannot be modified directly`);let isShellCommandRequiringVerification=isShellTool&&command.length>0&&!isReadOnlyShell,isRemoteReviewTool=/(?:git|github|pull|(?:^|[_-])pr(?:[_-]|$)|issue|review)/i.test(normalizedTool),hasRemoteMutationVerb=/(?:^|[_-])(?:add|approve|cancel|close|comment|commit|convert|create|delete|dismiss|edit|mark|merge|push|ready|reopen|rerun|resolve|submit|transfer|unresolve|update)(?:[_-]|$)/i.test(normalizedTool),hasRemoteReadVerb=/(?:^|[_-])(?:github|git)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool)||/(?:^|[_-])(?:github|git)[_-]+(?:pull[_-]+request|pr|issue|review[_-]+thread)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool),isRemoteMutationTool=isRemoteReviewTool&&(hasRemoteMutationVerb||!hasRemoteReadVerb),isRemoteCheckoutTool=/(?:^|[_-])(?:github|git)[_-]+checkout(?:[_-]|$)/i.test(normalizedTool),isShellCheckout=(normalizedTool==="bash"||normalizedTool==="shell")&&(/\bgit\b(?:(?![;&|]).){0,200}\b(?:checkout|switch)\b/i.test(command)||/\bgh\s+pr\s+checkout\b/i.test(command)),isCanonicalReviewCheckout=/^git\s+switch\s+--detach\s+[0-9a-f]{40,64}$/i.test(command),detachedFeedbackSwitchMatch=command.match(/^git\s+switch\s+--detach\s+(\S+)$/i),isDetachedFeedbackCheckout=Boolean(detachedFeedbackSwitchMatch?.[1]&&isSafeGitRefToken(detachedFeedbackSwitchMatch[1]))||/^gh\s+pr\s+checkout\b.*\s--detach(?:\s|$)/i.test(command),containsGitCommitShell=isShellCommandRequiringVerification&&/\bgit\b(?:(?![;&|]).){0,200}\bcommit\b/i.test(command),isStandaloneGitCommitShell=containsGitCommitShell&&isSafeStandaloneGitCommit(command),isPublicationShell=isShellCommandRequiringVerification&&(/\bgit\b(?:(?![;&|]).){0,200}\bpush\b/i.test(command)||/\bgh\s+(?:api|pr|issue|run)\b/i.test(command)),isPublicationTool=!isInternalWorkflowTool&&isRemoteMutationTool,isCoderTask=isDirectAgentTask&&requestedRoles.length>0&&requestedRoles.every((role)=>role==="coder");if(state.mode==="PR_REVIEW"){if(!(isInternalWorkflowTool||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_REVIEW checkout must use standalone commands: fetch the PR head, verify the full commit object with `git cat-file -e <full_pr_head_sha>^{commit}`, then run `git switch --detach <full_pr_head_sha>` and bind that exact head before dispatching explorer lanes. Do not use `--track FETCH_HEAD`.");throw Error("BLOCKED: PR_REVIEW is read-only and fail-closed; only controller tools and positively classified observation tools are allowed, and every agent lane requires structured dispatch_lanes_async")}return}if(isDirectAgentTask&&!isCoderTask)throw Error("BLOCKED: PR_FEEDBACK reviewer, test, critic, explorer, and unknown agent lanes require structured dispatch_lanes_async provenance");if(!isInternalWorkflowTool&&!isDirectAgentTask&&!isDirectWrite&&!isShellTool&&!isNamedReadOnlyTool)throw Error("BLOCKED: PR_FEEDBACK rejects unclassified plugin/MCP tools; use positively classified observation tools, built-in structured write tools after verification, or the workflow controller");if(state.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK is armed for publication; the approved commit is immutable");if((containsGitCommitShell||isPublicationShell)&&hasUnsafeShellControlSyntax(command))throw Error("BLOCKED: PR_FEEDBACK publication commands must be standalone shell commands without control, redirection, or command-substitution syntax");if(containsGitCommitShell&&!isStandaloneGitCommitShell)throw Error("BLOCKED: PR_FEEDBACK commit must use a standalone git commit command after every ordered local gate passes");if(state.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(isNamedReadOnlyTool)return;if((normalizedTool==="bash"||normalizedTool==="shell")&&command.length>0&&isAllowedPrWorkflowReadOnlyShell(command,{allowCheckout:!1,allowFetch:!1,allowTrackingFetch:!1}))return;if(normalizedTool==="bash"||normalizedTool==="shell"){let armed=(await assertPrFeedbackPublicationArmed(directory,sessionID)).prFeedbackReadyToPublish;if(isSafeExactBoundPush(command,armed))return;throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed")}if(!state.prHeadSha&&isDetachedFeedbackCheckout)throw Error("BLOCKED: PR_FEEDBACK requires a tracked PR branch before the first head bind; detached checkout is valid for PR_REVIEW, not PR_FEEDBACK.");if(isStandaloneGitCommitShell){await assertPrFeedbackReadyToPublish(directory,sessionID);return}if(isPublicationShell||isPublicationTool)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; finish every ordered gate, create the one approved commit, and call complete_pr_workflow before publishing");if(isShellCommandRequiringVerification){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout must use a safe standalone pre-bind form: `gh pr checkout <number-or-url>` without force/submodule flags, or `git switch -c <local> --track <remote>/<branch>`. Detached checkouts are not allowed in PR_FEEDBACK. Then verify exact HEAD, a clean tree, and the intended upstream before dispatching feedback lanes.");throw Error("BLOCKED: PR_FEEDBACK shell commands fail closed unless they are explicit read-only intake or the one standalone approved git commit; use structured coder/write tools for fixes and run_pr_feedback_stage_a for validation")}if(!isDirectWrite&&!isShellCommandRequiringVerification&&!isRemoteMutationTool&&!isCoderTask&&normalizedTool!=="prepare_pr_feedback_scope")return;if(normalizedTool==="abort_pr_workflow")return;await assertPrFeedbackVerificationSettled(directory,sessionID)}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha){let state=await requireBoundState(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state.prHeadSha}"`);let open3=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(open3.length>0)throw Error(`BLOCKED: ${expectedMode} completion has ${open3.length} unsettled PR workflow lane(s)`);if(expectedMode==="PR_REVIEW"){if(assertPrReviewCleanCheckout(directory),await assertPrReviewBaseCoverageSettled(directory,sessionID),!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW completion requires a persisted trigger evaluation artifact");if((state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council");await assertPrReviewValidationSettled(directory,sessionID,"reviewer");let criticInventory=derivePrReviewCriticInventory(directory,state);if(criticInventory.length>0){if(!(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic"))throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${criticInventory.join(", ")}`);await assertPrReviewValidationSettled(directory,sessionID,"critic")}let requiredArtifactBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state.prReviewArtifactBoundaries??[]),missingArtifactBoundaries=requiredArtifactBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state.prReviewFindingsPath||missingArtifactBoundaries.length>0)throw Error(`BLOCKED: PR_REVIEW completion requires durable findings checkpoints; missing: ${missingArtifactBoundaries.join(", ")||"findings path"}`);if(state.prReviewHandoffRequired&&!state.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact")}else{let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let localHead=_test_exports.resolveCurrentGitHead(directory)?.trim();if(!localHead)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a verified local Git HEAD");if(_test_exports.resolveCommitCountSince(directory,state.prHeadSha,localHead)!==1)throw Error("BLOCKED: PR_FEEDBACK publication requires exactly one descendant commit after the immutable intake head");if(_test_exports.resolveIsExactSingleChildCommit(directory,state.prHeadSha,localHead)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication commit must be a non-merge direct child of the immutable intake head");if(_test_exports.resolveIsWorkingTreeClean(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication requires a clean index and working tree so all approved content is captured by the bound commit");let upstreamTarget=_test_exports.resolveCurrentUpstreamPushTarget(directory);if(!upstreamTarget)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a current branch bound to an exact remote name, remote branch ref, and remote-tracking ref");return await persistState(directory,{...readyState,updatedAt:isoNow(),prFeedbackReadyToPublish:{revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,validatedAt:isoNow()}}),"ready-to-publish"}if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK publication revision differs from the independently approved content digest");let publishedHead=_test_exports.resolveCurrentGitHead(directory)?.trim(),remoteRefs=publishedHead?_test_exports.resolveRemoteRefsContainingHead(directory,publishedHead):null,remoteHead=_test_exports.resolveExactRemoteBranchHead(directory,armed.remoteName,armed.remoteBranchRef);if(!publishedHead||publishedHead!==armed.localHead||!remoteRefs?.includes(armed.remoteRef)||remoteHead?.toLowerCase()!==armed.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK completion requires approved commit ${armed.localHead} at current Git HEAD and intended remote-tracking ref ${armed.remoteRef} at that exact commit`)}return await _test_exports.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,state.revision),"completed"}async function requireAnyActiveState(directory,sessionID){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*".`);return state}async function requireBoundState(directory,sessionID,expectedMode){let state=await requireAnyActiveState(directory,sessionID);if(state.mode!==expectedMode)throw wrongModeError(state,expectedMode);if(!state.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")assertCurrentCheckoutHead(directory,state.prHeadSha),assertPrReviewCleanCheckout(directory);return state}function wrongModeError(state,expectedMode){return Error(`BLOCKED: session "${state.sessionID}" is active in ${state.mode}, not ${expectedMode}`)}function normalizeWorkflowLanes(lanes){if(!Array.isArray(lanes)||lanes.length===0)throw Error("BLOCKED: PR workflow lane validation requires at least one lane");let normalized=lanes.map((lane)=>{let workflowLane=lane.workflowLane?.trim(),laneId=lane.laneId?.trim()||workflowLane;if(!workflowLane||!laneId)throw Error("BLOCKED: PR workflow lane validation requires every lane to have non-empty laneId and workflow_lane values");let reviewItemIds=lane.reviewItemIds?.map((itemId)=>itemId.trim());if(reviewItemIds?.some((itemId)=>!itemId))throw Error("BLOCKED: PR workflow review_item_ids must not contain empty values");if(reviewItemIds)assertNoDuplicates(reviewItemIds,"review item ids within one lane");let ownedWorkflowLanes=lane.ownedWorkflowLanes?.map((owned)=>owned.trim());if(ownedWorkflowLanes){if(ownedWorkflowLanes.some((owned)=>!owned))throw Error("BLOCKED: PR workflow owned_workflow_lanes must not contain empty values");if(assertNoDuplicates(ownedWorkflowLanes,"owned workflow lanes within one lane"),!ownedWorkflowLanes.includes(workflowLane))throw Error(`BLOCKED: PR workflow lane "${laneId}" must include its own workflow_lane "${workflowLane}" in owned_workflow_lanes`)}return{laneId,workflowLane,...reviewItemIds?{reviewItemIds}:{},...ownedWorkflowLanes?{ownedWorkflowLanes}:{}}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"lane ids"),assertNoDuplicates(normalized.map((lane)=>lane.workflowLane),"workflow lane ids"),assertNoDuplicates(normalized.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]),"owned workflow lane ids across lanes"),normalized}function normalizeInventoryIds(inventoryIds){if(!Array.isArray(inventoryIds)||inventoryIds.length===0)throw Error("BLOCKED: PR_FEEDBACK inventory declaration requires at least one feedback item id");let normalized=inventoryIds.map((inventoryId)=>{let itemId=inventoryId.trim();if(!itemId)throw Error("BLOCKED: PR_FEEDBACK inventory declaration contains an empty item id");return itemId});return assertNoDuplicates(normalized,"inventory item ids"),normalized.sort()}function normalizeOwnership(ownership){if(!Array.isArray(ownership)||ownership.length===0)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires at least one lane declaration");let normalized=ownership.map((lane)=>{let laneId=lane.laneId?.trim();if(!laneId)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires every lane to have a non-empty laneId");let ownedItemIds=normalizeInventoryIds(lane.ownedItemIds);return{laneId,ownedItemIds}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"PR_FEEDBACK verification lane ids"),normalized}function assertNoDuplicates(values,label){let seen=new Set;for(let value of values){if(seen.has(value))throw Error(`BLOCKED: duplicate ${label} are not allowed: ${value}`);seen.add(value)}}function containsProtectedWorkflowPath(value){return/(?:^|[^A-Za-z0-9_.-])\.swarm(?:[\\/]|$)/i.test(value.replace(/\\\\/g,"\\"))}function isPrWorkflowControllerTool(mode,toolName){if(PR_WORKFLOW_SHARED_CONTROLLER_TOOLS.has(toolName))return!0;return mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS.has(toolName):PR_FEEDBACK_CONTROLLER_TOOLS.has(toolName)}function isTrustedPrWorkflowToolInvocationSafe(toolName,args2){if(toolName==="lint")return args2.mode==="check";if(toolName==="sast_scan")return args2.capture_baseline!==!0;return!0}function isAllowedPrReviewReadOnlyToolName(toolName){if(PR_REVIEW_READ_ONLY_TOOL_NAMES.has(toolName))return!0;let tokens=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens.some((token)=>/^(?:add|alter|and|append|apply|approve|cancel|checkout|close|comment|commit|convert|create|delete|destroy|dismiss|drop|edit|execute|grant|insert|mark|merge|move|patch|prepend|publish|push|ready|remove|rename|replace|resolve|rerun|revoke|run|send|submit|then|transfer|truncate|unresolve|update|upload|write)$/i.test(token)))return!1;return tokens.some((token)=>/^(?:check|checks|diff|fetch|find|get|glob|grep|hover|inspect|list|lookup|open|read|references|scan|screenshot|search|show|status|symbols|tree|view)$/i.test(token))}function readOnlyToolArgumentsAreSafe(value,key="",depth=0){if(depth>8)return!1;let keyTokens=key.replace(/([a-z0-9])([A-Z])/g,"$1_$2").split(/[._:/-]+/).filter(Boolean);if(keyTokens.some((token)=>/^(?:append|body|content|create|data|delete|destination|destroy|edit|insert|mutation|output|patch|payload|prepend|remove|replace|save|set|truncate|update|upload|write)$/i.test(token)))return!1;if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim());if(keyTokens.length===1&&keyTokens.some((token)=>/^(?:action|operation)$/i.test(token)))return typeof value==="string"&&/^(?:check|diff|fetch|find|get|inspect|list|lookup|open|read|scan|search|show|status|view)$/i.test(value.trim());if(/^mode$/i.test(key)&&typeof value==="string")return/^(?:r|rb|read)$/i.test(value.trim());if(typeof value==="string"){if(keyTokens.some((token)=>/^(?:query|request|sql|statement)$/i.test(token))&&/(?:\b(?:alter|call|comment|create|delete|drop|exec(?:ute)?|grant|insert|merge|mutation|replace|revoke|truncate|update|upsert)\b|\bselect\b[\s\S]{0,4000}\binto\s+[A-Za-z_"'`])/i.test(value))return!1;return!/(?:^(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE|write|edit|patch|create|delete|destroy|remove|replace|truncate|update|upload)$|(?:^|[\r\n])\s*(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE)\s+\S+(?:\s+HTTP\/\d(?:\.\d)?)?|\bmutation\b|\b(?:create|drop|alter|truncate)\s+(?:or\s+replace\s+)?(?:table|database|schema|index|view|function|procedure|trigger|sequence)\b|\b(?:delete\s+from|insert\s+into|merge\s+into|replace\s+into|upsert\s+into)\b|\bupdate\s+[A-Za-z0-9_."'`-]+(?:\s+(?:AS\s+)?[A-Za-z0-9_"'`-]+)?\s+set\b|\b(?:grant|revoke)\s+\S+\s+(?:on|from|to)\b|\b(?:call|exec(?:ute)?)\s+[A-Za-z0-9_."'`-]+|\b(?:rm|rmdir|del|remove-item|move-item|set-content|add-content)\b)/i.test(value)}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return!0;if(Array.isArray(value))return value.every((entry)=>readOnlyToolArgumentsAreSafe(entry,key,depth+1));if(typeof value==="object")return Object.entries(value).every(([childKey,childValue])=>readOnlyToolArgumentsAreSafe(childValue,childKey,depth+1));return!1}function isAllowedPrWorkflowReadOnlyShell(command,options){let normalized=command.trim().replace(/\s+/g," ");if(!normalized)return!1;if(/[\r\n;&|<>`]/.test(command)||/\$\(|@\(/.test(command))return!1;let gitMatch=normalized.match(/^git(?: -C (?:"[^"]+"|'[^']+'|\S+))* (.+)$/i);if(gitMatch?.[1]){if(/^git -C /i.test(normalized)&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))return!1;return isAllowedPrWorkflowGitIntake(gitMatch[1],options)}if(/^gh /i.test(normalized))return isAllowedPrFeedbackGhIntake(normalized);if(/^rg\b/i.test(normalized)&&/\s--pre(?:-glob)?(?:\s|=|$)/i.test(normalized))return!1;return/^(?:rg|grep|cat|Get-Content|Select-String|Test-Path|Get-ChildItem|ls|dir|pwd)(?:\s|$)/i.test(normalized)}function hasUnsafeShellControlSyntax(command){return/[;&|<>`\r\n]/.test(command)||/\$\(/.test(command)}function isSafeStandaloneGitCommit(command){if(hasUnsafeShellControlSyntax(command))return!1;if(/(?:^|\s)--(?:allow-empty|amend)(?:\s|=|$)/i.test(command))return!1;return/^git(?:\s+-C(?:=|\s+)(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>`]+))?\s+commit(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s;&|<>`]+))*\s*$/i.test(command.trim())}function boundPushTarget(armed){let remote=armed.remoteName,branch=armed.remoteBranchRef.slice(11);if(!armed.remoteBranchRef.startsWith("refs/heads/")||!branch)return null;if(/\s|[;&|<>`]/.test(remote)||/\s|[;&|<>`]/.test(branch))return null;return{remote,branch}}function expectedBoundPushCommand(armed){let target=boundPushTarget(armed);return target?`git push ${target.remote} ${armed.localHead}:refs/heads/${target.branch}`:"(invalid bound remote-tracking ref; restart the workflow)"}function isSafeExactBoundPush(command,armed){if(hasUnsafeShellControlSyntax(command))return!1;let target=boundPushTarget(armed);if(!target)return!1;let match=command.trim().match(/^git\s+push\s+([^\s;&|<>`]+)\s+([^\s;&|<>`]+)\s*$/i);if(!match)return!1;return match[1]===target.remote&&match[2]===`${armed.localHead}:refs/heads/${target.branch}`}function isAllowedPrWorkflowGitIntake(gitArgs,options){if(/(?:--ext-diff|--textconv|--open-files-in-pager|--output(?:=|\s)|--upload-pack(?:=|\s)|--exec(?:=|\s))/i.test(gitArgs))return!1;if(/^(?:status|log|show|diff|rev-parse|merge-base|ls-files|grep|blame|cat-file|for-each-ref)(?:\s|$)/i.test(gitArgs))return!0;if(options.allowFetch&&/^fetch(?:\s|$)/i.test(gitArgs))return!0;if(options.allowTrackingFetch&&isAllowedBoundRemoteTrackingFetch(gitArgs,options.trackingFetchTarget))return!0;if(/^remote(?:\s+-v)?$/i.test(gitArgs))return!0;if(options.allowCheckout&&isAllowedPreBindBranchSetup(gitArgs))return!0;if(options.allowCheckout&&/^(?:checkout|switch)\s+(?:--detach\s+)?[^\s-][^\s]*$/i.test(gitArgs))return!0;return/^config\s+(?:(?:--show-origin|--show-scope|--global|--local|--system|--worktree)\s+)*(?:--list|--get(?:-all)?\s+\S+)$/i.test(gitArgs)}function isAllowedBoundRemoteTrackingFetch(gitArgs,target){if(!target?.remoteName||!target.remoteBranchRef.startsWith("refs/heads/"))return!1;let tokens=gitArgs.trim().split(/\s+/);if(tokens.length!==3||tokens[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens,expectedBranch=target.remoteBranchRef.slice(11);return isSafeGitRefToken(remote)&&!remote.includes("/")&&isSafeGitRefToken(remoteBranch)&&!remoteBranch.startsWith("-")&&!remoteBranch.includes(":")&&remote===target.remoteName&&remoteBranch===expectedBranch}function isAllowedPreBindBranchSetup(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens.length===3&&tokens[0]==="branch"){let upstream=tokens[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens[2]))}return!1}function isSafeGitRefToken(value){return/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")&&!value.endsWith("/")&&!value.endsWith(".")&&!value.endsWith(".lock")}function isAllowedPrFeedbackGhIntake(command){if(/^gh\s+pr\s+checkout(?:\s|$)/i.test(command))return isAllowedSafeGhPrCheckout(command);if(/^gh\s+pr\s+(?:view|diff|checks|status|list)(?:\s|$)/i.test(command)||/^gh\s+run\s+(?:view|list|watch)(?:\s|$)/i.test(command)||/^gh\s+issue\s+(?:view|list)(?:\s|$)/i.test(command)||/^gh\s+search\s+(?:code|commits|issues|prs|repos)(?:\s|$)/i.test(command)||/^gh\s+auth\s+status(?:\s|$)/i.test(command))return!0;if(!/^gh\s+api(?:\s|$)/i.test(command))return!1;if(/\bmutation\b/i.test(command))return!1;let method=command.match(/\s(?:--method(?:\s+|=)|-X(?:\s+|=)?)([A-Z]+)/i)?.[1];if(method&&method.toUpperCase()!=="GET")return!1;if(/\s(?:--input|--raw-field)(?:\s|=)/i.test(command)||/\s-F(?:\s|=|\S)/.test(command))return!1;return!/\s(?:--field|-f)(?:\s|=)(?!query=)/i.test(command)}function isAllowedSafeGhPrCheckout(command){if(/\s--(?:force|recurse-submodules)(?:\s|=|$)/i.test(command))return!1;let tokens=command.trim().split(/\s+/);if(tokens.length<4||tokens[0]!=="gh"||tokens[1]!=="pr"||tokens[2]!=="checkout")return!1;let target=tokens[3];if(!/^\d+$/.test(target)&&!/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/\d+$/.test(target))return!1;for(let index=4;index<tokens.length;index+=1){let token=tokens[index],repoEquals=token.match(/^--repo=(.+)$/)?.[1];if(repoEquals){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repoEquals))return!1;continue}let branchEquals=token.match(/^--branch=(.+)$/)?.[1];if(branchEquals){if(!isSafeGitRefToken(branchEquals))return!1;continue}if(token==="--repo"||token==="-R"){let repo=tokens[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens[++index];if(!branch||!isSafeGitRefToken(branch))return!1;continue}return!1}return!0}function normalizePrHeadSha(prHeadSha){let normalized=prHeadSha.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty pr_head_sha");return normalized}async function currentPrFeedbackRevisionDigest(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let digest2=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!digest2)throw Error("BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest");return digest2}async function resolvePrWorkflowRevisionDigestForGate(directory,baseHeadSha){if(_test_exports.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _test_exports.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha)}function normalizeBatchId(batchId){let normalized=batchId.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty batch id");return normalized}function sameStringArray(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function assertExactStringSet(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),missing=[...expectedSet].filter((value)=>!actualSet.has(value)),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length!==actualSet.size||actualSet.size!==expectedSet.size||missing.length>0||extra.length>0)throw Error(`BLOCKED: ${label} must exactly cover the mechanically derived inventory; missing: ${missing.join(", ")||"(none)"}; extra: ${extra.join(", ")||"(none)"}`)}function derivePrReviewCandidateInventory(directory,state){let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map;for(let batch of[...state.prReviewBaseDispatches??[]].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt);for(let lane of batch.lanes){let ownedDimensions=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!ownedDimensions.every((dimension)=>successful.has(dimension)))continue;let key=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key,ownedDimensions.length);for(let dimension of ownedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key))continue;seenBaseSourceKeys.add(key);let credited=baseSourceCreditedDimensions.get(key),fullOwnershipCount=baseSourceFullOwnershipCount.get(key)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;for(let batch of[...state.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt);for(let lane of batch.lanes)if(successful.has(lane.workflowLane)&&!selectedCouncilLanes.has(lane.workflowLane))sources.push({batchId:batch.batchId,laneId:lane.laneId,mode:"swarm-pr-review:council"}),selectedCouncilLanes.add(lane.workflowLane)}if(state.prReviewTriggerEvalPath){let triggerPath=validateSwarmPath(directory,state.prReviewTriggerEvalPath),triggerArtifact;try{triggerArtifact=JSON.parse(readFileSync6(triggerPath,"utf-8"))}catch{throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid")}let rows=triggerArtifact.rows;if(!Array.isArray(rows))throw Error("BLOCKED: PR_REVIEW trigger evaluation rows are invalid");let rowIds=rows.map((row)=>typeof row==="object"&&row!==null?row.trigger_id:void 0),provenanceTuples=rows.map((row)=>{if(typeof row!=="object"||row===null)return"";let{source_batch_id:batchId,source_lane_id:laneId}=row;return typeof batchId==="string"&&typeof laneId==="string"&&batchId.trim()&&laneId.trim()?`${batchId}\x00${laneId}`:""});if(!(rows.length===PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length&&new Set(rowIds).size===PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length&&provenanceTuples.every(Boolean)&&PR_REVIEW_REQUIRED_MICRO_LANE_IDS.every((id)=>rowIds.includes(id))&&rows.every((row)=>typeof row==="object"&&row!==null&&row.result==="MATCHED")))throw Error("BLOCKED: PR_REVIEW requires the exact all-MATCHED repository-agnostic micro-lane set with complete source provenance");for(let row of rows)if(typeof row==="object"&&row!==null&&row.result==="MATCHED"&&typeof row.source_batch_id==="string"&&typeof row.source_lane_id==="string")sources.push({batchId:row.source_batch_id,laneId:row.source_lane_id,mode:"swarm-pr-review:micro",workflowLane:row.trigger_id})}let candidateIds=[],extractedLaneKeys=new Set;for(let source of sources){let resolvedArtifact=!1;for(let record2 of findByBatchId(directory,source.batchId,{parentSessionId:state.sessionID})){if(record2.laneId!==source.laneId||record2.mode!==source.mode||record2.status!=="completed"||record2.workspace?.prHeadSha!==state.prHeadSha||record2.workspace?.gitHead!==state.prHeadSha||record2.result?.outputDegraded===!0||record2.result?.transcriptIncomplete===!0||record2.result?.truncated===!0)continue;let ref=record2.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record2.ownedWorkflowLanes?.length?record2.ownedWorkflowLanes:record2.workflowLane?[record2.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state,record2,source.mode,record2.workflowLane??source.workflowLane??source.laneId,void 0,void 0,recordOwnedLanes))continue;if(source.workflowLane&&(!recordOwnedLanes?.includes(source.workflowLane)||!prReviewDiscoveryArtifactCoversLane(artifact.text,source.workflowLane)))continue;resolvedArtifact=!0;let laneKey=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey))extractedLaneKeys.add(laneKey),candidateIds.push(...extractCandidateIds(artifact.text,source.creditedLanes))}if(source.mode==="swarm-pr-review:micro"&&!resolvedArtifact)throw Error(`BLOCKED: PR_REVIEW mandatory micro-lane provenance is missing or invalid for ${source.workflowLane??source.laneId}`)}return assertNoDuplicates(candidateIds,"PR_REVIEW discovery candidate ids"),candidateIds.length>0?candidateIds.sort():["CLEAN-REVIEW"]}function extractCandidateIds(text,scopeToLanes){let candidateIds=[],markerHeaderSeen=!1,inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);for(let line of text.split(/\r?\n/)){let fields=pipeFields(line);if(fields[0]==="[CANDIDATE]"&&fields[1]?.toLowerCase()==="candidate_id"){markerHeaderSeen=!0;continue}if(fields[0]==="[CANDIDATE]"&&fields.length>=10&&fields.slice(1,10).every(Boolean)){if(inScope(fields[2]))candidateIds.push(fields[1]);continue}if(markerHeaderSeen&&fields.length>=9&&fields[0]&&!fields[0].startsWith("[")&&fields.slice(0,9).every(Boolean)){if(inScope(fields[1]))candidateIds.push(fields[0])}}return candidateIds}function derivePrReviewCriticInventory(directory,state){return[...deriveLatestPrReviewReviewerVerdicts(directory,state).entries()].filter(([,verdict])=>verdict.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(verdict.severity)).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state){let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state),criticBatches=(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="critic");for(let batch of[...criticBatches].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:critic",batch.validatedAt);if(batch.lanes.some((lane)=>!successful.has(lane.workflowLane))||successful.size!==batch.lanes.length)continue;let required2=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]),verdicts=new Map;for(let lane of batch.lanes){let ref=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===lane.laneId)?.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0;if(!artifact)continue;for(let itemId of lane.reviewItemIds??[]){let verdict=parseCriticVerdict(artifact.text,itemId,reviewerVerdicts.get(itemId)?.severity);if(verdict)verdicts.set(itemId,verdict)}}if(required2.every((itemId)=>verdicts.has(itemId)))return verdicts}return new Map}function deriveLatestPrReviewReviewerVerdicts(directory,state){let reviewerBatches=(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer");for(let batch of[...reviewerBatches].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:reviewer",batch.validatedAt);if(batch.lanes.some((lane)=>!successful.has(lane.workflowLane))||successful.size!==batch.lanes.length)continue;let required2=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]),verdicts=new Map;for(let lane of batch.lanes){let ref=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===lane.laneId)?.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0;if(!artifact)continue;for(let itemId of lane.reviewItemIds??[]){let verdict=parseReviewerVerdict(artifact.text,itemId);if(verdict)verdicts.set(itemId,verdict)}}if(required2.every((itemId)=>verdicts.has(itemId)))return verdicts}return new Map}function successfulObligationsFromExactBatch(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}),successful=new Set,validatedAtMs=Date.parse(validatedAt);if(!Number.isFinite(validatedAtMs))return successful;let expectedByLaneId=new Map(expectedLanes.map((lane)=>[lane.laneId,lane]));if(expectedByLaneId.size!==expectedLanes.length)return successful;let recordCountByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record2 of records){if(!record2.laneId||!expectedByLaneId.has(record2.laneId))continue;recordCountByLaneId.set(record2.laneId,(recordCountByLaneId.get(record2.laneId)??0)+1);let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)recordCountBySubagentSessionId.set(subagentSessionId,(recordCountBySubagentSessionId.get(subagentSessionId)??0)+1)}for(let record2 of records){let expectedLane=record2.laneId?expectedByLaneId.get(record2.laneId):void 0,expectedWorkflowLane=expectedLane?.workflowLane,expectedOwnedLanes=expectedLane?.ownedWorkflowLanes?.length?expectedLane.ownedWorkflowLanes:expectedWorkflowLane!==void 0?[expectedWorkflowLane]:void 0,subagentSessionId=record2.subagentSessionId?.trim();if(expectedWorkflowLane!==void 0&&expectedOwnedLanes!==void 0&&record2.laneId!==void 0&&recordCountByLaneId.get(record2.laneId)===1&&Boolean(subagentSessionId)&&recordCountBySubagentSessionId.get(subagentSessionId)===1&&!forbiddenSubagentSessionIds.has(subagentSessionId)&&record2.createdAt>=validatedAtMs&&(!checkWorkflowLane||record2.workflowLane===expectedWorkflowLane)&&(!checkWorkflowLane||ownedLaneSetsEqual(record2.ownedWorkflowLanes,expectedOwnedLanes))&&record2.mode===expectedMode&&record2.workspace?.prHeadSha===state.prHeadSha&&record2.workspace?.gitHead===state.prHeadSha&&record2.status==="completed"&&record2.result?.outputDegraded!==!0&&record2.result?.transcriptIncomplete!==!0&&record2.result?.truncated!==!0&&(record2.result?.chars??0)>0&&Boolean(record2.result?.digest?.trim())&&Boolean(record2.result?.outputRef?.trim())&&workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,expectedLane?.reviewItemIds,expectedRevisionDigest,expectedOwnedLanes))for(let obligation of expectedOwnedLanes)successful.add(obligation)}return successful}function ownedLaneSetsEqual(recordOwned,expectedOwned){if(!recordOwned||recordOwned.length===0)return expectedOwned.length===1;let recordSet=new Set(recordOwned),expectedSet=new Set(expectedOwned);if(recordSet.size!==recordOwned.length||recordSet.size!==expectedSet.size)return!1;return recordOwned.every((owned)=>expectedSet.has(owned))}function workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes){let ref=record2.result?.outputRef?.trim();if(!ref)return!1;let loaded=readLaneOutput(directory,ref);if(!loaded)return!1;let artifact=loaded.artifact,recordPrHeadSha=record2.workspace?.prHeadSha,recordGitHead=record2.workspace?.gitHead,resolvedRevisionDigest=expectedRevisionDigest??(recordPrHeadSha?_test_exports.resolvePrWorkflowRevisionDigest(directory,recordPrHeadSha):null),expectedReviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0;if(artifact.batchId!==record2.batchId||artifact.laneId!==record2.laneId||artifact.mode!==expectedMode||artifact.sessionId!==record2.subagentSessionId||artifact.parentSessionId!==record2.parentSessionId||artifact.agent!==record2.swarmPrefixedAgent||artifact.role!==record2.normalizedAgent||artifact.source!=="collect_lane_results"||artifact.workflowLane!==record2.workflowLane||artifact.workflowLane!==expectedWorkflowLane||!recordPrHeadSha||artifact.prHeadSha!==recordPrHeadSha||!recordGitHead||artifact.gitHead!==recordGitHead||!resolvedRevisionDigest||artifact.revisionDigest!==resolvedRevisionDigest||expectedReviewScope!==void 0&&(record2.workspace?.scope!==expectedReviewScope||artifact.scope!==expectedReviewScope)||artifact.digest!==record2.result?.digest||artifact.chars!==record2.result?.chars)return!1;if(expectedMode==="swarm-pr-review:reviewer")return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>Boolean(parseReviewerVerdict(artifact.text,itemId))));if(expectedMode==="swarm-pr-review:critic"){let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state);return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>Boolean(parseCriticVerdict(artifact.text,itemId,reviewerVerdicts.get(itemId)?.severity))))}if(expectedMode==="swarm-pr-feedback:verification")return/^\[FEEDBACK-VERIFIED\]\s*\|/m.test(artifact.text);let feedbackVerdict={"swarm-pr-feedback:stage-b-reviewer":["[STAGE-B-REVIEW]","APPROVE"],"swarm-pr-feedback:stage-b-test":["[STAGE-B-TEST]","PASS"],"swarm-pr-feedback:closeout-reviewer":["[CLOSEOUT-REVIEW]","APPROVE"],"swarm-pr-feedback:closeout-critic":["[CLOSEOUT-CRITIC]","APPROVE"]}[expectedMode];if(feedbackVerdict)return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>artifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));let coveredLanes=ownedWorkflowLanes?.length?ownedWorkflowLanes:[expectedWorkflowLane];if(!coveredLanes.every((coveredLane)=>prReviewDiscoveryArtifactCoversLane(artifact.text,coveredLane)))return!1;if(coveredLanes.length>1){let seenEvidence=new Map;for(let coveredLane of coveredLanes){let evidence=extractLaneCoverageEvidenceText(artifact.text,coveredLane);if(evidence===null)continue;if(seenEvidence.get(evidence))return!1;seenEvidence.set(evidence,coveredLane)}}return!0}function prReviewDiscoveryArtifactCoversLane(text,expectedWorkflowLane){let lines=text.split(/\r?\n/),candidateHeaderSeen=!1;for(let line of lines){let fields=pipeFields(line);if(fields.length===0)continue;if(fields[0]==="[CLEAN]"&&fields.length>=4&&fields[1]===expectedWorkflowLane&&fields.slice(1,4).every(Boolean)&&fields[2].length>=12&&fields[3].length>=20)return!0;if(fields[0]==="[CANDIDATE]"){if(fields[1]?.toLowerCase()==="candidate_id"){candidateHeaderSeen=!0;continue}if(fields.length>=10&&fields[2]===expectedWorkflowLane&&fields.slice(1,10).every(Boolean))return!0;continue}if(candidateHeaderSeen&&fields.length>=9&&fields[0]?.toLowerCase()!=="candidate_id"&&fields[1]===expectedWorkflowLane&&fields.slice(0,9).every(Boolean))return!0}return!1}function extractLaneCoverageEvidenceText(text,expectedWorkflowLane){let lines=text.split(/\r?\n/),candidateHeaderSeen=!1;for(let line of lines){let fields=pipeFields(line);if(fields.length===0)continue;if(fields[0]==="[CLEAN]"&&fields.length>=4&&fields[1]===expectedWorkflowLane&&fields.slice(1,4).every(Boolean)&&fields[2].length>=12&&fields[3].length>=20)return`${fields[2]}\x00${fields[3]}`;if(fields[0]==="[CANDIDATE]"){if(fields[1]?.toLowerCase()==="candidate_id"){candidateHeaderSeen=!0;continue}if(fields.length>=10&&fields[2]===expectedWorkflowLane&&fields.slice(1,10).every(Boolean))return fields.slice(3,10).join("\x00");continue}if(candidateHeaderSeen&&fields.length>=9&&fields[0]?.toLowerCase()!=="candidate_id"&&fields[1]===expectedWorkflowLane&&fields.slice(0,9).every(Boolean))return fields.slice(2,9).join("\x00")}return null}function parseReviewerVerdict(text,itemId){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[REVIEWED]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==10||!fields.slice(1).every(Boolean))return null;let introduced=fields[5].replace(/^introduced_by_pr\s*:\s*/i,"").toUpperCase();if(!REVIEWER_CLASSIFICATIONS.has(fields[2])||!REVIEWER_EVIDENCE_TYPES.has(fields[3])||!REVIEW_SEVERITIES.has(fields[4])||!["YES","NO","UNKNOWN"].includes(introduced))return null;if(fields[7].length<8||fields[8].length<5||fields[9].length<3)return null;return{classification:fields[2],severity:fields[4]}}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[CRITIC]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==6||!fields.slice(1).every(Boolean)||!CRITIC_STATUSES.has(fields[2])||!REVIEW_SEVERITIES.has(fields[3]))return null;if(fields[2]==="NEEDS_MORE_EVIDENCE")return null;if(fields[2]==="DISPROVED"&&fields[3]!=="NONE")return null;if(fields[2]==="UPHELD"&&!["CRITICAL","HIGH","MEDIUM"].includes(fields[3]))return null;if(fields[2]==="DOWNGRADED"&&fields[3]==="CRITICAL")return null;if(reviewerSeverity){let severityRank=new Map([["NONE",0],["INFO",1],["LOW",2],["MEDIUM",3],["HIGH",4],["CRITICAL",5]]),reviewerRank=severityRank.get(reviewerSeverity),criticRank=severityRank.get(fields[3]);if(reviewerRank===void 0||criticRank===void 0)return null;if(fields[2]==="UPHELD"&&criticRank!==reviewerRank)return null;if(fields[2]==="DOWNGRADED"&&criticRank>=reviewerRank)return null}if(fields[4].length<6||fields[5].length<6)return null;return{status:fields[2],severity:fields[3]}}function artifactHasExactPositiveVerdictRow(text,marker,itemId,positiveVerdict){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]===marker&&fields[1]===itemId);return rows.length===1&&rows[0].length>=4&&rows[0][2]===positiveVerdict&&rows[0].slice(1,4).every(Boolean)}function pipeFields(line){if(!line.includes("|"))return[];return line.split("|").map((field)=>field.trim())}function feedbackArtifactCoversItems(directory,state,batchId,laneId,itemIds){let ref=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===laneId)?.result?.outputRef?.trim(),loaded=ref?readLaneOutput(directory,ref):null;if(!loaded)return!1;let rows=loaded.artifact.text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]==="[FEEDBACK-VERIFIED]");if(rows.length!==itemIds.length)return!1;return itemIds.every((itemId)=>{let matches=rows.filter((fields)=>fields[1]===itemId);return matches.length===1&&matches[0].length===4&&matches[0].slice(1,4).every(Boolean)&&FEEDBACK_CLASSIFICATIONS.has(matches[0][2])})}async function persistState(directory,state){let validated=PrWorkflowGateStateSchema.parse(state);await withSessionStateMutation(directory,validated.sessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk(directory,validated.sessionID);if(current?current.revision!==validated.revision:validated.revision!==0)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");let nextRevision=validated.revision+1,nextState={...validated,revision:nextRevision},filePath=workflowGateStatePath(directory,validated.sessionID);await fsp2.mkdir(path11.dirname(filePath),{recursive:!0}),await writeAtomicJson2(filePath,nextState),Object.assign(state,nextState),rememberState(directory,nextState)})}async function withSessionStateMutation(directory,sessionID,action){let key=stateCacheKey(directory,sessionID),previous=pendingStateMutationsByProjectSession.get(key)??Promise.resolve(),release,current=new Promise((resolve8)=>{release=resolve8}),queued=previous.then(()=>current);pendingStateMutationsByProjectSession.set(key,queued),await previous;try{let lock=await acquireSessionStateMutationLock(directory,sessionID);try{return await action()}finally{await releaseSessionStateMutationLock(lock)}}finally{if(release(),pendingStateMutationsByProjectSession.get(key)===queued)pendingStateMutationsByProjectSession.delete(key)}}async function acquireSessionStateMutationLock(directory,sessionID){let lockPath=workflowGateStateLockPath(directory,sessionID);await fsp2.mkdir(path11.dirname(lockPath),{recursive:!0});for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await fsp2.open(lockPath,"wx"),lock={ownerToken:randomUUID2(),pid:process.pid,createdAtMs:_test_exports.nowMs()};try{await handle.writeFile(JSON.stringify(lock),"utf-8"),await handle.close()}catch(error49){throw await removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken),error49}return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedSessionStateMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow gate state is being mutated by another process; retry after that session transition finishes")}async function releaseSessionStateMutationLock(lock){try{await removeSessionStateMutationLockIfOwned(lock.path,lock.ownerToken)}catch{}}async function reclaimAbandonedSessionStateMutationLock(lockPath){let lock=await readSessionStateMutationLock(lockPath);if(lock){if(_test_exports.isProcessAlive(lock.pid))return!1;return removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp2.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp2.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp2.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeSessionStateMutationLockIfOwned(lockPath,ownerToken){let lock=await readSessionStateMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await fsp2.rm(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error49){return error49.code!=="ESRCH"}}async function readPrWorkflowGateStateFromDisk(directory,sessionID){let filePath=workflowGateStatePath(directory,sessionID),raw;try{raw=await fsp2.readFile(filePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(!parsed.success)throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is invalid`);return parsed.data}function rememberState(directory,state){let cacheKey=stateCacheKey(directory,state.sessionID);trackedStatesByProjectSession.delete(cacheKey),trackedStatesByProjectSession.set(cacheKey,state);while(trackedStatesByProjectSession.size>MAX_TRACKED_SESSIONS){let oldestKey=trackedStatesByProjectSession.keys().next().value;if(!oldestKey)break;trackedStatesByProjectSession.delete(oldestKey)}}function stateCacheKey(directory,sessionID){let resolved=path11.normalize(path11.resolve(directory));return`${process.platform==="win32"?resolved.toLowerCase():resolved}\x00${normalizeSessionID(sessionID)}`}function workflowGateStatePath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateRelativePath(sessionID))}function workflowGateStateLockPath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateLockRelativePath(sessionID))}function workflowGateStateLockRelativePath(sessionID){return path11.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path11.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.json`)}function prWorkflowSessionFileStem(sessionID){let normalized=normalizeSessionID(sessionID),slug=normalized.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)||"session",digest2=createHash5("sha256").update(normalized).digest("hex").slice(0,12);return`${slug}-${digest2}`}function normalizeSessionID(sessionID){let normalized=sessionID.trim();if(!normalized)throw Error("BLOCKED: PR workflow gate requires a non-empty sessionID");return normalized}async function writeAtomicJson2(filePath,value){let tempPath=`${filePath}.tmp.${process.pid}.${randomUUID2()}`,lastError;try{await fsp2.writeFile(tempPath,JSON.stringify(value,null,2),"utf-8");for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await _test_exports.rename(tempPath,filePath),lastError=void 0;break}catch(error49){lastError=error49;let code=error49.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")break;if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}if(lastError)throw lastError}finally{try{await fsp2.rm(tempPath,{force:!0})}catch{}}}async function writePrWorkflowAtomicJson(filePath,value){await writeAtomicJson2(filePath,value)}function isoNow(){return new Date().toISOString()}function delay(ms){return new Promise((resolve8)=>setTimeout(resolve8,ms))}var PR_REVIEW_BASE_DIMENSION_IDS,PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS,GATE_SCHEMA_VERSION=1,MAX_TRACKED_SESSIONS=200,MAX_WORKFLOW_BATCHES=128,WINDOWS_RENAME_MAX_RETRIES3=3,RENAME_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_MAX_ATTEMPTS=50,STATE_MUTATION_LOCK_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS=30000,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",WORKFLOW_GATE_DIR="pr-workflow-gates",trackedStatesByProjectSession,pendingStateMutationsByProjectSession,PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrReviewValidationBatchRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowGateStateSchema,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,_test_exports,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,REVIEWER_CLASSIFICATIONS,REVIEWER_EVIDENCE_TYPES,REVIEW_SEVERITIES,CRITIC_STATUSES,FEEDBACK_CLASSIFICATIONS;var init_pr_workflow_gate=__esm(()=>{init_zod();init_lane_output_store();init_pending_delegations();init_workspace_snapshot();init_constants();init_schema();init_tool_metadata();init_utils2();PR_REVIEW_BASE_DIMENSION_IDS=["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"],PR_REVIEW_REQUIRED_MICRO_LANE_IDS=["auth-identity-secrets","untrusted-input-boundaries","subprocess-platform","concurrency-state","dependencies-build-release","api-schema-migrations","test-infrastructure","ui-accessibility-i18n","privacy-observability","generated-provenance","unclassified-risk"],PR_REVIEW_DEPTH_TIER_THRESHOLDS={smallMaxChangedLines:50,smallMaxChangedFiles:3,mediumMaxChangedLines:500,mediumMaxChangedFiles:20},PR_REVIEW_BASE_LANE_FLOORS={S:1,M:3,L:PR_REVIEW_BASE_DIMENSION_IDS.length};trackedStatesByProjectSession=new Map,pendingStateMutationsByProjectSession=new Map,PrReviewBaseDimensionIdSchema=exports_external.enum(["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"]),PrReviewBaseDispatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:PrReviewBaseDimensionIdSchema,ownedWorkflowLanes:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackLaneOwnershipSchema=exports_external.object({laneId:exports_external.string().min(1),ownedItemIds:exports_external.array(exports_external.string().min(1)).min(1)}).strict(),PrFeedbackVerificationRecordSchema=exports_external.object({batchId:exports_external.string().min(1),ownership:exports_external.array(PrFeedbackLaneOwnershipSchema).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackStageACheckReceiptSchema=exports_external.object({category:exports_external.enum(["build","typecheck","lint","diff-check","reproduction"]),workingDirectory:exports_external.string().min(1).optional(),obligationId:exports_external.string().min(1).optional(),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional(),command:exports_external.array(exports_external.string().min(1)).min(1),targets:exports_external.array(exports_external.string().min(1)).min(1).optional(),feedbackTargets:exports_external.array(exports_external.object({feedbackItemId:exports_external.string().min(1),target:exports_external.string().min(1),expectedBehavior:exports_external.string().min(8)}).strict()).min(1).optional(),durationMs:exports_external.number().nonnegative()}).strict(),PrFeedbackStageARecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),checks:exports_external.array(PrFeedbackStageACheckReceiptSchema).min(2).max(258),feedbackItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional(),applicableCategories:exports_external.array(exports_external.enum(["build","typecheck","lint"])).max(3).optional(),applicableObligations:exports_external.array(exports_external.object({id:exports_external.string().min(1),category:exports_external.enum(["build","typecheck","lint"]),workingDirectory:exports_external.string().min(1),source:exports_external.string().min(1),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional()}).strict()).max(256).optional(),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackGateBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),laneId:exports_external.string().min(1),itemIds:exports_external.array(exports_external.string().min(1)).min(1),revisionDigest:exports_external.string().min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackReadyToPublishRecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),validatedAt:exports_external.string().min(1)}).strict(),PrReviewValidationBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["council","reviewer","critic"]),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:exports_external.string().min(1),reviewItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackScopeDeclarationRecordSchema=exports_external.object({taskId:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/),files:exports_external.array(exports_external.string().min(1)).min(1).max(1e4),revisionDigest:exports_external.string().min(1),declaredAt:exports_external.string().min(1),consumedByCallId:exports_external.string().min(1).optional()}).strict(),PrWorkflowGateStateSchema=exports_external.object({schemaVersion:exports_external.literal(GATE_SCHEMA_VERSION),revision:exports_external.number().int().nonnegative().default(0),sessionID:exports_external.string().min(1),mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),activatedAt:exports_external.string().min(1),updatedAt:exports_external.string().min(1),prHeadSha:exports_external.string().min(1).optional(),prReviewBaseRef:exports_external.string().min(1).optional(),prReviewBaseSha:exports_external.string().min(1).optional(),prReviewDepthTier:exports_external.enum(["S","M","L"]).optional(),prReviewDiffStats:exports_external.object({changedLines:exports_external.number().int().nonnegative(),changedFiles:exports_external.number().int().nonnegative(),hasSubmoduleChange:exports_external.boolean().default(!1)}).strict().optional(),prReviewBaseDispatches:exports_external.array(PrReviewBaseDispatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBaseDispatch:PrReviewBaseDispatchRecordSchema.optional(),prReviewTriggerEvalPath:exports_external.string().min(1).optional(),prReviewValidationBatches:exports_external.array(PrReviewValidationBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewArtifactBoundaries:exports_external.array(exports_external.enum(["post_explorer","post_reviewer","post_critic"])).max(3).optional(),prReviewHandoffPath:exports_external.string().min(1).optional(),prReviewHandoffRequired:exports_external.boolean().optional(),prFeedbackInventory:exports_external.array(exports_external.string().min(1)).min(1).optional(),prFeedbackVerifications:exports_external.array(PrFeedbackVerificationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackVerification:PrFeedbackVerificationRecordSchema.optional(),prFeedbackStageA:PrFeedbackStageARecordSchema.optional(),prFeedbackGateBatches:exports_external.array(PrFeedbackGateBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackReadyToPublish:PrFeedbackReadyToPublishRecordSchema.optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();PR_FEEDBACK_PHASE_ORDER=["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"];PR_FEEDBACK_PHASE_ROLE={"stage-b-reviewer":"reviewer","stage-b-test":"test_engineer","closeout-reviewer":"reviewer","closeout-critic":"critic"};_test_exports={workflowGateStateRelativePath,workflowGateStateLockRelativePath,resetTrackedStateCache:()=>{trackedStatesByProjectSession.clear(),pendingStateMutationsByProjectSession.clear(),_test_exports.beforeTerminalClear=void 0},beforeTerminalClear:void 0,resolveCurrentGitHead,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamRemoteRef,resolveExactRemoteBranchHead,resolveCommitCountSince,resolveIsWorkingTreeClean,resolveIsExactSingleChildCommit,resolvePrReviewDiffStats,resolvePrWorkflowRevisionDigest,resolveRemoteRefsContainingHead,parseCriticVerdict,isProcessAlive,rename:fsp2.rename,nowMs:()=>Date.now()};PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","get_async_result","get_async_status","prepare_pr_workflow_checkout"]),PR_REVIEW_CONTROLLER_TOOLS=new Set(["parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["prepare_pr_feedback_scope","run_pr_feedback_stage_a"]);PR_REVIEW_READ_ONLY_TOOL_NAMES=new Set(["ast_grep_search","codesearch","glob","grep","lsp","open","read","search","skill","tree","view","webfetch","websearch"]);REVIEWER_CLASSIFICATIONS=new Set(["CONFIRMED","DISPROVED","UNVERIFIED","PRE_EXISTING"]),REVIEWER_EVIDENCE_TYPES=new Set(["STRUCTURALLY_PROVEN","EXECUTION_PROVEN","STATIC_TRACE_PROVEN","PLAUSIBLE_BUT_UNVERIFIED"]),REVIEW_SEVERITIES=new Set(["CRITICAL","HIGH","MEDIUM","LOW","INFO","NONE"]),CRITIC_STATUSES=new Set(["UPHELD","DOWNGRADED","DISPROVED","NEEDS_MORE_EVIDENCE"]),FEEDBACK_CLASSIFICATIONS=new Set(["CONFIRMED","PARTIAL","DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"])});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,reasonStartIndex=knownMode?1:0,reason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500)||void 0;if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
170
+ `).some((line)=>GITLINK_MODE_PATTERN.test(line.trim()));return{changedLines,changedFiles,hasSubmoduleChange}}async function resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha){if(!isSafeGitRevisionToken(baseSha)||!isSafeGitRevisionToken(prHeadSha))return null;let range=`${baseSha}...${prHeadSha}`,output=await runGitAsync(directory,["diff","--no-renames","--numstat",range]);if(output===null)return null;let changedLines=0,changedFiles=0;for(let line of output.split(`
171
+ `)){let trimmed=line.trim();if(trimmed.length===0)continue;let fields=trimmed.split("\t");if(fields.length<3)return null;let added=fields[0]==="-"?0:Number.parseInt(fields[0],10),deleted=fields[1]==="-"?0:Number.parseInt(fields[1],10);if(Number.isNaN(added)||Number.isNaN(deleted))return null;changedFiles+=1,changedLines+=added+deleted}let rawOutput=await runGitAsync(directory,["diff","--raw",range]);if(rawOutput===null)return null;let hasSubmoduleChange=rawOutput.split(`
172
+ `).some((line)=>GITLINK_MODE_PATTERN.test(line.trim()));return{changedLines,changedFiles,hasSubmoduleChange}}function isSafeGitRevisionToken(value){return/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")}function resolveCurrentUpstreamRemoteRef(directory){let upstream=runGit(directory,["rev-parse","--symbolic-full-name","@{upstream}"]);if(!upstream?.startsWith("refs/remotes/")||upstream.endsWith("/HEAD"))return null;return upstream}function resolveCurrentUpstreamPushTarget(directory){let localBranchRef=runGit(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=runGit(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}async function resolveCurrentUpstreamPushTargetAsync(directory){let localBranchRef=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=await runGitAsync(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}function resolveExactRemoteBranchHead(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=runGit(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}async function resolveExactRemoteBranchHeadAsync(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=await runGitAsync(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}function resolveGitControlStateDigest(directory){let head=runGit(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=runGit(directory,["symbolic-ref","--quiet","HEAD"]),upstream=resolveCurrentUpstreamPushTarget(directory),refs=runGit(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=runGit(directory,["config","--null","--show-origin","--show-scope","--list"]),index=runGit(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}async function resolveGitControlStateDigestAsync(directory){let head=await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]),upstream=await resolveCurrentUpstreamPushTargetAsync(directory),refs=await runGitAsync(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=await runGitAsync(directory,["config","--null","--show-origin","--show-scope","--list"]),index=await runGitAsync(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}function resolveIsWorkingTreeClean(directory){let status=runGit(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}async function resolveIsWorkingTreeCleanAsync(directory){let status=await runGitAsync(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}function resolveCommitCountSince(directory,baseHeadSha,currentHeadSha){let output=runGit(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}async function resolveCommitCountSinceAsync(directory,baseHeadSha,currentHeadSha){let output=await runGitAsync(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}function resolveIsExactSingleChildCommit(directory,baseHeadSha,currentHeadSha){let base=runGit(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),current=runGit(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`]);if(!base||!current)return null;let commitAndParents=runGit(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}async function resolveIsExactSingleChildCommitAsync(directory,baseHeadSha,currentHeadSha){let base=await runGitAsync(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),current=await runGitAsync(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`]);if(!base||!current)return null;let commitAndParents=await runGitAsync(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}function resolveRemoteRefsContainingHead(directory,headSha){let output=runGit(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}async function resolveRemoteRefsContainingHeadAsync(directory,headSha){let output=await runGitAsync(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}function resolvePrWorkflowRevisionDigest(directory,baseHeadSha){let projectRoot=path10.resolve(directory),baseHead=runGit(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),diffNames=runGit(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha]),porcelain=runGit(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!baseHead||diffNames===null||porcelain===null)return null;let porcelainPaths=parsePorcelainPaths(porcelain);if(!porcelainPaths)return null;let changedPaths=[...new Set([...parseNulPaths(diffNames),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>REVISION_MAX_FILES)return null;let hash2=createHash4("sha256");hash2.update(`base\x00${baseHead}\x00`);let totalBytes=0;for(let relativePath of changedPaths){let resolvedPath=path10.resolve(projectRoot,relativePath),relativeToRoot=path10.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path10.isAbsolute(relativeToRoot))return null;hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=fs7.lstatSync(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return null}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${fs7.readlinkSync(resolvedPath)}\x00`);continue}catch{return null}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>REVISION_MAX_TOTAL_BYTES)return null;try{hash2.update(`file\x00${stats2.mode}\x00`),hash2.update(fs7.readFileSync(resolvedPath)),hash2.update("\x00")}catch{return null}}return hash2.digest("hex")}async function resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha){let projectRoot=path10.resolve(directory),[baseHead,diffNames,porcelain]=await Promise.all([runGitAsync(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),runGitAsync(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha]),runGitAsync(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])]);if(!baseHead||diffNames===null||porcelain===null)return null;let porcelainPaths=parsePorcelainPaths(porcelain);if(!porcelainPaths)return null;let changedPaths=[...new Set([...parseNulPaths(diffNames),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>REVISION_MAX_FILES)return null;let hash2=createHash4("sha256");hash2.update(`base\x00${baseHead}\x00`);let totalBytes=0,chunksSinceYield=0;for(let relativePath of changedPaths){let resolvedPath=path10.resolve(projectRoot,relativePath),relativeToRoot=path10.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path10.isAbsolute(relativeToRoot))return null;hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=await fs7.promises.lstat(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return null}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${await fs7.promises.readlink(resolvedPath)}\x00`);continue}catch{return null}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>REVISION_MAX_TOTAL_BYTES)return null;hash2.update(`file\x00${stats2.mode}\x00`);let handle;try{handle=await fs7.promises.open(resolvedPath,"r");let buffer=Buffer.allocUnsafe(REVISION_READ_CHUNK_BYTES);for(let position=0;position<stats2.size;){let length=Math.min(REVISION_READ_CHUNK_BYTES,stats2.size-position),{bytesRead}=await handle.read(buffer,0,length,position);if(bytesRead<=0)return null;if(hash2.update(buffer.subarray(0,bytesRead)),position+=bytesRead,chunksSinceYield++,chunksSinceYield>=REVISION_YIELD_EVERY_CHUNKS)chunksSinceYield=0,await _internals6.yieldControl()}hash2.update("\x00")}catch{return null}finally{await handle?.close().catch(()=>{return})}}return hash2.digest("hex")}function parseNulPaths(output){return output.split("\x00").filter((entry)=>entry.length>0)}function parsePorcelainPaths(output){let entries=parseNulPaths(output),paths=[];for(let index=0;index<entries.length;index++){let entry=entries[index];if(entry.length<4||entry[2]!==" ")return null;let status=entry.slice(0,2),changedPath=entry.slice(3);if(!changedPath)return null;if(paths.push(changedPath),status.includes("R")||status.includes("C")){let originalPath=entries[++index];if(!originalPath)return null;paths.push(originalPath)}}return[...new Set(paths)]}function parsePorcelainV2Snapshot(output){let records=output.split("\x00"),headers=[];while(records[0]?.startsWith("# "))headers.push(records.shift());let oidMatch=headers.join(`
173
+ `).match(/^# branch\.oid (.+)$/m);if(!oidMatch)return null;let gitHead=/^[0-9a-f]{6,64}$/i.test(oidMatch[1])?oidMatch[1]:oidMatch[1]==="(initial)"?null:null,paths=[];for(let index=0;index<records.length;index++){let record2=records[index];if(!record2)continue;if(record2.startsWith("? ")){paths.push(record2.slice(2));continue}if(record2.startsWith("1 ")){let changedPath=porcelainV2PathAfterFields(record2,8);if(!changedPath)return null;paths.push(changedPath);continue}if(record2.startsWith("2 ")){let changedPath=porcelainV2PathAfterFields(record2,9),originalPath=records[++index];if(!changedPath||!originalPath)return null;paths.push(changedPath,originalPath);continue}if(record2.startsWith("u ")){let changedPath=porcelainV2PathAfterFields(record2,10);if(!changedPath)return null;paths.push(changedPath);continue}return null}return{gitHead,changedFiles:[...new Set(paths)]}}function porcelainV2PathAfterFields(record2,fields){let offset=0;for(let index=0;index<fields;index++){let delimiter=record2.indexOf(" ",offset);if(delimiter<0)return null;offset=delimiter+1}return record2.slice(offset)||null}function captureWorkspaceSnapshot(directory,optionsOrScope=null,prHeadShaArg=null){let scope=typeof optionsOrScope==="object"&&optionsOrScope!==null?optionsOrScope.scope??null:optionsOrScope,configuredPrHeadSha=(()=>{if(typeof optionsOrScope!=="object"||optionsOrScope===null)return prHeadShaArg;return optionsOrScope.prHeadSha??null})(),resolveCurrentPrHeadSha=typeof optionsOrScope==="object"&&optionsOrScope!==null&&optionsOrScope.resolveCurrentPrHeadSha===!0,upstreamBefore=resolveCurrentPrHeadSha?runGit(directory,["rev-parse","@{upstream}"]):null,porcelain=runGit(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),snapshot=porcelain===null?null:parsePorcelainV2Snapshot(porcelain),upstreamAfter=resolveCurrentPrHeadSha?runGit(directory,["rev-parse","@{upstream}"]):null,prHeadSha=resolveCurrentPrHeadSha?upstreamBefore&&upstreamBefore===upstreamAfter?upstreamBefore:null:configuredPrHeadSha;return{directory:path10.resolve(directory),gitHead:snapshot?.gitHead??null,dirtyHash:porcelain===null?null:digest(porcelain),changedFiles:snapshot?.changedFiles??null,prHeadSha,scope}}function changedFilesSinceSnapshot(directory,baseline){if(!baseline?.gitHead||baseline.changedFiles==null)return null;if(baseline.changedFiles.length>0)return null;let current=captureWorkspaceSnapshot(directory);if(!current.gitHead||current.changedFiles==null)return null;let changed=new Set(current.changedFiles);if(baseline.gitHead!==current.gitHead){let committed=runGit(directory,["diff","--name-only","-z",baseline.gitHead,current.gitHead]);if(committed===null)return null;for(let changedPath of parseNulPaths(committed))changed.add(changedPath)}return[...changed]}function workspaceSnapshotMatches(expected,current){if(!expected)return{ok:!0};if(path10.resolve(expected.directory)!==path10.resolve(current.directory))return{ok:!1,reason:`directory changed: expected ${expected.directory}, got ${current.directory}`};let checks3=["gitHead","dirtyHash","prHeadSha"];for(let key of checks3){let expectedValue=expected[key];if(expectedValue===null)continue;if(current[key]!==expectedValue)return{ok:!1,reason:`${key} changed: expected ${expectedValue}, got ${current[key]??"unknown"}`}}return{ok:!0}}function compareWorkspaceSnapshots(expected,current){let result=workspaceSnapshotMatches(expected,current);if(result.ok)return{stale:!1};return{stale:!0,reason:result.reason}}function digest(text){return createHash4("sha256").update(text).digest("hex")}var GIT_SNAPSHOT_TIMEOUT_MS=3000,GIT_SNAPSHOT_MAX_BUFFER=524288,REVISION_MAX_FILES=5000,REVISION_MAX_TOTAL_BYTES=67108864,REVISION_READ_CHUNK_BYTES=65536,REVISION_YIELD_EVERY_CHUNKS=16,GITLINK_MODE_PATTERN,compareWorkspaceSnapshot,_internals6;var init_workspace_snapshot=__esm(()=>{GITLINK_MODE_PATTERN=/^:\d{6} 160000 |^:160000 \d{6} /;compareWorkspaceSnapshot=workspaceSnapshotMatches;_internals6={spawnSync:child_process.spawnSync,yieldControl:()=>new Promise((resolve7)=>setImmediate(resolve7)),parsePorcelainV2Snapshot}});import{createHash as createHash5,randomUUID as randomUUID2}from"node:crypto";import{readFileSync as readFileSync6}from"node:fs";import*as fsp2 from"node:fs/promises";import*as path11 from"node:path";function computePrReviewDepthTier(stats2){if(!stats2)return"L";if(stats2.hasSubmoduleChange)return"L";if(stats2.changedLines<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.smallMaxChangedLines&&stats2.changedFiles<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.smallMaxChangedFiles)return"S";if(stats2.changedLines<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.mediumMaxChangedLines&&stats2.changedFiles<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.mediumMaxChangedFiles)return"M";return"L"}async function activatePrWorkflow(directory,sessionID,mode,options={}){let normalizedSessionID=normalizeSessionID(sessionID),existing=await readPrWorkflowGateState(directory,normalizedSessionID);if(existing?.mode===mode)return options.prHeadSha?bindPrWorkflowHead(directory,normalizedSessionID,options.prHeadSha):existing;if(existing)throw Error(`BLOCKED: session "${normalizedSessionID}" already has an active ${existing.mode} workflow; complete it before starting ${mode}`);let initialHead=options.prHeadSha?await assertCurrentCheckoutHead(directory,options.prHeadSha):void 0,timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:0,sessionID:normalizedSessionID,mode,activatedAt:timestamp,updatedAt:timestamp,...initialHead?{prHeadSha:initialHead}:{}};return await persistState(directory,nextState),nextState}async function readPrWorkflowGateState(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),state=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(state)rememberState(directory,state);else trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID));return state}async function withPrWorkflowCheckoutPreparationLock(directory,sessionID,action){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizedSessionID}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (which activates PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (which activates PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*". Run the appropriate command first, then retry checkout preparation.`);if(state.prHeadSha)throw Error(`BLOCKED: ${state.mode} checkout preparation is allowed only before the PR head is bound`);return action(state)})}async function clearPrWorkflowGateState(directory,sessionID,expectedRevision){let normalizedSessionID=normalizeSessionID(sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{if(expectedRevision!==void 0){let current=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(!current||current.revision!==expectedRevision)throw Error("BLOCKED: PR workflow gate state changed during terminal completion; revalidate the current session state before retrying")}try{await fsp2.rm(workflowGateStatePath(directory,normalizedSessionID),{force:!0})}catch(error49){if(error49.code!=="ENOENT")throw error49}trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID))})}async function abortPrWorkflow(directory,sessionID,options={}){let state=await requireAnyActiveState(directory,sessionID);if(options.expectedMode&&state.mode!==options.expectedMode)throw wrongModeError(state,options.expectedMode);if(state.prFeedbackReadyToPublish)throw Error(`BLOCKED: ${state.mode} is armed for publication; abort is blocked. Complete the workflow with complete_pr_workflow (or push the bound commit first) before aborting.`);let openLanes=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(openLanes.length>0){let laneIds=openLanes.map((record2)=>record2.laneId??record2.subagentSessionId??"unknown").filter(Boolean).slice(0,10).join(", ");throw Error(`BLOCKED: ${state.mode} abort refused while ${openLanes.length} PR workflow lane(s) are still in flight (lane ids: ${laneIds}). Collect their results or let them settle before aborting.`)}let sanitizedReason=typeof options.reason==="string"?options.reason.trim().slice(0,500):void 0,abortEvent={type:"pr_workflow_aborted",timestamp:isoNow(),sessionID:state.sessionID,mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:openLanes.length,...sanitizedReason?{reason:sanitizedReason}:{}};try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp2.appendFile(eventsPath,`${JSON.stringify(abortEvent)}
174
+ `,"utf-8")}catch{}return await clearPrWorkflowGateState(directory,sessionID,state.revision),{mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:openLanes.length}}async function bindPrWorkflowHead(directory,sessionID,prHeadSha){let state=await requireAnyActiveState(directory,sessionID),normalizedHead=normalizePrHeadSha(prHeadSha);if(await assertCurrentCheckoutHead(directory,normalizedHead),!state.prHeadSha)await assertPrReviewCleanCheckout(directory,state.mode);if(!state.prHeadSha&&state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);if(state.prHeadSha&&state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: active ${state.mode} workflow is bound to PR head "${state.prHeadSha}"; received "${normalizedHead}"`);if(state.prHeadSha===normalizedHead)return state;let nextState={...state,prHeadSha:normalizedHead,updatedAt:isoNow()};return await persistState(directory,nextState),nextState}async function bindPrReviewBase(directory,sessionID,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw Error("BLOCKED: only PR_REVIEW can bind a review merge base");let baseRef=options.baseRef.trim(),baseSha=normalizePrHeadSha(options.baseSha).toLowerCase();if(!baseRef)throw Error("BLOCKED: PR_REVIEW base_ref must not be empty");if(state.prReviewBaseRef&&state.prReviewBaseRef!==baseRef||state.prReviewBaseSha&&state.prReviewBaseSha!==baseSha)throw Error(`BLOCKED: active PR_REVIEW is bound to merge-base scope "${state.prReviewBaseRef??"(unbound)"}" at "${state.prReviewBaseSha??"(unbound)"}"; received "${baseRef}" at "${baseSha}"`);if(state.prReviewBaseRef===baseRef&&state.prReviewBaseSha===baseSha)return state;let prHeadSha=normalizePrHeadSha(options.prHeadSha).toLowerCase(),diffStats=await _test_exports.resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha);return state={...state,prReviewBaseRef:baseRef,prReviewBaseSha:baseSha,prReviewDepthTier:computePrReviewDepthTier(diffStats),...diffStats?{prReviewDiffStats:diffStats}:{},updatedAt:isoNow()},await persistState(directory,state),state}async function assertCurrentCheckoutHead(directory,expectedHead){let normalizedExpected=normalizePrHeadSha(expectedHead),currentHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!currentHead)throw Error(`BLOCKED: cannot resolve the current Git HEAD in "${directory}" to verify against PR head "${normalizedExpected}". This means Git could not resolve HEAD (the working directory may not be a Git repository, HEAD may be unborn, the commit object may be missing in a shallow clone, the Git binary may not be on PATH, or the bounded Git invocation may have timed out). Verify with: git -C "${directory}" rev-parse --verify HEAD^{commit}`);if(currentHead.toLowerCase()!==normalizedExpected.toLowerCase())throw Error(`BLOCKED: current checkout HEAD "${currentHead}" does not match PR head "${normalizedExpected}" (working directory: "${directory}"). Check out the exact PR head with: git -C "${directory}" switch --detach ${normalizedExpected}`);return normalizedExpected}async function assertPrReviewCleanCheckout(directory,mode="PR_REVIEW"){if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error(`BLOCKED: ${mode} requires a clean index and working tree at the exact PR head`)}async function assertPrFeedbackTrackingCheckout(directory,prHeadSha){let upstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!upstream)throw Error("BLOCKED: PR_FEEDBACK requires a current local branch bound to an exact remote name, remote branch ref, and remote-tracking ref before the first head bind; detached or non-tracking checkouts are not allowed");if(!(await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha))?.includes(upstream.remoteTrackingRef))throw Error(`BLOCKED: PR_FEEDBACK upstream "${upstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}" before the first head bind`)}async function enforcePrWorkflowDispatchLanesAsync(directory,sessionID,toolName){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return null;if(toolName===DISPATCH_TOOL_NAME)return state;if(toolName===BLOCKING_DISPATCH_TOOL_NAME)throw Error(`BLOCKED: active ${state.mode} workflow for session "${state.sessionID}" requires ${DISPATCH_TOOL_NAME}; ${BLOCKING_DISPATCH_TOOL_NAME} is not allowed`);return state}async function enforcePrReviewBaseDimensions(directory,sessionID,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");let normalizedLanes=normalizeWorkflowLanes(lanes),claimedDimensionIds=normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]);if(claimedDimensionIds.filter((laneId)=>!PR_REVIEW_BASE_DIMENSION_IDS.includes(laneId)).length>0){let expected=PR_REVIEW_BASE_DIMENSION_IDS.join(", "),received=claimedDimensionIds.join(", ")||"(none)";throw Error(`BLOCKED: PR_REVIEW base dispatch lane ids must be drawn from: ${expected}. Received: ${received}`)}if((state.prReviewDepthTier??"L")==="L"&&normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier L requires one dedicated lane per dimension; consolidated owned_workflow_lanes are allowed only at tiers S and M");let batchId=normalizeBatchId(options.batchId),previous=state.prReviewBaseDispatches??[];if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW base batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW base batch limit reached");let record2={batchId,lanes:normalizedLanes.map((lane)=>({laneId:lane.laneId,workflowLane:lane.workflowLane,...lane.ownedWorkflowLanes?{ownedWorkflowLanes:lane.ownedWorkflowLanes}:{}})),validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prReviewBaseDispatches:[...previous,record2],prReviewBaseDispatch:record2};return await persistState(directory,nextState),nextState}async function assertPrReviewBaseCoverageSettled(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),batches=state.prReviewBaseDispatches??[];if(batches.length===0)throw Error("BLOCKED: PR_REVIEW requires at least one base batch");let covered=new Set;for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt);for(let obligation of successful)covered.add(obligation)}let missing=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!covered.has(dimension));if(missing.length>0||covered.size!==PR_REVIEW_BASE_DIMENSION_IDS.length)throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete; missing dimensions: ${missing.join(", ")||"(none)"}`);return state}async function recordPrReviewValidationBatch(directory,sessionID,phase,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW validation dispatch requires a completed trigger evaluation");if(phase==="reviewer"&&(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state=await assertPrReviewValidationSettled(directory,sessionID,"council");else if(phase==="critic")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer");let normalizedLanes=normalizeWorkflowLanes(lanes);if((phase==="reviewer"||phase==="critic")&&normalizedLanes.some((lane)=>!lane.reviewItemIds?.length))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes require non-empty review_item_ids ownership`);if(phase==="reviewer"||phase==="critic"){assertNoDuplicates(normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),`PR_REVIEW ${phase} review item ownership`);let assigned=normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),required2=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state):derivePrReviewCriticInventory(directory,state);assertExactStringSet(assigned,required2,`PR_REVIEW ${phase} ownership`)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewValidationBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW validation batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached");let record2={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"):previous,nextState={...state,updatedAt:isoNow(),prReviewValidationBatches:[...retained,record2]};return await persistState(directory,nextState),nextState}async function assertPrReviewValidationSettled(directory,sessionID,phase){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),declaredPhases=new Set((state.prReviewValidationBatches??[]).map((batch)=>batch.phase)),phases=phase?[phase]:["council","reviewer","critic"].filter((candidate)=>declaredPhases.has(candidate));for(let requiredPhase of phases){let validationBatches=state.prReviewValidationBatches??[],forbiddenSubagentSessionIds=new Set;if(requiredPhase==="critic")for(let reviewerBatch of validationBatches.filter((batch)=>batch.phase==="reviewer"))for(let record2 of findByBatchId(directory,reviewerBatch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)forbiddenSubagentSessionIds.add(subagentSessionId)}let batches=validationBatches.filter((batch)=>batch.phase===requiredPhase);if(requiredPhase==="reviewer"){let latestCouncilIndex=-1;for(let index=0;index<validationBatches.length;index++)if(validationBatches[index]?.phase==="council")latestCouncilIndex=index;if(latestCouncilIndex>=0)batches=validationBatches.slice(latestCouncilIndex+1).filter((batch)=>batch.phase==="reviewer")}if(batches.length===0)throw Error(requiredPhase==="reviewer"&&declaredPhases.has("council")?"BLOCKED: PR_REVIEW requires at least one reviewer batch after the latest council batch":`BLOCKED: PR_REVIEW requires at least one ${requiredPhase} batch`);let allObligations=new Set(batches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane))),settled=new Set,hasFullySuccessfulExactBatch=!1;for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${requiredPhase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds);if(successful.size===batch.lanes.length&&batch.lanes.every((lane)=>successful.has(lane.workflowLane)))hasFullySuccessfulExactBatch=!0;for(let obligation of successful)settled.add(obligation)}if((requiredPhase==="reviewer"||requiredPhase==="critic")&&!hasFullySuccessfulExactBatch)throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} requires one fully successful exact batch; complementary partial retries are not a coherent verdict set`);let missing=[...allObligations].filter((obligation)=>!settled.has(obligation));if(missing.length>0)throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} obligations lack successful exact artifacts: ${missing.join(", ")}`)}return state}async function declarePrFeedbackInventory(directory,sessionID,inventoryIds,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let normalizedInventory=normalizeInventoryIds(inventoryIds);if(state.prFeedbackInventory){if(!sameStringArray(state.prFeedbackInventory,normalizedInventory))throw Error("BLOCKED: PR_FEEDBACK inventory is immutable after declaration");return state}let nextState={...state,updatedAt:isoNow(),prFeedbackInventory:normalizedInventory,prFeedbackVerifications:[]};return await persistState(directory,nextState),nextState}async function enforcePrFeedbackVerificationOwnership(directory,sessionID,ownership,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory||inventory.length===0)throw Error(`BLOCKED: PR_FEEDBACK verification for session "${state.sessionID}" requires a declared feedback inventory before dispatch`);let normalizedOwnership=normalizeOwnership(ownership),inventorySet=new Set(inventory),claimedByItemId=new Map,previous=state.prFeedbackVerifications??[],batchId=normalizeBatchId(options.batchId);if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK verification batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached");for(let record3 of previous)for(let lane of record3.ownership)for(let itemId of lane.ownedItemIds)claimedByItemId.set(itemId,lane.laneId);for(let lane of normalizedOwnership)for(let itemId of lane.ownedItemIds){if(!inventorySet.has(itemId))throw Error(`BLOCKED: PR_FEEDBACK verification lane "${lane.laneId}" owns undeclared item "${itemId}"`);let previousLane=claimedByItemId.get(itemId);if(previousLane&&previousLane!==lane.laneId)throw Error(`BLOCKED: PR_FEEDBACK verification item "${itemId}" is owned by both "${previousLane}" and "${lane.laneId}"`);claimedByItemId.set(itemId,lane.laneId)}let record2={batchId,ownership:normalizedOwnership,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackVerifications:[...previous,record2],prFeedbackVerification:record2};return await persistState(directory,nextState),nextState}async function assertPrFeedbackVerificationSettled(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state),inventory=state.prFeedbackInventory,batches=state.prFeedbackVerifications??[];if(!inventory||batches.length===0)throw Error("BLOCKED: PR_FEEDBACK requires an immutable inventory and verification batches");let covered=new Set;for(let batch of batches){let successfulLaneIds=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.ownership.map((lane)=>({laneId:lane.laneId,workflowLane:lane.laneId})),"swarm-pr-feedback:verification",batch.validatedAt,!1,new Set,currentDigest);for(let lane of batch.ownership){if(!successfulLaneIds.has(lane.laneId))continue;if(!feedbackArtifactCoversItems(directory,state,batch.batchId,lane.laneId,lane.ownedItemIds))continue;for(let itemId of lane.ownedItemIds)covered.add(itemId)}}let missing=inventory.filter((itemId)=>!covered.has(itemId));if(missing.length>0||covered.size!==inventory.length)throw Error(`BLOCKED: PR_FEEDBACK verification ownership is incomplete; missing inventory items: ${missing.join(", ")||"(none)"}`);return state}async function recordPrFeedbackStageA(directory,sessionID,revisionDigest,checks3,options={}){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK Stage A receipt is stale because the working-tree revision changed during validation");if(checks3.length<2||checks3.length>258)throw Error("BLOCKED: PR_FEEDBACK Stage A requires two to 258 controller-created check receipts");let optionalCategoryOrder=["build","typecheck","lint"],applicableCategories=options.applicableCategories??optionalCategoryOrder.filter((category)=>checks3.some((check2)=>check2.category===category));if(assertNoDuplicates(applicableCategories,"PR_FEEDBACK Stage A applicable categories"),applicableCategories.some((category)=>!optionalCategoryOrder.includes(category)))throw Error("BLOCKED: PR_FEEDBACK Stage A applicability may contain only build, typecheck, and lint");let required2=new Set(["diff-check","reproduction",...applicableCategories]),singletonSeen=new Set,applicableObligations=[...options.applicableObligations??[]];assertNoDuplicates(applicableObligations.map(({id})=>id),"PR_FEEDBACK Stage A applicable obligations");let requiredObligationIds=new Set(applicableObligations.map(({id})=>id)),commandDigests=new Set,reproductionFeedbackItemIds=[];for(let check2 of checks3){if(["diff-check","reproduction"].includes(check2.category)&&singletonSeen.has(check2.category))throw Error(`BLOCKED: PR_FEEDBACK Stage A contains duplicate category "${check2.category}"`);if(singletonSeen.add(check2.category),required2.delete(check2.category),check2.obligationId){let obligation=applicableObligations.find((candidate)=>candidate.id===check2.obligationId);if(!obligation||obligation.category!==check2.category||obligation.workingDirectory!==(check2.workingDirectory??".")||!requiredObligationIds.delete(check2.obligationId))throw Error(`BLOCKED: PR_FEEDBACK Stage A receipt does not match one exact applicable obligation: ${check2.obligationId}`);let sourceContract=obligation.source.includes(".pr-validation.json#")?{path:obligation.source.slice(0,obligation.source.lastIndexOf("#")),id:obligation.source.slice(obligation.source.lastIndexOf("#")+1)}:void 0,requiredContract=obligation.validatorContract??sourceContract;if(requiredContract&&(check2.validatorContract?.path!==requiredContract.path||check2.validatorContract.id!==requiredContract.id))throw Error(`BLOCKED: PR_FEEDBACK Stage A obligation ${obligation.id} requires exact validator contract provenance`)}let commandDigest=createHash5("sha256").update(`${check2.obligationId??check2.category}\x00${check2.workingDirectory??"."}\x00${check2.command.join("\x00")}`).digest("hex");if(commandDigests.has(commandDigest))throw Error("BLOCKED: PR_FEEDBACK Stage A cannot reuse one command as multiple check receipts");if(commandDigests.add(commandDigest),check2.category==="diff-check"&&!sameStringArray(check2.command,["git","diff","--check"]))throw Error("BLOCKED: PR_FEEDBACK Stage A diff-check receipt is not the exact git diff --check command");if(check2.category==="reproduction"&&(!check2.targets?.length||!check2.feedbackTargets?.length||check2.targets.some((target)=>!check2.command.join(" ").includes(target))))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction receipt requires exact selected targets");if(check2.category==="reproduction"){if(reproductionFeedbackItemIds=check2.feedbackTargets.map((mapping)=>mapping.feedbackItemId),assertNoDuplicates(reproductionFeedbackItemIds,"PR_FEEDBACK Stage A reproduction feedback item mappings"),check2.feedbackTargets.some((mapping)=>!check2.targets.includes(mapping.target)))throw Error("BLOCKED: PR_FEEDBACK Stage A feedback mappings must reference exact executed reproduction targets")}}if(required2.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing required checks: ${[...required2].join(", ")}`);if(requiredObligationIds.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing applicable workspace obligations: ${[...requiredObligationIds].join(", ")}`);if(!sameStringArray(reproductionFeedbackItemIds,state.prFeedbackInventory??[]))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction must map every immutable feedback item exactly once and in declared order");let nextState={...state,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks3],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:optionalCategoryOrder.filter((category)=>applicableCategories.includes(category)),applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:[],prFeedbackReadyToPublish:void 0};return await persistState(directory,nextState),nextState}async function recordPrFeedbackGateBatch(directory,sessionID,phase,lane,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory?.length)throw Error("BLOCKED: PR_FEEDBACK ordered gates require an immutable feedback inventory");let normalized=normalizeOwnership([lane])[0];if(!sameStringArray(normalized.ownedItemIds,inventory))throw Error(`BLOCKED: PR_FEEDBACK ${phase} must own every inventory item exactly once and in declared order`);let phaseIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(phase),prerequisite=PR_FEEDBACK_PHASE_ORDER[phaseIndex-1];if(prerequisite)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,prerequisite);let{prFeedbackStageA:stageA,prFeedbackInventory:refreshedInventory}=state,currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(!stageA||!refreshedInventory||stageA.revisionDigest!==currentDigest||!sameStringArray(stageA.feedbackItemIds??[],refreshedInventory)||options.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires fresh Stage A checks on the current revision`);let batchId=normalizeBatchId(options.batchId),previous=state.prFeedbackGateBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK gate batch id "${batchId}" is already recorded`);let retained=previous.filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<phaseIndex),record2={batchId,phase,laneId:normalized.laneId,itemIds:normalized.ownedItemIds,revisionDigest:currentDigest,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackGateBatches:[...retained,record2]};return await persistState(directory,nextState),nextState}async function assertPrFeedbackGatePhaseSettled(directory,sessionID,phase){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(state.prFeedbackStageA?.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} cannot use stale Stage A evidence`);if(!sameStringArray(state.prFeedbackStageA?.feedbackItemIds??[],state.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} Stage A reproduction is not bound to the exact immutable feedback inventory`);let batch=[...state.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===phase);if(!batch||batch.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} has no validation batch on the current revision`);if(!successfulObligationsFromExactBatch(directory,state,batch.batchId,[{laneId:batch.laneId,workflowLane:phase,reviewItemIds:batch.itemIds}],`swarm-pr-feedback:${phase}`,batch.validatedAt,!0,new Set,currentDigest).has(phase))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires one complete, non-degraded positive verdict row per inventory item`);if(findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===batch.laneId)?.workspace?.dirtyHash!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} artifact is not bound to the current revision digest`);return assertIndependentFeedbackGateSessions(directory,state,phase),state}function assertIndependentFeedbackGateSessions(directory,state,throughPhase){let throughIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(throughPhase),batches=(state.prFeedbackGateBatches??[]).filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<=throughIndex),seenSessions=new Set;for(let batch of batches){let matching=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).filter((record3)=>record3.laneId===batch.laneId);if(matching.length!==1)throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} must resolve from exactly one durable child session`);let record2=matching[0],expectedRole=PR_FEEDBACK_PHASE_ROLE[batch.phase];if(!(record2.normalizedAgent===expectedRole||expectedRole==="critic"&&record2.normalizedAgent.startsWith("critic_")))throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} requires role ${expectedRole}, received ${record2.normalizedAgent||"(unknown)"}`);if(seenSessions.has(record2.subagentSessionId))throw Error(`BLOCKED: PR_FEEDBACK independent phases reused child session "${record2.subagentSessionId}"`);seenSessions.add(record2.subagentSessionId)}}async function assertPrFeedbackReadyToPublish(directory,sessionID){let state=await assertPrFeedbackVerificationSettled(directory,sessionID);for(let phase of PR_FEEDBACK_PHASE_ORDER)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,phase);return state}async function assertPrFeedbackPublicationArmed(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),armed=state.prFeedbackReadyToPublish;if(!armed)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK changed after publication was armed; rerun Stage A and every independent gate");if((await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim()!==armed.localHead)throw Error("BLOCKED: PR_FEEDBACK current Git HEAD changed after publication was armed");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK working tree changed after publication was armed");let currentTarget=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!currentTarget||currentTarget.remoteName!==armed.remoteName||currentTarget.remoteBranchRef!==armed.remoteBranchRef||currentTarget.remoteTrackingRef!==armed.remoteRef)throw Error("BLOCKED: PR_FEEDBACK upstream publication target changed after publication was armed");return state}async function markPrReviewTriggerEvaluationComplete(directory,sessionID,artifactPath){let state=await assertPrReviewBaseCoverageSettled(directory,sessionID),normalizedPath=artifactPath.trim();if(!normalizedPath)throw Error("BLOCKED: PR_REVIEW trigger artifact path is required");let nextState={...state,updatedAt:isoNow(),prReviewTriggerEvalPath:normalizedPath};return await persistState(directory,nextState),nextState}async function assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW findings persistence requires the trigger evaluation artifact");let persistedBoundaries=state.prReviewArtifactBoundaries??[],boundaryOrder=["post_explorer","post_reviewer","post_critic"],boundaryIndex=boundaryOrder.indexOf(boundary),requiredPriorBoundary=boundaryOrder[boundaryIndex-1];if(requiredPriorBoundary&&!persistedBoundaries.includes(requiredPriorBoundary))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings require the prior ${requiredPriorBoundary} checkpoint`);if(persistedBoundaries.some((persisted)=>boundaryOrder.indexOf(persisted)>boundaryIndex))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings cannot be persisted after a later checkpoint`);if(boundary==="post_reviewer")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer");else if(boundary==="post_critic"){if(await assertPrReviewValidationSettled(directory,sessionID,"reviewer"),derivePrReviewCriticInventory(directory,state).length>0)state=await assertPrReviewValidationSettled(directory,sessionID,"critic")}if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==runId)throw Error(`BLOCKED: PR_REVIEW artifacts are already bound to run "${state.prReviewArtifactRunId}"`);let expectedFindingIds=derivePrReviewCandidateInventory(directory,state),normalizedFindingIds=[...new Set(findingIds)].sort();if(normalizedFindingIds.length!==findingIds.length||JSON.stringify(normalizedFindingIds)!==JSON.stringify([...expectedFindingIds].sort()))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings must exactly cover the discovered candidate inventory`);return state}async function assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,boundary,records){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(boundary==="post_explorer"){for(let record2 of records)if(record2.status!=="PENDING"||record2.next_action!=="route_to_reviewer")throw Error(`BLOCKED: PR_REVIEW post_explorer record ${record2.finding_id} must remain PENDING and route_to_reviewer`);return}let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state),criticVerdicts=boundary==="post_critic"?deriveLatestPrReviewCriticVerdicts(directory,state):void 0;for(let record2 of records){let reviewer=reviewerVerdicts.get(record2.finding_id);if(!reviewer)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} has no authoritative reviewer verdict`);if(record2.severity&&record2.severity!==reviewer.severity)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} severity differs from its reviewer verdict`);let requiresCritic=reviewer.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(reviewer.severity);if(boundary==="post_reviewer"){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification;if(record2.status!==expectedStatus)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} status differs from its reviewer verdict`);let expectedAction=requiresCritic?"route_to_critic":reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} action does not match reviewer disposition`);continue}if(!requiresCritic){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification,expectedAction=reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.status!==expectedStatus||record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} cannot override its non-critic reviewer disposition`);continue}let critic=criticVerdicts?.get(record2.finding_id);if(!critic)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} has no authoritative critic verdict`);if(record2.severity&&record2.severity!==critic.severity)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} severity differs from its critic verdict`);if(critic.status==="DISPROVED"){if(record2.status!=="DISPROVED"||record2.next_action!=="suppress_with_reason")throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} must preserve the critic DISPROVED disposition`)}else if(record2.status!=="CONFIRMED"||!["report","handoff_to_feedback"].includes(record2.next_action))throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} action does not match its critic verdict`)}}async function markPrReviewArtifactBoundary(directory,sessionID,runId,boundary,artifactPath,findingIds,handoffRequired){let state=await assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds),boundaries=new Set(state.prReviewArtifactBoundaries??[]);boundaries.add(boundary);let nextState={...state,updatedAt:isoNow(),prReviewArtifactRunId:runId,prReviewFindingsPath:artifactPath,prReviewArtifactBoundaries:[...boundaries],prReviewHandoffRequired:handoffRequired};return await persistState(directory,nextState),nextState}async function markPrReviewHandoffComplete(directory,sessionID,runId,artifactPath){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(state.prReviewArtifactRunId!==runId||!(state.prReviewArtifactBoundaries??[]).includes("post_critic"))throw Error("BLOCKED: PR_REVIEW handoff requires the final findings boundary for the same run");let nextState={...state,updatedAt:isoNow(),prReviewHandoffPath:artifactPath};return await persistState(directory,nextState),nextState}async function declarePrFeedbackScope(directory,sessionID,taskId,files){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state),previous=state.prFeedbackScopes??[];if(previous.find((entry)=>entry.taskId===taskId)?.consumedByCallId)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed; use a fresh task_id for any retry`);let record2={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record2]};return await persistState(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_FEEDBACK")return null;let declaration=(state.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID){let declaration=await resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId);if(!declaration)return null;if(declaration.consumedByCallId&&declaration.consumedByCallId!==callID)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed by another Task call`);if(declaration.consumedByCallId===callID)return declaration;let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),nextState={...state,updatedAt:isoNow(),prFeedbackScopes:(state.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?{...entry,consumedByCallId:callID}:entry)};return await persistState(directory,nextState),{...declaration,consumedByCallId:callID}}async function validatePrFeedbackScopeBinding(directory,binding){if(!binding.workflowSessionId||!binding.workflowRevisionDigest)return!1;let declaration=await resolvePrFeedbackScopeDeclaration(directory,binding.workflowSessionId,binding.taskId);return Boolean(declaration&&declaration.consumedByCallId===binding.dispatchCallId&&declaration.revisionDigest===binding.workflowRevisionDigest&&JSON.stringify(declaration.files)===JSON.stringify(binding.files))}async function enforcePrWorkflowToolBefore(directory,sessionID,toolName,args2,generatedAgentNames=[]){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedRoles=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)).map((field)=>{let value=args2?.[field];if(typeof value!=="string"||!value.trim())return"";return resolveGeneratedAgentRole(value.trim(),generatedAgentNames)}),isDirectWrite=WRITE_TOOL_NAMES.includes(normalizedTool),command=typeof args2?.command==="string"?args2.command.trim():"",serializedArgs=JSON.stringify(args2??{}),referencesProtectedWorkflowEvidence=containsProtectedWorkflowPath(command||serializedArgs),isInternalWorkflowTool=isPrWorkflowControllerTool(state.mode,normalizedTool),isShellTool=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1;if(isShellTool&&command.length>0){let trackingFetchTarget=state.prHeadSha?await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory):null;isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,{allowCheckout:!state.prHeadSha,allowFetch:!state.prHeadSha,allowTrackingFetch:Boolean(state.prHeadSha),trackingFetchTarget})}let isNamedReadOnlyTool=getPrWorkflowToolCapability(normalizedTool,state.mode)!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{});if(referencesProtectedWorkflowEvidence&&!isInternalWorkflowTool&&!isNamedReadOnlyTool&&!isReadOnlyShell)throw Error(`BLOCKED: active ${state.mode} workflow evidence under .swarm is controller-owned and cannot be modified directly`);let isShellCommandRequiringVerification=isShellTool&&command.length>0&&!isReadOnlyShell,isRemoteReviewTool=/(?:git|github|pull|(?:^|[_-])pr(?:[_-]|$)|issue|review)/i.test(normalizedTool),hasRemoteMutationVerb=/(?:^|[_-])(?:add|approve|cancel|close|comment|commit|convert|create|delete|dismiss|edit|mark|merge|push|ready|reopen|rerun|resolve|submit|transfer|unresolve|update)(?:[_-]|$)/i.test(normalizedTool),hasRemoteReadVerb=/(?:^|[_-])(?:github|git)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool)||/(?:^|[_-])(?:github|git)[_-]+(?:pull[_-]+request|pr|issue|review[_-]+thread)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool),isRemoteMutationTool=isRemoteReviewTool&&(hasRemoteMutationVerb||!hasRemoteReadVerb),isRemoteCheckoutTool=/(?:^|[_-])(?:github|git)[_-]+checkout(?:[_-]|$)/i.test(normalizedTool),isShellCheckout=(normalizedTool==="bash"||normalizedTool==="shell")&&(/\bgit\b(?:(?![;&|]).){0,200}\b(?:checkout|switch)\b/i.test(command)||/\bgh\s+pr\s+checkout\b/i.test(command)),isCanonicalReviewCheckout=/^git\s+switch\s+--detach\s+[0-9a-f]{40,64}$/i.test(command),detachedFeedbackSwitchMatch=command.match(/^git\s+switch\s+--detach\s+(\S+)$/i),isDetachedFeedbackCheckout=Boolean(detachedFeedbackSwitchMatch?.[1]&&isSafeGitRefToken(detachedFeedbackSwitchMatch[1]))||/^gh\s+pr\s+checkout\b.*\s--detach(?:\s|$)/i.test(command),containsGitCommitShell=isShellCommandRequiringVerification&&/\bgit\b(?:(?![;&|]).){0,200}\bcommit\b/i.test(command),isStandaloneGitCommitShell=containsGitCommitShell&&isSafeStandaloneGitCommit(command),isPublicationShell=isShellCommandRequiringVerification&&(/\bgit\b(?:(?![;&|]).){0,200}\bpush\b/i.test(command)||/\bgh\s+(?:api|pr|issue|run)\b/i.test(command)),isPublicationTool=!isInternalWorkflowTool&&isRemoteMutationTool,isCoderTask=isDirectAgentTask&&requestedRoles.length>0&&requestedRoles.every((role)=>role==="coder");if(state.mode==="PR_REVIEW"){if(!(isInternalWorkflowTool||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_REVIEW checkout must use standalone commands: fetch the PR head, verify the full commit object with `git cat-file -e <full_pr_head_sha>^{commit}`, then run `git switch --detach <full_pr_head_sha>` and bind that exact head before dispatching explorer lanes. Do not use `--track FETCH_HEAD`.");throw Error("BLOCKED: PR_REVIEW is read-only and fail-closed; only controller tools and positively classified observation tools are allowed, and every agent lane requires structured dispatch_lanes_async")}return}if(isDirectAgentTask&&!isCoderTask)throw Error("BLOCKED: PR_FEEDBACK reviewer, test, critic, explorer, and unknown agent lanes require structured dispatch_lanes_async provenance");if(!isInternalWorkflowTool&&!isDirectAgentTask&&!isDirectWrite&&!isShellTool&&!isNamedReadOnlyTool)throw Error("BLOCKED: PR_FEEDBACK rejects unclassified plugin/MCP tools; use positively classified observation tools, built-in structured write tools after verification, or the workflow controller");if(state.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK is armed for publication; the approved commit is immutable");if((containsGitCommitShell||isPublicationShell)&&hasUnsafeShellControlSyntax(command))throw Error("BLOCKED: PR_FEEDBACK publication commands must be standalone shell commands without control, redirection, or command-substitution syntax");if(containsGitCommitShell&&!isStandaloneGitCommitShell)throw Error("BLOCKED: PR_FEEDBACK commit must use a standalone git commit command after every ordered local gate passes");if(state.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(isNamedReadOnlyTool)return;if((normalizedTool==="bash"||normalizedTool==="shell")&&command.length>0&&isAllowedPrWorkflowReadOnlyShell(command,{allowCheckout:!1,allowFetch:!1,allowTrackingFetch:!1}))return;if(normalizedTool==="bash"||normalizedTool==="shell"){let armed=(await assertPrFeedbackPublicationArmed(directory,sessionID)).prFeedbackReadyToPublish;if(isSafeExactBoundPush(command,armed))return;throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed")}if(!state.prHeadSha&&isDetachedFeedbackCheckout)throw Error("BLOCKED: PR_FEEDBACK requires a tracked PR branch before the first head bind; detached checkout is valid for PR_REVIEW, not PR_FEEDBACK.");if(isStandaloneGitCommitShell){await assertPrFeedbackReadyToPublish(directory,sessionID);return}if(isPublicationShell||isPublicationTool)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; finish every ordered gate, create the one approved commit, and call complete_pr_workflow before publishing");if(isShellCommandRequiringVerification){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout must use a safe standalone pre-bind form: `gh pr checkout <number-or-url>` without force/submodule flags, or `git switch -c <local> --track <remote>/<branch>`. Detached checkouts are not allowed in PR_FEEDBACK. Then verify exact HEAD, a clean tree, and the intended upstream before dispatching feedback lanes.");throw Error("BLOCKED: PR_FEEDBACK shell commands fail closed unless they are explicit read-only intake or the one standalone approved git commit; use structured coder/write tools for fixes and run_pr_feedback_stage_a for validation")}if(!isDirectWrite&&!isShellCommandRequiringVerification&&!isRemoteMutationTool&&!isCoderTask&&normalizedTool!=="prepare_pr_feedback_scope")return;if(normalizedTool==="abort_pr_workflow")return;await assertPrFeedbackVerificationSettled(directory,sessionID)}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha){let state=await requireBoundState(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state.prHeadSha}"`);let open3=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(open3.length>0)throw Error(`BLOCKED: ${expectedMode} completion has ${open3.length} unsettled PR workflow lane(s)`);if(expectedMode==="PR_REVIEW"){if(await assertPrReviewCleanCheckout(directory),await assertPrReviewBaseCoverageSettled(directory,sessionID),!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW completion requires a persisted trigger evaluation artifact");if((state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council");await assertPrReviewValidationSettled(directory,sessionID,"reviewer");let criticInventory=derivePrReviewCriticInventory(directory,state);if(criticInventory.length>0){if(!(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic"))throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${criticInventory.join(", ")}`);await assertPrReviewValidationSettled(directory,sessionID,"critic")}let requiredArtifactBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state.prReviewArtifactBoundaries??[]),missingArtifactBoundaries=requiredArtifactBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state.prReviewFindingsPath||missingArtifactBoundaries.length>0)throw Error(`BLOCKED: PR_REVIEW completion requires durable findings checkpoints; missing: ${missingArtifactBoundaries.join(", ")||"findings path"}`);if(state.prReviewHandoffRequired&&!state.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact")}else{let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let localHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!localHead)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a verified local Git HEAD");if(await _test_exports.resolveCommitCountSinceAsync(directory,state.prHeadSha,localHead)!==1)throw Error("BLOCKED: PR_FEEDBACK publication requires exactly one descendant commit after the immutable intake head");if(await _test_exports.resolveIsExactSingleChildCommitAsync(directory,state.prHeadSha,localHead)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication commit must be a non-merge direct child of the immutable intake head");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication requires a clean index and working tree so all approved content is captured by the bound commit");let upstreamTarget=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!upstreamTarget)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a current branch bound to an exact remote name, remote branch ref, and remote-tracking ref");return await persistState(directory,{...readyState,updatedAt:isoNow(),prFeedbackReadyToPublish:{revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,validatedAt:isoNow()}}),"ready-to-publish"}if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK publication revision differs from the independently approved content digest");let publishedHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim(),remoteRefs=publishedHead?await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,publishedHead):null,remoteHead=await _test_exports.resolveExactRemoteBranchHeadAsync(directory,armed.remoteName,armed.remoteBranchRef);if(!publishedHead||publishedHead!==armed.localHead||!remoteRefs?.includes(armed.remoteRef)||remoteHead?.toLowerCase()!==armed.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK completion requires approved commit ${armed.localHead} at current Git HEAD and intended remote-tracking ref ${armed.remoteRef} at that exact commit`)}return await _test_exports.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,state.revision),"completed"}async function requireAnyActiveState(directory,sessionID){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*".`);return state}async function requireBoundState(directory,sessionID,expectedMode){let state=await requireAnyActiveState(directory,sessionID);if(state.mode!==expectedMode)throw wrongModeError(state,expectedMode);if(!state.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")await assertCurrentCheckoutHead(directory,state.prHeadSha),await assertPrReviewCleanCheckout(directory);return state}function wrongModeError(state,expectedMode){return Error(`BLOCKED: session "${state.sessionID}" is active in ${state.mode}, not ${expectedMode}`)}function normalizeWorkflowLanes(lanes){if(!Array.isArray(lanes)||lanes.length===0)throw Error("BLOCKED: PR workflow lane validation requires at least one lane");let normalized=lanes.map((lane)=>{let workflowLane=lane.workflowLane?.trim(),laneId=lane.laneId?.trim()||workflowLane;if(!workflowLane||!laneId)throw Error("BLOCKED: PR workflow lane validation requires every lane to have non-empty laneId and workflow_lane values");let reviewItemIds=lane.reviewItemIds?.map((itemId)=>itemId.trim());if(reviewItemIds?.some((itemId)=>!itemId))throw Error("BLOCKED: PR workflow review_item_ids must not contain empty values");if(reviewItemIds)assertNoDuplicates(reviewItemIds,"review item ids within one lane");let ownedWorkflowLanes=lane.ownedWorkflowLanes?.map((owned)=>owned.trim());if(ownedWorkflowLanes){if(ownedWorkflowLanes.some((owned)=>!owned))throw Error("BLOCKED: PR workflow owned_workflow_lanes must not contain empty values");if(assertNoDuplicates(ownedWorkflowLanes,"owned workflow lanes within one lane"),!ownedWorkflowLanes.includes(workflowLane))throw Error(`BLOCKED: PR workflow lane "${laneId}" must include its own workflow_lane "${workflowLane}" in owned_workflow_lanes`)}return{laneId,workflowLane,...reviewItemIds?{reviewItemIds}:{},...ownedWorkflowLanes?{ownedWorkflowLanes}:{}}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"lane ids"),assertNoDuplicates(normalized.map((lane)=>lane.workflowLane),"workflow lane ids"),assertNoDuplicates(normalized.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]),"owned workflow lane ids across lanes"),normalized}function normalizeInventoryIds(inventoryIds){if(!Array.isArray(inventoryIds)||inventoryIds.length===0)throw Error("BLOCKED: PR_FEEDBACK inventory declaration requires at least one feedback item id");let normalized=inventoryIds.map((inventoryId)=>{let itemId=inventoryId.trim();if(!itemId)throw Error("BLOCKED: PR_FEEDBACK inventory declaration contains an empty item id");return itemId});return assertNoDuplicates(normalized,"inventory item ids"),normalized.sort()}function normalizeOwnership(ownership){if(!Array.isArray(ownership)||ownership.length===0)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires at least one lane declaration");let normalized=ownership.map((lane)=>{let laneId=lane.laneId?.trim();if(!laneId)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires every lane to have a non-empty laneId");let ownedItemIds=normalizeInventoryIds(lane.ownedItemIds);return{laneId,ownedItemIds}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"PR_FEEDBACK verification lane ids"),normalized}function assertNoDuplicates(values,label){let seen=new Set;for(let value of values){if(seen.has(value))throw Error(`BLOCKED: duplicate ${label} are not allowed: ${value}`);seen.add(value)}}function containsProtectedWorkflowPath(value){return/(?:^|[^A-Za-z0-9_.-])\.swarm(?:[\\/]|$)/i.test(value.replace(/\\\\/g,"\\"))}function isPrWorkflowControllerTool(mode,toolName){if(PR_WORKFLOW_SHARED_CONTROLLER_TOOLS.has(toolName))return!0;return mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS.has(toolName):PR_FEEDBACK_CONTROLLER_TOOLS.has(toolName)}function isTrustedPrWorkflowToolInvocationSafe(toolName,args2){if(toolName==="lint")return args2.mode==="check";if(toolName==="sast_scan")return args2.capture_baseline!==!0;return!0}function isAllowedPrReviewReadOnlyToolName(toolName){if(PR_REVIEW_READ_ONLY_TOOL_NAMES.has(toolName))return!0;let tokens=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens.some((token)=>/^(?:add|alter|and|append|apply|approve|cancel|checkout|close|comment|commit|convert|create|delete|destroy|dismiss|drop|edit|execute|grant|insert|mark|merge|move|patch|prepend|publish|push|ready|remove|rename|replace|resolve|rerun|revoke|run|send|submit|then|transfer|truncate|unresolve|update|upload|write)$/i.test(token)))return!1;return tokens.some((token)=>/^(?:check|checks|diff|fetch|find|get|glob|grep|hover|inspect|list|lookup|open|read|references|scan|screenshot|search|show|status|symbols|tree|view)$/i.test(token))}function readOnlyToolArgumentsAreSafe(value,key="",depth=0){if(depth>8)return!1;let keyTokens=key.replace(/([a-z0-9])([A-Z])/g,"$1_$2").split(/[._:/-]+/).filter(Boolean);if(keyTokens.some((token)=>/^(?:append|body|content|create|data|delete|destination|destroy|edit|insert|mutation|output|patch|payload|prepend|remove|replace|save|set|truncate|update|upload|write)$/i.test(token)))return!1;if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim());if(keyTokens.length===1&&keyTokens.some((token)=>/^(?:action|operation)$/i.test(token)))return typeof value==="string"&&/^(?:check|diff|fetch|find|get|inspect|list|lookup|open|read|scan|search|show|status|view)$/i.test(value.trim());if(/^mode$/i.test(key)&&typeof value==="string")return/^(?:r|rb|read)$/i.test(value.trim());if(typeof value==="string"){if(keyTokens.some((token)=>/^(?:query|request|sql|statement)$/i.test(token))&&/(?:\b(?:alter|call|comment|create|delete|drop|exec(?:ute)?|grant|insert|merge|mutation|replace|revoke|truncate|update|upsert)\b|\bselect\b[\s\S]{0,4000}\binto\s+[A-Za-z_"'`])/i.test(value))return!1;return!/(?:^(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE|write|edit|patch|create|delete|destroy|remove|replace|truncate|update|upload)$|(?:^|[\r\n])\s*(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE)\s+\S+(?:\s+HTTP\/\d(?:\.\d)?)?|\bmutation\b|\b(?:create|drop|alter|truncate)\s+(?:or\s+replace\s+)?(?:table|database|schema|index|view|function|procedure|trigger|sequence)\b|\b(?:delete\s+from|insert\s+into|merge\s+into|replace\s+into|upsert\s+into)\b|\bupdate\s+[A-Za-z0-9_."'`-]+(?:\s+(?:AS\s+)?[A-Za-z0-9_"'`-]+)?\s+set\b|\b(?:grant|revoke)\s+\S+\s+(?:on|from|to)\b|\b(?:call|exec(?:ute)?)\s+[A-Za-z0-9_."'`-]+|\b(?:rm|rmdir|del|remove-item|move-item|set-content|add-content)\b)/i.test(value)}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return!0;if(Array.isArray(value))return value.every((entry)=>readOnlyToolArgumentsAreSafe(entry,key,depth+1));if(typeof value==="object")return Object.entries(value).every(([childKey,childValue])=>readOnlyToolArgumentsAreSafe(childValue,childKey,depth+1));return!1}function isAllowedPrWorkflowReadOnlyShell(command,options){let normalized=command.trim().replace(/\s+/g," ");if(!normalized)return!1;if(/[\r\n;&|<>`]/.test(command)||/\$\(|@\(/.test(command))return!1;let gitMatch=normalized.match(/^git(?: -C (?:"[^"]+"|'[^']+'|\S+))* (.+)$/i);if(gitMatch?.[1]){if(/^git -C /i.test(normalized)&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))return!1;return isAllowedPrWorkflowGitIntake(gitMatch[1],options)}if(/^gh /i.test(normalized))return isAllowedPrFeedbackGhIntake(normalized);if(/^rg\b/i.test(normalized)&&/\s--pre(?:-glob)?(?:\s|=|$)/i.test(normalized))return!1;return/^(?:rg|grep|cat|Get-Content|Select-String|Test-Path|Get-ChildItem|ls|dir|pwd)(?:\s|$)/i.test(normalized)}function hasUnsafeShellControlSyntax(command){return/[;&|<>`\r\n]/.test(command)||/\$\(/.test(command)}function isSafeStandaloneGitCommit(command){if(hasUnsafeShellControlSyntax(command))return!1;if(/(?:^|\s)--(?:allow-empty|amend)(?:\s|=|$)/i.test(command))return!1;return/^git(?:\s+-C(?:=|\s+)(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>`]+))?\s+commit(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s;&|<>`]+))*\s*$/i.test(command.trim())}function boundPushTarget(armed){let remote=armed.remoteName,branch=armed.remoteBranchRef.slice(11);if(!armed.remoteBranchRef.startsWith("refs/heads/")||!branch)return null;if(/\s|[;&|<>`]/.test(remote)||/\s|[;&|<>`]/.test(branch))return null;return{remote,branch}}function expectedBoundPushCommand(armed){let target=boundPushTarget(armed);return target?`git push ${target.remote} ${armed.localHead}:refs/heads/${target.branch}`:"(invalid bound remote-tracking ref; restart the workflow)"}function isSafeExactBoundPush(command,armed){if(hasUnsafeShellControlSyntax(command))return!1;let target=boundPushTarget(armed);if(!target)return!1;let match=command.trim().match(/^git\s+push\s+([^\s;&|<>`]+)\s+([^\s;&|<>`]+)\s*$/i);if(!match)return!1;return match[1]===target.remote&&match[2]===`${armed.localHead}:refs/heads/${target.branch}`}function isAllowedPrWorkflowGitIntake(gitArgs,options){if(/(?:--ext-diff|--textconv|--open-files-in-pager|--output(?:=|\s)|--upload-pack(?:=|\s)|--exec(?:=|\s))/i.test(gitArgs))return!1;if(/^(?:status|log|show|diff|rev-parse|merge-base|ls-files|grep|blame|cat-file|for-each-ref)(?:\s|$)/i.test(gitArgs))return!0;if(options.allowFetch&&/^fetch(?:\s|$)/i.test(gitArgs))return!0;if(options.allowTrackingFetch&&isAllowedBoundRemoteTrackingFetch(gitArgs,options.trackingFetchTarget))return!0;if(/^remote(?:\s+-v)?$/i.test(gitArgs))return!0;if(options.allowCheckout&&isAllowedPreBindBranchSetup(gitArgs))return!0;if(options.allowCheckout&&/^(?:checkout|switch)\s+(?:--detach\s+)?[^\s-][^\s]*$/i.test(gitArgs))return!0;return/^config\s+(?:(?:--show-origin|--show-scope|--global|--local|--system|--worktree)\s+)*(?:--list|--get(?:-all)?\s+\S+)$/i.test(gitArgs)}function isAllowedBoundRemoteTrackingFetch(gitArgs,target){if(!target?.remoteName||!target.remoteBranchRef.startsWith("refs/heads/"))return!1;let tokens=gitArgs.trim().split(/\s+/);if(tokens.length!==3||tokens[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens,expectedBranch=target.remoteBranchRef.slice(11);return isSafeGitRefToken(remote)&&!remote.includes("/")&&isSafeGitRefToken(remoteBranch)&&!remoteBranch.startsWith("-")&&!remoteBranch.includes(":")&&remote===target.remoteName&&remoteBranch===expectedBranch}function isAllowedPreBindBranchSetup(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens.length===3&&tokens[0]==="branch"){let upstream=tokens[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens[2]))}return!1}function isSafeGitRefToken(value){return/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")&&!value.endsWith("/")&&!value.endsWith(".")&&!value.endsWith(".lock")}function isAllowedPrFeedbackGhIntake(command){if(/^gh\s+pr\s+checkout(?:\s|$)/i.test(command))return isAllowedSafeGhPrCheckout(command);if(/^gh\s+pr\s+(?:view|diff|checks|status|list)(?:\s|$)/i.test(command)||/^gh\s+run\s+(?:view|list|watch)(?:\s|$)/i.test(command)||/^gh\s+issue\s+(?:view|list)(?:\s|$)/i.test(command)||/^gh\s+search\s+(?:code|commits|issues|prs|repos)(?:\s|$)/i.test(command)||/^gh\s+auth\s+status(?:\s|$)/i.test(command))return!0;if(!/^gh\s+api(?:\s|$)/i.test(command))return!1;if(/\bmutation\b/i.test(command))return!1;let method=command.match(/\s(?:--method(?:\s+|=)|-X(?:\s+|=)?)([A-Z]+)/i)?.[1];if(method&&method.toUpperCase()!=="GET")return!1;if(/\s(?:--input|--raw-field)(?:\s|=)/i.test(command)||/\s-F(?:\s|=|\S)/.test(command))return!1;return!/\s(?:--field|-f)(?:\s|=)(?!query=)/i.test(command)}function isAllowedSafeGhPrCheckout(command){if(/\s--(?:force|recurse-submodules)(?:\s|=|$)/i.test(command))return!1;let tokens=command.trim().split(/\s+/);if(tokens.length<4||tokens[0]!=="gh"||tokens[1]!=="pr"||tokens[2]!=="checkout")return!1;let target=tokens[3];if(!/^\d+$/.test(target)&&!/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/\d+$/.test(target))return!1;for(let index=4;index<tokens.length;index+=1){let token=tokens[index],repoEquals=token.match(/^--repo=(.+)$/)?.[1];if(repoEquals){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repoEquals))return!1;continue}let branchEquals=token.match(/^--branch=(.+)$/)?.[1];if(branchEquals){if(!isSafeGitRefToken(branchEquals))return!1;continue}if(token==="--repo"||token==="-R"){let repo=tokens[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens[++index];if(!branch||!isSafeGitRefToken(branch))return!1;continue}return!1}return!0}function normalizePrHeadSha(prHeadSha){let normalized=prHeadSha.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty pr_head_sha");return normalized}async function currentPrFeedbackRevisionDigest(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let digest2=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!digest2)throw Error("BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest");return digest2}async function resolvePrWorkflowRevisionDigestForGate(directory,baseHeadSha){if(_test_exports.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _test_exports.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha)}function normalizeBatchId(batchId){let normalized=batchId.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty batch id");return normalized}function sameStringArray(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function assertExactStringSet(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),missing=[...expectedSet].filter((value)=>!actualSet.has(value)),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length!==actualSet.size||actualSet.size!==expectedSet.size||missing.length>0||extra.length>0)throw Error(`BLOCKED: ${label} must exactly cover the mechanically derived inventory; missing: ${missing.join(", ")||"(none)"}; extra: ${extra.join(", ")||"(none)"}`)}function derivePrReviewCandidateInventory(directory,state){let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map;for(let batch of[...state.prReviewBaseDispatches??[]].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt);for(let lane of batch.lanes){let ownedDimensions=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!ownedDimensions.every((dimension)=>successful.has(dimension)))continue;let key=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key,ownedDimensions.length);for(let dimension of ownedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key))continue;seenBaseSourceKeys.add(key);let credited=baseSourceCreditedDimensions.get(key),fullOwnershipCount=baseSourceFullOwnershipCount.get(key)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;for(let batch of[...state.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt);for(let lane of batch.lanes)if(successful.has(lane.workflowLane)&&!selectedCouncilLanes.has(lane.workflowLane))sources.push({batchId:batch.batchId,laneId:lane.laneId,mode:"swarm-pr-review:council"}),selectedCouncilLanes.add(lane.workflowLane)}if(state.prReviewTriggerEvalPath){let triggerPath=validateSwarmPath(directory,state.prReviewTriggerEvalPath),triggerArtifact;try{triggerArtifact=JSON.parse(readFileSync6(triggerPath,"utf-8"))}catch{throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid")}let rows=triggerArtifact.rows;if(!Array.isArray(rows))throw Error("BLOCKED: PR_REVIEW trigger evaluation rows are invalid");let rowIds=rows.map((row)=>typeof row==="object"&&row!==null?row.trigger_id:void 0),provenanceTuples=rows.map((row)=>{if(typeof row!=="object"||row===null)return"";let{source_batch_id:batchId,source_lane_id:laneId}=row;return typeof batchId==="string"&&typeof laneId==="string"&&batchId.trim()&&laneId.trim()?`${batchId}\x00${laneId}`:""});if(!(rows.length===PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length&&new Set(rowIds).size===PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length&&provenanceTuples.every(Boolean)&&PR_REVIEW_REQUIRED_MICRO_LANE_IDS.every((id)=>rowIds.includes(id))&&rows.every((row)=>typeof row==="object"&&row!==null&&row.result==="MATCHED")))throw Error("BLOCKED: PR_REVIEW requires the exact all-MATCHED repository-agnostic micro-lane set with complete source provenance");for(let row of rows)if(typeof row==="object"&&row!==null&&row.result==="MATCHED"&&typeof row.source_batch_id==="string"&&typeof row.source_lane_id==="string")sources.push({batchId:row.source_batch_id,laneId:row.source_lane_id,mode:"swarm-pr-review:micro",workflowLane:row.trigger_id})}let candidateIds=[],extractedLaneKeys=new Set;for(let source of sources){let resolvedArtifact=!1;for(let record2 of findByBatchId(directory,source.batchId,{parentSessionId:state.sessionID})){if(record2.laneId!==source.laneId||record2.mode!==source.mode||record2.status!=="completed"||record2.workspace?.prHeadSha!==state.prHeadSha||record2.workspace?.gitHead!==state.prHeadSha||record2.result?.outputDegraded===!0||record2.result?.transcriptIncomplete===!0||record2.result?.truncated===!0)continue;let ref=record2.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record2.ownedWorkflowLanes?.length?record2.ownedWorkflowLanes:record2.workflowLane?[record2.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state,record2,source.mode,record2.workflowLane??source.workflowLane??source.laneId,void 0,void 0,recordOwnedLanes))continue;if(source.workflowLane&&(!recordOwnedLanes?.includes(source.workflowLane)||!prReviewDiscoveryArtifactCoversLane(artifact.text,source.workflowLane)))continue;resolvedArtifact=!0;let laneKey=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey))extractedLaneKeys.add(laneKey),candidateIds.push(...extractCandidateIds(artifact.text,source.creditedLanes))}if(source.mode==="swarm-pr-review:micro"&&!resolvedArtifact)throw Error(`BLOCKED: PR_REVIEW mandatory micro-lane provenance is missing or invalid for ${source.workflowLane??source.laneId}`)}return assertNoDuplicates(candidateIds,"PR_REVIEW discovery candidate ids"),candidateIds.length>0?candidateIds.sort():["CLEAN-REVIEW"]}function extractCandidateIds(text,scopeToLanes){let candidateIds=[],markerHeaderSeen=!1,inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);for(let line of text.split(/\r?\n/)){let fields=pipeFields(line);if(fields[0]==="[CANDIDATE]"&&fields[1]?.toLowerCase()==="candidate_id"){markerHeaderSeen=!0;continue}if(fields[0]==="[CANDIDATE]"&&fields.length>=10&&fields.slice(1,10).every(Boolean)){if(inScope(fields[2]))candidateIds.push(fields[1]);continue}if(markerHeaderSeen&&fields.length>=9&&fields[0]&&!fields[0].startsWith("[")&&fields.slice(0,9).every(Boolean)){if(inScope(fields[1]))candidateIds.push(fields[0])}}return candidateIds}function derivePrReviewCriticInventory(directory,state){return[...deriveLatestPrReviewReviewerVerdicts(directory,state).entries()].filter(([,verdict])=>verdict.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(verdict.severity)).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state){let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state),criticBatches=(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="critic");for(let batch of[...criticBatches].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:critic",batch.validatedAt);if(batch.lanes.some((lane)=>!successful.has(lane.workflowLane))||successful.size!==batch.lanes.length)continue;let required2=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]),verdicts=new Map;for(let lane of batch.lanes){let ref=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===lane.laneId)?.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0;if(!artifact)continue;for(let itemId of lane.reviewItemIds??[]){let verdict=parseCriticVerdict(artifact.text,itemId,reviewerVerdicts.get(itemId)?.severity);if(verdict)verdicts.set(itemId,verdict)}}if(required2.every((itemId)=>verdicts.has(itemId)))return verdicts}return new Map}function deriveLatestPrReviewReviewerVerdicts(directory,state){let reviewerBatches=(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer");for(let batch of[...reviewerBatches].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:reviewer",batch.validatedAt);if(batch.lanes.some((lane)=>!successful.has(lane.workflowLane))||successful.size!==batch.lanes.length)continue;let required2=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]),verdicts=new Map;for(let lane of batch.lanes){let ref=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===lane.laneId)?.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0;if(!artifact)continue;for(let itemId of lane.reviewItemIds??[]){let verdict=parseReviewerVerdict(artifact.text,itemId);if(verdict)verdicts.set(itemId,verdict)}}if(required2.every((itemId)=>verdicts.has(itemId)))return verdicts}return new Map}function successfulObligationsFromExactBatch(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}),successful=new Set,validatedAtMs=Date.parse(validatedAt);if(!Number.isFinite(validatedAtMs))return successful;let expectedByLaneId=new Map(expectedLanes.map((lane)=>[lane.laneId,lane]));if(expectedByLaneId.size!==expectedLanes.length)return successful;let recordCountByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record2 of records){if(!record2.laneId||!expectedByLaneId.has(record2.laneId))continue;recordCountByLaneId.set(record2.laneId,(recordCountByLaneId.get(record2.laneId)??0)+1);let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)recordCountBySubagentSessionId.set(subagentSessionId,(recordCountBySubagentSessionId.get(subagentSessionId)??0)+1)}for(let record2 of records){let expectedLane=record2.laneId?expectedByLaneId.get(record2.laneId):void 0,expectedWorkflowLane=expectedLane?.workflowLane,expectedOwnedLanes=expectedLane?.ownedWorkflowLanes?.length?expectedLane.ownedWorkflowLanes:expectedWorkflowLane!==void 0?[expectedWorkflowLane]:void 0,subagentSessionId=record2.subagentSessionId?.trim();if(expectedWorkflowLane!==void 0&&expectedOwnedLanes!==void 0&&record2.laneId!==void 0&&recordCountByLaneId.get(record2.laneId)===1&&Boolean(subagentSessionId)&&recordCountBySubagentSessionId.get(subagentSessionId)===1&&!forbiddenSubagentSessionIds.has(subagentSessionId)&&record2.createdAt>=validatedAtMs&&(!checkWorkflowLane||record2.workflowLane===expectedWorkflowLane)&&(!checkWorkflowLane||ownedLaneSetsEqual(record2.ownedWorkflowLanes,expectedOwnedLanes))&&record2.mode===expectedMode&&record2.workspace?.prHeadSha===state.prHeadSha&&record2.workspace?.gitHead===state.prHeadSha&&record2.status==="completed"&&record2.result?.outputDegraded!==!0&&record2.result?.transcriptIncomplete!==!0&&record2.result?.truncated!==!0&&(record2.result?.chars??0)>0&&Boolean(record2.result?.digest?.trim())&&Boolean(record2.result?.outputRef?.trim())&&workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,expectedLane?.reviewItemIds,expectedRevisionDigest,expectedOwnedLanes))for(let obligation of expectedOwnedLanes)successful.add(obligation)}return successful}function ownedLaneSetsEqual(recordOwned,expectedOwned){if(!recordOwned||recordOwned.length===0)return expectedOwned.length===1;let recordSet=new Set(recordOwned),expectedSet=new Set(expectedOwned);if(recordSet.size!==recordOwned.length||recordSet.size!==expectedSet.size)return!1;return recordOwned.every((owned)=>expectedSet.has(owned))}function workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes){let ref=record2.result?.outputRef?.trim();if(!ref)return!1;let loaded=readLaneOutput(directory,ref);if(!loaded)return!1;let artifact=loaded.artifact,recordPrHeadSha=record2.workspace?.prHeadSha,recordGitHead=record2.workspace?.gitHead,resolvedRevisionDigest=expectedRevisionDigest??(recordPrHeadSha?_test_exports.resolvePrWorkflowRevisionDigest(directory,recordPrHeadSha):null),expectedReviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0;if(artifact.batchId!==record2.batchId||artifact.laneId!==record2.laneId||artifact.mode!==expectedMode||artifact.sessionId!==record2.subagentSessionId||artifact.parentSessionId!==record2.parentSessionId||artifact.agent!==record2.swarmPrefixedAgent||artifact.role!==record2.normalizedAgent||artifact.source!=="collect_lane_results"||artifact.workflowLane!==record2.workflowLane||artifact.workflowLane!==expectedWorkflowLane||!recordPrHeadSha||artifact.prHeadSha!==recordPrHeadSha||!recordGitHead||artifact.gitHead!==recordGitHead||!resolvedRevisionDigest||artifact.revisionDigest!==resolvedRevisionDigest||expectedReviewScope!==void 0&&(record2.workspace?.scope!==expectedReviewScope||artifact.scope!==expectedReviewScope)||artifact.digest!==record2.result?.digest||artifact.chars!==record2.result?.chars)return!1;if(expectedMode==="swarm-pr-review:reviewer")return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>Boolean(parseReviewerVerdict(artifact.text,itemId))));if(expectedMode==="swarm-pr-review:critic"){let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state);return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>Boolean(parseCriticVerdict(artifact.text,itemId,reviewerVerdicts.get(itemId)?.severity))))}if(expectedMode==="swarm-pr-feedback:verification")return/^\[FEEDBACK-VERIFIED\]\s*\|/m.test(artifact.text);let feedbackVerdict={"swarm-pr-feedback:stage-b-reviewer":["[STAGE-B-REVIEW]","APPROVE"],"swarm-pr-feedback:stage-b-test":["[STAGE-B-TEST]","PASS"],"swarm-pr-feedback:closeout-reviewer":["[CLOSEOUT-REVIEW]","APPROVE"],"swarm-pr-feedback:closeout-critic":["[CLOSEOUT-CRITIC]","APPROVE"]}[expectedMode];if(feedbackVerdict)return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>artifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));let coveredLanes=ownedWorkflowLanes?.length?ownedWorkflowLanes:[expectedWorkflowLane];if(!coveredLanes.every((coveredLane)=>prReviewDiscoveryArtifactCoversLane(artifact.text,coveredLane)))return!1;if(coveredLanes.length>1){let seenEvidence=new Map;for(let coveredLane of coveredLanes){let evidence=extractLaneCoverageEvidenceText(artifact.text,coveredLane);if(evidence===null)continue;if(seenEvidence.get(evidence))return!1;seenEvidence.set(evidence,coveredLane)}}return!0}function prReviewDiscoveryArtifactCoversLane(text,expectedWorkflowLane){let lines=text.split(/\r?\n/),candidateHeaderSeen=!1;for(let line of lines){let fields=pipeFields(line);if(fields.length===0)continue;if(fields[0]==="[CLEAN]"&&fields.length>=4&&fields[1]===expectedWorkflowLane&&fields.slice(1,4).every(Boolean)&&fields[2].length>=12&&fields[3].length>=20)return!0;if(fields[0]==="[CANDIDATE]"){if(fields[1]?.toLowerCase()==="candidate_id"){candidateHeaderSeen=!0;continue}if(fields.length>=10&&fields[2]===expectedWorkflowLane&&fields.slice(1,10).every(Boolean))return!0;continue}if(candidateHeaderSeen&&fields.length>=9&&fields[0]?.toLowerCase()!=="candidate_id"&&fields[1]===expectedWorkflowLane&&fields.slice(0,9).every(Boolean))return!0}return!1}function extractLaneCoverageEvidenceText(text,expectedWorkflowLane){let lines=text.split(/\r?\n/),candidateHeaderSeen=!1;for(let line of lines){let fields=pipeFields(line);if(fields.length===0)continue;if(fields[0]==="[CLEAN]"&&fields.length>=4&&fields[1]===expectedWorkflowLane&&fields.slice(1,4).every(Boolean)&&fields[2].length>=12&&fields[3].length>=20)return`${fields[2]}\x00${fields[3]}`;if(fields[0]==="[CANDIDATE]"){if(fields[1]?.toLowerCase()==="candidate_id"){candidateHeaderSeen=!0;continue}if(fields.length>=10&&fields[2]===expectedWorkflowLane&&fields.slice(1,10).every(Boolean))return fields.slice(3,10).join("\x00");continue}if(candidateHeaderSeen&&fields.length>=9&&fields[0]?.toLowerCase()!=="candidate_id"&&fields[1]===expectedWorkflowLane&&fields.slice(0,9).every(Boolean))return fields.slice(2,9).join("\x00")}return null}function parseReviewerVerdict(text,itemId){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[REVIEWED]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==10||!fields.slice(1).every(Boolean))return null;let introduced=fields[5].replace(/^introduced_by_pr\s*:\s*/i,"").toUpperCase();if(!REVIEWER_CLASSIFICATIONS.has(fields[2])||!REVIEWER_EVIDENCE_TYPES.has(fields[3])||!REVIEW_SEVERITIES.has(fields[4])||!["YES","NO","UNKNOWN"].includes(introduced))return null;if(fields[7].length<8||fields[8].length<5||fields[9].length<3)return null;return{classification:fields[2],severity:fields[4]}}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[CRITIC]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==6||!fields.slice(1).every(Boolean)||!CRITIC_STATUSES.has(fields[2])||!REVIEW_SEVERITIES.has(fields[3]))return null;if(fields[2]==="NEEDS_MORE_EVIDENCE")return null;if(fields[2]==="DISPROVED"&&fields[3]!=="NONE")return null;if(fields[2]==="UPHELD"&&!["CRITICAL","HIGH","MEDIUM"].includes(fields[3]))return null;if(fields[2]==="DOWNGRADED"&&fields[3]==="CRITICAL")return null;if(reviewerSeverity){let severityRank=new Map([["NONE",0],["INFO",1],["LOW",2],["MEDIUM",3],["HIGH",4],["CRITICAL",5]]),reviewerRank=severityRank.get(reviewerSeverity),criticRank=severityRank.get(fields[3]);if(reviewerRank===void 0||criticRank===void 0)return null;if(fields[2]==="UPHELD"&&criticRank!==reviewerRank)return null;if(fields[2]==="DOWNGRADED"&&criticRank>=reviewerRank)return null}if(fields[4].length<6||fields[5].length<6)return null;return{status:fields[2],severity:fields[3]}}function artifactHasExactPositiveVerdictRow(text,marker,itemId,positiveVerdict){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]===marker&&fields[1]===itemId);return rows.length===1&&rows[0].length>=4&&rows[0][2]===positiveVerdict&&rows[0].slice(1,4).every(Boolean)}function pipeFields(line){if(!line.includes("|"))return[];return line.split("|").map((field)=>field.trim())}function feedbackArtifactCoversItems(directory,state,batchId,laneId,itemIds){let ref=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===laneId)?.result?.outputRef?.trim(),loaded=ref?readLaneOutput(directory,ref):null;if(!loaded)return!1;let rows=loaded.artifact.text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]==="[FEEDBACK-VERIFIED]");if(rows.length!==itemIds.length)return!1;return itemIds.every((itemId)=>{let matches=rows.filter((fields)=>fields[1]===itemId);return matches.length===1&&matches[0].length===4&&matches[0].slice(1,4).every(Boolean)&&FEEDBACK_CLASSIFICATIONS.has(matches[0][2])})}async function persistState(directory,state){let validated=PrWorkflowGateStateSchema.parse(state);await withSessionStateMutation(directory,validated.sessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk(directory,validated.sessionID);if(current?current.revision!==validated.revision:validated.revision!==0)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");let nextRevision=validated.revision+1,nextState={...validated,revision:nextRevision},filePath=workflowGateStatePath(directory,validated.sessionID);await fsp2.mkdir(path11.dirname(filePath),{recursive:!0}),await writeAtomicJson2(filePath,nextState),Object.assign(state,nextState),rememberState(directory,nextState)})}async function withSessionStateMutation(directory,sessionID,action){let key=stateCacheKey(directory,sessionID),previous=pendingStateMutationsByProjectSession.get(key)??Promise.resolve(),release,current=new Promise((resolve8)=>{release=resolve8}),queued=previous.then(()=>current);pendingStateMutationsByProjectSession.set(key,queued),await previous;try{let lock=await acquireSessionStateMutationLock(directory,sessionID);try{return await action()}finally{await releaseSessionStateMutationLock(lock)}}finally{if(release(),pendingStateMutationsByProjectSession.get(key)===queued)pendingStateMutationsByProjectSession.delete(key)}}async function acquireSessionStateMutationLock(directory,sessionID){let lockPath=workflowGateStateLockPath(directory,sessionID);await fsp2.mkdir(path11.dirname(lockPath),{recursive:!0});for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await fsp2.open(lockPath,"wx"),lock={ownerToken:randomUUID2(),pid:process.pid,createdAtMs:_test_exports.nowMs()};try{await handle.writeFile(JSON.stringify(lock),"utf-8"),await handle.close()}catch(error49){throw await removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken),error49}return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedSessionStateMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow gate state is being mutated by another process; retry after that session transition finishes")}async function releaseSessionStateMutationLock(lock){try{await removeSessionStateMutationLockIfOwned(lock.path,lock.ownerToken)}catch{}}async function reclaimAbandonedSessionStateMutationLock(lockPath){let lock=await readSessionStateMutationLock(lockPath);if(lock){if(_test_exports.isProcessAlive(lock.pid))return!1;return removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp2.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp2.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp2.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeSessionStateMutationLockIfOwned(lockPath,ownerToken){let lock=await readSessionStateMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await fsp2.rm(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error49){return error49.code!=="ESRCH"}}async function readPrWorkflowGateStateFromDisk(directory,sessionID){let filePath=workflowGateStatePath(directory,sessionID),raw;try{raw=await fsp2.readFile(filePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(!parsed.success)throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is invalid`);return parsed.data}function rememberState(directory,state){let cacheKey=stateCacheKey(directory,state.sessionID);trackedStatesByProjectSession.delete(cacheKey),trackedStatesByProjectSession.set(cacheKey,state);while(trackedStatesByProjectSession.size>MAX_TRACKED_SESSIONS){let oldestKey=trackedStatesByProjectSession.keys().next().value;if(!oldestKey)break;trackedStatesByProjectSession.delete(oldestKey)}}function stateCacheKey(directory,sessionID){let resolved=path11.normalize(path11.resolve(directory));return`${process.platform==="win32"?resolved.toLowerCase():resolved}\x00${normalizeSessionID(sessionID)}`}function workflowGateStatePath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateRelativePath(sessionID))}function workflowGateStateLockPath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateLockRelativePath(sessionID))}function workflowGateStateLockRelativePath(sessionID){return path11.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path11.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.json`)}function prWorkflowSessionFileStem(sessionID){let normalized=normalizeSessionID(sessionID),slug=normalized.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)||"session",digest2=createHash5("sha256").update(normalized).digest("hex").slice(0,12);return`${slug}-${digest2}`}function normalizeSessionID(sessionID){let normalized=sessionID.trim();if(!normalized)throw Error("BLOCKED: PR workflow gate requires a non-empty sessionID");return normalized}async function writeAtomicJson2(filePath,value){let tempPath=`${filePath}.tmp.${process.pid}.${randomUUID2()}`,lastError;try{await fsp2.writeFile(tempPath,JSON.stringify(value,null,2),"utf-8");for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await _test_exports.rename(tempPath,filePath),lastError=void 0;break}catch(error49){lastError=error49;let code=error49.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")break;if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}if(lastError)throw lastError}finally{try{await fsp2.rm(tempPath,{force:!0})}catch{}}}async function writePrWorkflowAtomicJson(filePath,value){await writeAtomicJson2(filePath,value)}function isoNow(){return new Date().toISOString()}function delay(ms){return new Promise((resolve8)=>setTimeout(resolve8,ms))}var PR_REVIEW_BASE_DIMENSION_IDS,PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS,PR_REVIEW_MICRO_LANE_FLOORS,GATE_SCHEMA_VERSION=1,MAX_TRACKED_SESSIONS=200,MAX_WORKFLOW_BATCHES=128,WINDOWS_RENAME_MAX_RETRIES3=3,RENAME_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_MAX_ATTEMPTS=50,STATE_MUTATION_LOCK_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS=30000,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",WORKFLOW_GATE_DIR="pr-workflow-gates",trackedStatesByProjectSession,pendingStateMutationsByProjectSession,PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrReviewValidationBatchRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowGateStateSchema,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,_test_exports,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,REVIEWER_CLASSIFICATIONS,REVIEWER_EVIDENCE_TYPES,REVIEW_SEVERITIES,CRITIC_STATUSES,FEEDBACK_CLASSIFICATIONS;var init_pr_workflow_gate=__esm(()=>{init_zod();init_lane_output_store();init_pending_delegations();init_workspace_snapshot();init_constants();init_schema();init_tool_metadata();init_utils2();PR_REVIEW_BASE_DIMENSION_IDS=["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"],PR_REVIEW_REQUIRED_MICRO_LANE_IDS=["auth-identity-secrets","untrusted-input-boundaries","subprocess-platform","concurrency-state","dependencies-build-release","api-schema-migrations","test-infrastructure","ui-accessibility-i18n","privacy-observability","generated-provenance","unclassified-risk"],PR_REVIEW_DEPTH_TIER_THRESHOLDS={smallMaxChangedLines:50,smallMaxChangedFiles:3,mediumMaxChangedLines:500,mediumMaxChangedFiles:20},PR_REVIEW_BASE_LANE_FLOORS={S:1,M:3,L:PR_REVIEW_BASE_DIMENSION_IDS.length},PR_REVIEW_MICRO_LANE_FLOORS={S:1,M:6,L:PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length};trackedStatesByProjectSession=new Map,pendingStateMutationsByProjectSession=new Map,PrReviewBaseDimensionIdSchema=exports_external.enum(["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"]),PrReviewBaseDispatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:PrReviewBaseDimensionIdSchema,ownedWorkflowLanes:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackLaneOwnershipSchema=exports_external.object({laneId:exports_external.string().min(1),ownedItemIds:exports_external.array(exports_external.string().min(1)).min(1)}).strict(),PrFeedbackVerificationRecordSchema=exports_external.object({batchId:exports_external.string().min(1),ownership:exports_external.array(PrFeedbackLaneOwnershipSchema).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackStageACheckReceiptSchema=exports_external.object({category:exports_external.enum(["build","typecheck","lint","diff-check","reproduction"]),workingDirectory:exports_external.string().min(1).optional(),obligationId:exports_external.string().min(1).optional(),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional(),command:exports_external.array(exports_external.string().min(1)).min(1),targets:exports_external.array(exports_external.string().min(1)).min(1).optional(),feedbackTargets:exports_external.array(exports_external.object({feedbackItemId:exports_external.string().min(1),target:exports_external.string().min(1),expectedBehavior:exports_external.string().min(8)}).strict()).min(1).optional(),durationMs:exports_external.number().nonnegative()}).strict(),PrFeedbackStageARecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),checks:exports_external.array(PrFeedbackStageACheckReceiptSchema).min(2).max(258),feedbackItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional(),applicableCategories:exports_external.array(exports_external.enum(["build","typecheck","lint"])).max(3).optional(),applicableObligations:exports_external.array(exports_external.object({id:exports_external.string().min(1),category:exports_external.enum(["build","typecheck","lint"]),workingDirectory:exports_external.string().min(1),source:exports_external.string().min(1),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional()}).strict()).max(256).optional(),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackGateBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),laneId:exports_external.string().min(1),itemIds:exports_external.array(exports_external.string().min(1)).min(1),revisionDigest:exports_external.string().min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackReadyToPublishRecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),validatedAt:exports_external.string().min(1)}).strict(),PrReviewValidationBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["council","reviewer","critic"]),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:exports_external.string().min(1),reviewItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackScopeDeclarationRecordSchema=exports_external.object({taskId:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/),files:exports_external.array(exports_external.string().min(1)).min(1).max(1e4),revisionDigest:exports_external.string().min(1),declaredAt:exports_external.string().min(1),consumedByCallId:exports_external.string().min(1).optional()}).strict(),PrWorkflowGateStateSchema=exports_external.object({schemaVersion:exports_external.literal(GATE_SCHEMA_VERSION),revision:exports_external.number().int().nonnegative().default(0),sessionID:exports_external.string().min(1),mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),activatedAt:exports_external.string().min(1),updatedAt:exports_external.string().min(1),prHeadSha:exports_external.string().min(1).optional(),prReviewBaseRef:exports_external.string().min(1).optional(),prReviewBaseSha:exports_external.string().min(1).optional(),prReviewDepthTier:exports_external.enum(["S","M","L"]).optional(),prReviewDiffStats:exports_external.object({changedLines:exports_external.number().int().nonnegative(),changedFiles:exports_external.number().int().nonnegative(),hasSubmoduleChange:exports_external.boolean().default(!1)}).strict().optional(),prReviewBaseDispatches:exports_external.array(PrReviewBaseDispatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBaseDispatch:PrReviewBaseDispatchRecordSchema.optional(),prReviewTriggerEvalPath:exports_external.string().min(1).optional(),prReviewValidationBatches:exports_external.array(PrReviewValidationBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewArtifactBoundaries:exports_external.array(exports_external.enum(["post_explorer","post_reviewer","post_critic"])).max(3).optional(),prReviewHandoffPath:exports_external.string().min(1).optional(),prReviewHandoffRequired:exports_external.boolean().optional(),prFeedbackInventory:exports_external.array(exports_external.string().min(1)).min(1).optional(),prFeedbackVerifications:exports_external.array(PrFeedbackVerificationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackVerification:PrFeedbackVerificationRecordSchema.optional(),prFeedbackStageA:PrFeedbackStageARecordSchema.optional(),prFeedbackGateBatches:exports_external.array(PrFeedbackGateBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackReadyToPublish:PrFeedbackReadyToPublishRecordSchema.optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();PR_FEEDBACK_PHASE_ORDER=["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"];PR_FEEDBACK_PHASE_ROLE={"stage-b-reviewer":"reviewer","stage-b-test":"test_engineer","closeout-reviewer":"reviewer","closeout-critic":"critic"};_test_exports={workflowGateStateRelativePath,workflowGateStateLockRelativePath,resetTrackedStateCache:()=>{trackedStatesByProjectSession.clear(),pendingStateMutationsByProjectSession.clear(),_test_exports.beforeTerminalClear=void 0},beforeTerminalClear:void 0,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,isProcessAlive,rename:fsp2.rename,nowMs:()=>Date.now()};PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","get_async_result","get_async_status","prepare_pr_workflow_checkout"]),PR_REVIEW_CONTROLLER_TOOLS=new Set(["parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["prepare_pr_feedback_scope","run_pr_feedback_stage_a"]);PR_REVIEW_READ_ONLY_TOOL_NAMES=new Set(["ast_grep_search","codesearch","glob","grep","lsp","open","read","search","skill","tree","view","webfetch","websearch"]);REVIEWER_CLASSIFICATIONS=new Set(["CONFIRMED","DISPROVED","UNVERIFIED","PRE_EXISTING"]),REVIEWER_EVIDENCE_TYPES=new Set(["STRUCTURALLY_PROVEN","EXECUTION_PROVEN","STATIC_TRACE_PROVEN","PLAUSIBLE_BUT_UNVERIFIED"]),REVIEW_SEVERITIES=new Set(["CRITICAL","HIGH","MEDIUM","LOW","INFO","NONE"]),CRITIC_STATUSES=new Set(["UPHELD","DOWNGRADED","DISPROVED","NEEDS_MORE_EVIDENCE"]),FEEDBACK_CLASSIFICATIONS=new Set(["CONFIRMED","PARTIAL","DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"])});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,reasonStartIndex=knownMode?1:0,reason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500)||void 0;if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
173
175
 
174
176
  ${USAGE}`;if(!sessionID?.trim())return`Error: abort-pr-workflow requires an active sessionID.
175
177
 
@@ -6094,7 +6096,7 @@ followed by exactly:
6094
6096
  [CLEAN] | workflow_lane | coverage_scope | evidence
6095
6097
  Fill every CLEAN field with the exact workflow_lane; bare header-only output is
6096
6098
  UNATTESTED for every PR-review lane.
6097
- Do NOT use the default PROJECT/STRUCTURE output format for this dispatch.`,READ_ONLY_LANE_ROLES=new Set(["explorer","reviewer","test_engineer","critic","critic_oversight","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","sme","researcher","council_generalist","council_skeptic","council_domain_expert"]),READ_ONLY_TOOL_DENYLIST=[...new Set([...WRITE_TOOL_NAMES,"extract_code_blocks","multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","summarize_work","doc_scan","lint","shell","bash"])],LaneSchema=exports_external.object({id:exports_external.string().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).describe("Stable lane identifier, unique within this dispatch batch"),agent:exports_external.string().min(1).max(120).describe("Read-only swarm agent name, including any generated swarm prefix"),prompt:exports_external.string().min(1).max(MAX_PROMPT_CHARS).describe("Full lane prompt to send to the requested agent"),workflow_lane:exports_external.string().min(1).max(120).optional().describe("Required mechanical policy identifier in PR workflows; distinct from the retry-safe lane id"),owned_workflow_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Complete dimension/family set a consolidated PR-review base or micro lane covers under the controller-computed depth tier; must include workflow_lane. Omit for singleton lanes."),feedback_item_ids:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("PR-feedback ledger item IDs owned exclusively by this lane"),review_item_ids:exports_external.array(exports_external.string().trim().min(1).max(160)).min(1).optional().describe("Candidate/finding IDs owned by a PR-review reviewer or critic lane; every ID requires a parseable verdict row")}),PrReviewTriggerEvaluationRowSchema=exports_external.object({trigger_id:exports_external.string().trim().min(1).max(120),result:exports_external.literal("MATCHED"),evidence:exports_external.string().trim().min(1).max(4000)}).strict(),DispatchLanesArgsSchema=exports_external.object({lanes:exports_external.array(LaneSchema).min(1).max(MAX_LANES).describe("Read-only lane specs to dispatch concurrently"),common_prompt:exports_external.string().min(1).regex(/\S/,"common_prompt must contain non-whitespace content").max(MAX_PROMPT_CHARS-COMMON_PROMPT_SEPARATOR.length-1).optional().describe("Optional shared context prepended to every lane prompt. Send large shared context (PR diff, obligation ledger, scope) ONCE here instead of inlining the same blob into each lane prompt; this keeps the tool-call payload small and avoids malformed/truncated tool-call JSON. Combined common_prompt + per-lane prompt must not exceed the per-lane character limit."),max_concurrent:exports_external.number().int().min(1).max(MAX_LANES).optional().describe("Maximum lanes in flight at once; defaults to lane count"),timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS2).optional().describe("Per-lane timeout in milliseconds. For blocking dispatch this covers session create and prompt execution; for async dispatch this covers launch only, never lane runtime.")}),DispatchLanesAsyncArgsSchema=DispatchLanesArgsSchema.extend({launch_timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS2).optional().describe("Async launch acceptance timeout in milliseconds. This only bounds session creation and promptAsync acceptance; it is never a lane runtime timeout. Deprecated alias: timeout_ms."),batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS).regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/).optional().describe("Stable async batch id for later collection; generated when omitted"),mode:exports_external.string().min(1).max(80).optional().describe("Advisory workflow mode, such as deep-dive or swarm-pr-review"),pr_head_sha:exports_external.string().min(1).max(80).optional(),base_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i).optional(),base_ref:exports_external.string().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional(),scope:exports_external.string().min(1).max(500).optional(),trigger_evaluation:exports_external.array(PrReviewTriggerEvaluationRowSchema).min(1).optional().describe("Exact all-MATCHED repository-agnostic mandatory micro-lane ledger required for swarm-pr-review:micro"),feedback_inventory:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("Complete immutable feedback item inventory required for swarm-pr-feedback:verification")}),CollectLaneResultsArgsSchema=exports_external.object({batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS),wait:exports_external.boolean().optional().describe("Poll until all lanes settle or timeout"),timeout_ms:exports_external.number().int().min(0).max(MAX_COLLECT_TIMEOUT_MS).optional().describe("Total wait budget when wait=true"),include_pending:exports_external.boolean().optional().describe("Include pending/running lanes in lane_results. Defaults to true for non-blocking polls and false for wait=true joins."),cancel_pending:exports_external.boolean().optional().describe("Abort and mark pending/running lanes cancelled")});function validatePrReviewMicroDispatch(args2,depthTier){let evaluation=args2.trigger_evaluation;if(!evaluation)throw Error("BLOCKED: PR_REVIEW micro dispatch requires the complete trigger_evaluation ledger");let expected=new Set(PR_REVIEW_REQUIRED_MICRO_LANE_IDS),seen=new Set;for(let row of evaluation){if(seen.has(row.trigger_id))throw Error(`BLOCKED: duplicate PR_REVIEW trigger row: ${row.trigger_id}`);seen.add(row.trigger_id)}let missing=[...expected].filter((id)=>!seen.has(id)),unknown3=[...seen].filter((id)=>!expected.has(id));if(missing.length>0||unknown3.length>0)throw Error(`BLOCKED: PR_REVIEW trigger ledger must be exact; missing: ${missing.join(", ")||"(none)"}; unknown: ${unknown3.join(", ")||"(none)"}`);let required3=new Set(evaluation.map((row)=>row.trigger_id)),laneOwnership=args2.lanes.map((lane)=>({label:lane.workflow_lane??"",owned:lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]}));if(depthTier==="L"&&laneOwnership.some((lane)=>lane.owned.length!==1))throw Error("BLOCKED: PR_REVIEW micro dispatch at depth tier L requires one dedicated lane per risk family; consolidated owned_workflow_lanes are allowed only at tiers S and M");let flattened=laneOwnership.flatMap((lane)=>lane.owned),duplicates=flattened.filter((value,index)=>flattened.indexOf(value)!==index),unmatched=flattened.filter((triggerId)=>!required3.has(triggerId)),invalidLabels=laneOwnership.filter((lane)=>lane.label.length===0||!lane.owned.includes(lane.label)).map((lane)=>lane.label||"(missing workflow_lane)");if(invalidLabels.length>0||duplicates.length>0||unmatched.length>0)throw Error(`BLOCKED: PR_REVIEW micro lanes must have unique workflow_lane IDs from the mandatory repository-agnostic lane set, with workflow_lane contained in its own owned set; invalid: ${[...new Set([...invalidLabels,...duplicates,...unmatched])].join(", ")}`)}var _internals140={getSessionOps:()=>swarmState.opencodeClient?.session??null,getGeneratedAgentNames:()=>swarmState.generatedAgentNames,createParallelDispatcher,resolvePrWorkflowRevisionDigest,resolveExactMergeBase,now:()=>Date.now(),sleep:sleep3};async function executeDispatchLanes(args2,directory,context={}){let parsed=DispatchLanesArgsSchema.safeParse(args2);if(!parsed.success)return failureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`)});let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return failureResult({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});if(context.sessionID?.trim())try{await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes")}catch(error93){return failureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let session=_internals140.getSessionOps();if(!session)return failureResult({failure_class:"no_client",message:"OpenCode session client is not available"});let common=applyCommonPrompt(parsed.data.lanes,parsed.data.common_prompt);if(!common.ok)return failureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:common.errors});let lanes=applyExplorerFormatSuffix(common.lanes),maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS4,dispatcher=_internals140.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>runLane(session,dispatcher,lane,directory,timeoutMs,context))));return buildResult(laneResults,maxConcurrent,timeoutMs)}finally{dispatcher.shutdown()}}async function executeDispatchLanesAsync(args2,directory,context={}){let parsed=DispatchLanesAsyncArgsSchema.safeParse(args2);if(!parsed.success)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`)});let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return asyncFailureResult({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes_async batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});let requestedBatchId=parsed.data.batch_id??makeBatchId(),session=_internals140.getSessionOps();if(!session||typeof session.promptAsync!=="function")return asyncFailureResult({failure_class:"no_client",message:"OpenCode session promptAsync client is not available"});let common=applyCommonPrompt(parsed.data.lanes,parsed.data.common_prompt);if(!common.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:common.errors});let lanes=common.lanes,batchId=requestedBatchId;if(findByBatchId(directory,batchId).length>0)return asyncFailureResult({failure_class:"invalid_args",message:`Async lane batch already exists: ${batchId}`,errors:[`batch_id must be unique: ${batchId}`]});let verifiedPrHead,workflowRevisionDigest,verifiedReviewBaseSha;if(context.sessionID?.trim()&&parsed.data.pr_head_sha&&(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")))try{if(verifiedPrHead=assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha),workflowRevisionDigest=_internals140.resolvePrWorkflowRevisionDigest(directory,parsed.data.pr_head_sha)??void 0,!workflowRevisionDigest)throw Error("BLOCKED: PR workflow could not compute a bounded current-revision digest");if(parsed.data.mode?.startsWith("swarm-pr-review:")){if(!parsed.data.base_sha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW dispatch requires exact base_sha and base_ref");let resolvedBase=_internals140.resolveExactMergeBase(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedBase||resolvedBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())throw Error("BLOCKED: PR_REVIEW base_sha is not the exact merge base of base_ref and pr_head_sha");verifiedReviewBaseSha=resolvedBase}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow checkout head verification failed"})}if(context.sessionID?.trim())try{let gateState=await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes_async");if(!gateState&&parsed.data.mode?.startsWith("swarm-pr-review:"))gateState=await activatePrWorkflow(directory,context.sessionID,"PR_REVIEW");else if(!gateState&&parsed.data.mode==="swarm-pr-feedback:verification")gateState=await activatePrWorkflow(directory,context.sessionID,"PR_FEEDBACK");if(gateState?.mode==="PR_REVIEW"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: active PR_REVIEW dispatch requires pr_head_sha");if(!verifiedReviewBaseSha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW exact merge-base scope was not verified");gateState=await bindPrReviewBase(directory,context.sessionID,{prHeadSha:headSha,baseRef:parsed.data.base_ref,baseSha:verifiedReviewBaseSha});let laneSpecs=parsed.data.lanes.map((lane)=>({laneId:lane.id,workflowLane:lane.workflow_lane,reviewItemIds:lane.review_item_ids,ownedWorkflowLanes:lane.owned_workflow_lanes})),depthTier=gateState.prReviewDepthTier??"L";if(parsed.data.mode==="swarm-pr-review:base"){if((gateState.prReviewBaseDispatches?.length??0)===0){let ownedDimensionIds=parsed.data.lanes.flatMap((lane)=>lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]),coversAllSixExactlyOnce=ownedDimensionIds.length===PR_REVIEW_BASE_DIMENSION_IDS.length&&new Set(ownedDimensionIds).size===PR_REVIEW_BASE_DIMENSION_IDS.length&&PR_REVIEW_BASE_DIMENSION_IDS.every((dimensionId)=>ownedDimensionIds.includes(dimensionId));if(depthTier==="L"){if(parsed.data.lanes.length!==6||parsed.data.max_concurrent!==6||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: initial PR_REVIEW base dispatch requires exactly six lanes and max_concurrent: 6 at depth tier L (consolidated owned_workflow_lanes are allowed only at tiers S and M)")}else if(!coversAllSixExactlyOnce||parsed.data.lanes.length<PR_REVIEW_BASE_LANE_FLOORS[depthTier]||parsed.data.lanes.length>PR_REVIEW_BASE_DIMENSION_IDS.length||parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error(`BLOCKED: initial PR_REVIEW base dispatch at depth tier ${depthTier} requires between ${PR_REVIEW_BASE_LANE_FLOORS[depthTier]} and ${PR_REVIEW_BASE_DIMENSION_IDS.length} lanes whose owned_workflow_lanes partition all six dimensions exactly once, with max_concurrent equal to the lane count`)}for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW base lane "${lane.id}" must use the explorer role`);await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha})}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled(directory,context.sessionID),gateState.prHeadSha&&gateState.prHeadSha!==headSha)throw Error(`BLOCKED: PR_REVIEW head mismatch; expected "${gateState.prHeadSha}", received "${headSha}"`);for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW micro lane "${lane.id}" must use the explorer role`);validatePrReviewMicroDispatch(parsed.data,depthTier)}else if(parsed.data.mode==="swarm-pr-review:council"||parsed.data.mode==="swarm-pr-review:reviewer"||parsed.data.mode==="swarm-pr-review:critic"){let phase=parsed.data.mode.endsWith(":council")?"council":parsed.data.mode.endsWith(":reviewer")?"reviewer":"critic";if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to base and micro discovery lanes`);for(let lane of parsed.data.lanes){let role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames);if(phase==="council"&&!role.startsWith("council_")||phase==="reviewer"&&role!=="reviewer"||phase==="critic"&&!role.startsWith("critic"))throw Error(`BLOCKED: PR_REVIEW ${phase} lane "${lane.id}" uses invalid role "${role||lane.agent}"`)}await recordPrReviewValidationBatch(directory,context.sessionID,phase,laneSpecs,{batchId,prHeadSha:headSha})}else throw Error("BLOCKED: active PR_REVIEW requires a structured base, micro, council, reviewer, or critic mode")}else if(gateState?.mode==="PR_FEEDBACK"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha");if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error("BLOCKED: PR_FEEDBACK lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to PR_REVIEW base and micro discovery lanes");if(parsed.data.mode==="swarm-pr-feedback:verification")await declarePrFeedbackInventory(directory,context.sessionID,parsed.data.feedback_inventory??[],{prHeadSha:headSha}),await enforcePrFeedbackVerificationOwnership(directory,context.sessionID,parsed.data.lanes.map((lane)=>({laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]})),{batchId,prHeadSha:headSha});else if(parsed.data.mode==="swarm-pr-feedback:stage-b-reviewer"||parsed.data.mode==="swarm-pr-feedback:stage-b-test"||parsed.data.mode==="swarm-pr-feedback:closeout-reviewer"||parsed.data.mode==="swarm-pr-feedback:closeout-critic"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1)throw Error("BLOCKED: each ordered PR_FEEDBACK gate requires exactly one lane and max_concurrent: 1");let phase=parsed.data.mode.slice(18),lane=parsed.data.lanes[0],role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames),expectedRole=phase==="stage-b-test"?"test_engineer":phase==="closeout-critic"?"critic":"reviewer";if(lane.workflow_lane!==phase||(expectedRole==="critic"?!role.startsWith("critic"):role!==expectedRole))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires workflow_lane "${phase}" and role "${expectedRole}"`);await recordPrFeedbackGateBatch(directory,context.sessionID,phase,{laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]},{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest??""})}else throw Error("BLOCKED: active PR_FEEDBACK requires structured verification, Stage B reviewer/test, and closeout reviewer/critic modes")}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let contracted=applyPrWorkflowPromptContract(lanes,{mode:parsed.data.mode,prHeadSha:verifiedPrHead,revisionDigest:workflowRevisionDigest,scope:verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:"the complete immutable feedback inventory on the exact checked-out revision",callerFocus:parsed.data.scope});if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});lanes=applyExplorerFormatSuffix(contracted.lanes);let canonicalWorkflowScope=verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:parsed.data.mode?.startsWith("swarm-pr-feedback:")?"the complete immutable feedback inventory on the exact checked-out revision":parsed.data.scope,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),launchTimeoutMs=parsed.data.launch_timeout_ms??parsed.data.timeout_ms??DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS,dispatcher=_internals140.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>launchAsyncLane({session,dispatcher,lane,directory,timeoutMs:launchTimeoutMs,context,batchId,mode:parsed.data.mode,prHeadSha:parsed.data.pr_head_sha,gitHead:verifiedPrHead,dirtyHash:workflowRevisionDigest,scope:canonicalWorkflowScope})))),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected"),pending=laneResults.filter((lane)=>lane.status==="pending");return{success:failed.length===0&&rejected.length===0,batch_id:batchId,dispatched:laneResults.length,pending:pending.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,launch_timeout_ms:launchTimeoutMs,timeout_ms:launchTimeoutMs,lane_results:laneResults}}finally{dispatcher.shutdown()}}async function executeCollectLaneResults(args2,directory,context={}){let parsed=CollectLaneResultsArgsSchema.safeParse(args2);if(!parsed.success)return collectFailureResult({failure_class:"invalid_args",batch_id:"",message:"Invalid collect_lane_results arguments",errors:parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`)});let session=_internals140.getSessionOps();if(!session||typeof session.messages!=="function")return collectFailureResult({failure_class:"no_client",batch_id:parsed.data.batch_id,message:"OpenCode session messages client is not available"});let timeoutMs=parsed.data.timeout_ms??DEFAULT_COLLECT_TIMEOUT_MS,deadline=_internals140.now()+timeoutMs,batchFilter=context.sessionID!==void 0?{parentSessionId:context.sessionID}:void 0,records=findByBatchId(directory,parsed.data.batch_id,batchFilter);if(records.length===0)return collectFailureResult({failure_class:"not_found",batch_id:parsed.data.batch_id,message:`No async lane batch found for ${parsed.data.batch_id}`});let keepPolling=!0,pollIntervalMs=COLLECT_POLL_INTERVAL_MS;while(keepPolling){if(await collectOnce(session,directory,records,parsed.data.cancel_pending===!0),await sweepStaleAsyncLaneRecords(session,directory,records,DEFAULT_ASYNC_STALE_TIMEOUT_MS),records=findByBatchId(directory,parsed.data.batch_id,batchFilter),allSettled(records)||parsed.data.wait!==!0){keepPolling=!1;continue}if(_internals140.now()>=deadline){keepPolling=!1;continue}await _internals140.sleep(Math.min(pollIntervalMs,Math.max(0,deadline-_internals140.now()))),pollIntervalMs=nextCollectPollInterval(pollIntervalMs)}return buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0)}async function launchAsyncLane(args2){let validation2=validateLaneAgent(args2.lane.agent,args2.context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:args2.lane.id,agent:args2.lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let decision=args2.dispatcher.dispatch(args2.lane.id);if(decision.action!=="dispatch")return{id:args2.lane.id,agent:args2.lane.agent,role,status:"failed",started_at:startedAt,completed_at:isoNow2(),error:`dispatcher ${decision.action}: ${decision.reason}`};try{let createTimeoutMessage=`Lane "${args2.lane.id}" session.create timed out after ${args2.timeoutMs}ms`,createPromise=args2.session.create(buildLaneSessionCreateArgs(args2.directory,args2.lane,args2.context)),createTimedOut=!1;createPromise.then((createResult2)=>{if(createTimedOut&&createResult2.data?.id)scheduleSessionCleanup(args2.session,createResult2.data.id)}).catch(()=>{return});let createResult=await withTimeout2(createPromise,args2.timeoutMs,createTimeoutMessage).catch((error93)=>{if(formatError3(error93)===createTimeoutMessage)createTimedOut=!0;throw error93}),sessionId=createResult.data?.id;if(!sessionId)return failedLane(args2.lane,role,startedAt,`session.create failed: ${formatError3(createResult.error)}`,decision.slot.slotId,decision.slot.runId);if(!await recordPendingDelegation(args2.directory,{correlationId:sessionId,jobId:null,subagentSessionId:sessionId,parentSessionId:args2.context.sessionID??`dispatch_lanes_async:${args2.batchId}`,callID:args2.batchId,normalizedAgent:role,swarmPrefixedAgent:args2.lane.agent,planTaskId:null,evidenceTaskId:null,batchId:args2.batchId,laneId:args2.lane.id,mode:args2.mode??"advisory",workflowLane:args2.lane.workflow_lane,ownedWorkflowLanes:args2.lane.owned_workflow_lanes,promptHash:promptHash(args2.lane,args2.directory,args2.batchId),workspace:{directory:args2.directory,gitHead:args2.gitHead??null,dirtyHash:args2.dirtyHash??null,prHeadSha:args2.prHeadSha??null,scope:args2.scope??null},generation:1}))return cleanupAsyncLaunchSession(args2.session,sessionId),failedLane(args2.lane,role,startedAt,"Failed to record async lane in background delegation ledger",decision.slot.slotId,decision.slot.runId);return scheduleAsyncLanePrompt({session:args2.session,directory:args2.directory,sessionId,lane:args2.lane,timeoutMs:args2.timeoutMs}),{id:args2.lane.id,agent:args2.lane.agent,role,status:"pending",session_id:sessionId,slot_id:decision.slot.slotId,run_id:decision.slot.runId,started_at:startedAt,completed_at:isoNow2()}}catch(error93){return failedLane(args2.lane,role,startedAt,formatError3(error93),decision.slot.slotId,decision.slot.runId)}finally{args2.dispatcher.releaseSlot(decision.slot.slotId)}}async function collectOnce(session,directory,records,cancelPending){for(let record3 of records){if(record3.status!=="pending"&&record3.status!=="running")continue;if(cancelPending){if(typeof session.abort==="function")await session.abort({path:{id:record3.subagentSessionId}}).catch(()=>{return});await appendDelegationTransition(directory,record3.correlationId,{status:"cancelled"});continue}if(!await isLaneReadyForCollection(session,directory,record3.subagentSessionId))continue;let messages;try{messages=await session.messages({path:{id:record3.subagentSessionId},query:{directory,limit:ASYNC_MESSAGE_FETCH_LIMIT}})}catch{continue}if(!messages.data)continue;let transcript=extractAssistantTranscript(messages.data);if(!transcript.text)continue;let output=prepareLaneOutput({directory,batchId:record3.batchId??record3.callID,laneId:record3.laneId??record3.correlationId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,sessionId:record3.subagentSessionId,parentSessionId:record3.parentSessionId,mode:record3.mode,workflowLane:record3.workflowLane,prHeadSha:record3.workspace?.prHeadSha??void 0,gitHead:record3.workspace?.gitHead??void 0,revisionDigest:record3.workspace?.prHeadSha?_internals140.resolvePrWorkflowRevisionDigest(directory,record3.workspace.prHeadSha)??void 0:void 0,scope:record3.workspace?.scope??void 0,source:"collect_lane_results",text:transcript.text,messageCount:transcript.messageCount,transcriptIncomplete:transcript.transcriptIncomplete});await appendDelegationTransition(directory,record3.correlationId,{status:"completed",result:{text:output.output,chars:output.output_chars,truncated:output.output_truncated,digest:output.output_digest,...output.output_ref?{outputRef:output.output_ref}:{},outputPreviewChars:output.output.length,...output.output_degraded!==void 0?{outputDegraded:output.output_degraded}:{},...output.output_artifact_error?{outputArtifactError:output.output_artifact_error}:{},...output.transcript_incomplete!==void 0?{transcriptIncomplete:output.transcript_incomplete}:{},messageCount:transcript.messageCount}})}}function scheduleAsyncLanePrompt(args2){queueMicrotask(()=>{startAsyncLanePrompt(args2).catch(async(error93)=>{let message=formatError3(error93);await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,message)})})}async function startAsyncLanePrompt(args2){let promptController=new AbortController,promptResult;try{promptResult=await withTimeout2(args2.session.promptAsync({path:{id:args2.sessionId},query:{directory:args2.directory},body:{agent:args2.lane.agent,tools:buildReadOnlyTools(),parts:[{type:"text",text:args2.lane.prompt}]},signal:promptController.signal}),args2.timeoutMs,`Lane "${args2.lane.id}" session.promptAsync launch timed out after ${args2.timeoutMs}ms`,promptController)}catch(error93){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}if(promptResult.error){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`session.promptAsync launch failed: ${formatError3(promptResult.error)}`);return}await appendDelegationTransition(args2.directory,args2.sessionId,{status:"running"})}async function appendAsyncLaneLaunchError(directory,session,sessionId,message){await appendDelegationTransition(directory,sessionId,{status:"error",result:{error:message,chars:message.length,truncated:!1,digest:digestText2(message)}}),cleanupAsyncLaunchSession(session,sessionId)}async function isLaneReadyForCollection(session,directory,sessionId){if(typeof session.status!=="function")return!0;try{let status=await session.status({query:{directory}});if(status.error||!status.data)return!1;let current=status.data[sessionId];return current===void 0||current.type==="idle"}catch{return!1}}async function sweepStaleAsyncLaneRecords(session,directory,records,staleTimeoutMs){if(staleTimeoutMs<=0)return;let now=_internals140.now();for(let record3 of records){if(record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingestion_error")continue;if(now-record3.updatedAt<=staleTimeoutMs)continue;if(!await isLaneReadyForCollection(session,directory,record3.subagentSessionId))continue;await appendDelegationTransition(directory,record3.correlationId,{status:"stale"})}}function extractAssistantTranscript(messages){let assistantTexts=[];for(let message of messages){if(message.info?.role!=="assistant")continue;let text=extractText3(message.parts);if(text.trim().length>0)assistantTexts.push(text)}return{text:assistantTexts.join(`
6099
+ Do NOT use the default PROJECT/STRUCTURE output format for this dispatch.`,READ_ONLY_LANE_ROLES=new Set(["explorer","reviewer","test_engineer","critic","critic_oversight","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","sme","researcher","council_generalist","council_skeptic","council_domain_expert"]),READ_ONLY_TOOL_DENYLIST=[...new Set([...WRITE_TOOL_NAMES,"extract_code_blocks","multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","summarize_work","doc_scan","lint","shell","bash"])],LaneSchema=exports_external.object({id:exports_external.string().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).describe("Stable lane identifier, unique within this dispatch batch"),agent:exports_external.string().min(1).max(120).describe("Read-only swarm agent name, including any generated swarm prefix"),prompt:exports_external.string().min(1).max(MAX_PROMPT_CHARS).describe("Full lane prompt to send to the requested agent"),workflow_lane:exports_external.string().min(1).max(120).optional().describe("Required mechanical policy identifier in PR workflows; distinct from the retry-safe lane id"),owned_workflow_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Complete dimension/family set a consolidated PR-review base or micro lane covers under the controller-computed depth tier; must include workflow_lane. Omit for singleton lanes."),feedback_item_ids:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("PR-feedback ledger item IDs owned exclusively by this lane"),review_item_ids:exports_external.array(exports_external.string().trim().min(1).max(160)).min(1).optional().describe("Candidate/finding IDs owned by a PR-review reviewer or critic lane; every ID requires a parseable verdict row")}),PrReviewTriggerEvaluationRowSchema=exports_external.object({trigger_id:exports_external.string().trim().min(1).max(120),result:exports_external.literal("MATCHED"),evidence:exports_external.string().trim().min(1).max(4000)}).strict(),DispatchLanesArgsSchema=exports_external.object({lanes:exports_external.array(LaneSchema).min(1).max(MAX_LANES).describe("Read-only lane specs to dispatch concurrently"),common_prompt:exports_external.string().min(1).regex(/\S/,"common_prompt must contain non-whitespace content").max(MAX_PROMPT_CHARS-COMMON_PROMPT_SEPARATOR.length-1).optional().describe("Optional shared context prepended to every lane prompt. Send large shared context (PR diff, obligation ledger, scope) ONCE here instead of inlining the same blob into each lane prompt; this keeps the tool-call payload small and avoids malformed/truncated tool-call JSON. Combined common_prompt + per-lane prompt must not exceed the per-lane character limit."),max_concurrent:exports_external.number().int().min(1).max(MAX_LANES).optional().describe("Maximum lanes in flight at once; defaults to lane count"),timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS2).optional().describe("Per-lane timeout in milliseconds. For blocking dispatch this covers session create and prompt execution; for async dispatch this covers launch only, never lane runtime.")}),DispatchLanesAsyncArgsSchema=DispatchLanesArgsSchema.extend({launch_timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS2).optional().describe("Async launch acceptance timeout in milliseconds. This only bounds session creation and promptAsync acceptance; it is never a lane runtime timeout. Deprecated alias: timeout_ms."),batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS).regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/).optional().describe("Stable async batch id for later collection; generated when omitted"),mode:exports_external.string().min(1).max(80).optional().describe("Advisory workflow mode, such as deep-dive or swarm-pr-review"),pr_head_sha:exports_external.string().min(1).max(80).optional(),base_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i).optional(),base_ref:exports_external.string().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional(),scope:exports_external.string().min(1).max(500).optional(),trigger_evaluation:exports_external.array(PrReviewTriggerEvaluationRowSchema).min(1).optional().describe("Exact all-MATCHED repository-agnostic mandatory micro-lane ledger required for swarm-pr-review:micro"),feedback_inventory:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("Complete immutable feedback item inventory required for swarm-pr-feedback:verification")}),CollectLaneResultsArgsSchema=exports_external.object({batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS),wait:exports_external.boolean().optional().describe("Poll until all lanes settle or timeout"),timeout_ms:exports_external.number().int().min(0).max(MAX_COLLECT_TIMEOUT_MS).optional().describe("Total wait budget when wait=true"),include_pending:exports_external.boolean().optional().describe("Include pending/running lanes in lane_results. Defaults to true for non-blocking polls and false for wait=true joins."),cancel_pending:exports_external.boolean().optional().describe("Abort and mark pending/running lanes cancelled")});function validatePrReviewMicroDispatch(args2,depthTier){let evaluation=args2.trigger_evaluation;if(!evaluation)throw Error("BLOCKED: PR_REVIEW micro dispatch requires the complete trigger_evaluation ledger");let expected=new Set(PR_REVIEW_REQUIRED_MICRO_LANE_IDS),seen=new Set;for(let row of evaluation){if(seen.has(row.trigger_id))throw Error(`BLOCKED: duplicate PR_REVIEW trigger row: ${row.trigger_id}`);seen.add(row.trigger_id)}let missing=[...expected].filter((id)=>!seen.has(id)),unknown3=[...seen].filter((id)=>!expected.has(id));if(missing.length>0||unknown3.length>0)throw Error(`BLOCKED: PR_REVIEW trigger ledger must be exact; missing: ${missing.join(", ")||"(none)"}; unknown: ${unknown3.join(", ")||"(none)"}`);let required3=new Set(evaluation.map((row)=>row.trigger_id)),laneOwnership=args2.lanes.map((lane)=>({label:lane.workflow_lane??"",owned:lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]}));if(depthTier==="L"&&laneOwnership.some((lane)=>lane.owned.length!==1))throw Error("BLOCKED: PR_REVIEW micro dispatch at depth tier L requires one dedicated lane per risk family; consolidated owned_workflow_lanes are allowed only at tiers S and M");let flattened=laneOwnership.flatMap((lane)=>lane.owned),duplicates=flattened.filter((value,index)=>flattened.indexOf(value)!==index),unmatched=flattened.filter((triggerId)=>!required3.has(triggerId)),invalidLabels=laneOwnership.filter((lane)=>lane.label.length===0||!lane.owned.includes(lane.label)).map((lane)=>lane.label||"(missing workflow_lane)");if(invalidLabels.length>0||duplicates.length>0||unmatched.length>0)throw Error(`BLOCKED: PR_REVIEW micro lanes must have unique workflow_lane IDs from the mandatory repository-agnostic lane set, with workflow_lane contained in its own owned set; invalid: ${[...new Set([...invalidLabels,...duplicates,...unmatched])].join(", ")}`);let coversAllFamilies=required3.size>0&&[...required3].every((id)=>flattened.includes(id)),microFloor=PR_REVIEW_MICRO_LANE_FLOORS[depthTier];if(coversAllFamilies&&laneOwnership.length<microFloor)throw Error(`BLOCKED: PR_REVIEW micro dispatch at depth tier ${depthTier} covering all ${PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length} risk families requires at least ${microFloor} lanes; received ${laneOwnership.length}. Partial retry batches covering a subset of families are exempt.`)}var _internals140={getSessionOps:()=>swarmState.opencodeClient?.session??null,getGeneratedAgentNames:()=>swarmState.generatedAgentNames,createParallelDispatcher,resolvePrWorkflowRevisionDigestAsync,resolveExactMergeBaseAsync,now:()=>Date.now(),sleep:sleep3};async function executeDispatchLanes(args2,directory,context={}){let parsed=DispatchLanesArgsSchema.safeParse(args2);if(!parsed.success)return failureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`)});let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return failureResult({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});if(context.sessionID?.trim())try{await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes")}catch(error93){return failureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let session=_internals140.getSessionOps();if(!session)return failureResult({failure_class:"no_client",message:"OpenCode session client is not available"});let common=applyCommonPrompt(parsed.data.lanes,parsed.data.common_prompt);if(!common.ok)return failureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:common.errors});let lanes=applyExplorerFormatSuffix(common.lanes),maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS4,dispatcher=_internals140.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>runLane(session,dispatcher,lane,directory,timeoutMs,context))));return buildResult(laneResults,maxConcurrent,timeoutMs)}finally{dispatcher.shutdown()}}async function executeDispatchLanesAsync(args2,directory,context={}){let parsed=DispatchLanesAsyncArgsSchema.safeParse(args2);if(!parsed.success)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`)});let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return asyncFailureResult({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes_async batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});let requestedBatchId=parsed.data.batch_id??makeBatchId(),session=_internals140.getSessionOps();if(!session||typeof session.promptAsync!=="function")return asyncFailureResult({failure_class:"no_client",message:"OpenCode session promptAsync client is not available"});let common=applyCommonPrompt(parsed.data.lanes,parsed.data.common_prompt);if(!common.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:common.errors});let lanes=common.lanes,batchId=requestedBatchId;if(findByBatchId(directory,batchId).length>0)return asyncFailureResult({failure_class:"invalid_args",message:`Async lane batch already exists: ${batchId}`,errors:[`batch_id must be unique: ${batchId}`]});let verifiedPrHead,workflowRevisionDigest,verifiedReviewBaseSha;if(context.sessionID?.trim()&&parsed.data.pr_head_sha&&(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")))try{if(verifiedPrHead=await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha),workflowRevisionDigest=await _internals140.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha)??void 0,!workflowRevisionDigest)throw Error("BLOCKED: PR workflow could not compute a bounded current-revision digest");if(parsed.data.mode?.startsWith("swarm-pr-review:")){if(!parsed.data.base_sha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW dispatch requires exact base_sha and base_ref");let resolvedBase=await _internals140.resolveExactMergeBaseAsync(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedBase||resolvedBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())throw Error("BLOCKED: PR_REVIEW base_sha is not the exact merge base of base_ref and pr_head_sha");verifiedReviewBaseSha=resolvedBase}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow checkout head verification failed"})}if(context.sessionID?.trim())try{let gateState=await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes_async");if(!gateState&&parsed.data.mode?.startsWith("swarm-pr-review:"))gateState=await activatePrWorkflow(directory,context.sessionID,"PR_REVIEW");else if(!gateState&&parsed.data.mode==="swarm-pr-feedback:verification")gateState=await activatePrWorkflow(directory,context.sessionID,"PR_FEEDBACK");if(gateState?.mode==="PR_REVIEW"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: active PR_REVIEW dispatch requires pr_head_sha");if(!verifiedReviewBaseSha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW exact merge-base scope was not verified");gateState=await bindPrReviewBase(directory,context.sessionID,{prHeadSha:headSha,baseRef:parsed.data.base_ref,baseSha:verifiedReviewBaseSha});let laneSpecs=parsed.data.lanes.map((lane)=>({laneId:lane.id,workflowLane:lane.workflow_lane,reviewItemIds:lane.review_item_ids,ownedWorkflowLanes:lane.owned_workflow_lanes})),depthTier=gateState.prReviewDepthTier??"L";if(parsed.data.mode==="swarm-pr-review:base"){if((gateState.prReviewBaseDispatches?.length??0)===0){let ownedDimensionIds=parsed.data.lanes.flatMap((lane)=>lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]),coversAllSixExactlyOnce=ownedDimensionIds.length===PR_REVIEW_BASE_DIMENSION_IDS.length&&new Set(ownedDimensionIds).size===PR_REVIEW_BASE_DIMENSION_IDS.length&&PR_REVIEW_BASE_DIMENSION_IDS.every((dimensionId)=>ownedDimensionIds.includes(dimensionId));if(depthTier==="L"){if(parsed.data.lanes.length!==6||parsed.data.max_concurrent!==6||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: initial PR_REVIEW base dispatch requires exactly six lanes and max_concurrent: 6 at depth tier L (consolidated owned_workflow_lanes are allowed only at tiers S and M)")}else if(!coversAllSixExactlyOnce||parsed.data.lanes.length<PR_REVIEW_BASE_LANE_FLOORS[depthTier]||parsed.data.lanes.length>PR_REVIEW_BASE_DIMENSION_IDS.length||parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error(`BLOCKED: initial PR_REVIEW base dispatch at depth tier ${depthTier} requires between ${PR_REVIEW_BASE_LANE_FLOORS[depthTier]} and ${PR_REVIEW_BASE_DIMENSION_IDS.length} lanes whose owned_workflow_lanes partition all six dimensions exactly once, with max_concurrent equal to the lane count`)}for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW base lane "${lane.id}" must use the explorer role`);await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha})}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled(directory,context.sessionID),gateState.prHeadSha&&gateState.prHeadSha!==headSha)throw Error(`BLOCKED: PR_REVIEW head mismatch; expected "${gateState.prHeadSha}", received "${headSha}"`);for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW micro lane "${lane.id}" must use the explorer role`);validatePrReviewMicroDispatch(parsed.data,depthTier)}else if(parsed.data.mode==="swarm-pr-review:council"||parsed.data.mode==="swarm-pr-review:reviewer"||parsed.data.mode==="swarm-pr-review:critic"){let phase=parsed.data.mode.endsWith(":council")?"council":parsed.data.mode.endsWith(":reviewer")?"reviewer":"critic";if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to base and micro discovery lanes`);for(let lane of parsed.data.lanes){let role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames);if(phase==="council"&&!role.startsWith("council_")||phase==="reviewer"&&role!=="reviewer"||phase==="critic"&&!role.startsWith("critic"))throw Error(`BLOCKED: PR_REVIEW ${phase} lane "${lane.id}" uses invalid role "${role||lane.agent}"`)}await recordPrReviewValidationBatch(directory,context.sessionID,phase,laneSpecs,{batchId,prHeadSha:headSha})}else throw Error("BLOCKED: active PR_REVIEW requires a structured base, micro, council, reviewer, or critic mode")}else if(gateState?.mode==="PR_FEEDBACK"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha");if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error("BLOCKED: PR_FEEDBACK lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to PR_REVIEW base and micro discovery lanes");if(parsed.data.mode==="swarm-pr-feedback:verification")await declarePrFeedbackInventory(directory,context.sessionID,parsed.data.feedback_inventory??[],{prHeadSha:headSha}),await enforcePrFeedbackVerificationOwnership(directory,context.sessionID,parsed.data.lanes.map((lane)=>({laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]})),{batchId,prHeadSha:headSha});else if(parsed.data.mode==="swarm-pr-feedback:stage-b-reviewer"||parsed.data.mode==="swarm-pr-feedback:stage-b-test"||parsed.data.mode==="swarm-pr-feedback:closeout-reviewer"||parsed.data.mode==="swarm-pr-feedback:closeout-critic"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1)throw Error("BLOCKED: each ordered PR_FEEDBACK gate requires exactly one lane and max_concurrent: 1");let phase=parsed.data.mode.slice(18),lane=parsed.data.lanes[0],role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames),expectedRole=phase==="stage-b-test"?"test_engineer":phase==="closeout-critic"?"critic":"reviewer";if(lane.workflow_lane!==phase||(expectedRole==="critic"?!role.startsWith("critic"):role!==expectedRole))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires workflow_lane "${phase}" and role "${expectedRole}"`);await recordPrFeedbackGateBatch(directory,context.sessionID,phase,{laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]},{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest??""})}else throw Error("BLOCKED: active PR_FEEDBACK requires structured verification, Stage B reviewer/test, and closeout reviewer/critic modes")}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let contracted=applyPrWorkflowPromptContract(lanes,{mode:parsed.data.mode,prHeadSha:verifiedPrHead,revisionDigest:workflowRevisionDigest,scope:verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:"the complete immutable feedback inventory on the exact checked-out revision",callerFocus:parsed.data.scope});if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});lanes=applyExplorerFormatSuffix(contracted.lanes);let canonicalWorkflowScope=verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:parsed.data.mode?.startsWith("swarm-pr-feedback:")?"the complete immutable feedback inventory on the exact checked-out revision":parsed.data.scope,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),launchTimeoutMs=parsed.data.launch_timeout_ms??parsed.data.timeout_ms??DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS,dispatcher=_internals140.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>launchAsyncLane({session,dispatcher,lane,directory,timeoutMs:launchTimeoutMs,context,batchId,mode:parsed.data.mode,prHeadSha:parsed.data.pr_head_sha,gitHead:verifiedPrHead,dirtyHash:workflowRevisionDigest,scope:canonicalWorkflowScope})))),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected"),pending=laneResults.filter((lane)=>lane.status==="pending");return{success:failed.length===0&&rejected.length===0,batch_id:batchId,dispatched:laneResults.length,pending:pending.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,launch_timeout_ms:launchTimeoutMs,timeout_ms:launchTimeoutMs,lane_results:laneResults}}finally{dispatcher.shutdown()}}async function executeCollectLaneResults(args2,directory,context={}){let parsed=CollectLaneResultsArgsSchema.safeParse(args2);if(!parsed.success)return collectFailureResult({failure_class:"invalid_args",batch_id:"",message:"Invalid collect_lane_results arguments",errors:parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`)});let session=_internals140.getSessionOps();if(!session||typeof session.messages!=="function")return collectFailureResult({failure_class:"no_client",batch_id:parsed.data.batch_id,message:"OpenCode session messages client is not available"});let timeoutMs=parsed.data.timeout_ms??DEFAULT_COLLECT_TIMEOUT_MS,deadline=_internals140.now()+timeoutMs,batchFilter=context.sessionID!==void 0?{parentSessionId:context.sessionID}:void 0,records=findByBatchId(directory,parsed.data.batch_id,batchFilter);if(records.length===0)return collectFailureResult({failure_class:"not_found",batch_id:parsed.data.batch_id,message:`No async lane batch found for ${parsed.data.batch_id}`});let keepPolling=!0,pollIntervalMs=COLLECT_POLL_INTERVAL_MS;while(keepPolling){if(await collectOnce(session,directory,records,parsed.data.cancel_pending===!0),await sweepStaleAsyncLaneRecords(session,directory,records,DEFAULT_ASYNC_STALE_TIMEOUT_MS),records=findByBatchId(directory,parsed.data.batch_id,batchFilter),allSettled(records)||parsed.data.wait!==!0){keepPolling=!1;continue}if(_internals140.now()>=deadline){keepPolling=!1;continue}await _internals140.sleep(Math.min(pollIntervalMs,Math.max(0,deadline-_internals140.now()))),pollIntervalMs=nextCollectPollInterval(pollIntervalMs)}return buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0)}async function launchAsyncLane(args2){let validation2=validateLaneAgent(args2.lane.agent,args2.context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:args2.lane.id,agent:args2.lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let decision=args2.dispatcher.dispatch(args2.lane.id);if(decision.action!=="dispatch")return{id:args2.lane.id,agent:args2.lane.agent,role,status:"failed",started_at:startedAt,completed_at:isoNow2(),error:`dispatcher ${decision.action}: ${decision.reason}`};try{let createTimeoutMessage=`Lane "${args2.lane.id}" session.create timed out after ${args2.timeoutMs}ms`,createPromise=args2.session.create(buildLaneSessionCreateArgs(args2.directory,args2.lane,args2.context)),createTimedOut=!1;createPromise.then((createResult2)=>{if(createTimedOut&&createResult2.data?.id)scheduleSessionCleanup(args2.session,createResult2.data.id)}).catch(()=>{return});let createResult=await withTimeout2(createPromise,args2.timeoutMs,createTimeoutMessage).catch((error93)=>{if(formatError3(error93)===createTimeoutMessage)createTimedOut=!0;throw error93}),sessionId=createResult.data?.id;if(!sessionId)return failedLane(args2.lane,role,startedAt,`session.create failed: ${formatError3(createResult.error)}`,decision.slot.slotId,decision.slot.runId);if(!await recordPendingDelegation(args2.directory,{correlationId:sessionId,jobId:null,subagentSessionId:sessionId,parentSessionId:args2.context.sessionID??`dispatch_lanes_async:${args2.batchId}`,callID:args2.batchId,normalizedAgent:role,swarmPrefixedAgent:args2.lane.agent,planTaskId:null,evidenceTaskId:null,batchId:args2.batchId,laneId:args2.lane.id,mode:args2.mode??"advisory",workflowLane:args2.lane.workflow_lane,ownedWorkflowLanes:args2.lane.owned_workflow_lanes,promptHash:promptHash(args2.lane,args2.directory,args2.batchId),workspace:{directory:args2.directory,gitHead:args2.gitHead??null,dirtyHash:args2.dirtyHash??null,prHeadSha:args2.prHeadSha??null,scope:args2.scope??null},generation:1}))return cleanupAsyncLaunchSession(args2.session,sessionId),failedLane(args2.lane,role,startedAt,"Failed to record async lane in background delegation ledger",decision.slot.slotId,decision.slot.runId);return scheduleAsyncLanePrompt({session:args2.session,directory:args2.directory,sessionId,lane:args2.lane,timeoutMs:args2.timeoutMs}),{id:args2.lane.id,agent:args2.lane.agent,role,status:"pending",session_id:sessionId,slot_id:decision.slot.slotId,run_id:decision.slot.runId,started_at:startedAt,completed_at:isoNow2()}}catch(error93){return failedLane(args2.lane,role,startedAt,formatError3(error93),decision.slot.slotId,decision.slot.runId)}finally{args2.dispatcher.releaseSlot(decision.slot.slotId)}}async function collectOnce(session,directory,records,cancelPending){for(let record3 of records){if(record3.status!=="pending"&&record3.status!=="running")continue;if(cancelPending){if(typeof session.abort==="function")await session.abort({path:{id:record3.subagentSessionId}}).catch(()=>{return});await appendDelegationTransition(directory,record3.correlationId,{status:"cancelled"});continue}if(!await isLaneReadyForCollection(session,directory,record3.subagentSessionId))continue;let messages;try{messages=await session.messages({path:{id:record3.subagentSessionId},query:{directory,limit:ASYNC_MESSAGE_FETCH_LIMIT}})}catch{continue}if(!messages.data)continue;let transcript=extractAssistantTranscript(messages.data);if(!transcript.text)continue;let collectedRevisionDigest=record3.workspace?.prHeadSha?await _internals140.resolvePrWorkflowRevisionDigestAsync(directory,record3.workspace.prHeadSha)??void 0:void 0,output=prepareLaneOutput({directory,batchId:record3.batchId??record3.callID,laneId:record3.laneId??record3.correlationId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,sessionId:record3.subagentSessionId,parentSessionId:record3.parentSessionId,mode:record3.mode,workflowLane:record3.workflowLane,prHeadSha:record3.workspace?.prHeadSha??void 0,gitHead:record3.workspace?.gitHead??void 0,revisionDigest:collectedRevisionDigest,scope:record3.workspace?.scope??void 0,source:"collect_lane_results",text:transcript.text,messageCount:transcript.messageCount,transcriptIncomplete:transcript.transcriptIncomplete});await appendDelegationTransition(directory,record3.correlationId,{status:"completed",result:{text:output.output,chars:output.output_chars,truncated:output.output_truncated,digest:output.output_digest,...output.output_ref?{outputRef:output.output_ref}:{},outputPreviewChars:output.output.length,...output.output_degraded!==void 0?{outputDegraded:output.output_degraded}:{},...output.output_artifact_error?{outputArtifactError:output.output_artifact_error}:{},...output.transcript_incomplete!==void 0?{transcriptIncomplete:output.transcript_incomplete}:{},messageCount:transcript.messageCount}})}}function scheduleAsyncLanePrompt(args2){queueMicrotask(()=>{startAsyncLanePrompt(args2).catch(async(error93)=>{let message=formatError3(error93);await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,message)})})}async function startAsyncLanePrompt(args2){let promptController=new AbortController,promptResult;try{promptResult=await withTimeout2(args2.session.promptAsync({path:{id:args2.sessionId},query:{directory:args2.directory},body:{agent:args2.lane.agent,tools:buildReadOnlyTools(),parts:[{type:"text",text:args2.lane.prompt}]},signal:promptController.signal}),args2.timeoutMs,`Lane "${args2.lane.id}" session.promptAsync launch timed out after ${args2.timeoutMs}ms`,promptController)}catch(error93){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}if(promptResult.error){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`session.promptAsync launch failed: ${formatError3(promptResult.error)}`);return}await appendDelegationTransition(args2.directory,args2.sessionId,{status:"running"})}async function appendAsyncLaneLaunchError(directory,session,sessionId,message){await appendDelegationTransition(directory,sessionId,{status:"error",result:{error:message,chars:message.length,truncated:!1,digest:digestText2(message)}}),cleanupAsyncLaunchSession(session,sessionId)}async function isLaneReadyForCollection(session,directory,sessionId){if(typeof session.status!=="function")return!0;try{let status=await session.status({query:{directory}});if(status.error||!status.data)return!1;let current=status.data[sessionId];return current===void 0||current.type==="idle"}catch{return!1}}async function sweepStaleAsyncLaneRecords(session,directory,records,staleTimeoutMs){if(staleTimeoutMs<=0)return;let now=_internals140.now();for(let record3 of records){if(record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingestion_error")continue;if(now-record3.updatedAt<=staleTimeoutMs)continue;if(!await isLaneReadyForCollection(session,directory,record3.subagentSessionId))continue;await appendDelegationTransition(directory,record3.correlationId,{status:"stale"})}}function extractAssistantTranscript(messages){let assistantTexts=[];for(let message of messages){if(message.info?.role!=="assistant")continue;let text=extractText3(message.parts);if(text.trim().length>0)assistantTexts.push(text)}return{text:assistantTexts.join(`
6098
6100
 
6099
6101
  `),messageCount:assistantTexts.length,transcriptIncomplete:messages.length>=ASYNC_MESSAGE_FETCH_LIMIT}}function nextCollectPollInterval(currentMs){if(currentMs<=0)return COLLECT_POLL_INTERVAL_MS;return Math.min(currentMs*2,MAX_COLLECT_POLL_INTERVAL_MS)}async function runLane(session,dispatcher,lane,directory,timeoutMs,context){let validation2=validateLaneAgent(lane.agent,context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:lane.id,agent:lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let decision=dispatcher.dispatch(lane.id);if(decision.action!=="dispatch")return{id:lane.id,agent:lane.agent,role,status:"failed",started_at:startedAt,completed_at:isoNow2(),error:`dispatcher ${decision.action}: ${decision.reason}`};let promptController=new AbortController,sessionId;try{let createTimeoutMessage=`Lane "${lane.id}" session.create timed out after ${timeoutMs}ms`,createPromise=session.create(buildLaneSessionCreateArgs(directory,lane,context)),createTimedOut=!1;createPromise.then((createResult2)=>{if(createTimedOut&&createResult2.data?.id)scheduleSessionCleanup(session,createResult2.data.id)}).catch(()=>{return});let createResult=await withTimeout2(createPromise,timeoutMs,createTimeoutMessage).catch((error93)=>{if(formatError3(error93)===createTimeoutMessage)createTimedOut=!0;throw error93});if(!createResult.data?.id)return failedLane(lane,role,startedAt,`session.create failed: ${formatError3(createResult.error)}`,decision.slot.slotId,decision.slot.runId);sessionId=createResult.data.id;let promptResult=await withTimeout2(session.prompt({path:{id:sessionId},body:{agent:lane.agent,tools:buildReadOnlyTools(),parts:[{type:"text",text:lane.prompt}]},signal:promptController.signal}),timeoutMs,`Lane "${lane.id}" session.prompt timed out after ${timeoutMs}ms`,promptController);if(!promptResult.data)return failedLane(lane,role,startedAt,`session.prompt failed: ${formatError3(promptResult.error)}`,decision.slot.slotId,decision.slot.runId,sessionId);let laneOutput=prepareLaneOutput({directory,batchId:`blocking:${sessionId}`,laneId:lane.id,agent:lane.agent,role,sessionId,parentSessionId:context.sessionID,source:"dispatch_lanes",text:extractText3(promptResult.data.parts)});return{id:lane.id,agent:lane.agent,role,status:"completed",session_id:sessionId,slot_id:decision.slot.slotId,run_id:decision.slot.runId,started_at:startedAt,completed_at:isoNow2(),...laneOutput}}catch(error93){return failedLane(lane,role,startedAt,formatError3(error93),decision.slot.slotId,decision.slot.runId,sessionId)}finally{if(dispatcher.releaseSlot(decision.slot.slotId),promptController.abort(),sessionId)scheduleSessionCleanup(session,sessionId)}}function buildResult(laneResults,maxConcurrent,timeoutMs){let completed=laneResults.filter((lane)=>lane.status==="completed"),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected");return{success:failed.length===0&&rejected.length===0,dispatched:laneResults.length,completed:completed.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,timeout_ms:timeoutMs,lane_results:laneResults}}function buildCollectResult(batchId,records,includePending){let laneResults=records.filter((record3)=>includePending||record3.status!=="pending"&&record3.status!=="running").map(recordToLaneResult),completed=records.filter((record3)=>record3.status==="completed"),failed=records.filter((record3)=>record3.status==="error"||record3.status==="ingestion_error"),cancelled=records.filter((record3)=>record3.status==="cancelled"),stale=records.filter((record3)=>record3.status==="stale"),pending=records.filter((record3)=>record3.status==="pending"||record3.status==="running"),consumed=records.filter((record3)=>record3.status==="consumed");return{success:pending.length===0&&failed.length===0&&cancelled.length===0&&stale.length===0,batch_id:batchId,total:records.length,completed:completed.length,failed:failed.length,cancelled:cancelled.length,stale:stale.length,pending:pending.length,consumed:consumed.length,all_settled:pending.length===0,lane_results:laneResults}}function recordToLaneResult(record3){let status=record3.status==="error"?"failed":record3.status==="ingestion_error"?"failed":record3.status==="running"?"pending":record3.status;return{id:record3.laneId??record3.correlationId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,status,session_id:record3.subagentSessionId,started_at:new Date(record3.createdAt).toISOString(),completed_at:new Date(record3.completedAt??record3.updatedAt).toISOString(),...record3.result?.text!==void 0?{output:record3.result.text,output_chars:record3.result.chars,output_truncated:record3.result.truncated,output_digest:record3.result.digest,...record3.result.outputRef?{output_ref:record3.result.outputRef}:{},...record3.result.outputPreviewChars!==void 0?{output_preview_chars:record3.result.outputPreviewChars}:{},...record3.result.outputDegraded!==void 0?{output_degraded:record3.result.outputDegraded}:{},...record3.result.outputArtifactError?{output_artifact_error:record3.result.outputArtifactError}:{},...record3.result.transcriptIncomplete!==void 0?{transcript_incomplete:record3.result.transcriptIncomplete}:{},...record3.result.messageCount!==void 0?{message_count:record3.result.messageCount}:{}}:{},...record3.result?.error!==void 0?{error:record3.result.error}:{}}}function allSettled(records){return records.every((record3)=>record3.status!=="pending"&&record3.status!=="running")}function failedLane(lane,role,startedAt,error93,slotId,runId,sessionId){return{id:lane.id,agent:lane.agent,role,status:"failed",session_id:sessionId,slot_id:slotId,run_id:runId,started_at:startedAt,completed_at:isoNow2(),error:error93}}function validateLaneAgent(agent,context){let generatedAgentNames=_internals140.getGeneratedAgentNames(),role=resolveGeneratedAgentRole(agent,generatedAgentNames);if(!isKnownCanonicalRole(role))return{ok:!1,role,error:`Agent "${agent}" is not registered as a generated swarm agent or canonical role`};if(!READ_ONLY_LANE_ROLES.has(role))return{ok:!1,role,error:`Agent role "${role}" is not allowed for read-only lane dispatch`};let callerPrefix=context.callerAgent?getGeneratedAgentPrefix(context.callerAgent,generatedAgentNames):null;if(callerPrefix){if(getGeneratedAgentPrefix(agent,generatedAgentNames)!==callerPrefix)return{ok:!1,role,error:`Agent "${agent}" does not match caller swarm prefix "${callerPrefix}"`}}return{ok:!0,role}}function getGeneratedAgentPrefix(agent,generatedAgentNames){let role=resolveGeneratedAgentRole(agent,generatedAgentNames);if(!isKnownCanonicalRole(role))return null;let normalized=agent.toLowerCase();if(normalized===role)return null;for(let separator of AGENT_NAME_SEPARATORS){let suffix=`${separator}${role}`;if(normalized.endsWith(suffix))return normalized.slice(0,-suffix.length)}return null}function buildReadOnlyTools(){let tools={};for(let toolName of READ_ONLY_TOOL_DENYLIST)tools[toolName]=!1;return tools.write=!1,tools.edit=!1,tools.patch=!1,tools}function prepareLaneOutput(args2){let stored=storeLaneOutput(args2.directory,{batchId:args2.batchId,laneId:args2.laneId,agent:args2.agent,role:args2.role,sessionId:args2.sessionId,parentSessionId:args2.parentSessionId,mode:args2.mode,workflowLane:args2.workflowLane,prHeadSha:args2.prHeadSha,gitHead:args2.gitHead,revisionDigest:args2.revisionDigest,scope:args2.scope,source:args2.source,text:args2.text,messageCount:args2.messageCount,transcriptIncomplete:args2.transcriptIncomplete}),preview=buildLaneOutputPreview({text:args2.text,ref:stored.ref,degraded:stored.degraded,maxChars:MAX_LANE_OUTPUT_CHARS});return{...preview,output_ref:stored.ref,output_digest:stored.digest,output_preview_chars:preview.output.length,...stored.degraded?{output_degraded:!0}:{},...stored.error?{output_artifact_error:stored.error}:{},...args2.transcriptIncomplete!==void 0?{transcript_incomplete:args2.transcriptIncomplete}:{},...args2.messageCount!==void 0?{message_count:args2.messageCount}:{}}}function failureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,dispatched:0,completed:0,failed:0,rejected:0,max_concurrent:0,timeout_ms:0,lane_results:[],errors:args2.errors}}function asyncFailureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,batch_id:null,dispatched:0,pending:0,failed:0,rejected:0,max_concurrent:0,launch_timeout_ms:0,timeout_ms:0,lane_results:[],errors:args2.errors}}function collectFailureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,batch_id:args2.batch_id,total:0,completed:0,failed:0,cancelled:0,stale:0,pending:0,consumed:0,all_settled:!1,lane_results:[],errors:args2.errors}}function applyCommonPrompt(lanes,commonPrompt){if(!commonPrompt)return{ok:!0,lanes:[...lanes]};let errors5=[],merged=lanes.map((lane)=>{let prompt=`${commonPrompt}${COMMON_PROMPT_SEPARATOR}${lane.prompt}`;if(prompt.length>MAX_PROMPT_CHARS)errors5.push(`Lane "${lane.id}" combined common_prompt + prompt is ${prompt.length} chars (common_prompt ${commonPrompt.length} + separator ${COMMON_PROMPT_SEPARATOR.length} + lane prompt ${lane.prompt.length}; max ${MAX_PROMPT_CHARS})`);return{...lane,prompt}});if(errors5.length>0)return{ok:!1,errors:errors5};return{ok:!0,lanes:merged}}function applyExplorerFormatSuffix(lanes){let generatedAgentNames=_internals140.getGeneratedAgentNames();return lanes.map((lane)=>{if(resolveGeneratedAgentRole(lane.agent,generatedAgentNames)!=="explorer")return lane;if(lane.prompt.includes("[CANDIDATE]"))return lane;let exactLane=lane.workflow_lane??lane.id,ownedLanes=lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:[exactLane],identity=ownedLanes.length===1?`every output row MUST use the exact lane value "${ownedLanes[0]}"`:`this consolidated lane covers ${ownedLanes.length} obligations — evaluate EVERY one and emit a distinct [CANDIDATE] row set or fully populated [CLEAN] attestation for EACH of: ${ownedLanes.map((owned)=>`"${owned}"`).join(", ")}; every output row MUST use the exact lane value of the obligation it reports`,prompt=`${lane.prompt}
6100
6102
 
@@ -6230,9 +6232,9 @@ ${page.content}`;if(page.endLine<page.totalLines){let remaining=page.totalLines-
6230
6232
  ${paginatedContent}`;if(endLine<totalLines){let remaining=totalLines-endLine;response+=`
6231
6233
 
6232
6234
  ... ${remaining} more line${remaining===1?"":"s"}. Use offset=${endLine} to retrieve more.`}return response}});init_zod();init_workspace_snapshot();init_pr_workflow_gate();init_external_tool_runner();init_create_tool();import*as fs150 from"node:fs";import*as path248 from"node:path";var STAGE_A_CATEGORIES=["build","typecheck","lint","diff-check","reproduction"],OPTIONAL_STAGE_A_CATEGORIES=["build","typecheck","lint"],ALWAYS_REQUIRED_CATEGORIES=["diff-check","reproduction"],MAX_OUTPUT_BYTES9=65536,BLOCKED_EXECUTABLES=new Set(["aws","az","bash","cmd","curl","docker","echo","env","false","ftp","gcloud","gh","git","kubectl","podman","powershell","printf","pwsh","rsync","scp","sh","sleep","ssh","test","true","wget","zsh"]),MUTATING_ARGUMENT=/(?:^|[-_:])(publish|deploy|push|upload|login|logout|release|promote|destroy|delete|remove|prune)(?:$|[-_:])/i,StageACheckSchema=exports_external.object({category:exports_external.enum(STAGE_A_CATEGORIES),command:exports_external.array(exports_external.string().min(1).max(2000)).min(1).max(64).describe("Array-form executable and arguments; no shell string"),targets:exports_external.array(exports_external.string().trim().min(1).max(500)).min(1).max(32).optional().describe("Required for reproduction: exact test path, test name, package, or regression selector present in the command"),feedback_targets:exports_external.array(exports_external.object({feedback_item_id:exports_external.string().trim().min(1).max(120),target:exports_external.string().trim().min(1).max(500),expected_behavior:exports_external.string().trim().min(8).max(1000)}).strict()).min(1).max(128).optional().describe("Required for reproduction: one exact mapping from every immutable feedback item to an executed target and expected post-fix behavior"),working_directory:exports_external.string().trim().min(1).max(500).optional().describe("Repository-relative workspace directory for this concrete validation obligation; defaults to the repository root"),obligation_id:exports_external.string().trim().min(1).max(1000).optional().describe("Exact controller-discovered workspace/category/source obligation id; required when a category has more than one applicable obligation in a workspace"),validator_contract:exports_external.object({path:exports_external.string().trim().min(1).max(500),id:exports_external.string().trim().min(1).max(120)}).strict().optional().describe("Optional exact validator entry from a bounded repository-owned .pr-validation.json contract"),timeout_ms:exports_external.number().int().min(1000).max(600000).optional()}).strict(),RunPrFeedbackStageAArgsSchema=exports_external.object({pr_head_sha:exports_external.string().trim().min(1).max(80),base_ref:exports_external.string().trim().min(1).max(256).optional(),base_sha:exports_external.string().trim().min(6).max(80).optional(),checks:exports_external.array(StageACheckSchema).min(2).max(258)}).strict(),RepositoryValidationContractSchema=exports_external.object({version:exports_external.literal(1),validators:exports_external.array(exports_external.object({id:exports_external.string().trim().min(1).max(120),category:exports_external.enum(OPTIONAL_STAGE_A_CATEGORIES),working_directory:exports_external.string().trim().min(1).max(500).default("."),command:exports_external.array(exports_external.string().min(1).max(2000)).min(1).max(64)}).strict()).min(1).max(256)}).strict().superRefine((value,context)=>{let seen=new Set;for(let[index,validator]of value.validators.entries()){if(seen.has(validator.id))context.addIssue({code:exports_external.ZodIssueCode.custom,path:["validators",index,"id"],message:`duplicate validator id ${validator.id}`});seen.add(validator.id)}});function failure2(message,checks5=[]){return JSON.stringify({success:!1,message,checks:checks5},null,2)}function isExactDiffCheck(command){let executable=path248.basename(command[0]).toLowerCase();return(executable==="git"||executable==="git.exe")&&command.length===3&&command[1]==="diff"&&command[2]==="--check"}function isPlausibleBuildCommand(executable,args2){let cleanOnlyPositionals=(optionsWithValue)=>{let positionals=[];for(let index=0;index<args2.length;index+=1){let arg=args2[index];if(optionsWithValue.has(arg)){index+=1;continue}if(arg.startsWith("-")||arg.startsWith("/"))continue;positionals.push(arg.toLowerCase())}return positionals.length>0&&positionals.every((arg)=>arg==="clean")};switch(executable){case"make":return!cleanOnlyPositionals(new Set(["-C","--directory","-f","--file","-I","--include-dir"]))&&!args2.some((arg)=>/^(?:-n|--just-print|--dry-run|--recon|-q|--question|-t|--touch|-p|--print-data-base)$/i.test(arg));case"ninja":return!cleanOnlyPositionals(new Set(["-C","-f","-j","-k","-l","-d"]))&&!args2.some((arg)=>/^(?:-n|--dry-run|-t|--tool)$/i.test(arg));case"cmake":if(!args2.includes("--build"))return!1;{let targetIndex=args2.indexOf("--target");if(targetIndex>=0){let declaredTargets=[];for(let index=targetIndex+1;index<args2.length;index+=1){if(args2[index].startsWith("-"))break;declaredTargets.push(args2[index].toLowerCase())}if(declaredTargets.length>0&&declaredTargets.every((target)=>target==="clean"))return!1}}return!0;case"msbuild":{let targetArgs=args2.map((arg)=>arg.match(/^(?:-|\/)(?:t|target):(.+)$/i)?.[1]).filter((value)=>Boolean(value));if(targetArgs.length>0&&targetArgs.flatMap((value)=>value.split(/[;,]/)).every((target)=>target.trim().toLowerCase()==="clean"))return!1;return args2.some((arg)=>/\.(?:sln|slnx|proj|csproj|fsproj|vbproj)$/i.test(arg)||/^(?:-|\/)(?:t|target):/i.test(arg))&&!args2.some((arg)=>/^(?:-|\/)(?:preprocess|pp|version|ver)(?::|$)/i.test(arg))}case"cargo":return args2[0]==="build";case"go":return args2[0]==="build"&&!args2.some((arg)=>/^-n(?:=.*)?$/i.test(arg));case"dotnet":case"swift":case"stack":case"cabal":case"bazel":case"buck":return args2[0]==="build";case"mix":return args2[0]==="compile";case"mvn":case"mvnw":return args2.some((arg)=>/^(?:compile|package|verify|install|pre-integration-test|integration-test|post-integration-test)$/i.test(arg));case"gradle":case"gradlew":return!args2.some((arg)=>/^(?:-m|--dry-run)(?:=.*)?$/i.test(arg))&&args2.some((arg)=>/(?:^|:)(?:build|assemble|classes|jar|war|compile[A-Za-z0-9_-]*)(?:$|:)/i.test(arg));case"ant":return!cleanOnlyPositionals(new Set(["-f","-file","-buildfile","-lib"]))&&(args2.length===0||args2.some((arg)=>!arg.startsWith("-")&&!arg.startsWith("/")));case"swiftc":return args2.some((arg)=>/\.swift$/i.test(arg));case"rustc":return args2.some((arg)=>/\.rs$/i.test(arg));case"xcodebuild":return args2.some((arg)=>arg.toLowerCase()==="build")&&!args2.some((arg)=>/^-(?:list|showBuildSettings|showdestinations|showsdks|version|help)$/i.test(arg));default:if(["python","python3"].includes(executable)&&(args2[0]==="-m"&&args2[1]==="build"||args2[0]==="setup.py"&&args2.includes("build")))return!0;return["vite","webpack","rollup","parcel","esbuild","tsup"].includes(executable)&&args2.some((arg)=>arg.toLowerCase()==="build")}}function categoryMatchesScriptName(category,scriptName){switch(category){case"build":return/(?:^|[:_-])(?:build|compile|package|assemble)(?:$|[:_-])/i.test(scriptName);case"typecheck":return/(?:type[:_-]*check|check[:_-]*types|types?)(?:$|[:_-])/i.test(scriptName);case"lint":return/(?:^|[:_-])(?:lint|format[:_-]*check|check[:_-]*format)(?:$|[:_-])/i.test(scriptName);case"reproduction":return/(?:^|[:_-])(?:test|spec|repro(?:duction)?|regression)(?:$|[:_-])/i.test(scriptName);case"diff-check":return!1}}function isPlausiblePackageManagerCommand(category,executable,args2){if(args2.some((arg)=>/^(?:--(?:cwd|filter|prefix|workspace)(?:=|$)|-[CFw](?:$|=))/.test(arg))||executable==="yarn"&&args2.includes("workspace"))return!1;let optionTakesValue=new Set(["--cwd","--filter","--prefix","--workspace","-C","-F","-w"]),commandTokens=[];for(let index=0;index<args2.length;index+=1){let arg=args2[index];if(optionTakesValue.has(arg)){index+=1;continue}if(arg.startsWith("-"))continue;commandTokens.push({index,value:arg.toLowerCase()})}if(commandTokens.length===0)return!1;let firstArgIndex=commandTokens[0].index,first=commandTokens[0].value;if(executable==="npm"){let runToken=commandTokens.find(({value})=>["run","run-script"].includes(value));if(!runToken)return!1;let script=commandTokens.find(({index})=>index>runToken.index)?.value;return Boolean(script&&categoryMatchesScriptName(category,script))}if(executable==="bun"){if(category==="build"&&first==="build")return!0;if(category==="reproduction"&&first==="test")return!0;if(first!=="run")return!1;let script=args2.slice(firstArgIndex+1).find((arg)=>!arg.startsWith("-"));return Boolean(script&&categoryMatchesScriptName(category,script))}if(executable==="pnpm"||executable==="yarn"){let script;if(executable==="yarn"&&first==="workspace"){let runToken=commandTokens.find(({value},index)=>index>=2&&value==="run");script=runToken?commandTokens.find(({index})=>index>runToken.index)?.value:commandTokens[2]?.value}else{let runToken=commandTokens.find(({value})=>value==="run");script=runToken?commandTokens.find(({index})=>index>runToken.index)?.value:commandTokens[0]?.value}return Boolean(script&&categoryMatchesScriptName(category,script))}if(executable==="npx"){let invokedArgs=args2.slice(firstArgIndex),invokedExecutable=path248.basename(invokedArgs[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,""),invokedToolArgs=invokedArgs.slice(1);switch(category){case"build":return["vite","webpack","rollup","parcel","esbuild"].includes(invokedExecutable)&&invokedToolArgs.some((arg)=>arg.toLowerCase()==="build");case"typecheck":return isPlausibleTypecheckCommand(invokedExecutable,invokedToolArgs,invokedExecutable);case"lint":return isPlausibleLintCommand(invokedExecutable,invokedToolArgs,invokedExecutable);case"reproduction":return isPlausibleReproductionCommand(invokedExecutable,invokedToolArgs,invokedExecutable,invokedArgs[0]);case"diff-check":return!1}}return!1}function isPlausibleLintCommand(executable,args2,_directCommandName){let hasTarget=(from=0)=>args2.slice(from).some((arg)=>!arg.startsWith("-")&&!arg.startsWith("/"));switch(executable){case"eslint":case"shellcheck":case"pylint":case"flake8":case"stylelint":case"hadolint":case"ktlint":case"checkstyle":case"cppcheck":return hasTarget();case"biome":return["check","lint"].includes(args2[0]?.toLowerCase())&&hasTarget(1);case"ruff":return args2[0]?.toLowerCase()==="check"&&hasTarget(1);case"golangci-lint":return args2[0]?.toLowerCase()==="run";case"swiftlint":return args2.length===0||args2[0]?.toLowerCase()==="lint";case"rubocop":return!args2.some((arg)=>/^--show-cops(?:=.*)?$/i.test(arg));case"cargo":return args2[0]==="clippy";case"dotnet":return args2[0]==="format"&&args2.includes("--verify-no-changes");default:return!1}}function outputReportsZeroTests(result){if(result.stdoutTruncated||result.stderrTruncated)return!0;let output=`${result.stdout}
6233
- ${result.stderr}`;return/(?:\b(?:ran|running|collected)\s+0\s+(?:tests?|items?)\b|\btests? run:\s*0\b|\b0\s+(?:tests?\s+(?:ran|passed)|pass(?:ed)?|passing|examples?)\b|\bno tests? (?:ran|to run|found|were found|executed|is available)\b|\bno test is available\b|\btests? (?:are|were) skipped\b|\btest\b[^\n]*\bskipped\b|\bNO-SOURCE\b|\[no test files\])/i.test(output)}function reproductionSelectorValues(command){let runnerVerbs=new Set(["run","run-script","test","tests","spec","check"]),selectorFlags=new Set(["--test-name-pattern","--testNamePattern","--tests","--filter","--grep","-k","-m","-run"]),selectors=new Set;for(let index=1;index<command.length;index+=1){let arg=command[index];if(selectorFlags.has(arg)){let value=command[index+1];if(value&&!value.startsWith("-"))selectors.add(value);index+=1;continue}let assignment=arg.match(/^(?:--(?:test-name-pattern|testNamePattern|tests|filter|grep)|-run|-Dtest)=(.+)$/);if(assignment?.[1]){selectors.add(assignment[1]);continue}if(arg.startsWith("-")||arg.startsWith("/"))continue;if(runnerVerbs.has(arg.toLowerCase()))continue;selectors.add(arg)}return selectors}function isPlausibleTypecheckCommand(executable,args2,_directCommandName){if(executable==="go")return args2[0]==="vet"&&!args2.some((arg)=>/^-n(?:=.*)?$/i.test(arg));if(executable==="flow")return["check","status","focus-check"].includes(args2[0]?.toLowerCase());if(executable==="phpstan")return["analyse","analyze"].includes(args2[0]?.toLowerCase())&&!args2.some((arg)=>/^--generate-baseline(?:=.*)?$/i.test(arg));return/^(?:tsc|pyright|mypy|sorbet|psalm)$/.test(executable)||executable==="cargo"&&args2[0]==="check"||executable==="dotnet"&&args2[0]==="build"}function isPlausibleReproductionCommand(executable,args2,_directCommandName,_commandPath){if(executable==="python"||executable==="python3")return args2[0]==="-m"&&args2[1]?.toLowerCase()==="pytest";if(executable==="bundle")return args2[0]==="exec"&&args2[1]?.toLowerCase()==="rspec";if(executable==="cargo")return args2[0]==="test"||args2[0]==="nextest"&&args2[1]?.toLowerCase()==="run";if(executable==="go")return args2[0]==="test"&&!args2.some((arg)=>/^(?:-c|-list(?:=.*)?)$/i.test(arg));if(executable==="node")return args2[0]==="--test";if(executable==="deno")return args2[0]==="test";if(executable==="zig")return args2[0]==="test";if(executable==="meson")return args2[0]==="test";if(executable==="make"||executable==="ninja")return args2.some((arg)=>/^(?:test|check|verify|regression)$/i.test(arg));if(executable==="playwright")return args2[0]==="test";if(executable==="dart"||executable==="flutter")return args2[0]==="test";if(executable==="xcodebuild")return args2.some((arg)=>["test","test-without-building"].includes(arg.toLowerCase()))&&!args2.some((arg)=>/^-(?:list|enumerate-tests|showBuildSettings|showdestinations|showTestPlans|showsdks|version|help)$/i.test(arg));if(executable==="cypress")return args2[0]==="run";if(/^(?:pytest|ctest|rspec|phpunit|vitest|jest|mocha|ava|go-test-sum)$/.test(executable))return!0;if(executable==="dotnet")return args2[0]?.toLowerCase()==="test";if(["mvn","mvnw"].includes(executable))return args2.some((arg)=>/^(?:test|verify|integration-test|failsafe:integration-test)$/i.test(arg));if(["gradle","gradlew"].includes(executable)){let invokesExecutableTestTask=args2.some((arg)=>{if(arg.startsWith("-"))return!1;let task=arg.split(":").filter(Boolean).at(-1)??"";if(/^(?:compile|process|generate|assemble|classes|jar|source|kapt|prepare)/i.test(task))return!1;return task.toLowerCase()==="test"||/^test[A-Z0-9_-]/.test(task)&&/Test$/.test(task)||/^[a-z][A-Za-z0-9_-]*Test$/.test(task)});return!args2.some((arg)=>/^(?:-m|--dry-run)(?:=.*)?$/i.test(arg))&&invokesExecutableTestTask}return!1}function isPlausibleStageACommand(category,command){if(category==="diff-check")return isExactDiffCheck(command);let executable=path248.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"");if(BLOCKED_EXECUTABLES.has(executable))return!1;if(command.slice(1).some((arg)=>/^(?:-h|--help|--version|version|help|list|-N|--fixtures(?:-per-test)?|--markers|--trace-config|--cache-show|--list(?:-?(?:tests?|suites|groups))?(?:-xml)?(?:=.*)?|--show-only(?:=.*)?|--print-labels|--listFilesOnly|--noCheck|--no-check|--no-run(?:=.*)?|--test-dry-run(?:=.*)?|--createStub|--createstub|--print-config|--env-info|--show-settings|--show-files|--list-msgs|--generate-rcfile|--show-?config(?:=.*)?|--init|--dry-run(?:=.*)?|--collect-only|--setup-(?:only|plan)|--co|--if-present(?:=.*)?)$/i.test(arg)))return!1;if(command.slice(1).some((arg)=>MUTATING_ARGUMENT.test(arg))||["bun","node","python","python3","ruby","perl","npx"].includes(executable)&&command.slice(1).some((arg)=>["-e","--eval","-c","--call"].includes(arg)))return!1;if(category==="lint"&&command.some((arg)=>/^(?:--fix(?:-only)?|--write|--apply|--auto-?correct)(?:=.*)?$|^-[aAw]$/.test(arg)))return!1;if(category==="reproduction"&&(command.some((arg)=>/^(?:--passWithNoTests|--allow-no-tests|--collect-only|--list|--dry-run|--only|--todo|--update-snapshot|--bless|--accept|-w|-x(?:.+)?|--exclude-task(?:=.+)?)$/i.test(arg))||command.some((arg)=>/^-D(?:skipTests|skipITs|maven\.test\.(?:skip|skip\.exec))(?:=true)?$/i.test(arg))))return!1;if(["npm","pnpm","yarn"].includes(executable)||executable==="bun"&&["build","run","test"].includes(command[1]))return isPlausiblePackageManagerCommand(category,executable,command.slice(1));if(executable==="npx")return isPlausiblePackageManagerCommand(category,executable,command.slice(1));let directCommandName=executable.replace(/\.(?:sh|ps1|py|js|mjs|cjs|rb|pl)$/,"");switch(category){case"build":return isPlausibleBuildCommand(executable,command.slice(1));case"typecheck":return isPlausibleTypecheckCommand(executable,command.slice(1),directCommandName);case"lint":return isPlausibleLintCommand(executable,command.slice(1),directCommandName);case"reproduction":return isPlausibleReproductionCommand(executable,command.slice(1),directCommandName,command[0])}}function readBoundedText(filePath){try{let stat17=fs150.statSync(filePath);if(!stat17.isFile()||stat17.size>524288)return;return fs150.readFileSync(filePath,"utf8")}catch{return}}function readPresentRepositoryText(directory,filePath,label){let stat17;try{stat17=fs150.statSync(filePath)}catch(error93){if(error93.code==="ENOENT")return;throw Error(`BLOCKED: Stage A cannot inspect present ${label}`)}if(!stat17.isFile()||stat17.size>524288)throw Error(`BLOCKED: Stage A cannot inspect present ${label}`);try{let canonicalRoot=fs150.realpathSync(path248.resolve(directory)),canonicalFile=fs150.realpathSync(filePath),relative57=path248.relative(canonicalRoot,canonicalFile);if(relative57===".."||relative57.startsWith(`..${path248.sep}`)||path248.isAbsolute(relative57))throw Error("escaping manifest");return fs150.readFileSync(canonicalFile,"utf8")}catch{throw Error(`BLOCKED: Stage A cannot inspect present ${label}`)}}function resolveContainedDirectory(directory,workingDirectory="."){let root=path248.resolve(directory),canonicalRoot=(()=>{try{return fs150.realpathSync(root)}catch{return root}})(),candidate=path248.resolve(root,workingDirectory);try{if(!fs150.statSync(candidate).isDirectory())return;let absolute=fs150.realpathSync(candidate),relativePath2=path248.relative(canonicalRoot,absolute);if(relativePath2===".."||relativePath2.startsWith(`..${path248.sep}`)||path248.isAbsolute(relativePath2))return;return{absolute,relative:relativePath2.replaceAll("\\","/")||"."}}catch{return}}function readRepositoryValidationContract(directory,contractPath){let root=path248.resolve(directory),canonicalRoot=(()=>{try{return fs150.realpathSync(root)}catch{return root}})(),resolved=path248.resolve(root,contractPath),canonicalContract;try{canonicalContract=fs150.realpathSync(resolved)}catch{return}let relative57=path248.relative(canonicalRoot,canonicalContract);if(!relative57||relative57===".."||relative57.startsWith(`..${path248.sep}`)||path248.isAbsolute(relative57)||path248.basename(canonicalContract)!==".pr-validation.json")return;let text=readBoundedText(canonicalContract);if(!text)return;try{return RepositoryValidationContractSchema.parse(JSON.parse(text))}catch{return}}function resolveContractBaseProvenance(directory,prHeadSha,baseRef,baseSha){if(!baseRef&&!baseSha)return;if(!baseRef||!baseSha)throw Error("BLOCKED: Stage A contract authorization requires both base_ref and base_sha");let resolvedBase=_internals164.resolveExactMergeBase(directory,baseRef,prHeadSha);if(!resolvedBase||resolvedBase.toLowerCase()!==baseSha.toLowerCase()||resolvedBase.toLowerCase()===prHeadSha.toLowerCase())throw Error("Stage A contract authorization requires base_sha to be the immutable merge base of base_ref and pr_head_sha");return{baseRef,baseSha:resolvedBase.toLowerCase()}}function readTrustedRepositoryValidationContract(directory,contractPath,provenance){if(!provenance)return;let current=readRepositoryValidationContract(directory,contractPath),currentText=readBoundedText(path248.resolve(directory,contractPath)),baseText=_internals164.readGitTextAtRevision(directory,provenance.baseSha,contractPath.replaceAll("\\","/").replace(/^\.\//,""));if(!current||!currentText||baseText===null||currentText!==baseText)return;return current}function isExactRepositoryContractValidator(directory,check3,provenance){if(!check3.validator_contract)return!1;let validator=readTrustedRepositoryValidationContract(directory,check3.validator_contract.path,provenance)?.validators.find((candidate)=>candidate.id===check3.validator_contract?.id);if(!validator||validator.category!==check3.category)return!1;let requestedDirectory=resolveContainedDirectory(directory,check3.working_directory??"."),declaredDirectory=resolveContainedDirectory(directory,validator.working_directory);return Boolean(requestedDirectory&&declaredDirectory)&&requestedDirectory?.absolute===declaredDirectory?.absolute&&validator.command.length===check3.command.length&&validator.command.every((part,index)=>part===check3.command[index])}function isExactObligationContractAuthorization(directory,obligation,check3,provenance){let identity=obligation.validatorContract;if(!identity||check3.validator_contract?.path!==identity.path||check3.validator_contract.id!==identity.id)return!1;let validator=readTrustedRepositoryValidationContract(directory,identity.path,provenance)?.validators.find(({id})=>id===identity.id),workspace=resolveContainedDirectory(directory,obligation.workingDirectory),validatorWorkspace=validator?resolveContainedDirectory(directory,validator.working_directory):void 0;if(!validator||validator.category!==obligation.category||validatorWorkspace?.absolute!==workspace?.absolute)return!1;if(!obligation.source.startsWith("package.json#")||!workspace)return!1;let scriptName=obligation.source.slice(13),packageText=readBoundedText(path248.join(workspace.absolute,"package.json"));if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared&&declared.length===validator.command.length&&declared.every((part,index)=>part===validator.command[index])&&(packageManagerSelectsExactScript(check3.command,scriptName)||declared.length===check3.command.length&&declared.every((part,index)=>part===check3.command[index])))}catch{return!1}}function isSafeContractCommand(command){let executable=path248.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"");return!BLOCKED_EXECUTABLES.has(executable)&&!command.slice(1).some((arg)=>MUTATING_ARGUMENT.test(arg))&&!command.some((arg)=>/^(?:-h|--help|--version|help|version|--dry-run|--if-present)$/i.test(arg))&&!(["bun","node","python","python3","ruby","perl","npx"].includes(executable)&&command.slice(1).some((arg)=>["-e","--eval","-c","--call"].includes(arg)))}function isAllowedRepositoryExecutable(directory,workingDirectory,executable,contractValidated){if(!/[\\/]/.test(executable))return!0;if(path248.isAbsolute(executable))return!1;let workspace=resolveContainedDirectory(directory,workingDirectory);if(!workspace)return!1;let resolved=path248.resolve(workspace.absolute,executable),canonicalExecutable;try{canonicalExecutable=fs150.realpathSync(resolved)}catch{return!1}let canonicalRoot=(()=>{try{return fs150.realpathSync(path248.resolve(directory))}catch{return path248.resolve(directory)}})(),relative57=path248.relative(canonicalRoot,canonicalExecutable);if(relative57===".."||relative57.startsWith(`..${path248.sep}`)||path248.isAbsolute(relative57))return!1;let basename32=path248.basename(canonicalExecutable).toLowerCase().replace(/\.(?:cmd|bat|exe)$/,"");if(!contractValidated&&!["gradlew","mvnw"].includes(basename32))return!1;return fs150.statSync(canonicalExecutable).isFile()}function normalizedExecutable(command){return path248.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"")}function parseSimpleRepositoryScript(script){if(/[;&|><`\r\n]/.test(script)||script.includes("$(")||script.includes("${"))return;let tokens=script.match(/"(?:\\.|[^"\\])*"|'[^']*'|[^\s]+/g)?.map((token)=>{if(token.startsWith('"')&&token.endsWith('"')||token.startsWith("'")&&token.endsWith("'"))return token.slice(1,-1);return token})??[];return tokens.length>0?tokens:void 0}function packageManagerSelectedScriptName(command){let executable=normalizedExecutable(command);if(!["npm","bun","pnpm","yarn"].includes(executable))return;let positional=command.slice(1,command.indexOf("--")>=0?command.indexOf("--"):void 0).filter((arg)=>!arg.startsWith("-"));if(executable==="npm")return["run","run-script"].includes(positional[0]??"")?positional[1]:void 0;if(executable==="bun")return positional[0]==="run"?positional[1]:void 0;return positional[0]==="run"?positional[1]:positional[0]}function packageManagerSelectsExactScript(command,scriptName){return packageManagerSelectedScriptName(command)===scriptName}function isExactRepositoryPackageManagerScript(directory,workingDirectory,category,command){let scriptName=packageManagerSelectedScriptName(command),workspace=resolveContainedDirectory(directory,workingDirectory);if(!scriptName||!workspace||!categoryMatchesScriptName(category,scriptName))return!1;let packageText=readBoundedText(path248.join(workspace.absolute,"package.json"));if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared&&isPlausibleStageACommand(category,declared))}catch{return!1}}function commandMatchesObligationSource(directory,obligation,check3,contractValidated){let executable=normalizedExecutable(check3.command),effectiveExecutable=executable==="npx"&&check3.command[1]?path248.basename(check3.command[1]).toLowerCase():executable,source=obligation.source;if(source.includes(".pr-validation.json#")){let separator=source.lastIndexOf("#"),contractPath=source.slice(0,separator),validatorId=source.slice(separator+1);return contractValidated&&check3.validator_contract?.id===validatorId&&check3.validator_contract?.path.replaceAll("\\","/").replace(/^\.\//,"")===contractPath.replace(/^\.\//,"")}if(source.startsWith("package.json#")){let scriptName=source.slice(13),workspace=resolveContainedDirectory(directory,obligation.workingDirectory),packageText=workspace?readBoundedText(path248.join(workspace.absolute,"package.json")):void 0;if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared)&&declared?.length===check3.command.length&&declared.every((part,index)=>part===check3.command[index])||packageManagerSelectsExactScript(check3.command,scriptName)}catch{return!1}}if(source==="Cargo.toml")return effectiveExecutable==="cargo";if(source==="go.mod")return effectiveExecutable==="go";if(source==="pom.xml")return["mvn","mvnw"].includes(effectiveExecutable);if(/^build\.gradle(?:\.kts)?$/.test(source))return["gradle","gradlew"].includes(effectiveExecutable);if(/^(?:Makefile|makefile)$/.test(source))return effectiveExecutable==="make";if(source==="CMakeLists.txt")return effectiveExecutable==="cmake";if(source==="Package.swift")return["swift","swiftc"].includes(effectiveExecutable);if(source==="setup.py"||source==="pyproject.toml#build-system")return["python","python3"].includes(effectiveExecutable);if(/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(source))return["dotnet","msbuild"].includes(effectiveExecutable);if(/\.(?:xcodeproj|xcworkspace)$/i.test(source))return effectiveExecutable==="xcodebuild";let sourceExecutables={"tsconfig.json":["tsc"],"pyrightconfig.json":["pyright"],".flowconfig":["flow"],"phpstan.neon":["phpstan"],"phpstan.neon.dist":["phpstan"],"psalm.xml":["psalm"],"psalm.xml.dist":["psalm"],"mypy.ini":["mypy"],"pyproject.toml#mypy":["mypy"],"biome.json":["biome"],"biome.jsonc":["biome"],"ruff.toml":["ruff"],".ruff.toml":["ruff"],"pyproject.toml#ruff":["ruff"],".rubocop.yml":["rubocop"],".swiftlint.yml":["swiftlint"],".golangci.yml":["golangci-lint"],".golangci.yaml":["golangci-lint"],".stylelintrc":["stylelint"],".stylelintrc.json":["stylelint"]};if(/^(?:\.eslintrc|eslint\.config\.)/.test(source))return effectiveExecutable==="eslint";return sourceExecutables[source]?.includes(effectiveExecutable)??!1}function discoverApplicableStageAObligations(directory,contractBase){let root=path248.resolve(directory),canonicalRoot=(()=>{try{return fs150.realpathSync(root)}catch{return root}})(),candidateRoots=[],seenRoots=new Set,discoveryOverflow,addCandidateRoot=(candidate)=>{if(candidateRoots.length>=256){discoveryOverflow="Stage A repository discovery exceeded 256 contained workspace roots";return}try{if(!fs150.statSync(candidate).isDirectory())return;let canonicalCandidate=fs150.realpathSync(candidate),relative57=path248.relative(canonicalRoot,canonicalCandidate);if(relative57.startsWith(`..${path248.sep}`)||relative57===".."||path248.isAbsolute(relative57)||seenRoots.has(canonicalCandidate))return;seenRoots.add(canonicalCandidate),candidateRoots.push(canonicalCandidate)}catch{}},addWorkspacePattern=(pattern)=>{let normalized=pattern.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!normalized||normalized.startsWith("!")||path248.posix.isAbsolute(normalized)||normalized.split("/").includes("..")){discoveryOverflow=`Stage A cannot safely expand declared workspace pattern "${pattern}"`;return}if(!normalized.includes("*")){addCandidateRoot(path248.resolve(root,normalized));return}let wildcard=normalized.match(/^([^*?[\]]+)\/\*\/?$/);if(!wildcard){discoveryOverflow=`Stage A cannot safely expand declared workspace pattern "${pattern}"`;return}let container=path248.resolve(root,wildcard[1]);try{let entries=fs150.readdirSync(container,{withFileTypes:!0});if(entries.length>256){discoveryOverflow=`Stage A workspace container ${wildcard[1]} exceeds the 256-entry bounded discovery limit`;return}for(let entry of entries)if(entry.isDirectory())addCandidateRoot(path248.join(container,entry.name))}catch{}};addCandidateRoot(root);for(let containerName of["packages","apps","services","libs","crates"])addWorkspacePattern(`${containerName}/*`);let rootPackageText=readPresentRepositoryText(canonicalRoot,path248.join(root,"package.json"),"root package.json workspace declaration");if(rootPackageText)try{let value=JSON.parse(rootPackageText),workspacePatterns=Array.isArray(value.workspaces)?value.workspaces:value.workspaces?.packages;for(let pattern of workspacePatterns??[])if(typeof pattern==="string")addWorkspacePattern(pattern)}catch{discoveryOverflow="Stage A cannot safely inspect malformed root package.json workspace metadata"}let pnpmWorkspaceText=readPresentRepositoryText(canonicalRoot,path248.join(root,"pnpm-workspace.yaml"),"pnpm-workspace.yaml declaration");for(let match of pnpmWorkspaceText?.matchAll(/^\s*-\s*['"]?([^'"#\r\n]+?)['"]?\s*$/gm)??[])addWorkspacePattern(match[1]);let cargoMembers=readPresentRepositoryText(canonicalRoot,path248.join(root,"Cargo.toml"),"Cargo.toml workspace declaration")?.match(/\bmembers\s*=\s*\[([\s\S]*?)\]/m)?.[1];for(let match of cargoMembers?.matchAll(/['"]([^'"]+)['"]/g)??[])addWorkspacePattern(match[1]);let mavenText=readPresentRepositoryText(canonicalRoot,path248.join(root,"pom.xml"),"pom.xml module declaration");for(let match of mavenText?.matchAll(/<module>\s*([^<]+?)\s*<\/module>/gi)??[])addWorkspacePattern(match[1]);let goWorkText=readPresentRepositoryText(canonicalRoot,path248.join(root,"go.work"),"go.work workspace declaration");for(let match of goWorkText?.matchAll(/^\s*(?:use\s+)?(\.\.?\/[^\s/]+(?:\/[^\s]+)*)\s*$/gm)??[])addWorkspacePattern(match[1]);for(let settingsName of["settings.gradle","settings.gradle.kts"]){let settingsText=readPresentRepositoryText(canonicalRoot,path248.join(root,settingsName),`${settingsName} workspace declaration`);for(let includeMatch of settingsText?.matchAll(/\binclude\s*\(?([^\r\n)]+)/g)??[])for(let projectMatch of includeMatch[1].matchAll(/['"]:?(.*?)['"]/g)){let projectPath=projectMatch[1].replaceAll(":","/");if(projectPath)addWorkspacePattern(projectPath)}}let obligations=new Map,addObligation=(category,candidateRoot,source,validatorContract)=>{let workspace=path248.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||".",id=`${category}:${workspace}:${source}`;if(!obligations.has(id)&&obligations.size>=256){discoveryOverflow="Stage A repository discovery exceeded 256 concrete validation obligations";return}obligations.set(id,{id,category,workingDirectory:workspace,source,...validatorContract?{validatorContract}:{}})},buildFiles=new Set(["Cargo.toml","go.mod","pom.xml","build.gradle","build.gradle.kts","Makefile","makefile","CMakeLists.txt","Package.swift","setup.py"]),typecheckFiles=new Set(["tsconfig.json","pyrightconfig.json",".flowconfig","phpstan.neon","phpstan.neon.dist","psalm.xml","psalm.xml.dist","mypy.ini"]),lintFiles=new Set(["biome.json","biome.jsonc",".eslintrc",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml",".eslintrc.js",".eslintrc.cjs",".eslintrc.mjs","eslint.config.js","eslint.config.mjs","eslint.config.cjs","eslint.config.ts","ruff.toml",".ruff.toml",".rubocop.yml",".swiftlint.yml",".golangci.yml",".golangci.yaml",".stylelintrc",".stylelintrc.json"]);for(let candidateRoot of candidateRoots){let entries=[];try{if(entries=fs150.readdirSync(candidateRoot,{withFileTypes:!0}),entries.length>2048){discoveryOverflow=`Stage A workspace ${path248.relative(canonicalRoot,candidateRoot)||"."} exceeds the 2048-entry bounded manifest scan`;continue}}catch{continue}for(let entry of entries){if(entry.isFile()&&buildFiles.has(entry.name))addObligation("build",candidateRoot,entry.name);if(entry.isFile()&&typecheckFiles.has(entry.name))addObligation("typecheck",candidateRoot,entry.name);if(entry.isFile()&&lintFiles.has(entry.name))addObligation("lint",candidateRoot,entry.name);if(entry.isFile()&&/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(entry.name))addObligation("build",candidateRoot,entry.name);if(entry.isDirectory()&&/\.(?:xcodeproj|xcworkspace)$/i.test(entry.name))addObligation("build",candidateRoot,entry.name)}let contractPath=path248.join(candidateRoot,".pr-validation.json"),contractRelative=path248.relative(canonicalRoot,contractPath).replaceAll("\\","/"),untrustedContract=readRepositoryValidationContract(canonicalRoot,contractRelative),contract=readTrustedRepositoryValidationContract(canonicalRoot,contractRelative,contractBase);if(fs150.existsSync(contractPath)&&!untrustedContract)discoveryOverflow=`Stage A found an invalid, oversized, unreadable, or escaping validation contract at ${contractRelative}`;else if(untrustedContract&&!contract)discoveryOverflow=`Stage A validation contract at ${contractRelative} must be unchanged from the immutable merge base named by base_ref and base_sha`;let contractValidatorsCoveredByScripts=new Set,packageText=readPresentRepositoryText(canonicalRoot,path248.join(candidateRoot,"package.json"),`${path248.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json manifest`);if(packageText)try{let value=JSON.parse(packageText);for(let[script,commandText]of Object.entries(value.scripts??{})){let declaredCommand=typeof commandText==="string"?parseSimpleRepositoryScript(commandText):void 0;for(let category of OPTIONAL_STAGE_A_CATEGORIES){if(!categoryMatchesScriptName(category,script))continue;let authorizingValidator=contract?.validators.find((validator)=>{let validatorWorkspace=resolveContainedDirectory(canonicalRoot,validator.working_directory);return validator.category===category&&validatorWorkspace?.absolute===candidateRoot&&(!declaredCommand||declaredCommand.length===validator.command.length&&declaredCommand.every((part,index)=>part===validator.command[index]))});if(!declaredCommand){if(!authorizingValidator)discoveryOverflow=`Stage A opaque package script ${path248.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json#${script} requires a trusted base-identical contract validator for ${category}`;continue}if(isPlausibleStageACommand(category,declaredCommand)||Boolean(authorizingValidator)){if(addObligation(category,candidateRoot,`package.json#${script}`,authorizingValidator?{path:contractRelative,id:authorizingValidator.id}:void 0),authorizingValidator)contractValidatorsCoveredByScripts.add(authorizingValidator.id)}}}}catch{discoveryOverflow=`Stage A cannot safely inspect malformed package manifest at ${path248.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json`}let pyprojectText=readPresentRepositoryText(canonicalRoot,path248.join(candidateRoot,"pyproject.toml"),`${path248.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/pyproject.toml manifest`);if(pyprojectText?.match(/\[build-system\]/i))addObligation("build",candidateRoot,"pyproject.toml#build-system");if(pyprojectText?.match(/\[(?:tool\.)?mypy\]/i))addObligation("typecheck",candidateRoot,"pyproject.toml#mypy");if(pyprojectText?.match(/\[tool\.ruff(?:\.|\])/i))addObligation("lint",candidateRoot,"pyproject.toml#ruff");for(let validator of contract?.validators??[]){if(contractValidatorsCoveredByScripts.has(validator.id))continue;if(OPTIONAL_STAGE_A_CATEGORIES.includes(validator.category)){let validatorWorkspace=resolveContainedDirectory(canonicalRoot,validator.working_directory);if(!validatorWorkspace)continue;addObligation(validator.category,validatorWorkspace.absolute,`${contractRelative}#${validator.id}`)}}}if(discoveryOverflow)throw Error(`BLOCKED: ${discoveryOverflow}`);return[...obligations.values()]}function discoverApplicableStageACategories(directory,contractBase){let applicable=new Set(discoverApplicableStageAObligations(directory,contractBase).map(({category})=>category));return OPTIONAL_STAGE_A_CATEGORIES.filter((category)=>applicable.has(category))}async function executeRunPrFeedbackStageA(args2,directory,context={}){let parsed=RunPrFeedbackStageAArgsSchema.safeParse(args2);if(!parsed.success)return failure2(`Invalid PR-feedback Stage A request: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);if(!context.sessionID?.trim())return failure2("PR-feedback Stage A requires an active sessionID");let categories=parsed.data.checks.map((check3)=>check3.category);for(let requiredSingleton of ALWAYS_REQUIRED_CATEGORIES)if(categories.filter((category)=>category===requiredSingleton).length!==1)return failure2(`Stage A requires exactly one ${requiredSingleton} receipt`);let contractBase;try{contractBase=resolveContractBaseProvenance(directory,parsed.data.pr_head_sha,parsed.data.base_ref,parsed.data.base_sha)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}let applicableObligations;try{applicableObligations=_internals164.discoverApplicableStageAObligations(directory,contractBase)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}let applicableCategories=OPTIONAL_STAGE_A_CATEGORIES.filter((category)=>applicableObligations.some((obligation)=>obligation.category===category)),matchedObligationIds=new Set,selectedObligations=new Map,normalizedCheckDirectories=new Map;for(let check3 of parsed.data.checks){let workspace=resolveContainedDirectory(directory,check3.working_directory??".");if(!workspace)return failure2(`Stage A ${check3.category} working_directory is not a contained repository workspace`);if(normalizedCheckDirectories.set(check3,workspace.relative),!OPTIONAL_STAGE_A_CATEGORIES.includes(check3.category))continue;let candidates=applicableObligations.filter((obligation)=>obligation.category===check3.category&&obligation.workingDirectory===workspace.relative);if(candidates.length===0&&!check3.obligation_id)continue;let selected=check3.obligation_id?candidates.find((candidate)=>candidate.id===check3.obligation_id):candidates.length===1?candidates[0]:void 0;if(!selected)return failure2(`Stage A ${check3.category} must name one exact discovered obligation_id for workspace ${workspace.relative}: ${candidates.map(({id})=>id).join(", ")||"none discovered"}`);if(matchedObligationIds.has(selected.id))return failure2(`Stage A repeats discovered obligation ${selected.id}`);matchedObligationIds.add(selected.id),selectedObligations.set(check3,selected),check3.obligation_id=selected.id,check3.working_directory=workspace.relative}let missingObligations=applicableObligations.filter(({id})=>!matchedObligationIds.has(id));if(missingObligations.length>0)return failure2(`Stage A is missing concrete repository validation obligations: ${missingObligations.map(({id})=>id).join(", ")}`);let diffCheck=parsed.data.checks.find((check3)=>check3.category==="diff-check");if(!diffCheck||!isExactDiffCheck(diffCheck.command))return failure2('Stage A diff-check must execute array-form ["git", "diff", "--check"]');for(let check3 of parsed.data.checks){let directContractValidated=isExactRepositoryContractValidator(directory,check3,contractBase),selectedObligation=selectedObligations.get(check3),obligationContractValidated=selectedObligation?isExactObligationContractAuthorization(directory,selectedObligation,check3,contractBase):!1,contractValidated=directContractValidated||obligationContractValidated;if(selectedObligation?.validatorContract&&!obligationContractValidated)return failure2(`Stage A obligation ${selectedObligation.id} requires exact validator_contract ${selectedObligation.validatorContract.path}#${selectedObligation.validatorContract.id}`);let executable=normalizedExecutable(check3.command);if(selectedObligation&&!commandMatchesObligationSource(directory,selectedObligation,check3,contractValidated))return failure2(`Stage A command does not prove its exact source obligation ${selectedObligation.id}`);if(!isPlausibleStageACommand(check3.category,check3.command)&&!(contractValidated&&isSafeContractCommand(check3.command)))return failure2(`Stage A ${check3.category} command is not a recognized non-publishing ${check3.category} validation command`);let isPackageManagerCommand=["npm","pnpm","yarn"].includes(executable)||executable==="bun"&&check3.command[1]==="run";if(!selectedObligation&&isPackageManagerCommand&&(check3.category!=="reproduction"||!isExactRepositoryPackageManagerScript(directory,normalizedCheckDirectories.get(check3)??".",check3.category,check3.command)))return failure2(`Stage A ${check3.category} package-manager command must select one exact inspected repository script`);if(!isAllowedRepositoryExecutable(directory,normalizedCheckDirectories.get(check3)??".",check3.command[0],contractValidated))return failure2(`Stage A rejects escaping or undeclared repository wrapper executables: ${check3.command[0]}`)}let normalizedCommands=parsed.data.checks.map((check3)=>`${check3.obligation_id??check3.category}\x00${normalizedCheckDirectories.get(check3)??"."}\x00${check3.command.join("\x00")}`.toLowerCase());if(new Set(normalizedCommands).size!==normalizedCommands.length)return failure2("Stage A categories require distinct commands; one command cannot prove multiple obligations");let reproduction=parsed.data.checks.find((check3)=>check3.category==="reproduction");if(!reproduction?.targets?.length)return failure2("Stage A reproduction requires at least one explicit test/regression target");let reproductionSelectors=reproductionSelectorValues(reproduction.command),missingTargets=reproduction.targets.filter((target)=>![...reproductionSelectors].some((selector)=>selector===target||selector.replaceAll("\\","/")===target.replaceAll("\\","/")));if(missingTargets.length>0)return failure2(`Stage A reproduction command does not select declared target(s): ${missingTargets.join(", ")}`);for(let target of reproduction.targets){if(!/[\\/]/.test(target))continue;let pathTarget=target.split("::",1)[0].replace(/:\d+(?::\d+)?$/,""),resolved=path248.resolve(directory,pathTarget),relative57=path248.relative(path248.resolve(directory),resolved);if(!relative57||relative57.startsWith("..")||path248.isAbsolute(relative57)||!fs150.existsSync(resolved)||!fs150.statSync(resolved).isFile())return failure2(`Stage A reproduction target is not a contained existing file: ${target}`)}try{let state=await assertPrFeedbackVerificationSettled(directory,context.sessionID),feedbackTargets=reproduction.feedback_targets??[],mappedFeedbackIds=feedbackTargets.map((mapping)=>mapping.feedback_item_id);if(mappedFeedbackIds.length!==new Set(mappedFeedbackIds).size||mappedFeedbackIds.length!==(state.prFeedbackInventory?.length??0)||!mappedFeedbackIds.every((itemId,index)=>itemId===state.prFeedbackInventory?.[index])||feedbackTargets.some((mapping)=>!reproduction.targets?.includes(mapping.target)))return failure2("Stage A reproduction requires one exact target and expected-behavior mapping for every immutable feedback item in declared order");if(state.prHeadSha!==parsed.data.pr_head_sha)return failure2(`PR_FEEDBACK head mismatch: expected ${state.prHeadSha??"(unbound)"}, received ${parsed.data.pr_head_sha}`);assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha);let beforeDigest=_internals164.resolvePrWorkflowRevisionDigest(directory,parsed.data.pr_head_sha);if(!beforeDigest)return failure2("Could not compute a bounded Stage A revision digest");let boundHead=_internals164.resolveCurrentGitHead(directory)?.trim(),boundControlState=_internals164.resolveGitControlStateDigest(directory);if(!boundHead||!boundControlState)return failure2("Could not bind Stage A to the current Git HEAD, refs, config, and index state");let results=[],receipts=[];for(let check3 of parsed.data.checks){let commandRevision=_internals164.resolvePrWorkflowRevisionDigest(directory,parsed.data.pr_head_sha),commandControl=_internals164.resolveGitControlStateDigest(directory);if(commandRevision!==beforeDigest||commandControl!==boundControlState||_internals164.resolveCurrentGitHead(directory)?.trim()!==boundHead)return failure2(`Stage A Git or content state changed before ${check3.category}; restart the complete sequence`,results);let started=Date.now(),[executable,...commandArgs]=check3.command,checkDirectory=resolveContainedDirectory(directory,check3.working_directory??".");if(!checkDirectory)return failure2(`Stage A ${check3.category} workspace disappeared before execution`,results);let result;try{result=await _internals164.runExternalTool({executable,args:commandArgs,cwd:checkDirectory.absolute,timeoutMs:check3.timeout_ms??120000,maxStdoutBytes:MAX_OUTPUT_BYTES9,maxStderrBytes:MAX_OUTPUT_BYTES9})}catch(error93){let afterThrowRevision=_internals164.resolvePrWorkflowRevisionDigest(directory,parsed.data.pr_head_sha),afterThrowControl=_internals164.resolveGitControlStateDigest(directory);if(afterThrowRevision!==beforeDigest||afterThrowControl!==boundControlState||_internals164.resolveCurrentGitHead(directory)?.trim()!==boundHead)return failure2(`Stage A ${check3.category} threw after mutating content, HEAD, refs, Git config, or index state`,results);return failure2(`Stage A ${check3.category} execution threw: ${error93 instanceof Error?error93.message:String(error93)}`,results)}let durationMs=Date.now()-started;results.push({category:check3.category,working_directory:checkDirectory.relative,...check3.obligation_id?{obligation_id:check3.obligation_id}:{},command:check3.command,status:result.status,exit_code:result.exitCode,duration_ms:durationMs,stdout:result.stdout,stderr:result.stderr,stdout_truncated:result.stdoutTruncated,stderr_truncated:result.stderrTruncated,...result.message?{message:result.message}:{}});let afterCommandRevision=_internals164.resolvePrWorkflowRevisionDigest(directory,parsed.data.pr_head_sha),afterCommandControl=_internals164.resolveGitControlStateDigest(directory);if(afterCommandRevision!==beforeDigest||afterCommandControl!==boundControlState||_internals164.resolveCurrentGitHead(directory)?.trim()!==boundHead)return failure2(`Stage A ${check3.category} mutated content, HEAD, refs, Git config, or index state`,results);if(result.status!=="completed"||result.exitCode!==0)return failure2(`Stage A ${check3.category} failed (${result.status}, exit ${result.exitCode??"unknown"})`,results);if(check3.validator_contract&&!`${result.stdout}
6235
+ ${result.stderr}`;return/(?:\b(?:ran|running|collected)\s+0\s+(?:tests?|items?)\b|\btests? run:\s*0\b|\b0\s+(?:tests?\s+(?:ran|passed)|pass(?:ed)?|passing|examples?)\b|\bno tests? (?:ran|to run|found|were found|executed|is available)\b|\bno test is available\b|\btests? (?:are|were) skipped\b|\btest\b[^\n]*\bskipped\b|\bNO-SOURCE\b|\[no test files\])/i.test(output)}function reproductionSelectorValues(command){let runnerVerbs=new Set(["run","run-script","test","tests","spec","check"]),selectorFlags=new Set(["--test-name-pattern","--testNamePattern","--tests","--filter","--grep","-k","-m","-run"]),selectors=new Set;for(let index=1;index<command.length;index+=1){let arg=command[index];if(selectorFlags.has(arg)){let value=command[index+1];if(value&&!value.startsWith("-"))selectors.add(value);index+=1;continue}let assignment=arg.match(/^(?:--(?:test-name-pattern|testNamePattern|tests|filter|grep)|-run|-Dtest)=(.+)$/);if(assignment?.[1]){selectors.add(assignment[1]);continue}if(arg.startsWith("-")||arg.startsWith("/"))continue;if(runnerVerbs.has(arg.toLowerCase()))continue;selectors.add(arg)}return selectors}function isPlausibleTypecheckCommand(executable,args2,_directCommandName){if(executable==="go")return args2[0]==="vet"&&!args2.some((arg)=>/^-n(?:=.*)?$/i.test(arg));if(executable==="flow")return["check","status","focus-check"].includes(args2[0]?.toLowerCase());if(executable==="phpstan")return["analyse","analyze"].includes(args2[0]?.toLowerCase())&&!args2.some((arg)=>/^--generate-baseline(?:=.*)?$/i.test(arg));return/^(?:tsc|pyright|mypy|sorbet|psalm)$/.test(executable)||executable==="cargo"&&args2[0]==="check"||executable==="dotnet"&&args2[0]==="build"}function isPlausibleReproductionCommand(executable,args2,_directCommandName,_commandPath){if(executable==="python"||executable==="python3")return args2[0]==="-m"&&args2[1]?.toLowerCase()==="pytest";if(executable==="bundle")return args2[0]==="exec"&&args2[1]?.toLowerCase()==="rspec";if(executable==="cargo")return args2[0]==="test"||args2[0]==="nextest"&&args2[1]?.toLowerCase()==="run";if(executable==="go")return args2[0]==="test"&&!args2.some((arg)=>/^(?:-c|-list(?:=.*)?)$/i.test(arg));if(executable==="node")return args2[0]==="--test";if(executable==="deno")return args2[0]==="test";if(executable==="zig")return args2[0]==="test";if(executable==="meson")return args2[0]==="test";if(executable==="make"||executable==="ninja")return args2.some((arg)=>/^(?:test|check|verify|regression)$/i.test(arg));if(executable==="playwright")return args2[0]==="test";if(executable==="dart"||executable==="flutter")return args2[0]==="test";if(executable==="xcodebuild")return args2.some((arg)=>["test","test-without-building"].includes(arg.toLowerCase()))&&!args2.some((arg)=>/^-(?:list|enumerate-tests|showBuildSettings|showdestinations|showTestPlans|showsdks|version|help)$/i.test(arg));if(executable==="cypress")return args2[0]==="run";if(/^(?:pytest|ctest|rspec|phpunit|vitest|jest|mocha|ava|go-test-sum)$/.test(executable))return!0;if(executable==="dotnet")return args2[0]?.toLowerCase()==="test";if(["mvn","mvnw"].includes(executable))return args2.some((arg)=>/^(?:test|verify|integration-test|failsafe:integration-test)$/i.test(arg));if(["gradle","gradlew"].includes(executable)){let invokesExecutableTestTask=args2.some((arg)=>{if(arg.startsWith("-"))return!1;let task=arg.split(":").filter(Boolean).at(-1)??"";if(/^(?:compile|process|generate|assemble|classes|jar|source|kapt|prepare)/i.test(task))return!1;return task.toLowerCase()==="test"||/^test[A-Z0-9_-]/.test(task)&&/Test$/.test(task)||/^[a-z][A-Za-z0-9_-]*Test$/.test(task)});return!args2.some((arg)=>/^(?:-m|--dry-run)(?:=.*)?$/i.test(arg))&&invokesExecutableTestTask}return!1}function isPlausibleStageACommand(category,command){if(category==="diff-check")return isExactDiffCheck(command);let executable=path248.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"");if(BLOCKED_EXECUTABLES.has(executable))return!1;if(command.slice(1).some((arg)=>/^(?:-h|--help|--version|version|help|list|-N|--fixtures(?:-per-test)?|--markers|--trace-config|--cache-show|--list(?:-?(?:tests?|suites|groups))?(?:-xml)?(?:=.*)?|--show-only(?:=.*)?|--print-labels|--listFilesOnly|--noCheck|--no-check|--no-run(?:=.*)?|--test-dry-run(?:=.*)?|--createStub|--createstub|--print-config|--env-info|--show-settings|--show-files|--list-msgs|--generate-rcfile|--show-?config(?:=.*)?|--init|--dry-run(?:=.*)?|--collect-only|--setup-(?:only|plan)|--co|--if-present(?:=.*)?)$/i.test(arg)))return!1;if(command.slice(1).some((arg)=>MUTATING_ARGUMENT.test(arg))||["bun","node","python","python3","ruby","perl","npx"].includes(executable)&&command.slice(1).some((arg)=>["-e","--eval","-c","--call"].includes(arg)))return!1;if(category==="lint"&&command.some((arg)=>/^(?:--fix(?:-only)?|--write|--apply|--auto-?correct)(?:=.*)?$|^-[aAw]$/.test(arg)))return!1;if(category==="reproduction"&&(command.some((arg)=>/^(?:--passWithNoTests|--allow-no-tests|--collect-only|--list|--dry-run|--only|--todo|--update-snapshot|--bless|--accept|-w|-x(?:.+)?|--exclude-task(?:=.+)?)$/i.test(arg))||command.some((arg)=>/^-D(?:skipTests|skipITs|maven\.test\.(?:skip|skip\.exec))(?:=true)?$/i.test(arg))))return!1;if(["npm","pnpm","yarn"].includes(executable)||executable==="bun"&&["build","run","test"].includes(command[1]))return isPlausiblePackageManagerCommand(category,executable,command.slice(1));if(executable==="npx")return isPlausiblePackageManagerCommand(category,executable,command.slice(1));let directCommandName=executable.replace(/\.(?:sh|ps1|py|js|mjs|cjs|rb|pl)$/,"");switch(category){case"build":return isPlausibleBuildCommand(executable,command.slice(1));case"typecheck":return isPlausibleTypecheckCommand(executable,command.slice(1),directCommandName);case"lint":return isPlausibleLintCommand(executable,command.slice(1),directCommandName);case"reproduction":return isPlausibleReproductionCommand(executable,command.slice(1),directCommandName,command[0])}}function readBoundedText(filePath){try{let stat17=fs150.statSync(filePath);if(!stat17.isFile()||stat17.size>524288)return;return fs150.readFileSync(filePath,"utf8")}catch{return}}function readPresentRepositoryText(directory,filePath,label){let stat17;try{stat17=fs150.statSync(filePath)}catch(error93){if(error93.code==="ENOENT")return;throw Error(`BLOCKED: Stage A cannot inspect present ${label}`)}if(!stat17.isFile()||stat17.size>524288)throw Error(`BLOCKED: Stage A cannot inspect present ${label}`);try{let canonicalRoot=fs150.realpathSync(path248.resolve(directory)),canonicalFile=fs150.realpathSync(filePath),relative57=path248.relative(canonicalRoot,canonicalFile);if(relative57===".."||relative57.startsWith(`..${path248.sep}`)||path248.isAbsolute(relative57))throw Error("escaping manifest");return fs150.readFileSync(canonicalFile,"utf8")}catch{throw Error(`BLOCKED: Stage A cannot inspect present ${label}`)}}function resolveContainedDirectory(directory,workingDirectory="."){let root=path248.resolve(directory),canonicalRoot=(()=>{try{return fs150.realpathSync(root)}catch{return root}})(),candidate=path248.resolve(root,workingDirectory);try{if(!fs150.statSync(candidate).isDirectory())return;let absolute=fs150.realpathSync(candidate),relativePath2=path248.relative(canonicalRoot,absolute);if(relativePath2===".."||relativePath2.startsWith(`..${path248.sep}`)||path248.isAbsolute(relativePath2))return;return{absolute,relative:relativePath2.replaceAll("\\","/")||"."}}catch{return}}function readRepositoryValidationContract(directory,contractPath){let root=path248.resolve(directory),canonicalRoot=(()=>{try{return fs150.realpathSync(root)}catch{return root}})(),resolved=path248.resolve(root,contractPath),canonicalContract;try{canonicalContract=fs150.realpathSync(resolved)}catch{return}let relative57=path248.relative(canonicalRoot,canonicalContract);if(!relative57||relative57===".."||relative57.startsWith(`..${path248.sep}`)||path248.isAbsolute(relative57)||path248.basename(canonicalContract)!==".pr-validation.json")return;let text=readBoundedText(canonicalContract);if(!text)return;try{return RepositoryValidationContractSchema.parse(JSON.parse(text))}catch{return}}async function resolveContractBaseProvenance(directory,prHeadSha,baseRef,baseSha){if(!baseRef&&!baseSha)return;if(!baseRef||!baseSha)throw Error("BLOCKED: Stage A contract authorization requires both base_ref and base_sha");let resolvedBase=await _internals164.resolveExactMergeBaseAsync(directory,baseRef,prHeadSha);if(!resolvedBase||resolvedBase.toLowerCase()!==baseSha.toLowerCase()||resolvedBase.toLowerCase()===prHeadSha.toLowerCase())throw Error("Stage A contract authorization requires base_sha to be the immutable merge base of base_ref and pr_head_sha");return{baseRef,baseSha:resolvedBase.toLowerCase()}}function readTrustedRepositoryValidationContract(directory,contractPath,provenance){if(!provenance)return;let current=readRepositoryValidationContract(directory,contractPath),currentText=readBoundedText(path248.resolve(directory,contractPath)),baseText=_internals164.readGitTextAtRevision(directory,provenance.baseSha,contractPath.replaceAll("\\","/").replace(/^\.\//,""));if(!current||!currentText||baseText===null||currentText!==baseText)return;return current}function isExactRepositoryContractValidator(directory,check3,provenance){if(!check3.validator_contract)return!1;let validator=readTrustedRepositoryValidationContract(directory,check3.validator_contract.path,provenance)?.validators.find((candidate)=>candidate.id===check3.validator_contract?.id);if(!validator||validator.category!==check3.category)return!1;let requestedDirectory=resolveContainedDirectory(directory,check3.working_directory??"."),declaredDirectory=resolveContainedDirectory(directory,validator.working_directory);return Boolean(requestedDirectory&&declaredDirectory)&&requestedDirectory?.absolute===declaredDirectory?.absolute&&validator.command.length===check3.command.length&&validator.command.every((part,index)=>part===check3.command[index])}function isExactObligationContractAuthorization(directory,obligation,check3,provenance){let identity=obligation.validatorContract;if(!identity||check3.validator_contract?.path!==identity.path||check3.validator_contract.id!==identity.id)return!1;let validator=readTrustedRepositoryValidationContract(directory,identity.path,provenance)?.validators.find(({id})=>id===identity.id),workspace=resolveContainedDirectory(directory,obligation.workingDirectory),validatorWorkspace=validator?resolveContainedDirectory(directory,validator.working_directory):void 0;if(!validator||validator.category!==obligation.category||validatorWorkspace?.absolute!==workspace?.absolute)return!1;if(!obligation.source.startsWith("package.json#")||!workspace)return!1;let scriptName=obligation.source.slice(13),packageText=readBoundedText(path248.join(workspace.absolute,"package.json"));if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared&&declared.length===validator.command.length&&declared.every((part,index)=>part===validator.command[index])&&(packageManagerSelectsExactScript(check3.command,scriptName)||declared.length===check3.command.length&&declared.every((part,index)=>part===check3.command[index])))}catch{return!1}}function isSafeContractCommand(command){let executable=path248.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"");return!BLOCKED_EXECUTABLES.has(executable)&&!command.slice(1).some((arg)=>MUTATING_ARGUMENT.test(arg))&&!command.some((arg)=>/^(?:-h|--help|--version|help|version|--dry-run|--if-present)$/i.test(arg))&&!(["bun","node","python","python3","ruby","perl","npx"].includes(executable)&&command.slice(1).some((arg)=>["-e","--eval","-c","--call"].includes(arg)))}function isAllowedRepositoryExecutable(directory,workingDirectory,executable,contractValidated){if(!/[\\/]/.test(executable))return!0;if(path248.isAbsolute(executable))return!1;let workspace=resolveContainedDirectory(directory,workingDirectory);if(!workspace)return!1;let resolved=path248.resolve(workspace.absolute,executable),canonicalExecutable;try{canonicalExecutable=fs150.realpathSync(resolved)}catch{return!1}let canonicalRoot=(()=>{try{return fs150.realpathSync(path248.resolve(directory))}catch{return path248.resolve(directory)}})(),relative57=path248.relative(canonicalRoot,canonicalExecutable);if(relative57===".."||relative57.startsWith(`..${path248.sep}`)||path248.isAbsolute(relative57))return!1;let basename32=path248.basename(canonicalExecutable).toLowerCase().replace(/\.(?:cmd|bat|exe)$/,"");if(!contractValidated&&!["gradlew","mvnw"].includes(basename32))return!1;return fs150.statSync(canonicalExecutable).isFile()}function normalizedExecutable(command){return path248.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"")}function parseSimpleRepositoryScript(script){if(/[;&|><`\r\n]/.test(script)||script.includes("$(")||script.includes("${"))return;let tokens=script.match(/"(?:\\.|[^"\\])*"|'[^']*'|[^\s]+/g)?.map((token)=>{if(token.startsWith('"')&&token.endsWith('"')||token.startsWith("'")&&token.endsWith("'"))return token.slice(1,-1);return token})??[];return tokens.length>0?tokens:void 0}function packageManagerSelectedScriptName(command){let executable=normalizedExecutable(command);if(!["npm","bun","pnpm","yarn"].includes(executable))return;let positional=command.slice(1,command.indexOf("--")>=0?command.indexOf("--"):void 0).filter((arg)=>!arg.startsWith("-"));if(executable==="npm")return["run","run-script"].includes(positional[0]??"")?positional[1]:void 0;if(executable==="bun")return positional[0]==="run"?positional[1]:void 0;return positional[0]==="run"?positional[1]:positional[0]}function packageManagerSelectsExactScript(command,scriptName){return packageManagerSelectedScriptName(command)===scriptName}function isExactRepositoryPackageManagerScript(directory,workingDirectory,category,command){let scriptName=packageManagerSelectedScriptName(command),workspace=resolveContainedDirectory(directory,workingDirectory);if(!scriptName||!workspace||!categoryMatchesScriptName(category,scriptName))return!1;let packageText=readBoundedText(path248.join(workspace.absolute,"package.json"));if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared&&isPlausibleStageACommand(category,declared))}catch{return!1}}function commandMatchesObligationSource(directory,obligation,check3,contractValidated){let executable=normalizedExecutable(check3.command),effectiveExecutable=executable==="npx"&&check3.command[1]?path248.basename(check3.command[1]).toLowerCase():executable,source=obligation.source;if(source.includes(".pr-validation.json#")){let separator=source.lastIndexOf("#"),contractPath=source.slice(0,separator),validatorId=source.slice(separator+1);return contractValidated&&check3.validator_contract?.id===validatorId&&check3.validator_contract?.path.replaceAll("\\","/").replace(/^\.\//,"")===contractPath.replace(/^\.\//,"")}if(source.startsWith("package.json#")){let scriptName=source.slice(13),workspace=resolveContainedDirectory(directory,obligation.workingDirectory),packageText=workspace?readBoundedText(path248.join(workspace.absolute,"package.json")):void 0;if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared)&&declared?.length===check3.command.length&&declared.every((part,index)=>part===check3.command[index])||packageManagerSelectsExactScript(check3.command,scriptName)}catch{return!1}}if(source==="Cargo.toml")return effectiveExecutable==="cargo";if(source==="go.mod")return effectiveExecutable==="go";if(source==="pom.xml")return["mvn","mvnw"].includes(effectiveExecutable);if(/^build\.gradle(?:\.kts)?$/.test(source))return["gradle","gradlew"].includes(effectiveExecutable);if(/^(?:Makefile|makefile)$/.test(source))return effectiveExecutable==="make";if(source==="CMakeLists.txt")return effectiveExecutable==="cmake";if(source==="Package.swift")return["swift","swiftc"].includes(effectiveExecutable);if(source==="setup.py"||source==="pyproject.toml#build-system")return["python","python3"].includes(effectiveExecutable);if(/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(source))return["dotnet","msbuild"].includes(effectiveExecutable);if(/\.(?:xcodeproj|xcworkspace)$/i.test(source))return effectiveExecutable==="xcodebuild";let sourceExecutables={"tsconfig.json":["tsc"],"pyrightconfig.json":["pyright"],".flowconfig":["flow"],"phpstan.neon":["phpstan"],"phpstan.neon.dist":["phpstan"],"psalm.xml":["psalm"],"psalm.xml.dist":["psalm"],"mypy.ini":["mypy"],"pyproject.toml#mypy":["mypy"],"biome.json":["biome"],"biome.jsonc":["biome"],"ruff.toml":["ruff"],".ruff.toml":["ruff"],"pyproject.toml#ruff":["ruff"],".rubocop.yml":["rubocop"],".swiftlint.yml":["swiftlint"],".golangci.yml":["golangci-lint"],".golangci.yaml":["golangci-lint"],".stylelintrc":["stylelint"],".stylelintrc.json":["stylelint"]};if(/^(?:\.eslintrc|eslint\.config\.)/.test(source))return effectiveExecutable==="eslint";return sourceExecutables[source]?.includes(effectiveExecutable)??!1}function discoverApplicableStageAObligations(directory,contractBase){let root=path248.resolve(directory),canonicalRoot=(()=>{try{return fs150.realpathSync(root)}catch{return root}})(),candidateRoots=[],seenRoots=new Set,discoveryOverflow,addCandidateRoot=(candidate)=>{if(candidateRoots.length>=256){discoveryOverflow="Stage A repository discovery exceeded 256 contained workspace roots";return}try{if(!fs150.statSync(candidate).isDirectory())return;let canonicalCandidate=fs150.realpathSync(candidate),relative57=path248.relative(canonicalRoot,canonicalCandidate);if(relative57.startsWith(`..${path248.sep}`)||relative57===".."||path248.isAbsolute(relative57)||seenRoots.has(canonicalCandidate))return;seenRoots.add(canonicalCandidate),candidateRoots.push(canonicalCandidate)}catch{}},addWorkspacePattern=(pattern)=>{let normalized=pattern.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!normalized||normalized.startsWith("!")||path248.posix.isAbsolute(normalized)||normalized.split("/").includes("..")){discoveryOverflow=`Stage A cannot safely expand declared workspace pattern "${pattern}"`;return}if(!normalized.includes("*")){addCandidateRoot(path248.resolve(root,normalized));return}let wildcard=normalized.match(/^([^*?[\]]+)\/\*\/?$/);if(!wildcard){discoveryOverflow=`Stage A cannot safely expand declared workspace pattern "${pattern}"`;return}let container=path248.resolve(root,wildcard[1]);try{let entries=fs150.readdirSync(container,{withFileTypes:!0});if(entries.length>256){discoveryOverflow=`Stage A workspace container ${wildcard[1]} exceeds the 256-entry bounded discovery limit`;return}for(let entry of entries)if(entry.isDirectory())addCandidateRoot(path248.join(container,entry.name))}catch{}};addCandidateRoot(root);for(let containerName of["packages","apps","services","libs","crates"])addWorkspacePattern(`${containerName}/*`);let rootPackageText=readPresentRepositoryText(canonicalRoot,path248.join(root,"package.json"),"root package.json workspace declaration");if(rootPackageText)try{let value=JSON.parse(rootPackageText),workspacePatterns=Array.isArray(value.workspaces)?value.workspaces:value.workspaces?.packages;for(let pattern of workspacePatterns??[])if(typeof pattern==="string")addWorkspacePattern(pattern)}catch{discoveryOverflow="Stage A cannot safely inspect malformed root package.json workspace metadata"}let pnpmWorkspaceText=readPresentRepositoryText(canonicalRoot,path248.join(root,"pnpm-workspace.yaml"),"pnpm-workspace.yaml declaration");for(let match of pnpmWorkspaceText?.matchAll(/^\s*-\s*['"]?([^'"#\r\n]+?)['"]?\s*$/gm)??[])addWorkspacePattern(match[1]);let cargoMembers=readPresentRepositoryText(canonicalRoot,path248.join(root,"Cargo.toml"),"Cargo.toml workspace declaration")?.match(/\bmembers\s*=\s*\[([\s\S]*?)\]/m)?.[1];for(let match of cargoMembers?.matchAll(/['"]([^'"]+)['"]/g)??[])addWorkspacePattern(match[1]);let mavenText=readPresentRepositoryText(canonicalRoot,path248.join(root,"pom.xml"),"pom.xml module declaration");for(let match of mavenText?.matchAll(/<module>\s*([^<]+?)\s*<\/module>/gi)??[])addWorkspacePattern(match[1]);let goWorkText=readPresentRepositoryText(canonicalRoot,path248.join(root,"go.work"),"go.work workspace declaration");for(let match of goWorkText?.matchAll(/^\s*(?:use\s+)?(\.\.?\/[^\s/]+(?:\/[^\s]+)*)\s*$/gm)??[])addWorkspacePattern(match[1]);for(let settingsName of["settings.gradle","settings.gradle.kts"]){let settingsText=readPresentRepositoryText(canonicalRoot,path248.join(root,settingsName),`${settingsName} workspace declaration`);for(let includeMatch of settingsText?.matchAll(/\binclude\s*\(?([^\r\n)]+)/g)??[])for(let projectMatch of includeMatch[1].matchAll(/['"]:?(.*?)['"]/g)){let projectPath=projectMatch[1].replaceAll(":","/");if(projectPath)addWorkspacePattern(projectPath)}}let obligations=new Map,addObligation=(category,candidateRoot,source,validatorContract)=>{let workspace=path248.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||".",id=`${category}:${workspace}:${source}`;if(!obligations.has(id)&&obligations.size>=256){discoveryOverflow="Stage A repository discovery exceeded 256 concrete validation obligations";return}obligations.set(id,{id,category,workingDirectory:workspace,source,...validatorContract?{validatorContract}:{}})},buildFiles=new Set(["Cargo.toml","go.mod","pom.xml","build.gradle","build.gradle.kts","Makefile","makefile","CMakeLists.txt","Package.swift","setup.py"]),typecheckFiles=new Set(["tsconfig.json","pyrightconfig.json",".flowconfig","phpstan.neon","phpstan.neon.dist","psalm.xml","psalm.xml.dist","mypy.ini"]),lintFiles=new Set(["biome.json","biome.jsonc",".eslintrc",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml",".eslintrc.js",".eslintrc.cjs",".eslintrc.mjs","eslint.config.js","eslint.config.mjs","eslint.config.cjs","eslint.config.ts","ruff.toml",".ruff.toml",".rubocop.yml",".swiftlint.yml",".golangci.yml",".golangci.yaml",".stylelintrc",".stylelintrc.json"]);for(let candidateRoot of candidateRoots){let entries=[];try{if(entries=fs150.readdirSync(candidateRoot,{withFileTypes:!0}),entries.length>2048){discoveryOverflow=`Stage A workspace ${path248.relative(canonicalRoot,candidateRoot)||"."} exceeds the 2048-entry bounded manifest scan`;continue}}catch{continue}for(let entry of entries){if(entry.isFile()&&buildFiles.has(entry.name))addObligation("build",candidateRoot,entry.name);if(entry.isFile()&&typecheckFiles.has(entry.name))addObligation("typecheck",candidateRoot,entry.name);if(entry.isFile()&&lintFiles.has(entry.name))addObligation("lint",candidateRoot,entry.name);if(entry.isFile()&&/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(entry.name))addObligation("build",candidateRoot,entry.name);if(entry.isDirectory()&&/\.(?:xcodeproj|xcworkspace)$/i.test(entry.name))addObligation("build",candidateRoot,entry.name)}let contractPath=path248.join(candidateRoot,".pr-validation.json"),contractRelative=path248.relative(canonicalRoot,contractPath).replaceAll("\\","/"),untrustedContract=readRepositoryValidationContract(canonicalRoot,contractRelative),contract=readTrustedRepositoryValidationContract(canonicalRoot,contractRelative,contractBase);if(fs150.existsSync(contractPath)&&!untrustedContract)discoveryOverflow=`Stage A found an invalid, oversized, unreadable, or escaping validation contract at ${contractRelative}`;else if(untrustedContract&&!contract)discoveryOverflow=`Stage A validation contract at ${contractRelative} must be unchanged from the immutable merge base named by base_ref and base_sha`;let contractValidatorsCoveredByScripts=new Set,packageText=readPresentRepositoryText(canonicalRoot,path248.join(candidateRoot,"package.json"),`${path248.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json manifest`);if(packageText)try{let value=JSON.parse(packageText);for(let[script,commandText]of Object.entries(value.scripts??{})){let declaredCommand=typeof commandText==="string"?parseSimpleRepositoryScript(commandText):void 0;for(let category of OPTIONAL_STAGE_A_CATEGORIES){if(!categoryMatchesScriptName(category,script))continue;let authorizingValidator=contract?.validators.find((validator)=>{let validatorWorkspace=resolveContainedDirectory(canonicalRoot,validator.working_directory);return validator.category===category&&validatorWorkspace?.absolute===candidateRoot&&(!declaredCommand||declaredCommand.length===validator.command.length&&declaredCommand.every((part,index)=>part===validator.command[index]))});if(!declaredCommand){if(!authorizingValidator)discoveryOverflow=`Stage A opaque package script ${path248.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json#${script} requires a trusted base-identical contract validator for ${category}`;continue}if(isPlausibleStageACommand(category,declaredCommand)||Boolean(authorizingValidator)){if(addObligation(category,candidateRoot,`package.json#${script}`,authorizingValidator?{path:contractRelative,id:authorizingValidator.id}:void 0),authorizingValidator)contractValidatorsCoveredByScripts.add(authorizingValidator.id)}}}}catch{discoveryOverflow=`Stage A cannot safely inspect malformed package manifest at ${path248.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json`}let pyprojectText=readPresentRepositoryText(canonicalRoot,path248.join(candidateRoot,"pyproject.toml"),`${path248.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/pyproject.toml manifest`);if(pyprojectText?.match(/\[build-system\]/i))addObligation("build",candidateRoot,"pyproject.toml#build-system");if(pyprojectText?.match(/\[(?:tool\.)?mypy\]/i))addObligation("typecheck",candidateRoot,"pyproject.toml#mypy");if(pyprojectText?.match(/\[tool\.ruff(?:\.|\])/i))addObligation("lint",candidateRoot,"pyproject.toml#ruff");for(let validator of contract?.validators??[]){if(contractValidatorsCoveredByScripts.has(validator.id))continue;if(OPTIONAL_STAGE_A_CATEGORIES.includes(validator.category)){let validatorWorkspace=resolveContainedDirectory(canonicalRoot,validator.working_directory);if(!validatorWorkspace)continue;addObligation(validator.category,validatorWorkspace.absolute,`${contractRelative}#${validator.id}`)}}}if(discoveryOverflow)throw Error(`BLOCKED: ${discoveryOverflow}`);return[...obligations.values()]}function discoverApplicableStageACategories(directory,contractBase){let applicable=new Set(discoverApplicableStageAObligations(directory,contractBase).map(({category})=>category));return OPTIONAL_STAGE_A_CATEGORIES.filter((category)=>applicable.has(category))}async function executeRunPrFeedbackStageA(args2,directory,context={}){let parsed=RunPrFeedbackStageAArgsSchema.safeParse(args2);if(!parsed.success)return failure2(`Invalid PR-feedback Stage A request: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);if(!context.sessionID?.trim())return failure2("PR-feedback Stage A requires an active sessionID");let categories=parsed.data.checks.map((check3)=>check3.category);for(let requiredSingleton of ALWAYS_REQUIRED_CATEGORIES)if(categories.filter((category)=>category===requiredSingleton).length!==1)return failure2(`Stage A requires exactly one ${requiredSingleton} receipt`);let contractBase;try{contractBase=await resolveContractBaseProvenance(directory,parsed.data.pr_head_sha,parsed.data.base_ref,parsed.data.base_sha)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}let applicableObligations;try{applicableObligations=_internals164.discoverApplicableStageAObligations(directory,contractBase)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}let applicableCategories=OPTIONAL_STAGE_A_CATEGORIES.filter((category)=>applicableObligations.some((obligation)=>obligation.category===category)),matchedObligationIds=new Set,selectedObligations=new Map,normalizedCheckDirectories=new Map;for(let check3 of parsed.data.checks){let workspace=resolveContainedDirectory(directory,check3.working_directory??".");if(!workspace)return failure2(`Stage A ${check3.category} working_directory is not a contained repository workspace`);if(normalizedCheckDirectories.set(check3,workspace.relative),!OPTIONAL_STAGE_A_CATEGORIES.includes(check3.category))continue;let candidates=applicableObligations.filter((obligation)=>obligation.category===check3.category&&obligation.workingDirectory===workspace.relative);if(candidates.length===0&&!check3.obligation_id)continue;let selected=check3.obligation_id?candidates.find((candidate)=>candidate.id===check3.obligation_id):candidates.length===1?candidates[0]:void 0;if(!selected)return failure2(`Stage A ${check3.category} must name one exact discovered obligation_id for workspace ${workspace.relative}: ${candidates.map(({id})=>id).join(", ")||"none discovered"}`);if(matchedObligationIds.has(selected.id))return failure2(`Stage A repeats discovered obligation ${selected.id}`);matchedObligationIds.add(selected.id),selectedObligations.set(check3,selected),check3.obligation_id=selected.id,check3.working_directory=workspace.relative}let missingObligations=applicableObligations.filter(({id})=>!matchedObligationIds.has(id));if(missingObligations.length>0)return failure2(`Stage A is missing concrete repository validation obligations: ${missingObligations.map(({id})=>id).join(", ")}`);let diffCheck=parsed.data.checks.find((check3)=>check3.category==="diff-check");if(!diffCheck||!isExactDiffCheck(diffCheck.command))return failure2('Stage A diff-check must execute array-form ["git", "diff", "--check"]');for(let check3 of parsed.data.checks){let directContractValidated=isExactRepositoryContractValidator(directory,check3,contractBase),selectedObligation=selectedObligations.get(check3),obligationContractValidated=selectedObligation?isExactObligationContractAuthorization(directory,selectedObligation,check3,contractBase):!1,contractValidated=directContractValidated||obligationContractValidated;if(selectedObligation?.validatorContract&&!obligationContractValidated)return failure2(`Stage A obligation ${selectedObligation.id} requires exact validator_contract ${selectedObligation.validatorContract.path}#${selectedObligation.validatorContract.id}`);let executable=normalizedExecutable(check3.command);if(selectedObligation&&!commandMatchesObligationSource(directory,selectedObligation,check3,contractValidated))return failure2(`Stage A command does not prove its exact source obligation ${selectedObligation.id}`);if(!isPlausibleStageACommand(check3.category,check3.command)&&!(contractValidated&&isSafeContractCommand(check3.command)))return failure2(`Stage A ${check3.category} command is not a recognized non-publishing ${check3.category} validation command`);let isPackageManagerCommand=["npm","pnpm","yarn"].includes(executable)||executable==="bun"&&check3.command[1]==="run";if(!selectedObligation&&isPackageManagerCommand&&(check3.category!=="reproduction"||!isExactRepositoryPackageManagerScript(directory,normalizedCheckDirectories.get(check3)??".",check3.category,check3.command)))return failure2(`Stage A ${check3.category} package-manager command must select one exact inspected repository script`);if(!isAllowedRepositoryExecutable(directory,normalizedCheckDirectories.get(check3)??".",check3.command[0],contractValidated))return failure2(`Stage A rejects escaping or undeclared repository wrapper executables: ${check3.command[0]}`)}let normalizedCommands=parsed.data.checks.map((check3)=>`${check3.obligation_id??check3.category}\x00${normalizedCheckDirectories.get(check3)??"."}\x00${check3.command.join("\x00")}`.toLowerCase());if(new Set(normalizedCommands).size!==normalizedCommands.length)return failure2("Stage A categories require distinct commands; one command cannot prove multiple obligations");let reproduction=parsed.data.checks.find((check3)=>check3.category==="reproduction");if(!reproduction?.targets?.length)return failure2("Stage A reproduction requires at least one explicit test/regression target");let reproductionSelectors=reproductionSelectorValues(reproduction.command),missingTargets=reproduction.targets.filter((target)=>![...reproductionSelectors].some((selector)=>selector===target||selector.replaceAll("\\","/")===target.replaceAll("\\","/")));if(missingTargets.length>0)return failure2(`Stage A reproduction command does not select declared target(s): ${missingTargets.join(", ")}`);for(let target of reproduction.targets){if(!/[\\/]/.test(target))continue;let pathTarget=target.split("::",1)[0].replace(/:\d+(?::\d+)?$/,""),resolved=path248.resolve(directory,pathTarget),relative57=path248.relative(path248.resolve(directory),resolved);if(!relative57||relative57.startsWith("..")||path248.isAbsolute(relative57)||!fs150.existsSync(resolved)||!fs150.statSync(resolved).isFile())return failure2(`Stage A reproduction target is not a contained existing file: ${target}`)}try{let state=await assertPrFeedbackVerificationSettled(directory,context.sessionID),feedbackTargets=reproduction.feedback_targets??[],mappedFeedbackIds=feedbackTargets.map((mapping)=>mapping.feedback_item_id);if(mappedFeedbackIds.length!==new Set(mappedFeedbackIds).size||mappedFeedbackIds.length!==(state.prFeedbackInventory?.length??0)||!mappedFeedbackIds.every((itemId,index)=>itemId===state.prFeedbackInventory?.[index])||feedbackTargets.some((mapping)=>!reproduction.targets?.includes(mapping.target)))return failure2("Stage A reproduction requires one exact target and expected-behavior mapping for every immutable feedback item in declared order");if(state.prHeadSha!==parsed.data.pr_head_sha)return failure2(`PR_FEEDBACK head mismatch: expected ${state.prHeadSha??"(unbound)"}, received ${parsed.data.pr_head_sha}`);await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha);let beforeDigest=await _internals164.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha);if(!beforeDigest)return failure2("Could not compute a bounded Stage A revision digest");let boundHead=(await _internals164.resolveCurrentGitHeadAsync(directory))?.trim(),boundControlState=await _internals164.resolveGitControlStateDigestAsync(directory);if(!boundHead||!boundControlState)return failure2("Could not bind Stage A to the current Git HEAD, refs, config, and index state");let results=[],receipts=[];for(let check3 of parsed.data.checks){let commandRevision=await _internals164.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),commandControl=await _internals164.resolveGitControlStateDigestAsync(directory);if(commandRevision!==beforeDigest||commandControl!==boundControlState||(await _internals164.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A Git or content state changed before ${check3.category}; restart the complete sequence`,results);let started=Date.now(),[executable,...commandArgs]=check3.command,checkDirectory=resolveContainedDirectory(directory,check3.working_directory??".");if(!checkDirectory)return failure2(`Stage A ${check3.category} workspace disappeared before execution`,results);let result;try{result=await _internals164.runExternalTool({executable,args:commandArgs,cwd:checkDirectory.absolute,timeoutMs:check3.timeout_ms??120000,maxStdoutBytes:MAX_OUTPUT_BYTES9,maxStderrBytes:MAX_OUTPUT_BYTES9})}catch(error93){let afterThrowRevision=await _internals164.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),afterThrowControl=await _internals164.resolveGitControlStateDigestAsync(directory);if(afterThrowRevision!==beforeDigest||afterThrowControl!==boundControlState||(await _internals164.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A ${check3.category} threw after mutating content, HEAD, refs, Git config, or index state`,results);return failure2(`Stage A ${check3.category} execution threw: ${error93 instanceof Error?error93.message:String(error93)}`,results)}let durationMs=Date.now()-started;results.push({category:check3.category,working_directory:checkDirectory.relative,...check3.obligation_id?{obligation_id:check3.obligation_id}:{},command:check3.command,status:result.status,exit_code:result.exitCode,duration_ms:durationMs,stdout:result.stdout,stderr:result.stderr,stdout_truncated:result.stdoutTruncated,stderr_truncated:result.stderrTruncated,...result.message?{message:result.message}:{}});let afterCommandRevision=await _internals164.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),afterCommandControl=await _internals164.resolveGitControlStateDigestAsync(directory);if(afterCommandRevision!==beforeDigest||afterCommandControl!==boundControlState||(await _internals164.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A ${check3.category} mutated content, HEAD, refs, Git config, or index state`,results);if(result.status!=="completed"||result.exitCode!==0)return failure2(`Stage A ${check3.category} failed (${result.status}, exit ${result.exitCode??"unknown"})`,results);if(check3.validator_contract&&!`${result.stdout}
6234
6236
  ${result.stderr}`.trim())return failure2(`Stage A repository-contract validator ${check3.validator_contract.id} produced no machine-observable evidence`,results);if(check3.category==="reproduction"&&outputReportsZeroTests(result))return failure2("Stage A reproduction produced truncated proof or reported that zero tests executed",results);if(check3.category==="reproduction"&&!`${result.stdout}
6235
- ${result.stderr}`.trim())return failure2("Stage A reproduction produced no machine-observable execution evidence",results);receipts.push({category:check3.category,workingDirectory:checkDirectory.relative,...check3.obligation_id?{obligationId:check3.obligation_id}:{},...check3.validator_contract?{validatorContract:{path:check3.validator_contract.path,id:check3.validator_contract.id}}:{},command:check3.command,...check3.targets?{targets:check3.targets}:{},...check3.feedback_targets?{feedbackTargets:check3.feedback_targets.map((mapping)=>({feedbackItemId:mapping.feedback_item_id,target:mapping.target,expectedBehavior:mapping.expected_behavior}))}:{},durationMs})}let afterDigest=_internals164.resolvePrWorkflowRevisionDigest(directory,parsed.data.pr_head_sha);if(!afterDigest||afterDigest!==beforeDigest)return failure2("Stage A changed the working-tree revision; rerun all Stage A checks on the resulting diff",results);if(_internals164.resolveGitControlStateDigest(directory)!==boundControlState||_internals164.resolveCurrentGitHead(directory)?.trim()!==boundHead)return failure2("Stage A changed HEAD, refs, Git config, or index state; rerun the complete sequence",results);return await recordPrFeedbackStageA(directory,context.sessionID,afterDigest,receipts,{applicableCategories,applicableObligations}),JSON.stringify({success:!0,pr_head_sha:parsed.data.pr_head_sha,revision_digest:afterDigest,checks:results},null,2)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}}var _internals164={runExternalTool,readGitTextAtRevision,resolveExactMergeBase,resolveCurrentGitHead,resolveGitControlStateDigest,resolvePrWorkflowRevisionDigest,isPlausibleStageACommand,discoverApplicableStageACategories,discoverApplicableStageAObligations,commandMatchesObligationSource},run_pr_feedback_stage_a=createSwarmTool({description:"Execute and persist mandatory PR-feedback Stage A diff-check and targeted reproduction receipts plus every build, typecheck, or lint check mechanically applicable to this repository, on one content-bound revision.",args:{pr_head_sha:RunPrFeedbackStageAArgsSchema.shape.pr_head_sha,checks:RunPrFeedbackStageAArgsSchema.shape.checks},execute:executeRunPrFeedbackStageA});init_sast_scan();init_zod();init_plan_schema();init_qa_gate_profile();init_file_locks();import*as fs151 from"node:fs";import*as path249 from"node:path";init_ledger();init_manager();init_utils3();init_effective_spec();init_state2();init_create_tool();function executionProfilesEqual(a,b){return a.parallelization_enabled===b.parallelization_enabled&&a.max_concurrent_tasks===b.max_concurrent_tasks&&a.council_parallel===b.council_parallel&&a.locked===b.locked&&a.auto_proceed===b.auto_proceed}function evaluateRequirementCoverage(specContent,args2){if(!specContent)return null;let requirements=extractRequirements(specContent);if(requirements.length===0)return null;let covered=[],missing=[];for(let requirement of requirements){let mappedTaskIds=[],idPattern=new RegExp(`\\b${requirement.id}\\b`,"i");for(let phase of args2.phases)for(let task of phase.tasks){let taskText=`${task.description}
6237
+ ${result.stderr}`.trim())return failure2("Stage A reproduction produced no machine-observable execution evidence",results);receipts.push({category:check3.category,workingDirectory:checkDirectory.relative,...check3.obligation_id?{obligationId:check3.obligation_id}:{},...check3.validator_contract?{validatorContract:{path:check3.validator_contract.path,id:check3.validator_contract.id}}:{},command:check3.command,...check3.targets?{targets:check3.targets}:{},...check3.feedback_targets?{feedbackTargets:check3.feedback_targets.map((mapping)=>({feedbackItemId:mapping.feedback_item_id,target:mapping.target,expectedBehavior:mapping.expected_behavior}))}:{},durationMs})}let afterDigest=await _internals164.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha);if(!afterDigest||afterDigest!==beforeDigest)return failure2("Stage A changed the working-tree revision; rerun all Stage A checks on the resulting diff",results);if(await _internals164.resolveGitControlStateDigestAsync(directory)!==boundControlState||(await _internals164.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2("Stage A changed HEAD, refs, Git config, or index state; rerun the complete sequence",results);return await recordPrFeedbackStageA(directory,context.sessionID,afterDigest,receipts,{applicableCategories,applicableObligations}),JSON.stringify({success:!0,pr_head_sha:parsed.data.pr_head_sha,revision_digest:afterDigest,checks:results},null,2)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}}var _internals164={runExternalTool,readGitTextAtRevision,resolveExactMergeBase,resolveExactMergeBaseAsync,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveGitControlStateDigest,resolveGitControlStateDigestAsync,resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,isPlausibleStageACommand,discoverApplicableStageACategories,discoverApplicableStageAObligations,commandMatchesObligationSource},run_pr_feedback_stage_a=createSwarmTool({description:"Execute and persist mandatory PR-feedback Stage A diff-check and targeted reproduction receipts plus every build, typecheck, or lint check mechanically applicable to this repository, on one content-bound revision.",args:{pr_head_sha:RunPrFeedbackStageAArgsSchema.shape.pr_head_sha,checks:RunPrFeedbackStageAArgsSchema.shape.checks},execute:executeRunPrFeedbackStageA});init_sast_scan();init_zod();init_plan_schema();init_qa_gate_profile();init_file_locks();import*as fs151 from"node:fs";import*as path249 from"node:path";init_ledger();init_manager();init_utils3();init_effective_spec();init_state2();init_create_tool();function executionProfilesEqual(a,b){return a.parallelization_enabled===b.parallelization_enabled&&a.max_concurrent_tasks===b.max_concurrent_tasks&&a.council_parallel===b.council_parallel&&a.locked===b.locked&&a.auto_proceed===b.auto_proceed}function evaluateRequirementCoverage(specContent,args2){if(!specContent)return null;let requirements=extractRequirements(specContent);if(requirements.length===0)return null;let covered=[],missing=[];for(let requirement of requirements){let mappedTaskIds=[],idPattern=new RegExp(`\\b${requirement.id}\\b`,"i");for(let phase of args2.phases)for(let task of phase.tasks){let taskText=`${task.description}
6236
6238
  ${task.acceptance??""}`,matchesFreeText=idPattern.test(taskText),matchesFrRefs=task.fr_refs?.includes(requirement.id)??!1;if(matchesFreeText||matchesFrRefs)mappedTaskIds.push(task.id)}let entry={id:requirement.id,obligation:requirement.obligation,text:requirement.text,mapped_task_ids:mappedTaskIds};if(mappedTaskIds.length>0)covered.push(entry);else missing.push(entry)}let blockingMissing=missing.filter((entry)=>entry.obligation==="MUST"||entry.obligation==="SHALL");return{status:blockingMissing.length>0?args2.confirm_requirement_coverage_gaps===!0?"override":"failed":"passed",total_requirements:requirements.length,covered_count:covered.length,missing_count:missing.length,blocking_missing_count:blockingMissing.length,covered,missing,blocking_missing:blockingMissing}}function detectPlaceholderContent(args2){let issues=[],placeholderPattern=/^\[\w[\w\s]*\]$/;if(placeholderPattern.test(args2.title.trim()))issues.push(`Plan title appears to be a template placeholder: "${args2.title}"`);for(let phase of args2.phases){if(placeholderPattern.test(phase.name.trim()))issues.push(`Phase ${phase.id} name appears to be a template placeholder: "${phase.name}"`);for(let task of phase.tasks)if(placeholderPattern.test(task.description.trim()))issues.push(`Task ${task.id} description appears to be a template placeholder: "${task.description}"`)}return issues}function validateTargetWorkspace(target,source){if(target===void 0||target===null)return`Target workspace is required: ${source} not provided`;let trimmed=target.trim();if(trimmed.length===0)return`Target workspace cannot be empty or whitespace: ${source}`;if(trimmed.replace(/\\/g,"/").includes(".."))return`Target workspace cannot contain path traversal: ${source} contains ".."`;return}async function executeSavePlan(args2,fallbackDir){let validationErrors=[];for(let phase of args2.phases){if(!Number.isInteger(phase.id)||phase.id<=0)validationErrors.push(`Phase ${phase.id} has invalid id: must be a positive integer`);let taskIdPattern=/^\d+\.\d+(\.\d+)*$/;for(let task of phase.tasks)if(!taskIdPattern.test(task.id))validationErrors.push(`Task '${task.id}' in phase ${phase.id} has invalid id format: must match N.M pattern (e.g. '1.1', '2.3')`)}if(validationErrors.length>0)return{success:!1,message:"Plan rejected: invalid phase or task IDs",errors:validationErrors,recovery_guidance:'Phase IDs must be positive integers: 1, 2, 3 (not 0, -1, or decimals). Task IDs must use N.M format: "1.1", "2.3", "3.1". Call save_plan again with corrected ids. Never write .swarm/plan.json or .swarm/plan.md directly.'};let placeholderIssues=detectPlaceholderContent(args2);if(placeholderIssues.length>0)return{success:!1,message:"Plan rejected: contains template placeholder content",errors:placeholderIssues,recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."};let targetWorkspace=args2.working_directory??fallbackDir,workspaceError=validateTargetWorkspace(targetWorkspace,args2.working_directory?"working_directory":"fallbackDir");if(workspaceError)return{success:!1,message:"Target workspace validation failed: provide working_directory parameter to save_plan",errors:[workspaceError],recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."};if(args2.working_directory&&fallbackDir){let resolvedTarget=path249.resolve(args2.working_directory),resolvedRoot=path249.resolve(fallbackDir),fallbackExists=!1;try{fs151.accessSync(resolvedRoot,fs151.constants.F_OK),fallbackExists=!0}catch{fallbackExists=!1}if(fallbackExists){if(resolvedTarget.startsWith(resolvedRoot+path249.sep))return{success:!1,message:`working_directory must be the project root. Got "${args2.working_directory}" (resolves to "${resolvedTarget}"), which is a subdirectory of fallback "${resolvedRoot}". Omit working_directory or pass the project root explicitly.`,errors:[`working_directory "${resolvedTarget}" is a subdirectory of fallback "${resolvedRoot}"`],recovery_guidance:`Pass working_directory: "${resolvedRoot}" or omit the field entirely.`}}}let specMtime,specHash,specContent;if(process.env.SWARM_SKIP_SPEC_GATE!=="1"){let spec=readEffectiveSpecSync(targetWorkspace);if(!spec)return{success:!1,message:"SPEC_REQUIRED: an effective spec (native .swarm/spec.md, OpenSpec openspec/specs or openspec/changes, or Spec-Kit .specify/) must exist before saving a plan.",errors:["No effective spec found — .swarm/spec.md is absent and no OpenSpec/Spec-Kit projection succeeded."],recovery_guidance:"Obtain explicit user consent, then run /swarm sdd project (agent-invocable) to materialize an effective spec from SDD sources. If .swarm/spec.md already exists, pass --overwrite after consent. Alternatively, run /swarm specify to author a native spec. Never write .swarm/plan.json or .swarm/plan.md directly."};specMtime=spec.mtime??void 0,specHash=spec.hash,specContent=spec.content;try{let snapshotPath=path249.join(targetWorkspace,".swarm","spec-snapshot.md");await fs151.promises.writeFile(snapshotPath,spec.content,"utf-8")}catch{}}if(process.env.SWARM_SKIP_GATE_SELECTION!=="1"){let contextPath=path249.join(targetWorkspace,".swarm","context.md"),contextContent="";try{contextContent=await fs151.promises.readFile(contextPath,"utf8")}catch{}if(!contextContent.includes("## Pending QA Gate Selection")){let candidatePlanId=derivePlanId({swarm:args2.swarm_id,title:args2.title}),existingProfile=null;try{existingProfile=getProfile(targetWorkspace,candidatePlanId)}catch{}if(!existingProfile)return{success:!1,message:'QA_GATE_SELECTION_REQUIRED: QA gate selection has not been completed. Present the gate selection question to the user (step 5b of MODE: SPECIFY or Phase 6 of MODE: BRAINSTORM), write their response to .swarm/context.md under "## Pending QA Gate Selection", then retry save_plan.',errors:["Missing ## Pending QA Gate Selection in .swarm/context.md","No existing QaGateProfile found for this plan"],recovery_guidance:"Do not call set_qa_gates with assumed values. Present the gate dialogue, wait for the user's answer, write it to context.md, then retry save_plan."}}}let requirementCoverage=evaluateRequirementCoverage(specContent,args2);if(requirementCoverage?.status==="failed"&&args2.confirm_requirement_coverage_gaps!==!0)return{success:!1,message:"REQUIREMENT_COVERAGE_GAPS: save_plan rejected because required FR-### MUST/SHALL requirements are not mapped to any task.",errors:requirementCoverage.blocking_missing.map((requirement)=>`${requirement.id} (${requirement.obligation}): ${requirement.text}`),recovery_guidance:"Add each required FR-### id to a task description or acceptance criterion, or retry with confirm_requirement_coverage_gaps: true only after surfacing the gaps to the user.",requirement_coverage:requirementCoverage};let dir=targetWorkspace,existingStatusMap=new Map,priorTaskIds=new Set,preservedExecutionProfile;{let existing=null;try{existing=await loadPlanJsonOnly(dir)}catch{}if(existing){for(let phase of existing.phases)for(let task of phase.tasks)priorTaskIds.add(task.id);if(!args2.reset_statuses)for(let phase of existing.phases)for(let task of phase.tasks)existingStatusMap.set(task.id,task.status);if(args2.confirm_identity_change!==!0){let existingId=derivePlanId(existing),incomingId=derivePlanId({swarm:args2.swarm_id,title:args2.title});if(existingId!==incomingId)return{success:!1,message:"PLAN_IDENTITY_MISMATCH: The incoming plan identity does not match the existing plan. To overwrite with a new identity, set confirm_identity_change: true.",errors:[`Existing plan identity: ${existingId} (swarm: "${existing.swarm}", title: "${existing.title}")`,`Incoming plan identity: ${incomingId} (swarm: "${args2.swarm_id}", title: "${args2.title}")`],recovery_guidance:"Verify the title and swarm_id match the intended plan. If the identity change is intentional, retry with confirm_identity_change: true. Never write .swarm/plan.json or .swarm/plan.md directly."}}if(existing.execution_profile?.locked){if(args2.execution_profile!==void 0&&!args2.reset_statuses){let requestedProfile=ExecutionProfileSchema.safeParse({...existing.execution_profile,...args2.execution_profile});if(!requestedProfile.success)return{success:!1,message:"Invalid execution_profile: schema validation failed",errors:requestedProfile.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`),recovery_guidance:"Check execution_profile fields: parallelization_enabled (boolean), max_concurrent_tasks (integer 1-64), council_parallel (boolean), locked (boolean), auto_proceed (boolean)."};if(executionProfilesEqual(existing.execution_profile,requestedProfile.data))preservedExecutionProfile=existing.execution_profile;else return{success:!1,message:"EXECUTION_PROFILE_LOCKED: The execution_profile for this plan is locked and cannot be changed.",errors:["execution_profile.locked is true — to change the profile you must first unlock it via a separate plan revision that explicitly sets locked: false, or reset the plan with reset_statuses."],recovery_guidance:"Remove the execution_profile field from this save_plan call to preserve the locked profile, or use reset_statuses: true to start fresh (this clears the lock). Never modify execution_profile directly in plan.json."}}else if(!args2.reset_statuses)preservedExecutionProfile=existing.execution_profile}else preservedExecutionProfile=existing.execution_profile}}let resolvedProfile=preservedExecutionProfile;if(args2.execution_profile!==void 0){let merged={...preservedExecutionProfile??{},...args2.execution_profile},parsed=ExecutionProfileSchema.safeParse(merged);if(!parsed.success)return{success:!1,message:"Invalid execution_profile: schema validation failed",errors:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`),recovery_guidance:"Check execution_profile fields: parallelization_enabled (boolean), max_concurrent_tasks (integer 1-64), council_parallel (boolean), locked (boolean)."};resolvedProfile=parsed.data}let incomingTaskIds=new Set;for(let phase of args2.phases)for(let task of phase.tasks)incomingTaskIds.add(task.id);let missingTaskIds=[];for(let id of priorTaskIds)if(!incomingTaskIds.has(id))missingTaskIds.push(id);let rawRemovedIds=args2.removed_task_ids??[];if(rawRemovedIds.length>0){let seen=new Set;for(let id of rawRemovedIds){if(seen.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains duplicate entries",errors:[`Duplicate id in removed_task_ids: "${id}"`],recovery_guidance:"Deduplicate removed_task_ids and retry save_plan."};seen.add(id)}for(let id of rawRemovedIds)if(incomingTaskIds.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains a task that also appears in args.phases",errors:[`Task "${id}" appears in both removed_task_ids and args.phases — these are contradictory`],recovery_guidance:"A task cannot be both kept and removed in the same save_plan call. Either drop it from args.phases or remove it from removed_task_ids."};for(let id of rawRemovedIds)if(!priorTaskIds.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains an id that was not in the prior plan",errors:[`Task "${id}" is in removed_task_ids but not present in the prior plan`],recovery_guidance:"Re-read the prior plan and update removed_task_ids to only list tasks that actually existed."}}let resolvedRemovedIds=[...rawRemovedIds],resolvedRemovalReason=args2.removal_reason;if(args2.reset_statuses===!0&&missingTaskIds.length>0){if(args2.confirm_destructive_reset!==!0)return{success:!1,message:"PLAN_DESTRUCTIVE_RESET_NOT_CONFIRMED: reset_statuses with missing tasks requires confirm_destructive_reset: true",errors:[`reset_statuses: true would drop ${missingTaskIds.length} task(s) from the prior plan: ${missingTaskIds.join(", ")}`],recovery_guidance:"Surface the list of dropped tasks to the user and confirm intent before retrying. Pass confirm_destructive_reset: true (with reset_statuses: true) to acknowledge the destructive reset, or list removed_task_ids explicitly with a removal_reason."};if(rawRemovedIds.length===0)resolvedRemovedIds=[...missingTaskIds],resolvedRemovalReason="destructive reset acknowledged"}if(resolvedRemovedIds.length>0){if((resolvedRemovalReason??"").trim().length===0)return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removal_reason is required when removed_task_ids is non-empty",errors:["removal_reason must be a non-empty, non-whitespace string"],recovery_guidance:"Provide a removal_reason describing why these tasks are being dropped."}}if(missingTaskIds.length>0){let ackSet=new Set(resolvedRemovedIds),unacked=missingTaskIds.filter((id)=>!ackSet.has(id));if(unacked.length>0)return{success:!1,message:"PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: this save would silently drop tasks from the prior plan",errors:[`The following prior tasks are missing from the new save and were not listed in removed_task_ids: ${unacked.join(", ")}`],recovery_guidance:`Re-read the current plan, then retry save_plan with removed_task_ids: ${JSON.stringify(unacked)} and a non-empty removal_reason. Tasks not yet finished (status pending/in_progress/blocked) MUST NOT be removed without explicit user confirmation.`}}let plan={schema_version:"1.0.0",title:args2.title,swarm:args2.swarm_id,migration_status:"native",current_phase:args2.phases[0]?.id,specMtime,specHash,...resolvedProfile!==void 0?{execution_profile:resolvedProfile}:{},phases:args2.phases.map((phase)=>{return{id:phase.id,name:phase.name,status:"pending",tasks:phase.tasks.map((task)=>{return{id:task.id,phase:phase.id,status:existingStatusMap.get(task.id)??"pending",size:task.size??"small",description:task.description,depends:task.depends??[],acceptance:task.acceptance,files_touched:[],fr_refs:task.fr_refs}})}})},tasksCount=plan.phases.reduce((acc,phase)=>acc+phase.tasks.length,0),lockTaskId=`save-plan-${Date.now()}`,planFilePath="plan.json";try{let lockResult=await tryAcquireLock(dir,planFilePath,"architect",lockTaskId);if(!lockResult.acquired)return{success:!1,message:`Plan write blocked: file is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`,errors:["Concurrent plan write detected — retry after the current write completes"],recovery_guidance:"Wait a moment and retry save_plan. The lock will expire automatically if the holding agent fails."};try{await savePlan(dir,plan,{preserveCompletedStatuses:!args2.reset_statuses,...resolvedRemovedIds.length>0?{acknowledged_removals:{ids:resolvedRemovedIds,reason:(resolvedRemovalReason??"").trim(),source:"save_plan_tool"}}:{}});let savedPlan=await loadPlanJsonOnly(dir);if(savedPlan)await takeSnapshotWithRetry(dir,savedPlan);if(resolvedProfile!==void 0&&savedPlan){let planId=derivePlanId(plan),planHashAfter=computePlanHash(savedPlan);if(JSON.stringify(resolvedProfile)!==JSON.stringify(preservedExecutionProfile))await appendLedgerEvent(dir,{event_type:"execution_profile_set",source:"save_plan",plan_id:planId,payload:{execution_profile:resolvedProfile}},{planHashAfter}).catch(()=>{});let wasAlreadyLocked=preservedExecutionProfile?.locked===!0;if(resolvedProfile.locked&&!wasAlreadyLocked)await appendLedgerEvent(dir,{event_type:"execution_profile_locked",source:"save_plan",plan_id:planId},{planHashAfter}).catch(()=>{})}await writeCheckpoint(dir).catch(()=>{});try{let markerPath=path249.join(dir,".swarm",".plan-write-marker"),marker=JSON.stringify({source:"save_plan",timestamp:new Date().toISOString(),phases_count:plan.phases.length,tasks_count:tasksCount});await fs151.promises.writeFile(markerPath,marker,"utf8")}catch{}let warnings=[],criticReviewFound=!1;for(let[,session]of swarmState.agentSessions)if(session.phaseAgentsDispatched?.has("critic")||session.lastCompletedPhaseAgentsDispatched?.has("critic")){criticReviewFound=!0;break}if(!criticReviewFound)warnings.push("No critic review detected before plan save. Consider delegating to critic for plan validation.");if(requirementCoverage?.status==="override"){let missingIds=requirementCoverage.blocking_missing.map((requirement)=>requirement.id).join(", ");warnings.push(`Requirement coverage override used. Missing required FR mappings: ${missingIds}`)}return{success:!0,message:"Plan saved successfully",plan_path:path249.join(dir,".swarm","plan.json"),phases_count:plan.phases.length,tasks_count:tasksCount,...requirementCoverage?{requirement_coverage:requirementCoverage}:{},...resolvedProfile!==void 0?{execution_profile:resolvedProfile}:{},...warnings.length>0?{warnings}:{}}}finally{if(lockResult.acquired&&lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}catch(error93){if(error93 instanceof PlanTaskRemovalNotAcknowledgedError){let ids=error93.missingTasks.map((t)=>t.id);return{success:!1,message:"PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: this save would silently drop tasks from the prior plan",errors:[error93.message],recovery_guidance:`Re-read the current plan, then retry save_plan with removed_task_ids: ${JSON.stringify(ids)} and a non-empty removal_reason.`}}return{success:!1,message:"Failed to save plan: retry with save_plan after resolving the error above",errors:[error93 instanceof Error?error93.message:String(error93)],recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."}}}var save_plan=createSwarmTool({description:"Save or revise a structured implementation plan to .swarm/plan.json and .swarm/plan.md. "+"Use this tool for all structural plan changes on an existing plan (adding/removing tasks, updating descriptions, dependencies, or phase names) — existing task statuses are preserved by default (set reset_statuses: true to start fresh). "+"Task descriptions and phase names MUST contain real content from the spec — "+"bracket placeholders like [task] or [Project] will be rejected.",args:{title:exports_external.string().min(1).describe("Plan title — the REAL project name from the spec. NOT a placeholder like [Project]."),swarm_id:exports_external.string().min(1).describe('Swarm identifier (e.g. "mega")'),phases:exports_external.array(exports_external.object({id:exports_external.number().int().min(1).describe("Phase number — a positive integer starting at 1. Use 1, 2, 3, etc."),name:exports_external.string().min(1).describe("Descriptive phase name derived from the spec"),tasks:exports_external.array(exports_external.object({id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M format, e.g. "1.1"').describe('Task ID in N.M format, e.g. "1.1", "2.3"'),description:exports_external.string().min(1).describe("Specific task description from the spec. NOT a placeholder like [task]."),size:exports_external.enum(["small","medium","large"]).optional().describe("Task size estimate (default: small)"),depends:exports_external.array(exports_external.string()).optional().describe('Task IDs this task depends on, e.g. ["1.1", "1.2"]'),acceptance:exports_external.string().optional().describe("Acceptance criteria for this task"),fr_refs:exports_external.array(exports_external.string()).optional().describe('Spec FR-###/SC-### IDs this task maps to, e.g. ["FR-001", "SC-002"]')})).min(1).describe("Tasks in this phase")})).min(1).describe("Implementation phases"),working_directory:exports_external.string().optional().describe("Working directory (explicit path, required - no fallback)"),reset_statuses:exports_external.boolean().optional().describe("When true, reset ALL task statuses to pending regardless of prior completion state. Use only when deliberately re-planning a phase from scratch. Default false (preserves existing task statuses across plan revisions)."),removed_task_ids:exports_external.array(exports_external.string()).optional().describe("Task IDs that are present in the prior plan but intentionally being removed by this save. Every task missing from `phases` MUST be enumerated here, otherwise save_plan rejects with PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED. Tasks not yet finished (status pending/in_progress/blocked) MUST NOT be removed without explicit user confirmation."),removal_reason:exports_external.string().optional().describe("Required when removed_task_ids is non-empty. Human-readable reason recorded on each task_removed ledger event."),confirm_destructive_reset:exports_external.boolean().optional().describe("Required when reset_statuses is true AND at least one task is missing from the new plan. Set true to acknowledge that the destructive reset drops unfinished work. When set together with reset_statuses, save_plan auto-populates removed_task_ids from the missing set."),confirm_identity_change:exports_external.boolean().optional().describe("When true, allows overwriting an existing plan that has a different identity (swarm_id + title). Without this flag, save_plan rejects with PLAN_IDENTITY_MISMATCH if the identity differs."),confirm_requirement_coverage_gaps:exports_external.boolean().optional().describe("When true, allows saving a plan even when required FR-### MUST/SHALL requirements from the effective spec are not explicitly mapped in task descriptions or acceptance criteria. Use only after surfacing the structured requirement_coverage gaps to the user."),execution_profile:exports_external.object({parallelization_enabled:exports_external.boolean().optional().describe("When true, enables parallel task dispatch for this plan. Default false (serial)."),max_concurrent_tasks:exports_external.number().int().min(1).max(64).optional().describe("Maximum tasks that may run concurrently when parallelization is enabled. Default 10."),council_parallel:exports_external.boolean().optional().describe("When true, council review phases may run in parallel. Default true."),locked:exports_external.boolean().optional().describe("When true, locks the profile — future save_plan calls that include "+"execution_profile will be rejected (fail-closed). Unlock by resetting the plan (reset_statuses: true)."),auto_proceed:exports_external.boolean().optional().describe("When true, the architect advances to the next phase automatically without asking for confirmation. Default false.")}).optional().describe("Architect-facing concurrency controls. Once locked, cannot be changed without resetting. Omit to preserve the existing profile.")},execute:async(args2,_directory)=>{return JSON.stringify(await executeSavePlan(args2,_directory),null,2)}});init_zod();init_manager2();import*as fs152 from"node:fs";import*as path250 from"node:path";init_utils();init_logger();function parsePubspecLock(content){let components=[];if(!content.match(/^packages:\s*$/m))return components;let lines=content.split(`
6237
6239
  `),inPackages=!1,currentPackage="",currentVersion="";for(let i=0;i<lines.length;i++){let line=lines[i],trimmed=line.replace(/^ {2}/,"");if(trimmed==="packages:"||trimmed.startsWith("packages:")){inPackages=!0;continue}if(!inPackages)continue;let packageMatch=line.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(packageMatch){if(currentPackage&&currentVersion)components.push({name:currentPackage,version:currentVersion,type:"library",purl:generatePurl("pub",currentPackage,currentVersion)});currentPackage=packageMatch[1],currentVersion="";continue}if(currentPackage&&line.includes("version:")){let versionMatch=line.match(/version:\s*"([^"]+)"/);if(versionMatch)currentVersion=versionMatch[1]}}if(currentPackage&&currentVersion)components.push({name:currentPackage,version:currentVersion,type:"library",purl:generatePurl("pub",currentPackage,currentVersion)});return components}function parsePubspecYaml(content){let components=[],lines=content.split(`
6238
6240
  `),inDependencies=!1,inDevDependencies=!1;for(let line of lines){let trimmed=line.trim();if(trimmed==="dependencies:"){inDependencies=!0,inDevDependencies=!1;continue}if(trimmed==="dev_dependencies:"){inDependencies=!1,inDevDependencies=!0;continue}if(trimmed==="dependencies_overrides:"||trimmed==="dev_dependencies_overrides:"||trimmed.startsWith("environment:")){inDependencies=!1,inDevDependencies=!1;continue}if(!inDependencies&&!inDevDependencies)continue;if(!trimmed||trimmed.startsWith("#")||trimmed.includes("sdk:"))continue;let match=trimmed.match(/^([a-zA-Z0-9_-]+):\s*(.+)?$/);if(match){let name=match[1],value=match[2]||"";if(name==="flutter"||name==="environment")continue;let version5="unknown",caretMatch=value.match(/\^?([\d.]+)/);if(caretMatch)version5=caretMatch[1];let hostedMatch=value.match(/version:\s*"?\^?([\d.]+)/);if(hostedMatch)version5=hostedMatch[1];if(name&&version5!=="unknown")components.push({name,version:version5,type:"library",purl:generatePurl("pub",name,version5)})}}return components}var dartDetectors=[{name:"Dart pubspec.lock",patterns:["pubspec.lock"],detect:(_filePath,content)=>{return parsePubspecLock(content)}},{name:"Dart pubspec.yaml",patterns:["pubspec.yaml"],detect:(_filePath,content)=>{return parsePubspecYaml(content)}}];function parsePackagesLockJson(content){let components=[];try{let lock=JSON.parse(content),targets=lock.targets||lock.dependencies||{};for(let[_target,targetDeps]of Object.entries(targets)){if(!targetDeps||typeof targetDeps!=="object")continue;for(let[pkgSpec,pkgData]of Object.entries(targetDeps)){if(!pkgSpec.includes("/"))continue;let[name,version5]=pkgSpec.split("/"),pkg=pkgData;if(name&&version5)components.push({name,version:version5,type:"library",purl:generatePurl("nuget",name,version5),license:pkg.license})}}}catch{}return components}function parsePaketLock(content){let components=[],lines=content.split(`
@@ -6291,7 +6293,7 @@ ${scopeWarning}`:scopeWarning}}function recoverTaskStateFromDelegations(taskId,d
6291
6293
  `).trim(),text=bodyText.length>MAX_TEXT_LENGTH2?`${bodyText.slice(0,MAX_TEXT_LENGTH2)}…`:bodyText,textTruncated=outcome.truncated||bodyText.length>MAX_TEXT_LENGTH2,evidence=await captureFetchEvidence(dirResult.directory,outcome.finalUrl,title,text),ok2={success:!0,url:parsed.data.url,finalUrl:outcome.finalUrl,status:outcome.status,contentType:outcome.contentType??void 0,title,text,truncated:textTruncated,bytesReturned:outcome.bytes.byteLength,evidence};return JSON.stringify(ok2,null,2)}});async function captureFetchEvidence(directory,url3,title,text){try{let written=await _internals173.writeEvidenceDocuments(directory,[{sourceType:"crawl",url:url3,title,text,createdBy:"web_fetch"}]);return{stored:written.records.length>0,ref:written.refs[0],path:written.path}}catch(err2){return{stored:!1,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals173={httpRequest:performHttpRequest,dnsLookup:lookup,loadPluginConfig,writeEvidenceDocuments};init_zod();init_loader();var CURRENT_INTENT_RE=/\b(?:latest|current|currently|today|now|newest|recent|recently|up\s*-?\s*to\s*-?\s*date|this\s+(?:week|month|year)|as\s+of\s+(?:today|now))\b/i,HISTORICAL_INTENT_RE=/\b(?:history|historical|archive|archived|in\s+20\d{2}|during\s+20\d{2}|from\s+20\d{2}|for\s+20\d{2}|as\s+of\s+20\d{2})\b/i;function applySearchQueryPolicy(rawQuery,now=new Date){let originalQuery=rawQuery,query=rawQuery.trim().replace(/\s+/g," "),currentYear=now.getUTCFullYear(),temporalIntent=detectTemporalIntent(query),removedStaleYears=[];if(temporalIntent==="current")query=removeTrailingStaleCutoffYears(query,currentYear,removedStaleYears);return{originalQuery,query,temporalIntent,freshness:temporalIntent==="current"?chooseFreshness(query):void 0,removedStaleYears}}function detectTemporalIntent(query){if(CURRENT_INTENT_RE.test(query))return"current";if(HISTORICAL_INTENT_RE.test(query))return"historical";return"unspecified"}function chooseFreshness(query){if(/\b(?:today|now|as\s+of\s+(?:today|now))\b/i.test(query))return"day";if(/\bthis\s+week\b/i.test(query))return"week";if(/\b(?:recent|recently|this\s+month)\b/i.test(query))return"month";return"year"}function removeTrailingStaleCutoffYears(query,currentYear,removed){return query.replace(/\s+(?:as\s+of\s+)?(20\d{2})\s*$/i,(match,year)=>{if(Number(year)>=currentYear)return match;return removed.push(year),""}).replace(/\s+/g," ").trim()}class WebSearchError extends Error{cause;constructor(message,cause){super(message);this.cause=cause;this.name="WebSearchError"}}class WebSearchConfigError extends Error{constructor(message){super(message);this.name="WebSearchConfigError"}}class TavilyProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let requestBody={api_key:this.apiKey,query,max_results:maxResults,search_depth:"advanced"};if(options.freshness)requestBody.time_range=options.freshness;let response;try{response=await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(requestBody)})}catch(err2){throw new WebSearchError(`Tavily network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Tavily HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Tavily returned non-JSON response",err2)}let results=body?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.content==="string").map((r)=>({title:r.title,url:r.url,snippet:r.content,query}))}}class BraveProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let url3=new URL("https://api.search.brave.com/res/v1/web/search");url3.searchParams.set("q",query),url3.searchParams.set("count",String(maxResults));let freshness=toBraveFreshness(options.freshness);if(freshness)url3.searchParams.set("freshness",freshness);let response;try{response=await fetch(url3.toString(),{method:"GET",headers:{"X-Subscription-Token":this.apiKey,Accept:"application/json"}})}catch(err2){throw new WebSearchError(`Brave network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Brave HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Brave returned non-JSON response",err2)}let results=body?.web?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.description==="string").map((r)=>({title:r.title,url:r.url,snippet:r.description,query}))}}function toBraveFreshness(freshness){switch(freshness){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return}}function resolveApiKey(provider,configKey){if(configKey&&configKey.length>0)return configKey;let envName=provider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY",fromEnv=process.env[envName];return fromEnv&&fromEnv.length>0?fromEnv:void 0}function createWebSearchProvider(config3){let apiKey=resolveApiKey(config3.searchProvider,config3.searchApiKey);if(!apiKey){let envName=config3.searchProvider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY";throw new WebSearchConfigError(`No API key for search provider "${config3.searchProvider}". Set council.general.searchApiKey in the resolved config (global ~/.config/opencode/opencode-swarm.json, project .opencode/opencode-swarm.json override) or export ${envName}.`)}switch(config3.searchProvider){case"tavily":return new TavilyProvider(apiKey);case"brave":return new BraveProvider(apiKey)}}init_create_tool();init_resolve_working_directory();var MAX_RESULTS_HARD_CAP=10,ArgsSchema7=exports_external.object({query:exports_external.string().min(1).max(500),max_results:exports_external.number().int().min(1).max(20).optional(),freshness:exports_external.enum(["auto","none","day","week","month","year"]).default("auto"),working_directory:exports_external.string().optional()}),web_search=createSwarmTool({description:"External web search for architect-driven council research, SME domain research, and skill-improver research. Returns titled results with snippets and URLs. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents and by SME to evaluate external skill/source candidates. Normalizes current-intent queries, strips trailing stale cutoff years, and applies provider freshness filters by default. Requires council.general.enabled and a configured search API key (Tavily or Brave) in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. max_results is capped at 10 with default from council.general.maxSourcesPerMember.",args:{query:exports_external.string().min(1).max(500).describe("Search query string (1–500 characters)."),freshness:exports_external.enum(["auto","none","day","week","month","year"]).optional().describe('Optional freshness filter. Query normalization always runs; "auto" infers provider freshness from current/recency terms, while "none" disables provider freshness filtering.'),max_results:exports_external.number().int().min(1).max(20).optional().describe(`Number of results to request (1–20). Hard-capped at ${MAX_RESULTS_HARD_CAP}. Defaults to council.general.maxSourcesPerMember.`),working_directory:exports_external.string().optional().describe("Project root for config resolution. Optional.")},execute:async(args2,directory)=>{let parsed=ArgsSchema7.safeParse(args2);if(!parsed.success){let fail={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail,null,2)}let dirResult=resolveWorkingDirectory(parsed.data.working_directory,directory);if(!dirResult.success){let fail={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail,null,2)}let generalConfig=loadPluginConfig(dirResult.directory).council?.general;if(!generalConfig||generalConfig.enabled!==!0)return JSON.stringify({success:!1,reason:"council_general_disabled",message:"web_search is disabled - set council.general.enabled: true in the resolved config: global ~/.config/opencode/opencode-swarm.json or project .opencode/opencode-swarm.json."},null,2);let requested=parsed.data.max_results??generalConfig.maxSourcesPerMember,maxResults=Math.min(requested,MAX_RESULTS_HARD_CAP),policy=applySearchQueryPolicy(parsed.data.query),requestedFreshness=parsed.data.freshness??"auto",freshness=requestedFreshness==="auto"?policy.freshness:requestedFreshness==="none"?void 0:requestedFreshness,provider;try{provider=createWebSearchProvider(generalConfig)}catch(err2){let fail={success:!1,reason:err2 instanceof WebSearchConfigError?"missing_api_key":"provider_init_failed",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail,null,2)}try{let results=await provider.search(policy.query,maxResults,{freshness}),evidence=await captureSearchEvidence(dirResult.directory,policy.query,results),scannedResults=results.map(({title,url:url3,snippet})=>{let titleScan=scanExternalContent(title,{trustLevel:"low"}),snippetScan=scanExternalContent(snippet,{trustLevel:"low"}),threatLevel=titleScan.threatLevel==="error"||snippetScan.threatLevel==="error"?"error":titleScan.threatLevel==="warning"||snippetScan.threatLevel==="warning"?"warning":"none";return{title:titleScan.clean?title:titleScan.neutralized,url:url3,snippet:snippetScan.clean?snippet:snippetScan.neutralized,evidenceRef:evidence.refByUrl.get(url3),threatLevel}}),ok2={success:!0,query:policy.query,originalQuery:policy.originalQuery,temporalIntent:policy.temporalIntent,freshness,removedStaleYears:policy.removedStaleYears,totalResults:results.length,results:scannedResults,evidence:{stored:evidence.stored,path:evidence.path,refs:evidence.refs,error:evidence.error}};return JSON.stringify(ok2,null,2)}catch(err2){let fail={success:!1,reason:err2 instanceof WebSearchError?"search_failed":"unknown",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail,null,2)}}});async function captureSearchEvidence(directory,query,results){try{let written=await _internals174.writeEvidenceDocuments(directory,results.map((result)=>({sourceType:"web_search",query,title:result.title,url:result.url,snippet:result.snippet,createdBy:"web_search"}))),refByUrl=new Map;for(let record3 of written.records)if(record3.url)refByUrl.set(record3.url,record3.ref);return{stored:written.records.length>0,path:written.path,refs:written.refs,refByUrl}}catch(err2){return{stored:!1,refs:[],refByUrl:new Map,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals174={writeEvidenceDocuments};init_zod();init_loader();init_schema();init_curator_llm_factory();init_knowledge_curator();init_skill_generator();init_schema3();init_store2();init_create_tool();init_resolve_working_directory();import*as path263 from"node:path";var FindingSchema2=exports_external.object({severity:exports_external.enum(["low","medium","high","critical"]),category:exports_external.string().min(1),agents:exports_external.array(exports_external.string().min(1)).default([]),tasks:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),description:exports_external.string().min(1),recommendation:exports_external.string().default("")}),KnowledgeRecommendationSchema2=exports_external.object({lesson:exports_external.string().min(1),target_agents:exports_external.array(exports_external.string().min(1)).default([]),confidence:exports_external.number().min(0).max(1).default(0.5),evidence_refs:exports_external.array(exports_external.string().min(1)).default([])}),ArgsSchema8=exports_external.object({phase:exports_external.number().int().min(0).max(999),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),findings:exports_external.array(FindingSchema2).default([]),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).default([]),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional(),provenance_session_id:exports_external.string().min(1).optional()}),write_architecture_supervisor_evidence=createSwarmTool({description:"Persist the architecture supervisor verdict for a phase. PREREQUISITE: dispatch critic_architecture_supervisor as an Agent task with the phase + agent summaries, collect its strict-JSON verdict (verdict/findings/knowledge_recommendations), then call this tool with those values. Writes .swarm/evidence/{phase}/"+"architecture-supervisor.json. This tool persists only — it does not contact the "+"supervisor. Architect-only; config-gated via architectural_supervision.enabled.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number being reviewed."),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]).describe("Supervisor verdict."),findings:exports_external.array(FindingSchema2).optional().describe("System-level findings from the supervisor."),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).optional().describe("Durable lessons proposed by the supervisor."),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)."),provenance_session_id:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance).")},execute:async(rawArgs,directory)=>{let parsed=ArgsSchema8.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let provenance=args2.provenance_agent_name||args2.provenance_session_id?{agent_name:args2.provenance_agent_name,session_id:args2.provenance_session_id,captured_at:new Date().toISOString()}:void 0,report={schema_version:SUMMARY_SCHEMA_VERSION,phase:args2.phase,verdict:args2.verdict,findings:args2.findings,knowledge_recommendations:args2.knowledge_recommendations,created_at:new Date().toISOString(),...provenance?{provenance}:{}},evidencePath=writeSupervisorReport(dirResult.directory,report),knowledgeProposed=0,knowledgeReinforced=0,knowledgeQuarantined=0;try{let config3=loadPluginConfig(dirResult.directory);if(config3.architectural_supervision?.persist_knowledge_recommendations&&args2.knowledge_recommendations.length>0){let knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{}),lessons=args2.knowledge_recommendations.map((r)=>r.lesson),result=await curateAndStoreSwarm(lessons,path263.basename(dirResult.directory),{phase_number:args2.phase},dirResult.directory,knowledgeConfig,{skipAutoPromotion:!0,llmDelegate:createCuratorLLMDelegate(dirResult.directory,"phase"),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});knowledgeProposed=result.stored,knowledgeReinforced=result.reinforced,knowledgeQuarantined=result.quarantined}}catch{}let skillsProposed=0;try{let config3=loadPluginConfig(dirResult.directory),hasFailureLoop=args2.findings.some((f)=>f.category==="failure_loop");if(config3.architectural_supervision?.persist_knowledge_recommendations&&hasFailureLoop)skillsProposed=(await generateSkills({directory:dirResult.directory,mode:"draft"})).written.length}catch{}return JSON.stringify({success:!0,phase:args2.phase,verdict:args2.verdict,findings_count:args2.findings.length,knowledge_proposed:knowledgeProposed,knowledge_reinforced:knowledgeReinforced,knowledge_quarantined:knowledgeQuarantined,skills_proposed:skillsProposed,evidence_path:evidencePath},null,2)}});init_zod();init_qa_gate_profile();import fs162 from"node:fs";import path264 from"node:path";function normalizeVerdict2(verdict){if(!LIVE_VERDICT_SET_2.includes(verdict))throw Error(`Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION', got '${verdict}'`);switch(verdict){case"APPROVED":return"approved";case"NEEDS_REVISION":return"rejected";default:return verdict.toLowerCase()}}function normalizeVerdict4(verdict){if(!LIVE_VERDICT_SET_4.includes(verdict))throw Error(`Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP', got '${verdict}'`);switch(verdict){case"PASS":return"pass";case"WARN":return"warn";case"FAIL":return"fail";case"SKIP":return"skip";default:return verdict.toLowerCase()}}var LIVE_VERDICT_SET_2=["APPROVED","NEEDS_REVISION"],LIVE_VERDICT_SET_4=["PASS","WARN","FAIL","SKIP"],VERDICT_SET_2=LIVE_VERDICT_SET_2,VERDICT_SET_4=LIVE_VERDICT_SET_4;function isAcceptedVerdict2(v){return LIVE_VERDICT_SET_2.includes(v)}function isAcceptedVerdict4(v){return LIVE_VERDICT_SET_4.includes(v)}init_utils2();init_ledger();init_manager();init_utils3();init_logger();init_create_tool();async function executeWriteDriftEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals175.normalizeVerdict2(args2.verdict),provenance=args2.provenanceAgentName||args2.provenanceSessionId?{agent_name:args2.provenanceAgentName,session_id:args2.provenanceSessionId,captured_at:new Date().toISOString()}:void 0,evidenceContent={entries:[{type:"drift-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),requirementCoverage:args2.requirementCoverage,...provenance?{provenance}:{}}]},filename="drift-verifier.json",relativePath2=path264.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path264.dirname(validatedPath);try{await fs162.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path264.join(evidenceDir,`.${filename}.tmp`);await fs162.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs162.promises.rename(tempPath,validatedPath);let snapshotInfo,snapshotError,qaProfileLocked,qaProfileLockError;if(normalizedVerdict==="approved")try{let currentPlan=await loadPlanJsonOnly(directory);if(currentPlan){let snapshotEvent=await takeSnapshotEvent(directory,currentPlan,{source:"critic_approved",approvalMetadata:{phase,verdict:"APPROVED",summary:summary.trim(),approved_at:new Date().toISOString()}});snapshotInfo={seq:snapshotEvent.seq,timestamp:snapshotEvent.timestamp};try{let planId=derivePlanId(currentPlan),locked=lockProfile(directory,planId,snapshotEvent.seq);qaProfileLocked={plan_id:planId,locked_at:locked.locked_at??"",locked_by_snapshot_seq:locked.locked_by_snapshot_seq??-1}}catch(lockErr){let msg=lockErr instanceof Error?lockErr.message:String(lockErr);if(!/No QA gate profile/i.test(msg))qaProfileLockError=msg,log("[write_drift_evidence] QA gate profile lock failed:",msg)}}else snapshotError="plan.json not available for snapshot"}catch(err2){snapshotError=err2 instanceof Error?err2.message:String(err2),log("[write_drift_evidence] critic-approved snapshot failed:",snapshotError)}return JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Drift evidence written to .swarm/evidence/${phase}/drift-verifier.json`,approvedSnapshot:snapshotInfo,snapshotError,qaProfileLocked,qaProfileLockError},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals175={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2},write_drift_evidence=createSwarmTool({description:"Write drift verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/drift-verifier.json. Use this after critic_drift_verifier delegation to persist the verification result.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the drift verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the drift verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the drift verification"),requirementCoverage:exports_external.string().optional().describe("Requirement coverage report from req_coverage tool (JSON string)"),provenanceAgentName:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)"),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let writeDriftEvidenceArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),requirementCoverage:args2.requirementCoverage!==void 0?String(args2.requirementCoverage):void 0,provenanceAgentName:args2.provenanceAgentName!==void 0?String(args2.provenanceAgentName):void 0,provenanceSessionId:args2.provenanceSessionId!==void 0?String(args2.provenanceSessionId):void 0};return await executeWriteDriftEvidence(writeDriftEvidenceArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_loader();import fs163 from"node:fs";import path265 from"node:path";init_utils2();init_config2();init_gateway();init_reward_capture();init_ledger();init_manager();init_utils3();init_logger();init_create_tool();var FINAL_COUNCIL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],VerdictSchema3=exports_external.object({agent:exports_external.enum(FINAL_COUNCIL_MEMBERS),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema9=exports_external.object({phase:exports_external.number().int().min(1).max(1000),projectSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema3).min(1).max(5)});function normalizeFinalVerdict(verdict,requiredFixesCount){if(verdict==="APPROVE")return"approved";if(verdict==="REJECT")return"rejected";return requiredFixesCount>0?"rejected":"concerns"}async function executeWriteFinalCouncilEvidence(args2,directory,ctx){let parsed=ArgsSchema9.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let input=parsed.data,config3=loadPluginConfig(directory),requiredMembers=FINAL_COUNCIL_MEMBERS.length,distinctMembers=new Set(input.verdicts.map((v)=>v.agent)),membersVoted=[...distinctMembers],membersAbsent=FINAL_COUNCIL_MEMBERS.filter((m)=>!distinctMembers.has(m));if(membersVoted.length<requiredMembers)return JSON.stringify({success:!1,reason:"insufficient_quorum",message:`Final council quorum not met: ${membersVoted.length} of ${requiredMembers} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members with project-scoped context and collect their verdicts before calling write_final_council_evidence.`,membersVoted,membersAbsent,quorumRequired:requiredMembers},null,2);let synthesis=synthesizeFinalCouncilAdvisory(input.projectSummary.trim(),input.verdicts,input.roundNumber??1,config3.council);if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return JSON.stringify({success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Final council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the project can close. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},null,2);let plan=await loadPlan(directory);if(!plan)return JSON.stringify({success:!1,reason:"plan_not_found",message:"Cannot write final council evidence: plan.json not found. The plan must be loaded and available before writing final council evidence.",phase:input.phase,plan_id:"unknown"},null,2);let planId=derivePlanId(plan),planHash=computePlanHash(plan),planIdentityHash=derivePlanIdentityHash(plan),normalizedVerdict=normalizeFinalVerdict(synthesis.overallVerdict,synthesis.requiredFixes.length),evidenceEntry={type:"final-council",phase:input.phase,plan_id:planId,plan_hash:planHash,plan_identity_hash:planIdentityHash,verdict:normalizedVerdict,rawCouncilVerdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,membersVoted,membersAbsent,requiredFixes:synthesis.requiredFixes,advisoryFindings:synthesis.advisoryFindings,advisoryNotes:synthesis.advisoryNotes,unresolvedConflicts:synthesis.unresolvedConflicts,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,memberVerdicts:synthesis.memberVerdicts,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,projectSummary:synthesis.projectSummary,timestamp:synthesis.timestamp},filename="final-council.json",relativePath2=path265.join("evidence",filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase:input.phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceContent={entries:[evidenceEntry]},evidenceDir=path265.dirname(validatedPath);try{await fs163.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path265.join(evidenceDir,`.${filename}.tmp`);await fs163.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs163.promises.rename(tempPath,validatedPath);try{let memoryConfig=config3.memory;if(memoryConfig?.enabled===!0&&ctx?.sessionID){let provider=createConfiguredMemoryProvider(directory,memoryConfig);try{await applyCouncilReward(provider,{runId:ctx.sessionID,unitId:void 0,reward:COUNCIL_VERDICT_REWARDS[synthesis.overallVerdict],eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,timestamp:new Date().toISOString(),verdictLabel:synthesis.overallVerdict})}finally{await provider.close?.()}}}catch(rewardErr){warn(`[write-final-council-evidence] final council reward capture failed: ${rewardErr instanceof Error?rewardErr.message:String(rewardErr)}`)}return JSON.stringify({success:!0,phase:input.phase,overallVerdict:synthesis.overallVerdict,verdict:normalizedVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,advisoryNotes:synthesis.advisoryNotes,membersVoted,membersAbsent,quorumSize:synthesis.quorumSize,quorumMet:!0,evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:"Final council evidence written to .swarm/evidence/final-council.json"},null,2)}catch(error93){return JSON.stringify({success:!1,phase:input.phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var write_final_council_evidence=createSwarmTool({description:"Write final council evidence for a completed project. This is not General Council mode and does not use convene_general_council. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks, collect their CouncilMemberVerdict JSON, then call this tool to synthesize and persist .swarm/evidence/final-council.json.",args:{phase:exports_external.number().int().min(1).max(1000).describe("The final phase number for the project being reviewed"),projectSummary:exports_external.string().min(1).describe("Summary of the completed project and total work reviewed"),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed final council round number. Defaults to 1."),verdicts:exports_external.array(VerdictSchema3).min(1).max(5).describe("Collected CouncilMemberVerdict objects from critic, reviewer, sme, test_engineer, and explorer.")},execute:async(args2,directory,ctx)=>{let parsed=ArgsSchema9.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);return await executeWriteFinalCouncilEvidence(parsed.data,directory,ctx)}});init_zod();import fs164 from"node:fs";import path266 from"node:path";init_utils2();init_create_tool();async function executeWriteHallucinationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals176.normalizeVerdict2(args2.verdict),evidenceContent={entries:[{type:"hallucination-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),findings:args2.findings}]},filename="hallucination-guard.json",relativePath2=path266.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path266.dirname(validatedPath);try{await fs164.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path266.join(evidenceDir,`.${filename}.tmp`);return await fs164.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs164.promises.rename(tempPath,validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Hallucination evidence written to .swarm/evidence/${phase}/hallucination-guard.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals176={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2},write_hallucination_evidence=createSwarmTool({description:"Write hallucination verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/hallucination-guard.json. Use this after critic_hallucination_verifier delegation to persist the verification result. Unlike write_drift_evidence, this tool does NOT lock the QA gate profile.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the hallucination verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the hallucination verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the hallucination verification"),findings:exports_external.string().optional().describe("Optional bullet list of FABRICATED/DRIFTED/UNSUPPORTED/BROKEN findings (for NEEDS_REVISION)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),findings:args2.findings!==void 0?String(args2.findings):void 0};return await executeWriteHallucinationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();import fs165 from"node:fs";import path267 from"node:path";init_utils2();init_create_tool();async function executeWriteMutationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict4(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP'"},null,2);if(args2.killRate!==void 0){if(typeof args2.killRate!=="number"||Number.isNaN(args2.killRate))return JSON.stringify({success:!1,phase,message:"Invalid killRate: must be a number"},null,2)}if(args2.adjustedKillRate!==void 0){if(typeof args2.adjustedKillRate!=="number"||Number.isNaN(args2.adjustedKillRate))return JSON.stringify({success:!1,phase,message:"Invalid adjustedKillRate: must be a number"},null,2)}let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals177.normalizeVerdict4(args2.verdict),evidenceEntry={type:"mutation-gate",verdict:normalizedVerdict,killRate:args2.killRate??0,adjustedKillRate:args2.adjustedKillRate??0,summary:summary.trim(),timestamp:new Date().toISOString()};if(args2.survivedMutants!==void 0)evidenceEntry.survivedMutants=args2.survivedMutants;let evidenceContent={entries:[evidenceEntry]},filename="mutation-gate.json",relativePath2=path267.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path267.dirname(validatedPath);try{await fs165.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path267.join(evidenceDir,`.${filename}.tmp`);return await fs165.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs165.promises.rename(tempPath,validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Mutation gate evidence written to .swarm/evidence/${phase}/mutation-gate.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals177={normalizeVerdict4,VERDICT_SET_4,isAcceptedVerdict4},write_mutation_evidence=createSwarmTool({description:'Write mutation gate evidence for a completed phase. Accepts phase, verdict (PASS/WARN/FAIL/SKIP), killRate, adjustedKillRate, summary, and optional survivedMutants. Normalizes uppercase verdicts to lowercase (PASS→pass, WARN→warn, FAIL→fail, SKIP→skip) and writes entries[0].type="mutation-gate" to .swarm/evidence/{phase}/mutation-gate.json using atomic temp+rename write. Use this after mutation_test tool returns to persist the gate verdict.',args:{phase:exports_external.number().int().min(1).describe("The phase number for the mutation gate (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_4).describe("Verdict of the mutation gate: 'PASS', 'WARN', 'FAIL', or 'SKIP'"),killRate:exports_external.number().optional().describe("The raw kill rate (e.g., 0.85)"),adjustedKillRate:exports_external.number().optional().describe("The adjusted kill rate accounting for timeout survived mutants (e.g., 0.87)"),summary:exports_external.string().describe("Human-readable summary of the mutation gate result"),survivedMutants:exports_external.string().optional().describe("Optional JSON-serialized list of survived mutants")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),killRate:args2.killRate!==void 0?Number(args2.killRate):void 0,adjustedKillRate:args2.adjustedKillRate!==void 0?Number(args2.adjustedKillRate):void 0,summary:String(args2.summary??""),survivedMutants:args2.survivedMutants!==void 0?String(args2.survivedMutants):void 0};return await executeWriteMutationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_pr_workflow_gate();init_utils2();init_create_tool();import{randomUUID as randomUUID19}from"node:crypto";import*as fs166 from"node:fs";import*as path268 from"node:path";var RunIdSchema=exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,"run_id must be a safe relative identifier"),FindingSchema3=exports_external.object({finding_id:exports_external.string().trim().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),file_line:exports_external.string().trim().min(1).max(1000),evidence:exports_external.string().trim().min(1).max(20000),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"]),severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]).optional(),category:exports_external.string().trim().min(1).max(128).optional()}).strict(),HandoffSchema=exports_external.object({pr_url:exports_external.string().url(),finding_ids:exports_external.array(exports_external.string().trim().min(1).max(128)).min(1),summary:exports_external.string().trim().min(1).max(20000),provenance:exports_external.array(exports_external.string().trim().min(1).max(4000)).min(1)}).strict(),WritePrReviewArtifactArgsSchema=exports_external.discriminatedUnion("kind",[exports_external.object({kind:exports_external.literal("findings"),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]),records:exports_external.array(FindingSchema3).min(1).max(1000)}).strict(),exports_external.object({kind:exports_external.literal("handoff"),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),handoff:HandoffSchema}).strict()]);function failure3(message){return JSON.stringify({success:!1,message},null,2)}async function readFindings(filePath){try{let stat17=await fs166.promises.stat(filePath);if(!stat17.isFile()||stat17.size>10485760)throw Error("findings artifact is not a bounded regular file");return(await fs166.promises.readFile(filePath,"utf8")).split(/\r?\n/).filter(Boolean).map((line)=>JSON.parse(line))}catch(error93){if(error93.code==="ENOENT")return[];throw error93}}async function atomicWrite6(filePath,content){await fs166.promises.mkdir(path268.dirname(filePath),{recursive:!0});let tempPath=path268.join(path268.dirname(filePath),`.${path268.basename(filePath)}.${randomUUID19()}.tmp`);try{await fs166.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"}),await fs166.promises.rename(tempPath,filePath)}finally{await fs166.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}function latestFindings(records){let latest=new Map;for(let record3 of records)latest.set(record3.finding_id,record3);return latest}async function executeWritePrReviewArtifact(args2,directory,context={}){let parsed=WritePrReviewArtifactArgsSchema.safeParse(args2);if(!parsed.success)return failure3(`Invalid PR-review artifact: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure3("PR-review artifact requires an active session");let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_REVIEW"||!state.prHeadSha)return failure3("PR-review artifact requires an active, bound PR_REVIEW gate");if(state.prHeadSha!==parsed.data.pr_head_sha.toLowerCase())return failure3(`PR-review artifact head mismatch: expected ${state.prHeadSha}, received ${parsed.data.pr_head_sha}`);if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==parsed.data.run_id)return failure3(`PR-review artifacts are already bound to run ${state.prReviewArtifactRunId}`);let relativeFindingsPath=path268.join("pr-review",parsed.data.run_id,"findings.jsonl"),findingsPath=validateSwarmPath(directory,relativeFindingsPath),existing=await readFindings(findingsPath);if(parsed.data.kind==="findings"){let findingsInput=parsed.data,findingIds=findingsInput.records.map((record3)=>record3.finding_id);await assertPrReviewArtifactBoundary(directory,sessionID,findingsInput.run_id,findingsInput.boundary,findingIds),await assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,findingsInput.boundary,findingsInput.records);let recordedAt=new Date().toISOString(),appended=findingsInput.records.map((record3)=>({...record3,boundary:findingsInput.boundary,pr_head_sha:state.prHeadSha,recorded_at:recordedAt})),allRecords=[...existing,...appended];await atomicWrite6(findingsPath,allRecords.map((record3)=>JSON.stringify(record3)).join(`
6292
6294
  `)+(allRecords.length>0?`
6293
6295
  `:""));let handoffRequired=[...latestFindings(allRecords).values()].some((record3)=>record3.status==="CONFIRMED"&&record3.next_action==="handoff_to_feedback");return await markPrReviewArtifactBoundary(directory,sessionID,findingsInput.run_id,findingsInput.boundary,relativeFindingsPath.split(path268.sep).join("/"),findingIds,handoffRequired),JSON.stringify({success:!0,path:relativeFindingsPath.split(path268.sep).join("/"),boundary:findingsInput.boundary,appended:appended.length,handoff_required:handoffRequired},null,2)}let actionableIds=[...latestFindings(existing).values()].filter((record3)=>record3.status==="CONFIRMED"&&record3.next_action==="handoff_to_feedback").map((record3)=>record3.finding_id).sort(),requestedIds=[...new Set(parsed.data.handoff.finding_ids)].sort();if(actionableIds.length===0||JSON.stringify(actionableIds)!==JSON.stringify(requestedIds))return failure3(`handoff finding_ids must exactly match actionable findings: ${actionableIds.join(", ")||"(none)"}`);let relativeHandoffPath=path268.join("pr-review",parsed.data.run_id,"feedback-handoff.json"),handoffPath=validateSwarmPath(directory,relativeHandoffPath);return await atomicWrite6(handoffPath,`${JSON.stringify({schema_version:1,run_id:parsed.data.run_id,pr_head_sha:state.prHeadSha,created_at:new Date().toISOString(),...parsed.data.handoff},null,2)}
6294
- `),await markPrReviewHandoffComplete(directory,sessionID,parsed.data.run_id,relativeHandoffPath.split(path268.sep).join("/")),JSON.stringify({success:!0,path:relativeHandoffPath.split(path268.sep).join("/"),finding_count:actionableIds.length},null,2)}var write_pr_review_artifact=createSwarmTool({description:"Persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run.",args:{kind:exports_external.enum(["findings","handoff"]),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]).optional(),records:exports_external.array(FindingSchema3).min(1).max(1000).optional(),handoff:HandoffSchema.optional()},execute:executeWritePrReviewArtifact});init_zod();init_lane_output_store();init_pending_delegations();init_workspace_snapshot();init_pr_workflow_gate();init_utils2();init_create_tool();import{randomUUID as randomUUID20}from"node:crypto";import fs167 from"node:fs";import path269 from"node:path";var _internals178={resolvePrWorkflowRevisionDigest,resolveMergeBase:resolveExactMergeBase},PR_REVIEW_TRIGGER_DEFINITIONS=[{id:"auth-identity-secrets",scope:"universal",trigger_row:"authentication, authorization, identity, sessions, permissions, secrets, cryptography",micro_lane:"Identity and secret boundaries"},{id:"untrusted-input-boundaries",scope:"universal",trigger_row:"parsing, serialization, queries, templates/rendering, file or network input/output",micro_lane:"Untrusted input and sink analysis"},{id:"subprocess-platform",scope:"universal",trigger_row:"subprocesses, shell commands, filesystem operations, OS/runtime-specific code",micro_lane:"Subprocess and platform safety"},{id:"concurrency-state",scope:"universal",trigger_row:"queues, caches, retries, transactions, locks, state machines, async coordination",micro_lane:"Concurrency and state transitions"},{id:"dependencies-build-release",scope:"universal",trigger_row:"dependency manifests, lockfiles, installers, build scripts, CI, packaging, deployment",micro_lane:"Dependency and delivery integrity"},{id:"api-schema-migrations",scope:"universal",trigger_row:"public API, wire/schema/config/storage formats, migrations, feature flags",micro_lane:"Compatibility and migration safety"},{id:"test-infrastructure",scope:"universal",trigger_row:"tests, mocks, fixtures, harnesses, coverage, CI matrices",micro_lane:"Test validity and isolation"},{id:"ui-accessibility-i18n",scope:"universal",trigger_row:"user interfaces, interaction flows, rendering, accessibility, localization",micro_lane:"UI and human-interface quality"},{id:"privacy-observability",scope:"universal",trigger_row:"telemetry, logs, analytics, traces, retention, diagnostics",micro_lane:"Privacy and observability safety"},{id:"generated-provenance",scope:"universal",trigger_row:"generated, vendored, binary, model-produced, codegen or checked-in build artifacts",micro_lane:"Generated artifact provenance"},{id:"unclassified-risk",scope:"universal",trigger_row:"any changed artifact or behavior not confidently classified by the rows above",micro_lane:"Unclassified high-risk fallback"}],TriggerEvalRowSchema=exports_external.object({trigger_id:exports_external.string().min(1),result:exports_external.literal("MATCHED"),evidence:exports_external.string().trim().min(1).max(4000),source_batch_id:exports_external.string().trim().min(1).optional(),source_lane_id:exports_external.string().trim().min(1).optional()}).strict(),WritePrReviewTriggerEvalArgsSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,"run_id must be a safe relative identifier"),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i).optional(),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional(),rows:exports_external.array(TriggerEvalRowSchema).min(1)}).strict();function failure4(message){return JSON.stringify({success:!1,message},null,2)}async function executeWritePrReviewTriggerEval(args2,directory,context={}){let parsed=WritePrReviewTriggerEvalArgsSchema.safeParse(args2);if(!parsed.success)return failure4(`Invalid trigger evaluation: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let expectedIds=new Set(PR_REVIEW_REQUIRED_MICRO_LANE_IDS),seenIds=new Set,duplicateIds=new Set;for(let row of parsed.data.rows){if(seenIds.has(row.trigger_id))duplicateIds.add(row.trigger_id);seenIds.add(row.trigger_id)}if(duplicateIds.size>0)return failure4(`duplicate trigger IDs: ${[...duplicateIds].join(", ")}`);let unknownIds=[...seenIds].filter((id)=>!expectedIds.has(id));if(unknownIds.length>0)return failure4(`unknown trigger IDs: ${unknownIds.join(", ")}. trigger_id must be one of the 11 mandatory micro-lane IDs: ${[...expectedIds].join(", ")}. Base-lane IDs and mode strings (e.g. swarm-pr-review:base) are NOT trigger IDs.`);let missingIds=[...expectedIds].filter((id)=>!seenIds.has(id));if(missingIds.length>0)return failure4(`missing trigger IDs: ${missingIds.join(", ")}`);for(let row of parsed.data.rows)if(row.result==="MATCHED"){if(!row.source_batch_id||!row.source_lane_id)return failure4(`MATCHED rows require source_batch_id and source_lane_id: ${row.trigger_id}`)}let sessionID=context.sessionID?.trim();if(!sessionID)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");let gateState;try{gateState=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(gateState?.mode!=="PR_REVIEW"||!gateState.prHeadSha)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");if(gateState.prHeadSha!==parsed.data.pr_head_sha)return failure4(`PR_REVIEW trigger evaluation head mismatch: expected ${gateState.prHeadSha}, received ${parsed.data.pr_head_sha}`);try{await assertPrReviewBaseCoverageSettled(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let currentRevisionDigest=_internals178.resolvePrWorkflowRevisionDigest(directory,parsed.data.pr_head_sha);if(!currentRevisionDigest)return failure4("Active PR_REVIEW trigger evaluation could not bind the current exact revision digest");let citedLaneOwnership=new Map;for(let row of parsed.data.rows){if(row.result!=="MATCHED")continue;let record3=findByBatchId(directory,row.source_batch_id,{parentSessionId:sessionID}).find((candidate)=>candidate.laneId===row.source_lane_id),recordOwnedLanes=record3?.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3?.workflowLane?[record3.workflowLane]:[];citedLaneOwnership.set(`${row.source_batch_id}\x00${row.source_lane_id}`,recordOwnedLanes);let outputRef=record3?.result?.outputRef?.trim(),outputArtifact=outputRef?readLaneOutput(directory,outputRef):null;if(!record3||record3.mode!=="swarm-pr-review:micro"||!recordOwnedLanes.includes(row.trigger_id)||record3.status!=="completed"||record3.result?.outputDegraded===!0||record3.result?.transcriptIncomplete===!0||record3.result?.truncated===!0||(record3.result?.chars??0)<=0||!record3.result?.digest?.trim()||!record3.result?.outputRef?.trim()||!outputArtifact||outputArtifact.artifact.batchId!==row.source_batch_id||outputArtifact.artifact.laneId!==row.source_lane_id||outputArtifact.artifact.mode!=="swarm-pr-review:micro"||outputArtifact.artifact.sessionId!==record3.subagentSessionId||outputArtifact.artifact.parentSessionId!==record3.parentSessionId||outputArtifact.artifact.agent!==record3.swarmPrefixedAgent||outputArtifact.artifact.role!==record3.normalizedAgent||outputArtifact.artifact.source!=="collect_lane_results"||outputArtifact.artifact.workflowLane!==record3.workflowLane||outputArtifact.artifact.prHeadSha!==record3.workspace?.prHeadSha||outputArtifact.artifact.gitHead!==record3.workspace?.gitHead||outputArtifact.artifact.revisionDigest!==currentRevisionDigest||outputArtifact.artifact.digest!==record3.result?.digest||outputArtifact.artifact.chars!==record3.result?.chars||!recordOwnedLanes.every((ownedFamily)=>prReviewDiscoveryArtifactCoversLane(outputArtifact.artifact.text,ownedFamily))||record3.workspace?.prHeadSha!==parsed.data.pr_head_sha||record3.workspace?.gitHead!==parsed.data.pr_head_sha)return failure4(`MATCHED trigger ${row.trigger_id} does not reference a completed non-degraded micro-lane artifact`)}let citedLaneEntries=[...citedLaneOwnership.entries()];for(let i=0;i<citedLaneEntries.length;i++)for(let j=i+1;j<citedLaneEntries.length;j++){let[keyA,ownedA]=citedLaneEntries[i],[keyB,ownedB]=citedLaneEntries[j],overlap2=ownedA.filter((family)=>ownedB.includes(family));if(overlap2.length>0)return failure4(`PR_REVIEW trigger evaluation cites two lanes with overlapping ownership: "${keyA}" and "${keyB}" both declare ${overlap2.join(", ")}`)}if(!parsed.data.base_sha)return failure4("Active PR_REVIEW trigger evaluation requires the exact merge-base base_sha");if(!parsed.data.base_ref)return failure4("Active PR_REVIEW trigger evaluation requires the exact live base_ref used to verify base_sha");let resolvedMergeBase=_internals178.resolveMergeBase(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedMergeBase)return failure4("Active PR_REVIEW trigger evaluation could not resolve the exact merge base from base_ref and pr_head_sha");if(resolvedMergeBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW merge-base mismatch: expected ${resolvedMergeBase}, received ${parsed.data.base_sha}`);if(gateState.prReviewBaseRef!==parsed.data.base_ref||gateState.prReviewBaseSha!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW trigger evaluation scope mismatch: workflow is bound to ${gateState.prReviewBaseRef??"(unbound)"} at ${gateState.prReviewBaseSha??"(unbound)"}, received ${parsed.data.base_ref} at ${parsed.data.base_sha}`);let rowsById=new Map(parsed.data.rows.map((row)=>[row.trigger_id,row])),artifactRows=PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>{let row=rowsById.get(definition.id);if(!row)throw Error(`Missing validated trigger row: ${definition.id}`);return{trigger_id:definition.id,scope:definition.scope,trigger_row:definition.trigger_row,micro_lane:definition.micro_lane,result:row.result,evidence:row.evidence,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}}),matchedCount=artifactRows.length,dispatchedMicroLaneCount=new Set(parsed.data.rows.map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size,artifact={schema_version:1,run_id:parsed.data.run_id,pr_head_sha:parsed.data.pr_head_sha,base_ref:parsed.data.base_ref,base_sha:parsed.data.base_sha,evaluated_at:new Date().toISOString(),trigger_count:artifactRows.length,matched_count:matchedCount,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount,rows:artifactRows},relativePath2=path269.join("pr-review",parsed.data.run_id,"trigger-eval.json"),destination;try{destination=validateSwarmPath(directory,relativePath2)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let parent=path269.dirname(destination),tempPath=path269.join(parent,`.trigger-eval.${randomUUID20()}.tmp`);try{await fs167.promises.mkdir(parent,{recursive:!0}),await fs167.promises.writeFile(tempPath,`${JSON.stringify(artifact,null,2)}
6296
+ `),await markPrReviewHandoffComplete(directory,sessionID,parsed.data.run_id,relativeHandoffPath.split(path268.sep).join("/")),JSON.stringify({success:!0,path:relativeHandoffPath.split(path268.sep).join("/"),finding_count:actionableIds.length},null,2)}var write_pr_review_artifact=createSwarmTool({description:"Persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run.",args:{kind:exports_external.enum(["findings","handoff"]),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]).optional(),records:exports_external.array(FindingSchema3).min(1).max(1000).optional(),handoff:HandoffSchema.optional()},execute:executeWritePrReviewArtifact});init_zod();init_lane_output_store();init_pending_delegations();init_workspace_snapshot();init_pr_workflow_gate();init_utils2();init_create_tool();import{randomUUID as randomUUID20}from"node:crypto";import fs167 from"node:fs";import path269 from"node:path";var _internals178={resolvePrWorkflowRevisionDigest,resolveMergeBase:resolveExactMergeBase},PR_REVIEW_TRIGGER_DEFINITIONS=[{id:"auth-identity-secrets",scope:"universal",trigger_row:"authentication, authorization, identity, sessions, permissions, secrets, cryptography",micro_lane:"Identity and secret boundaries"},{id:"untrusted-input-boundaries",scope:"universal",trigger_row:"parsing, serialization, queries, templates/rendering, file or network input/output",micro_lane:"Untrusted input and sink analysis"},{id:"subprocess-platform",scope:"universal",trigger_row:"subprocesses, shell commands, filesystem operations, OS/runtime-specific code",micro_lane:"Subprocess and platform safety"},{id:"concurrency-state",scope:"universal",trigger_row:"queues, caches, retries, transactions, locks, state machines, async coordination",micro_lane:"Concurrency and state transitions"},{id:"dependencies-build-release",scope:"universal",trigger_row:"dependency manifests, lockfiles, installers, build scripts, CI, packaging, deployment",micro_lane:"Dependency and delivery integrity"},{id:"api-schema-migrations",scope:"universal",trigger_row:"public API, wire/schema/config/storage formats, migrations, feature flags",micro_lane:"Compatibility and migration safety"},{id:"test-infrastructure",scope:"universal",trigger_row:"tests, mocks, fixtures, harnesses, coverage, CI matrices",micro_lane:"Test validity and isolation"},{id:"ui-accessibility-i18n",scope:"universal",trigger_row:"user interfaces, interaction flows, rendering, accessibility, localization",micro_lane:"UI and human-interface quality"},{id:"privacy-observability",scope:"universal",trigger_row:"telemetry, logs, analytics, traces, retention, diagnostics",micro_lane:"Privacy and observability safety"},{id:"generated-provenance",scope:"universal",trigger_row:"generated, vendored, binary, model-produced, codegen or checked-in build artifacts",micro_lane:"Generated artifact provenance"},{id:"unclassified-risk",scope:"universal",trigger_row:"any changed artifact or behavior not confidently classified by the rows above",micro_lane:"Unclassified high-risk fallback"}],TriggerEvalRowSchema=exports_external.object({trigger_id:exports_external.string().min(1),result:exports_external.literal("MATCHED"),evidence:exports_external.string().trim().min(1).max(4000),source_batch_id:exports_external.string().trim().min(1).optional(),source_lane_id:exports_external.string().trim().min(1).optional()}).strict(),WritePrReviewTriggerEvalArgsSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,"run_id must be a safe relative identifier"),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i).optional(),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional(),rows:exports_external.array(TriggerEvalRowSchema).min(1)}).strict();function failure4(message){return JSON.stringify({success:!1,message},null,2)}async function executeWritePrReviewTriggerEval(args2,directory,context={}){let parsed=WritePrReviewTriggerEvalArgsSchema.safeParse(args2);if(!parsed.success)return failure4(`Invalid trigger evaluation: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let expectedIds=new Set(PR_REVIEW_REQUIRED_MICRO_LANE_IDS),seenIds=new Set,duplicateIds=new Set;for(let row of parsed.data.rows){if(seenIds.has(row.trigger_id))duplicateIds.add(row.trigger_id);seenIds.add(row.trigger_id)}if(duplicateIds.size>0)return failure4(`duplicate trigger IDs: ${[...duplicateIds].join(", ")}`);let unknownIds=[...seenIds].filter((id)=>!expectedIds.has(id));if(unknownIds.length>0)return failure4(`unknown trigger IDs: ${unknownIds.join(", ")}. trigger_id must be one of the 11 mandatory micro-lane IDs: ${[...expectedIds].join(", ")}. Base-lane IDs and mode strings (e.g. swarm-pr-review:base) are NOT trigger IDs.`);let missingIds=[...expectedIds].filter((id)=>!seenIds.has(id));if(missingIds.length>0)return failure4(`missing trigger IDs: ${missingIds.join(", ")}`);for(let row of parsed.data.rows)if(row.result==="MATCHED"){if(!row.source_batch_id||!row.source_lane_id)return failure4(`MATCHED rows require source_batch_id and source_lane_id: ${row.trigger_id}`)}let sessionID=context.sessionID?.trim();if(!sessionID)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");let gateState;try{gateState=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(gateState?.mode!=="PR_REVIEW"||!gateState.prHeadSha)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");if(gateState.prHeadSha!==parsed.data.pr_head_sha)return failure4(`PR_REVIEW trigger evaluation head mismatch: expected ${gateState.prHeadSha}, received ${parsed.data.pr_head_sha}`);try{await assertPrReviewBaseCoverageSettled(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let currentRevisionDigest=_internals178.resolvePrWorkflowRevisionDigest(directory,parsed.data.pr_head_sha);if(!currentRevisionDigest)return failure4("Active PR_REVIEW trigger evaluation could not bind the current exact revision digest");let citedLaneOwnership=new Map;for(let row of parsed.data.rows){if(row.result!=="MATCHED")continue;let record3=findByBatchId(directory,row.source_batch_id,{parentSessionId:sessionID}).find((candidate)=>candidate.laneId===row.source_lane_id),recordOwnedLanes=record3?.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3?.workflowLane?[record3.workflowLane]:[];citedLaneOwnership.set(`${row.source_batch_id}\x00${row.source_lane_id}`,recordOwnedLanes);let outputRef=record3?.result?.outputRef?.trim(),outputArtifact=outputRef?readLaneOutput(directory,outputRef):null;if(!record3||record3.mode!=="swarm-pr-review:micro"||!recordOwnedLanes.includes(row.trigger_id)||record3.status!=="completed"||record3.result?.outputDegraded===!0||record3.result?.transcriptIncomplete===!0||record3.result?.truncated===!0||(record3.result?.chars??0)<=0||!record3.result?.digest?.trim()||!record3.result?.outputRef?.trim()||!outputArtifact||outputArtifact.artifact.batchId!==row.source_batch_id||outputArtifact.artifact.laneId!==row.source_lane_id||outputArtifact.artifact.mode!=="swarm-pr-review:micro"||outputArtifact.artifact.sessionId!==record3.subagentSessionId||outputArtifact.artifact.parentSessionId!==record3.parentSessionId||outputArtifact.artifact.agent!==record3.swarmPrefixedAgent||outputArtifact.artifact.role!==record3.normalizedAgent||outputArtifact.artifact.source!=="collect_lane_results"||outputArtifact.artifact.workflowLane!==record3.workflowLane||outputArtifact.artifact.prHeadSha!==record3.workspace?.prHeadSha||outputArtifact.artifact.gitHead!==record3.workspace?.gitHead||outputArtifact.artifact.revisionDigest!==currentRevisionDigest||outputArtifact.artifact.digest!==record3.result?.digest||outputArtifact.artifact.chars!==record3.result?.chars||!recordOwnedLanes.every((ownedFamily)=>prReviewDiscoveryArtifactCoversLane(outputArtifact.artifact.text,ownedFamily))||record3.workspace?.prHeadSha!==parsed.data.pr_head_sha||record3.workspace?.gitHead!==parsed.data.pr_head_sha)return failure4(`MATCHED trigger ${row.trigger_id} does not reference a completed non-degraded micro-lane artifact`)}let citedLaneEntries=[...citedLaneOwnership.entries()];for(let i=0;i<citedLaneEntries.length;i++)for(let j=i+1;j<citedLaneEntries.length;j++){let[keyA,ownedA]=citedLaneEntries[i],[keyB,ownedB]=citedLaneEntries[j],overlap2=ownedA.filter((family)=>ownedB.includes(family));if(overlap2.length>0)return failure4(`PR_REVIEW trigger evaluation cites two lanes with overlapping ownership: "${keyA}" and "${keyB}" both declare ${overlap2.join(", ")}`)}if(!parsed.data.base_sha)return failure4("Active PR_REVIEW trigger evaluation requires the exact merge-base base_sha");if(!parsed.data.base_ref)return failure4("Active PR_REVIEW trigger evaluation requires the exact live base_ref used to verify base_sha");let resolvedMergeBase=_internals178.resolveMergeBase(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedMergeBase)return failure4("Active PR_REVIEW trigger evaluation could not resolve the exact merge base from base_ref and pr_head_sha");if(resolvedMergeBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW merge-base mismatch: expected ${resolvedMergeBase}, received ${parsed.data.base_sha}`);if(gateState.prReviewBaseRef!==parsed.data.base_ref||gateState.prReviewBaseSha!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW trigger evaluation scope mismatch: workflow is bound to ${gateState.prReviewBaseRef??"(unbound)"} at ${gateState.prReviewBaseSha??"(unbound)"}, received ${parsed.data.base_ref} at ${parsed.data.base_sha}`);let rowsById=new Map(parsed.data.rows.map((row)=>[row.trigger_id,row])),artifactRows=PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>{let row=rowsById.get(definition.id);if(!row)throw Error(`Missing validated trigger row: ${definition.id}`);return{trigger_id:definition.id,scope:definition.scope,trigger_row:definition.trigger_row,micro_lane:definition.micro_lane,result:row.result,evidence:row.evidence,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}}),matchedCount=artifactRows.length,dispatchedMicroLaneCount=new Set(parsed.data.rows.map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size,microFloor=PR_REVIEW_MICRO_LANE_FLOORS[gateState.prReviewDepthTier??"L"];if(dispatchedMicroLaneCount<microFloor)return failure4(`PR_REVIEW micro lane floor unmet: depth tier ${gateState.prReviewDepthTier??"L"} requires at least ${microFloor} dispatched micro lane(s) across the attestation; the ledger attributes all ${PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length} families to only ${dispatchedMicroLaneCount}`);let artifact={schema_version:1,run_id:parsed.data.run_id,pr_head_sha:parsed.data.pr_head_sha,base_ref:parsed.data.base_ref,base_sha:parsed.data.base_sha,evaluated_at:new Date().toISOString(),trigger_count:artifactRows.length,matched_count:matchedCount,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount,rows:artifactRows},relativePath2=path269.join("pr-review",parsed.data.run_id,"trigger-eval.json"),destination;try{destination=validateSwarmPath(directory,relativePath2)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let parent=path269.dirname(destination),tempPath=path269.join(parent,`.trigger-eval.${randomUUID20()}.tmp`);try{await fs167.promises.mkdir(parent,{recursive:!0}),await fs167.promises.writeFile(tempPath,`${JSON.stringify(artifact,null,2)}
6295
6297
  `,{encoding:"utf-8",flag:"wx"}),await fs167.promises.rename(tempPath,destination)}catch(error93){return failure4(`Failed to persist trigger evaluation: ${error93 instanceof Error?error93.message:String(error93)}`)}finally{await fs167.promises.rm(tempPath,{force:!0}).catch(()=>{return})}return await markPrReviewTriggerEvaluationComplete(directory,sessionID,relativePath2.split(path269.sep).join("/")),JSON.stringify({success:!0,path:relativePath2.split(path269.sep).join("/"),trigger_count:artifactRows.length,matched_count:matchedCount,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount},null,2)}var write_pr_review_trigger_eval=createSwarmTool({description:"Persist the complete, exact-set PR-review micro-lane ledger after every repository-agnostic lane has completed.",args:{run_id:WritePrReviewTriggerEvalArgsSchema.shape.run_id,pr_head_sha:WritePrReviewTriggerEvalArgsSchema.shape.pr_head_sha,base_sha:WritePrReviewTriggerEvalArgsSchema.shape.base_sha,base_ref:WritePrReviewTriggerEvalArgsSchema.shape.base_ref,rows:WritePrReviewTriggerEvalArgsSchema.shape.rows},execute:executeWritePrReviewTriggerEval});init_write_retro();function defineHandlers(handlers){return handlers}var TOOL_MANIFEST=defineHandlers({diff:()=>diff,diff_summary:()=>diff_summary,syntax_check:()=>syntax_check,placeholder_scan:()=>placeholder_scan,imports:()=>imports,lint:()=>lint,secretscan:()=>secretscan,sast_scan:()=>sast_scan,build_check:()=>build_check,pre_check_batch:()=>pre_check_batch,quality_budget:()=>quality_budget,symbols:()=>symbols,complexity_hotspots:()=>complexity_hotspots,schema_drift:()=>schema_drift,todo_extract:()=>todo_extract,evidence_check:()=>evidence_check,check_gate_status:()=>check_gate_status,completion_verify:()=>completion_verify,complete_pr_workflow:()=>complete_pr_workflow,abort_pr_workflow:()=>abort_pr_workflow,prepare_pr_workflow_checkout:()=>prepare_pr_workflow_checkout,run_pr_feedback_stage_a:()=>run_pr_feedback_stage_a,submit_council_verdicts:()=>submit_council_verdicts,submit_phase_council_verdicts:()=>submit_phase_council_verdicts,declare_council_criteria:()=>declare_council_criteria,sbom_generate:()=>sbom_generate,checkpoint:()=>checkpoint,pkg_audit:()=>pkg_audit,parse_lane_candidates:()=>parse_lane_candidates,prepare_pr_feedback_scope:()=>prepare_pr_feedback_scope,write_pr_review_artifact:()=>write_pr_review_artifact,write_pr_review_trigger_eval:()=>write_pr_review_trigger_eval,test_runner:()=>test_runner,test_impact:()=>test_impact,mutation_test:()=>mutation_test,generate_mutants:()=>generate_mutants,detect_domains:()=>detect_domains,git_blame:()=>git_blame,gitingest:()=>gitingest,retrieve_summary:()=>retrieve_summary,retrieve_lane_output:()=>retrieve_lane_output,extract_code_blocks:()=>extract_code_blocks,phase_complete:()=>phase_complete,save_plan:()=>save_plan,update_task_status:()=>update_task_status,lint_spec:()=>lint_spec,write_retro:()=>write_retro,write_drift_evidence:()=>write_drift_evidence,write_hallucination_evidence:()=>write_hallucination_evidence,write_mutation_evidence:()=>write_mutation_evidence,declare_scope:()=>declare_scope,knowledge_query:()=>knowledge_query,doc_scan:()=>doc_scan,doc_extract:()=>doc_extract,curator_analyze:()=>curator_analyze,knowledge_add:()=>knowledge_add,knowledge_recall:()=>knowledge_recall,knowledge_remove:()=>knowledge_remove,co_change_analyzer:()=>co_change_analyzer,context_status:()=>context_status,search:()=>search,ast_grep:()=>ast_grep,actionlint_scan:()=>actionlint_scan,osv_scan:()=>osv_scan,gh_evidence:()=>gh_evidence,batch_symbols:()=>batch_symbols,suggest_patch:()=>suggestPatch,req_coverage:()=>req_coverage,get_approved_plan:()=>get_approved_plan,repo_map:()=>repo_map,get_qa_gate_profile:()=>get_qa_gate_profile,set_qa_gates:()=>set_qa_gates,web_search:()=>web_search,web_fetch:()=>web_fetch,convene_general_council:()=>convene_general_council,write_final_council_evidence:()=>write_final_council_evidence,skill_generate:()=>skill_generate,skill_list:()=>skill_list,skill_apply:()=>skill_apply,skill_inspect:()=>skill_inspect,run_stale_reconciliation:()=>run_stale_reconciliation,skill_regenerate:()=>skill_regenerate,skill_retire:()=>skill_retire,skill_improve:()=>skill_improve,spec_write:()=>spec_write,knowledge_receipt:()=>knowledge_receipt,knowledge_archive:()=>knowledge_archive,swarm_memory_recall:()=>swarm_memory_recall,swarm_memory_propose:()=>swarm_memory_propose,swarm_command:()=>swarm_command,dispatch_lanes:()=>dispatch_lanes,dispatch_lanes_async:()=>dispatch_lanes_async,collect_lane_results:()=>collect_lane_results,summarize_work:()=>summarize_work,write_architecture_supervisor_evidence:()=>write_architecture_supervisor_evidence,lean_turbo_plan_lanes:()=>lean_turbo_plan_lanes,lean_turbo_acquire_locks:()=>lean_turbo_acquire_locks,lean_turbo_runner_status:()=>lean_turbo_runner_status,lean_turbo_review:()=>lean_turbo_review,lean_turbo_run_phase:()=>lean_turbo_run_phase,lean_turbo_status:()=>lean_turbo_status,swarm_apply_patch:()=>swarmApplyPatch2,external_skill_discover:()=>external_skill_discover,external_skill_list:()=>external_skill_list,external_skill_inspect:()=>external_skill_inspect,external_skill_promote:()=>external_skill_promote,external_skill_reject:()=>external_skill_reject,external_skill_delete:()=>external_skill_delete,external_skill_revoke:()=>external_skill_revoke,epic_decide_phase:()=>epic_decide_phase,epic_plan_waves:()=>epic_plan_waves,epic_record_divergence:()=>epic_record_divergence});function buildPluginToolObject(agents,config3,evaluationModelDispatcher){let tools={},knowledgeEnabled=config3?.knowledge?.enabled!==!1,knowledgeTools=new Set(["knowledge_add","knowledge_recall","knowledge_remove","knowledge_query","knowledge_receipt","knowledge_archive"]);for(let[name,handler]of Object.entries(TOOL_MANIFEST)){if(!knowledgeEnabled&&knowledgeTools.has(name))continue;tools[name]=handler()}return tools.swarm_command=createSwarmCommandTool(agents,evaluationModelDispatcher),tools}init_utils();function truncateToolOutput(output,maxLines,toolName,tailLines=10){if(!output)return output;if(tailLines>=maxLines)tailLines=Math.floor(maxLines/2);let lines=output.split(`
6296
6298
  `);if(lines.length<=maxLines)return output;let omittedCount=lines.length-maxLines,headLines=lines.slice(0,maxLines-tailLines),tailContent=lines.slice(-tailLines),footerLines=[];if(footerLines.push(""),footerLines.push(`[... ${omittedCount} line${omittedCount===1?"":"s"} omitted ...]`),toolName)footerLines.push(`Tool: ${toolName}`);return footerLines.push("Use /swarm retrieve <id> to get the full content"),`${headLines.join(`
6297
6299
  `)}