opencode-swarm 7.143.4 → 7.143.6
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/.opencode/skills/swarm-pr-review/SKILL.md +5 -5
- package/.opencode/skills/swarm-pr-review/references/lane-output-recoverability.md +129 -0
- package/dist/background/pending-delegations.d.ts +42 -1
- package/dist/background/pr-review-trigger-contract.d.ts +17 -0
- package/dist/cli/{config-doctor-az6nqawx.js → config-doctor-72zp0k4x.js} +2 -2
- package/dist/cli/{core-a6rzajem.js → core-aj0wmbg8.js} +1 -1
- package/dist/cli/{curator-tbw9przg.js → curator-2gt2835v.js} +18 -18
- package/dist/cli/{curator-llm-factory-j42j5rcr.js → curator-llm-factory-x1vjhrnc.js} +18 -18
- package/dist/cli/{evidence-summary-service-3f319cst.js → evidence-summary-service-yjr0662r.js} +6 -6
- package/dist/cli/{gate-evidence-k2yycngf.js → gate-evidence-r3c7eqpz.js} +2 -2
- package/dist/cli/{guardrail-explain-tsgsw91f.js → guardrail-explain-f3zysesy.js} +19 -19
- package/dist/cli/{guardrail-log-70cxb3va.js → guardrail-log-eat71fnh.js} +3 -3
- package/dist/cli/{hive-promoter-nksqxfs4.js → hive-promoter-fyb40am9.js} +18 -18
- package/dist/cli/{index-19wyta2k.js → index-02nm8qhk.js} +3 -3
- package/dist/cli/{index-8fq18k02.js → index-0adcjpyx.js} +3 -3
- package/dist/cli/{index-f39n8pbr.js → index-36vry26a.js} +1 -1
- package/dist/cli/{index-gz3z9d64.js → index-5d8ydxae.js} +399 -77
- package/dist/cli/{index-8aabbfhv.js → index-6vmazy9f.js} +8 -5
- package/dist/cli/{index-bt47jrhx.js → index-72zhsqgy.js} +2 -2
- package/dist/cli/{index-z4g05zbr.js → index-7bs015gm.js} +1 -1
- package/dist/cli/{index-dmtq7tvd.js → index-92bm9ys3.js} +1 -1
- package/dist/cli/{index-td2ga37v.js → index-bbv64s17.js} +1 -1
- package/dist/cli/{index-mewk624g.js → index-dtf2va28.js} +20 -20
- package/dist/cli/{index-jmgm1npc.js → index-fn0k0vsa.js} +1 -1
- package/dist/cli/{index-z0j133c4.js → index-gzxz0s50.js} +1 -1
- package/dist/cli/{index-8qmnqd6g.js → index-hjy4txgr.js} +1 -1
- package/dist/cli/{index-seedt8m3.js → index-kc2x117y.js} +3 -3
- package/dist/cli/{index-6htwcbxh.js → index-nd1j9wkw.js} +1 -1
- package/dist/cli/{index-9m5gz9ea.js → index-peqmw3wr.js} +2 -2
- package/dist/cli/{index-gbr0jbxy.js → index-s7nb33pc.js} +1 -1
- package/dist/cli/{index-f3xf9dv5.js → index-scj2asek.js} +5 -5
- package/dist/cli/{index-c9d5y70c.js → index-w1q9yy1e.js} +3 -3
- package/dist/cli/{index-ja15rdzd.js → index-whyrhjsk.js} +1 -1
- package/dist/cli/{index-5qqyvwqw.js → index-wjk00vwk.js} +4 -4
- package/dist/cli/{index-v9qmhrj9.js → index-z4cv77tq.js} +2 -2
- package/dist/cli/index.js +18 -18
- package/dist/cli/{knowledge-escalator-8akk4n18.js → knowledge-escalator-ejpyrby0.js} +6 -6
- package/dist/cli/{knowledge-events-51qk8fq2.js → knowledge-events-yw2kydyy.js} +4 -4
- package/dist/cli/{knowledge-store-7rsezhav.js → knowledge-store-j6gkk62e.js} +1 -1
- package/dist/cli/{knowledge-validator-nq75s9et.js → knowledge-validator-xervpe5k.js} +2 -2
- package/dist/cli/{pending-delegations-b3pt3w5w.js → pending-delegations-19wg9j08.js} +5 -1
- package/dist/cli/{scan-cursor-em4vrcw6.js → scan-cursor-x7a99wmq.js} +2 -2
- package/dist/cli/{schema-1wmfgtm9.js → schema-z141arx9.js} +1 -1
- package/dist/cli/{scope-persistence-8ehnjgsg.js → scope-persistence-js90c1f4.js} +4 -4
- package/dist/cli/{skill-generator-3jstr1sx.js → skill-generator-t202jza0.js} +7 -7
- package/dist/cli/{worktree-collision-ownership-bfz3drxm.js → worktree-collision-ownership-42bb3gcb.js} +1 -1
- package/dist/cli/{worktree-isolation-cc3x13ng.js → worktree-isolation-fbfvxw9a.js} +18 -18
- package/dist/hooks/pr-workflow-gate.d.ts +135 -1
- package/dist/index.js +20 -18
- package/dist/tools/complete-pr-workflow.d.ts +3 -1
- package/dist/tools/pr-workflow-status.d.ts +2 -2
- package/dist/tools/write-pr-review-trigger-eval.d.ts +2 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.143.4",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},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",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","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","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro: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","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts"},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","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",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"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"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"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, 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_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_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_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately 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. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",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,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.143.6",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",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","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","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro: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","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts"},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","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",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"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"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"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, 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_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_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_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately 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. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",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,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -179,22 +179,24 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
|
|
|
179
179
|
`),totalLines=lines.length,startLine=Math.max(0,offset);if(startLine>=totalLines)return{totalLines,startLine,endLine:totalLines,content:"",exhausted:!0};let endLine=Math.min(startLine+limit,totalLines);return{totalLines,startLine,endLine,content:lines.slice(startLine,endLine).join(`
|
|
180
180
|
`),exhausted:!1}}function buildPreviewMarker(args2){let retrieval=args2.ref?` retrieve_lane_output ref=${args2.ref} for full output.`:" no full output artifact is available; treat this lane as degraded.";return`
|
|
181
181
|
[... lane output preview omitted middle content.${args2.degraded?" Artifact storage degraded.":""}${retrieval} ...]
|
|
182
|
-
`}function laneOutputRelativePath(ref){let[,batchDigest,laneDigest,outputDigest]=ref.split(":");return path7.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){mkdirSync2(path7.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 createHash2("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()});import*as crypto2 from"node:crypto";import*as fs4 from"node:fs";import*as path8 from"node:path";function getLockFilePath(directory,filePath){let normalized=path8.resolve(directory,filePath),baseDir=path8.resolve(directory)+path8.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=path8.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=path8.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 _internals6.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=path8.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_lockfile2.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=path8.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=path8.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=path8.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=path8.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs4.unlinkSync(lockPath)}catch{}try{fs4.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals6;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals6={tryAcquireLock,writeFile:fs4.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,FORBID_SESSION,CONSUMER_COST_ACCOUNTING,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:127"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:162"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:467",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:471",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:475",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:512",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:560",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:710",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:718",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:743",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:479",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:489",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:574",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:521",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:538",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:525",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:548",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:564",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:589",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:598",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:602",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:698",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:706",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:728",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:616",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:637",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:651",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:668",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:685",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:852",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:758",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:772",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:785",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:799",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:344",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:1842",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1143",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:836",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:191",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash4,randomBytes,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash4("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance is `delegation_end` (`src/telemetry.ts` `delegationEnd`, pre-existing): it coerces `?? 0` / `?? null` / `?? 'unavailable'` before emitting, so its cost fields can never appear in `unknown`; there, `cost_source: 'unavailable'` is how absence stays recoverable.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals7,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 path9 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_writeStream!==null||_disabled)return;try{_projectDirectory=projectDirectory;let swarmDir=path9.join(projectDirectory,".swarm");if(!fs5.existsSync(swarmDir))fs5.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path9.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 canonical=_internals7.createObservation(event,data),line=JSON.stringify(_internals7.toLegacyTelemetryLine(canonical))+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,_internals7.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path9.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs5.existsSync(telemetryPath))return;if(fs5.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path9.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{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path9.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve5)=>{stream.end(()=>resolve5())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals7;var init_telemetry=__esm(()=>{init_observability();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals7.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals7.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals7.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals7.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals7.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){_internals7.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals7.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals7.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals7.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals7.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals7.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals7.emit("budget_updated",{sessionId,budgetPct,agentName})},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals7.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},hardLimitHit(sessionId,agentName,limitType,value){_internals7.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals7.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals7.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals7.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals7.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals7.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals7.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals7.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals7.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals7.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals7.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals7.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals7.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals7.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals7.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals7.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals7.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals7.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals7.emit("close_archive_result",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals7.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})}},_internals7={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine}});import*as fs6 from"node:fs";import*as os3 from"node:os";import*as path10 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path10.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals8.lstatSync(path10.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative3=path10.relative(root,candidate);return relative3!==""&&relative3!==".."&&!relative3.startsWith(`..${path10.sep}`)&&!path10.isAbsolute(relative3)}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os3.tmpdir())||resolved===dependencies.realpathSync(os3.homedir())}catch{let resolved=path10.resolve(directory);return resolved===path10.resolve(os3.tmpdir())||resolved===path10.resolve(os3.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path10.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs6,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}if(hasExplicitProjectBoundary(resolved))return;let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);depth++;let parent=path10.dirname(current);if(parent===current)break;if(path10.dirname(parent)===parent){current=parent;continue}let parentSwarm=path10.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}throw warn(`[project-boundary] Cannot inspect ancestor state "${parentSwarm}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${parentSwarm}" is inaccessible`)}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${parent}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${parent}" are inaccessible`);if(indicatorState==="present")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${parent}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${parent}" already contains a .swarm/ folder. Runtime state must be written to the project root.`)}current=parent}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals8;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals8={lstatSync:fs6.lstatSync}});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){assertProjectRoot(directory);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((resolve6)=>setTimeout(resolve6,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();init_project_boundary();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,{writeDelegationFallback:()=>writeDelegationFallback,updateCoderSettlement:()=>updateCoderSettlement,sweepStaleDelegations:()=>sweepStaleDelegations,scanDelegationsForRecovery:()=>scanDelegationsForRecovery,scanDelegationFallbacksForRecovery:()=>scanDelegationFallbacksForRecovery,scanBackgroundCoderReservationsForAdmission:()=>scanBackgroundCoderReservationsForAdmission,reserveBackgroundCoderSlot:()=>reserveBackgroundCoderSlot,removeDelegationFallback:()=>removeDelegationFallback,releasePreparedBackgroundAdvisories:()=>releasePreparedBackgroundAdvisories,releaseBackgroundCoderReservation:()=>releaseBackgroundCoderReservation,recordPendingDelegationDetailed:()=>recordPendingDelegationDetailed,recordPendingDelegation:()=>recordPendingDelegation,recordDelegationIngestionResult:()=>recordDelegationIngestionResult,readDelegations:()=>readDelegations,readDelegationFallback:()=>readDelegationFallback,putPendingBackgroundAdvisory:()=>putPendingBackgroundAdvisory,promoteDelegationFallback:()=>promoteDelegationFallback,preparePendingBackgroundAdvisories:()=>preparePendingBackgroundAdvisories,normalizeBackgroundObservedFiles:()=>normalizeBackgroundObservedFiles,listDelegationFallbacks:()=>listDelegationFallbacks,findOpenAsyncLaneBatches:()=>findOpenAsyncLaneBatches,findDelegationForCompletion:()=>findDelegationForCompletion,findByCorrelationId:()=>findByCorrelationId,findByBatchId:()=>findByBatchId,claimTerminalResult:()=>claimTerminalResult,claimDelegationIngestion:()=>claimDelegationIngestion,claimCoderSettlement:()=>claimCoderSettlement,buildPromptSnapshot:()=>buildPromptSnapshot,buildBackgroundCompletionEventId:()=>buildBackgroundCompletionEventId,buildBackgroundCoderReservationId:()=>buildBackgroundCoderReservationId,bindBackgroundCoderReservation:()=>bindBackgroundCoderReservation,appendDelegationTransition:()=>appendDelegationTransition,acknowledgeObservedBackgroundAdvisories:()=>acknowledgeObservedBackgroundAdvisories,MAX_LIVE_BACKGROUND_FALLBACKS:()=>MAX_LIVE_BACKGROUND_FALLBACKS,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS:()=>MAX_LIVE_BACKGROUND_CODER_RESERVATIONS,MAX_BACKGROUND_OBSERVED_FILES:()=>MAX_BACKGROUND_OBSERVED_FILES,MAX_BACKGROUND_ADVISORY_CHARS:()=>MAX_BACKGROUND_ADVISORY_CHARS,BACKGROUND_INGESTION_LEASE_MS:()=>BACKGROUND_INGESTION_LEASE_MS,BACKGROUND_DELEGATION_FALLBACK_DIR:()=>BACKGROUND_DELEGATION_FALLBACK_DIR,BACKGROUND_DELEGATIONS_FILE:()=>BACKGROUND_DELEGATIONS_FILE,BACKGROUND_CODER_RESERVATIONS_FILE:()=>BACKGROUND_CODER_RESERVATIONS_FILE});import{createHash as createHash5}from"node:crypto";import*as fs7 from"node:fs";import*as path11 from"node:path";import{isDeepStrictEqual}from"node:util";function storePath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_FILE)}function ensureSwarmDir(directory){fs7.mkdirSync(path11.resolve(directory,".swarm"),{recursive:!0})}function readDelegations(directory){let raw;try{raw=fs7.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(`
|
|
182
|
+
`}function laneOutputRelativePath(ref){let[,batchDigest,laneDigest,outputDigest]=ref.split(":");return path7.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){mkdirSync2(path7.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 createHash2("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()});import*as crypto2 from"node:crypto";import*as fs4 from"node:fs";import*as path8 from"node:path";function getLockFilePath(directory,filePath){let normalized=path8.resolve(directory,filePath),baseDir=path8.resolve(directory)+path8.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=path8.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=path8.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 _internals6.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=path8.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_lockfile2.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=path8.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=path8.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=path8.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=path8.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs4.unlinkSync(lockPath)}catch{}try{fs4.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals6;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals6={tryAcquireLock,writeFile:fs4.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,FORBID_SESSION,CONSUMER_COST_ACCOUNTING,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:127"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:162"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:467",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:471",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:475",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:512",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:560",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:710",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:718",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:743",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:479",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:489",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:574",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:521",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:538",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:525",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:548",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:564",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:589",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:598",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:602",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:698",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:706",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:728",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:616",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:637",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:651",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:668",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:685",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:852",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:758",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:772",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:785",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:799",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:344",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:1842",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1143",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:836",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:191",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash4,randomBytes,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash4("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance is `delegation_end` (`src/telemetry.ts` `delegationEnd`, pre-existing): it coerces `?? 0` / `?? null` / `?? 'unavailable'` before emitting, so its cost fields can never appear in `unknown`; there, `cost_source: 'unavailable'` is how absence stays recoverable.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals7,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 path9 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_writeStream!==null||_disabled)return;try{_projectDirectory=projectDirectory;let swarmDir=path9.join(projectDirectory,".swarm");if(!fs5.existsSync(swarmDir))fs5.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path9.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 canonical=_internals7.createObservation(event,data),line=JSON.stringify(_internals7.toLegacyTelemetryLine(canonical))+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,_internals7.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path9.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs5.existsSync(telemetryPath))return;if(fs5.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path9.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{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path9.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve5)=>{stream.end(()=>resolve5())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals7;var init_telemetry=__esm(()=>{init_observability();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals7.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals7.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals7.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals7.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals7.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){_internals7.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals7.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals7.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals7.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals7.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals7.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals7.emit("budget_updated",{sessionId,budgetPct,agentName})},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals7.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},hardLimitHit(sessionId,agentName,limitType,value){_internals7.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals7.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals7.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals7.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals7.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals7.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals7.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals7.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals7.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals7.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals7.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals7.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals7.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals7.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals7.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals7.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals7.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals7.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals7.emit("close_archive_result",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals7.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})}},_internals7={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine}});import*as fs6 from"node:fs";import*as os3 from"node:os";import*as path10 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path10.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals8.lstatSync(path10.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative3=path10.relative(root,candidate);return relative3!==""&&relative3!==".."&&!relative3.startsWith(`..${path10.sep}`)&&!path10.isAbsolute(relative3)}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os3.tmpdir())||resolved===dependencies.realpathSync(os3.homedir())}catch{let resolved=path10.resolve(directory);return resolved===path10.resolve(os3.tmpdir())||resolved===path10.resolve(os3.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path10.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs6,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}if(hasExplicitProjectBoundary(resolved))return;let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);depth++;let parent=path10.dirname(current);if(parent===current)break;if(path10.dirname(parent)===parent){current=parent;continue}let parentSwarm=path10.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}throw warn(`[project-boundary] Cannot inspect ancestor state "${parentSwarm}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${parentSwarm}" is inaccessible`)}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${parent}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${parent}" are inaccessible`);if(indicatorState==="present")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${parent}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${parent}" already contains a .swarm/ folder. Runtime state must be written to the project root.`)}current=parent}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals8;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals8={lstatSync:fs6.lstatSync}});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){assertProjectRoot(directory);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((resolve6)=>setTimeout(resolve6,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();init_project_boundary();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,{writeDelegationFallback:()=>writeDelegationFallback,updateCoderSettlement:()=>updateCoderSettlement,sweepStaleDelegations:()=>sweepStaleDelegations,scanDelegationsForRecovery:()=>scanDelegationsForRecovery,scanDelegationFallbacksForRecovery:()=>scanDelegationFallbacksForRecovery,scanBackgroundCoderReservationsForAdmission:()=>scanBackgroundCoderReservationsForAdmission,reserveBackgroundCoderSlot:()=>reserveBackgroundCoderSlot,removeDelegationFallback:()=>removeDelegationFallback,releasePreparedBackgroundAdvisories:()=>releasePreparedBackgroundAdvisories,releaseBackgroundCoderReservation:()=>releaseBackgroundCoderReservation,recordPendingDelegationDetailed:()=>recordPendingDelegationDetailed,recordPendingDelegation:()=>recordPendingDelegation,recordDelegationIngestionResult:()=>recordDelegationIngestionResult,readDelegations:()=>readDelegations,readDelegationFallback:()=>readDelegationFallback,putPendingBackgroundAdvisory:()=>putPendingBackgroundAdvisory,promoteDelegationFallback:()=>promoteDelegationFallback,preparePendingBackgroundAdvisories:()=>preparePendingBackgroundAdvisories,normalizeBackgroundObservedFiles:()=>normalizeBackgroundObservedFiles,listDelegationFallbacks:()=>listDelegationFallbacks,findOpenAsyncLaneBatches:()=>findOpenAsyncLaneBatches,findDelegationForCompletion:()=>findDelegationForCompletion,findByCorrelationId:()=>findByCorrelationId,findByBatchId:()=>findByBatchId,claimTerminalResult:()=>claimTerminalResult,claimDelegationIngestion:()=>claimDelegationIngestion,claimCoderSettlement:()=>claimCoderSettlement,buildPromptSnapshot:()=>buildPromptSnapshot,buildBackgroundCompletionEventId:()=>buildBackgroundCompletionEventId,buildBackgroundCoderReservationId:()=>buildBackgroundCoderReservationId,bindBackgroundCoderReservation:()=>bindBackgroundCoderReservation,appendDelegationTransition:()=>appendDelegationTransition,acknowledgeObservedBackgroundAdvisories:()=>acknowledgeObservedBackgroundAdvisories,MAX_LIVE_BACKGROUND_FALLBACKS:()=>MAX_LIVE_BACKGROUND_FALLBACKS,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS:()=>MAX_LIVE_BACKGROUND_CODER_RESERVATIONS,MAX_BACKGROUND_OBSERVED_FILES:()=>MAX_BACKGROUND_OBSERVED_FILES,MAX_BACKGROUND_ADVISORY_CHARS:()=>MAX_BACKGROUND_ADVISORY_CHARS,DEFAULT_SWEEPABLE_DELEGATION_STATUSES:()=>DEFAULT_SWEEPABLE_DELEGATION_STATUSES,DEFAULT_STALE_DELEGATION_TIMEOUT_MS:()=>DEFAULT_STALE_DELEGATION_TIMEOUT_MS,BACKGROUND_INGESTION_LEASE_MS:()=>BACKGROUND_INGESTION_LEASE_MS,BACKGROUND_DELEGATION_FALLBACK_DIR:()=>BACKGROUND_DELEGATION_FALLBACK_DIR,BACKGROUND_DELEGATIONS_FILE:()=>BACKGROUND_DELEGATIONS_FILE,BACKGROUND_CODER_RESERVATIONS_FILE:()=>BACKGROUND_CODER_RESERVATIONS_FILE});import{createHash as createHash5}from"node:crypto";import*as fs7 from"node:fs";import*as path11 from"node:path";import{isDeepStrictEqual}from"node:util";function storePath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_FILE)}function ensureSwarmDir(directory){fs7.mkdirSync(path11.resolve(directory,".swarm"),{recursive:!0})}function readDelegations(directory){let raw;try{raw=fs7.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(`
|
|
183
183
|
`)){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 scanDelegationsForRecovery(directory){let absolutePath;try{if(absolutePath=storePath(directory),fs7.statSync(absolutePath).size>MAX_RECOVERY_LEDGER_BYTES)return{status:"uncertain",reason:`background delegation ledger exceeds the ${MAX_RECOVERY_LEDGER_BYTES}-byte recovery bound`}}catch(error49){if(error49.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`background delegation ledger metadata is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}let raw;try{raw=fs7.readFileSync(absolutePath,"utf-8")}catch(error49){return{status:"uncertain",reason:`background delegation ledger is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_RECOVERY_LEDGER_BYTES)return{status:"uncertain",reason:`background delegation ledger changed beyond the ${MAX_RECOVERY_LEDGER_BYTES}-byte recovery bound`};let folded=new Map,lineNumber=0;for(let line of raw.split(`
|
|
184
184
|
`)){lineNumber+=1;let trimmed=line.trim();if(!trimmed)continue;let parsedJson;try{parsedJson=JSON.parse(trimmed)}catch{return{status:"uncertain",reason:`background delegation ledger has malformed JSON at line ${lineNumber}`}}let parsed=RecordSchema.safeParse(parsedJson);if(!parsed.success)return{status:"uncertain",reason:`background delegation ledger has an invalid record at line ${lineNumber}`};folded.set(parsed.data.correlationId,parsed.data)}return{status:"ok",owners:[...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),fs7.appendFileSync(storePath(directory),`${JSON.stringify(record2)}
|
|
185
185
|
`,"utf-8")}function buildPendingRecord(input,now){return{schemaVersion:input.worktree?3: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.workflowGeneration!==void 0?{workflowGeneration:input.workflowGeneration}:{},...input.worktree?{worktree:input.worktree}:{},...input.coderReservationId?{coderReservationId:input.coderReservationId}:{},...input.prompt?{prompt:input.prompt}:{},...input.generation!==void 0?{generation:input.generation}:{}}}function pendingLaunchIdentity(record2){return{correlationId:record2.correlationId,jobId:record2.jobId,subagentSessionId:record2.subagentSessionId,parentSessionId:record2.parentSessionId,callID:record2.callID,normalizedAgent:record2.normalizedAgent,swarmPrefixedAgent:record2.swarmPrefixedAgent,planTaskId:record2.planTaskId,evidenceTaskId:record2.evidenceTaskId,batchId:record2.batchId,laneId:record2.laneId,mode:record2.mode,workflowLane:record2.workflowLane,ownedWorkflowLanes:record2.ownedWorkflowLanes,promptHash:record2.promptHash,workspace:record2.workspace,taskChangeContext:record2.taskChangeContext,workflowGeneration:record2.workflowGeneration,worktree:record2.worktree,coderReservationId:record2.coderReservationId,prompt:record2.prompt,generation:record2.generation??1}}function samePendingLaunchIdentity(left,right){return isDeepStrictEqual(pendingLaunchIdentity(left),pendingLaunchIdentity(right))}async function recordPendingDelegationDetailed(directory,input,options={}){let now=Date.now(),record2=buildPendingRecord(input,now),parsedRecord=RecordSchema.safeParse(record2);if(!parsedRecord.success)return warn("[background] recordPendingDelegation rejected invalid input"),{status:"failed",record:null};try{let outcome={status:"failed",record:null};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);let existing=findByCorrelationId(directory,parsedRecord.data.correlationId);if(existing){outcome={status:samePendingLaunchIdentity(existing,parsedRecord.data)?"duplicate":"conflict",record:existing};return}appendRecord(directory,parsedRecord.data),outcome={status:"recorded",record:parsedRecord.data}}),outcome}catch(err){return warn(`[background] recordPendingDelegation failed: ${err instanceof Error?err.message:String(err)}`),{status:"failed",record:null}}}async function recordPendingDelegation(directory,input,options={}){let outcome=await recordPendingDelegationDetailed(directory,input,options);return outcome.status==="recorded"||outcome.status==="duplicate"?outcome.record: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:createHash5("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"&&!(current.status==="completed"&&transition.status==="stale")){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 buildBackgroundCompletionEventId(input){let canonical=JSON.stringify([input.correlationId,input.jobId,input.status,input.resultDigest]);return`bgc1:${createHash5("sha256").update(canonical).digest("hex")}`}function sameJson(left,right){return JSON.stringify(left)===JSON.stringify(right)}function sameTerminalEvent(left,right){return left.eventId===right.eventId&&left.status===right.status&&sameJson(left.result,right.result)}function settlementProvenanceFor(record2){let baseline=record2.taskChangeContext?.baseline;if(!baseline)return null;return{correlationId:record2.correlationId,parentSessionId:record2.parentSessionId,callID:record2.callID,planTaskId:record2.planTaskId,baseline,worktree:record2.worktree??null}}function terminalDisposition(record2){if(record2.status==="consumed")return"consumed";if(record2.coderSettlement?.state==="settling")return"resume_settlement";if(record2.coderSettlement?.state==="preserved")return"preserved";if(record2.status==="ingestion_error")return"retry_ingestion";return"duplicate"}async function claimTerminalResult(directory,correlationId,terminalResult){let parsedTerminal=TerminalResultSchema.safeParse(terminalResult);if(!correlationId||!parsedTerminal.success)return null;let claim=null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let current=findByCorrelationId(directory,correlationId);if(!current)return;if(current.terminalResult){if(!sameTerminalEvent(current.terminalResult,parsedTerminal.data)){warn(`[background] claimTerminalResult: different terminal event for correlationId=${correlationId}; existing={status: ${current.terminalResult.status}, eventId: ${current.terminalResult.eventId}} incoming={status: ${parsedTerminal.data.status}, eventId: ${parsedTerminal.data.eventId}}; rejected`);return}claim={disposition:terminalDisposition(current),record:current};return}if(current.status!=="pending"&¤t.status!=="running")return;let coderSettlement=current.coderSettlement;if(current.normalizedAgent==="coder"&&!coderSettlement){let provenance=settlementProvenanceFor(current);if(provenance)coderSettlement={state:"pending",provenance,observedFiles:null,updatedAt:parsedTerminal.data.recordedAt}}let next={...current,schemaVersion:3,status:parsedTerminal.data.status,terminalResult:parsedTerminal.data,result:parsedTerminal.data.result,completedAt:parsedTerminal.data.recordedAt,updatedAt:parsedTerminal.data.recordedAt,...coderSettlement?{coderSettlement}:{}};if(!RecordSchema.safeParse(next).success)return;appendRecord(directory,next),claim={disposition:"claimed",record:next}}),claim}catch(err){return warn(`[background] claimTerminalResult failed: ${err instanceof Error?err.message:String(err)}`),null}}async function claimCoderSettlement(directory,correlationId,operationId,input={}){if(!correlationId||!operationId||operationId.length>256)return null;let claim=null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let current=findByCorrelationId(directory,correlationId);if(!current||current.normalizedAgent!=="coder"||current.terminalResult?.status!=="completed")return;let provenance=settlementProvenanceFor(current);if(!provenance)return;let existing=current.coderSettlement??{state:"pending",provenance,observedFiles:null,updatedAt:current.updatedAt};if(existing.state==="settled"||existing.state==="preserved"){claim={disposition:existing.state,record:current};return}if(existing.state==="settling"&&existing.operationId!==operationId)return;if(existing.sourceHeadAfterCommit!==void 0&&input.sourceHeadAfterCommit!==void 0&&existing.sourceHeadAfterCommit!==input.sourceHeadAfterCommit)return;if(existing.targetHeadBeforeMerge!==void 0&&input.targetHeadBeforeMerge!==void 0&&existing.targetHeadBeforeMerge!==input.targetHeadBeforeMerge)return;let settlement={...existing,state:"settling",operationId,...input.sourceHeadAfterCommit!==void 0?{sourceHeadAfterCommit:input.sourceHeadAfterCommit}:{},...input.targetHeadBeforeMerge!==void 0?{targetHeadBeforeMerge:input.targetHeadBeforeMerge}:{},updatedAt:Date.now()},next={...current,schemaVersion:3,coderSettlement:settlement,updatedAt:settlement.updatedAt};if(!RecordSchema.safeParse(next).success)return;appendRecord(directory,next),claim={disposition:existing.state==="settling"?"resume":"claimed",record:next}}),claim}catch(err){return warn(`[background] claimCoderSettlement failed: ${err instanceof Error?err.message:String(err)}`),null}}function normalizeObservedFile(value){if(typeof value!=="string")return null;let trimmed=value.trim().replace(/\\/g,"/");if(trimmed.length===0||trimmed.length>4096||trimmed.includes("\x00")||path11.posix.isAbsolute(trimmed)||/^[A-Za-z]:\//.test(trimmed))return null;let normalized=path11.posix.normalize(trimmed).replace(/^\.\//,"");if(normalized==="."||normalized===".."||normalized.startsWith("../")||normalized.endsWith("/"))return null;return normalized}function normalizeBackgroundObservedFiles(files){if(!Array.isArray(files)||files.length>MAX_BACKGROUND_OBSERVED_FILES)return null;let normalized=new Set;for(let file2 of files){let candidate=normalizeObservedFile(file2);if(!candidate)return null;normalized.add(candidate)}return[...normalized].sort()}async function updateCoderSettlement(directory,correlationId,input){if(!correlationId||!input.operationId)return null;let result=null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let current=findByCorrelationId(directory,correlationId),existing=current?.coderSettlement;if(!current||!existing)return;if(existing.state==="settled"||existing.state==="preserved"){result=current;return}if(existing.state!=="settling"||existing.operationId!==input.operationId)return;if(existing.sourceHeadAfterCommit!==void 0&&input.sourceHeadAfterCommit!==void 0&&existing.sourceHeadAfterCommit!==input.sourceHeadAfterCommit)return;if(existing.targetHeadBeforeMerge!==void 0&&input.targetHeadBeforeMerge!==void 0&&existing.targetHeadBeforeMerge!==input.targetHeadBeforeMerge)return;if((input.state==="settled"||input.state==="preserved")&&!input.outcome)return;if(input.outcome&&(existing.provenance.worktree&&input.outcome.kind!=="standard-worktree"||!existing.provenance.worktree&&input.outcome.kind!=="shared-root"))return;if(input.state==="settled"&&input.outcome&&(input.outcome.result==="partial"||input.outcome.result==="failed"))return;if(input.state==="preserved"&&input.outcome&&input.outcome.result!=="partial"&&input.outcome.result!=="failed")return;let observedFiles=existing.observedFiles;if(input.observedFiles!==void 0)if(input.observedFiles===null)observedFiles=null;else{let normalized=normalizeBackgroundObservedFiles(input.observedFiles);if(!normalized)return;observedFiles=normalized}if(input.state==="settled"&&observedFiles===null)return;let updatedAt=Date.now(),settlement={...existing,state:input.state,...input.sourceHeadAfterCommit!==void 0?{sourceHeadAfterCommit:input.sourceHeadAfterCommit}:{},...input.targetHeadBeforeMerge!==void 0?{targetHeadBeforeMerge:input.targetHeadBeforeMerge}:{},observedFiles,...input.outcome?{outcome:input.outcome}:{},updatedAt},next={...current,schemaVersion:3,coderSettlement:settlement,updatedAt};if(!RecordSchema.safeParse(next).success)return;appendRecord(directory,next),result=next}),result}catch(err){return warn(`[background] updateCoderSettlement failed: ${err instanceof Error?err.message:String(err)}`),null}}async function claimDelegationIngestion(directory,correlationId,options){if(!correlationId||!options.claimantId)return null;let now=options.now??Date.now(),leaseMs=Math.max(1000,Math.min(options.leaseMs??INGESTION_CLAIM_LEASE_MS,300000)),claim=null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let current=findByCorrelationId(directory,correlationId);if(!current?.terminalResult)return;if(current.status==="consumed"){claim={disposition:"consumed",record:current};return}if(current.ingestion?.state==="claimed"&&(current.ingestion.leaseExpiresAt??Number.MAX_SAFE_INTEGER)>now){claim={disposition:"busy",record:current};return}if(current.coderSettlement?.state==="preserved"){claim={disposition:"preserved",record:current};return}if(current.terminalResult.status!=="completed"||current.normalizedAgent==="coder"&¤t.coderSettlement?.state!=="settled"){claim={disposition:"not_ready",record:current};return}if(current.status!=="completed"&¤t.status!=="ingestion_error"){claim={disposition:"not_ready",record:current};return}let disposition=current.status==="ingestion_error"||current.ingestion?.state==="claimed"?"retry":"claimed",attempt=(current.ingestion?.attempt??0)+1,claimToken=createHash5("sha256").update(JSON.stringify([correlationId,options.claimantId,attempt,now])).digest("hex"),next={...current,schemaVersion:3,ingestion:{state:"claimed",attempt,updatedAt:now,claimToken,leaseExpiresAt:now+leaseMs},updatedAt:now};appendRecord(directory,next),claim={disposition,record:next}}),claim}catch(err){return warn(`[background] claimDelegationIngestion failed: ${err instanceof Error?err.message:String(err)}`),null}}async function recordDelegationIngestionResult(directory,correlationId,claimToken,success2,options={}){if(!correlationId||!claimToken)return null;let result=null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let current=findByCorrelationId(directory,correlationId);if(!current)return;if(success2&¤t.status==="consumed"&¤t.ingestion?.state==="consumed"&¤t.ingestion.claimToken===claimToken||!success2&¤t.status==="ingestion_error"&¤t.ingestion?.state==="retryable"&¤t.ingestion.claimToken===claimToken){result=current;return}if(current.ingestion?.state!=="claimed"||current.ingestion.claimToken!==claimToken||(current.ingestion.leaseExpiresAt??0)<=(options.now??Date.now()))return;let updatedAt=options.now??Date.now(),next={...current,schemaVersion:3,status:success2?"consumed":"ingestion_error",ingestion:{state:success2?"consumed":"retryable",attempt:current.ingestion.attempt,claimToken,updatedAt},updatedAt};appendRecord(directory,next),result=next}),result}catch(err){return warn(`[background] recordDelegationIngestionResult failed: ${err instanceof Error?err.message:String(err)}`),null}}async function putPendingBackgroundAdvisory(directory,correlationId,input){let createdAt=input.createdAt??Date.now(),parsed=AdvisoryInboxSchema.safeParse({eventId:input.eventId,parentSessionId:input.parentSessionId,state:"pending",message:input.message,createdAt});if(!correlationId||!parsed.success)return null;let result=null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let current=findByCorrelationId(directory,correlationId);if(!current?.terminalResult||current.terminalResult.eventId!==parsed.data.eventId||current.parentSessionId!==parsed.data.parentSessionId)return;if(current.advisoryInbox){if(current.advisoryInbox.eventId===parsed.data.eventId&¤t.advisoryInbox.parentSessionId===parsed.data.parentSessionId&¤t.advisoryInbox.message===parsed.data.message)result=current.advisoryInbox;return}let next={...current,schemaVersion:3,advisoryInbox:parsed.data,updatedAt:createdAt};appendRecord(directory,next),result=parsed.data}),result}catch(err){return warn(`[background] putPendingBackgroundAdvisory failed: ${err instanceof Error?err.message:String(err)}`),null}}async function preparePendingBackgroundAdvisories(directory,parentSessionId,options){if(!parentSessionId||!options.preparationId)return[];let now=options.now??Date.now(),leaseMs=Math.max(1000,Math.min(options.leaseMs??ADVISORY_PREPARE_LEASE_MS,300000)),prepared=[];try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{for(let current of readDelegations(directory)){if(prepared.length>=1)break;let advisory=current.advisoryInbox;if(!advisory||advisory.parentSessionId!==parentSessionId||advisory.state!=="pending")continue;if(advisory.preparation&&advisory.preparation.id!==options.preparationId&&advisory.preparation.leaseExpiresAt>now)continue;let nextAdvisory={...advisory,preparation:{id:options.preparationId,preparedAt:now,leaseExpiresAt:now+leaseMs}},next={...current,schemaVersion:3,advisoryInbox:nextAdvisory,updatedAt:now};appendRecord(directory,next),prepared.push(nextAdvisory)}}),prepared}catch(err){return warn(`[background] preparePendingBackgroundAdvisories failed: ${err instanceof Error?err.message:String(err)}`),[]}}async function releaseBackgroundAdvisoryPreparation(directory,parentSessionId,preparationId,eventIds){let uniqueEventIds=[...new Set(eventIds)];if(!parentSessionId||!preparationId||uniqueEventIds.length!==1)return!1;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let byEvent=new Map;for(let current of readDelegations(directory)){let advisory=current.advisoryInbox;if(advisory?.parentSessionId===parentSessionId&&uniqueEventIds.includes(advisory.eventId))byEvent.set(advisory.eventId,current)}for(let eventId of uniqueEventIds){let advisory=byEvent.get(eventId)?.advisoryInbox;if(!advisory||advisory.state!=="pending"||advisory.preparation?.id!==preparationId)return!1}for(let eventId of uniqueEventIds){let current=byEvent.get(eventId);if(!current?.advisoryInbox)return!1;let now=Date.now(),next={...current,schemaVersion:3,advisoryInbox:{...current.advisoryInbox,preparation:void 0},updatedAt:now};appendRecord(directory,next)}return!0})}catch(err){return warn(`[background] releasePreparedBackgroundAdvisories failed: ${err instanceof Error?err.message:String(err)}`),!1}}async function acknowledgeObservedBackgroundAdvisories(directory,parentSessionId,observedTexts){if(!parentSessionId||observedTexts.length===0)return 0;let acknowledged=0;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let now=Date.now();for(let current of readDelegations(directory)){let advisory=current.advisoryInbox;if(!advisory||advisory.parentSessionId!==parentSessionId||advisory.state!=="pending"||!observedTexts.some((text)=>{let advisoryBlock=text.match(/\[ADVISORIES\]([\s\S]*?)\[\/ADVISORIES\]/);if(advisoryBlock)return advisoryBlock[1].split(`
|
|
186
186
|
---
|
|
187
|
-
`).some((entry)=>entry.trim()===advisory.message);return text.includes(advisory.message)}))continue;let next={...current,schemaVersion:3,advisoryInbox:{...advisory,state:"delivered",deliveredAt:now,preparation:void 0},updatedAt:now};appendRecord(directory,next),acknowledged+=1}}),acknowledged}catch(err){return warn(`[background] acknowledgeObservedBackgroundAdvisories failed: ${err instanceof Error?err.message:String(err)}`),0}}async function releasePreparedBackgroundAdvisories(directory,parentSessionId,preparationId,eventIds){return releaseBackgroundAdvisoryPreparation(directory,parentSessionId,preparationId,eventIds)}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(
|
|
187
|
+
`).some((entry)=>entry.trim()===advisory.message);return text.includes(advisory.message)}))continue;let next={...current,schemaVersion:3,advisoryInbox:{...advisory,state:"delivered",deliveredAt:now,preparation:void 0},updatedAt:now};appendRecord(directory,next),acknowledged+=1}}),acknowledged}catch(err){return warn(`[background] acknowledgeObservedBackgroundAdvisories failed: ${err instanceof Error?err.message:String(err)}`),0}}async function releasePreparedBackgroundAdvisories(directory,parentSessionId,preparationId,eventIds){return releaseBackgroundAdvisoryPreparation(directory,parentSessionId,preparationId,eventIds)}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,statuses=DEFAULT_SWEEPABLE_DELEGATION_STATUSES){let swept=0;for(let record2 of readDelegations(directory)){if(!statuses.has(record2.status))continue;if(now-record2.updatedAt<=timeoutMs)continue;appendRecord(directory,{...record2,status:"stale",updatedAt:now}),swept+=1}return swept}async function sweepStaleDelegations(directory,timeoutMs,options={}){if(!timeoutMs||timeoutMs<=0)return 0;let statuses=options.statuses??DEFAULT_SWEEPABLE_DELEGATION_STATUSES;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>sweepStaleLocked(directory,timeoutMs,Date.now(),statuses))}catch(err){return warn(`[background] sweepStaleDelegations failed: ${err instanceof Error?err.message:String(err)}`),0}}function fallbackRelativePath(correlationId){let digest=createHash5("sha256").update(correlationId).digest("hex");return path11.join(BACKGROUND_DELEGATION_FALLBACK_DIR,`${digest}.json`)}function fallbackPath(directory,correlationId){return validateSwarmPath(directory,fallbackRelativePath(correlationId))}function fallbackDirectoryPath(directory){return path11.dirname(validateSwarmPath(directory,path11.join(BACKGROUND_DELEGATION_FALLBACK_DIR,".containment-anchor")))}async function readFallbackFile(directory,correlationId){for(let attempt=0;attempt<5;attempt++)try{let raw=await fs7.promises.readFile(fallbackPath(directory,correlationId),"utf-8"),parsedJson=JSON.parse(raw),parsed=FallbackArtifactSchema.safeParse(parsedJson);if(!parsed.success||parsed.data.correlationId!==correlationId)return null;return parsed.data}catch(err){if(err.code==="ENOENT"&&attempt<4){await new Promise((resolve7)=>setTimeout(resolve7,10));continue}return null}return null}async function readDelegationFallback(directory,correlationId){if(!correlationId)return null;return readFallbackFile(directory,correlationId)}async function listDelegationFallbacks(directory){let entries;try{entries=fs7.readdirSync(fallbackDirectoryPath(directory),{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).slice(0,MAX_LIVE_BACKGROUND_FALLBACKS)}catch{return[]}let artifacts=[];for(let entry of entries)try{let raw=await fs7.promises.readFile(path11.join(fallbackDirectoryPath(directory),entry.name),"utf-8"),parsed=FallbackArtifactSchema.safeParse(JSON.parse(raw));if(parsed.success)artifacts.push(parsed.data)}catch{}return artifacts}async function scanDelegationFallbacksForRecovery(directory){let fallbackDir,entries;try{fallbackDir=fallbackDirectoryPath(directory),entries=fs7.readdirSync(fallbackDir,{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json"))}catch(error49){if(error49.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`background fallback directory is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(entries.length>MAX_LIVE_BACKGROUND_FALLBACKS)return{status:"uncertain",reason:`background fallback owner count exceeds the ${MAX_LIVE_BACKGROUND_FALLBACKS}-artifact safety bound`};let artifacts=[];for(let entry of entries){let artifactPath=path11.join(fallbackDir,entry.name),raw;try{if(fs7.statSync(artifactPath).size>MAX_RECOVERY_FALLBACK_BYTES)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" exceeds the recovery size bound`};raw=await fs7.promises.readFile(artifactPath,"utf-8")}catch(error49){return{status:"uncertain",reason:`background fallback artifact "${entry.name}" is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_RECOVERY_FALLBACK_BYTES)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" changed beyond the recovery size bound`};let parsedJson;try{parsedJson=JSON.parse(raw)}catch{return{status:"uncertain",reason:`background fallback artifact "${entry.name}" has malformed JSON`}}let parsed=FallbackArtifactSchema.safeParse(parsedJson);if(!parsed.success)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" has an invalid owner record`};artifacts.push(parsed.data)}return{status:"ok",owners:artifacts}}function countFallbackFiles(directory){try{return fs7.readdirSync(fallbackDirectoryPath(directory),{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).length}catch(err){if(err.code==="ENOENT")return 0;return MAX_LIVE_BACKGROUND_FALLBACKS}}async function writeDelegationFallback(directory,input,options={}){let now=Date.now(),record2={...buildPendingRecord(input,now),schemaVersion:3},artifact={schemaVersion:1,correlationId:input.correlationId,createdAt:now,record:record2},parsed=FallbackArtifactSchema.safeParse(artifact);if(!parsed.success)return null;let requestedCap=Math.floor(Math.max(1,options.maxLive??MAX_LIVE_BACKGROUND_FALLBACKS)),maxLive=Math.min(requestedCap,MAX_LIVE_BACKGROUND_FALLBACKS);try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT,FALLBACK_LOCK_TASK,async()=>{let existing=await readFallbackFile(directory,input.correlationId);if(existing)return samePendingRecord(existing.record,parsed.data.record)?existing:null;if(countFallbackFiles(directory)>=maxLive)return null;let absPath=fallbackPath(directory,input.correlationId);return fs7.mkdirSync(path11.dirname(absPath),{recursive:!0}),await bunWrite(absPath,`${JSON.stringify(parsed.data)}
|
|
188
188
|
`),parsed.data})}catch(err){return warn(`[background] writeDelegationFallback failed: ${err instanceof Error?err.message:String(err)}`),null}}async function removeDelegationFallback(directory,correlationId){if(!correlationId)return!1;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT,FALLBACK_LOCK_TASK,async()=>{try{return await fs7.promises.unlink(fallbackPath(directory,correlationId)),!0}catch(err){return err.code==="ENOENT"}})}catch(err){return warn(`[background] removeDelegationFallback failed: ${err instanceof Error?err.message:String(err)}`),!1}}async function findDelegationForCompletion(directory,correlationId){if(!correlationId)return null;let primary=findByCorrelationId(directory,correlationId);if(primary)return{source:"primary",record:primary};let fallback=await readDelegationFallback(directory,correlationId);return fallback?{source:"fallback",record:fallback.record,fallback}:null}function samePromotionIdentity(primary,fallback){return primary.correlationId===fallback.correlationId&&primary.subagentSessionId===fallback.subagentSessionId&&primary.parentSessionId===fallback.parentSessionId&&primary.callID===fallback.callID&&primary.planTaskId===fallback.planTaskId&&primary.coderReservationId===fallback.coderReservationId&&sameJson(primary.worktree??null,fallback.worktree??null)&&sameJson(primary.taskChangeContext??null,fallback.taskChangeContext??null)}function samePendingRecord(left,right){let{createdAt:_leftCreatedAt,updatedAt:_leftUpdatedAt,...leftIdentity}=left,{createdAt:_rightCreatedAt,updatedAt:_rightUpdatedAt,...rightIdentity}=right;return sameJson(leftIdentity,rightIdentity)}async function promoteDelegationFallback(directory,correlationId){if(!correlationId)return null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT,FALLBACK_LOCK_TASK,async()=>{let fallback=await readFallbackFile(directory,correlationId);if(!fallback){let primary=findByCorrelationId(directory,correlationId);return primary?{source:"primary",record:primary}:null}let promoted=null;if(await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let current=findByCorrelationId(directory,correlationId);if(current){if(samePromotionIdentity(current,fallback.record))promoted=current;return}appendRecord(directory,fallback.record),promoted=fallback.record}),!promoted)return null;try{await fs7.promises.unlink(fallbackPath(directory,correlationId))}catch(err){if(err.code!=="ENOENT")return null}return{source:"primary",record:promoted}})}catch(err){return warn(`[background] promoteDelegationFallback failed: ${err instanceof Error?err.message:String(err)}`),null}}function reservationStorePath(directory){return validateSwarmPath(directory,BACKGROUND_CODER_RESERVATIONS_FILE)}function buildBackgroundCoderReservationId(input){let ownerIdentity=input.planTaskId===null?["call",input.parentSessionId,input.callID]:["task",input.parentSessionId,input.planTaskId];return`bgcr1:${createHash5("sha256").update(JSON.stringify(ownerIdentity)).digest("hex")}`}function scanBackgroundCoderReservationsForAdmission(directory){let absolutePath,raw;try{if(absolutePath=reservationStorePath(directory),fs7.statSync(absolutePath).size>MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES)return{status:"uncertain",reason:`background coder reservation store exceeds the ${MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES}-byte safety bound`};raw=fs7.readFileSync(absolutePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return{status:"ok",reservations:[]};return{status:"uncertain",reason:`background coder reservation store is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES)return{status:"uncertain",reason:"background coder reservation store changed beyond its safety bound"};let parsedJson;try{parsedJson=JSON.parse(raw)}catch{return{status:"uncertain",reason:"background coder reservation store contains malformed JSON"}}let parsed=BackgroundCoderReservationStoreSchema.safeParse(parsedJson);if(!parsed.success)return{status:"uncertain",reason:"background coder reservation store failed strict schema validation"};return{status:"ok",reservations:parsed.data.reservations}}async function writeBackgroundCoderReservations(directory,reservations){let parsed=BackgroundCoderReservationStoreSchema.safeParse({schemaVersion:1,reservations});if(!parsed.success)return!1;try{return await bunWrite(reservationStorePath(directory),`${JSON.stringify(parsed.data)}
|
|
189
|
-
`),!0}catch(error49){return warn(`[background] reservation write failed: ${error49 instanceof Error?error49.message:String(error49)}`),!1}}function reservationOwnerKey(input){return input.planTaskId===null?`call:${input.parentSessionId}:${input.callID}`:`task:${input.parentSessionId}:${input.planTaskId}`}function isActiveCoderOwner(record2){if(record2.normalizedAgent!=="coder"||record2.status==="consumed")return!1;if(record2.status==="pending"||record2.status==="running"||record2.status==="completed"||record2.status==="ingestion_error")return!0;if(record2.coderSettlement?.state==="preserved")return!0;return record2.worktree!==void 0}async function scanDurableCoderOwners(directory){let fallbackScan=await scanDelegationFallbacksForRecovery(directory);if(fallbackScan.status==="uncertain")return fallbackScan;let primaryScan=scanDelegationsForRecovery(directory);if(primaryScan.status==="uncertain")return primaryScan;let recordsByCorrelation=new Map;for(let artifact of fallbackScan.owners)recordsByCorrelation.set(artifact.correlationId,artifact.record);let primaryByCorrelation=new Map,primaryByReservationId=new Map;for(let record2 of primaryScan.owners){if(primaryByCorrelation.set(record2.correlationId,record2),record2.coderReservationId){let owners=primaryByReservationId.get(record2.coderReservationId)??[];owners.push(record2),primaryByReservationId.set(record2.coderReservationId,owners)}recordsByCorrelation.set(record2.correlationId,record2)}return{status:"ok",recordsByCorrelation,primaryByCorrelation,primaryByReservationId}}function exactReservationOwnerCoordinates(reservation,record2){return record2.coderReservationId===reservation.reservationId&&record2.parentSessionId===reservation.parentSessionId&&record2.planTaskId===reservation.planTaskId&&record2.callID===reservation.callID}function exactReservationRecordMatch(reservation,record2){return exactReservationOwnerCoordinates(reservation,record2)&&record2.correlationId===reservation.correlationId}function findExactPrimaryReservationOwner(reservation,ownerScan){if(reservation.correlationId!==null){let primary=ownerScan.primaryByCorrelation.get(reservation.correlationId);return primary&&exactReservationRecordMatch(reservation,primary)?primary:null}let exactOwners=(ownerScan.primaryByReservationId.get(reservation.reservationId)??[]).filter((record2)=>exactReservationOwnerCoordinates(reservation,record2));return exactOwners.length===1?exactOwners[0]:null}function hasProvenReleasedReservationOwner(record2){if(record2.status==="consumed")return!0;return record2.worktree===void 0&&(record2.status==="error"||record2.status==="cancelled")&&record2.terminalResult?.status===record2.status}function validateReservationIdentity(input){return typeof input.parentSessionId==="string"&&input.parentSessionId.length>0&&input.parentSessionId.length<=256&&input.parentSessionId.trim()===input.parentSessionId&&typeof input.callID==="string"&&input.callID.length>0&&input.callID.length<=256&&input.callID.trim()===input.callID&&(input.planTaskId===null||typeof input.planTaskId==="string"&&input.planTaskId.length>0&&input.planTaskId.length<=256&&input.planTaskId.trim()===input.planTaskId)}async function reserveBackgroundCoderSlot(directory,input){if(!validateReservationIdentity(input)||!Number.isInteger(input.maxConcurrent)||input.maxConcurrent<1||input.maxConcurrent>64||(input.occupiedTaskIds?.length??0)>64)return{ok:!1,reason:"invalid"};let occupiedTaskIds=new Set;for(let taskId of input.occupiedTaskIds??[]){if(typeof taskId!=="string"||taskId.length===0||taskId.length>256||taskId.trim()!==taskId)return{ok:!1,reason:"invalid"};occupiedTaskIds.add(taskId)}try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let reservationScan=scanBackgroundCoderReservationsForAdmission(directory);if(reservationScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:reservationScan.reason};let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:ownerScan.reason};let reservations=reservationScan.reservations.filter((reservation2)=>{let primary=findExactPrimaryReservationOwner(reservation2,ownerScan);return!(primary&&hasProvenReleasedReservationOwner(primary))});if(reservations.length!==reservationScan.reservations.length&&!await writeBackgroundCoderReservations(directory,reservations))return{ok:!1,reason:"uncertain",detail:"finished reservation reconciliation could not be persisted"};let activeOwnerKeys=new Set;for(let taskId of occupiedTaskIds)activeOwnerKeys.add(reservationOwnerKey({parentSessionId:input.parentSessionId,planTaskId:taskId,callID:""}));for(let reservation2 of reservations)if(reservation2.parentSessionId===input.parentSessionId)activeOwnerKeys.add(reservationOwnerKey(reservation2));for(let record2 of ownerScan.recordsByCorrelation.values())if(record2.parentSessionId===input.parentSessionId&&isActiveCoderOwner(record2))activeOwnerKeys.add(reservationOwnerKey({parentSessionId:record2.parentSessionId,planTaskId:record2.planTaskId,callID:record2.callID}));let reservationId=buildBackgroundCoderReservationId(input),existing=reservations.find((reservation2)=>reservation2.reservationId===reservationId);if(existing)return{ok:!1,reason:input.planTaskId===null?"duplicate_call":"duplicate_task",activeCount:activeOwnerKeys.size,existing};let incomingOwnerKey=reservationOwnerKey(input);if(input.planTaskId!==null&&activeOwnerKeys.has(incomingOwnerKey))return{ok:!1,reason:"duplicate_task",activeCount:activeOwnerKeys.size};if(activeOwnerKeys.size>=input.maxConcurrent)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size};if(reservations.length>=MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size,detail:"durable reservation store is at its hard safety cap"};let now=input.now??Date.now(),reservation={reservationId,parentSessionId:input.parentSessionId,planTaskId:input.planTaskId,callID:input.callID,state:"reserved",correlationId:null,createdAt:now,updatedAt:now};if(!await writeBackgroundCoderReservations(directory,[...reservations,reservation]))return{ok:!1,reason:"uncertain",detail:"durable reservation claim could not be persisted"};return{ok:!0,reservation,activeCount:activeOwnerKeys.size+1}})}catch(error49){return{ok:!1,reason:"uncertain",detail:`background coder reservation lock failed: ${error49 instanceof Error?error49.message:String(error49)}`}}}async function bindBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||!input.correlationId||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId||input.reservationId!==buildBackgroundCoderReservationId(input))return null;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return null;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return null;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID)return null;if(current.state==="bound")return current.correlationId===input.correlationId?current:null;let next={...current,state:"bound",correlationId:input.correlationId,updatedAt:input.now??Date.now()},reservations=[...scan.reservations];return reservations[index]=next,await writeBackgroundCoderReservations(directory,reservations)?next:null})}catch{return null}}async function releaseBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||input.reservationId!==buildBackgroundCoderReservationId(input)||input.correlationId!==null&&(input.correlationId.length===0||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId))return!1;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return!1;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return!1;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID||current.correlationId!==input.correlationId)return!1;if(input.reason==="consumed"){if(current.state!=="bound"||!current.correlationId)return!1;let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return!1;let primary=ownerScan.primaryByCorrelation.get(current.correlationId);if(!primary||primary.status!=="consumed"||!exactReservationRecordMatch(current,primary))return!1}let reservations=scan.reservations.filter((_,reservationIndex)=>reservationIndex!==index);return writeBackgroundCoderReservations(directory,reservations)})}catch{return!1}}var BACKGROUND_DELEGATIONS_FILE="background-delegations.jsonl",BACKGROUND_DELEGATION_FALLBACK_DIR="background-delegation-fallback",BACKGROUND_CODER_RESERVATIONS_FILE="background-coder-reservations.json",MAX_LIVE_BACKGROUND_FALLBACKS=256,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS=256,MAX_BACKGROUND_OBSERVED_FILES=5000,MAX_BACKGROUND_ADVISORY_CHARS=4000,MAX_BACKGROUND_DELEGATION_GENERATION=1e6,MAX_RECOVERY_LEDGER_BYTES=4194304,MAX_RECOVERY_FALLBACK_BYTES=1048576,STORE_LOCK_AGENT="background",STORE_LOCK_TASK="background-delegations",FALLBACK_LOCK_TASK="background-delegation-fallback",RESERVATION_LOCK_TASK="background-coder-reservations",ADVISORY_PREPARE_LEASE_MS=30000,INGESTION_CLAIM_LEASE_MS=30000,BACKGROUND_INGESTION_LEASE_MS=30000,ResultSchema,WorkspaceSchema,TaskChangeContextSchema,WorktreeDescriptorSchema,TerminalResultSchema,NormalizedObservedFileSchema,SettlementProvenanceSchema,SettlementOutcomeSchema,CoderSettlementSchema,AdvisoryPreparationSchema,AdvisoryInboxSchema,DelegationIngestionSchema,BackgroundCoderReservationSchema,BackgroundCoderReservationStoreSchema,PromptSchema,RecordSchema,FallbackArtifactSchema,MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES=2097152;var init_pending_delegations=__esm(()=>{init_zod();init_lock();init_utils2();init_bun_compat();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(),salvagedWorkflowLanes:exports_external.array(exports_external.string()).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,workflowGeneration:exports_external.number().int().nonnegative().optional()}).strict(),WorktreeDescriptorSchema=exports_external.object({callID:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),taskId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),worktreePath:exports_external.string().min(1).max(4096),branchName:exports_external.string().min(1).max(1024),worktreeId:exports_external.string().min(1).max(256),worktreeSessionId:exports_external.string().min(1).max(256),mergeStrategy:exports_external.enum(["merge","rebase","cherry-pick"]),laneIndex:exports_external.number().int().nonnegative().max(255),worktreeDir:exports_external.string().min(1).max(4096).nullable()}).strict(),TerminalResultSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),status:exports_external.enum(["completed","error","cancelled"]),recordedAt:exports_external.number().int().nonnegative(),result:ResultSchema}).strict(),NormalizedObservedFileSchema=exports_external.string().min(1).max(4096).refine((value)=>normalizeObservedFile(value)===value),SettlementProvenanceSchema=exports_external.object({correlationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),callID:exports_external.string().max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),baseline:WorkspaceSchema,worktree:WorktreeDescriptorSchema.nullable()}).strict(),SettlementOutcomeSchema=exports_external.object({kind:exports_external.enum(["shared-root","standard-worktree"]),result:exports_external.enum(["ready","merged","unchanged","partial","failed"]),reason:exports_external.string().min(1).max(2000).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),targetHeadAfterMerge:exports_external.string().min(1).max(256).nullable().optional()}).strict(),CoderSettlementSchema=exports_external.object({state:exports_external.enum(["pending","settling","settled","preserved"]),provenance:SettlementProvenanceSchema,operationId:exports_external.string().min(1).max(256).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),observedFiles:exports_external.array(NormalizedObservedFileSchema).max(MAX_BACKGROUND_OBSERVED_FILES).nullable(),outcome:SettlementOutcomeSchema.optional(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state!=="pending"&&!value.operationId)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"settling, settled, and preserved states require operationId"});if((value.state==="settled"||value.state==="preserved")&&!value.outcome)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"terminal settlement state requires outcome"})}),AdvisoryPreparationSchema=exports_external.object({id:exports_external.string().min(1).max(256),preparedAt:exports_external.number().int().nonnegative(),leaseExpiresAt:exports_external.number().int().nonnegative()}).strict(),AdvisoryInboxSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),state:exports_external.enum(["pending","delivered"]),message:exports_external.string().min(1).max(MAX_BACKGROUND_ADVISORY_CHARS),createdAt:exports_external.number().int().nonnegative(),preparation:AdvisoryPreparationSchema.optional(),deliveredAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="delivered"&&value.deliveredAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory requires deliveredAt"});if(value.state==="delivered"&&value.preparation!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory cannot retain a preparation lease"})}),DelegationIngestionSchema=exports_external.object({state:exports_external.enum(["claimed","retryable","consumed"]),attempt:exports_external.number().int().positive(),updatedAt:exports_external.number().int().nonnegative(),claimToken:exports_external.string().min(1).max(256),leaseExpiresAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="claimed"&&value.leaseExpiresAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"claimed ingestion requires a lease expiry"});if(value.state!=="claimed"&&value.leaseExpiresAt!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"completed ingestion cannot retain a claim lease"})}),BackgroundCoderReservationSchema=exports_external.object({reservationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),callID:exports_external.string().min(1).max(256),state:exports_external.enum(["reserved","bound"]),correlationId:exports_external.string().min(1).max(256).nullable(),createdAt:exports_external.number().int().nonnegative(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state==="reserved"&&value.correlationId!==null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"unbound reservation cannot have a correlationId"});if(value.state==="bound"&&value.correlationId===null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"bound reservation requires a correlationId"})}),BackgroundCoderReservationStoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),reservations:exports_external.array(BackgroundCoderReservationSchema).max(MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)}).strict().superRefine((value,context)=>{let ids=new Set;for(let reservation of value.reservations){if(ids.has(reservation.reservationId)){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"duplicate reservationId"});return}if(reservation.reservationId!==buildBackgroundCoderReservationId({parentSessionId:reservation.parentSessionId,planTaskId:reservation.planTaskId,callID:reservation.callID})){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"reservationId does not match owner identity"});return}ids.add(reservation.reservationId)}}),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),exports_external.literal(3)]),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(),workflowGeneration:exports_external.number().int().nonnegative().optional(),worktree:WorktreeDescriptorSchema.optional(),coderReservationId:exports_external.string().min(1).max(256).optional(),prompt:PromptSchema.optional(),generation:exports_external.number().int().positive().max(MAX_BACKGROUND_DELEGATION_GENERATION).optional(),terminalResult:TerminalResultSchema.optional(),coderSettlement:CoderSettlementSchema.optional(),advisoryInbox:AdvisoryInboxSchema.optional(),ingestion:DelegationIngestionSchema.optional(),result:ResultSchema.optional(),completedAt:exports_external.number().optional()}).strict(),FallbackArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(1),correlationId:exports_external.string().min(1).max(256),createdAt:exports_external.number().int().nonnegative(),record:RecordSchema}).strict().superRefine((value,context)=>{if(value.record.correlationId!==value.correlationId||value.record.subagentSessionId!==value.correlationId||value.record.status!=="pending")context.addIssue({code:exports_external.ZodIssueCode.custom,message:"fallback identity/status does not match its pending record"})})});import{createHash as createHash6}from"node:crypto";function rawTriggerIds(input){if(!Array.isArray(input))return null;let ids=[];for(let row of input){if(typeof row!=="object"||row===null)return null;let triggerId=row.trigger_id;if(typeof triggerId!=="string"||!triggerId.trim())return null;ids.push(triggerId.trim())}return ids}function assertExactTriggerIdSet(input){let ids=rawTriggerIds(input);if(!ids)return;let expected=new Set(PR_REVIEW_REQUIRED_TRIGGER_IDS),seen=new Set,duplicate=new Set;for(let id of ids){if(seen.has(id))duplicate.add(id);seen.add(id)}if(duplicate.size>0)throw Error(`duplicate trigger IDs: ${[...duplicate].join(", ")}`);let unknown2=[...seen].filter((id)=>!expected.has(id));if(unknown2.length>0)throw Error(`unknown trigger IDs: ${unknown2.join(", ")}. trigger_id must be one of the 11 mandatory micro-lane IDs: ${[...expected].join(", ")}. Base-lane IDs and mode strings (e.g. swarm-pr-review:base) are NOT trigger IDs.`);let missing=[...expected].filter((id)=>!seen.has(id));if(missing.length>0)throw Error(`missing trigger IDs: ${missing.join(", ")}`)}function assertMatchedRowsHaveProvenance(input){if(!Array.isArray(input))return;for(let row of input){if(typeof row!=="object"||row===null)continue;let value=row;if(value.result!=="MATCHED")continue;if(typeof value.source_batch_id!=="string"||!value.source_batch_id.trim()||typeof value.source_lane_id!=="string"||!value.source_lane_id.trim())throw Error(`MATCHED rows require source_batch_id and source_lane_id: ${String(value.trigger_id??"(missing trigger_id)")}`)}}function assertNoLegacyNoMatchResult(input){if(!Array.isArray(input))return;for(let row of input){if(typeof row!=="object"||row===null)continue;if(row.result==="NO-MATCH")throw Error("NO-MATCH is not a valid PR_REVIEW trigger result; use MATCHED or NOT_TRIGGERED with concrete evidence")}}function exactTriggerRows(rows){let expected=new Set(PR_REVIEW_REQUIRED_TRIGGER_IDS),seen=new Set,duplicate=new Set;for(let row of rows){if(seen.has(row.trigger_id))duplicate.add(row.trigger_id);seen.add(row.trigger_id)}let unknown2=[...seen].filter((id)=>!expected.has(id)),missing=[...expected].filter((id)=>!seen.has(id));if(duplicate.size>0||unknown2.length>0||missing.length>0)throw Error(`PR_REVIEW trigger ledger must be exact; missing: ${missing.join(", ")||"(none)"}; duplicate: ${[...duplicate].join(", ")||"(none)"}; unknown: ${unknown2.join(", ")||"(none)"}`);let byId=new Map(rows.map((row)=>[row.trigger_id,row]));return PR_REVIEW_REQUIRED_TRIGGER_IDS.map((id)=>{let row=byId.get(id);if(!row)throw Error(`missing trigger row: ${id}`);return row})}function summarizeTriggerRows(rows){let orderedRows=exactTriggerRows(rows);if(orderedRows.find((row)=>row.trigger_id==="unclassified-risk")?.result!=="MATCHED")throw Error("PR_REVIEW trigger ledger requires unclassified-risk to remain MATCHED as the fallback family");return{rows:orderedRows,matchedIds:orderedRows.filter((row)=>row.result==="MATCHED").map((row)=>row.trigger_id),notTriggeredIds:orderedRows.filter((row)=>row.result==="NOT_TRIGGERED").map((row)=>row.trigger_id)}}function parseRows(input,schema,label){let parsed=exports_external.array(schema).safeParse(input);if(!parsed.success)throw Error(`${label}: ${parsed.error.issues.map((issue2)=>`${issue2.path.join(".")}: ${issue2.message}`).join("; ")}`);return parsed.data}function validatePrReviewInlineTriggerLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),summarizeTriggerRows(parseRows(input,PrReviewInlineTriggerRowSchema,"Invalid trigger ledger"))}function validatePrReviewPersistedInputLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),assertMatchedRowsHaveProvenance(input),summarizeTriggerRows(parseRows(input,PrReviewPersistedInputRowSchema,"Invalid persisted trigger ledger"))}function validatePrReviewWriterInputLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),assertMatchedRowsHaveProvenance(input),summarizeTriggerRows(parseRows(input,PrReviewWriterInputRowSchema,"Invalid final-writer trigger ledger"))}function assertCanonicalDefinitionFields(rows){let definitions=new Map(PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>[definition.id,definition]));for(let row of rows){let definition=definitions.get(row.trigger_id);if(!definition||row.scope!==definition.scope||row.trigger_row!==definition.trigger_row||row.micro_lane!==definition.micro_lane)throw Error(`PR_REVIEW trigger definition drift for ${row.trigger_id}: scope, trigger_row, and micro_lane must match the canonical definition`)}}function dispatchedMicroLaneCount(rows){return new Set(rows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size}function buildPrReviewTriggerReceiptV2(input){let envelope=ReceiptEnvelopeSchema.parse(input),validated=validatePrReviewPersistedInputLedger(input.rows),dispatchedCount=dispatchedMicroLaneCount(validated.rows);if(envelope.dispatched_micro_lane_count!==dispatchedCount)throw Error(`PR_REVIEW trigger receipt dispatched_micro_lane_count is inconsistent: expected ${dispatchedCount}`);let rows=validated.rows.map((row)=>{let definition=PR_REVIEW_TRIGGER_DEFINITIONS.find((candidate)=>candidate.id===row.trigger_id);if(!definition)throw Error(`unknown trigger definition: ${row.trigger_id}`);return{trigger_id:row.trigger_id,scope:definition.scope,trigger_row:definition.trigger_row,micro_lane:definition.micro_lane,result:row.result,evidence:row.evidence,...row.result==="MATCHED"?{source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}:{}}});return V2ReceiptSchema.parse({...envelope,schema_version:2,trigger_count:rows.length,matched_count:validated.matchedIds.length,not_triggered_count:validated.notTriggeredIds.length,no_match_count:0,rows,coverage_degradations:input.coverage_degradations??[]})}function prReviewTriggerLedgerDigest(rows){let canonical=rows.map((row)=>[row.trigger_id,row.result,row.evidence]);return createHash6("sha256").update(JSON.stringify(canonical)).digest("hex")}function parsedReceipt(schemaVersion,rows,coverageDegradations=[]){return{schemaVersion,rows,matchedRows:rows.filter((row)=>row.result==="MATCHED"),notTriggeredRows:rows.filter((row)=>row.result==="NOT_TRIGGERED"),coverageDegradations}}function parsePrReviewTriggerReceipt(input){if(typeof input!=="object"||input===null)throw Error("PR_REVIEW trigger receipt must be an object");let schemaVersion=input.schema_version;if(schemaVersion===2){let receipt=V2ReceiptSchema.parse(input);assertCanonicalDefinitionFields(receipt.rows);let normalizedRows=receipt.rows.map((row)=>({trigger_id:row.trigger_id,result:row.result,evidence:row.evidence,...row.result==="MATCHED"?{source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}:{}})),validated2=validatePrReviewPersistedInputLedger(normalizedRows),counts={trigger_count:validated2.rows.length,matched_count:validated2.matchedIds.length,not_triggered_count:validated2.notTriggeredIds.length,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount(validated2.rows)};for(let[field,expected]of Object.entries(counts))if(receipt[field]!==expected)throw Error(`PR_REVIEW trigger receipt ${field} is inconsistent: expected ${expected}`);return parsedReceipt(2,validated2.rows,receipt.coverage_degradations)}if(schemaVersion!==void 0&&schemaVersion!==1)throw Error(`Unsupported PR_REVIEW trigger schema_version: ${schemaVersion}`);let legacyEnvelope=schemaVersion===1?V1ReceiptSchema.parse(input):UnversionedRowOnlyReceiptSchema.parse(input),rowsInput=legacyEnvelope.rows,parsedLegacyRows=parseRows(rowsInput,LegacyRowSchema,"Invalid legacy trigger ledger; all rows must be MATCHED with complete source provenance");assertCanonicalDefinitionFields(parsedLegacyRows.filter((row)=>("scope"in row)));let legacyRows=parsedLegacyRows.map((row)=>({trigger_id:row.trigger_id,result:row.result,evidence:row.evidence,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id})),validated=summarizeTriggerRows(legacyRows);if(schemaVersion===1){let receipt=legacyEnvelope,countFields={trigger_count:validated.rows.length,matched_count:validated.rows.length,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount(validated.rows)};for(let[field,expected]of Object.entries(countFields))if(receipt[field]!==expected)throw Error(`Historical PR_REVIEW trigger receipt ${field} is inconsistent: expected ${expected}`)}return parsedReceipt(schemaVersion===1?1:0,validated.rows)}var PR_REVIEW_TRIGGER_DEFINITIONS,PR_REVIEW_REQUIRED_TRIGGER_IDS,TriggerIdSchema,TriggerEvidenceSchema,PrReviewInlineTriggerRowSchema,PrReviewPersistedInputRowSchema,PrReviewWriterInputRowSchema,TriggerDefinitionFieldShape,V2MatchedRowSchema,V2NotTriggeredRowSchema,V2RowSchema,TriggerCoverageDegradationSchema,ReceiptEnvelopeSchema,V2ReceiptSchema,LegacyRowFieldShape,LegacyBasicRowSchema,LegacyFullRowSchema,LegacyRowSchema,V1ReceiptSchema,UnversionedRowOnlyReceiptSchema;var init_pr_review_trigger_contract=__esm(()=>{init_zod();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"}],PR_REVIEW_REQUIRED_TRIGGER_IDS=PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>definition.id),TriggerIdSchema=exports_external.enum(PR_REVIEW_REQUIRED_TRIGGER_IDS,{error:"unknown PR_REVIEW trigger_id"}),TriggerEvidenceSchema=exports_external.string().trim().min(1).max(4000),PrReviewInlineTriggerRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict()]),PrReviewPersistedInputRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict()]),PrReviewWriterInputRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema.optional(),source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema.optional()}).strict()]);TriggerDefinitionFieldShape={scope:exports_external.literal("universal"),trigger_row:exports_external.string().trim().min(1),micro_lane:exports_external.string().trim().min(1)},V2MatchedRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),V2NotTriggeredRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict(),V2RowSchema=exports_external.union([V2MatchedRowSchema,V2NotTriggeredRowSchema]),TriggerCoverageDegradationSchema=exports_external.object({trigger_id:TriggerIdSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1),reason:exports_external.string().trim().min(1)}).strict(),ReceiptEnvelopeSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),evaluated_at:exports_external.string().datetime(),dispatched_micro_lane_count:exports_external.number().int().min(1)}),V2ReceiptSchema=ReceiptEnvelopeSchema.extend({schema_version:exports_external.literal(2),trigger_count:exports_external.number().int().min(0),matched_count:exports_external.number().int().min(0),not_triggered_count:exports_external.number().int().min(0),no_match_count:exports_external.number().int().min(0),rows:exports_external.array(V2RowSchema),coverage_degradations:exports_external.array(TriggerCoverageDegradationSchema).default([])}).strict();LegacyRowFieldShape={trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)},LegacyBasicRowSchema=exports_external.object(LegacyRowFieldShape).strict(),LegacyFullRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),LegacyRowSchema=exports_external.union([LegacyBasicRowSchema,LegacyFullRowSchema]),V1ReceiptSchema=ReceiptEnvelopeSchema.extend({schema_version:exports_external.literal(1),trigger_count:exports_external.number().int().min(0),matched_count:exports_external.number().int().min(0),no_match_count:exports_external.number().int().min(0),rows:exports_external.array(LegacyRowSchema)}).strict(),UnversionedRowOnlyReceiptSchema=exports_external.object({rows:exports_external.array(exports_external.unknown())}).strict()});var exports_workspace_snapshot={};__export(exports_workspace_snapshot,{workspaceSnapshotMatches:()=>workspaceSnapshotMatches,switchPrFeedbackTrackingCandidateAsync:()=>switchPrFeedbackTrackingCandidateAsync,resolveRemoteRefsContainingHeadAsync:()=>resolveRemoteRefsContainingHeadAsync,resolveRemoteRefsContainingHead:()=>resolveRemoteRefsContainingHead,resolvePrWorkflowRevisionDigestDetailedAsync:()=>resolvePrWorkflowRevisionDigestDetailedAsync,resolvePrWorkflowRevisionDigestDetailed:()=>resolvePrWorkflowRevisionDigestDetailed,resolvePrWorkflowRevisionDigestAsync:()=>resolvePrWorkflowRevisionDigestAsync,resolvePrWorkflowRevisionDigest:()=>resolvePrWorkflowRevisionDigest,resolvePrReviewDiffStatsAsync:()=>resolvePrReviewDiffStatsAsync,resolvePrReviewDiffStats:()=>resolvePrReviewDiffStats,resolvePrFeedbackTrackingCandidatesAsync:()=>resolvePrFeedbackTrackingCandidatesAsync,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,parsePorcelainV2Snapshot:()=>parsePorcelainV2Snapshot,parsePorcelainPaths:()=>parsePorcelainPaths,digest:()=>digest,compareWorkspaceSnapshots:()=>compareWorkspaceSnapshots,compareWorkspaceSnapshot:()=>compareWorkspaceSnapshot,changedFilesSinceSnapshot:()=>changedFilesSinceSnapshot,captureWorkspaceSnapshot:()=>captureWorkspaceSnapshot,_internals:()=>_internals9});import*as child_process from"node:child_process";import{createHash as createHash7}from"node:crypto";import*as fs8 from"node:fs";import*as path12 from"node:path";async function readBoundedGitOutput(stream,maxBytes,onOverflow){let reader=stream.getReader(),chunks=[],totalBytes=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-totalBytes;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining));return onOverflow(),{text:"",truncated:!0}}chunks.push(value),totalBytes+=value.byteLength}let joined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)joined.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(joined),truncated:!1}}finally{try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function runGit(directory,args2,timeoutMs=GIT_SNAPSHOT_TIMEOUT_MS){let result=_internals9.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=_internals9.gitTimeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,killProcessTree:!0};proc=_internals9.bunSpawn(["git","-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow),readBoundedGitOutput(proc.stderr,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve8)=>{timeout=setTimeout(()=>resolve8({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout"||overflowed||result.exitCode!==0||result.stdout.truncated||result.stderr.truncated)return null;return result.stdout.text.trimEnd()}catch{return null}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function runGitDetailed(directory,args2,timeoutMs){let result=_internals9.spawnSync("git",["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:_internals9.gitSnapshotMaxBuffer,stdio:["ignore","pipe","pipe"]}),errorCode=result.error?.code;if(errorCode==="ENOBUFS")return{ok:!1,reason:"buffer-truncated"};if(errorCode==="ETIMEDOUT")return{ok:!1,reason:"timeout"};if(result.error||result.status!==0||typeof result.stdout!=="string")return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.trimEnd()}}async function runGitAsyncDetailed(directory,args2,timeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",killProcessTree:!0};proc=_internals9.bunSpawn(["git","-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},maxBuffer=_internals9.gitSnapshotMaxBuffer,completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,maxBuffer,stopOverflow),readBoundedGitOutput(proc.stderr,maxBuffer,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve8)=>{timeout=setTimeout(()=>resolve8({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout")return{ok:!1,reason:"timeout"};if(overflowed||result.stdout.truncated||result.stderr.truncated)return{ok:!1,reason:"buffer-truncated"};if(result.exitCode!==0)return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.text.trimEnd()}}catch{return{ok:!1,reason:"git-failed"}}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}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=_internals9.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(`
|
|
189
|
+
`),!0}catch(error49){return warn(`[background] reservation write failed: ${error49 instanceof Error?error49.message:String(error49)}`),!1}}function reservationOwnerKey(input){return input.planTaskId===null?`call:${input.parentSessionId}:${input.callID}`:`task:${input.parentSessionId}:${input.planTaskId}`}function isActiveCoderOwner(record2){if(record2.normalizedAgent!=="coder"||record2.status==="consumed")return!1;if(record2.status==="pending"||record2.status==="running"||record2.status==="completed"||record2.status==="ingestion_error")return!0;if(record2.coderSettlement?.state==="preserved")return!0;return record2.worktree!==void 0}async function scanDurableCoderOwners(directory){let fallbackScan=await scanDelegationFallbacksForRecovery(directory);if(fallbackScan.status==="uncertain")return fallbackScan;let primaryScan=scanDelegationsForRecovery(directory);if(primaryScan.status==="uncertain")return primaryScan;let recordsByCorrelation=new Map;for(let artifact of fallbackScan.owners)recordsByCorrelation.set(artifact.correlationId,artifact.record);let primaryByCorrelation=new Map,primaryByReservationId=new Map;for(let record2 of primaryScan.owners){if(primaryByCorrelation.set(record2.correlationId,record2),record2.coderReservationId){let owners=primaryByReservationId.get(record2.coderReservationId)??[];owners.push(record2),primaryByReservationId.set(record2.coderReservationId,owners)}recordsByCorrelation.set(record2.correlationId,record2)}return{status:"ok",recordsByCorrelation,primaryByCorrelation,primaryByReservationId}}function exactReservationOwnerCoordinates(reservation,record2){return record2.coderReservationId===reservation.reservationId&&record2.parentSessionId===reservation.parentSessionId&&record2.planTaskId===reservation.planTaskId&&record2.callID===reservation.callID}function exactReservationRecordMatch(reservation,record2){return exactReservationOwnerCoordinates(reservation,record2)&&record2.correlationId===reservation.correlationId}function findExactPrimaryReservationOwner(reservation,ownerScan){if(reservation.correlationId!==null){let primary=ownerScan.primaryByCorrelation.get(reservation.correlationId);return primary&&exactReservationRecordMatch(reservation,primary)?primary:null}let exactOwners=(ownerScan.primaryByReservationId.get(reservation.reservationId)??[]).filter((record2)=>exactReservationOwnerCoordinates(reservation,record2));return exactOwners.length===1?exactOwners[0]:null}function hasProvenReleasedReservationOwner(record2){if(record2.status==="consumed")return!0;return record2.worktree===void 0&&(record2.status==="error"||record2.status==="cancelled")&&record2.terminalResult?.status===record2.status}function validateReservationIdentity(input){return typeof input.parentSessionId==="string"&&input.parentSessionId.length>0&&input.parentSessionId.length<=256&&input.parentSessionId.trim()===input.parentSessionId&&typeof input.callID==="string"&&input.callID.length>0&&input.callID.length<=256&&input.callID.trim()===input.callID&&(input.planTaskId===null||typeof input.planTaskId==="string"&&input.planTaskId.length>0&&input.planTaskId.length<=256&&input.planTaskId.trim()===input.planTaskId)}async function reserveBackgroundCoderSlot(directory,input){if(!validateReservationIdentity(input)||!Number.isInteger(input.maxConcurrent)||input.maxConcurrent<1||input.maxConcurrent>64||(input.occupiedTaskIds?.length??0)>64)return{ok:!1,reason:"invalid"};let occupiedTaskIds=new Set;for(let taskId of input.occupiedTaskIds??[]){if(typeof taskId!=="string"||taskId.length===0||taskId.length>256||taskId.trim()!==taskId)return{ok:!1,reason:"invalid"};occupiedTaskIds.add(taskId)}try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let reservationScan=scanBackgroundCoderReservationsForAdmission(directory);if(reservationScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:reservationScan.reason};let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:ownerScan.reason};let reservations=reservationScan.reservations.filter((reservation2)=>{let primary=findExactPrimaryReservationOwner(reservation2,ownerScan);return!(primary&&hasProvenReleasedReservationOwner(primary))});if(reservations.length!==reservationScan.reservations.length&&!await writeBackgroundCoderReservations(directory,reservations))return{ok:!1,reason:"uncertain",detail:"finished reservation reconciliation could not be persisted"};let activeOwnerKeys=new Set;for(let taskId of occupiedTaskIds)activeOwnerKeys.add(reservationOwnerKey({parentSessionId:input.parentSessionId,planTaskId:taskId,callID:""}));for(let reservation2 of reservations)if(reservation2.parentSessionId===input.parentSessionId)activeOwnerKeys.add(reservationOwnerKey(reservation2));for(let record2 of ownerScan.recordsByCorrelation.values())if(record2.parentSessionId===input.parentSessionId&&isActiveCoderOwner(record2))activeOwnerKeys.add(reservationOwnerKey({parentSessionId:record2.parentSessionId,planTaskId:record2.planTaskId,callID:record2.callID}));let reservationId=buildBackgroundCoderReservationId(input),existing=reservations.find((reservation2)=>reservation2.reservationId===reservationId);if(existing)return{ok:!1,reason:input.planTaskId===null?"duplicate_call":"duplicate_task",activeCount:activeOwnerKeys.size,existing};let incomingOwnerKey=reservationOwnerKey(input);if(input.planTaskId!==null&&activeOwnerKeys.has(incomingOwnerKey))return{ok:!1,reason:"duplicate_task",activeCount:activeOwnerKeys.size};if(activeOwnerKeys.size>=input.maxConcurrent)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size};if(reservations.length>=MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size,detail:"durable reservation store is at its hard safety cap"};let now=input.now??Date.now(),reservation={reservationId,parentSessionId:input.parentSessionId,planTaskId:input.planTaskId,callID:input.callID,state:"reserved",correlationId:null,createdAt:now,updatedAt:now};if(!await writeBackgroundCoderReservations(directory,[...reservations,reservation]))return{ok:!1,reason:"uncertain",detail:"durable reservation claim could not be persisted"};return{ok:!0,reservation,activeCount:activeOwnerKeys.size+1}})}catch(error49){return{ok:!1,reason:"uncertain",detail:`background coder reservation lock failed: ${error49 instanceof Error?error49.message:String(error49)}`}}}async function bindBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||!input.correlationId||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId||input.reservationId!==buildBackgroundCoderReservationId(input))return null;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return null;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return null;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID)return null;if(current.state==="bound")return current.correlationId===input.correlationId?current:null;let next={...current,state:"bound",correlationId:input.correlationId,updatedAt:input.now??Date.now()},reservations=[...scan.reservations];return reservations[index]=next,await writeBackgroundCoderReservations(directory,reservations)?next:null})}catch{return null}}async function releaseBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||input.reservationId!==buildBackgroundCoderReservationId(input)||input.correlationId!==null&&(input.correlationId.length===0||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId))return!1;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return!1;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return!1;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID||current.correlationId!==input.correlationId)return!1;if(input.reason==="consumed"){if(current.state!=="bound"||!current.correlationId)return!1;let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return!1;let primary=ownerScan.primaryByCorrelation.get(current.correlationId);if(!primary||primary.status!=="consumed"||!exactReservationRecordMatch(current,primary))return!1}let reservations=scan.reservations.filter((_,reservationIndex)=>reservationIndex!==index);return writeBackgroundCoderReservations(directory,reservations)})}catch{return!1}}var BACKGROUND_DELEGATIONS_FILE="background-delegations.jsonl",BACKGROUND_DELEGATION_FALLBACK_DIR="background-delegation-fallback",BACKGROUND_CODER_RESERVATIONS_FILE="background-coder-reservations.json",MAX_LIVE_BACKGROUND_FALLBACKS=256,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS=256,MAX_BACKGROUND_OBSERVED_FILES=5000,MAX_BACKGROUND_ADVISORY_CHARS=4000,MAX_BACKGROUND_DELEGATION_GENERATION=1e6,MAX_RECOVERY_LEDGER_BYTES=4194304,MAX_RECOVERY_FALLBACK_BYTES=1048576,STORE_LOCK_AGENT="background",STORE_LOCK_TASK="background-delegations",FALLBACK_LOCK_TASK="background-delegation-fallback",RESERVATION_LOCK_TASK="background-coder-reservations",ADVISORY_PREPARE_LEASE_MS=30000,INGESTION_CLAIM_LEASE_MS=30000,BACKGROUND_INGESTION_LEASE_MS=30000,DEFAULT_STALE_DELEGATION_TIMEOUT_MS=1800000,DEFAULT_SWEEPABLE_DELEGATION_STATUSES,ResultSchema,WorkspaceSchema,TaskChangeContextSchema,WorktreeDescriptorSchema,TerminalResultSchema,NormalizedObservedFileSchema,SettlementProvenanceSchema,SettlementOutcomeSchema,CoderSettlementSchema,AdvisoryPreparationSchema,AdvisoryInboxSchema,DelegationIngestionSchema,BackgroundCoderReservationSchema,BackgroundCoderReservationStoreSchema,PromptSchema,RecordSchema,FallbackArtifactSchema,MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES=2097152;var init_pending_delegations=__esm(()=>{init_zod();init_lock();init_utils2();init_bun_compat();init_logger();DEFAULT_SWEEPABLE_DELEGATION_STATUSES=new Set(["pending","running","ingestion_error"]),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(),salvagedWorkflowLanes:exports_external.array(exports_external.string()).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,workflowGeneration:exports_external.number().int().nonnegative().optional()}).strict(),WorktreeDescriptorSchema=exports_external.object({callID:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),taskId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),worktreePath:exports_external.string().min(1).max(4096),branchName:exports_external.string().min(1).max(1024),worktreeId:exports_external.string().min(1).max(256),worktreeSessionId:exports_external.string().min(1).max(256),mergeStrategy:exports_external.enum(["merge","rebase","cherry-pick"]),laneIndex:exports_external.number().int().nonnegative().max(255),worktreeDir:exports_external.string().min(1).max(4096).nullable()}).strict(),TerminalResultSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),status:exports_external.enum(["completed","error","cancelled"]),recordedAt:exports_external.number().int().nonnegative(),result:ResultSchema}).strict(),NormalizedObservedFileSchema=exports_external.string().min(1).max(4096).refine((value)=>normalizeObservedFile(value)===value),SettlementProvenanceSchema=exports_external.object({correlationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),callID:exports_external.string().max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),baseline:WorkspaceSchema,worktree:WorktreeDescriptorSchema.nullable()}).strict(),SettlementOutcomeSchema=exports_external.object({kind:exports_external.enum(["shared-root","standard-worktree"]),result:exports_external.enum(["ready","merged","unchanged","partial","failed"]),reason:exports_external.string().min(1).max(2000).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),targetHeadAfterMerge:exports_external.string().min(1).max(256).nullable().optional()}).strict(),CoderSettlementSchema=exports_external.object({state:exports_external.enum(["pending","settling","settled","preserved"]),provenance:SettlementProvenanceSchema,operationId:exports_external.string().min(1).max(256).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),observedFiles:exports_external.array(NormalizedObservedFileSchema).max(MAX_BACKGROUND_OBSERVED_FILES).nullable(),outcome:SettlementOutcomeSchema.optional(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state!=="pending"&&!value.operationId)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"settling, settled, and preserved states require operationId"});if((value.state==="settled"||value.state==="preserved")&&!value.outcome)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"terminal settlement state requires outcome"})}),AdvisoryPreparationSchema=exports_external.object({id:exports_external.string().min(1).max(256),preparedAt:exports_external.number().int().nonnegative(),leaseExpiresAt:exports_external.number().int().nonnegative()}).strict(),AdvisoryInboxSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),state:exports_external.enum(["pending","delivered"]),message:exports_external.string().min(1).max(MAX_BACKGROUND_ADVISORY_CHARS),createdAt:exports_external.number().int().nonnegative(),preparation:AdvisoryPreparationSchema.optional(),deliveredAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="delivered"&&value.deliveredAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory requires deliveredAt"});if(value.state==="delivered"&&value.preparation!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory cannot retain a preparation lease"})}),DelegationIngestionSchema=exports_external.object({state:exports_external.enum(["claimed","retryable","consumed"]),attempt:exports_external.number().int().positive(),updatedAt:exports_external.number().int().nonnegative(),claimToken:exports_external.string().min(1).max(256),leaseExpiresAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="claimed"&&value.leaseExpiresAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"claimed ingestion requires a lease expiry"});if(value.state!=="claimed"&&value.leaseExpiresAt!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"completed ingestion cannot retain a claim lease"})}),BackgroundCoderReservationSchema=exports_external.object({reservationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),callID:exports_external.string().min(1).max(256),state:exports_external.enum(["reserved","bound"]),correlationId:exports_external.string().min(1).max(256).nullable(),createdAt:exports_external.number().int().nonnegative(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state==="reserved"&&value.correlationId!==null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"unbound reservation cannot have a correlationId"});if(value.state==="bound"&&value.correlationId===null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"bound reservation requires a correlationId"})}),BackgroundCoderReservationStoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),reservations:exports_external.array(BackgroundCoderReservationSchema).max(MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)}).strict().superRefine((value,context)=>{let ids=new Set;for(let reservation of value.reservations){if(ids.has(reservation.reservationId)){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"duplicate reservationId"});return}if(reservation.reservationId!==buildBackgroundCoderReservationId({parentSessionId:reservation.parentSessionId,planTaskId:reservation.planTaskId,callID:reservation.callID})){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"reservationId does not match owner identity"});return}ids.add(reservation.reservationId)}}),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),exports_external.literal(3)]),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(),workflowGeneration:exports_external.number().int().nonnegative().optional(),worktree:WorktreeDescriptorSchema.optional(),coderReservationId:exports_external.string().min(1).max(256).optional(),prompt:PromptSchema.optional(),generation:exports_external.number().int().positive().max(MAX_BACKGROUND_DELEGATION_GENERATION).optional(),terminalResult:TerminalResultSchema.optional(),coderSettlement:CoderSettlementSchema.optional(),advisoryInbox:AdvisoryInboxSchema.optional(),ingestion:DelegationIngestionSchema.optional(),result:ResultSchema.optional(),completedAt:exports_external.number().optional()}).strict(),FallbackArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(1),correlationId:exports_external.string().min(1).max(256),createdAt:exports_external.number().int().nonnegative(),record:RecordSchema}).strict().superRefine((value,context)=>{if(value.record.correlationId!==value.correlationId||value.record.subagentSessionId!==value.correlationId||value.record.status!=="pending")context.addIssue({code:exports_external.ZodIssueCode.custom,message:"fallback identity/status does not match its pending record"})})});import{createHash as createHash6}from"node:crypto";function rawTriggerIds(input){if(!Array.isArray(input))return null;let ids=[];for(let row of input){if(typeof row!=="object"||row===null)return null;let triggerId=row.trigger_id;if(typeof triggerId!=="string"||!triggerId.trim())return null;ids.push(triggerId.trim())}return ids}function assertExactTriggerIdSet(input){let ids=rawTriggerIds(input);if(!ids)return;let expected=new Set(PR_REVIEW_REQUIRED_TRIGGER_IDS),seen=new Set,duplicate=new Set;for(let id of ids){if(seen.has(id))duplicate.add(id);seen.add(id)}if(duplicate.size>0)throw Error(`duplicate trigger IDs: ${[...duplicate].join(", ")}`);let unknown2=[...seen].filter((id)=>!expected.has(id));if(unknown2.length>0)throw Error(`unknown trigger IDs: ${unknown2.join(", ")}. trigger_id must be one of the 11 mandatory micro-lane IDs: ${[...expected].join(", ")}. Base-lane IDs and mode strings (e.g. swarm-pr-review:base) are NOT trigger IDs.`);let missing=[...expected].filter((id)=>!seen.has(id));if(missing.length>0)throw Error(`missing trigger IDs: ${missing.join(", ")}`)}function assertMatchedRowsHaveProvenance(input){if(!Array.isArray(input))return;for(let row of input){if(typeof row!=="object"||row===null)continue;let value=row;if(value.result!=="MATCHED")continue;if(typeof value.source_batch_id!=="string"||!value.source_batch_id.trim()||typeof value.source_lane_id!=="string"||!value.source_lane_id.trim())throw Error(`MATCHED rows require source_batch_id and source_lane_id: ${String(value.trigger_id??"(missing trigger_id)")}`)}}function assertNoLegacyNoMatchResult(input){if(!Array.isArray(input))return;for(let row of input){if(typeof row!=="object"||row===null)continue;if(row.result==="NO-MATCH")throw Error("NO-MATCH is not a valid PR_REVIEW trigger result; use MATCHED or NOT_TRIGGERED with concrete evidence")}}function exactTriggerRows(rows){let expected=new Set(PR_REVIEW_REQUIRED_TRIGGER_IDS),seen=new Set,duplicate=new Set;for(let row of rows){if(seen.has(row.trigger_id))duplicate.add(row.trigger_id);seen.add(row.trigger_id)}let unknown2=[...seen].filter((id)=>!expected.has(id)),missing=[...expected].filter((id)=>!seen.has(id));if(duplicate.size>0||unknown2.length>0||missing.length>0)throw Error(`PR_REVIEW trigger ledger must be exact; missing: ${missing.join(", ")||"(none)"}; duplicate: ${[...duplicate].join(", ")||"(none)"}; unknown: ${unknown2.join(", ")||"(none)"}`);let byId=new Map(rows.map((row)=>[row.trigger_id,row]));return PR_REVIEW_REQUIRED_TRIGGER_IDS.map((id)=>{let row=byId.get(id);if(!row)throw Error(`missing trigger row: ${id}`);return row})}function summarizeTriggerRows(rows){let orderedRows=exactTriggerRows(rows);if(orderedRows.find((row)=>row.trigger_id==="unclassified-risk")?.result!=="MATCHED")throw Error("PR_REVIEW trigger ledger requires unclassified-risk to remain MATCHED as the fallback family");return{rows:orderedRows,matchedIds:orderedRows.filter((row)=>row.result==="MATCHED").map((row)=>row.trigger_id),notTriggeredIds:orderedRows.filter((row)=>row.result==="NOT_TRIGGERED").map((row)=>row.trigger_id)}}function parseRows(input,schema,label){let parsed=exports_external.array(schema).safeParse(input);if(!parsed.success)throw Error(`${label}: ${parsed.error.issues.map((issue2)=>`${issue2.path.join(".")}: ${issue2.message}`).join("; ")}`);return parsed.data}function validatePrReviewInlineTriggerLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),summarizeTriggerRows(parseRows(input,PrReviewInlineTriggerRowSchema,"Invalid trigger ledger"))}function validatePrReviewPersistedInputLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),assertMatchedRowsHaveProvenance(input),summarizeTriggerRows(parseRows(input,PrReviewPersistedInputRowSchema,"Invalid persisted trigger ledger"))}function validatePrReviewWriterInputLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),assertMatchedRowsHaveProvenance(input),summarizeTriggerRows(parseRows(input,PrReviewWriterInputRowSchema,"Invalid final-writer trigger ledger"))}function assertCanonicalDefinitionFields(rows){let definitions=new Map(PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>[definition.id,definition]));for(let row of rows){let definition=definitions.get(row.trigger_id);if(!definition||row.scope!==definition.scope||row.trigger_row!==definition.trigger_row||row.micro_lane!==definition.micro_lane)throw Error(`PR_REVIEW trigger definition drift for ${row.trigger_id}: scope, trigger_row, and micro_lane must match the canonical definition`)}}function dispatchedMicroLaneCount(rows){return new Set(rows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size}function buildPrReviewTriggerReceiptV2(input){let envelope=ReceiptEnvelopeSchema.parse(input),validated=validatePrReviewPersistedInputLedger(input.rows),dispatchedCount=dispatchedMicroLaneCount(validated.rows);if(envelope.dispatched_micro_lane_count!==dispatchedCount)throw Error(`PR_REVIEW trigger receipt dispatched_micro_lane_count is inconsistent: expected ${dispatchedCount}`);let rows=validated.rows.map((row)=>{let definition=PR_REVIEW_TRIGGER_DEFINITIONS.find((candidate)=>candidate.id===row.trigger_id);if(!definition)throw Error(`unknown trigger definition: ${row.trigger_id}`);return{trigger_id:row.trigger_id,scope:definition.scope,trigger_row:definition.trigger_row,micro_lane:definition.micro_lane,result:row.result,evidence:row.evidence,...row.result==="MATCHED"?{source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}:{}}});return V2ReceiptSchema.parse({...envelope,schema_version:2,trigger_count:rows.length,matched_count:validated.matchedIds.length,not_triggered_count:validated.notTriggeredIds.length,no_match_count:0,rows,coverage_degradations:input.coverage_degradations??[],...input.base_verification?{base_verification:input.base_verification}:{}})}function prReviewTriggerLedgerDigest(rows){let canonical=rows.map((row)=>[row.trigger_id,row.result,row.evidence]);return createHash6("sha256").update(JSON.stringify(canonical)).digest("hex")}function parsedReceipt(schemaVersion,rows,coverageDegradations=[],baseVerification){return{schemaVersion,rows,matchedRows:rows.filter((row)=>row.result==="MATCHED"),notTriggeredRows:rows.filter((row)=>row.result==="NOT_TRIGGERED"),coverageDegradations,...baseVerification?{baseVerification}:{}}}function parsePrReviewTriggerReceipt(input){if(typeof input!=="object"||input===null)throw Error("PR_REVIEW trigger receipt must be an object");let schemaVersion=input.schema_version;if(schemaVersion===2){let receipt=V2ReceiptSchema.parse(input);assertCanonicalDefinitionFields(receipt.rows);let normalizedRows=receipt.rows.map((row)=>({trigger_id:row.trigger_id,result:row.result,evidence:row.evidence,...row.result==="MATCHED"?{source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}:{}})),validated2=validatePrReviewPersistedInputLedger(normalizedRows),counts={trigger_count:validated2.rows.length,matched_count:validated2.matchedIds.length,not_triggered_count:validated2.notTriggeredIds.length,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount(validated2.rows)};for(let[field,expected]of Object.entries(counts))if(receipt[field]!==expected)throw Error(`PR_REVIEW trigger receipt ${field} is inconsistent: expected ${expected}`);return parsedReceipt(2,validated2.rows,receipt.coverage_degradations,receipt.base_verification)}if(schemaVersion!==void 0&&schemaVersion!==1)throw Error(`Unsupported PR_REVIEW trigger schema_version: ${schemaVersion}`);let legacyEnvelope=schemaVersion===1?V1ReceiptSchema.parse(input):UnversionedRowOnlyReceiptSchema.parse(input),rowsInput=legacyEnvelope.rows,parsedLegacyRows=parseRows(rowsInput,LegacyRowSchema,"Invalid legacy trigger ledger; all rows must be MATCHED with complete source provenance");assertCanonicalDefinitionFields(parsedLegacyRows.filter((row)=>("scope"in row)));let legacyRows=parsedLegacyRows.map((row)=>({trigger_id:row.trigger_id,result:row.result,evidence:row.evidence,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id})),validated=summarizeTriggerRows(legacyRows);if(schemaVersion===1){let receipt=legacyEnvelope,countFields={trigger_count:validated.rows.length,matched_count:validated.rows.length,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount(validated.rows)};for(let[field,expected]of Object.entries(countFields))if(receipt[field]!==expected)throw Error(`Historical PR_REVIEW trigger receipt ${field} is inconsistent: expected ${expected}`)}return parsedReceipt(schemaVersion===1?1:0,validated.rows)}var PR_REVIEW_TRIGGER_DEFINITIONS,PR_REVIEW_REQUIRED_TRIGGER_IDS,TriggerIdSchema,TriggerEvidenceSchema,PrReviewInlineTriggerRowSchema,PrReviewPersistedInputRowSchema,PrReviewWriterInputRowSchema,TriggerDefinitionFieldShape,V2MatchedRowSchema,V2NotTriggeredRowSchema,V2RowSchema,TriggerCoverageDegradationSchema,ReceiptEnvelopeSchema,V2ReceiptSchema,LegacyRowFieldShape,LegacyBasicRowSchema,LegacyFullRowSchema,LegacyRowSchema,V1ReceiptSchema,UnversionedRowOnlyReceiptSchema;var init_pr_review_trigger_contract=__esm(()=>{init_zod();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"}],PR_REVIEW_REQUIRED_TRIGGER_IDS=PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>definition.id),TriggerIdSchema=exports_external.enum(PR_REVIEW_REQUIRED_TRIGGER_IDS,{error:"unknown PR_REVIEW trigger_id"}),TriggerEvidenceSchema=exports_external.string().trim().min(1).max(4000),PrReviewInlineTriggerRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict()]),PrReviewPersistedInputRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict()]),PrReviewWriterInputRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema.optional(),source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema.optional()}).strict()]);TriggerDefinitionFieldShape={scope:exports_external.literal("universal"),trigger_row:exports_external.string().trim().min(1),micro_lane:exports_external.string().trim().min(1)},V2MatchedRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),V2NotTriggeredRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict(),V2RowSchema=exports_external.union([V2MatchedRowSchema,V2NotTriggeredRowSchema]),TriggerCoverageDegradationSchema=exports_external.object({trigger_id:TriggerIdSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1),reason:exports_external.string().trim().min(1)}).strict(),ReceiptEnvelopeSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),evaluated_at:exports_external.string().datetime(),dispatched_micro_lane_count:exports_external.number().int().min(1)}),V2ReceiptSchema=ReceiptEnvelopeSchema.extend({schema_version:exports_external.literal(2),trigger_count:exports_external.number().int().min(0),matched_count:exports_external.number().int().min(0),not_triggered_count:exports_external.number().int().min(0),no_match_count:exports_external.number().int().min(0),rows:exports_external.array(V2RowSchema),coverage_degradations:exports_external.array(TriggerCoverageDegradationSchema).default([]),base_verification:exports_external.enum(["live","bound_fallback"]).optional()}).strict();LegacyRowFieldShape={trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)},LegacyBasicRowSchema=exports_external.object(LegacyRowFieldShape).strict(),LegacyFullRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),LegacyRowSchema=exports_external.union([LegacyBasicRowSchema,LegacyFullRowSchema]),V1ReceiptSchema=ReceiptEnvelopeSchema.extend({schema_version:exports_external.literal(1),trigger_count:exports_external.number().int().min(0),matched_count:exports_external.number().int().min(0),no_match_count:exports_external.number().int().min(0),rows:exports_external.array(LegacyRowSchema)}).strict(),UnversionedRowOnlyReceiptSchema=exports_external.object({rows:exports_external.array(exports_external.unknown())}).strict()});var exports_workspace_snapshot={};__export(exports_workspace_snapshot,{workspaceSnapshotMatches:()=>workspaceSnapshotMatches,switchPrFeedbackTrackingCandidateAsync:()=>switchPrFeedbackTrackingCandidateAsync,resolveRemoteRefsContainingHeadAsync:()=>resolveRemoteRefsContainingHeadAsync,resolveRemoteRefsContainingHead:()=>resolveRemoteRefsContainingHead,resolvePrWorkflowRevisionDigestDetailedAsync:()=>resolvePrWorkflowRevisionDigestDetailedAsync,resolvePrWorkflowRevisionDigestDetailed:()=>resolvePrWorkflowRevisionDigestDetailed,resolvePrWorkflowRevisionDigestAsync:()=>resolvePrWorkflowRevisionDigestAsync,resolvePrWorkflowRevisionDigest:()=>resolvePrWorkflowRevisionDigest,resolvePrReviewDiffStatsAsync:()=>resolvePrReviewDiffStatsAsync,resolvePrReviewDiffStats:()=>resolvePrReviewDiffStats,resolvePrFeedbackTrackingCandidatesAsync:()=>resolvePrFeedbackTrackingCandidatesAsync,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,parsePorcelainV2Snapshot:()=>parsePorcelainV2Snapshot,parsePorcelainPaths:()=>parsePorcelainPaths,digest:()=>digest,compareWorkspaceSnapshots:()=>compareWorkspaceSnapshots,compareWorkspaceSnapshot:()=>compareWorkspaceSnapshot,changedFilesSinceSnapshot:()=>changedFilesSinceSnapshot,captureWorkspaceSnapshot:()=>captureWorkspaceSnapshot,_internals:()=>_internals9});import*as child_process from"node:child_process";import{createHash as createHash7}from"node:crypto";import*as fs8 from"node:fs";import*as path12 from"node:path";async function readBoundedGitOutput(stream,maxBytes,onOverflow){let reader=stream.getReader(),chunks=[],totalBytes=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-totalBytes;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining));return onOverflow(),{text:"",truncated:!0}}chunks.push(value),totalBytes+=value.byteLength}let joined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)joined.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(joined),truncated:!1}}finally{try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function runGit(directory,args2,timeoutMs=GIT_SNAPSHOT_TIMEOUT_MS){let result=_internals9.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=_internals9.gitTimeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,killProcessTree:!0};proc=_internals9.bunSpawn(["git","-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow),readBoundedGitOutput(proc.stderr,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve8)=>{timeout=setTimeout(()=>resolve8({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout"||overflowed||result.exitCode!==0||result.stdout.truncated||result.stderr.truncated)return null;return result.stdout.text.trimEnd()}catch{return null}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function runGitDetailed(directory,args2,timeoutMs){let result=_internals9.spawnSync("git",["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:_internals9.gitSnapshotMaxBuffer,stdio:["ignore","pipe","pipe"]}),errorCode=result.error?.code;if(errorCode==="ENOBUFS")return{ok:!1,reason:"buffer-truncated"};if(errorCode==="ETIMEDOUT")return{ok:!1,reason:"timeout"};if(result.error||result.status!==0||typeof result.stdout!=="string")return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.trimEnd()}}async function runGitAsyncDetailed(directory,args2,timeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",killProcessTree:!0};proc=_internals9.bunSpawn(["git","-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},maxBuffer=_internals9.gitSnapshotMaxBuffer,completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,maxBuffer,stopOverflow),readBoundedGitOutput(proc.stderr,maxBuffer,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve8)=>{timeout=setTimeout(()=>resolve8({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout")return{ok:!1,reason:"timeout"};if(overflowed||result.stdout.truncated||result.stderr.truncated)return{ok:!1,reason:"buffer-truncated"};if(result.exitCode!==0)return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.text.trimEnd()}}catch{return{ok:!1,reason:"git-failed"}}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}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=_internals9.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(`
|
|
190
190
|
`)){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(`
|
|
191
191
|
`).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(`
|
|
192
192
|
`)){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(`
|
|
193
193
|
`).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){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;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){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;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){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;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){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;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)}async function resolvePrFeedbackTrackingCandidatesAsync(directory,headSha){let[localOutput,remoteRefs]=await Promise.all([runGitAsync(directory,["for-each-ref","--format=%(refname)%09%(objectname)%09%(upstream)","refs/heads"]),resolveRemoteRefsContainingHeadAsync(directory,headSha)]);if(localOutput===null||remoteRefs===null)return null;let exactRemoteRefs=new Set(remoteRefs);return{local:localOutput.split(/\r?\n/).map((line)=>line.trim().split("\t")).flatMap(([ref,objectName,upstream,...extras])=>{if(extras.length>0||!ref?.startsWith("refs/heads/")||objectName?.toLowerCase()!==headSha.toLowerCase()||!upstream?.startsWith("refs/remotes/")||!exactRemoteRefs.has(upstream))return[];return[{kind:"local",branchName:ref.slice(11),remoteTrackingRef:upstream}]}),remote:remoteRefs.map((remoteTrackingRef)=>({kind:"remote",remoteTrackingRef}))}}async function switchPrFeedbackTrackingCandidateAsync(directory,candidate){let args2=candidate.kind==="local"?["switch","--no-guess","--",candidate.branchName]:["switch","--track","--",candidate.remoteTrackingRef];return await runGitAsync(directory,args2)!==null}function revisionDigestGitCallFailure(call,result){let description=result.reason==="timeout"?"timed out":result.reason==="buffer-truncated"?"output exceeded the bounded buffer":"failed";return{ok:!1,reason:result.reason,detail:`git ${call} ${description}`}}function resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha){let projectRoot=path12.resolve(directory),baseHeadResult=runGitDetailed(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`],_internals9.gitTimeoutMs);if(!baseHeadResult.ok)return revisionDigestGitCallFailure("rev-parse --verify",baseHeadResult);let diffResult=runGitDetailed(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha],_internals9.revisionEnumerationTimeoutMs);if(!diffResult.ok)return revisionDigestGitCallFailure("diff --name-only",diffResult);let porcelainResult=runGitDetailed(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"],_internals9.revisionEnumerationTimeoutMs);if(!porcelainResult.ok)return revisionDigestGitCallFailure("status --porcelain",porcelainResult);let porcelainPaths=parsePorcelainPaths(porcelainResult.text);if(!porcelainPaths)return{ok:!1,reason:"git-failed",detail:"malformed git status --porcelain=v1 output"};let changedPaths=[...new Set([...parseNulPaths(diffResult.text),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>_internals9.revisionMaxFiles)return{ok:!1,reason:"file-cap",detail:`${changedPaths.length} changed paths exceed the cap of ${_internals9.revisionMaxFiles}`};let hash2=createHash7("sha256");hash2.update(`base\x00${baseHeadResult.text}\x00`);let totalBytes=0;for(let relativePath of changedPaths){let resolvedPath=path12.resolve(projectRoot,relativePath),relativeToRoot=path12.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path12.isAbsolute(relativeToRoot))return{ok:!1,reason:"containment",detail:`path escapes the project root: ${relativePath}`};hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=fs8.lstatSync(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return{ok:!1,reason:"read-failed",detail:`lstat failed for ${relativePath}`}}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${fs8.readlinkSync(resolvedPath)}\x00`);continue}catch{return{ok:!1,reason:"read-failed",detail:`readlink failed for ${relativePath}`}}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>_internals9.revisionMaxTotalBytes)return{ok:!1,reason:"byte-cap",detail:`accumulated content bytes ${totalBytes} exceed the cap of ${_internals9.revisionMaxTotalBytes} at ${relativePath}`};try{hash2.update(`file\x00${stats2.mode}\x00`),hash2.update(_internals9.readChangedFileSync(resolvedPath)),hash2.update("\x00")}catch{return{ok:!1,reason:"read-failed",detail:`read failed for ${relativePath}`}}}return{ok:!0,digest:hash2.digest("hex")}}function resolvePrWorkflowRevisionDigest(directory,baseHeadSha){let result=resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);return result.ok?result.digest:null}async function resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha){let projectRoot=path12.resolve(directory),[baseHeadResult,diffResult,porcelainResult]=await Promise.all([runGitAsyncDetailed(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`],_internals9.gitTimeoutMs),runGitAsyncDetailed(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha],_internals9.revisionEnumerationTimeoutMs),runGitAsyncDetailed(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"],_internals9.revisionEnumerationTimeoutMs)]);if(!baseHeadResult.ok)return revisionDigestGitCallFailure("rev-parse --verify",baseHeadResult);if(!diffResult.ok)return revisionDigestGitCallFailure("diff --name-only",diffResult);if(!porcelainResult.ok)return revisionDigestGitCallFailure("status --porcelain",porcelainResult);let porcelainPaths=parsePorcelainPaths(porcelainResult.text);if(!porcelainPaths)return{ok:!1,reason:"git-failed",detail:"malformed git status --porcelain=v1 output"};let changedPaths=[...new Set([...parseNulPaths(diffResult.text),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>_internals9.revisionMaxFiles)return{ok:!1,reason:"file-cap",detail:`${changedPaths.length} changed paths exceed the cap of ${_internals9.revisionMaxFiles}`};let hash2=createHash7("sha256");hash2.update(`base\x00${baseHeadResult.text}\x00`);let totalBytes=0,chunksSinceYield=0;for(let relativePath of changedPaths){let resolvedPath=path12.resolve(projectRoot,relativePath),relativeToRoot=path12.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path12.isAbsolute(relativeToRoot))return{ok:!1,reason:"containment",detail:`path escapes the project root: ${relativePath}`};hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=await fs8.promises.lstat(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return{ok:!1,reason:"read-failed",detail:`lstat failed for ${relativePath}`}}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${await fs8.promises.readlink(resolvedPath)}\x00`);continue}catch{return{ok:!1,reason:"read-failed",detail:`readlink failed for ${relativePath}`}}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>_internals9.revisionMaxTotalBytes)return{ok:!1,reason:"byte-cap",detail:`accumulated content bytes ${totalBytes} exceed the cap of ${_internals9.revisionMaxTotalBytes} at ${relativePath}`};hash2.update(`file\x00${stats2.mode}\x00`);let handle;try{handle=await fs8.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{ok:!1,reason:"read-failed",detail:`short read for ${relativePath}`};if(hash2.update(buffer.subarray(0,bytesRead)),position+=bytesRead,chunksSinceYield++,chunksSinceYield>=REVISION_YIELD_EVERY_CHUNKS)chunksSinceYield=0,await _internals9.yieldControl()}hash2.update("\x00")}catch{return{ok:!1,reason:"read-failed",detail:`read failed for ${relativePath}`}}finally{await handle?.close().catch(()=>{return})}}return{ok:!0,digest:hash2.digest("hex")}}async function resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha){let result=await resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha);return result.ok?result.digest:null}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(`
|
|
194
|
-
`).match(/^# branch\.oid (.+)$/m);if(!oidMatch)return null;if(!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(oidMatch[1])&&oidMatch[1]!=="(initial)")return null;let gitHead=oidMatch[1]==="(initial)"?null:oidMatch[1],dirtyTrackedPaths=[],untrackedPaths=[],unmergedPaths=[],unmergedCodes=[],dirtySubmodulePaths=[],renameOrCopy=!1;for(let index=0;index<records.length;index++){let record2=records[index];if(!record2)continue;if(record2.startsWith("? ")){untrackedPaths.push(record2.slice(2));continue}if(record2.startsWith("1 ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,8);if(!changedPath||!fields[2])return null;if(dirtyTrackedPaths.push(changedPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}if(record2.startsWith("2 ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,9),originalPath=records[++index];if(!changedPath||!originalPath||!fields[2])return null;if(renameOrCopy=!0,dirtyTrackedPaths.push(changedPath,originalPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}if(record2.startsWith("u ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,10),unmergedCode=fields[1];if(!changedPath||!fields[2]||!unmergedCode||!/^(?:DD|AU|UD|UA|DU|AA|UU)$/.test(unmergedCode))return null;if(unmergedPaths.push(changedPath),unmergedCodes.push(unmergedCode),dirtyTrackedPaths.push(changedPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}return null}return{gitHead,dirtyTrackedPaths:[...new Set(dirtyTrackedPaths)],untrackedPaths:[...new Set(untrackedPaths)],renameOrCopy,unmergedPaths:[...new Set(unmergedPaths)],unmergedCodes:[...new Set(unmergedCodes)],dirtySubmodulePaths:[...new Set(dirtySubmodulePaths)]}}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:path12.resolve(directory),gitHead:snapshot?.gitHead??null,dirtyHash:porcelain===null?null:digest(porcelain),changedFiles:snapshot?[...new Set([...snapshot.dirtyTrackedPaths,...snapshot.untrackedPaths])]: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(path12.resolve(expected.directory)!==path12.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 createHash7("sha256").update(text).digest("hex")}var GIT_SNAPSHOT_TIMEOUT_MS=3000,GIT_SNAPSHOT_MAX_BUFFER=33554432,REVISION_MAX_FILES=50000,REVISION_MAX_TOTAL_BYTES=536870912,REVISION_READ_CHUNK_BYTES=65536,REVISION_YIELD_EVERY_CHUNKS=16,REVISION_ENUMERATION_TIMEOUT_MS=15000,GITLINK_MODE_PATTERN,compareWorkspaceSnapshot,_internals9;var init_workspace_snapshot=__esm(()=>{init_bun_compat();GITLINK_MODE_PATTERN=/^:\d{6} 160000 |^:160000 \d{6} /;compareWorkspaceSnapshot=workspaceSnapshotMatches;_internals9={spawnSync:child_process.spawnSync,bunSpawn,gitTimeoutMs:GIT_SNAPSHOT_TIMEOUT_MS,yieldControl:()=>new Promise((resolve8)=>setImmediate(resolve8)),parsePorcelainV2Snapshot,revisionMaxFiles:REVISION_MAX_FILES,revisionMaxTotalBytes:REVISION_MAX_TOTAL_BYTES,gitSnapshotMaxBuffer:GIT_SNAPSHOT_MAX_BUFFER,revisionEnumerationTimeoutMs:REVISION_ENUMERATION_TIMEOUT_MS,readChangedFileSync:(filePath)=>fs8.readFileSync(filePath)}});import*as fs9 from"node:fs";import*as path13 from"node:path";function isExecutableFile(candidate){try{return fs9.statSync(candidate).isFile()}catch{return!1}}function resolveExecutableFromPath(names,envPath=process.env.PATH??"",platform=process.platform){let pathEntries=envPath.split(path13.delimiter).filter(Boolean),isWindows=platform==="win32";for(let rawName of names){if(!rawName)continue;if(path13.isAbsolute(rawName)&&isExecutableFile(rawName))return rawName;let extensions=isWindows&&path13.extname(rawName)===""?DEFAULT_WINDOWS_EXTENSIONS:[""];for(let dir of pathEntries)for(let ext of extensions){let candidate=path13.join(dir,`${rawName}${ext}`);if(isExecutableFile(candidate))return candidate}}return null}function clampTimeoutMs(timeoutMs){if(!Number.isFinite(timeoutMs))return MAX_RUNNER_TIMEOUT_MS;return Math.min(Math.max(1,Math.floor(timeoutMs)),MAX_RUNNER_TIMEOUT_MS)}function addTimeoutMs(baseMs,deltaMs){if(baseMs>=MAX_TIMEOUT_MS)return MAX_TIMEOUT_MS;return Math.min(MAX_TIMEOUT_MS,baseMs+deltaMs)}function computeSpawnTimeoutMs(timeoutMs){let total=clampTimeoutMs(timeoutMs);for(let windowMs of[TERMINATION_GRACE_MS,TERMINATION_FORCE_MS,TERMINATION_CONFIRM_MS,TREE_TERMINATION_CONFIRM_MS,TERMINATION_FALLBACK_BUFFER_MS])total=addTimeoutMs(total,windowMs);return total}function startBoundedStreamRead(stream,maxBytes,onLimitExceeded){let reader=stream.getReader(),lockReleased=!1,cancelPromise,releaseLock=()=>{if(lockReleased)return;lockReleased=!0;try{reader.releaseLock()}catch{}},cancel=async()=>{return cancelPromise??=(async()=>{try{await reader.cancel()}catch{}finally{releaseLock()}})(),cancelPromise};if(maxBytes<=0)return onLimitExceeded?.(),{cancel,promise:(async()=>{return await cancel(),{text:"",truncated:!0}})()};return{promise:(async()=>{let chunks=[],total=0,truncated=!1;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-total;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining)),total+=remaining;truncated=!0,onLimitExceeded?.(),cancel();break}chunks.push(value),total+=value.byteLength}}finally{releaseLock()}let out=new Uint8Array(total),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(out),truncated}})(),cancel}}function timeoutKillSignal(platform){return platform==="win32"?"SIGTERM":"SIGKILL"}function killProcess(proc){try{proc?.kill(timeoutKillSignal(_internals10.platform()))}catch{}}function requestTermination(proc,signal){try{if(proc?.killTree)return proc.killTree(signal).then(()=>!0,()=>!1);else return proc?.kill(signal),Promise.resolve(proc!==void 0)}catch{return Promise.resolve(!1)}}async function waitForExitWithin(exitPromise,waitMs){if(waitMs<=0)return Promise.resolve(null);let timeoutHandle;try{return await Promise.race([exitPromise,new Promise((resolve8)=>{timeoutHandle=_internals10.setTimeout(()=>resolve8(null),waitMs)})])}finally{if(timeoutHandle!==void 0)_internals10.clearTimeout(timeoutHandle)}}async function waitForValueWithin(promise2,waitMs){let timeoutHandle;try{return await Promise.race([promise2.then((value)=>({completed:!0,value})),new Promise((resolve8)=>{timeoutHandle=_internals10.setTimeout(()=>resolve8({completed:!1}),waitMs)})])}finally{if(timeoutHandle!==void 0)_internals10.clearTimeout(timeoutHandle)}}async function collectBoundedStreams(stdoutRead,stderrRead,proc,treeAlreadyConfirmed=!1){let reads=Promise.all([stdoutRead.promise,stderrRead.promise]),collected=await waitForValueWithin(reads,STREAM_DRAIN_MS);if(!collected.completed){let treeTermination=waitForValueWithin(requestTermination(proc,"SIGKILL"),TREE_TERMINATION_CONFIRM_MS);Promise.allSettled([stdoutRead.cancel(),stderrRead.cancel()]),collected=await waitForValueWithin(reads,STREAM_CANCEL_MS);let terminationResult=await treeTermination;if(!treeAlreadyConfirmed&&(!terminationResult.completed||!terminationResult.value))return{kind:"unconfirmed-termination"}}if(!collected.completed)return{kind:"cleanup-failed"};return{kind:"collected",stdout:collected.value[0],stderr:collected.value[1]}}async function runExternalTool(options){if(!path13.isAbsolute(options.cwd))return{status:"spawn-error",exitCode:null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:"external tool cwd must be absolute"};if(options.abortSignal?.aborted)return{status:"cancelled",exitCode:null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:"external tool execution cancelled before spawn"};let proc,timeoutHandle,abortListener,overflowTreeTermination,exitSettled=!1,settledExitCode=null,runnerTimeoutMs=clampTimeoutMs(options.timeoutMs),spawnTimeoutMs=computeSpawnTimeoutMs(runnerTimeoutMs);try{proc=_internals10.bunSpawn([options.executable,...options.args],{cwd:options.cwd,env:options.env,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:spawnTimeoutMs,killProcessTree:!0,windowsVerbatimArguments:options.windowsVerbatimArguments});let exitPromise=proc.exited.then((exitCode)=>{return exitSettled=!0,settledExitCode=exitCode,exitCode}),exitRacePromise=exitPromise.then((exitCode)=>({kind:"exit",exitCode})),timeout=new Promise((resolve8)=>{timeoutHandle=_internals10.setTimeout(()=>{if(exitSettled){resolve8({kind:"exit",exitCode:settledExitCode??proc?.exitCode??0});return}resolve8({kind:"timeout"})},runnerTimeoutMs)}),cancelled=new Promise((resolve8)=>{if(!options.abortSignal)return;let handled=!1;if(abortListener=()=>{if(handled)return;handled=!0,resolve8({kind:"cancelled"})},options.abortSignal.addEventListener("abort",abortListener,{once:!0}),options.abortSignal.aborted)abortListener()}),terminateOnOverflow=()=>{overflowTreeTermination??=requestTermination(proc,"SIGKILL")},stdoutRead=startBoundedStreamRead(proc.stdout,options.maxStdoutBytes,terminateOnOverflow),stderrRead=startBoundedStreamRead(proc.stderr,options.maxStderrBytes,terminateOnOverflow),exitResult=await Promise.race([exitRacePromise,timeout,cancelled]);if(exitResult.kind==="timeout"||exitResult.kind==="cancelled"){let gracefulTreeTermination=requestTermination(proc,"SIGTERM"),confirmedExitCode=await waitForExitWithin(exitPromise,TERMINATION_GRACE_MS);if(!overflowTreeTermination)overflowTreeTermination=requestTermination(proc,"SIGKILL");let treeTerminationResult=waitForValueWithin(Promise.all([gracefulTreeTermination,overflowTreeTermination]),TREE_TERMINATION_CONFIRM_MS);if(confirmedExitCode===null)confirmedExitCode=await waitForExitWithin(exitPromise,TERMINATION_FORCE_MS);if(confirmedExitCode===null)confirmedExitCode=await waitForExitWithin(exitPromise,TERMINATION_CONFIRM_MS);let treeTermination=await treeTerminationResult,treeTerminationConfirmed=treeTermination.completed&&treeTermination.value.some(Boolean);Promise.allSettled([stdoutRead.cancel(),stderrRead.cancel()]);let streams2=await collectBoundedStreams(stdoutRead,stderrRead,proc,treeTerminationConfirmed);if(streams2.kind!=="collected")return{status:"spawn-error",exitCode:confirmedExitCode??proc.exitCode,stdout:"",stderr:"",stdoutTruncated:!0,stderrTruncated:!0,message:streams2.kind==="unconfirmed-termination"?UNCONFIRMED_TERMINATION_MESSAGE:"external tool output cleanup did not complete"};let{stdout:stdout2,stderr:stderr2}=streams2;if(confirmedExitCode===null||!treeTerminationConfirmed)return{status:"spawn-error",exitCode:proc.exitCode,stdout:stdout2.text,stderr:stderr2.text,stdoutTruncated:stdout2.truncated,stderrTruncated:stderr2.truncated,message:UNCONFIRMED_TERMINATION_MESSAGE};if(exitResult.kind==="timeout")return{status:"timeout",exitCode:confirmedExitCode,stdout:stdout2.text,stderr:stderr2.text,stdoutTruncated:stdout2.truncated,stderrTruncated:stderr2.truncated};return{status:"cancelled",exitCode:confirmedExitCode,stdout:stdout2.text,stderr:stderr2.text,stdoutTruncated:stdout2.truncated,stderrTruncated:stderr2.truncated,message:"external tool execution cancelled"}}let streams=await collectBoundedStreams(stdoutRead,stderrRead,proc);if(streams.kind!=="collected")return{status:"spawn-error",exitCode:exitResult.exitCode,stdout:"",stderr:"",stdoutTruncated:!0,stderrTruncated:!0,message:streams.kind==="unconfirmed-termination"?UNCONFIRMED_TERMINATION_MESSAGE:"external tool output cleanup did not complete"};let{stdout,stderr}=streams;if(overflowTreeTermination){let overflowTermination=await waitForValueWithin(overflowTreeTermination,TREE_TERMINATION_CONFIRM_MS);if(!overflowTermination.completed||!overflowTermination.value)return{status:"spawn-error",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated,message:UNCONFIRMED_TERMINATION_MESSAGE}}if(proc.spawnError)return{status:"spawn-error",exitCode:proc.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated,message:proc.spawnError.message};if(proc.signalCode)return{status:"spawn-error",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated,message:`external tool terminated by signal ${proc.signalCode}`};return{status:"completed",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated}}catch(err){return{status:"spawn-error",exitCode:proc?.exitCode??null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:err instanceof Error?err.message:String(err)}}finally{if(timeoutHandle!==void 0)_internals10.clearTimeout(timeoutHandle);if(abortListener&&options.abortSignal)options.abortSignal.removeEventListener("abort",abortListener);if(!exitSettled)killProcess(proc)}}var DEFAULT_WINDOWS_EXTENSIONS,TERMINATION_GRACE_MS=20,TERMINATION_FORCE_MS=20,TERMINATION_CONFIRM_MS=20,TREE_TERMINATION_CONFIRM_MS=5100,TERMINATION_FALLBACK_BUFFER_MS=1,STREAM_DRAIN_MS=50,STREAM_CANCEL_MS=50,MAX_TIMEOUT_MS=2147483647,TERMINATION_WINDOWS_MS,MAX_RUNNER_TIMEOUT_MS,UNCONFIRMED_TERMINATION_MESSAGE="external tool process termination could not be confirmed",_internals10;var init_external_tool_runner=__esm(()=>{init_bun_compat();DEFAULT_WINDOWS_EXTENSIONS=[".exe",".cmd",".bat"],TERMINATION_WINDOWS_MS=TERMINATION_GRACE_MS+TERMINATION_FORCE_MS+TERMINATION_CONFIRM_MS+TREE_TERMINATION_CONFIRM_MS+TERMINATION_FALLBACK_BUFFER_MS,MAX_RUNNER_TIMEOUT_MS=MAX_TIMEOUT_MS-TERMINATION_WINDOWS_MS;_internals10={bunSpawn,platform:()=>process.platform,now:()=>Date.now(),setTimeout,clearTimeout,clampTimeoutMs,computeSpawnTimeoutMs}});import*as fsp2 from"node:fs/promises";import*as path14 from"node:path";function boundPath(value){let cleaned=value.replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim();return cleaned.length>MAX_EVIDENCE_PATH_LENGTH?`${cleaned.slice(0,MAX_EVIDENCE_PATH_LENGTH)}...`:cleaned}function evidence(parsed,worktreeRoot,gitDir,operations,detail){let allPaths=parsed?[...parsed.unmergedPaths,...parsed.dirtySubmodulePaths,...parsed.dirtyTrackedPaths,...parsed.untrackedPaths]:[],uniquePaths=[...new Set(allPaths)].map(boundPath);return{worktreeRoot:worktreeRoot?boundPath(worktreeRoot):null,gitDir:gitDir?boundPath(gitDir):null,operations,unmergedCodes:parsed?[...new Set(parsed.unmergedCodes)].sort():[],paths:uniquePaths.slice(0,MAX_EVIDENCE_PATHS),trackedCount:parsed?.dirtyTrackedPaths.length??0,untrackedCount:parsed?.untrackedPaths.length??0,pathsTruncated:uniquePaths.length>MAX_EVIDENCE_PATHS,...detail?{detail}:{}}}async function runGitCapture(directory,args2){let result=await runExternalTool({executable:"git",args:[...args2],cwd:path14.resolve(directory),timeoutMs:GIT_TIMEOUT_MS,maxStdoutBytes:MAX_GIT_OUTPUT_BYTES,maxStderrBytes:65536});return{ok:result.status==="completed"&&result.exitCode===0&&!result.stdoutTruncated&&!result.stderrTruncated,stdout:result.stdout}}async function activeOperations(gitDir){return(await Promise.all(OPERATION_MARKERS.map(async([name,marker])=>{try{return await fsp2.lstat(path14.join(gitDir,marker)),name}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}))).filter((value)=>value!==null)}async function classifyPrWorkflowGitState(directory,options={}){let[statusResult,rootResult,gitDirResult]=await Promise.all([_internals11.runGitCapture(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),_internals11.runGitCapture(directory,["rev-parse","--show-toplevel"]),_internals11.runGitCapture(directory,["rev-parse","--absolute-git-dir"])]);if(!statusResult.ok||!rootResult.ok||!gitDirResult.ok)return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Confirm this is a readable Git worktree and resolve filesystem or Git errors before starting the PR workflow.",evidence:evidence(null,null,null,[],"required Git inspection failed")};let worktreeRoot=rootResult.stdout.trim(),gitDir=gitDirResult.stdout.trim(),parsedRaw=parsePorcelainV2Snapshot(statusResult.stdout);if(!worktreeRoot||!gitDir||!parsedRaw)return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Resolve the malformed or incomplete Git status before starting the PR workflow.",evidence:evidence(parsedRaw,worktreeRoot||null,gitDir||null,[],"Git returned an incomplete status snapshot")};let ignoredPaths=new Set((options.ignoredPaths??[]).map((value)=>value.replace(/\\/g,"/"))),keepPath=(value)=>!ignoredPaths.has(value.replace(/\\/g,"/")),parsed={...parsedRaw,dirtyTrackedPaths:parsedRaw.dirtyTrackedPaths.filter(keepPath),untrackedPaths:parsedRaw.untrackedPaths.filter(keepPath),unmergedPaths:parsedRaw.unmergedPaths.filter(keepPath),dirtySubmodulePaths:parsedRaw.dirtySubmodulePaths.filter(keepPath)},operations;try{operations=await _internals11.activeOperations(path14.resolve(gitDir))}catch{return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Resolve the unreadable Git operation state before starting the PR workflow.",evidence:evidence(parsed,worktreeRoot,gitDir,[],"Git operation markers could not be inspected")}}let stateEvidence=evidence(parsed,worktreeRoot,gitDir,operations);if(parsed.unmergedCodes.length>0)return{kind:"recovery-required",code:"UNMERGED_INDEX",retryable:!1,requiredAction:"Resolve or abort the current merge/rebase/cherry-pick/revert operation manually; conflicted index entries must never be stashed by PR workflow startup.",evidence:stateEvidence};if(operations.length>0)return{kind:"recovery-required",code:"GIT_OPERATION_IN_PROGRESS",retryable:!1,requiredAction:"Complete or abort the active Git operation manually before starting the PR workflow.",evidence:stateEvidence};if(parsed.dirtySubmodulePaths.length>0)return{kind:"recovery-required",code:"DIRTY_SUBMODULE",retryable:!1,requiredAction:"Resolve or preserve dirty submodule worktrees manually; the checkout-preparation stash cannot safely preserve them.",evidence:stateEvidence};if([...parsed.dirtyTrackedPaths,...parsed.untrackedPaths].find((candidate)=>candidate===".swarm"||candidate.startsWith(".swarm/")||candidate.startsWith(".swarm\\")))return{kind:"recovery-required",code:"SWARM_STATE_TRACKING_ERROR",retryable:!1,requiredAction:"Restore .swarm/ so it is git-excluded before starting the PR workflow; runtime state must not be treated as checkout dirt.",evidence:stateEvidence};if(parsed.dirtyTrackedPaths.length===0&&parsed.untrackedPaths.length===0)return{kind:"clean",code:"CLEAN",retryable:!0,requiredAction:"No checkout recovery is required.",evidence:stateEvidence};return{kind:"stashable",code:"STASHABLE_CHANGES",retryable:!0,requiredAction:"Run prepare_pr_workflow_checkout once to preserve the ordinary working-tree changes before checkout.",evidence:stateEvidence}}var GIT_TIMEOUT_MS=5000,MAX_GIT_OUTPUT_BYTES=524288,MAX_EVIDENCE_PATHS=20,MAX_EVIDENCE_PATH_LENGTH=240,OPERATION_MARKERS,_internals11;var init_pr_workflow_state=__esm(()=>{init_workspace_snapshot();init_external_tool_runner();OPERATION_MARKERS=[["merge","MERGE_HEAD"],["rebase-merge","rebase-merge"],["rebase-apply-or-am","rebase-apply"],["cherry-pick","CHERRY_PICK_HEAD"],["revert","REVERT_HEAD"],["bisect","BISECT_START"],["sequencer","sequencer"]];_internals11={runGitCapture,activeOperations,parsePorcelainV2:parsePorcelainV2Snapshot}});import{createHash as createHash8,randomUUID as randomUUID3}from"node:crypto";import{readFileSync as readFileSync6}from"node:fs";import*as fsp3 from"node:fs/promises";import*as path15 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"}function formatCheckoutRecoveryBlock(state){let evidence2=JSON.stringify({operations:state.evidence.operations,unmerged_codes:state.evidence.unmergedCodes,paths:state.evidence.paths,paths_truncated:state.evidence.pathsTruncated});return`BLOCKED: PR workflow checkout requires manual Git recovery before activation. code=${state.code} retryable=false required_action=${state.requiredAction} evidence=${evidence2}`}function checkoutRecoveryRecord(state){if(state.kind!=="recovery-required"&&state.kind!=="indeterminate")throw Error("PR workflow checkout recovery requires a terminal Git state");return{code:state.code,retryable:!1,requiredAction:state.requiredAction,evidence:state.evidence,detectedAt:isoNow()}}async function activatePrWorkflow(directory,sessionID,mode,options={}){let normalizedSessionID=normalizeSessionID(sessionID),checkoutPreflight=!await readPrWorkflowGateState(directory,normalizedSessionID)&&options.requireCheckoutPreflight?await _test_exports.classifyPrWorkflowGitStateAsync(directory):null;return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let existing=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(existing?.mode===mode){if(mode==="PR_FEEDBACK"&&options.prUrl){let requestedTarget=canonicalGitHubPrUrl(options.prUrl);if(!requestedTarget)throw Error("BLOCKED: PR_FEEDBACK target must be a canonical GitHub PR URL");let existingTarget=existing.prFeedbackTargetUrl?canonicalGitHubPrUrl(existing.prFeedbackTargetUrl):null;if(existingTarget&&requestedTarget!==existingTarget)throw Error("BLOCKED: active PR_FEEDBACK targets a different GitHub pull request");if(!existingTarget)existing=await writeStateWhileLocked(directory,{...existing,prFeedbackTargetUrl:options.prUrl,updatedAt:isoNow()})}return options.prHeadSha?bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,options.prHeadSha):existing}if(existing)throw Error(`BLOCKED: session "${normalizedSessionID}" already has an active ${existing.mode} workflow; complete it before starting ${mode}`);if(options.requireCheckoutPreflight){if(!checkoutPreflight)throw Error("BLOCKED: PR workflow gate state changed during checkout preflight; retry activation against the current project state");let lockedCheckoutPreflight=await _test_exports.classifyPrWorkflowGitStateAsync(directory,{ignoredPaths:[path15.join(".swarm",workflowCheckoutMutationLockRelativePath()),path15.join(".swarm",workflowGateStateLockRelativePath(normalizedSessionID))]});if(lockedCheckoutPreflight.kind==="recovery-required"||lockedCheckoutPreflight.kind==="indeterminate")throw Error(formatCheckoutRecoveryBlock(lockedCheckoutPreflight))}let initialHead=options.prHeadSha?await assertCurrentCheckoutHead(directory,options.prHeadSha,mode):void 0,timestamp=isoNow(),feedbackTargetUrl=mode==="PR_FEEDBACK"&&options.prUrl?canonicalGitHubPrUrl(options.prUrl)?options.prUrl:null:void 0;if(feedbackTargetUrl===null)throw Error("BLOCKED: PR_FEEDBACK target must be a canonical GitHub PR URL");let nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:0,workflowInstanceId:randomUUID3(),sessionID:normalizedSessionID,mode,activatedAt:timestamp,updatedAt:timestamp,...initialHead?{prHeadSha:initialHead}:{},...feedbackTargetUrl?{prFeedbackTargetUrl:feedbackTargetUrl}:{}};return writeStateWhileLocked(directory,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 withPrWorkflowCheckoutMutationLock(directory,async()=>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,{markRecoveryRequired:async(gitState)=>{let nextState={...state,updatedAt:isoNow(),checkoutRecovery:checkoutRecoveryRecord(gitState)},persisted=await writeStateWhileLocked(directory,nextState);return Object.assign(state,persisted),persisted}})}))}async function withInactivePrWorkflowCheckoutRestoreLock(directory,sessionID,action){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{if(await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID))throw Error("BLOCKED: checkout restoration is allowed only after complete_pr_workflow or abort_pr_workflow clears the active gate");return await assertNoActivePrWorkflowGateForCheckoutRestore(directory),action()}))}async function assertNoActivePrWorkflowGateForCheckoutRestore(directory){let gateDirectory=validateSwarmPath(directory,WORKFLOW_GATE_DIR),handle;try{handle=await fsp3.opendir(gateDirectory)}catch(error49){if(error49.code==="ENOENT")return;throw error49}let entriesRead=0,scanError,closeError;try{for(;;){let entry=await handle.read();if(!entry)break;if(entriesRead+=1,entriesRead>MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES)throw Error("BLOCKED: PR workflow gate inventory exceeds the bounded checkout-restoration scan; clear stale workflow state before retrying");if(!/\.json$/i.test(entry.name))continue;if(!entry.isFile())throw Error("BLOCKED: PR workflow gate inventory contains a non-regular state entry; checkout restoration cannot prove project inactivity");let statePath=validateSwarmPath(directory,path15.join(WORKFLOW_GATE_DIR,entry.name)),state=await readPrWorkflowGateStateFileFromDisk(statePath,entry.name);if(!state)continue;let expectedName=path15.basename(workflowGateStateRelativePath(state.sessionID));if(entry.name!==expectedName)throw Error("BLOCKED: PR workflow gate inventory contains an ambiguous state filename; checkout restoration cannot prove project inactivity");throw Error(`BLOCKED: checkout restoration cannot mutate this project while session "${state.sessionID}" has an active ${state.mode} workflow`)}}catch(error49){scanError=error49}finally{try{await handle.close()}catch(error49){if(error49.code!=="ERR_DIR_CLOSED")closeError=error49}}if(scanError!==void 0)throw scanError;if(closeError!==void 0)throw closeError}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 fsp3.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={kind:"recovery",reason:""}){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().length>0?options.reason.trim().slice(0,500):void 0;if(sanitizedReason===void 0)throw Error(`BLOCKED: ${state.mode} abort requires a non-empty reason (recorded to the audit trail).`);let abortEvent={type:"pr_workflow_aborted",timestamp:isoNow(),sessionID:state.sessionID,mode:state.mode,kind:options.kind,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},...state.checkoutRecovery?{hadTerminalRecovery:!0}:{},openLanes:openLanes.length,reason:sanitizedReason};try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp3.appendFile(eventsPath,`${JSON.stringify(abortEvent)}
|
|
195
|
-
`,"utf-8")}catch{}return
|
|
196
|
-
`,"utf-8")}catch{}return withSessionStateMutation(directory,state.sessionID,async()=>writeStateWhileLocked(directory,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,mode="PR_REVIEW"){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 two separate standalone commands. First run: git -C "${directory}" rev-parse --verify HEAD^0. Then run: git -C "${directory}" cat-file -t HEAD (which must print commit).`);if(currentHead.toLowerCase()!==normalizedExpected.toLowerCase()){let remediation=mode==="PR_FEEDBACK"?"Check out the intended local tracking branch at that exact head (for example with a safe standalone `gh pr checkout <number-or-url>` or `git switch -c <local> --track <remote>/<branch>`), then retry the bind. Do not create a new detached feedback checkout.":`Run bare, standalone commands from that directory. If the commit is not present locally, first run \`git fetch origin <pr-head-ref>\`. Then run \`git switch --detach ${normalizedExpected}\`. Do not prefix the switch with \`git -C\`; the read-only shell classifier refuses \`git -C ... switch\`.`;throw Error(`BLOCKED: current checkout HEAD "${currentHead}" does not match PR head "${normalizedExpected}" (working directory: "${directory}"). ${remediation}`)}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 currentHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!currentHead)throw Error("BLOCKED: PR_FEEDBACK requires a resolved exact Git HEAD before first head bind");if(currentHead.toLowerCase()!==prHeadSha.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK exact head changed before attach; expected ${prHeadSha}, received ${currentHead}`);let currentUpstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory),matchingRemoteRefs=await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha);if(currentUpstream){if(matchingRemoteRefs===null)throw Error("BLOCKED: PR_FEEDBACK could not verify the current upstream against the exact intake PR head; the bounded Git query failed or timed out");if(matchingRemoteRefs.includes(currentUpstream.remoteTrackingRef))return;throw Error(`BLOCKED: PR_FEEDBACK current upstream "${currentUpstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}"; refusing to replace an existing tracking relationship`)}let candidates=await resolvePrFeedbackTrackingCandidatesAsync(directory,prHeadSha);if(!candidates)throw Error(`BLOCKED: PR_FEEDBACK could not inspect tracked branches for exact PR head "${prHeadSha}"; the bounded Git query failed or timed out`);let{local:localCandidates,remote:remoteCandidates}=candidates;if(localCandidates.length===1){if(await _test_exports.beforePrFeedbackTrackingSwitch?.(),!await switchPrFeedbackTrackingCandidateAsync(directory,localCandidates[0]))throw Error(`BLOCKED: PR_FEEDBACK could not attach exact local tracked branch "${localCandidates[0].branchName}"; it may be checked out in another linked worktree or the bounded Git switch failed`)}else if(localCandidates.length>1)throw Error(`BLOCKED: PR_FEEDBACK exact head "${prHeadSha}" matches multiple local tracked branches: ${localCandidates.map((candidate)=>candidate.branchName).join(", ")}`);else if(remoteCandidates.length===1){if(await _test_exports.beforePrFeedbackTrackingSwitch?.(),!await switchPrFeedbackTrackingCandidateAsync(directory,remoteCandidates[0]))throw Error(`BLOCKED: PR_FEEDBACK could not attach exact remote-tracking branch "${remoteCandidates[0].remoteTrackingRef}"; the bounded Git switch failed or timed out`)}else if(remoteCandidates.length>1)throw Error(`BLOCKED: PR_FEEDBACK exact head "${prHeadSha}" matches multiple remote-tracking refs: ${remoteCandidates.map((candidate)=>candidate.remoteTrackingRef).join(", ")}`);else throw Error("BLOCKED: PR_FEEDBACK requires a current local branch or exact remote-tracking ref that points to the intake PR head before the first bind");await _test_exports.afterPrFeedbackTrackingSwitch?.();let attachedHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(attachedHead?.toLowerCase()!==prHeadSha.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK exact head changed after attach; expected ${prHeadSha}, received ${attachedHead??"(unresolved)"}`);if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK requires a clean working tree after checkout attachment");let attachedUpstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!attachedUpstream)throw Error("BLOCKED: PR_FEEDBACK could not resolve the attached branch upstream after checkout promotion");if(!(await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha))?.includes(attachedUpstream.remoteTrackingRef))throw Error(`BLOCKED: PR_FEEDBACK upstream "${attachedUpstream.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)){let rejection=await tierLConsolidationRejection(directory,state,normalizedLanes,options.revisionDigest);if(rejection)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, or on a retry batch that satisfies all five of: (1) every consolidated dimension already has a recorded lane that reached a terminal non-successful state; (2) no consolidated dimension already has a successful source; (3) no single lane owns all ${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions; (4) a batch claiming all ${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions uses at least ${PR_REVIEW_BASE_LANE_FLOORS.L} lanes; and (5) across every recorded base batch the six dimensions stay backed by at least ${PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR} distinct lanes, counting each dimension no consolidated lane claims as one plus the FEWEST declared consolidated lanes that suffice to cover every dimension consolidated lanes do claim. Clause 5 is cumulative over every base batch this wave recorded, including batches the `+"capacity GC has since dropped, and it counts a minimum cover rather than declarations — so "+"neither splitting one consolidation across several batches nor declaring overlapping or duplicate consolidations evades it. "+rejection)}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){if(state=await prunePrWorkflowBatchesForCapacity(directory,state,options.revisionDigest),previous=state.prReviewBaseDispatches??[],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}function summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest){let successful=new Set,dedicatedSuccessful=new Set,terminallyFailed=new Set;for(let batch of state.prReviewBaseDispatches??[]){let batchSuccessful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);for(let obligation of batchSuccessful)successful.add(obligation);for(let lane of batch.lanes){if((lane.ownedWorkflowLanes?.length??1)!==1)continue;let dimension=lane.ownedWorkflowLanes?.[0]??lane.workflowLane;if(batchSuccessful.has(dimension))dedicatedSuccessful.add(dimension)}let integrityPassingLaneIds=new Set(recordsPassingBatchIntegrity(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt).map((qualified)=>qualified.record.laneId)),records=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID});for(let lane of batch.lanes){if(integrityPassingLaneIds.has(lane.laneId))continue;let laneRecords=records.filter((record2)=>record2.laneId===lane.laneId);if(laneRecords.length===0||!laneRecords.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.status)))continue;for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])terminallyFailed.add(dimension)}}return{successful,dedicatedSuccessful,terminallyFailed}}function encodeConsolidatedLaneKey(owned){return[...new Set(owned)].sort().join("|")}function decodeConsolidatedLaneKey(key){return key.split("|").filter((dimension)=>dimension.length>0)}function minimumConsolidatedLaneCover(sets){let bitOf=new Map;for(let set2 of sets)for(let dimension of set2)if(!bitOf.has(dimension))bitOf.set(dimension,bitOf.size);let universeSize=bitOf.size;if(universeSize===0)return 0;let distinctMasks=new Set,largestSetSize=1;for(let set2 of sets){let mask=0,size=0;for(let dimension of set2){let bit=1<<bitOf.get(dimension);if((mask&bit)===0)size+=1;mask|=bit}if(mask===0)continue;distinctMasks.add(mask),largestSetSize=Math.max(largestSetSize,size)}if(universeSize>MAX_COVER_UNIVERSE_BITS)return Math.ceil(universeSize/largestSetSize);let full=(1<<universeSize)-1,unreachable=universeSize+1,best=Array(full+1).fill(unreachable);best[0]=0;for(let mask=0;mask<full;mask+=1){let steps=best[mask];if(steps===unreachable)continue;for(let setMask of distinctMasks){let next=mask|setMask;if(next===mask)continue;if(best[next]>steps+1)best[next]=steps+1}}return best[full]}function tierLBackingLaneCount(state,normalizedLanes,dedicatedSuccessful){let consolidatedDimensions=new Set,consolidatedSets=[],consider=(owned,allowSupersede)=>{let declared=owned.filter((dimension)=>Boolean(dimension));if(declared.length<2)return;let live=allowSupersede?declared.filter((dimension)=>!dedicatedSuccessful.has(dimension)):declared;if(live.length===0)return;consolidatedSets.push([...new Set(live)]);for(let dimension of live)consolidatedDimensions.add(dimension)},considerLane=(lane,allowSupersede)=>consider(lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane],allowSupersede);for(let batch of state.prReviewBaseDispatches??[])for(let lane of batch.lanes)considerLane(lane,!0);for(let key of state.prReviewRetiredConsolidatedLanes??[])consider(decodeConsolidatedLaneKey(key),!0);for(let lane of normalizedLanes)considerLane(lane,!1);return{backingLanes:PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!consolidatedDimensions.has(dimension)).length+minimumConsolidatedLaneCover(consolidatedSets),consolidatedDimensions:[...consolidatedDimensions]}}async function tierLConsolidationRejection(directory,state,normalizedLanes,revisionDigest){if((state.prReviewBaseDispatches?.length??0)===0)return"This is the initial base wave, which may never consolidate at tier L.";let dimensionCount=PR_REVIEW_BASE_DIMENSION_IDS.length,consolidatedLanes=normalizedLanes.filter((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1),wholeWaveLane=consolidatedLanes.find((lane)=>(lane.ownedWorkflowLanes?.length??1)>=dimensionCount);if(wholeWaveLane)return`Lane "${wholeWaveLane.laneId}" owns all ${dimensionCount} dimensions on its own.`;if(new Set(normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane])).size>=dimensionCount&&normalizedLanes.length<PR_REVIEW_BASE_LANE_FLOORS.L)return`This batch claims all ${dimensionCount} dimensions with only ${normalizedLanes.length} lanes.`;let digest2=revisionDigest;if(!digest2)digest2=(await createPrReviewGateContext(directory,state)).revisionDigest;let attempts=summarizePrReviewBaseDimensionAttempts(directory,state,digest2),consolidatedDimensions=[...new Set(consolidatedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]))].filter((dimension)=>Boolean(dimension)),alreadySuccessful=consolidatedDimensions.filter((dimension)=>attempts.successful.has(dimension));if(alreadySuccessful.length>0)return`These consolidated dimensions already have a successful source: ${alreadySuccessful.join(", ")}.`;let notTerminallyFailed=consolidatedDimensions.filter((dimension)=>!attempts.terminallyFailed.has(dimension));if(notTerminallyFailed.length>0)return`These consolidated dimensions have no recorded lane that reached a terminal non-successful state (never dispatched, still in flight, or awaiting ingestion): ${notTerminallyFailed.join(", ")}.`;let backing=tierLBackingLaneCount(state,normalizedLanes,attempts.dedicatedSuccessful);if(backing.backingLanes<PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR)return`Across every base batch this wave would be backed by only ${backing.backingLanes} distinct lanes (each dimension no consolidated lane claims counts as one, plus the fewest declared consolidated lanes that cover the rest), and dimensions ${backing.consolidatedDimensions.join(", ")} would be covered by consolidated lanes.`;return null}async function prunePrWorkflowBatchesForCapacity(directory,state,revisionDigest){try{let digest2=revisionDigest??(await createPrReviewGateContext(directory,state)).revisionDigest,before={candidate:derivePrReviewCandidateInventory(directory,state,{revisionDigest:digest2}),critic:derivePrReviewCriticInventory(directory,state,{revisionDigest:digest2})},pruned=pruneWorkflowBatches(directory,state,digest2);if(!pruned)return state;let after={candidate:derivePrReviewCandidateInventory(directory,pruned,{revisionDigest:digest2}),critic:derivePrReviewCriticInventory(directory,pruned,{revisionDigest:digest2})};if(!sameStringSet(before.candidate,after.candidate)||!sameStringSet(before.critic,after.critic))return warn("PR_REVIEW batch GC aborted: pruning would have changed the derived inventory; every batch was kept"),state;let survivingBaseIds=new Set((pruned.prReviewBaseDispatches??[]).map((batch)=>batch.batchId));if(state.prReviewBaseDispatch&&!survivingBaseIds.has(state.prReviewBaseDispatch.batchId))return warn("PR_REVIEW batch GC aborted: the latest base dispatch pointer would have been orphaned"),state;return pruned}catch(error49){return warn(`PR_REVIEW batch GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),state}}function pruneWorkflowBatches(directory,state,revisionDigest){let baseBatches=state.prReviewBaseDispatches??[],validationBatches=state.prReviewValidationBatches??[],ctx={revisionDigest},contributingBaseBatchIds=new Set;for(let batch of baseBatches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);if(batch.lanes.some((lane)=>((lane.ownedWorkflowLanes?.length)?lane.ownedWorkflowLanes:[lane.workflowLane]).every((dimension)=>successful.has(dimension))))contributingBaseBatchIds.add(batch.batchId)}let newestBaseBatchId=baseBatches.at(-1)?.batchId,survivingBase=baseBatches.filter((batch)=>batch.batchId===newestBaseBatchId||contributingBaseBatchIds.has(batch.batchId)),newestBatchIdByPhase=new Map;for(let batch of validationBatches)newestBatchIdByPhase.set(batch.phase,batch.batchId);let contributingReviewerBatchIds=new Set(composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx,!0).contributingBatchIds),survivingValidation=validationBatches.filter((batch)=>{if(batch.phase==="council"||batch.phase==="critic")return!0;if(newestBatchIdByPhase.get(batch.phase)===batch.batchId)return!0;return contributingReviewerBatchIds.has(batch.batchId)});if(survivingBase.length===baseBatches.length&&survivingValidation.length===validationBatches.length)return null;let survivingValidationIds=new Set(survivingValidation.map((batch)=>batch.batchId)),retiredReviewerSessionIds=new Set(state.prReviewRetiredReviewerSessionIds??[]);for(let batch of validationBatches){if(batch.phase!=="reviewer")continue;if(survivingValidationIds.has(batch.batchId))continue;for(let record2 of findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)retiredReviewerSessionIds.add(subagentSessionId)}}if(retiredReviewerSessionIds.size>MAX_RETIRED_REVIEWER_SESSION_IDS)return warn("PR_REVIEW batch GC aborted: retiring these reviewer batches would overflow the forbidden child-session ledger; every batch was kept"),null;let survivingBaseIds=new Set(survivingBase.map((batch)=>batch.batchId)),retiredConsolidatedLanes=new Set(state.prReviewRetiredConsolidatedLanes??[]);for(let batch of baseBatches){if(survivingBaseIds.has(batch.batchId))continue;for(let lane of batch.lanes){let owned=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(new Set(owned).size<2)continue;retiredConsolidatedLanes.add(encodeConsolidatedLaneKey(owned))}}if(retiredConsolidatedLanes.size>MAX_RETIRED_CONSOLIDATED_LANES)return warn("PR_REVIEW batch GC aborted: retiring these base batches would overflow the retired consolidated-lane ledger; every batch was kept"),null;let survivingBatchIds=new Set([...survivingBaseIds,...survivingValidationIds]),coherence=Object.fromEntries(Object.entries(state.prReviewBatchCoherence??{}).filter(([batchId])=>survivingBatchIds.has(batchId)));return{...state,...state.prReviewBaseDispatches?{prReviewBaseDispatches:survivingBase}:{},...state.prReviewValidationBatches?{prReviewValidationBatches:survivingValidation}:{},prReviewBatchCoherence:Object.keys(coherence).length>0?coherence:void 0,prReviewRetiredReviewerSessionIds:retiredReviewerSessionIds.size>0?[...retiredReviewerSessionIds]:void 0,prReviewRetiredConsolidatedLanes:retiredConsolidatedLanes.size>0?[...retiredConsolidatedLanes]:void 0}}async function assertPrReviewBaseCoverageSettled(directory,sessionID,gateContext){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 ctx=gateContext??await createPrReviewGateContext(directory,state),covered=new Set,malformedDiagnostics=[];for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest,malformedDiagnostics);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)"}${malformedDiagnostics.length>0?`; first failed lane predicates: ${malformedDiagnostics.join(" | ")}`:""}; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; expected candidate row: ${CANDIDATE_HEADERS.base_explorer}; expected clean row: ${CLEAN_TEMPLATES.base_explorer}`);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");let ctx=await createPrReviewGateContext(directory,state);if(phase==="reviewer"&&(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state=await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);else if(phase==="critic")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);ctx={revisionDigest:ctx.revisionDigest};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`);let validatedInventory;if(phase==="reviewer"||phase==="critic"){assertNoDuplicates(normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),`PR_REVIEW ${phase} review item ownership`);let assigned=normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]);validatedInventory=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state,ctx):derivePrReviewCriticInventory(directory,state,ctx),assertExactStringSet(assigned,validatedInventory,`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){if(state=await prunePrWorkflowBatchesForCapacity(directory,state,ctx.revisionDigest),previous=state.prReviewValidationBatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached")}let record2={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},reviewerItemBindings=phase==="critic"?criticReviewerItemBindings(directory,state,normalizedLanes,ctx):void 0,retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"||Boolean(state.prReviewBatchCoherence?.[batch.batchId]?.reviewerItemBindings)):previous,retainedIds=new Set(retained.map((batch)=>batch.batchId)),coherence=Object.fromEntries(Object.entries(state.prReviewBatchCoherence??{}).filter(([id])=>retainedIds.has(id)));if(validatedInventory)coherence[batchId]={validatedInventory,...reviewerItemBindings?{reviewerItemBindings}:{}};let nextState={...state,updatedAt:isoNow(),prReviewValidationBatches:[...retained,record2],prReviewBatchCoherence:Object.keys(coherence).length>0?coherence:void 0};return await persistState(directory,nextState),nextState}async function assertPrReviewValidationSettled(directory,sessionID,phase,gateContext){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=gateContext??await createPrReviewGateContext(directory,state),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??[],batches=requiredPhase==="council"?validationBatches.filter((batch)=>batch.phase==="council"):prReviewPhaseWindow(state,requiredPhase);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`);if(requiredPhase==="council"){let settled=new Set;for(let batch of batches)for(let obligation of successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt,!0,new Set,ctx.revisionDigest))settled.add(obligation);let missing=[...new Set(batches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane)))].filter((obligation)=>!settled.has(obligation));if(missing.length>0)throw Error(`BLOCKED: PR_REVIEW council obligations lack successful exact artifacts: ${missing.join(", ")}`);continue}let composed=composePrReviewPhaseVerdicts(directory,state,requiredPhase,ctx);if(composed.unclaimed.length>0){let named=composed.unclaimed.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=composed.unclaimed.length-named.length;throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} items lack an authenticated verdict from any successful lane: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:"")+(composed.diagnostics.length>0?`; diagnostics: ${composed.diagnostics.join(" | ")}`:""))}if(assertSettledPhaseHasAuthoritativeVerdicts(requiredPhase,composed,requiredPhase==="reviewer"?deriveLatestPrReviewReviewerVerdicts(directory,state,ctx):deriveLatestPrReviewCriticVerdicts(directory,state,ctx),`assertPrReviewValidationSettled(${requiredPhase})`),composed.diagnostics.length>0)warn(`PR_REVIEW ${requiredPhase} settled by composition across batches [${composed.contributingBatchIds.join(", ")}] with abandoned or ineligible lanes`,composed.diagnostics)}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),requiredHandoffIds=state.prFeedbackReviewHandoff?.findingIds??[],inventorySet=new Set(normalizedInventory),missingHandoffIds=requiredHandoffIds.filter((findingId)=>!inventorySet.has(findingId));if(missingHandoffIds.length>0)throw Error(`BLOCKED: PR_FEEDBACK inventory must include every continued review finding: ${missingHandoffIds.join(", ")}`);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 prunePrFeedbackVerificationsForCapacity(directory,state){try{let digest2=await currentPrFeedbackRevisionDigest(directory,state),batches=state.prFeedbackVerifications??[],before=prFeedbackCoveredItems(directory,state,digest2),newestBatchId=batches.at(-1)?.batchId,surviving=batches.filter((batch)=>batch.batchId===newestBatchId||prFeedbackBatchCoveredItems(directory,state,batch,digest2).size>0);if(surviving.length===batches.length)return state;let retiredItemOwnership={...state.prFeedbackRetiredItemOwnership??{}},survivingIds=new Set(surviving.map((batch)=>batch.batchId));for(let batch of batches){if(survivingIds.has(batch.batchId))continue;for(let lane of batch.ownership)for(let itemId of lane.ownedItemIds)retiredItemOwnership[itemId]=lane.laneId}if(Object.keys(retiredItemOwnership).length>MAX_RETIRED_FEEDBACK_ITEM_OWNERS)return warn("PR_FEEDBACK verification GC aborted: retiring these batches would overflow the item-ownership ledger; every batch was kept"),state;let pruned={...state,prFeedbackVerifications:surviving,prFeedbackRetiredItemOwnership:Object.keys(retiredItemOwnership).length>0?retiredItemOwnership:void 0},after=prFeedbackCoveredItems(directory,pruned,digest2);if(!sameStringSet([...before],[...after]))return warn("PR_FEEDBACK verification GC aborted: pruning would have changed the covered inventory; every batch was kept"),state;if(state.prFeedbackVerification&&!survivingIds.has(state.prFeedbackVerification.batchId))return warn("PR_FEEDBACK verification GC aborted: the latest verification pointer would have been orphaned"),state;return pruned}catch(error49){return warn(`PR_FEEDBACK verification GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),state}}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){if(state=await prunePrFeedbackVerificationsForCapacity(directory,state),previous=state.prFeedbackVerifications??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached")}for(let[itemId,laneId]of Object.entries(state.prFeedbackRetiredItemOwnership??{}))claimedByItemId.set(itemId,laneId);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}function prFeedbackBatchCoveredItems(directory,state,batch,currentDigest){let covered=new Set,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)}return covered}function prFeedbackCoveredItems(directory,state,currentDigest){let covered=new Set;for(let batch of state.prFeedbackVerifications??[])for(let itemId of prFeedbackBatchCoveredItems(directory,state,batch,currentDigest))covered.add(itemId);return covered}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=prFeedbackCoveredItems(directory,state,currentDigest),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=createHash8("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 normalizedCategories=optionalCategoryOrder.filter((category)=>applicableCategories.includes(category)),retainsGateBatches=stageARetainsGateBatches(state.prFeedbackStageA,{revisionDigest:currentDigest,applicableCategories:normalizedCategories,applicableObligations}),nextState={...state,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks3],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:normalizedCategories,applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:retainsGateBatches?[...state.prFeedbackGateBatches??[]]:[],prFeedbackReadyToPublish:void 0};return await persistState(directory,nextState),nextState}function canonicalStageAObligation(obligation){return[obligation.id,obligation.category,obligation.workingDirectory,obligation.source,obligation.validatorContract?.path??"",obligation.validatorContract?.id??""].join("\x00")}function stageARetainsGateBatches(previous,next){if(!previous||previous.revisionDigest!==next.revisionDigest)return!1;if(!previous.applicableCategories||!previous.applicableObligations)return!1;let nextCategories=new Set(next.applicableCategories);if(!previous.applicableCategories.every((category)=>nextCategories.has(category)))return!1;let nextObligations=new Set(next.applicableObligations.map(canonicalStageAObligation));return previous.applicableObligations.every((obligation)=>nextObligations.has(canonicalStageAObligation(obligation)))}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,runId,artifactPath){let state=await assertPrReviewBaseCoverageSettled(directory,sessionID),normalizedRunId=runId.trim();if(!normalizedRunId)throw Error("BLOCKED: PR_REVIEW trigger artifact run_id is required");let normalizedPath=artifactPath.trim();if(!normalizedPath)throw Error("BLOCKED: PR_REVIEW trigger artifact path is required");if(state.prReviewTriggerEvalRunId&&state.prReviewTriggerEvalRunId!==normalizedRunId)throw Error(`BLOCKED: PR_REVIEW trigger evaluation is already bound to run "${state.prReviewTriggerEvalRunId}"`);if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==normalizedRunId)throw Error(`BLOCKED: PR_REVIEW trigger evaluation run_id must match the findings artifact run "${state.prReviewArtifactRunId}"`);let nextState={...state,updatedAt:isoNow(),prReviewTriggerEvalPath:normalizedPath,prReviewTriggerEvalRunId:normalizedRunId};return await persistState(directory,nextState),nextState}async function bindPrReviewTriggerLedger(directory,sessionID,input){let ledger;try{ledger=validatePrReviewInlineTriggerLedger(input)}catch(error49){throw Error(`BLOCKED: invalid PR_REVIEW trigger_evaluation: ${error49 instanceof Error?error49.message:String(error49)}`)}let state=await assertPrReviewBaseCoverageSettled(directory,sessionID);if(state.prReviewTriggerLedger){let frozen;try{frozen=validatePrReviewInlineTriggerLedger(state.prReviewTriggerLedger)}catch(error49){throw Error(`BLOCKED: persisted PR_REVIEW trigger ledger is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}if(prReviewTriggerLedgerDigest(frozen.rows)!==prReviewTriggerLedgerDigest(ledger.rows))throw Error("BLOCKED: PR_REVIEW trigger_evaluation must remain exactly identical across every micro dispatch");return state}let nextState={...state,updatedAt:isoNow(),prReviewTriggerLedger:ledger.rows};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`);let ctx=await createPrReviewGateContext(directory,state);if(boundary==="post_reviewer")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);else if(boundary==="post_critic"){if(await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx),derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,"assertPrReviewArtifactBoundary(post_critic)").length>0)state=await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx)}if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==runId)throw Error(`BLOCKED: PR_REVIEW artifacts are already bound to run "${state.prReviewArtifactRunId}"`);if(state.prReviewTriggerEvalRunId&&state.prReviewTriggerEvalRunId!==runId)throw Error(`BLOCKED: PR_REVIEW findings must use the same run as the trigger evaluation "${state.prReviewTriggerEvalRunId}"`);let expectedFindingIds=derivePrReviewCandidateInventory(directory,state,ctx),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 ctx=await createPrReviewGateContext(directory,state),reviewerVerdicts=authoritativeReviewerVerdictsForGate(directory,state,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`),criticVerdicts=boundary==="post_critic"?authoritativeCriticVerdictsForGate(directory,state,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`):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}function normalizePrReviewFeedbackHandoffPath(handoffPath){let normalized=handoffPath.trim().replace(/\\/g,"/"),relative5=normalized.startsWith(".swarm/")?normalized.slice(7):normalized,matched=relative5.match(PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN);if(!matched)return null;return{runId:matched[1],relativePath:relative5}}async function readBoundedSwarmRegularFile(directory,relativePath,maxBytes,label){let absPath=validateSwarmPath(directory,relativePath),swarmRoot=path15.resolve(directory,".swarm"),rootStat,artifactStat;try{rootStat=await fsp3.lstat(swarmRoot,{bigint:!0}),artifactStat=await fsp3.lstat(absPath,{bigint:!0})}catch(error49){if(error49.code==="ENOENT")throw Error(`BLOCKED: ${label} "${relativePath}" does not exist`);throw error49}if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error(`BLOCKED: ${label} root must be a real project .swarm directory`);if(artifactStat.isSymbolicLink()||!artifactStat.isFile())throw Error(`BLOCKED: ${label} must be a bounded regular file`);if(artifactStat.size>BigInt(maxBytes))throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);let[realRoot,realArtifact]=await Promise.all([fsp3.realpath(swarmRoot),fsp3.realpath(absPath)]),relativeRealPath=path15.relative(realRoot,realArtifact);if(relativeRealPath===""||relativeRealPath===".."||relativeRealPath.startsWith(`..${path15.sep}`)||path15.isAbsolute(relativeRealPath))throw Error(`BLOCKED: ${label} escapes the project .swarm directory`);await _test_exports.beforeBoundedSwarmFileOpen?.();let handle=await fsp3.open(realArtifact,"r");try{let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile()||openedStat.size>BigInt(maxBytes)||!sameBigIntFileIdentity(artifactStat,openedStat))throw Error(`BLOCKED: ${label} changed during its bounded read`);let[postRootStat,postArtifactStat,postRealRoot,postRealArtifact]=await Promise.all([fsp3.lstat(swarmRoot,{bigint:!0}),fsp3.lstat(absPath,{bigint:!0}),fsp3.realpath(swarmRoot),fsp3.realpath(absPath)]),postRelativeRealPath=path15.relative(postRealRoot,postRealArtifact);if(postRootStat.isSymbolicLink()||!postRootStat.isDirectory()||!sameBigIntFileIdentity(rootStat,postRootStat)||postArtifactStat.isSymbolicLink()||!postArtifactStat.isFile()||!sameBigIntFileIdentity(artifactStat,postArtifactStat)||!sameBigIntFileIdentity(openedStat,postArtifactStat)||normalizeComparableFsPath(realRoot)!==normalizeComparableFsPath(postRealRoot)||normalizeComparableFsPath(realArtifact)!==normalizeComparableFsPath(postRealArtifact)||postRelativeRealPath===""||postRelativeRealPath===".."||postRelativeRealPath.startsWith(`..${path15.sep}`)||path15.isAbsolute(postRelativeRealPath))throw Error(`BLOCKED: ${label} changed or escaped during its bounded read`);let buffer=Buffer.allocUnsafe(maxBytes+1),{bytesRead}=await handle.read(buffer,0,maxBytes+1,0);if(bytesRead>maxBytes)throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);return buffer.subarray(0,bytesRead).toString("utf8")}finally{await handle.close()}}function sameBigIntFileIdentity(left,right){return left.dev===right.dev&&left.ino===right.ino}function normalizeComparableFsPath(value){let normalized=path15.normalize(path15.resolve(value));return process.platform==="win32"?normalized.toLowerCase():normalized}async function readPrReviewFeedbackHandoffArtifact(directory,relativePath){let raw=await readBoundedSwarmRegularFile(directory,relativePath,PR_REVIEW_HANDOFF_MAX_BYTES,"PR_REVIEW feedback handoff artifact"),parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is not valid JSON")}let parsed=PrReviewFeedbackHandoffArtifactSchema.safeParse(parsedJson);if(!parsed.success)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is invalid");if(new Set(parsed.data.finding_ids).size!==parsed.data.finding_ids.length)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact contains duplicate finding IDs");return{artifact:parsed.data,digest:createHash8("sha256").update(raw,"utf8").digest("hex")}}async function readActionableReviewFindingIds(directory,state,runId){let expectedPath=`pr-review/${runId}/findings.jsonl`;if(state.prReviewFindingsPath!==expectedPath)throw Error(`BLOCKED: PR_REVIEW transition requires the exact final findings artifact "${expectedPath}"`);let raw=await readBoundedSwarmRegularFile(directory,expectedPath,PR_REVIEW_FINDINGS_MAX_BYTES,"PR_REVIEW final findings artifact"),latest=new Map;for(let[index,line]of raw.split(/\r?\n/).entries()){if(!line.trim())continue;let value;try{value=JSON.parse(line)}catch{throw Error(`BLOCKED: PR_REVIEW final findings artifact contains invalid JSON at line ${index+1}`)}let parsed=PrReviewFindingProjectionSchema.safeParse(value);if(!parsed.success)throw Error(`BLOCKED: PR_REVIEW final findings artifact contains an invalid record at line ${index+1}`);latest.set(parsed.data.finding_id,parsed.data)}return[...latest.values()].filter((record2)=>record2.status==="CONFIRMED"&&record2.next_action==="handoff_to_feedback").map((record2)=>record2.finding_id).sort()}function canonicalGitHubPrUrl(value){try{let url2=new URL(value);if(url2.protocol!=="https:"||url2.hostname.toLowerCase()!=="github.com")return null;let matched=url2.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(!matched)return null;let prNumber=Number(matched[3]);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return`github.com/${matched[1].toLowerCase()}/${matched[2].toLowerCase()}/pull/${prNumber}`}catch{return null}}function workflowIdentity(state){return state.workflowInstanceId??`legacy-${createHash8("sha256").update(`${state.sessionID}\x00${state.mode}\x00${state.activatedAt}`).digest("hex").slice(0,32)}`}function sameHandoffIds(left,right){let normalizedLeft=[...new Set(left)].sort(),normalizedRight=[...new Set(right)].sort();return sameStringArray(normalizedLeft,normalizedRight)}function assertSamePrFeedbackHandoff(state,relativePath,read,requestedPrUrl){let existing=state.prFeedbackReviewHandoff;if(!existing)throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK without persisted review handoff provenance`);let artifactPr=canonicalGitHubPrUrl(read.artifact.pr_url),requestedPr=requestedPrUrl?canonicalGitHubPrUrl(requestedPrUrl):artifactPr;if(!artifactPr||requestedPrUrl&&requestedPr!==artifactPr||existing.path!==relativePath||existing.runId!==read.artifact.run_id||existing.digest!==read.digest||existing.sourcePrHeadSha.toLowerCase()!==read.artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(existing.prUrl)!==artifactPr||!sameHandoffIds(existing.findingIds,read.artifact.finding_ids))throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK for a different handoff or PR`)}async function assertPrReviewTerminalReady(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");await assertPrReviewCleanCheckout(directory,"PR_REVIEW");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: PR_REVIEW transition has ${open3.length} unsettled PR workflow lane(s)`);let ctx=await createPrReviewGateContext(directory,state);if(await assertPrReviewBaseCoverageSettled(directory,sessionID,ctx),!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW transition requires a persisted trigger evaluation artifact");if((state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);let criticInventory=derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,"completePrWorkflow critic-coverage gate");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",ctx)}let requiredBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state.prReviewArtifactBoundaries??[]),missing=requiredBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state.prReviewFindingsPath||missing.length>0)throw Error(`BLOCKED: PR_REVIEW transition requires durable findings checkpoints; missing: ${missing.join(", ")||"findings path"}`);if(state.prReviewHandoffRequired&&!state.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact");return state}async function transitionPrReviewToFeedback(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID),normalizedHandoff=normalizePrReviewFeedbackHandoffPath(request.handoffPath);if(!normalizedHandoff||normalizedHandoff.runId!==request.runId)throw Error("BLOCKED: PR-feedback continuation must use .swarm/pr-review/<run_id>/feedback-handoff.json");let preliminaryRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath),artifact=preliminaryRead.artifact,artifactPr=canonicalGitHubPrUrl(artifact.pr_url),requestedPr=request.prUrl?canonicalGitHubPrUrl(request.prUrl):null;if(!artifactPr||request.prUrl&&requestedPr!==artifactPr)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested GitHub PR URL");if(artifact.run_id!==request.runId)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested review run");let preliminary=await readPrWorkflowGateState(directory,normalizedSessionID);if(preliminary?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(preliminary,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),preliminary;let sourceIdentity,sourceRevision=0,provenance;if(preliminary){if(preliminary.mode!=="PR_REVIEW")throw wrongModeError(preliminary,"PR_REVIEW");let ready=await assertPrReviewTerminalReady(directory,normalizedSessionID);if(workflowIdentity(ready)!==workflowIdentity(preliminary)||ready.revision!==preliminary.revision||ready.mode!=="PR_REVIEW"||ready.prReviewHandoffPath!==normalizedHandoff.relativePath||ready.prReviewArtifactRunId!==request.runId||!ready.prHeadSha||ready.prHeadSha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(artifact.pr_url)!==canonicalGitHubPrUrl(request.prUrl??artifact.pr_url))throw Error("BLOCKED: PR_REVIEW feedback handoff does not match the terminal active review state");let actionableIds=await readActionableReviewFindingIds(directory,ready,request.runId);if(!sameHandoffIds(actionableIds,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff finding IDs do not match the authoritative final findings ledger");sourceIdentity=workflowIdentity(ready),sourceRevision=ready.revision,provenance="active-review-v1"}else{if(!request.prUrl)throw Error("BLOCKED: continuing a completed PR_REVIEW requires an explicit GitHub PR URL");sourceIdentity=`external-${preliminaryRead.digest.slice(0,32)}`,provenance="external-v1"}return await _test_exports.beforePrFeedbackTransitionLock?.(),withSessionStateMutation(directory,normalizedSessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(current?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(current,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),current;if(provenance==="active-review-v1"){if(!current||current.mode!=="PR_REVIEW"||workflowIdentity(current)!==sourceIdentity||current.revision!==sourceRevision||current.prHeadSha?.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||current.prReviewArtifactRunId!==request.runId||current.prReviewHandoffPath!==normalizedHandoff.relativePath)throw Error("BLOCKED: PR_REVIEW state changed while validating the feedback handoff; retry from current state")}else if(current)throw Error("BLOCKED: another PR workflow became active while validating the external handoff");let lockedRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath);if(lockedRead.digest!==preliminaryRead.digest)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");if(artifactPr!==canonicalGitHubPrUrl(lockedRead.artifact.pr_url)||lockedRead.artifact.run_id!==request.runId||lockedRead.artifact.pr_head_sha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||!sameHandoffIds(lockedRead.artifact.finding_ids,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");let timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:sourceRevision,workflowInstanceId:randomUUID3(),sessionID:normalizedSessionID,mode:"PR_FEEDBACK",activatedAt:timestamp,updatedAt:timestamp,prFeedbackReviewHandoff:{path:normalizedHandoff.relativePath,runId:lockedRead.artifact.run_id,sourcePrHeadSha:lockedRead.artifact.pr_head_sha.toLowerCase(),prUrl:lockedRead.artifact.pr_url,findingIds:[...new Set(lockedRead.artifact.finding_ids)].sort(),digest:preliminaryRead.digest,sourceWorkflowInstanceId:sourceIdentity,provenance},prFeedbackTargetUrl:artifact.pr_url};return writeStateWhileLocked(directory,nextState,{replaceWorkflowInstanceId:provenance==="active-review-v1"?current?.workflowInstanceId:void 0})})}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,shellPermissionEnvelope=null;if(isShellTool&&command.length>0){let trackingFetchTarget=state.prHeadSha?await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state.prHeadSha,allowFetch:!state.prHeadSha,allowTrackingFetch:Boolean(state.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let trustedCapability=getPrWorkflowToolCapability(normalizedTool,state.mode),isNamedReadOnlyTool=trustedCapability!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{}),isRecoverySafeEvidenceTool=trustedCapability==="observe"&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{});if(state.checkoutRecovery){if(isRecoverySafeEvidenceTool||isReadOnlyShell||normalizedTool==="abort_pr_workflow"||normalizedTool==="pr_workflow_status"||normalizedTool==="prepare_pr_workflow_checkout")return;throw Error(`BLOCKED: ${state.mode} requires manual Git recovery before controller work can continue. code=${state.checkoutRecovery.code} retryable=false required_action=${state.checkoutRecovery.requiredAction}`)}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)),stderrMergeNormalizedCommand=command.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"").trim(),isCanonicalReviewCheckout=/^git\s+switch\s+--detach\s+[0-9a-f]{40,64}$/i.test(stderrMergeNormalizedCommand),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"),blockedShellDiagnosis=isShellTool&&command&&!isReadOnlyShell&&shellPermissionEnvelope?` ${describeBlockedPrReviewShellCommand(command,shellPermissionEnvelope)}`:"";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, run `git rev-parse --verify <full_pr_head_sha>^0`, run `git cat-file -t <full_pr_head_sha>` (which must print `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`."+blockedShellDiagnosis);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"+describePrWorkflowControllerToolNames(state.mode)+blockedShellDiagnosis)}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"+describePrWorkflowControllerToolNames(state.mode));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&&normalizedTool==="prepare_pr_workflow_checkout")return;if(!state.prHeadSha&&isDetachedFeedbackCheckout&&!isCanonicalReviewCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref. Other detached refs are not accepted");if(!state.prHeadSha&&isCanonicalReviewCheckout)return;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 should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref");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"){let readyState=await assertPrReviewTerminalReady(directory,sessionID);if(workflowIdentity(readyState)!==workflowIdentity(state)||readyState.revision!==state.revision)throw Error("BLOCKED: PR_REVIEW state changed while checking terminal readiness; retry from current state")}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");let commitCount=await _test_exports.resolveCommitCountSinceAsync(directory,state.prHeadSha,localHead);if(commitCount===0){if(localHead!==state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK zero-descendant completion requires HEAD to equal the immutable intake head (history diverged; resolve it or rebind via rebind_pr_feedback_head)");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK zero-descendant completion requires a clean index and working tree");let classifications=readSettledFeedbackClassifications(directory,readyState),inventory=readyState.prFeedbackInventory??[],offenders=inventory.filter((itemId)=>!classifications.has(itemId)||!FEEDBACK_NO_CHANGE_CLASSIFICATIONS.has(classifications.get(itemId)));if(offenders.length>0)throw Error(`BLOCKED: PR_FEEDBACK zero-commit completion requires every inventory item verified as a no-change outcome (DISPROVED, PRE_EXISTING, NEEDS_MORE_EVIDENCE, or NEEDS_USER_DECISION); offending items: ${offenders.slice(0,10).join(", ")}. Items with confirmed content changes must follow the exactly-one-reviewed-commit path.`);try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp3.appendFile(eventsPath,`${JSON.stringify({type:"pr_feedback_verified_no_change",timestamp:isoNow(),sessionID:state.sessionID,prHeadSha:state.prHeadSha,items:inventory.length})}
|
|
197
|
-
`,"utf-8")}catch{}return await clearPrWorkflowGateState(directory,sessionID,readyState.revision),"verified-no-change"}if(commitCount!==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,"PR_REVIEW"),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 describePrWorkflowControllerToolNames(mode){let modeTools=mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS:PR_FEEDBACK_CONTROLLER_TOOLS,names=[...PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,...modeTools].sort((a,b)=>a.localeCompare(b));return` Allowed controller tools for ${mode}: ${names.join(", ")}. Observe current state read-only with the pr_workflow_status tool.`}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 normalizePrWorkflowShellCommand(command){let normalized=command.trim(),withoutTrailingMerge=normalized.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"");if(withoutTrailingMerge!==normalized)normalized=withoutTrailingMerge.trim();let strippedCdPrefix=!1;for(let index=0;index<PR_WORKFLOW_MAX_CD_PREFIX_STRIPS;index+=1){let next=normalized.replace(PR_WORKFLOW_CD_PREFIX_PATTERN,"");if(next===normalized)break;normalized=next.trim(),strippedCdPrefix=!0}return{normalized,strippedCdPrefix}}function isAllowedPrWorkflowReadOnlyShell(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," ");if(!normalized)return!1;if(hasUnsafeShellControlSyntax(command))return!1;if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))return!1;let gitMatch=normalized.match(PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN);if(gitMatch?.[1]){if(PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN.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|which|where)(?:\s|$)/i.test(normalized)}function describeBlockedPrReviewShellCommand(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," "),gitMatch=normalized.match(PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN),pointer=" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool.",detail,syntaxViolation=describeShellSyntaxViolation(command);if(syntaxViolation)detail=syntaxViolation;else if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))detail="Reason: cd-prefix-on-checkout-verb. Run fetch/checkout/switch/branch or `gh pr checkout` bare, with no `cd <dir> &&` prefix.";else if(PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN.test(normalized)&&gitMatch?.[1]&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))detail="Reason: git -C on a state transition. Run fetch/checkout/switch/branch from the target directory, not via `git -C <dir>`.";else if(!options.allowFetch&&gitMatch?.[1]&&/^fetch(?:\s|$)/i.test(gitMatch[1]))detail=options.allowTrackingFetch?"Reason: bound-fetch-restriction. After the PR head is bound only the exact bound remote-tracking fetch is allowed; read remote state via gh_evidence otherwise.":"Reason: bound-fetch-restriction. Fetch is not permitted in this bound state; read remote state via gh_evidence instead.";else if(gitMatch?.[1]||/^git(?:\s|$)/i.test(normalized))detail="Reason: unlisted git verb. Allowed git reads: status/log/show/diff/rev-parse/merge-base/ls-files/grep/blame/cat-file/for-each-ref, `branch` with listing flags only, `stash list`, `worktree list`, `remote -v`, `config --get`.";else if(/^gh(?:\s|$)/i.test(normalized))detail="Reason: unlisted gh form. Allowed gh reads: pr view/diff/checks/status/list, run view/list/watch, issue view/list, search, api GET. If gh is missing, fetch the api.github.com REST URL with the web fetch tool.";else detail="Reason: unlisted binary. Allowed: rg/grep/cat/ls/dir/pwd/which/where plus read-only git/gh intake.";return detail+" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool."}function classifyPrWorkflowShellSyntax(command){let{normalized:inner}=normalizePrWorkflowShellCommand(command),compact=inner.replace(/\s+/g," ").trim();if(!compact)return{unsafe:!0,reason:"compound-syntax"};if(/\$\(|@\(/.test(inner))return{unsafe:!0,reason:"command-substitution"};if(/\\"|\^"/.test(inner))return{unsafe:!0,reason:"ambiguous-escaped-quote"};if(/[\r\n;&<>`]/.test(inner))return{unsafe:!0,reason:"compound-syntax"};let tokens=[],current="",quoted=!1,quote=null,pipeIsDoubleQuoted=!0,flush=()=>{if(current.length>0||quoted)tokens.push({value:current,quoted,pipeIsDoubleQuoted});current="",quoted=!1,quote=null,pipeIsDoubleQuoted=!0};for(let index=0;index<inner.length;index+=1){let ch=inner[index];if(quote===null){if(/\s/.test(ch)){flush();continue}if(ch==="'"||ch==='"'){quoted=!0,quote=ch;continue}if(ch===";"||ch==="<"||ch===">"||ch==="`"||ch==="|")return{unsafe:!0,reason:"compound-syntax"};if(ch==="$"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};if(ch==="@"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};current+=ch;continue}if(quote==="'"){if(ch==="'"){quote=null;continue}if(ch==="|")pipeIsDoubleQuoted=!1;current+=ch;continue}if(ch==='"'){quote=null;continue}if(ch==="\\"&&inner[index+1]==='"')return{unsafe:!0,reason:"ambiguous-escaped-quote"};if(ch==="`")return{unsafe:!0,reason:"command-substitution"};if(ch==="$"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};if(ch==="@"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};current+=ch}if(quote!==null)return{unsafe:!0,reason:"unmatched-quote"};flush();let pipeTokens=tokens.filter((token)=>token.value.includes("|"));if(pipeTokens.length===0)return{unsafe:!1,reason:null};if(pipeTokens.length!==1||!pipeTokens[0].quoted||!pipeTokens[0].pipeIsDoubleQuoted)return{unsafe:!0,reason:"gh-api-jq-pipe"};let quotedPipeToken=pipeTokens[0];if(!/^gh\s+api(?:\s|$)/i.test(compact))return{unsafe:!0,reason:"gh-api-jq-pipe"};for(let index=0;index<tokens.length;index+=1)if(tokens[index].value==="--jq"&&tokens[index+1]===quotedPipeToken)return{unsafe:!1,reason:null};return{unsafe:!0,reason:"gh-api-jq-pipe"}}function hasUnsafeShellControlSyntax(command){return classifyPrWorkflowShellSyntax(command).unsafe}function describeShellSyntaxViolation(command){let verdict=classifyPrWorkflowShellSyntax(command);if(!verdict.unsafe)return null;switch(verdict.reason){case"unmatched-quote":return"Reason: unmatched quote in the shell command. Close the quote and retry with a single read-only command.";case"ambiguous-escaped-quote":return"Reason: backslash- or caret-escaped double quotes are ambiguous across cmd.exe, PowerShell, and POSIX shells. Use a jq filter that needs no nested double quotes, or use the bounded gh_evidence tool.";case"command-substitution":return"Reason: command-substitution syntax ($() or @()) is not allowed in this read-only gate.";case"gh-api-jq-pipe":return"Reason: literal `|` is only allowed inside a double-quoted `gh api --jq` value; single quotes do not protect pipes under cmd.exe, and every other shape is treated as compound shell syntax.";default:return"Reason: compound-syntax (;, &&, |, <, >, backtick, or $()/@()). Run ONE command per call; a single leading `cd <dir> &&` and a trailing `2>&1` are tolerated for reads only."}}function isSafeStandaloneGitCommit(command){if(hasUnsafeShellControlSyntax(command))return!1;if(/(?:^|\s)--(?:allow-empty|amend)(?:\s|=|$)/i.test(command))return!1;return/^[Gg][Ii][Tt](?:\s+-C(?:=|\s+)(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>`]+))?\s+commit(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s;&|<>`]+))*\s*$/.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|--version|version)(?:\s|$)/i.test(gitArgs))return!0;if(isAllowedReadOnlyGitBranchListing(gitArgs))return!0;if(isAllowedReadOnlyGitStashListing(gitArgs))return!0;if(isAllowedReadOnlyGitWorktreeListing(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 isAllowedReadOnlyGitBranchListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===0||tokens[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:--list|--contains|--merged|--no-merged|--points-at)$/i.test(token)){listingSelectorInEffect=!0;continue}if(/^(?:-a|--all|-r|--remotes|-v|-vv|--verbose|--show-current|--color|--no-color|--column|--no-column|-i|--ignore-case)$/i.test(token)||/^--(?:sort|format|color)=/i.test(token))continue;if(token.startsWith("-"))return!1;if(!listingSelectorInEffect)return!1}return!0}function isAllowedReadOnlyGitStashListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="stash")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--oneline|--patch|-p|--stat|--color|--no-color)$/i.test(token))continue;if(/^--(?:format|pretty)=/i.test(token))continue;return!1}return!0}function isAllowedReadOnlyGitWorktreeListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="worktree")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--verbose|--porcelain|-z)$/i.test(token))continue;return!1}return!0}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+--version$/i.test(command)||/^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 resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest for pr_head_sha "${state.prHeadSha}"; ${describePrWorkflowRevisionDigestFailure(resolved)}`);return resolved.digest}function describePrWorkflowRevisionDigestFailure(failure){let detail=failure.detail?` (${failure.detail})`:"";switch(failure.reason){case"file-cap":return`the changed-file snapshot exceeded REVISION_MAX_FILES${detail}. Reduce the changed-path count (commit or stash generated/vendored output) before retrying`;case"byte-cap":return`the changed-file snapshot exceeded REVISION_MAX_TOTAL_BYTES${detail}. Reduce the changed content size before retrying`;case"buffer-truncated":return`a bounded git enumeration exceeded GIT_SNAPSHOT_MAX_BUFFER${detail}. The changed-path list is too large to enumerate`;case"timeout":return`a bounded git enumeration timed out${detail}. Retry once the working tree is quiescent`;case"git-failed":return`a bounded git enumeration failed${detail}. Verify the checkout is a healthy Git worktree at the recorded head`;case"containment":return`git reported a changed path outside the project root${detail}. Nothing outside the project root may be hashed`;case"read-failed":return`a changed path could not be read${detail}. Resolve the filesystem error before retrying`;default:return`an injected revision-digest seam returned no digest${detail}; production names one of REVISION_MAX_FILES / REVISION_MAX_TOTAL_BYTES / GIT_SNAPSHOT_MAX_BUFFER, a bounded git enumeration timeout, or a read failure`}}async function resolvePrWorkflowRevisionDigestForGate(directory,baseHeadSha){if(_test_exports.resolvePrWorkflowRevisionDigestDetailed!==resolvePrWorkflowRevisionDigestDetailed)return _test_exports.resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);if(_test_exports.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest){let digest2=_test_exports.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return digest2?{ok:!0,digest:digest2}:{ok:!1,reason:"seam-unavailable"}}return resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha)}async function createPrReviewGateContext(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_REVIEW revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_REVIEW could not compute a bounded current-revision digest for pr_head_sha "${state.prHeadSha}"; ${describePrWorkflowRevisionDigestFailure(resolved)}`);return{revisionDigest:resolved.digest}}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 sameStringSet(left,right){let leftSet=new Set(left),rightSet=new Set(right);return leftSet.size===rightSet.size&&[...leftSet].every((v)=>rightSet.has(v))}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,ctx){if(ctx.candidateInventory)return ctx.candidateInventory;let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map,reversedBaseBatches=[...state.prReviewBaseDispatches??[]].reverse(),successfulByBaseBatchId=new Map;for(let batch of reversedBaseBatches)successfulByBaseBatchId.set(batch.batchId,successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest));let laneClassPasses=(state.prReviewDepthTier??"L")==="L"?[(ownedCount)=>ownedCount===1,(ownedCount)=>ownedCount!==1]:[()=>!0];for(let laneIsInClass of laneClassPasses)for(let batch of reversedBaseBatches){let successful=successfulByBaseBatchId.get(batch.batchId)??new Set;for(let lane of batch.lanes){let ownedDimensions=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!laneIsInClass(ownedDimensions.length))continue;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,!0,new Set,ctx.revisionDigest);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)}let degradedSourceKeys=new Set;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 receipt;try{receipt=parsePrReviewTriggerReceipt(triggerArtifact)}catch(error49){throw Error(`BLOCKED: PR_REVIEW trigger evaluation is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}for(let row of receipt.matchedRows)sources.push({batchId:row.source_batch_id,laneId:row.source_lane_id,mode:"swarm-pr-review:micro",workflowLane:row.trigger_id});for(let degradation of receipt.coverageDegradations)degradedSourceKeys.add(`${degradation.source_batch_id}\x00${degradation.source_lane_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.workspace?.prHeadSha!==state.prHeadSha||record2.workspace?.gitHead!==state.prHeadSha)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,ctx.revisionDigest,recordOwnedLanes))continue;if(source.workflowLane&&(!recordOwnedLanes?.includes(source.workflowLane)||!prReviewDiscoveryArtifactCoversLane(artifact.text,source.workflowLane,recordOwnedLanes,source.mode)))continue;resolvedArtifact=!0;let laneKey=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey))extractedLaneKeys.add(laneKey),candidateIds.push(...extractCandidateIds(artifact.text,resolvePrReviewRowFamily(source.workflowLane,source.mode),source.creditedLanes))}if(source.mode==="swarm-pr-review:micro"&&!resolvedArtifact){if(degradedSourceKeys.has(`${source.batchId}\x00${source.laneId}`))continue;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"),ctx.candidateInventory=candidateIds.length>0?candidateIds.sort():["CLEAN-REVIEW"],ctx.candidateInventory}function appendBoundedCandidateIssue(issues,message){if(issues.length<MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1){issues.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return}if(issues.length===MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1)issues.push("additional malformed candidate diagnostics omitted")}function resolvePrReviewRowFamily(workflowLane,mode){if(mode==="swarm-pr-review:base")return"base_explorer";if(mode==="swarm-pr-review:micro"||mode==="swarm-pr-review:council")return"micro_lane";return workflowLane!==void 0&&PR_REVIEW_BASE_DIMENSION_IDS.includes(workflowLane)?"base_explorer":"micro_lane"}function parseCanonicalCandidateRows(text,fallbackFamily){let rows=[],issues=[],headerFamily=null;for(let[index,line]of normalizeCandidateArtifact(text,fallbackFamily).text.split(/\r?\n/).entries()){let fields=splitPipeFields(line).map((field)=>field.trim()),detectedHeaderFamily=candidateHeaderFamily(fields);if(detectedHeaderFamily){headerFamily=detectedHeaderFamily;continue}let explicitMarker=fields[0]==="[CANDIDATE]",markerlessRow=headerFamily!==null&&Boolean(fields[0])&&!fields[0].startsWith("[");if(!explicitMarker&&!markerlessRow)continue;if(explicitMarker&&headerFamily===null){appendBoundedCandidateIssue(issues,`row ${index+1} field header: candidate output must begin with one exact canonical base or micro [CANDIDATE] header`);continue}let family=headerFamily??fallbackFamily,candidateFields=explicitMarker?fields.slice(1):fields,analysis=analyzeCandidateFields(candidateFields,family);if(!analysis.valid){for(let issue2 of analysis.issues)appendBoundedCandidateIssue(issues,`row ${index+1} field ${issue2.field}: ${issue2.message}`);continue}if(!analysis.candidateId||!analysis.workflowLane)continue;rows.push({candidateId:analysis.candidateId,workflowLane:analysis.workflowLane,evidence:candidateFields.slice(2).join("\x00"),lineNumber:index+1})}return{rows,issues}}function extractCandidateIds(text,fallbackFamily,scopeToLanes){let inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);return parseCanonicalCandidateRows(text,fallbackFamily).rows.filter((row)=>inScope(row.workflowLane)).map((row)=>row.candidateId)}function appendCompositionDiagnostic(diagnostics,message){if(diagnostics.length>=MAX_COMPOSITION_DIAGNOSTICS)return;diagnostics.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS))}function prReviewPhaseWindow(state,phase){let all=state.prReviewValidationBatches??[];if(phase==="critic")return all.filter((batch)=>batch.phase==="critic");let latestCouncilIndex=-1;for(let index=0;index<all.length;index++)if(all[index]?.phase==="council")latestCouncilIndex=index;return(latestCouncilIndex>=0?all.slice(latestCouncilIndex+1):all).filter((batch)=>batch.phase==="reviewer")}function reviewerSubagentSessionIds(directory,state){let forbidden=new Set(state.prReviewRetiredReviewerSessionIds??[]);for(let reviewerBatch of(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer"))for(let record2 of findByBatchId(directory,reviewerBatch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)forbidden.add(subagentSessionId)}return forbidden}function batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){let coherence=state.prReviewBatchCoherence?.[batch.batchId];if(coherence)return phase==="critic"||sameStringSet(coherence.validatedInventory,requiredInventory);let declaredItems=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]);if(!sameStringSet(declaredItems,requiredInventory))return!1;let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${phase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds,ctx.revisionDigest,void 0,reviewerClaims);return successful.size===batch.lanes.length&&batch.lanes.every((lane)=>successful.has(lane.workflowLane))}function composePrReviewPhaseVerdicts(directory,state,phase,ctx,exhaustive=!1){let memoized=phase==="reviewer"?ctx.reviewer:ctx.critic;if(memoized&&!exhaustive)return memoized;let requiredInventory=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state,ctx):derivePrReviewCriticInventory(directory,state,ctx),reviewerClaims=phase==="critic"?authoritativeReviewerClaims(directory,state,ctx):void 0,forbiddenSubagentSessionIds=phase==="critic"?reviewerSubagentSessionIds(directory,state):new Set,expectedMode=`swarm-pr-review:${phase}`,window2=prReviewPhaseWindow(state,phase),requiredSet=new Set(requiredInventory),claims=new Map,contributingBatchIds=[],diagnostics=[],satisfiedObligations=new Set,scannedBatches=[];for(let batch of[...window2].reverse()){if(scannedBatches.push(batch),!batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx)){appendCompositionDiagnostic(diagnostics,`${phase} batch "${batch.batchId}" was validated against a different inventory or is not wholly successful legacy state; it contributes no claims`);continue}let coherence=state.prReviewBatchCoherence?.[batch.batchId],contributed=!1;for(let qualified of recordsPassingBatchIntegrity(directory,state,batch.batchId,batch.lanes,expectedMode,batch.validatedAt,!0,forbiddenSubagentSessionIds)){let artifact=loadArtifactPassingLaneIntegrity(directory,state,qualified.record,expectedMode,qualified.expectedWorkflowLane,ctx.revisionDigest);if(!artifact)continue;let declaredItems=qualified.expectedLane.reviewItemIds??[],parsed=parseLaneItemVerdicts(artifact.text,declaredItems,phase,reviewerClaims);if(declaredItems.length>0&&parsed.size===declaredItems.length)satisfiedObligations.add(qualified.expectedWorkflowLane);for(let[itemId,verdict]of parsed){if(!requiredSet.has(itemId)||claims.has(itemId))continue;if(coherence&&!coherence.validatedInventory.includes(itemId))continue;if(phase==="critic"&&coherence&&!criticClaimIsBoundToCurrentReviewerRow(coherence,itemId,reviewerClaims))continue;claims.set(itemId,{batchId:batch.batchId,laneId:qualified.expectedLane.laneId,workflowLane:qualified.expectedWorkflowLane,...verdict}),contributed=!0}}if(contributed)contributingBatchIds.push(batch.batchId);if(!exhaustive&&claims.size===requiredSet.size)break}for(let obligation of new Set(scannedBatches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane)))){if(satisfiedObligations.has(obligation))continue;appendCompositionDiagnostic(diagnostics,`declared ${phase} lane "${obligation}" produced no successful exact artifact`)}let composition={claims,requiredInventory,unclaimed:requiredInventory.filter((itemId)=>!claims.has(itemId)),contributingBatchIds,diagnostics};if(!exhaustive)if(phase==="reviewer")ctx.reviewer=composition;else ctx.critic=composition;return composition}function criticClaimIsBoundToCurrentReviewerRow(coherence,itemId,reviewerClaims){let bound=coherence.reviewerItemBindings?.[itemId],current=reviewerClaims?.get(itemId)?.rowDigest;return Boolean(bound&¤t&&bound===current)}function authoritativeReviewerClaims(directory,state,ctx){let composed=composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx);return composed.unclaimed.length===0?composed.claims:new Map}function criticReviewerItemBindings(directory,state,lanes,ctx){let reviewerClaims=authoritativeReviewerClaims(directory,state,ctx),bindings={};for(let itemId of lanes.flatMap((lane)=>lane.reviewItemIds??[])){let rowDigest=reviewerClaims.get(itemId)?.rowDigest;if(!rowDigest)throw Error(`BLOCKED: PR_REVIEW critic dispatch cannot bind item "${itemId}" to an authoritative reviewer verdict row`);bindings[itemId]=rowDigest}return bindings}function derivePrReviewCriticInventory(directory,state,ctx){return[...authoritativeReviewerVerdictsForGate(directory,state,ctx,"derivePrReviewCriticInventory").entries()].filter(([,verdict])=>verdict.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(verdict.severity)).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state,ctx){let composed=composePrReviewPhaseVerdicts(directory,state,"critic",ctx);if(composed.unclaimed.length>0)return new Map;return new Map([...composed.claims].map(([itemId,claim])=>[itemId,{status:claim.classification,severity:claim.severity}]))}function deriveLatestPrReviewReviewerVerdicts(directory,state,ctx){return new Map([...authoritativeReviewerClaims(directory,state,ctx)].map(([itemId,claim])=>[itemId,{classification:claim.classification,severity:claim.severity}]))}function assertSettledPhaseHasAuthoritativeVerdicts(phase,composed,authoritative,origin){if(composed.unclaimed.length>0)return;if(composed.requiredInventory.length===0)return;let missing=composed.requiredInventory.filter((itemId)=>!authoritative.has(itemId));if(missing.length===0)return;let named=missing.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=missing.length-named.length;throw Error(`BLOCKED: PR_REVIEW internal invariant violated at ${origin}: the ${phase} phase settled over ${composed.requiredInventory.length} required item(s), but its authoritative ${phase} verdict map is `+(authoritative.size===0?"EMPTY":`PARTIAL (${authoritative.size} of ${composed.requiredInventory.length} items)`)+" after successful settlement"+(phase==="reviewer"?"; an empty or partial reviewer verdict map empties the critic inventory, which silently skips the critic-coverage gate and lets CONFIRMED CRITICAL/HIGH findings ship unchallenged":"; an empty or partial critic verdict map silently drops challenges the gate already accepted")+`; missing ${phase} verdicts for: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:""))}function authoritativeReviewerVerdictsForGate(directory,state,ctx,origin){let verdicts=deriveLatestPrReviewReviewerVerdicts(directory,state,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("reviewer",composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx),verdicts,origin),verdicts}function authoritativeCriticVerdictsForGate(directory,state,ctx,origin){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("critic",composePrReviewPhaseVerdicts(directory,state,"critic",ctx),verdicts,origin),verdicts}function derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,origin){let reviewer=composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx);if(reviewer.unclaimed.length>0){let named=reviewer.unclaimed.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=reviewer.unclaimed.length-named.length;throw Error(`BLOCKED: PR_REVIEW internal invariant violated at ${origin}: the critic-coverage decision requires a settled reviewer phase, but ${reviewer.unclaimed.length} reviewer item(s) lack an authenticated verdict; an unsettled reviewer phase derives an empty critic inventory, which would skip critic coverage instead of demanding it; unsettled reviewer items: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:""))}return derivePrReviewCriticInventory(directory,state,ctx)}function boundedLaneValidationValue(value){let rendered;try{rendered=typeof value==="string"?value:JSON.stringify(value)}catch{rendered=String(value)}let sanitized=[...rendered??String(value)].map((character)=>{let code=character.charCodeAt(0);return code<=31||code===127?" ":character}).join("").trim();return sanitized.length<=MAX_LANE_VALIDATION_VALUE_CHARS?sanitized:`${sanitized.slice(0,MAX_LANE_VALIDATION_VALUE_CHARS-1)}…`}function failedLaneValidation(predicate,expected,actual){return{ok:!1,failure:{predicate,expected:boundedLaneValidationValue(expected),actual:boundedLaneValidationValue(actual)}}}function formatPrReviewLaneValidationFailure(failure){return`predicate=${failure.predicate} expected=${JSON.stringify(failure.expected)} actual=${JSON.stringify(failure.actual)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS)}function analyzeLaneRecordResultIntegrity(args2){let{record:record2,result,expected}=args2;if(expected.checkWorkflowLane&&record2.workflowLane!==expected.workflowLane)return failedLaneValidation("record.workflow_lane",expected.workflowLane,record2.workflowLane??"(missing)");if(expected.checkWorkflowLane&&!ownedLaneSetsEqual(record2.ownedWorkflowLanes,expected.ownedWorkflowLanes))return failedLaneValidation("record.owned_workflow_lanes",expected.ownedWorkflowLanes,record2.ownedWorkflowLanes??(record2.workflowLane?[record2.workflowLane]:[]));if(record2.mode!==expected.mode)return failedLaneValidation("record.mode",expected.mode,record2.mode??"(missing)");if(record2.workspace?.prHeadSha!==expected.prHeadSha)return failedLaneValidation("record.pr_head_sha",expected.prHeadSha,record2.workspace?.prHeadSha??"(missing)");if(record2.workspace?.gitHead!==expected.gitHead)return failedLaneValidation("record.git_head",expected.gitHead,record2.workspace?.gitHead??"(missing)");if(args2.requireCompleted&&record2.status!=="completed")return failedLaneValidation("record.status","completed",record2.status);if(result?.outputDegraded===!0)return failedLaneValidation("result.output_degraded","not true",!0);if(result?.transcriptIncomplete===!0)return failedLaneValidation("result.transcript_incomplete","not true",!0);if(result?.truncated===!0)return failedLaneValidation("result.truncated","not true",!0);if((result?.chars??0)<=0)return failedLaneValidation("result.chars","greater than 0",result?.chars??0);if(!result?.digest?.trim())return failedLaneValidation("result.digest","non-empty digest",result?.digest??"(missing)");if(!result?.outputRef?.trim())return failedLaneValidation("result.output_ref","non-empty output ref",result?.outputRef??"(missing)");return{ok:!0}}function analyzePrReviewBatchRecordIntegrity(args2){let validatedAtMs=Date.parse(args2.validatedAt),expectedByLaneId=new Map(args2.expectedLanes.map((lane)=>[lane.laneId,lane])),batchFailure=!Number.isFinite(validatedAtMs)?failedLaneValidation("batch.validated_at","valid ISO timestamp",args2.validatedAt):expectedByLaneId.size!==args2.expectedLanes.length?failedLaneValidation("batch.expected_lane_unique","unique expected lane ids",args2.expectedLanes.map((lane)=>lane.laneId)):null,relevantRecords=args2.records.filter((record2)=>record2.laneId&&expectedByLaneId.has(record2.laneId)),recordsByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record2 of relevantRecords){let laneRecords=recordsByLaneId.get(record2.laneId)??[];laneRecords.push(record2),recordsByLaneId.set(record2.laneId,laneRecords);let sessionId=record2.subagentSessionId?.trim();if(sessionId)recordCountBySubagentSessionId.set(sessionId,(recordCountBySubagentSessionId.get(sessionId)??0)+1)}return args2.expectedLanes.map((expectedLane)=>{let expectedWorkflowLane=expectedLane.workflowLane,expectedOwnedLanes=expectedLane.ownedWorkflowLanes?.length?expectedLane.ownedWorkflowLanes:[expectedWorkflowLane],failed=(failure)=>({ok:!1,expectedLane,expectedWorkflowLane,expectedOwnedLanes,failure});if(batchFailure&&!batchFailure.ok)return failed(batchFailure.failure);let laneRecords=recordsByLaneId.get(expectedLane.laneId)??[];if(laneRecords.length===0)return failed(failedLaneValidation("record.missing","exactly one record",0).failure);if(laneRecords.length!==1)return failed(failedLaneValidation("record.duplicate_lane","exactly one record",laneRecords.length).failure);let record2=laneRecords[0],subagentSessionId=record2.subagentSessionId?.trim();if(!subagentSessionId)return failed(failedLaneValidation("record.subagent_session_id","non-empty child session id",record2.subagentSessionId??"(missing)").failure);if(recordCountBySubagentSessionId.get(subagentSessionId)!==1)return failed(failedLaneValidation("record.duplicate_subagent_session_id","one record per child session",recordCountBySubagentSessionId.get(subagentSessionId)).failure);if(args2.forbiddenSubagentSessionIds.has(subagentSessionId))return failed(failedLaneValidation("record.forbidden_subagent_session_id","child session not reused from a forbidden phase",subagentSessionId).failure);if(record2.createdAt<validatedAtMs)return failed(failedLaneValidation("record.created_at",`at or after ${args2.validatedAt}`,new Date(record2.createdAt).toISOString()).failure);let recordIntegrity=analyzeLaneRecordResultIntegrity({record:record2,result:record2.result,expected:{mode:args2.expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes:expectedOwnedLanes,prHeadSha:args2.expectedPrHeadSha??record2.workspace?.prHeadSha??"",gitHead:args2.expectedPrHeadSha??record2.workspace?.gitHead??"",checkWorkflowLane:args2.checkWorkflowLane},requireCompleted:!0});if(!recordIntegrity.ok)return failed(recordIntegrity.failure);return{ok:!0,record:record2,expectedLane,expectedWorkflowLane,expectedOwnedLanes}})}function recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,diagnostics){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}),analyses=analyzePrReviewBatchRecordIntegrity({batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,records,expectedPrHeadSha:state.prHeadSha});for(let analysis of analyses)if(!analysis.ok&&diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${batchId} lane=${analysis.expectedLane.laneId} workflow_lane=${analysis.expectedWorkflowLane}: ${formatPrReviewLaneValidationFailure(analysis.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return analyses.filter((analysis)=>analysis.ok)}function successfulObligationsFromExactBatch(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest,diagnostics,reviewerClaims){let successful=new Set;for(let qualified of recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics))if(workflowArtifactHasContractMarker(directory,state,qualified.record,expectedMode,qualified.expectedWorkflowLane,qualified.expectedLane.reviewItemIds,expectedRevisionDigest,qualified.expectedOwnedLanes,diagnostics,reviewerClaims))for(let obligation of qualified.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 analyzeLaneArtifactIntegrity(args2){let{record:record2,result,artifact,expected}=args2;if(!artifact)return failedLaneValidation("artifact.readable","readable stored artifact","missing or invalid");if(artifact.ref!==result.outputRef?.trim())return failedLaneValidation("artifact.ref",result.outputRef?.trim()??"(missing)",artifact.ref);if(artifact.batchId!==record2.batchId)return failedLaneValidation("artifact.batch_id",record2.batchId??"(missing)",artifact.batchId);if(artifact.laneId!==record2.laneId)return failedLaneValidation("artifact.lane_id",record2.laneId??"(missing)",artifact.laneId);if(artifact.mode!==expected.mode)return failedLaneValidation("artifact.mode",expected.mode,artifact.mode??"(missing)");if(artifact.sessionId!==record2.subagentSessionId)return failedLaneValidation("artifact.session_id",record2.subagentSessionId,artifact.sessionId??"(missing)");if(artifact.parentSessionId!==record2.parentSessionId)return failedLaneValidation("artifact.parent_session_id",record2.parentSessionId,artifact.parentSessionId??"(missing)");if(artifact.agent!==record2.swarmPrefixedAgent)return failedLaneValidation("artifact.agent",record2.swarmPrefixedAgent,artifact.agent);if(artifact.role!==record2.normalizedAgent)return failedLaneValidation("artifact.role",record2.normalizedAgent,artifact.role);if(artifact.source!=="collect_lane_results")return failedLaneValidation("artifact.source","collect_lane_results",artifact.source);if(artifact.workflowLane!==record2.workflowLane)return failedLaneValidation("artifact.workflow_lane_record",record2.workflowLane??"(missing)",artifact.workflowLane??"(missing)");if(artifact.workflowLane!==expected.workflowLane)return failedLaneValidation("artifact.workflow_lane_expected",expected.workflowLane,artifact.workflowLane??"(missing)");if(artifact.prHeadSha!==expected.prHeadSha)return failedLaneValidation("artifact.pr_head_sha",expected.prHeadSha,artifact.prHeadSha??"(missing)");if(artifact.gitHead!==expected.gitHead)return failedLaneValidation("artifact.git_head",expected.gitHead,artifact.gitHead??"(missing)");if(artifact.revisionDigest!==expected.revisionDigest)return failedLaneValidation("artifact.revision_digest",expected.revisionDigest,artifact.revisionDigest??"(missing)");if(expected.reviewScope!==void 0&&record2.workspace?.scope!==expected.reviewScope)return failedLaneValidation("record.scope",expected.reviewScope,record2.workspace?.scope??"(missing)");if(expected.reviewScope!==void 0&&artifact.scope!==expected.reviewScope)return failedLaneValidation("artifact.scope",expected.reviewScope,artifact.scope??"(missing)");if(artifact.digest!==result.digest)return failedLaneValidation("artifact.digest",result.digest,artifact.digest);if(artifact.chars!==result.chars)return failedLaneValidation("artifact.chars",result.chars,artifact.chars);return{ok:!0}}function loadArtifactPassingLaneIntegrity(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){let ref=record2.result?.outputRef?.trim();if(!ref)return null;let artifact=readLaneOutput(directory,ref)?.artifact??null,expectedReviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0,integrity=analyzeLaneArtifactIntegrity({record:record2,result:record2.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,prHeadSha:record2.workspace?.prHeadSha??"",gitHead:record2.workspace?.gitHead??"",revisionDigest:expectedRevisionDigest,reviewScope:expectedReviewScope}});if(!integrity.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(integrity.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return null}return artifact}function workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes,diagnostics,reviewerClaims){let ref=record2.result?.outputRef?.trim(),artifact=expectedRevisionDigest?loadArtifactPassingLaneIntegrity(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics):null;if(!artifact)return!1;if(expectedMode==="swarm-pr-review:reviewer"||expectedMode==="swarm-pr-review:critic"){let phase=expectedMode==="swarm-pr-review:reviewer"?"reviewer":"critic",parsed=parseLaneItemVerdicts(artifact.text,reviewItemIds??[],phase,reviewerClaims);return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>parsed.has(itemId)))}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])));if(expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"){let reviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0,validation=validatePrReviewDiscoveryLaneCompletion({record:record2,result:record2.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes,prHeadSha:state.prHeadSha??"",gitHead:state.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",reviewScope}});if(!validation.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(validation.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return!1}return!0}let coveredLanes=ownedWorkflowLanes?.length?ownedWorkflowLanes:[expectedWorkflowLane],coverageAnalyses=coveredLanes.map((coveredLane)=>({coveredLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,coveredLane,coveredLanes,expectedMode)}));if(coverageAnalyses.some(({analysis})=>!analysis.covered)){for(let{coveredLane,analysis}of coverageAnalyses){if(analysis.covered||analysis.issues.length===0)continue;if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS){let diagnostic=`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${coveredLane} output_ref=${ref} digest=${record2.result?.digest??"(missing)"}: ${analysis.issues.join("; ")}`;diagnostics.push(diagnostic.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS))}}return!1}if(coveredLanes.length>1){let seenEvidence=new Map;for(let coveredLane of coveredLanes){let evidence2=extractLaneCoverageEvidenceText(artifact.text,coveredLane,coveredLanes,expectedMode);if(evidence2===null)continue;if(seenEvidence.get(evidence2))return!1;seenEvidence.set(evidence2,coveredLane)}}return!0}function analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){let fallbackFamily=resolvePrReviewRowFamily(expectedWorkflowLane,mode),issues=[],normalized=normalizeCandidateArtifact(text,fallbackFamily),canonicalText=normalized.text,repairKinds=normalized.repairKinds,salvaged=repairKinds.length>0,header=selectCandidateHeader(canonicalText.split(/\r?\n/));if(header===null||!header.markerBearing||header.family!==fallbackFamily)return appendBoundedCandidateIssue(issues,`field header: expected one exact canonical ${fallbackFamily} [CANDIDATE] header before discovery rows`),{covered:!1,evidence:null,issues,salvaged,repairKinds,failurePredicate:"discovery.header"};let parsed=parseCandidates({output_ref:"pr-workflow:discovery-artifact",batchId:"pr-workflow",laneId:expectedWorkflowLane,agent:"explorer",role:"explorer",digest:"0".repeat(64),text:canonicalText,artifact_status:"ok",source:"collect_lane_results",produced_at:"1970-01-01T00:00:00.000Z"},{accept_partial:!1,accept_degraded:!1,degraded:!1,row_format_version:1,producer:"swarm-pr-review",expected_family:fallbackFamily,...fallbackFamily==="base_explorer"?{expected_lane:expectedWorkflowLane,expected_lanes:[...ownedWorkflowLanes]}:{expected_micro_lane:expectedWorkflowLane,expected_micro_lanes:[...ownedWorkflowLanes]}});if(parsed.error)appendBoundedCandidateIssue(issues,parsed.error);for(let detail of parsed.diagnostics.parse_error_details)appendBoundedCandidateIssue(issues,`row ${detail.row_index+1} field ${detail.field}: ${detail.message}`);let hasParseFailure=Boolean(parsed.error)||parsed.diagnostics.parse_error_details.length>0,extractedCandidateIds=parseCanonicalCandidateRows(canonicalText,fallbackFamily).rows.map((row)=>row.candidateId);if(new Set(extractedCandidateIds).size!==extractedCandidateIds.length)return{covered:!1,evidence:null,issues,salvaged,repairKinds,failurePredicate:"discovery.row"};let matchingCandidate=parsed.candidates.find((candidate)=>(candidate.lane??candidate.micro_lane)===expectedWorkflowLane);if(matchingCandidate)return{covered:!0,evidence:[matchingCandidate.severity,matchingCandidate.category,matchingCandidate.file_line,matchingCandidate.claim,matchingCandidate.evidence_summary,matchingCandidate.impact_context??matchingCandidate.invariant_violated,matchingCandidate.confidence].join("\x00"),issues,salvaged,repairKinds};let clean=parsed.clean_attestation;if(clean&&(clean.row_format_family==="base_explorer"?clean.lane:clean.micro_lane)===expectedWorkflowLane)return{covered:!0,evidence:`${clean.coverage_scope}\x00${clean.evidence}`,issues,salvaged,repairKinds};return{covered:!1,evidence:null,issues,salvaged,repairKinds,failurePredicate:hasParseFailure?"discovery.row":"discovery.coverage"}}function validatePrReviewDiscoveryLaneCompletion(input){let ownedWorkflowLanes=input.expected.ownedWorkflowLanes?.length?[...input.expected.ownedWorkflowLanes]:[input.expected.workflowLane],recordIntegrity=analyzeLaneRecordResultIntegrity({record:input.record,result:input.result,expected:{mode:input.expected.mode,workflowLane:input.expected.workflowLane,ownedWorkflowLanes,prHeadSha:input.expected.prHeadSha,gitHead:input.expected.gitHead,checkWorkflowLane:input.expected.checkWorkflowLane??!0},requireCompleted:!1});if(!recordIntegrity.ok)return recordIntegrity;let artifactIntegrity=analyzeLaneArtifactIntegrity({record:input.record,result:input.result,artifact:input.artifact,expected:{mode:input.expected.mode,workflowLane:input.expected.workflowLane,prHeadSha:input.expected.prHeadSha,gitHead:input.expected.gitHead,revisionDigest:input.expected.revisionDigest,reviewScope:input.expected.reviewScope}});if(!artifactIntegrity.ok)return artifactIntegrity;let artifact=input.artifact,analyses=ownedWorkflowLanes.map((workflowLane)=>({workflowLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,workflowLane,ownedWorkflowLanes,input.expected.mode)})),salvagedLanes=[];for(let{workflowLane,analysis}of analyses){if(!analysis.covered)continue;if(!analysis.salvaged&&analysis.issues.length===0)continue;salvagedLanes.push(workflowLane);let reason=analysis.repairKinds.length>0?`structural repairs applied: ${analysis.repairKinds.join(", ")}`:"one or more rows were dropped as malformed or out-of-ownership";warn(`[pr-workflow-gate] discovery artifact salvaged: batch=${input.record.batchId??"(missing)"} lane=${input.record.laneId??"(missing)"} workflow_lane=${workflowLane} — ${reason}; retained coverage from the valid rows. Dropped-row diagnostics: ${analysis.issues.join("; ")||"(none)"}`)}let failedCoverage=analyses.find(({analysis})=>!analysis.covered);if(failedCoverage)return failedLaneValidation(failedCoverage.analysis.failurePredicate??"discovery.coverage",`one valid ${input.expected.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane"} [CANDIDATE] row or [CLEAN] attestation for ${failedCoverage.workflowLane}`,failedCoverage.analysis.issues.join("; ")||"no matching lane row");if(ownedWorkflowLanes.length>1){let seenEvidence=new Map;for(let{workflowLane,analysis}of analyses){if(analysis.evidence===null)continue;let priorLane=seenEvidence.get(analysis.evidence);if(priorLane)return failedLaneValidation("discovery.duplicate_evidence","distinct evidence for every owned workflow lane",`${priorLane} and ${workflowLane} share evidence`);seenEvidence.set(analysis.evidence,workflowLane)}}return salvagedLanes.length>0?{ok:!0,salvaged:salvagedLanes}:{ok:!0}}function prReviewDiscoveryArtifactCoversLane(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes,mode).covered}function extractLaneCoverageEvidenceText(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes,mode).evidence}function parseReviewerVerdictFields(text,itemId){let rows=text.split(/\r?\n/).map((line)=>pipeFieldsCapped(line,10)).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 fields}function reviewerVerdictRowDigest(fields){return createHash8("sha256").update(fields.join("\x00")).digest("hex")}function parseLaneItemVerdicts(text,itemIds,phase,reviewerClaims){let parsed=new Map;for(let itemId of itemIds){if(phase==="reviewer"){let fields=parseReviewerVerdictFields(text,itemId);if(!fields)continue;parsed.set(itemId,{classification:fields[2],severity:fields[4],rowDigest:reviewerVerdictRowDigest(fields)});continue}let verdict=parseCriticVerdict(text,itemId,reviewerClaims?.get(itemId)?.severity);if(!verdict)continue;parsed.set(itemId,{classification:verdict.status,severity:verdict.severity})}return parsed}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=text.split(/\r?\n/).map((line)=>pipeFieldsCapped(line,6)).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((line)=>pipeFieldsCapped(line,4)).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 pipeFieldsCapped(line,expectedFieldCount){let fields=pipeFields(line);if(fields.length<=expectedFieldCount)return fields;let capped=[...fields.slice(0,expectedFieldCount-1),fields.slice(expectedFieldCount-1).join("|")];return warn(`[pr-workflow-gate] verdict row pipe tail-merge applied (expected ${expectedFieldCount} fields, received ${fields.length}); leading machine fields preserved, trailing prose fields merged: ${line.slice(0,120)}`),capped}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((line)=>pipeFieldsCapped(line,4)).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])})}function readSettledFeedbackClassifications(directory,state){let classifications=new Map;for(let record2 of state.prFeedbackVerifications??[])for(let ownership of record2.ownership){let ref=findByBatchId(directory,record2.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===ownership.laneId)?.result?.outputRef?.trim(),loaded=ref?readLaneOutput(directory,ref):null;if(!loaded)continue;for(let line of loaded.artifact.text.split(/\r?\n/)){let fields=pipeFieldsCapped(line,4);if(fields[0]!=="[FEEDBACK-VERIFIED]"||fields.length!==4||!fields.slice(1,4).every(Boolean)||!FEEDBACK_CLASSIFICATIONS.has(fields[2]))continue;if(!classifications.has(fields[1]))classifications.set(fields[1],fields[2])}}return classifications}async function persistState(directory,state){let validated=PrWorkflowGateStateSchema.parse(state);await withSessionStateMutation(directory,validated.sessionID,async()=>{let nextState=await writeStateWhileLocked(directory,validated);Object.assign(state,nextState)})}async function writeStateWhileLocked(directory,state,options={}){let validated=PrWorkflowGateStateSchema.parse(state),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");if(current?.workflowInstanceId&&validated.workflowInstanceId!==current.workflowInstanceId&&options.replaceWorkflowInstanceId!==current.workflowInstanceId)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");let nextState=PrWorkflowGateStateSchema.parse({...validated,revision:validated.revision+1}),filePath=workflowGateStatePath(directory,validated.sessionID);return await writeAtomicJson2(directory,filePath,nextState),rememberState(directory,nextState),nextState}function workflowCheckoutMutationLockRelativePath(){return path15.join(WORKFLOW_GATE_DIR,"checkout.lock")}function workflowCheckoutMutationLockPath(directory){return validateSwarmPath(directory,workflowCheckoutMutationLockRelativePath())}function openCheckoutLockFile(lockPath){return fsp3.open(lockPath,"wx")}function removeCheckoutLockFile(lockPath){return fsp3.rm(lockPath)}function checkoutMutationProjectKey(directory){return normalizeComparableFsPath(directory)}async function withCheckoutMutationDeadline(promise2,phase){let timeout;try{return await Promise.race([promise2,new Promise((resolve10)=>{timeout=setTimeout(()=>{resolve10({status:"timeout",error:new PrWorkflowCheckoutMutationTimeoutError(phase)})},_test_exports.checkoutMutationActionTimeoutMs)})])}finally{if(timeout)clearTimeout(timeout)}}async function withPrWorkflowCheckoutMutationLock(directory,action){let key=checkoutMutationProjectKey(directory),previous=pendingCheckoutMutationsByProject.get(key)??Promise.resolve(),release,current=new Promise((resolve10)=>{release=resolve10}),queued=previous.then(()=>current);pendingCheckoutMutationsByProject.set(key,queued);let previousResult=await withCheckoutMutationDeadline(previous.then(()=>({status:"ready"})),"queue");if(previousResult.status==="timeout")throw release(),queued.then(()=>{if(pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}),previousResult.error;let lock;try{lock=await acquireCheckoutMutationLock(directory)}catch(error49){if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key);throw error49}let actionOutcome=Promise.resolve().then(action).then((value)=>({status:"fulfilled",value}),(error49)=>({status:"rejected",error:error49})),outcome=await withCheckoutMutationDeadline(actionOutcome,"action");if(outcome.status==="timeout")throw actionOutcome.then(async()=>{try{await releaseCheckoutMutationLock(lock)}catch{}finally{if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}}),outcome.error;try{if(outcome.status==="rejected")throw outcome.error;return outcome.value}finally{try{await releaseCheckoutMutationLock(lock)}finally{if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}}}async function acquireCheckoutMutationLock(directory){let lockPath=workflowCheckoutMutationLockPath(directory),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await _test_exports.openCheckoutLock(lockPath),lock={ownerToken:randomUUID3(),pid:process.pid,createdAtMs:_test_exports.nowMs()},lockIdentity,writeError;try{let openedStat=await handle.stat({bigint:!0});lockIdentity={dev:openedStat.dev,ino:openedStat.ino},lockIdentity=await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow checkout mutation lock"),await _test_exports.beforeCheckoutLockWrite?.(),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError){if(lockIdentity)await removeCheckoutMutationLockByIdentity(directory,lockPath,lockIdentity,verifiedParent);throw writeError}return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedCheckoutMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow checkout mutation is being handled by another process; retry after that checkout settles")}async function releaseCheckoutMutationLock(lock){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++){try{if(await removeCheckoutMutationLockIfOwned(lock.path,lock.ownerToken)){completedCheckoutLockOwners.delete(lock.path);return}lastError=Error("PR workflow checkout mutation lock ownership changed before release")}catch(error49){lastError=error49}if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}throw rememberCompletedCheckoutLockOwner(lock.path,lock.ownerToken),lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock release failed")}async function reclaimAbandonedCheckoutMutationLock(lockPath){let lock=await readCheckoutMutationLock(lockPath);if(lock){if(lock.pid===process.pid&&completedCheckoutLockOwners.get(lockPath)===lock.ownerToken){let removed=await removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken);if(removed)completedCheckoutLockOwners.delete(lockPath);return removed}if(_test_exports.isProcessAlive(lock.pid))return!1;return removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp3.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp3.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readCheckoutMutationLock(lockPath){let raw;try{raw=await fsp3.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 removeCheckoutMutationLockIfOwned(lockPath,ownerToken){let lock=await readCheckoutMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await _test_exports.removeCheckoutLock(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}async function removeCheckoutMutationLockByIdentity(directory,lockPath,identity,verifiedParent){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await assertClosedSwarmFileIdentity(directory,lockPath,identity,verifiedParent,"PR workflow checkout mutation lock"),await _test_exports.removeCheckoutLock(lockPath);return}catch(error49){if(error49.code==="ENOENT")return;if(lastError=error49,attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock cleanup failed")}function rememberCompletedCheckoutLockOwner(lockPath,ownerToken){completedCheckoutLockOwners.delete(lockPath),completedCheckoutLockOwners.set(lockPath,ownerToken);while(completedCheckoutLockOwners.size>MAX_COMPLETED_CHECKOUT_LOCK_OWNERS){let oldest=completedCheckoutLockOwners.keys().next().value;if(oldest===void 0)break;completedCheckoutLockOwners.delete(oldest)}}async function withSessionStateMutation(directory,sessionID,action){let key=stateCacheKey(directory,sessionID),previous=pendingStateMutationsByProjectSession.get(key)??Promise.resolve(),release,current=new Promise((resolve10)=>{release=resolve10}),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),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await fsp3.open(lockPath,"wx"),lock={ownerToken:randomUUID3(),pid:process.pid,createdAtMs:_test_exports.nowMs()},writeError;try{await _test_exports.beforeSessionStateLockWrite?.(),await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow state mutation lock"),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError)throw await removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken),writeError;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 fsp3.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp3.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp3.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 fsp3.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);return readPrWorkflowGateStateFileFromDisk(filePath,sessionID)}async function readPrWorkflowGateStateFileFromDisk(filePath,stateLabel){let raw;try{raw=await fsp3.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 "${stateLabel}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(!parsed.success)throw Error(`BLOCKED: PR workflow gate state for session "${stateLabel}" 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=path15.normalize(path15.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 path15.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path15.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=createHash8("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 ensurePrWorkflowSafeParentDirectory(directory,filePath){let swarmRoot=path15.resolve(directory,".swarm"),parentPath=path15.dirname(path15.resolve(filePath)),relativeParent=path15.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path15.sep}`)||path15.isAbsolute(relativeParent))throw Error("BLOCKED: PR workflow atomic destination escapes the project .swarm directory");await fsp3.mkdir(swarmRoot,{recursive:!0});let currentPath=swarmRoot,currentIdentity=await assertSafeDirectory(currentPath,void 0);for(let segment of relativeParent.split(path15.sep).filter(Boolean)){let nextPath=path15.join(currentPath,segment);await _test_exports.beforeSafeDirectoryCreate?.(currentPath,nextPath),await assertSafeDirectory(currentPath,currentIdentity);try{await fsp3.mkdir(nextPath)}catch(error49){if(error49.code!=="EEXIST")throw error49}await assertSafeDirectory(currentPath,currentIdentity);let nextIdentity=await assertSafeDirectory(nextPath,void 0),[realCurrent,realNext]=await Promise.all([fsp3.realpath(currentPath),fsp3.realpath(nextPath)]);if(normalizeComparableFsPath(path15.dirname(realNext))!==normalizeComparableFsPath(realCurrent))throw Error("BLOCKED: PR workflow directory creation escaped the project .swarm tree");currentPath=nextPath,currentIdentity=nextIdentity}let realRoot=await fsp3.realpath(swarmRoot),realParent=await fsp3.realpath(parentPath),relativeRealParent=path15.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path15.sep}`)||path15.isAbsolute(relativeRealParent))throw Error("BLOCKED: PR workflow atomic parent escapes the project .swarm directory");return realParent}async function assertSafeDirectory(directoryPath,expectedIdentity){let stat6=await fsp3.lstat(directoryPath,{bigint:!0});if(stat6.isSymbolicLink()||!stat6.isDirectory()||expectedIdentity&&!sameBigIntFileIdentity(stat6,expectedIdentity))throw Error("BLOCKED: PR workflow .swarm path must be a real directory and must not change during the operation");return{dev:stat6.dev,ino:stat6.ino}}async function assertOpenedSwarmFileIdentity(directory,filePath,handle,expectedParent,label){let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile())throw Error(`BLOCKED: ${label} is not a file`);return await assertClosedSwarmFileIdentity(directory,filePath,openedStat,expectedParent,label),{dev:openedStat.dev,ino:openedStat.ino}}async function assertClosedSwarmFileIdentity(directory,filePath,expectedIdentity,expectedParent,label){if(!expectedIdentity)throw Error(`BLOCKED: ${label} has no identity`);let[stat6,realRoot,realFile,realParent]=await Promise.all([fsp3.lstat(filePath,{bigint:!0}),fsp3.realpath(path15.resolve(directory,".swarm")),fsp3.realpath(filePath),fsp3.realpath(path15.dirname(filePath))]),relativeFile=path15.relative(realRoot,realFile);if(stat6.isSymbolicLink()||!stat6.isFile()||!sameBigIntFileIdentity(stat6,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path15.sep}`)||path15.isAbsolute(relativeFile))throw Error(`BLOCKED: ${label} changed or escaped .swarm`)}async function writeAtomicJson2(directory,filePath,value){let safeParent=await ensurePrWorkflowSafeParentDirectory(directory,filePath),tempPath=`${filePath}.tmp.${process.pid}.${randomUUID3()}`,tempIdentity,lastError;try{let handle=await fsp3.open(tempPath,"wx");try{await _test_exports.beforeAtomicTempWrite?.(),tempIdentity=await assertOpenedSwarmFileIdentity(directory,tempPath,handle,safeParent,"PR workflow atomic temporary file"),await handle.writeFile(JSON.stringify(value,null,2),"utf-8"),await handle.sync()}finally{await handle.close()}await _test_exports.beforeAtomicRename?.(),await assertClosedSwarmFileIdentity(directory,tempPath,tempIdentity,safeParent,"PR workflow atomic temporary file");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;await assertClosedSwarmFileIdentity(directory,filePath,tempIdentity,safeParent,"PR workflow atomic destination file")}finally{try{await fsp3.rm(tempPath,{force:!0})}catch{}}}async function writePrWorkflowAtomicJson(directory,filePath,value){await writeAtomicJson2(directory,filePath,value)}function isoNow(){return new Date().toISOString()}function delay(ms){return new Promise((resolve10)=>setTimeout(resolve10,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_TIER_L_CONSOLIDATED_LANE_FLOOR,PR_REVIEW_MICRO_LANE_FLOORS,GATE_SCHEMA_VERSION=1,MAX_TRACKED_SESSIONS=200,MAX_WORKFLOW_BATCHES=128,MAX_RETIRED_REVIEWER_SESSION_IDS=1024,MAX_RETIRED_CONSOLIDATED_LANES=64,MAX_RETIRED_FEEDBACK_ITEM_OWNERS=4096,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,MAX_COMPLETED_CHECKOUT_LOCK_OWNERS=64,CHECKOUT_MUTATION_ACTION_TIMEOUT_MS=300000,MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES,MAX_CANDIDATE_ISSUES_PER_ARTIFACT=8,MAX_BASE_COVERAGE_DIAGNOSTICS=8,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS=1000,MAX_LANE_VALIDATION_VALUE_CHARS=240,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",WORKFLOW_GATE_DIR="pr-workflow-gates",trackedStatesByProjectSession,pendingStateMutationsByProjectSession,pendingCheckoutMutationsByProject,completedCheckoutLockOwners,PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrReviewValidationBatchRecordSchema,PrReviewBatchCoherenceRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowCheckoutRecoveryRecordSchema,PrFeedbackReviewHandoffRecordSchema,PrWorkflowGateStateSchema,TERMINAL_FAILED_DELEGATION_STATUSES,MAX_COVER_UNIVERSE_BITS=12,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN,PR_REVIEW_HANDOFF_MAX_BYTES=131072,PR_REVIEW_FINDINGS_MAX_BYTES=10485760,PrReviewFeedbackHandoffArtifactSchema,PrReviewFindingProjectionSchema,_test_exports,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,PR_WORKFLOW_CD_PREFIX_PATTERN,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,PR_WORKFLOW_MAX_CD_PREFIX_STRIPS=3,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN,MAX_COMPOSITION_DIAGNOSTICS=16,MAX_UNCLAIMED_ITEMS_IN_MESSAGE=50,REVIEWER_CLASSIFICATIONS,REVIEWER_EVIDENCE_TYPES,REVIEW_SEVERITIES,CRITIC_STATUSES,FEEDBACK_CLASSIFICATIONS,FEEDBACK_NO_CHANGE_CLASSIFICATIONS,PrWorkflowCheckoutMutationTimeoutError;var init_pr_workflow_gate=__esm(()=>{init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_pr_workflow_state();init_tool_metadata();init_logger();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=PR_REVIEW_REQUIRED_TRIGGER_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS={smallMaxChangedLines:100,smallMaxChangedFiles:5,mediumMaxChangedLines:1500,mediumMaxChangedFiles:50},PR_REVIEW_BASE_LANE_FLOORS={S:1,M:3,L:PR_REVIEW_BASE_DIMENSION_IDS.length},PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR=PR_REVIEW_BASE_LANE_FLOORS.M+1,PR_REVIEW_MICRO_LANE_FLOORS={S:1,M:6,L:PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length};MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES=MAX_TRACKED_SESSIONS*2+1,trackedStatesByProjectSession=new Map,pendingStateMutationsByProjectSession=new Map,pendingCheckoutMutationsByProject=new Map,completedCheckoutLockOwners=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),proofKind:exports_external.enum(["defect","metadata","source-proof","conflict","ci","user-decision"]).optional()}).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(),PrReviewBatchCoherenceRecordSchema=exports_external.object({validatedInventory:exports_external.array(exports_external.string().min(1)),reviewerItemBindings:exports_external.record(exports_external.string().min(1),exports_external.string().regex(/^[0-9a-f]{64}$/)).optional()}).passthrough(),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(),PrWorkflowCheckoutRecoveryRecordSchema=exports_external.object({code:exports_external.enum(["UNMERGED_INDEX","GIT_OPERATION_IN_PROGRESS","DIRTY_SUBMODULE","SWARM_STATE_TRACKING_ERROR","GIT_STATE_INDETERMINATE"]),retryable:exports_external.literal(!1),requiredAction:exports_external.string().min(1).max(2000),evidence:exports_external.object({worktreeRoot:exports_external.string().nullable(),gitDir:exports_external.string().nullable(),operations:exports_external.array(exports_external.string().min(1)).max(16),unmergedCodes:exports_external.array(exports_external.string().min(1)).max(16),paths:exports_external.array(exports_external.string()).max(20),trackedCount:exports_external.number().int().nonnegative(),untrackedCount:exports_external.number().int().nonnegative(),pathsTruncated:exports_external.boolean(),detail:exports_external.string().max(1000).optional()}).strict(),detectedAt:exports_external.string().min(1)}).strict(),PrFeedbackReviewHandoffRecordSchema=exports_external.object({path:exports_external.string().min(1).max(512),runId:exports_external.string().min(1).max(128),sourcePrHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),prUrl:exports_external.string().url().max(2000),findingIds:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),digest:exports_external.string().regex(/^[0-9a-f]{64}$/),sourceWorkflowInstanceId:exports_external.string().min(1).max(128),provenance:exports_external.enum(["active-review-v1","external-v1"])}).strict(),PrWorkflowGateStateSchema=exports_external.object({schemaVersion:exports_external.literal(GATE_SCHEMA_VERSION),revision:exports_external.number().int().nonnegative().default(0),workflowInstanceId:exports_external.string().min(1).max(128).optional(),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(),prReviewTriggerLedger:exports_external.array(PrReviewInlineTriggerRowSchema).length(PR_REVIEW_REQUIRED_TRIGGER_IDS.length).optional(),prReviewTriggerEvalPath:exports_external.string().min(1).optional(),prReviewTriggerEvalRunId:exports_external.string().min(1).optional(),prReviewValidationBatches:exports_external.array(PrReviewValidationBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBatchCoherence:exports_external.record(exports_external.string().min(1),PrReviewBatchCoherenceRecordSchema).refine((entries)=>Object.keys(entries).length<=MAX_WORKFLOW_BATCHES,`prReviewBatchCoherence may not exceed ${MAX_WORKFLOW_BATCHES} entries`).optional(),prReviewRetiredReviewerSessionIds:exports_external.array(exports_external.string().min(1)).max(MAX_RETIRED_REVIEWER_SESSION_IDS).optional(),prReviewRetiredConsolidatedLanes:exports_external.array(exports_external.string().min(1)).max(MAX_RETIRED_CONSOLIDATED_LANES).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(),checkoutRecovery:PrWorkflowCheckoutRecoveryRecordSchema.optional(),prFeedbackTargetUrl:exports_external.string().url().max(2000).optional(),prFeedbackReviewHandoff:PrFeedbackReviewHandoffRecordSchema.optional(),prFeedbackInventory:exports_external.array(exports_external.string().min(1)).min(1).optional(),prFeedbackVerifications:exports_external.array(PrFeedbackVerificationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackRetiredItemOwnership:exports_external.record(exports_external.string().min(1),exports_external.string().min(1)).refine((entries)=>Object.keys(entries).length<=MAX_RETIRED_FEEDBACK_ITEM_OWNERS,`prFeedbackRetiredItemOwnership may not exceed ${MAX_RETIRED_FEEDBACK_ITEM_OWNERS} entries`).optional(),prFeedbackVerification:PrFeedbackVerificationRecordSchema.optional(),prFeedbackStageA:PrFeedbackStageARecordSchema.optional(),prFeedbackGateBatches:exports_external.array(PrFeedbackGateBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackReadyToPublish:PrFeedbackReadyToPublishRecordSchema.optional(),prFeedbackRebindCount:exports_external.number().int().nonnegative().optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();TERMINAL_FAILED_DELEGATION_STATUSES=new Set(["completed","error","cancelled","stale"]);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"};PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN=/^pr-review\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/feedback-handoff\.json$/,PrReviewFeedbackHandoffArtifactSchema=exports_external.object({schema_version:exports_external.literal(1),run_id:exports_external.string().min(1).max(128),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),created_at:exports_external.string().datetime(),pr_url:exports_external.string().url().max(2000),finding_ids:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),summary:exports_external.string().min(1).max(20000),provenance:exports_external.array(exports_external.string().min(1).max(4000)).min(1).max(1000)}).strict();PrReviewFindingProjectionSchema=exports_external.object({finding_id:exports_external.string().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"])}).passthrough();_test_exports={minimumConsolidatedLaneCover,analyzePrReviewBatchRecordIntegrity,MAX_COVER_UNIVERSE_BITS,extractCandidateIds,parseCanonicalCandidateRows,resolvePrReviewRowFamily,pipeFieldsCapped,reviewerVerdictRowDigest,workflowGateStateRelativePath,workflowGateStateLockRelativePath,workflowCheckoutMutationLockRelativePath,withPrWorkflowCheckoutMutationLock,resetTrackedStateCache:()=>{trackedStatesByProjectSession.clear(),pendingStateMutationsByProjectSession.clear(),pendingCheckoutMutationsByProject.clear(),completedCheckoutLockOwners.clear(),_test_exports.beforeTerminalClear=void 0,_test_exports.beforePrFeedbackTransitionLock=void 0,_test_exports.beforePrFeedbackTrackingSwitch=void 0,_test_exports.afterPrFeedbackTrackingSwitch=void 0,_test_exports.beforePrFeedbackTrackingPersist=void 0,_test_exports.beforeBoundedSwarmFileOpen=void 0,_test_exports.beforeSessionStateLockWrite=void 0,_test_exports.beforeCheckoutLockWrite=void 0,_test_exports.beforeSafeDirectoryCreate=void 0,_test_exports.beforeAtomicTempWrite=void 0,_test_exports.beforeAtomicRename=void 0,_test_exports.openCheckoutLock=openCheckoutLockFile,_test_exports.removeCheckoutLock=removeCheckoutLockFile,_test_exports.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,_test_exports.classifyPrWorkflowGitStateAsync=classifyPrWorkflowGitState},beforeTerminalClear:void 0,beforePrFeedbackTransitionLock:void 0,beforePrFeedbackTrackingSwitch:void 0,afterPrFeedbackTrackingSwitch:void 0,beforePrFeedbackTrackingPersist:void 0,beforeBoundedSwarmFileOpen:void 0,beforeSessionStateLockWrite:void 0,beforeCheckoutLockWrite:void 0,beforeSafeDirectoryCreate:void 0,beforeAtomicTempWrite:void 0,beforeAtomicRename:void 0,openCheckoutLock:openCheckoutLockFile,removeCheckoutLock:removeCheckoutLockFile,checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,classifyPrWorkflowGitStateAsync:classifyPrWorkflowGitState,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,MAX_WORKFLOW_BATCHES,MAX_RETIRED_REVIEWER_SESSION_IDS,MAX_RETIRED_CONSOLIDATED_LANES,MAX_RETIRED_FEEDBACK_ITEM_OWNERS,resolvePrWorkflowRevisionDigestDetailed,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,composePrReviewPhaseVerdicts:async(directory,sessionID,phase)=>{let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext(directory,state);return composePrReviewPhaseVerdicts(directory,state,phase,ctx)},assertSettledPhaseHasAuthoritativeVerdicts,derivePrReviewCriticInventoryForCoverageGate:async(directory,sessionID,origin="_test_exports")=>{let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext(directory,state);return derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,origin)},derivePrReviewCandidateInventory:async(directory,sessionID)=>{let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext(directory,state);return derivePrReviewCandidateInventory(directory,state,ctx)},isProcessAlive,isSafeStandaloneGitCommit,rename:fsp3.rename,nowMs:()=>Date.now()};PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","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","list","lsp","open","read","search","skill","tree","view","web_fetch","web_search","webfetch","websearch"]);PR_WORKFLOW_CD_PREFIX_PATTERN=/^cd\s+(?:\/d\s+)?(?:"[A-Za-z0-9 _.\\/:~+-]+"|'[A-Za-z0-9 _.\\/:~+-]+'|[A-Za-z0-9_.\\/:~+-]+)\s*&&\s*/i,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN=/\s+2>&1\s*$/,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt](?: -C (?:"[^"]+"|'[^']+'|\S+))* (.+)$/,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt] -C /;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"]),FEEDBACK_NO_CHANGE_CLASSIFICATIONS=new Set(["DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"]);PrWorkflowCheckoutMutationTimeoutError=class PrWorkflowCheckoutMutationTimeoutError extends Error{phase;code="PR_WORKFLOW_CHECKOUT_MUTATION_TIMEOUT";retryable=!1;constructor(phase){super(phase==="queue"?"BLOCKED: timed out waiting for the active PR workflow checkout mutation; the existing owner still holds serialization and must settle before retrying":"BLOCKED: PR workflow checkout mutation exceeded its execution deadline; serialization remains held until the in-flight action actually settles");this.phase=phase;this.name="PrWorkflowCheckoutMutationTimeoutError"}}});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,explicitReason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500);if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
|
|
194
|
+
`).match(/^# branch\.oid (.+)$/m);if(!oidMatch)return null;if(!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(oidMatch[1])&&oidMatch[1]!=="(initial)")return null;let gitHead=oidMatch[1]==="(initial)"?null:oidMatch[1],dirtyTrackedPaths=[],untrackedPaths=[],unmergedPaths=[],unmergedCodes=[],dirtySubmodulePaths=[],renameOrCopy=!1;for(let index=0;index<records.length;index++){let record2=records[index];if(!record2)continue;if(record2.startsWith("? ")){untrackedPaths.push(record2.slice(2));continue}if(record2.startsWith("1 ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,8);if(!changedPath||!fields[2])return null;if(dirtyTrackedPaths.push(changedPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}if(record2.startsWith("2 ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,9),originalPath=records[++index];if(!changedPath||!originalPath||!fields[2])return null;if(renameOrCopy=!0,dirtyTrackedPaths.push(changedPath,originalPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}if(record2.startsWith("u ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,10),unmergedCode=fields[1];if(!changedPath||!fields[2]||!unmergedCode||!/^(?:DD|AU|UD|UA|DU|AA|UU)$/.test(unmergedCode))return null;if(unmergedPaths.push(changedPath),unmergedCodes.push(unmergedCode),dirtyTrackedPaths.push(changedPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}return null}return{gitHead,dirtyTrackedPaths:[...new Set(dirtyTrackedPaths)],untrackedPaths:[...new Set(untrackedPaths)],renameOrCopy,unmergedPaths:[...new Set(unmergedPaths)],unmergedCodes:[...new Set(unmergedCodes)],dirtySubmodulePaths:[...new Set(dirtySubmodulePaths)]}}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:path12.resolve(directory),gitHead:snapshot?.gitHead??null,dirtyHash:porcelain===null?null:digest(porcelain),changedFiles:snapshot?[...new Set([...snapshot.dirtyTrackedPaths,...snapshot.untrackedPaths])]: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(path12.resolve(expected.directory)!==path12.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 createHash7("sha256").update(text).digest("hex")}var GIT_SNAPSHOT_TIMEOUT_MS=3000,GIT_SNAPSHOT_MAX_BUFFER=33554432,REVISION_MAX_FILES=50000,REVISION_MAX_TOTAL_BYTES=536870912,REVISION_READ_CHUNK_BYTES=65536,REVISION_YIELD_EVERY_CHUNKS=16,REVISION_ENUMERATION_TIMEOUT_MS=15000,GITLINK_MODE_PATTERN,compareWorkspaceSnapshot,_internals9;var init_workspace_snapshot=__esm(()=>{init_bun_compat();GITLINK_MODE_PATTERN=/^:\d{6} 160000 |^:160000 \d{6} /;compareWorkspaceSnapshot=workspaceSnapshotMatches;_internals9={spawnSync:child_process.spawnSync,bunSpawn,gitTimeoutMs:GIT_SNAPSHOT_TIMEOUT_MS,yieldControl:()=>new Promise((resolve8)=>setImmediate(resolve8)),parsePorcelainV2Snapshot,revisionMaxFiles:REVISION_MAX_FILES,revisionMaxTotalBytes:REVISION_MAX_TOTAL_BYTES,gitSnapshotMaxBuffer:GIT_SNAPSHOT_MAX_BUFFER,revisionEnumerationTimeoutMs:REVISION_ENUMERATION_TIMEOUT_MS,readChangedFileSync:(filePath)=>fs8.readFileSync(filePath)}});import*as fs9 from"node:fs";import*as path13 from"node:path";function isExecutableFile(candidate){try{return fs9.statSync(candidate).isFile()}catch{return!1}}function resolveExecutableFromPath(names,envPath=process.env.PATH??"",platform=process.platform){let pathEntries=envPath.split(path13.delimiter).filter(Boolean),isWindows=platform==="win32";for(let rawName of names){if(!rawName)continue;if(path13.isAbsolute(rawName)&&isExecutableFile(rawName))return rawName;let extensions=isWindows&&path13.extname(rawName)===""?DEFAULT_WINDOWS_EXTENSIONS:[""];for(let dir of pathEntries)for(let ext of extensions){let candidate=path13.join(dir,`${rawName}${ext}`);if(isExecutableFile(candidate))return candidate}}return null}function clampTimeoutMs(timeoutMs){if(!Number.isFinite(timeoutMs))return MAX_RUNNER_TIMEOUT_MS;return Math.min(Math.max(1,Math.floor(timeoutMs)),MAX_RUNNER_TIMEOUT_MS)}function addTimeoutMs(baseMs,deltaMs){if(baseMs>=MAX_TIMEOUT_MS)return MAX_TIMEOUT_MS;return Math.min(MAX_TIMEOUT_MS,baseMs+deltaMs)}function computeSpawnTimeoutMs(timeoutMs){let total=clampTimeoutMs(timeoutMs);for(let windowMs of[TERMINATION_GRACE_MS,TERMINATION_FORCE_MS,TERMINATION_CONFIRM_MS,TREE_TERMINATION_CONFIRM_MS,TERMINATION_FALLBACK_BUFFER_MS])total=addTimeoutMs(total,windowMs);return total}function startBoundedStreamRead(stream,maxBytes,onLimitExceeded){let reader=stream.getReader(),lockReleased=!1,cancelPromise,releaseLock=()=>{if(lockReleased)return;lockReleased=!0;try{reader.releaseLock()}catch{}},cancel=async()=>{return cancelPromise??=(async()=>{try{await reader.cancel()}catch{}finally{releaseLock()}})(),cancelPromise};if(maxBytes<=0)return onLimitExceeded?.(),{cancel,promise:(async()=>{return await cancel(),{text:"",truncated:!0}})()};return{promise:(async()=>{let chunks=[],total=0,truncated=!1;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-total;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining)),total+=remaining;truncated=!0,onLimitExceeded?.(),cancel();break}chunks.push(value),total+=value.byteLength}}finally{releaseLock()}let out=new Uint8Array(total),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(out),truncated}})(),cancel}}function timeoutKillSignal(platform){return platform==="win32"?"SIGTERM":"SIGKILL"}function killProcess(proc){try{proc?.kill(timeoutKillSignal(_internals10.platform()))}catch{}}function requestTermination(proc,signal){try{if(proc?.killTree)return proc.killTree(signal).then(()=>!0,()=>!1);else return proc?.kill(signal),Promise.resolve(proc!==void 0)}catch{return Promise.resolve(!1)}}async function waitForExitWithin(exitPromise,waitMs){if(waitMs<=0)return Promise.resolve(null);let timeoutHandle;try{return await Promise.race([exitPromise,new Promise((resolve8)=>{timeoutHandle=_internals10.setTimeout(()=>resolve8(null),waitMs)})])}finally{if(timeoutHandle!==void 0)_internals10.clearTimeout(timeoutHandle)}}async function waitForValueWithin(promise2,waitMs){let timeoutHandle;try{return await Promise.race([promise2.then((value)=>({completed:!0,value})),new Promise((resolve8)=>{timeoutHandle=_internals10.setTimeout(()=>resolve8({completed:!1}),waitMs)})])}finally{if(timeoutHandle!==void 0)_internals10.clearTimeout(timeoutHandle)}}async function collectBoundedStreams(stdoutRead,stderrRead,proc,treeAlreadyConfirmed=!1){let reads=Promise.all([stdoutRead.promise,stderrRead.promise]),collected=await waitForValueWithin(reads,STREAM_DRAIN_MS);if(!collected.completed){let treeTermination=waitForValueWithin(requestTermination(proc,"SIGKILL"),TREE_TERMINATION_CONFIRM_MS);Promise.allSettled([stdoutRead.cancel(),stderrRead.cancel()]),collected=await waitForValueWithin(reads,STREAM_CANCEL_MS);let terminationResult=await treeTermination;if(!treeAlreadyConfirmed&&(!terminationResult.completed||!terminationResult.value))return{kind:"unconfirmed-termination"}}if(!collected.completed)return{kind:"cleanup-failed"};return{kind:"collected",stdout:collected.value[0],stderr:collected.value[1]}}async function runExternalTool(options){if(!path13.isAbsolute(options.cwd))return{status:"spawn-error",exitCode:null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:"external tool cwd must be absolute"};if(options.abortSignal?.aborted)return{status:"cancelled",exitCode:null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:"external tool execution cancelled before spawn"};let proc,timeoutHandle,abortListener,overflowTreeTermination,exitSettled=!1,settledExitCode=null,runnerTimeoutMs=clampTimeoutMs(options.timeoutMs),spawnTimeoutMs=computeSpawnTimeoutMs(runnerTimeoutMs);try{proc=_internals10.bunSpawn([options.executable,...options.args],{cwd:options.cwd,env:options.env,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:spawnTimeoutMs,killProcessTree:!0,windowsVerbatimArguments:options.windowsVerbatimArguments});let exitPromise=proc.exited.then((exitCode)=>{return exitSettled=!0,settledExitCode=exitCode,exitCode}),exitRacePromise=exitPromise.then((exitCode)=>({kind:"exit",exitCode})),timeout=new Promise((resolve8)=>{timeoutHandle=_internals10.setTimeout(()=>{if(exitSettled){resolve8({kind:"exit",exitCode:settledExitCode??proc?.exitCode??0});return}resolve8({kind:"timeout"})},runnerTimeoutMs)}),cancelled=new Promise((resolve8)=>{if(!options.abortSignal)return;let handled=!1;if(abortListener=()=>{if(handled)return;handled=!0,resolve8({kind:"cancelled"})},options.abortSignal.addEventListener("abort",abortListener,{once:!0}),options.abortSignal.aborted)abortListener()}),terminateOnOverflow=()=>{overflowTreeTermination??=requestTermination(proc,"SIGKILL")},stdoutRead=startBoundedStreamRead(proc.stdout,options.maxStdoutBytes,terminateOnOverflow),stderrRead=startBoundedStreamRead(proc.stderr,options.maxStderrBytes,terminateOnOverflow),exitResult=await Promise.race([exitRacePromise,timeout,cancelled]);if(exitResult.kind==="timeout"||exitResult.kind==="cancelled"){let gracefulTreeTermination=requestTermination(proc,"SIGTERM"),confirmedExitCode=await waitForExitWithin(exitPromise,TERMINATION_GRACE_MS);if(!overflowTreeTermination)overflowTreeTermination=requestTermination(proc,"SIGKILL");let treeTerminationResult=waitForValueWithin(Promise.all([gracefulTreeTermination,overflowTreeTermination]),TREE_TERMINATION_CONFIRM_MS);if(confirmedExitCode===null)confirmedExitCode=await waitForExitWithin(exitPromise,TERMINATION_FORCE_MS);if(confirmedExitCode===null)confirmedExitCode=await waitForExitWithin(exitPromise,TERMINATION_CONFIRM_MS);let treeTermination=await treeTerminationResult,treeTerminationConfirmed=treeTermination.completed&&treeTermination.value.some(Boolean);Promise.allSettled([stdoutRead.cancel(),stderrRead.cancel()]);let streams2=await collectBoundedStreams(stdoutRead,stderrRead,proc,treeTerminationConfirmed);if(streams2.kind!=="collected")return{status:"spawn-error",exitCode:confirmedExitCode??proc.exitCode,stdout:"",stderr:"",stdoutTruncated:!0,stderrTruncated:!0,message:streams2.kind==="unconfirmed-termination"?UNCONFIRMED_TERMINATION_MESSAGE:"external tool output cleanup did not complete"};let{stdout:stdout2,stderr:stderr2}=streams2;if(confirmedExitCode===null||!treeTerminationConfirmed)return{status:"spawn-error",exitCode:proc.exitCode,stdout:stdout2.text,stderr:stderr2.text,stdoutTruncated:stdout2.truncated,stderrTruncated:stderr2.truncated,message:UNCONFIRMED_TERMINATION_MESSAGE};if(exitResult.kind==="timeout")return{status:"timeout",exitCode:confirmedExitCode,stdout:stdout2.text,stderr:stderr2.text,stdoutTruncated:stdout2.truncated,stderrTruncated:stderr2.truncated};return{status:"cancelled",exitCode:confirmedExitCode,stdout:stdout2.text,stderr:stderr2.text,stdoutTruncated:stdout2.truncated,stderrTruncated:stderr2.truncated,message:"external tool execution cancelled"}}let streams=await collectBoundedStreams(stdoutRead,stderrRead,proc);if(streams.kind!=="collected")return{status:"spawn-error",exitCode:exitResult.exitCode,stdout:"",stderr:"",stdoutTruncated:!0,stderrTruncated:!0,message:streams.kind==="unconfirmed-termination"?UNCONFIRMED_TERMINATION_MESSAGE:"external tool output cleanup did not complete"};let{stdout,stderr}=streams;if(overflowTreeTermination){let overflowTermination=await waitForValueWithin(overflowTreeTermination,TREE_TERMINATION_CONFIRM_MS);if(!overflowTermination.completed||!overflowTermination.value)return{status:"spawn-error",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated,message:UNCONFIRMED_TERMINATION_MESSAGE}}if(proc.spawnError)return{status:"spawn-error",exitCode:proc.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated,message:proc.spawnError.message};if(proc.signalCode)return{status:"spawn-error",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated,message:`external tool terminated by signal ${proc.signalCode}`};return{status:"completed",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated}}catch(err){return{status:"spawn-error",exitCode:proc?.exitCode??null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:err instanceof Error?err.message:String(err)}}finally{if(timeoutHandle!==void 0)_internals10.clearTimeout(timeoutHandle);if(abortListener&&options.abortSignal)options.abortSignal.removeEventListener("abort",abortListener);if(!exitSettled)killProcess(proc)}}var DEFAULT_WINDOWS_EXTENSIONS,TERMINATION_GRACE_MS=20,TERMINATION_FORCE_MS=20,TERMINATION_CONFIRM_MS=20,TREE_TERMINATION_CONFIRM_MS=5100,TERMINATION_FALLBACK_BUFFER_MS=1,STREAM_DRAIN_MS=50,STREAM_CANCEL_MS=50,MAX_TIMEOUT_MS=2147483647,TERMINATION_WINDOWS_MS,MAX_RUNNER_TIMEOUT_MS,UNCONFIRMED_TERMINATION_MESSAGE="external tool process termination could not be confirmed",_internals10;var init_external_tool_runner=__esm(()=>{init_bun_compat();DEFAULT_WINDOWS_EXTENSIONS=[".exe",".cmd",".bat"],TERMINATION_WINDOWS_MS=TERMINATION_GRACE_MS+TERMINATION_FORCE_MS+TERMINATION_CONFIRM_MS+TREE_TERMINATION_CONFIRM_MS+TERMINATION_FALLBACK_BUFFER_MS,MAX_RUNNER_TIMEOUT_MS=MAX_TIMEOUT_MS-TERMINATION_WINDOWS_MS;_internals10={bunSpawn,platform:()=>process.platform,now:()=>Date.now(),setTimeout,clearTimeout,clampTimeoutMs,computeSpawnTimeoutMs}});import*as fsp2 from"node:fs/promises";import*as path14 from"node:path";function boundPath(value){let cleaned=value.replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim();return cleaned.length>MAX_EVIDENCE_PATH_LENGTH?`${cleaned.slice(0,MAX_EVIDENCE_PATH_LENGTH)}...`:cleaned}function evidence(parsed,worktreeRoot,gitDir,operations,detail){let allPaths=parsed?[...parsed.unmergedPaths,...parsed.dirtySubmodulePaths,...parsed.dirtyTrackedPaths,...parsed.untrackedPaths]:[],uniquePaths=[...new Set(allPaths)].map(boundPath);return{worktreeRoot:worktreeRoot?boundPath(worktreeRoot):null,gitDir:gitDir?boundPath(gitDir):null,operations,unmergedCodes:parsed?[...new Set(parsed.unmergedCodes)].sort():[],paths:uniquePaths.slice(0,MAX_EVIDENCE_PATHS),trackedCount:parsed?.dirtyTrackedPaths.length??0,untrackedCount:parsed?.untrackedPaths.length??0,pathsTruncated:uniquePaths.length>MAX_EVIDENCE_PATHS,...detail?{detail}:{}}}async function runGitCapture(directory,args2){let result=await runExternalTool({executable:"git",args:[...args2],cwd:path14.resolve(directory),timeoutMs:GIT_TIMEOUT_MS,maxStdoutBytes:MAX_GIT_OUTPUT_BYTES,maxStderrBytes:65536});return{ok:result.status==="completed"&&result.exitCode===0&&!result.stdoutTruncated&&!result.stderrTruncated,stdout:result.stdout}}async function activeOperations(gitDir){return(await Promise.all(OPERATION_MARKERS.map(async([name,marker])=>{try{return await fsp2.lstat(path14.join(gitDir,marker)),name}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}))).filter((value)=>value!==null)}async function classifyPrWorkflowGitState(directory,options={}){let[statusResult,rootResult,gitDirResult]=await Promise.all([_internals11.runGitCapture(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),_internals11.runGitCapture(directory,["rev-parse","--show-toplevel"]),_internals11.runGitCapture(directory,["rev-parse","--absolute-git-dir"])]);if(!statusResult.ok||!rootResult.ok||!gitDirResult.ok)return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Confirm this is a readable Git worktree and resolve filesystem or Git errors before starting the PR workflow.",evidence:evidence(null,null,null,[],"required Git inspection failed")};let worktreeRoot=rootResult.stdout.trim(),gitDir=gitDirResult.stdout.trim(),parsedRaw=parsePorcelainV2Snapshot(statusResult.stdout);if(!worktreeRoot||!gitDir||!parsedRaw)return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Resolve the malformed or incomplete Git status before starting the PR workflow.",evidence:evidence(parsedRaw,worktreeRoot||null,gitDir||null,[],"Git returned an incomplete status snapshot")};let ignoredPaths=new Set((options.ignoredPaths??[]).map((value)=>value.replace(/\\/g,"/"))),keepPath=(value)=>!ignoredPaths.has(value.replace(/\\/g,"/")),parsed={...parsedRaw,dirtyTrackedPaths:parsedRaw.dirtyTrackedPaths.filter(keepPath),untrackedPaths:parsedRaw.untrackedPaths.filter(keepPath),unmergedPaths:parsedRaw.unmergedPaths.filter(keepPath),dirtySubmodulePaths:parsedRaw.dirtySubmodulePaths.filter(keepPath)},operations;try{operations=await _internals11.activeOperations(path14.resolve(gitDir))}catch{return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Resolve the unreadable Git operation state before starting the PR workflow.",evidence:evidence(parsed,worktreeRoot,gitDir,[],"Git operation markers could not be inspected")}}let stateEvidence=evidence(parsed,worktreeRoot,gitDir,operations);if(parsed.unmergedCodes.length>0)return{kind:"recovery-required",code:"UNMERGED_INDEX",retryable:!1,requiredAction:"Resolve or abort the current merge/rebase/cherry-pick/revert operation manually; conflicted index entries must never be stashed by PR workflow startup.",evidence:stateEvidence};if(operations.length>0)return{kind:"recovery-required",code:"GIT_OPERATION_IN_PROGRESS",retryable:!1,requiredAction:"Complete or abort the active Git operation manually before starting the PR workflow.",evidence:stateEvidence};if(parsed.dirtySubmodulePaths.length>0)return{kind:"recovery-required",code:"DIRTY_SUBMODULE",retryable:!1,requiredAction:"Resolve or preserve dirty submodule worktrees manually; the checkout-preparation stash cannot safely preserve them.",evidence:stateEvidence};if([...parsed.dirtyTrackedPaths,...parsed.untrackedPaths].find((candidate)=>candidate===".swarm"||candidate.startsWith(".swarm/")||candidate.startsWith(".swarm\\")))return{kind:"recovery-required",code:"SWARM_STATE_TRACKING_ERROR",retryable:!1,requiredAction:"Restore .swarm/ so it is git-excluded before starting the PR workflow; runtime state must not be treated as checkout dirt.",evidence:stateEvidence};if(parsed.dirtyTrackedPaths.length===0&&parsed.untrackedPaths.length===0)return{kind:"clean",code:"CLEAN",retryable:!0,requiredAction:"No checkout recovery is required.",evidence:stateEvidence};return{kind:"stashable",code:"STASHABLE_CHANGES",retryable:!0,requiredAction:"Run prepare_pr_workflow_checkout once to preserve the ordinary working-tree changes before checkout.",evidence:stateEvidence}}var GIT_TIMEOUT_MS=5000,MAX_GIT_OUTPUT_BYTES=524288,MAX_EVIDENCE_PATHS=20,MAX_EVIDENCE_PATH_LENGTH=240,OPERATION_MARKERS,_internals11;var init_pr_workflow_state=__esm(()=>{init_workspace_snapshot();init_external_tool_runner();OPERATION_MARKERS=[["merge","MERGE_HEAD"],["rebase-merge","rebase-merge"],["rebase-apply-or-am","rebase-apply"],["cherry-pick","CHERRY_PICK_HEAD"],["revert","REVERT_HEAD"],["bisect","BISECT_START"],["sequencer","sequencer"]];_internals11={runGitCapture,activeOperations,parsePorcelainV2:parsePorcelainV2Snapshot}});import{createHash as createHash8,randomUUID as randomUUID3}from"node:crypto";import{readFileSync as readFileSync6}from"node:fs";import*as fsp3 from"node:fs/promises";import*as path15 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"}function formatCheckoutRecoveryBlock(state){let evidence2=JSON.stringify({operations:state.evidence.operations,unmerged_codes:state.evidence.unmergedCodes,paths:state.evidence.paths,paths_truncated:state.evidence.pathsTruncated});return`BLOCKED: PR workflow checkout requires manual Git recovery before activation. code=${state.code} retryable=false required_action=${state.requiredAction} evidence=${evidence2}`}function checkoutRecoveryRecord(state){if(state.kind!=="recovery-required"&&state.kind!=="indeterminate")throw Error("PR workflow checkout recovery requires a terminal Git state");return{code:state.code,retryable:!1,requiredAction:state.requiredAction,evidence:state.evidence,detectedAt:isoNow()}}async function activatePrWorkflow(directory,sessionID,mode,options={}){let normalizedSessionID=normalizeSessionID(sessionID),checkoutPreflight=!await readPrWorkflowGateState(directory,normalizedSessionID)&&options.requireCheckoutPreflight?await _test_exports.classifyPrWorkflowGitStateAsync(directory):null;return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let existing=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(existing?.mode===mode){if(mode==="PR_FEEDBACK"&&options.prUrl){let requestedTarget=canonicalGitHubPrUrl(options.prUrl);if(!requestedTarget)throw Error("BLOCKED: PR_FEEDBACK target must be a canonical GitHub PR URL");let existingTarget=existing.prFeedbackTargetUrl?canonicalGitHubPrUrl(existing.prFeedbackTargetUrl):null;if(existingTarget&&requestedTarget!==existingTarget)throw Error("BLOCKED: active PR_FEEDBACK targets a different GitHub pull request");if(!existingTarget)existing=await writeStateWhileLocked(directory,{...existing,prFeedbackTargetUrl:options.prUrl,updatedAt:isoNow()})}return options.prHeadSha?bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,options.prHeadSha):existing}if(existing)throw Error(`BLOCKED: session "${normalizedSessionID}" already has an active ${existing.mode} workflow; complete it before starting ${mode}`);if(options.requireCheckoutPreflight){if(!checkoutPreflight)throw Error("BLOCKED: PR workflow gate state changed during checkout preflight; retry activation against the current project state");let lockedCheckoutPreflight=await _test_exports.classifyPrWorkflowGitStateAsync(directory,{ignoredPaths:[path15.join(".swarm",workflowCheckoutMutationLockRelativePath()),path15.join(".swarm",workflowGateStateLockRelativePath(normalizedSessionID))]});if(lockedCheckoutPreflight.kind==="recovery-required"||lockedCheckoutPreflight.kind==="indeterminate")throw Error(formatCheckoutRecoveryBlock(lockedCheckoutPreflight))}let initialHead=options.prHeadSha?await assertCurrentCheckoutHead(directory,options.prHeadSha,mode):void 0,timestamp=isoNow(),feedbackTargetUrl=mode==="PR_FEEDBACK"&&options.prUrl?canonicalGitHubPrUrl(options.prUrl)?options.prUrl:null:void 0;if(feedbackTargetUrl===null)throw Error("BLOCKED: PR_FEEDBACK target must be a canonical GitHub PR URL");let nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:0,workflowInstanceId:randomUUID3(),sessionID:normalizedSessionID,mode,activatedAt:timestamp,updatedAt:timestamp,...initialHead?{prHeadSha:initialHead}:{},...feedbackTargetUrl?{prFeedbackTargetUrl:feedbackTargetUrl}:{}};return writeStateWhileLocked(directory,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 withPrWorkflowCheckoutMutationLock(directory,async()=>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,{markRecoveryRequired:async(gitState)=>{let nextState={...state,updatedAt:isoNow(),checkoutRecovery:checkoutRecoveryRecord(gitState)},persisted=await writeStateWhileLocked(directory,nextState);return Object.assign(state,persisted),persisted}})}))}async function withInactivePrWorkflowCheckoutRestoreLock(directory,sessionID,action){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{if(await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID))throw Error("BLOCKED: checkout restoration is allowed only after complete_pr_workflow or abort_pr_workflow clears the active gate");return await assertNoActivePrWorkflowGateForCheckoutRestore(directory),action()}))}async function assertNoActivePrWorkflowGateForCheckoutRestore(directory){let gateDirectory=validateSwarmPath(directory,WORKFLOW_GATE_DIR),handle;try{handle=await fsp3.opendir(gateDirectory)}catch(error49){if(error49.code==="ENOENT")return;throw error49}let entriesRead=0,scanError,closeError;try{for(;;){let entry=await handle.read();if(!entry)break;if(entriesRead+=1,entriesRead>MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES)throw Error("BLOCKED: PR workflow gate inventory exceeds the bounded checkout-restoration scan; clear stale workflow state before retrying");if(!/\.json$/i.test(entry.name))continue;if(!entry.isFile())throw Error("BLOCKED: PR workflow gate inventory contains a non-regular state entry; checkout restoration cannot prove project inactivity");let statePath=validateSwarmPath(directory,path15.join(WORKFLOW_GATE_DIR,entry.name)),state=await readPrWorkflowGateStateFileFromDisk(statePath,entry.name);if(!state)continue;let expectedName=path15.basename(workflowGateStateRelativePath(state.sessionID));if(entry.name!==expectedName)throw Error("BLOCKED: PR workflow gate inventory contains an ambiguous state filename; checkout restoration cannot prove project inactivity");throw Error(`BLOCKED: checkout restoration cannot mutate this project while session "${state.sessionID}" has an active ${state.mode} workflow`)}}catch(error49){scanError=error49}finally{try{await handle.close()}catch(error49){if(error49.code!=="ERR_DIR_CLOSED")closeError=error49}}if(scanError!==void 0)throw scanError;if(closeError!==void 0)throw closeError}async function clearPrWorkflowGateState(directory,sessionID,expectedRevision,options={}){let normalizedSessionID=normalizeSessionID(sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{if(expectedRevision!==void 0){let current=options.allowSalvagedRead?(await readPrWorkflowGateStateForRecovery(directory,normalizedSessionID))?.state??null: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 fsp3.rm(workflowGateStatePath(directory,normalizedSessionID),{force:!0})}catch(error49){if(error49.code!=="ENOENT")throw error49}trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID))})}function prWorkflowLaneLabel(record2){return record2.laneId??record2.subagentSessionId??"unknown"}function isOpenPrWorkflowLane(record2,sessionID){return record2.parentSessionId===sessionID&&record2.mode?.startsWith("swarm-pr-")===!0&&(record2.status==="pending"||record2.status==="running")}async function settlePresumedStalePrWorkflowLanes(directory,sessionID){let now=Date.now(),open3=[],presumedStale=[];for(let record2 of readDelegations(directory)){if(!isOpenPrWorkflowLane(record2,sessionID))continue;if(now-record2.updatedAt>PR_WORKFLOW_STALE_LANE_TIMEOUT_MS)presumedStale.push(record2);else open3.push(record2)}let presumedStaleLaneIds=presumedStale.map(prWorkflowLaneLabel),openLaneIds=open3.map(prWorkflowLaneLabel);if(presumedStale.length===0)return{openLaneIds,openLanes:open3.length,presumedStaleLaneIds};let disclosure=`${presumedStaleLaneIds.length} lane(s) stale >${Math.round(PR_WORKFLOW_STALE_LANE_TIMEOUT_MS/60000)}min, treated as settled: ${presumedStaleLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}`;await sweepStaleDelegations(directory,PR_WORKFLOW_STALE_LANE_TIMEOUT_MS,{statuses:PR_WORKFLOW_SWEEPABLE_LANE_STATUSES});try{await fsp3.appendFile(validateSwarmPath(directory,"events.jsonl"),`${JSON.stringify({type:"pr_workflow_lanes_presumed_stale",timestamp:isoNow(),sessionID,presumedStaleLanes:presumedStaleLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS),staleTimeoutMs:PR_WORKFLOW_STALE_LANE_TIMEOUT_MS,disclosure})}
|
|
195
|
+
`,"utf-8")}catch{}return{openLaneIds,openLanes:open3.length,presumedStaleLaneIds,disclosure}}async function abortPrWorkflow(directory,sessionID,options={kind:"recovery",reason:""}){let recovery=await readPrWorkflowGateStateForRecovery(directory,sessionID);if(!recovery)throw noActiveGateError(sessionID);let state=recovery.state;if(options.expectedMode&&state.mode!==options.expectedMode)throw wrongModeError(state,options.expectedMode);if(state.prFeedbackReadyToPublish||recovery.armedShapeUnreadable)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.`+(recovery.armedShapeUnreadable?" The publication-arming record is itself unreadable, so it is treated as armed (fail-closed).":""));let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state.sessionID);if(laneSettlement.openLanes>0){let laneIds=laneSettlement.openLaneIds.filter(Boolean).slice(0,MAX_DISCLOSED_LANE_IDS).join(", ");throw Error(`BLOCKED: ${state.mode} abort refused while ${laneSettlement.openLanes} 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().length>0?options.reason.trim().slice(0,500):void 0;if(sanitizedReason===void 0)throw Error(`BLOCKED: ${state.mode} abort requires a non-empty reason (recorded to the audit trail).`);let abortEvent={type:"pr_workflow_aborted",timestamp:isoNow(),sessionID:state.sessionID,mode:state.mode,kind:options.kind,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},...state.checkoutRecovery?{hadTerminalRecovery:!0}:{},openLanes:laneSettlement.openLanes,...laneSettlement.presumedStaleLaneIds.length>0?{presumedStaleLanes:laneSettlement.presumedStaleLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS),presumedStaleDisclosure:laneSettlement.disclosure}:{},...recovery.salvaged?{stateSalvaged:!0,stateSalvageDisclosure:recovery.disclosure,...recovery.revisionSalvageable?{}:{casEscapeDisclosure:CAS_ESCAPE_DISCLOSURE}}:{},reason:sanitizedReason};try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp3.appendFile(eventsPath,`${JSON.stringify(abortEvent)}
|
|
196
|
+
`,"utf-8")}catch{}let casEscape=recovery.salvaged&&!recovery.revisionSalvageable;await _test_exports.beforeAbortClear?.();try{await clearPrWorkflowGateState(directory,sessionID,casEscape?void 0:state.revision,{allowSalvagedRead:recovery.salvaged})}catch(error49){try{await fsp3.appendFile(validateSwarmPath(directory,"events.jsonl"),`${JSON.stringify({type:"pr_workflow_abort_not_completed",timestamp:isoNow(),sessionID:state.sessionID,mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},reason:sanitizedReason,failure:(error49 instanceof Error?error49.message:String(error49)).slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS),disclosure:"RETRACTION: the pr_workflow_aborted record for this session did NOT complete — "+"the clear failed and the gate state may still be active. Revalidate the current session state before retrying the abort."})}
|
|
197
|
+
`,"utf-8")}catch{}throw error49}return{mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:laneSettlement.openLanes,...laneSettlement.presumedStaleLaneIds.length>0?{presumedStaleLanes:laneSettlement.presumedStaleLaneIds,presumedStaleDisclosure:laneSettlement.disclosure}:{},...recovery.salvaged?{stateSalvaged:!0,stateSalvageDisclosure:recovery.disclosure}:{},...casEscape?{casEscapeDisclosure:CAS_ESCAPE_DISCLOSURE}:{}}}async function bindPrWorkflowHead(directory,sessionID,prHeadSha){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,prHeadSha)))}async function bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,prHeadSha){let normalizedHead=normalizePrHeadSha(prHeadSha),state=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizedSessionID}". The gate must be activated before the PR head can be bound.`);if(await assertCurrentCheckoutHead(directory,normalizedHead,state.mode),state.prHeadSha&&state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: active ${state.mode} workflow is bound to PR head "${state.prHeadSha}"; received "${normalizedHead}"`);if(!state.prHeadSha)await assertPrReviewCleanCheckout(directory,state.mode);if(!state.prHeadSha&&state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);if(state.prHeadSha===normalizedHead){if(state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);return state}let nextState={...state,prHeadSha:normalizedHead,checkoutRecovery:void 0,updatedAt:isoNow()};return await _test_exports.beforePrFeedbackTrackingPersist?.(),writeStateWhileLocked(directory,nextState)}async function rebindPrFeedbackHead(directory,sessionID,prHeadSha){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK rebind is refused while publication is armed; complete the workflow (or push the bound commit) before rebinding.");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)throw Error(`BLOCKED: PR_FEEDBACK rebind refused while ${openLanes.length} PR workflow lane(s) are still in flight; collect their results first.`);if(normalizedHead===state.prHeadSha)throw Error(`BLOCKED: PR_FEEDBACK rebind to the current intake head "${normalizedHead}" is a no-op; a rebind must move to a genuinely new verified PR head after merge/rebase repair.`);await assertCurrentCheckoutHead(directory,normalizedHead,state.mode),await assertPrFeedbackTrackingCheckout(directory,normalizedHead);let nextState={...state,prHeadSha:normalizedHead,prFeedbackStageA:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackRebindCount:(state.prFeedbackRebindCount??0)+1,updatedAt:isoNow()};try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp3.appendFile(eventsPath,`${JSON.stringify({type:"pr_feedback_rebound",timestamp:isoNow(),sessionID:state.sessionID,previousPrHeadSha:state.prHeadSha,prHeadSha:normalizedHead,rebindCount:nextState.prFeedbackRebindCount})}
|
|
198
|
+
`,"utf-8")}catch{}return withSessionStateMutation(directory,state.sessionID,async()=>writeStateWhileLocked(directory,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,mode="PR_REVIEW"){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 two separate standalone commands. First run: git -C "${directory}" rev-parse --verify HEAD^0. Then run: git -C "${directory}" cat-file -t HEAD (which must print commit).`);if(currentHead.toLowerCase()!==normalizedExpected.toLowerCase()){let remediation=mode==="PR_FEEDBACK"?"Check out the intended local tracking branch at that exact head (for example with a safe standalone `gh pr checkout <number-or-url>` or `git switch -c <local> --track <remote>/<branch>`), then retry the bind. Do not create a new detached feedback checkout.":`Run bare, standalone commands from that directory. If the commit is not present locally, first run \`git fetch origin <pr-head-ref>\`. Then run \`git switch --detach ${normalizedExpected}\`. Do not prefix the switch with \`git -C\`; the read-only shell classifier refuses \`git -C ... switch\`.`;throw Error(`BLOCKED: current checkout HEAD "${currentHead}" does not match PR head "${normalizedExpected}" (working directory: "${directory}"). ${remediation}`)}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 currentHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!currentHead)throw Error("BLOCKED: PR_FEEDBACK requires a resolved exact Git HEAD before first head bind");if(currentHead.toLowerCase()!==prHeadSha.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK exact head changed before attach; expected ${prHeadSha}, received ${currentHead}`);let currentUpstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory),matchingRemoteRefs=await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha);if(currentUpstream){if(matchingRemoteRefs===null)throw Error("BLOCKED: PR_FEEDBACK could not verify the current upstream against the exact intake PR head; the bounded Git query failed or timed out");if(matchingRemoteRefs.includes(currentUpstream.remoteTrackingRef))return;throw Error(`BLOCKED: PR_FEEDBACK current upstream "${currentUpstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}"; refusing to replace an existing tracking relationship`)}let candidates=await resolvePrFeedbackTrackingCandidatesAsync(directory,prHeadSha);if(!candidates)throw Error(`BLOCKED: PR_FEEDBACK could not inspect tracked branches for exact PR head "${prHeadSha}"; the bounded Git query failed or timed out`);let{local:localCandidates,remote:remoteCandidates}=candidates;if(localCandidates.length===1){if(await _test_exports.beforePrFeedbackTrackingSwitch?.(),!await switchPrFeedbackTrackingCandidateAsync(directory,localCandidates[0]))throw Error(`BLOCKED: PR_FEEDBACK could not attach exact local tracked branch "${localCandidates[0].branchName}"; it may be checked out in another linked worktree or the bounded Git switch failed`)}else if(localCandidates.length>1)throw Error(`BLOCKED: PR_FEEDBACK exact head "${prHeadSha}" matches multiple local tracked branches: ${localCandidates.map((candidate)=>candidate.branchName).join(", ")}`);else if(remoteCandidates.length===1){if(await _test_exports.beforePrFeedbackTrackingSwitch?.(),!await switchPrFeedbackTrackingCandidateAsync(directory,remoteCandidates[0]))throw Error(`BLOCKED: PR_FEEDBACK could not attach exact remote-tracking branch "${remoteCandidates[0].remoteTrackingRef}"; the bounded Git switch failed or timed out`)}else if(remoteCandidates.length>1)throw Error(`BLOCKED: PR_FEEDBACK exact head "${prHeadSha}" matches multiple remote-tracking refs: ${remoteCandidates.map((candidate)=>candidate.remoteTrackingRef).join(", ")}`);else throw Error("BLOCKED: PR_FEEDBACK requires a current local branch or exact remote-tracking ref that points to the intake PR head before the first bind");await _test_exports.afterPrFeedbackTrackingSwitch?.();let attachedHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(attachedHead?.toLowerCase()!==prHeadSha.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK exact head changed after attach; expected ${prHeadSha}, received ${attachedHead??"(unresolved)"}`);if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK requires a clean working tree after checkout attachment");let attachedUpstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!attachedUpstream)throw Error("BLOCKED: PR_FEEDBACK could not resolve the attached branch upstream after checkout promotion");if(!(await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha))?.includes(attachedUpstream.remoteTrackingRef))throw Error(`BLOCKED: PR_FEEDBACK upstream "${attachedUpstream.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)){let rejection=await tierLConsolidationRejection(directory,state,normalizedLanes,options.revisionDigest);if(rejection)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, or on a retry batch that satisfies all five of: (1) every consolidated dimension already has a recorded lane that reached a terminal non-successful state; (2) no consolidated dimension already has a successful source; (3) no single lane owns all ${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions; (4) a batch claiming all ${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions uses at least ${PR_REVIEW_BASE_LANE_FLOORS.L} lanes; and (5) across every recorded base batch the six dimensions stay backed by at least ${PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR} distinct lanes, counting each dimension no consolidated lane claims as one plus the FEWEST declared consolidated lanes that suffice to cover every dimension consolidated lanes do claim. Clause 5 is cumulative over every base batch this wave recorded, including batches the `+"capacity GC has since dropped, and it counts a minimum cover rather than declarations — so "+"neither splitting one consolidation across several batches nor declaring overlapping or duplicate consolidations evades it. "+rejection)}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){if(state=await prunePrWorkflowBatchesForCapacity(directory,state,options.revisionDigest),previous=state.prReviewBaseDispatches??[],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}function summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest){let successful=new Set,dedicatedSuccessful=new Set,terminallyFailed=new Set;for(let batch of state.prReviewBaseDispatches??[]){let batchSuccessful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);for(let obligation of batchSuccessful)successful.add(obligation);for(let lane of batch.lanes){if((lane.ownedWorkflowLanes?.length??1)!==1)continue;let dimension=lane.ownedWorkflowLanes?.[0]??lane.workflowLane;if(batchSuccessful.has(dimension))dedicatedSuccessful.add(dimension)}let integrityPassingLaneIds=new Set(recordsPassingBatchIntegrity(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt).map((qualified)=>qualified.record.laneId)),records=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID});for(let lane of batch.lanes){if(integrityPassingLaneIds.has(lane.laneId))continue;let laneRecords=records.filter((record2)=>record2.laneId===lane.laneId);if(laneRecords.length===0||!laneRecords.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.status)))continue;for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])terminallyFailed.add(dimension)}}return{successful,dedicatedSuccessful,terminallyFailed}}function encodeConsolidatedLaneKey(owned){return[...new Set(owned)].sort().join("|")}function decodeConsolidatedLaneKey(key){return key.split("|").filter((dimension)=>dimension.length>0)}function minimumConsolidatedLaneCover(sets){let bitOf=new Map;for(let set2 of sets)for(let dimension of set2)if(!bitOf.has(dimension))bitOf.set(dimension,bitOf.size);let universeSize=bitOf.size;if(universeSize===0)return 0;let distinctMasks=new Set,largestSetSize=1;for(let set2 of sets){let mask=0,size=0;for(let dimension of set2){let bit=1<<bitOf.get(dimension);if((mask&bit)===0)size+=1;mask|=bit}if(mask===0)continue;distinctMasks.add(mask),largestSetSize=Math.max(largestSetSize,size)}if(universeSize>MAX_COVER_UNIVERSE_BITS)return Math.ceil(universeSize/largestSetSize);let full=(1<<universeSize)-1,unreachable=universeSize+1,best=Array(full+1).fill(unreachable);best[0]=0;for(let mask=0;mask<full;mask+=1){let steps=best[mask];if(steps===unreachable)continue;for(let setMask of distinctMasks){let next=mask|setMask;if(next===mask)continue;if(best[next]>steps+1)best[next]=steps+1}}return best[full]}function tierLBackingLaneCount(state,normalizedLanes,dedicatedSuccessful){let consolidatedDimensions=new Set,consolidatedSets=[],consider=(owned,allowSupersede)=>{let declared=owned.filter((dimension)=>Boolean(dimension));if(declared.length<2)return;let live=allowSupersede?declared.filter((dimension)=>!dedicatedSuccessful.has(dimension)):declared;if(live.length===0)return;consolidatedSets.push([...new Set(live)]);for(let dimension of live)consolidatedDimensions.add(dimension)},considerLane=(lane,allowSupersede)=>consider(lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane],allowSupersede);for(let batch of state.prReviewBaseDispatches??[])for(let lane of batch.lanes)considerLane(lane,!0);for(let key of state.prReviewRetiredConsolidatedLanes??[])consider(decodeConsolidatedLaneKey(key),!0);for(let lane of normalizedLanes)considerLane(lane,!1);return{backingLanes:PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!consolidatedDimensions.has(dimension)).length+minimumConsolidatedLaneCover(consolidatedSets),consolidatedDimensions:[...consolidatedDimensions]}}async function tierLConsolidationRejection(directory,state,normalizedLanes,revisionDigest){if((state.prReviewBaseDispatches?.length??0)===0)return"This is the initial base wave, which may never consolidate at tier L.";let dimensionCount=PR_REVIEW_BASE_DIMENSION_IDS.length,consolidatedLanes=normalizedLanes.filter((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1),wholeWaveLane=consolidatedLanes.find((lane)=>(lane.ownedWorkflowLanes?.length??1)>=dimensionCount);if(wholeWaveLane)return`Lane "${wholeWaveLane.laneId}" owns all ${dimensionCount} dimensions on its own.`;if(new Set(normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane])).size>=dimensionCount&&normalizedLanes.length<PR_REVIEW_BASE_LANE_FLOORS.L)return`This batch claims all ${dimensionCount} dimensions with only ${normalizedLanes.length} lanes.`;let digest2=revisionDigest;if(!digest2)digest2=(await createPrReviewGateContext(directory,state)).revisionDigest;let attempts=summarizePrReviewBaseDimensionAttempts(directory,state,digest2),consolidatedDimensions=[...new Set(consolidatedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]))].filter((dimension)=>Boolean(dimension)),alreadySuccessful=consolidatedDimensions.filter((dimension)=>attempts.successful.has(dimension));if(alreadySuccessful.length>0)return`These consolidated dimensions already have a successful source: ${alreadySuccessful.join(", ")}.`;let notTerminallyFailed=consolidatedDimensions.filter((dimension)=>!attempts.terminallyFailed.has(dimension));if(notTerminallyFailed.length>0)return`These consolidated dimensions have no recorded lane that reached a terminal non-successful state (never dispatched, still in flight, or awaiting ingestion): ${notTerminallyFailed.join(", ")}.`;let backing=tierLBackingLaneCount(state,normalizedLanes,attempts.dedicatedSuccessful);if(backing.backingLanes<PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR)return`Across every base batch this wave would be backed by only ${backing.backingLanes} distinct lanes (each dimension no consolidated lane claims counts as one, plus the fewest declared consolidated lanes that cover the rest), and dimensions ${backing.consolidatedDimensions.join(", ")} would be covered by consolidated lanes.`;return null}async function prunePrWorkflowBatchesForCapacity(directory,state,revisionDigest){try{let digest2=revisionDigest??(await createPrReviewGateContext(directory,state)).revisionDigest,before={candidate:derivePrReviewCandidateInventory(directory,state,{revisionDigest:digest2}),critic:derivePrReviewCriticInventory(directory,state,{revisionDigest:digest2})},pruned=pruneWorkflowBatches(directory,state,digest2);if(!pruned)return state;let after={candidate:derivePrReviewCandidateInventory(directory,pruned,{revisionDigest:digest2}),critic:derivePrReviewCriticInventory(directory,pruned,{revisionDigest:digest2})};if(!sameStringSet(before.candidate,after.candidate)||!sameStringSet(before.critic,after.critic))return warn("PR_REVIEW batch GC aborted: pruning would have changed the derived inventory; every batch was kept"),state;let survivingBaseIds=new Set((pruned.prReviewBaseDispatches??[]).map((batch)=>batch.batchId));if(state.prReviewBaseDispatch&&!survivingBaseIds.has(state.prReviewBaseDispatch.batchId))return warn("PR_REVIEW batch GC aborted: the latest base dispatch pointer would have been orphaned"),state;return pruned}catch(error49){return warn(`PR_REVIEW batch GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),state}}function pruneWorkflowBatches(directory,state,revisionDigest){let baseBatches=state.prReviewBaseDispatches??[],validationBatches=state.prReviewValidationBatches??[],ctx={revisionDigest},contributingBaseBatchIds=new Set;for(let batch of baseBatches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);if(batch.lanes.some((lane)=>((lane.ownedWorkflowLanes?.length)?lane.ownedWorkflowLanes:[lane.workflowLane]).every((dimension)=>successful.has(dimension))))contributingBaseBatchIds.add(batch.batchId)}let newestBaseBatchId=baseBatches.at(-1)?.batchId,survivingBase=baseBatches.filter((batch)=>batch.batchId===newestBaseBatchId||contributingBaseBatchIds.has(batch.batchId)),newestBatchIdByPhase=new Map;for(let batch of validationBatches)newestBatchIdByPhase.set(batch.phase,batch.batchId);let contributingReviewerBatchIds=new Set(composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx,!0).contributingBatchIds),survivingValidation=validationBatches.filter((batch)=>{if(batch.phase==="council"||batch.phase==="critic")return!0;if(newestBatchIdByPhase.get(batch.phase)===batch.batchId)return!0;return contributingReviewerBatchIds.has(batch.batchId)});if(survivingBase.length===baseBatches.length&&survivingValidation.length===validationBatches.length)return null;let survivingValidationIds=new Set(survivingValidation.map((batch)=>batch.batchId)),retiredReviewerSessionIds=new Set(state.prReviewRetiredReviewerSessionIds??[]);for(let batch of validationBatches){if(batch.phase!=="reviewer")continue;if(survivingValidationIds.has(batch.batchId))continue;for(let record2 of findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)retiredReviewerSessionIds.add(subagentSessionId)}}if(retiredReviewerSessionIds.size>MAX_RETIRED_REVIEWER_SESSION_IDS)return warn("PR_REVIEW batch GC aborted: retiring these reviewer batches would overflow the forbidden child-session ledger; every batch was kept"),null;let survivingBaseIds=new Set(survivingBase.map((batch)=>batch.batchId)),retiredConsolidatedLanes=new Set(state.prReviewRetiredConsolidatedLanes??[]);for(let batch of baseBatches){if(survivingBaseIds.has(batch.batchId))continue;for(let lane of batch.lanes){let owned=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(new Set(owned).size<2)continue;retiredConsolidatedLanes.add(encodeConsolidatedLaneKey(owned))}}if(retiredConsolidatedLanes.size>MAX_RETIRED_CONSOLIDATED_LANES)return warn("PR_REVIEW batch GC aborted: retiring these base batches would overflow the retired consolidated-lane ledger; every batch was kept"),null;let survivingBatchIds=new Set([...survivingBaseIds,...survivingValidationIds]),coherence=Object.fromEntries(Object.entries(state.prReviewBatchCoherence??{}).filter(([batchId])=>survivingBatchIds.has(batchId)));return{...state,...state.prReviewBaseDispatches?{prReviewBaseDispatches:survivingBase}:{},...state.prReviewValidationBatches?{prReviewValidationBatches:survivingValidation}:{},prReviewBatchCoherence:Object.keys(coherence).length>0?coherence:void 0,prReviewRetiredReviewerSessionIds:retiredReviewerSessionIds.size>0?[...retiredReviewerSessionIds]:void 0,prReviewRetiredConsolidatedLanes:retiredConsolidatedLanes.size>0?[...retiredConsolidatedLanes]:void 0}}async function assertPrReviewBaseCoverageSettled(directory,sessionID,gateContext){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 ctx=gateContext??await createPrReviewGateContext(directory,state),covered=new Set,malformedDiagnostics=[];for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest,malformedDiagnostics);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)"}${malformedDiagnostics.length>0?`; first failed lane predicates: ${malformedDiagnostics.join(" | ")}`:""}; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; expected candidate row: ${CANDIDATE_HEADERS.base_explorer}; expected clean row: ${CLEAN_TEMPLATES.base_explorer}`);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");let ctx=await createPrReviewGateContext(directory,state);if(phase==="reviewer"&&(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state=await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);else if(phase==="critic")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);ctx={revisionDigest:ctx.revisionDigest};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`);let validatedInventory;if(phase==="reviewer"||phase==="critic"){assertNoDuplicates(normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),`PR_REVIEW ${phase} review item ownership`);let assigned=normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]);validatedInventory=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state,ctx):derivePrReviewCriticInventory(directory,state,ctx),assertExactStringSet(assigned,validatedInventory,`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){if(state=await prunePrWorkflowBatchesForCapacity(directory,state,ctx.revisionDigest),previous=state.prReviewValidationBatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached")}let record2={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},reviewerItemBindings=phase==="critic"?criticReviewerItemBindings(directory,state,normalizedLanes,ctx):void 0,retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"||Boolean(state.prReviewBatchCoherence?.[batch.batchId]?.reviewerItemBindings)):previous,retainedIds=new Set(retained.map((batch)=>batch.batchId)),coherence=Object.fromEntries(Object.entries(state.prReviewBatchCoherence??{}).filter(([id])=>retainedIds.has(id)));if(validatedInventory)coherence[batchId]={validatedInventory,...reviewerItemBindings?{reviewerItemBindings}:{}};let nextState={...state,updatedAt:isoNow(),prReviewValidationBatches:[...retained,record2],prReviewBatchCoherence:Object.keys(coherence).length>0?coherence:void 0};return await persistState(directory,nextState),nextState}async function assertPrReviewValidationSettled(directory,sessionID,phase,gateContext){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=gateContext??await createPrReviewGateContext(directory,state),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??[],batches=requiredPhase==="council"?validationBatches.filter((batch)=>batch.phase==="council"):prReviewPhaseWindow(state,requiredPhase);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`);if(requiredPhase==="council"){let settled=new Set;for(let batch of batches)for(let obligation of successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt,!0,new Set,ctx.revisionDigest))settled.add(obligation);let missing=[...new Set(batches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane)))].filter((obligation)=>!settled.has(obligation));if(missing.length>0)throw Error(`BLOCKED: PR_REVIEW council obligations lack successful exact artifacts: ${missing.join(", ")}`);continue}let composed=composePrReviewPhaseVerdicts(directory,state,requiredPhase,ctx);if(composed.unclaimed.length>0){let named=composed.unclaimed.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=composed.unclaimed.length-named.length;throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} items lack an authenticated verdict from any successful lane: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:"")+(composed.diagnostics.length>0?`; diagnostics: ${composed.diagnostics.join(" | ")}`:""))}if(assertSettledPhaseHasAuthoritativeVerdicts(requiredPhase,composed,requiredPhase==="reviewer"?deriveLatestPrReviewReviewerVerdicts(directory,state,ctx):deriveLatestPrReviewCriticVerdicts(directory,state,ctx),`assertPrReviewValidationSettled(${requiredPhase})`),composed.diagnostics.length>0)warn(`PR_REVIEW ${requiredPhase} settled by composition across batches [${composed.contributingBatchIds.join(", ")}] with abandoned or ineligible lanes`,composed.diagnostics)}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),requiredHandoffIds=state.prFeedbackReviewHandoff?.findingIds??[],inventorySet=new Set(normalizedInventory),missingHandoffIds=requiredHandoffIds.filter((findingId)=>!inventorySet.has(findingId));if(missingHandoffIds.length>0)throw Error(`BLOCKED: PR_FEEDBACK inventory must include every continued review finding: ${missingHandoffIds.join(", ")}`);if(state.prFeedbackInventory){let existing=state.prFeedbackInventory;if(sameStringArray(existing,normalizedInventory))return state;let nextIds=new Set(normalizedInventory),droppedIds=existing.filter((itemId)=>!nextIds.has(itemId));if(droppedIds.length>0)throw Error(`BLOCKED: PR_FEEDBACK inventory is append-only after declaration; declared item(s) may not be removed or renamed: ${droppedIds.join(", ")}`);let existingIds=new Set(existing),appendedIds=normalizedInventory.filter((itemId)=>!existingIds.has(itemId));if(appendedIds.length===0)throw Error("BLOCKED: PR_FEEDBACK inventory amendment declared no new items");let previousAmendments=state.prFeedbackInventoryAmendments??[];if(previousAmendments.length+appendedIds.length>MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS)throw Error(`BLOCKED: PR_FEEDBACK inventory amendment limit reached (${MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS}); the amendment ledger is an audit trail and is never pruned`);let amendedAt=isoNow(),batch=previousAmendments.reduce((highest,amendment)=>Math.max(highest,amendment.batch),0)+1,amendedState={...state,updatedAt:amendedAt,prFeedbackInventory:normalizedInventory,prFeedbackInventoryAmendments:[...previousAmendments,...appendedIds.map((entry)=>({entry,amendedAt,batch}))],prFeedbackReadyToPublish:void 0};return await persistState(directory,amendedState),amendedState}let nextState={...state,updatedAt:isoNow(),prFeedbackInventory:normalizedInventory,prFeedbackVerifications:[]};return await persistState(directory,nextState),nextState}async function prunePrFeedbackVerificationsForCapacity(directory,state){try{let digest2=await currentPrFeedbackRevisionDigest(directory,state),batches=state.prFeedbackVerifications??[],before=prFeedbackCoveredItems(directory,state,digest2),newestBatchId=batches.at(-1)?.batchId,surviving=batches.filter((batch)=>batch.batchId===newestBatchId||prFeedbackBatchCoveredItems(directory,state,batch,digest2).size>0);if(surviving.length===batches.length)return state;let retiredItemOwnership={...state.prFeedbackRetiredItemOwnership??{}},survivingIds=new Set(surviving.map((batch)=>batch.batchId));for(let batch of batches){if(survivingIds.has(batch.batchId))continue;for(let lane of batch.ownership)for(let itemId of lane.ownedItemIds)retiredItemOwnership[itemId]=lane.laneId}if(Object.keys(retiredItemOwnership).length>MAX_RETIRED_FEEDBACK_ITEM_OWNERS)return warn("PR_FEEDBACK verification GC aborted: retiring these batches would overflow the item-ownership ledger; every batch was kept"),state;let pruned={...state,prFeedbackVerifications:surviving,prFeedbackRetiredItemOwnership:Object.keys(retiredItemOwnership).length>0?retiredItemOwnership:void 0},after=prFeedbackCoveredItems(directory,pruned,digest2);if(!sameStringSet([...before],[...after]))return warn("PR_FEEDBACK verification GC aborted: pruning would have changed the covered inventory; every batch was kept"),state;if(state.prFeedbackVerification&&!survivingIds.has(state.prFeedbackVerification.batchId))return warn("PR_FEEDBACK verification GC aborted: the latest verification pointer would have been orphaned"),state;return pruned}catch(error49){return warn(`PR_FEEDBACK verification GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),state}}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){if(state=await prunePrFeedbackVerificationsForCapacity(directory,state),previous=state.prFeedbackVerifications??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached")}for(let[itemId,laneId]of Object.entries(state.prFeedbackRetiredItemOwnership??{}))claimedByItemId.set(itemId,laneId);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}function prFeedbackBatchCoveredItems(directory,state,batch,currentDigest){let covered=new Set,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)}return covered}function prFeedbackCoveredItems(directory,state,currentDigest){let covered=new Set;for(let batch of state.prFeedbackVerifications??[])for(let itemId of prFeedbackBatchCoveredItems(directory,state,batch,currentDigest))covered.add(itemId);return covered}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=prFeedbackCoveredItems(directory,state,currentDigest),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=createHash8("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 normalizedCategories=optionalCategoryOrder.filter((category)=>applicableCategories.includes(category)),retainsGateBatches=stageARetainsGateBatches(state.prFeedbackStageA,{revisionDigest:currentDigest,applicableCategories:normalizedCategories,applicableObligations}),nextState={...state,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks3],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:normalizedCategories,applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:retainsGateBatches?[...state.prFeedbackGateBatches??[]]:[],prFeedbackReadyToPublish:void 0};return await persistState(directory,nextState),nextState}function canonicalStageAObligation(obligation){return[obligation.id,obligation.category,obligation.workingDirectory,obligation.source,obligation.validatorContract?.path??"",obligation.validatorContract?.id??""].join("\x00")}function stageARetainsGateBatches(previous,next){if(!previous||previous.revisionDigest!==next.revisionDigest)return!1;if(!previous.applicableCategories||!previous.applicableObligations)return!1;let nextCategories=new Set(next.applicableCategories);if(!previous.applicableCategories.every((category)=>nextCategories.has(category)))return!1;let nextObligations=new Set(next.applicableObligations.map(canonicalStageAObligation));return previous.applicableObligations.every((obligation)=>nextObligations.has(canonicalStageAObligation(obligation)))}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(!sameStringArray(batch.itemIds,state.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} evidence covers a stale inventory; the feedback inventory was amended after this batch was recorded. Re-run ${phase} against every current inventory item.`);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,runId,artifactPath){let state=await assertPrReviewBaseCoverageSettled(directory,sessionID),normalizedRunId=runId.trim();if(!normalizedRunId)throw Error("BLOCKED: PR_REVIEW trigger artifact run_id is required");let normalizedPath=artifactPath.trim();if(!normalizedPath)throw Error("BLOCKED: PR_REVIEW trigger artifact path is required");if(state.prReviewTriggerEvalRunId&&state.prReviewTriggerEvalRunId!==normalizedRunId)throw Error(`BLOCKED: PR_REVIEW trigger evaluation is already bound to run "${state.prReviewTriggerEvalRunId}"`);if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==normalizedRunId)throw Error(`BLOCKED: PR_REVIEW trigger evaluation run_id must match the findings artifact run "${state.prReviewArtifactRunId}"`);let nextState={...state,updatedAt:isoNow(),prReviewTriggerEvalPath:normalizedPath,prReviewTriggerEvalRunId:normalizedRunId};return await persistState(directory,nextState),nextState}async function bindPrReviewTriggerLedger(directory,sessionID,input){let ledger;try{ledger=validatePrReviewInlineTriggerLedger(input)}catch(error49){throw Error(`BLOCKED: invalid PR_REVIEW trigger_evaluation: ${error49 instanceof Error?error49.message:String(error49)}`)}let state=await assertPrReviewBaseCoverageSettled(directory,sessionID);if(state.prReviewTriggerLedger){let frozen;try{frozen=validatePrReviewInlineTriggerLedger(state.prReviewTriggerLedger)}catch(error49){throw Error(`BLOCKED: persisted PR_REVIEW trigger ledger is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}if(prReviewTriggerLedgerDigest(frozen.rows)!==prReviewTriggerLedgerDigest(ledger.rows))throw Error("BLOCKED: PR_REVIEW trigger_evaluation must remain exactly identical across every micro dispatch");return state}let nextState={...state,updatedAt:isoNow(),prReviewTriggerLedger:ledger.rows};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`);let ctx=await createPrReviewGateContext(directory,state);if(boundary==="post_reviewer")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);else if(boundary==="post_critic"){if(await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx),derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,"assertPrReviewArtifactBoundary(post_critic)").length>0)state=await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx)}if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==runId)throw Error(`BLOCKED: PR_REVIEW artifacts are already bound to run "${state.prReviewArtifactRunId}"`);if(state.prReviewTriggerEvalRunId&&state.prReviewTriggerEvalRunId!==runId)throw Error(`BLOCKED: PR_REVIEW findings must use the same run as the trigger evaluation "${state.prReviewTriggerEvalRunId}"`);let expectedFindingIds=derivePrReviewCandidateInventory(directory,state,ctx),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 ctx=await createPrReviewGateContext(directory,state),reviewerVerdicts=authoritativeReviewerVerdictsForGate(directory,state,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`),criticVerdicts=boundary==="post_critic"?authoritativeCriticVerdictsForGate(directory,state,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`):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}function normalizePrReviewFeedbackHandoffPath(handoffPath){let normalized=handoffPath.trim().replace(/\\/g,"/"),relative5=normalized.startsWith(".swarm/")?normalized.slice(7):normalized,matched=relative5.match(PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN);if(!matched)return null;return{runId:matched[1],relativePath:relative5}}async function readBoundedSwarmRegularFile(directory,relativePath,maxBytes,label){let absPath=validateSwarmPath(directory,relativePath),swarmRoot=path15.resolve(directory,".swarm"),rootStat,artifactStat;try{rootStat=await fsp3.lstat(swarmRoot,{bigint:!0}),artifactStat=await fsp3.lstat(absPath,{bigint:!0})}catch(error49){if(error49.code==="ENOENT")throw Error(`BLOCKED: ${label} "${relativePath}" does not exist`);throw error49}if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error(`BLOCKED: ${label} root must be a real project .swarm directory`);if(artifactStat.isSymbolicLink()||!artifactStat.isFile())throw Error(`BLOCKED: ${label} must be a bounded regular file`);if(artifactStat.size>BigInt(maxBytes))throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);let[realRoot,realArtifact]=await Promise.all([fsp3.realpath(swarmRoot),fsp3.realpath(absPath)]),relativeRealPath=path15.relative(realRoot,realArtifact);if(relativeRealPath===""||relativeRealPath===".."||relativeRealPath.startsWith(`..${path15.sep}`)||path15.isAbsolute(relativeRealPath))throw Error(`BLOCKED: ${label} escapes the project .swarm directory`);await _test_exports.beforeBoundedSwarmFileOpen?.();let handle=await fsp3.open(realArtifact,"r");try{let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile()||openedStat.size>BigInt(maxBytes)||!sameBigIntFileIdentity(artifactStat,openedStat))throw Error(`BLOCKED: ${label} changed during its bounded read`);let[postRootStat,postArtifactStat,postRealRoot,postRealArtifact]=await Promise.all([fsp3.lstat(swarmRoot,{bigint:!0}),fsp3.lstat(absPath,{bigint:!0}),fsp3.realpath(swarmRoot),fsp3.realpath(absPath)]),postRelativeRealPath=path15.relative(postRealRoot,postRealArtifact);if(postRootStat.isSymbolicLink()||!postRootStat.isDirectory()||!sameBigIntFileIdentity(rootStat,postRootStat)||postArtifactStat.isSymbolicLink()||!postArtifactStat.isFile()||!sameBigIntFileIdentity(artifactStat,postArtifactStat)||!sameBigIntFileIdentity(openedStat,postArtifactStat)||normalizeComparableFsPath(realRoot)!==normalizeComparableFsPath(postRealRoot)||normalizeComparableFsPath(realArtifact)!==normalizeComparableFsPath(postRealArtifact)||postRelativeRealPath===""||postRelativeRealPath===".."||postRelativeRealPath.startsWith(`..${path15.sep}`)||path15.isAbsolute(postRelativeRealPath))throw Error(`BLOCKED: ${label} changed or escaped during its bounded read`);let buffer=Buffer.allocUnsafe(maxBytes+1),{bytesRead}=await handle.read(buffer,0,maxBytes+1,0);if(bytesRead>maxBytes)throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);return buffer.subarray(0,bytesRead).toString("utf8")}finally{await handle.close()}}function sameBigIntFileIdentity(left,right){return left.dev===right.dev&&left.ino===right.ino}function normalizeComparableFsPath(value){let normalized=path15.normalize(path15.resolve(value));return process.platform==="win32"?normalized.toLowerCase():normalized}async function readPrReviewFeedbackHandoffArtifact(directory,relativePath){let raw=await readBoundedSwarmRegularFile(directory,relativePath,PR_REVIEW_HANDOFF_MAX_BYTES,"PR_REVIEW feedback handoff artifact"),parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is not valid JSON")}let parsed=PrReviewFeedbackHandoffArtifactSchema.safeParse(parsedJson);if(!parsed.success)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is invalid");if(new Set(parsed.data.finding_ids).size!==parsed.data.finding_ids.length)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact contains duplicate finding IDs");return{artifact:parsed.data,digest:createHash8("sha256").update(raw,"utf8").digest("hex")}}async function readActionableReviewFindingIds(directory,state,runId){let expectedPath=`pr-review/${runId}/findings.jsonl`;if(state.prReviewFindingsPath!==expectedPath)throw Error(`BLOCKED: PR_REVIEW transition requires the exact final findings artifact "${expectedPath}"`);let raw=await readBoundedSwarmRegularFile(directory,expectedPath,PR_REVIEW_FINDINGS_MAX_BYTES,"PR_REVIEW final findings artifact"),latest=new Map;for(let[index,line]of raw.split(/\r?\n/).entries()){if(!line.trim())continue;let value;try{value=JSON.parse(line)}catch{throw Error(`BLOCKED: PR_REVIEW final findings artifact contains invalid JSON at line ${index+1}`)}let parsed=PrReviewFindingProjectionSchema.safeParse(value);if(!parsed.success)throw Error(`BLOCKED: PR_REVIEW final findings artifact contains an invalid record at line ${index+1}`);latest.set(parsed.data.finding_id,parsed.data)}return[...latest.values()].filter((record2)=>record2.status==="CONFIRMED"&&record2.next_action==="handoff_to_feedback").map((record2)=>record2.finding_id).sort()}function canonicalGitHubPrUrl(value){try{let url2=new URL(value);if(url2.protocol!=="https:"||url2.hostname.toLowerCase()!=="github.com")return null;let matched=url2.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(!matched)return null;let prNumber=Number(matched[3]);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return`github.com/${matched[1].toLowerCase()}/${matched[2].toLowerCase()}/pull/${prNumber}`}catch{return null}}function workflowIdentity(state){return state.workflowInstanceId??`legacy-${createHash8("sha256").update(`${state.sessionID}\x00${state.mode}\x00${state.activatedAt}`).digest("hex").slice(0,32)}`}function sameHandoffIds(left,right){let normalizedLeft=[...new Set(left)].sort(),normalizedRight=[...new Set(right)].sort();return sameStringArray(normalizedLeft,normalizedRight)}function assertSamePrFeedbackHandoff(state,relativePath,read,requestedPrUrl){let existing=state.prFeedbackReviewHandoff;if(!existing)throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK without persisted review handoff provenance`);let artifactPr=canonicalGitHubPrUrl(read.artifact.pr_url),requestedPr=requestedPrUrl?canonicalGitHubPrUrl(requestedPrUrl):artifactPr;if(!artifactPr||requestedPrUrl&&requestedPr!==artifactPr||existing.path!==relativePath||existing.runId!==read.artifact.run_id||existing.digest!==read.digest||existing.sourcePrHeadSha.toLowerCase()!==read.artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(existing.prUrl)!==artifactPr||!sameHandoffIds(existing.findingIds,read.artifact.finding_ids))throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK for a different handoff or PR`)}async function assertPrReviewTerminalReady(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");await assertPrReviewCleanCheckout(directory,"PR_REVIEW");let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state.sessionID);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: PR_REVIEW transition has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`);let ctx=await createPrReviewGateContext(directory,state);if(await assertPrReviewBaseCoverageSettled(directory,sessionID,ctx),!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW transition requires a persisted trigger evaluation artifact");if((state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);let criticInventory=derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,"completePrWorkflow critic-coverage gate");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",ctx)}let requiredBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state.prReviewArtifactBoundaries??[]),missing=requiredBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state.prReviewFindingsPath||missing.length>0)throw Error(`BLOCKED: PR_REVIEW transition requires durable findings checkpoints; missing: ${missing.join(", ")||"findings path"}`);if(state.prReviewHandoffRequired&&!state.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact");return state}async function transitionPrReviewToFeedback(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID),normalizedHandoff=normalizePrReviewFeedbackHandoffPath(request.handoffPath);if(!normalizedHandoff||normalizedHandoff.runId!==request.runId)throw Error("BLOCKED: PR-feedback continuation must use .swarm/pr-review/<run_id>/feedback-handoff.json");let preliminaryRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath),artifact=preliminaryRead.artifact,artifactPr=canonicalGitHubPrUrl(artifact.pr_url),requestedPr=request.prUrl?canonicalGitHubPrUrl(request.prUrl):null;if(!artifactPr||request.prUrl&&requestedPr!==artifactPr)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested GitHub PR URL");if(artifact.run_id!==request.runId)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested review run");let preliminary=await readPrWorkflowGateState(directory,normalizedSessionID);if(preliminary?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(preliminary,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),preliminary;let sourceIdentity,sourceRevision=0,provenance;if(preliminary){if(preliminary.mode!=="PR_REVIEW")throw wrongModeError(preliminary,"PR_REVIEW");let ready=await assertPrReviewTerminalReady(directory,normalizedSessionID);if(workflowIdentity(ready)!==workflowIdentity(preliminary)||ready.revision!==preliminary.revision||ready.mode!=="PR_REVIEW"||ready.prReviewHandoffPath!==normalizedHandoff.relativePath||ready.prReviewArtifactRunId!==request.runId||!ready.prHeadSha||ready.prHeadSha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(artifact.pr_url)!==canonicalGitHubPrUrl(request.prUrl??artifact.pr_url))throw Error("BLOCKED: PR_REVIEW feedback handoff does not match the terminal active review state");let actionableIds=await readActionableReviewFindingIds(directory,ready,request.runId);if(!sameHandoffIds(actionableIds,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff finding IDs do not match the authoritative final findings ledger");sourceIdentity=workflowIdentity(ready),sourceRevision=ready.revision,provenance="active-review-v1"}else{if(!request.prUrl)throw Error("BLOCKED: continuing a completed PR_REVIEW requires an explicit GitHub PR URL");sourceIdentity=`external-${preliminaryRead.digest.slice(0,32)}`,provenance="external-v1"}return await _test_exports.beforePrFeedbackTransitionLock?.(),withSessionStateMutation(directory,normalizedSessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(current?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(current,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),current;if(provenance==="active-review-v1"){if(!current||current.mode!=="PR_REVIEW"||workflowIdentity(current)!==sourceIdentity||current.revision!==sourceRevision||current.prHeadSha?.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||current.prReviewArtifactRunId!==request.runId||current.prReviewHandoffPath!==normalizedHandoff.relativePath)throw Error("BLOCKED: PR_REVIEW state changed while validating the feedback handoff; retry from current state")}else if(current)throw Error("BLOCKED: another PR workflow became active while validating the external handoff");let lockedRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath);if(lockedRead.digest!==preliminaryRead.digest)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");if(artifactPr!==canonicalGitHubPrUrl(lockedRead.artifact.pr_url)||lockedRead.artifact.run_id!==request.runId||lockedRead.artifact.pr_head_sha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||!sameHandoffIds(lockedRead.artifact.finding_ids,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");let timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:sourceRevision,workflowInstanceId:randomUUID3(),sessionID:normalizedSessionID,mode:"PR_FEEDBACK",activatedAt:timestamp,updatedAt:timestamp,prFeedbackReviewHandoff:{path:normalizedHandoff.relativePath,runId:lockedRead.artifact.run_id,sourcePrHeadSha:lockedRead.artifact.pr_head_sha.toLowerCase(),prUrl:lockedRead.artifact.pr_url,findingIds:[...new Set(lockedRead.artifact.finding_ids)].sort(),digest:preliminaryRead.digest,sourceWorkflowInstanceId:sourceIdentity,provenance},prFeedbackTargetUrl:artifact.pr_url};return writeStateWhileLocked(directory,nextState,{replaceWorkflowInstanceId:provenance==="active-review-v1"?current?.workflowInstanceId:void 0})})}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,shellPermissionEnvelope=null;if(isShellTool&&command.length>0){let trackingFetchTarget=state.prHeadSha?await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state.prHeadSha,allowFetch:!state.prHeadSha,allowTrackingFetch:Boolean(state.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let trustedCapability=getPrWorkflowToolCapability(normalizedTool,state.mode),isNamedReadOnlyTool=trustedCapability!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{}),isRecoverySafeEvidenceTool=trustedCapability==="observe"&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{});if(state.checkoutRecovery){if(isRecoverySafeEvidenceTool||isReadOnlyShell||normalizedTool==="abort_pr_workflow"||normalizedTool==="pr_workflow_status"||normalizedTool==="prepare_pr_workflow_checkout")return;throw Error(`BLOCKED: ${state.mode} requires manual Git recovery before controller work can continue. code=${state.checkoutRecovery.code} retryable=false required_action=${state.checkoutRecovery.requiredAction}`)}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)),stderrMergeNormalizedCommand=command.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"").trim(),isCanonicalReviewCheckout=/^git\s+switch\s+--detach\s+[0-9a-f]{40,64}$/i.test(stderrMergeNormalizedCommand),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"),blockedShellDiagnosis=isShellTool&&command&&!isReadOnlyShell&&shellPermissionEnvelope?` ${describeBlockedPrReviewShellCommand(command,shellPermissionEnvelope)}`:"";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, run `git rev-parse --verify <full_pr_head_sha>^0`, run `git cat-file -t <full_pr_head_sha>` (which must print `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`."+blockedShellDiagnosis);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"+describePrWorkflowControllerToolNames(state.mode)+blockedShellDiagnosis)}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"+describePrWorkflowControllerToolNames(state.mode));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&&normalizedTool==="prepare_pr_workflow_checkout")return;if(!state.prHeadSha&&isDetachedFeedbackCheckout&&!isCanonicalReviewCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref. Other detached refs are not accepted");if(!state.prHeadSha&&isCanonicalReviewCheckout)return;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 should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref");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 laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state.sessionID);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: ${expectedMode} completion has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`);if(expectedMode==="PR_REVIEW"){let readyState=await assertPrReviewTerminalReady(directory,sessionID);if(workflowIdentity(readyState)!==workflowIdentity(state)||readyState.revision!==state.revision)throw Error("BLOCKED: PR_REVIEW state changed while checking terminal readiness; retry from current state")}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");let commitCount=await _test_exports.resolveCommitCountSinceAsync(directory,state.prHeadSha,localHead);if(commitCount===0){if(localHead!==state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK zero-descendant completion requires HEAD to equal the immutable intake head (history diverged; resolve it or rebind via rebind_pr_feedback_head)");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK zero-descendant completion requires a clean index and working tree");let classifications=readSettledFeedbackClassifications(directory,readyState),inventory=readyState.prFeedbackInventory??[],offenders=inventory.filter((itemId)=>!classifications.has(itemId)||!FEEDBACK_NO_CHANGE_CLASSIFICATIONS.has(classifications.get(itemId)));if(offenders.length>0)throw Error(`BLOCKED: PR_FEEDBACK zero-commit completion requires every inventory item verified as a no-change outcome (DISPROVED, PRE_EXISTING, NEEDS_MORE_EVIDENCE, or NEEDS_USER_DECISION); offending items: ${offenders.slice(0,10).join(", ")}. Items with confirmed content changes must follow the exactly-one-reviewed-commit path.`);try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp3.appendFile(eventsPath,`${JSON.stringify({type:"pr_feedback_verified_no_change",timestamp:isoNow(),sessionID:state.sessionID,prHeadSha:state.prHeadSha,items:inventory.length})}
|
|
199
|
+
`,"utf-8")}catch{}return await clearPrWorkflowGateState(directory,sessionID,readyState.revision),"verified-no-change"}if(commitCount!==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"}function noActiveGateError(sessionID){return 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:*".`)}async function requireAnyActiveState(directory,sessionID){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)throw noActiveGateError(sessionID);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,"PR_REVIEW"),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 describePrWorkflowControllerToolNames(mode){let modeTools=mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS:PR_FEEDBACK_CONTROLLER_TOOLS,names=[...PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,...modeTools].sort((a,b)=>a.localeCompare(b));return` Allowed controller tools for ${mode}: ${names.join(", ")}. Observe current state read-only with the pr_workflow_status tool.`}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 normalizePrWorkflowShellCommand(command){let normalized=command.trim(),withoutTrailingMerge=normalized.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"");if(withoutTrailingMerge!==normalized)normalized=withoutTrailingMerge.trim();let strippedCdPrefix=!1;for(let index=0;index<PR_WORKFLOW_MAX_CD_PREFIX_STRIPS;index+=1){let next=normalized.replace(PR_WORKFLOW_CD_PREFIX_PATTERN,"");if(next===normalized)break;normalized=next.trim(),strippedCdPrefix=!0}return{normalized,strippedCdPrefix}}function isAllowedPrWorkflowReadOnlyShell(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," ");if(!normalized)return!1;if(hasUnsafeShellControlSyntax(command))return!1;if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))return!1;let gitMatch=normalized.match(PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN);if(gitMatch?.[1]){if(PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN.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|which|where)(?:\s|$)/i.test(normalized)}function describeBlockedPrReviewShellCommand(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," "),gitMatch=normalized.match(PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN),pointer=" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool.",detail,syntaxViolation=describeShellSyntaxViolation(command);if(syntaxViolation)detail=syntaxViolation;else if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))detail="Reason: cd-prefix-on-checkout-verb. Run fetch/checkout/switch/branch or `gh pr checkout` bare, with no `cd <dir> &&` prefix.";else if(PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN.test(normalized)&&gitMatch?.[1]&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))detail="Reason: git -C on a state transition. Run fetch/checkout/switch/branch from the target directory, not via `git -C <dir>`.";else if(!options.allowFetch&&gitMatch?.[1]&&/^fetch(?:\s|$)/i.test(gitMatch[1]))detail=options.allowTrackingFetch?"Reason: bound-fetch-restriction. After the PR head is bound only the exact bound remote-tracking fetch is allowed; read remote state via gh_evidence otherwise.":"Reason: bound-fetch-restriction. Fetch is not permitted in this bound state; read remote state via gh_evidence instead.";else if(gitMatch?.[1]||/^git(?:\s|$)/i.test(normalized))detail="Reason: unlisted git verb. Allowed git reads: status/log/show/diff/rev-parse/merge-base/ls-files/grep/blame/cat-file/for-each-ref, `branch` with listing flags only, `stash list`, `worktree list`, `remote -v`, `config --get`.";else if(/^gh(?:\s|$)/i.test(normalized))detail="Reason: unlisted gh form. Allowed gh reads: pr view/diff/checks/status/list, run view/list/watch, issue view/list, search, api GET. If gh is missing, fetch the api.github.com REST URL with the web fetch tool.";else detail="Reason: unlisted binary. Allowed: rg/grep/cat/ls/dir/pwd/which/where plus read-only git/gh intake.";return detail+" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool."}function classifyPrWorkflowShellSyntax(command){let{normalized:inner}=normalizePrWorkflowShellCommand(command),compact=inner.replace(/\s+/g," ").trim();if(!compact)return{unsafe:!0,reason:"compound-syntax"};if(/\$\(|@\(/.test(inner))return{unsafe:!0,reason:"command-substitution"};if(/\\"|\^"/.test(inner))return{unsafe:!0,reason:"ambiguous-escaped-quote"};if(/[\r\n;&<>`]/.test(inner))return{unsafe:!0,reason:"compound-syntax"};let tokens=[],current="",quoted=!1,quote=null,pipeIsDoubleQuoted=!0,flush=()=>{if(current.length>0||quoted)tokens.push({value:current,quoted,pipeIsDoubleQuoted});current="",quoted=!1,quote=null,pipeIsDoubleQuoted=!0};for(let index=0;index<inner.length;index+=1){let ch=inner[index];if(quote===null){if(/\s/.test(ch)){flush();continue}if(ch==="'"||ch==='"'){quoted=!0,quote=ch;continue}if(ch===";"||ch==="<"||ch===">"||ch==="`"||ch==="|")return{unsafe:!0,reason:"compound-syntax"};if(ch==="$"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};if(ch==="@"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};current+=ch;continue}if(quote==="'"){if(ch==="'"){quote=null;continue}if(ch==="|")pipeIsDoubleQuoted=!1;current+=ch;continue}if(ch==='"'){quote=null;continue}if(ch==="\\"&&inner[index+1]==='"')return{unsafe:!0,reason:"ambiguous-escaped-quote"};if(ch==="`")return{unsafe:!0,reason:"command-substitution"};if(ch==="$"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};if(ch==="@"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};current+=ch}if(quote!==null)return{unsafe:!0,reason:"unmatched-quote"};flush();let pipeTokens=tokens.filter((token)=>token.value.includes("|"));if(pipeTokens.length===0)return{unsafe:!1,reason:null};if(pipeTokens.length!==1||!pipeTokens[0].quoted||!pipeTokens[0].pipeIsDoubleQuoted)return{unsafe:!0,reason:"gh-api-jq-pipe"};let quotedPipeToken=pipeTokens[0];if(!/^gh\s+api(?:\s|$)/i.test(compact))return{unsafe:!0,reason:"gh-api-jq-pipe"};for(let index=0;index<tokens.length;index+=1)if(tokens[index].value==="--jq"&&tokens[index+1]===quotedPipeToken)return{unsafe:!1,reason:null};return{unsafe:!0,reason:"gh-api-jq-pipe"}}function hasUnsafeShellControlSyntax(command){return classifyPrWorkflowShellSyntax(command).unsafe}function describeShellSyntaxViolation(command){let verdict=classifyPrWorkflowShellSyntax(command);if(!verdict.unsafe)return null;switch(verdict.reason){case"unmatched-quote":return"Reason: unmatched quote in the shell command. Close the quote and retry with a single read-only command.";case"ambiguous-escaped-quote":return"Reason: backslash- or caret-escaped double quotes are ambiguous across cmd.exe, PowerShell, and POSIX shells. Use a jq filter that needs no nested double quotes, or use the bounded gh_evidence tool.";case"command-substitution":return"Reason: command-substitution syntax ($() or @()) is not allowed in this read-only gate.";case"gh-api-jq-pipe":return"Reason: literal `|` is only allowed inside a double-quoted `gh api --jq` value; single quotes do not protect pipes under cmd.exe, and every other shape is treated as compound shell syntax.";default:return"Reason: compound-syntax (;, &&, |, <, >, backtick, or $()/@()). Run ONE command per call; a single leading `cd <dir> &&` and a trailing `2>&1` are tolerated for reads only."}}function isSafeStandaloneGitCommit(command){if(hasUnsafeShellControlSyntax(command))return!1;if(/(?:^|\s)--(?:allow-empty|amend)(?:\s|=|$)/i.test(command))return!1;return/^[Gg][Ii][Tt](?:\s+-C(?:=|\s+)(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>`]+))?\s+commit(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s;&|<>`]+))*\s*$/.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|--version|version)(?:\s|$)/i.test(gitArgs))return!0;if(isAllowedReadOnlyGitBranchListing(gitArgs))return!0;if(isAllowedReadOnlyGitStashListing(gitArgs))return!0;if(isAllowedReadOnlyGitWorktreeListing(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 isAllowedReadOnlyGitBranchListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===0||tokens[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:--list|--contains|--merged|--no-merged|--points-at)$/i.test(token)){listingSelectorInEffect=!0;continue}if(/^(?:-a|--all|-r|--remotes|-v|-vv|--verbose|--show-current|--color|--no-color|--column|--no-column|-i|--ignore-case)$/i.test(token)||/^--(?:sort|format|color)=/i.test(token))continue;if(token.startsWith("-"))return!1;if(!listingSelectorInEffect)return!1}return!0}function isAllowedReadOnlyGitStashListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="stash")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--oneline|--patch|-p|--stat|--color|--no-color)$/i.test(token))continue;if(/^--(?:format|pretty)=/i.test(token))continue;return!1}return!0}function isAllowedReadOnlyGitWorktreeListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="worktree")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--verbose|--porcelain|-z)$/i.test(token))continue;return!1}return!0}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+--version$/i.test(command)||/^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 resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest for pr_head_sha "${state.prHeadSha}"; ${describePrWorkflowRevisionDigestFailure(resolved)}`);return resolved.digest}function describePrWorkflowRevisionDigestFailure(failure){let detail=failure.detail?` (${failure.detail})`:"";switch(failure.reason){case"file-cap":return`the changed-file snapshot exceeded REVISION_MAX_FILES${detail}. Reduce the changed-path count (commit or stash generated/vendored output) before retrying`;case"byte-cap":return`the changed-file snapshot exceeded REVISION_MAX_TOTAL_BYTES${detail}. Reduce the changed content size before retrying`;case"buffer-truncated":return`a bounded git enumeration exceeded GIT_SNAPSHOT_MAX_BUFFER${detail}. The changed-path list is too large to enumerate`;case"timeout":return`a bounded git enumeration timed out${detail}. Retry once the working tree is quiescent`;case"git-failed":return`a bounded git enumeration failed${detail}. Verify the checkout is a healthy Git worktree at the recorded head`;case"containment":return`git reported a changed path outside the project root${detail}. Nothing outside the project root may be hashed`;case"read-failed":return`a changed path could not be read${detail}. Resolve the filesystem error before retrying`;default:return`an injected revision-digest seam returned no digest${detail}; production names one of REVISION_MAX_FILES / REVISION_MAX_TOTAL_BYTES / GIT_SNAPSHOT_MAX_BUFFER, a bounded git enumeration timeout, or a read failure`}}async function resolvePrWorkflowRevisionDigestForGate(directory,baseHeadSha){if(_test_exports.resolvePrWorkflowRevisionDigestDetailed!==resolvePrWorkflowRevisionDigestDetailed)return _test_exports.resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);if(_test_exports.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest){let digest2=_test_exports.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return digest2?{ok:!0,digest:digest2}:{ok:!1,reason:"seam-unavailable"}}return resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha)}async function createPrReviewGateContext(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_REVIEW revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_REVIEW could not compute a bounded current-revision digest for pr_head_sha "${state.prHeadSha}"; ${describePrWorkflowRevisionDigestFailure(resolved)}`);return{revisionDigest:resolved.digest}}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 sameStringSet(left,right){let leftSet=new Set(left),rightSet=new Set(right);return leftSet.size===rightSet.size&&[...leftSet].every((v)=>rightSet.has(v))}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,ctx){if(ctx.candidateInventory)return ctx.candidateInventory;let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map,reversedBaseBatches=[...state.prReviewBaseDispatches??[]].reverse(),successfulByBaseBatchId=new Map;for(let batch of reversedBaseBatches)successfulByBaseBatchId.set(batch.batchId,successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest));let laneClassPasses=(state.prReviewDepthTier??"L")==="L"?[(ownedCount)=>ownedCount===1,(ownedCount)=>ownedCount!==1]:[()=>!0];for(let laneIsInClass of laneClassPasses)for(let batch of reversedBaseBatches){let successful=successfulByBaseBatchId.get(batch.batchId)??new Set;for(let lane of batch.lanes){let ownedDimensions=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!laneIsInClass(ownedDimensions.length))continue;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,!0,new Set,ctx.revisionDigest);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)}let degradedSourceKeys=new Set;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 receipt;try{receipt=parsePrReviewTriggerReceipt(triggerArtifact)}catch(error49){throw Error(`BLOCKED: PR_REVIEW trigger evaluation is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}for(let row of receipt.matchedRows)sources.push({batchId:row.source_batch_id,laneId:row.source_lane_id,mode:"swarm-pr-review:micro",workflowLane:row.trigger_id});for(let degradation of receipt.coverageDegradations)degradedSourceKeys.add(`${degradation.source_batch_id}\x00${degradation.source_lane_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.workspace?.prHeadSha!==state.prHeadSha||record2.workspace?.gitHead!==state.prHeadSha)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,ctx.revisionDigest,recordOwnedLanes))continue;if(source.workflowLane&&(!recordOwnedLanes?.includes(source.workflowLane)||!prReviewDiscoveryArtifactCoversLane(artifact.text,source.workflowLane,recordOwnedLanes,source.mode)))continue;resolvedArtifact=!0;let laneKey=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey))extractedLaneKeys.add(laneKey),candidateIds.push(...extractCandidateIds(artifact.text,resolvePrReviewRowFamily(source.workflowLane,source.mode),source.creditedLanes))}if(source.mode==="swarm-pr-review:micro"&&!resolvedArtifact){if(degradedSourceKeys.has(`${source.batchId}\x00${source.laneId}`))continue;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"),ctx.candidateInventory=candidateIds.length>0?candidateIds.sort():["CLEAN-REVIEW"],ctx.candidateInventory}function appendBoundedCandidateIssue(issues,message){if(issues.length<MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1){issues.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return}if(issues.length===MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1)issues.push("additional malformed candidate diagnostics omitted")}function resolvePrReviewRowFamily(workflowLane,mode){if(mode==="swarm-pr-review:base")return"base_explorer";if(mode==="swarm-pr-review:micro"||mode==="swarm-pr-review:council")return"micro_lane";return workflowLane!==void 0&&PR_REVIEW_BASE_DIMENSION_IDS.includes(workflowLane)?"base_explorer":"micro_lane"}function parseCanonicalCandidateRows(text,fallbackFamily){let rows=[],issues=[],headerFamily=null;for(let[index,line]of normalizeCandidateArtifact(text,fallbackFamily).text.split(/\r?\n/).entries()){let fields=splitPipeFields(line).map((field)=>field.trim()),detectedHeaderFamily=candidateHeaderFamily(fields);if(detectedHeaderFamily){headerFamily=detectedHeaderFamily;continue}let explicitMarker=fields[0]==="[CANDIDATE]",markerlessRow=headerFamily!==null&&Boolean(fields[0])&&!fields[0].startsWith("[");if(!explicitMarker&&!markerlessRow)continue;if(explicitMarker&&headerFamily===null){appendBoundedCandidateIssue(issues,`row ${index+1} field header: candidate output must begin with one exact canonical base or micro [CANDIDATE] header`);continue}let family=headerFamily??fallbackFamily,candidateFields=explicitMarker?fields.slice(1):fields,analysis=analyzeCandidateFields(candidateFields,family);if(!analysis.valid){for(let issue2 of analysis.issues)appendBoundedCandidateIssue(issues,`row ${index+1} field ${issue2.field}: ${issue2.message}`);continue}if(!analysis.candidateId||!analysis.workflowLane)continue;rows.push({candidateId:analysis.candidateId,workflowLane:analysis.workflowLane,evidence:candidateFields.slice(2).join("\x00"),lineNumber:index+1})}return{rows,issues}}function extractCandidateIds(text,fallbackFamily,scopeToLanes){let inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);return parseCanonicalCandidateRows(text,fallbackFamily).rows.filter((row)=>inScope(row.workflowLane)).map((row)=>row.candidateId)}function appendCompositionDiagnostic(diagnostics,message){if(diagnostics.length>=MAX_COMPOSITION_DIAGNOSTICS)return;diagnostics.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS))}function prReviewPhaseWindow(state,phase){let all=state.prReviewValidationBatches??[];if(phase==="critic")return all.filter((batch)=>batch.phase==="critic");let latestCouncilIndex=-1;for(let index=0;index<all.length;index++)if(all[index]?.phase==="council")latestCouncilIndex=index;return(latestCouncilIndex>=0?all.slice(latestCouncilIndex+1):all).filter((batch)=>batch.phase==="reviewer")}function reviewerSubagentSessionIds(directory,state){let forbidden=new Set(state.prReviewRetiredReviewerSessionIds??[]);for(let reviewerBatch of(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer"))for(let record2 of findByBatchId(directory,reviewerBatch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)forbidden.add(subagentSessionId)}return forbidden}function batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){let coherence=state.prReviewBatchCoherence?.[batch.batchId];if(coherence)return phase==="critic"||sameStringSet(coherence.validatedInventory,requiredInventory);let declaredItems=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]);if(!sameStringSet(declaredItems,requiredInventory))return!1;let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${phase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds,ctx.revisionDigest,void 0,reviewerClaims);return successful.size===batch.lanes.length&&batch.lanes.every((lane)=>successful.has(lane.workflowLane))}function composePrReviewPhaseVerdicts(directory,state,phase,ctx,exhaustive=!1){let memoized=phase==="reviewer"?ctx.reviewer:ctx.critic;if(memoized&&!exhaustive)return memoized;let requiredInventory=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state,ctx):derivePrReviewCriticInventory(directory,state,ctx),reviewerClaims=phase==="critic"?authoritativeReviewerClaims(directory,state,ctx):void 0,forbiddenSubagentSessionIds=phase==="critic"?reviewerSubagentSessionIds(directory,state):new Set,expectedMode=`swarm-pr-review:${phase}`,window2=prReviewPhaseWindow(state,phase),requiredSet=new Set(requiredInventory),claims=new Map,contributingBatchIds=[],diagnostics=[],satisfiedObligations=new Set,scannedBatches=[];for(let batch of[...window2].reverse()){if(scannedBatches.push(batch),!batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx)){appendCompositionDiagnostic(diagnostics,`${phase} batch "${batch.batchId}" was validated against a different inventory or is not wholly successful legacy state; it contributes no claims`);continue}let coherence=state.prReviewBatchCoherence?.[batch.batchId],contributed=!1;for(let qualified of recordsPassingBatchIntegrity(directory,state,batch.batchId,batch.lanes,expectedMode,batch.validatedAt,!0,forbiddenSubagentSessionIds)){let artifact=loadArtifactPassingLaneIntegrity(directory,state,qualified.record,expectedMode,qualified.expectedWorkflowLane,ctx.revisionDigest);if(!artifact)continue;let declaredItems=qualified.expectedLane.reviewItemIds??[],parsed=parseLaneItemVerdicts(artifact.text,declaredItems,phase,reviewerClaims);if(declaredItems.length>0&&parsed.size===declaredItems.length)satisfiedObligations.add(qualified.expectedWorkflowLane);for(let[itemId,verdict]of parsed){if(!requiredSet.has(itemId)||claims.has(itemId))continue;if(coherence&&!coherence.validatedInventory.includes(itemId))continue;if(phase==="critic"&&coherence&&!criticClaimIsBoundToCurrentReviewerRow(coherence,itemId,reviewerClaims))continue;claims.set(itemId,{batchId:batch.batchId,laneId:qualified.expectedLane.laneId,workflowLane:qualified.expectedWorkflowLane,...verdict}),contributed=!0}}if(contributed)contributingBatchIds.push(batch.batchId);if(!exhaustive&&claims.size===requiredSet.size)break}for(let obligation of new Set(scannedBatches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane)))){if(satisfiedObligations.has(obligation))continue;appendCompositionDiagnostic(diagnostics,`declared ${phase} lane "${obligation}" produced no successful exact artifact`)}let composition={claims,requiredInventory,unclaimed:requiredInventory.filter((itemId)=>!claims.has(itemId)),contributingBatchIds,diagnostics};if(!exhaustive)if(phase==="reviewer")ctx.reviewer=composition;else ctx.critic=composition;return composition}function criticClaimIsBoundToCurrentReviewerRow(coherence,itemId,reviewerClaims){let bound=coherence.reviewerItemBindings?.[itemId],current=reviewerClaims?.get(itemId)?.rowDigest;return Boolean(bound&¤t&&bound===current)}function authoritativeReviewerClaims(directory,state,ctx){let composed=composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx);return composed.unclaimed.length===0?composed.claims:new Map}function criticReviewerItemBindings(directory,state,lanes,ctx){let reviewerClaims=authoritativeReviewerClaims(directory,state,ctx),bindings={};for(let itemId of lanes.flatMap((lane)=>lane.reviewItemIds??[])){let rowDigest=reviewerClaims.get(itemId)?.rowDigest;if(!rowDigest)throw Error(`BLOCKED: PR_REVIEW critic dispatch cannot bind item "${itemId}" to an authoritative reviewer verdict row`);bindings[itemId]=rowDigest}return bindings}function derivePrReviewCriticInventory(directory,state,ctx){return[...authoritativeReviewerVerdictsForGate(directory,state,ctx,"derivePrReviewCriticInventory").entries()].filter(([,verdict])=>verdict.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(verdict.severity)).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state,ctx){let composed=composePrReviewPhaseVerdicts(directory,state,"critic",ctx);if(composed.unclaimed.length>0)return new Map;return new Map([...composed.claims].map(([itemId,claim])=>[itemId,{status:claim.classification,severity:claim.severity}]))}function deriveLatestPrReviewReviewerVerdicts(directory,state,ctx){return new Map([...authoritativeReviewerClaims(directory,state,ctx)].map(([itemId,claim])=>[itemId,{classification:claim.classification,severity:claim.severity}]))}function assertSettledPhaseHasAuthoritativeVerdicts(phase,composed,authoritative,origin){if(composed.unclaimed.length>0)return;if(composed.requiredInventory.length===0)return;let missing=composed.requiredInventory.filter((itemId)=>!authoritative.has(itemId));if(missing.length===0)return;let named=missing.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=missing.length-named.length;throw Error(`BLOCKED: PR_REVIEW internal invariant violated at ${origin}: the ${phase} phase settled over ${composed.requiredInventory.length} required item(s), but its authoritative ${phase} verdict map is `+(authoritative.size===0?"EMPTY":`PARTIAL (${authoritative.size} of ${composed.requiredInventory.length} items)`)+" after successful settlement"+(phase==="reviewer"?"; an empty or partial reviewer verdict map empties the critic inventory, which silently skips the critic-coverage gate and lets CONFIRMED CRITICAL/HIGH findings ship unchallenged":"; an empty or partial critic verdict map silently drops challenges the gate already accepted")+`; missing ${phase} verdicts for: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:""))}function authoritativeReviewerVerdictsForGate(directory,state,ctx,origin){let verdicts=deriveLatestPrReviewReviewerVerdicts(directory,state,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("reviewer",composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx),verdicts,origin),verdicts}function authoritativeCriticVerdictsForGate(directory,state,ctx,origin){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("critic",composePrReviewPhaseVerdicts(directory,state,"critic",ctx),verdicts,origin),verdicts}function derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,origin){let reviewer=composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx);if(reviewer.unclaimed.length>0){let named=reviewer.unclaimed.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=reviewer.unclaimed.length-named.length;throw Error(`BLOCKED: PR_REVIEW internal invariant violated at ${origin}: the critic-coverage decision requires a settled reviewer phase, but ${reviewer.unclaimed.length} reviewer item(s) lack an authenticated verdict; an unsettled reviewer phase derives an empty critic inventory, which would skip critic coverage instead of demanding it; unsettled reviewer items: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:""))}return derivePrReviewCriticInventory(directory,state,ctx)}function boundedLaneValidationValue(value){let rendered;try{rendered=typeof value==="string"?value:JSON.stringify(value)}catch{rendered=String(value)}let sanitized=[...rendered??String(value)].map((character)=>{let code=character.charCodeAt(0);return code<=31||code===127?" ":character}).join("").trim();return sanitized.length<=MAX_LANE_VALIDATION_VALUE_CHARS?sanitized:`${sanitized.slice(0,MAX_LANE_VALIDATION_VALUE_CHARS-1)}…`}function failedLaneValidation(predicate,expected,actual){return{ok:!1,failure:{predicate,expected:boundedLaneValidationValue(expected),actual:boundedLaneValidationValue(actual)}}}function formatPrReviewLaneValidationFailure(failure){return`predicate=${failure.predicate} expected=${JSON.stringify(failure.expected)} actual=${JSON.stringify(failure.actual)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS)}function analyzeLaneRecordResultIntegrity(args2){let{record:record2,result,expected}=args2;if(expected.checkWorkflowLane&&record2.workflowLane!==expected.workflowLane)return failedLaneValidation("record.workflow_lane",expected.workflowLane,record2.workflowLane??"(missing)");if(expected.checkWorkflowLane&&!ownedLaneSetsEqual(record2.ownedWorkflowLanes,expected.ownedWorkflowLanes))return failedLaneValidation("record.owned_workflow_lanes",expected.ownedWorkflowLanes,record2.ownedWorkflowLanes??(record2.workflowLane?[record2.workflowLane]:[]));if(record2.mode!==expected.mode)return failedLaneValidation("record.mode",expected.mode,record2.mode??"(missing)");if(record2.workspace?.prHeadSha!==expected.prHeadSha)return failedLaneValidation("record.pr_head_sha",expected.prHeadSha,record2.workspace?.prHeadSha??"(missing)");if(record2.workspace?.gitHead!==expected.gitHead)return failedLaneValidation("record.git_head",expected.gitHead,record2.workspace?.gitHead??"(missing)");if(args2.requireCompleted&&record2.status!=="completed")return failedLaneValidation("record.status","completed",record2.status);if(result?.outputDegraded===!0)return failedLaneValidation("result.output_degraded","not true",!0);if(result?.transcriptIncomplete===!0)return failedLaneValidation("result.transcript_incomplete","not true",!0);if(result?.truncated===!0)return failedLaneValidation("result.truncated","not true",!0);if((result?.chars??0)<=0)return failedLaneValidation("result.chars","greater than 0",result?.chars??0);if(!result?.digest?.trim())return failedLaneValidation("result.digest","non-empty digest",result?.digest??"(missing)");if(!result?.outputRef?.trim())return failedLaneValidation("result.output_ref","non-empty output ref",result?.outputRef??"(missing)");return{ok:!0}}function analyzePrReviewBatchRecordIntegrity(args2){let validatedAtMs=Date.parse(args2.validatedAt),expectedByLaneId=new Map(args2.expectedLanes.map((lane)=>[lane.laneId,lane])),batchFailure=!Number.isFinite(validatedAtMs)?failedLaneValidation("batch.validated_at","valid ISO timestamp",args2.validatedAt):expectedByLaneId.size!==args2.expectedLanes.length?failedLaneValidation("batch.expected_lane_unique","unique expected lane ids",args2.expectedLanes.map((lane)=>lane.laneId)):null,relevantRecords=args2.records.filter((record2)=>record2.laneId&&expectedByLaneId.has(record2.laneId)),recordsByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record2 of relevantRecords){let laneRecords=recordsByLaneId.get(record2.laneId)??[];laneRecords.push(record2),recordsByLaneId.set(record2.laneId,laneRecords);let sessionId=record2.subagentSessionId?.trim();if(sessionId)recordCountBySubagentSessionId.set(sessionId,(recordCountBySubagentSessionId.get(sessionId)??0)+1)}return args2.expectedLanes.map((expectedLane)=>{let expectedWorkflowLane=expectedLane.workflowLane,expectedOwnedLanes=expectedLane.ownedWorkflowLanes?.length?expectedLane.ownedWorkflowLanes:[expectedWorkflowLane],failed=(failure)=>({ok:!1,expectedLane,expectedWorkflowLane,expectedOwnedLanes,failure});if(batchFailure&&!batchFailure.ok)return failed(batchFailure.failure);let laneRecords=recordsByLaneId.get(expectedLane.laneId)??[];if(laneRecords.length===0)return failed(failedLaneValidation("record.missing","exactly one record",0).failure);if(laneRecords.length!==1)return failed(failedLaneValidation("record.duplicate_lane","exactly one record",laneRecords.length).failure);let record2=laneRecords[0],subagentSessionId=record2.subagentSessionId?.trim();if(!subagentSessionId)return failed(failedLaneValidation("record.subagent_session_id","non-empty child session id",record2.subagentSessionId??"(missing)").failure);if(recordCountBySubagentSessionId.get(subagentSessionId)!==1)return failed(failedLaneValidation("record.duplicate_subagent_session_id","one record per child session",recordCountBySubagentSessionId.get(subagentSessionId)).failure);if(args2.forbiddenSubagentSessionIds.has(subagentSessionId))return failed(failedLaneValidation("record.forbidden_subagent_session_id","child session not reused from a forbidden phase",subagentSessionId).failure);if(record2.createdAt<validatedAtMs)return failed(failedLaneValidation("record.created_at",`at or after ${args2.validatedAt}`,new Date(record2.createdAt).toISOString()).failure);let recordIntegrity=analyzeLaneRecordResultIntegrity({record:record2,result:record2.result,expected:{mode:args2.expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes:expectedOwnedLanes,prHeadSha:args2.expectedPrHeadSha??record2.workspace?.prHeadSha??"",gitHead:args2.expectedPrHeadSha??record2.workspace?.gitHead??"",checkWorkflowLane:args2.checkWorkflowLane},requireCompleted:!0});if(!recordIntegrity.ok)return failed(recordIntegrity.failure);return{ok:!0,record:record2,expectedLane,expectedWorkflowLane,expectedOwnedLanes}})}function recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,diagnostics){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}),analyses=analyzePrReviewBatchRecordIntegrity({batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,records,expectedPrHeadSha:state.prHeadSha});for(let analysis of analyses)if(!analysis.ok&&diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${batchId} lane=${analysis.expectedLane.laneId} workflow_lane=${analysis.expectedWorkflowLane}: ${formatPrReviewLaneValidationFailure(analysis.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return analyses.filter((analysis)=>analysis.ok)}function successfulObligationsFromExactBatch(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest,diagnostics,reviewerClaims){let successful=new Set;for(let qualified of recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics))if(workflowArtifactHasContractMarker(directory,state,qualified.record,expectedMode,qualified.expectedWorkflowLane,qualified.expectedLane.reviewItemIds,expectedRevisionDigest,qualified.expectedOwnedLanes,diagnostics,reviewerClaims))for(let obligation of qualified.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 analyzeLaneArtifactIntegrity(args2){let{record:record2,result,artifact,expected}=args2;if(!artifact)return failedLaneValidation("artifact.readable","readable stored artifact","missing or invalid");if(artifact.ref!==result.outputRef?.trim())return failedLaneValidation("artifact.ref",result.outputRef?.trim()??"(missing)",artifact.ref);if(artifact.batchId!==record2.batchId)return failedLaneValidation("artifact.batch_id",record2.batchId??"(missing)",artifact.batchId);if(artifact.laneId!==record2.laneId)return failedLaneValidation("artifact.lane_id",record2.laneId??"(missing)",artifact.laneId);if(artifact.mode!==expected.mode)return failedLaneValidation("artifact.mode",expected.mode,artifact.mode??"(missing)");if(artifact.sessionId!==record2.subagentSessionId)return failedLaneValidation("artifact.session_id",record2.subagentSessionId,artifact.sessionId??"(missing)");if(artifact.parentSessionId!==record2.parentSessionId)return failedLaneValidation("artifact.parent_session_id",record2.parentSessionId,artifact.parentSessionId??"(missing)");if(artifact.agent!==record2.swarmPrefixedAgent)return failedLaneValidation("artifact.agent",record2.swarmPrefixedAgent,artifact.agent);if(artifact.role!==record2.normalizedAgent)return failedLaneValidation("artifact.role",record2.normalizedAgent,artifact.role);if(artifact.source!=="collect_lane_results")return failedLaneValidation("artifact.source","collect_lane_results",artifact.source);if(artifact.workflowLane!==record2.workflowLane)return failedLaneValidation("artifact.workflow_lane_record",record2.workflowLane??"(missing)",artifact.workflowLane??"(missing)");if(artifact.workflowLane!==expected.workflowLane)return failedLaneValidation("artifact.workflow_lane_expected",expected.workflowLane,artifact.workflowLane??"(missing)");if(artifact.prHeadSha!==expected.prHeadSha)return failedLaneValidation("artifact.pr_head_sha",expected.prHeadSha,artifact.prHeadSha??"(missing)");if(artifact.gitHead!==expected.gitHead)return failedLaneValidation("artifact.git_head",expected.gitHead,artifact.gitHead??"(missing)");if(artifact.revisionDigest!==expected.revisionDigest)return failedLaneValidation("artifact.revision_digest",expected.revisionDigest,artifact.revisionDigest??"(missing)");if(expected.reviewScope!==void 0&&record2.workspace?.scope!==expected.reviewScope)return failedLaneValidation("record.scope",expected.reviewScope,record2.workspace?.scope??"(missing)");if(expected.reviewScope!==void 0&&artifact.scope!==expected.reviewScope)return failedLaneValidation("artifact.scope",expected.reviewScope,artifact.scope??"(missing)");if(artifact.digest!==result.digest)return failedLaneValidation("artifact.digest",result.digest,artifact.digest);if(artifact.chars!==result.chars)return failedLaneValidation("artifact.chars",result.chars,artifact.chars);return{ok:!0}}function loadArtifactPassingLaneIntegrity(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){let ref=record2.result?.outputRef?.trim();if(!ref)return null;let artifact=readLaneOutput(directory,ref)?.artifact??null,expectedReviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0,integrity=analyzeLaneArtifactIntegrity({record:record2,result:record2.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,prHeadSha:record2.workspace?.prHeadSha??"",gitHead:record2.workspace?.gitHead??"",revisionDigest:expectedRevisionDigest,reviewScope:expectedReviewScope}});if(!integrity.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(integrity.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return null}return artifact}function workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes,diagnostics,reviewerClaims){let ref=record2.result?.outputRef?.trim(),artifact=expectedRevisionDigest?loadArtifactPassingLaneIntegrity(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics):null;if(!artifact)return!1;if(expectedMode==="swarm-pr-review:reviewer"||expectedMode==="swarm-pr-review:critic"){let phase=expectedMode==="swarm-pr-review:reviewer"?"reviewer":"critic",parsed=parseLaneItemVerdicts(artifact.text,reviewItemIds??[],phase,reviewerClaims);return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>parsed.has(itemId)))}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])));if(expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"){let reviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0,validation=validatePrReviewDiscoveryLaneCompletion({record:record2,result:record2.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes,prHeadSha:state.prHeadSha??"",gitHead:state.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",reviewScope}});if(!validation.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(validation.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return!1}return!0}let coveredLanes=ownedWorkflowLanes?.length?ownedWorkflowLanes:[expectedWorkflowLane],coverageAnalyses=coveredLanes.map((coveredLane)=>({coveredLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,coveredLane,coveredLanes,expectedMode)}));if(coverageAnalyses.some(({analysis})=>!analysis.covered)){for(let{coveredLane,analysis}of coverageAnalyses){if(analysis.covered||analysis.issues.length===0)continue;if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS){let diagnostic=`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${coveredLane} output_ref=${ref} digest=${record2.result?.digest??"(missing)"}: ${analysis.issues.join("; ")}`;diagnostics.push(diagnostic.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS))}}return!1}if(coveredLanes.length>1){let seenEvidence=new Map;for(let coveredLane of coveredLanes){let evidence2=extractLaneCoverageEvidenceText(artifact.text,coveredLane,coveredLanes,expectedMode);if(evidence2===null)continue;if(seenEvidence.get(evidence2))return!1;seenEvidence.set(evidence2,coveredLane)}}return!0}function analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){let fallbackFamily=resolvePrReviewRowFamily(expectedWorkflowLane,mode),issues=[],normalized=normalizeCandidateArtifact(text,fallbackFamily),canonicalText=normalized.text,repairKinds=normalized.repairKinds,salvaged=repairKinds.length>0,header=selectCandidateHeader(canonicalText.split(/\r?\n/));if(header===null||!header.markerBearing||header.family!==fallbackFamily)return appendBoundedCandidateIssue(issues,`field header: expected one exact canonical ${fallbackFamily} [CANDIDATE] header before discovery rows`),{covered:!1,evidence:null,issues,salvaged,repairKinds,failurePredicate:"discovery.header"};let parsed=parseCandidates({output_ref:"pr-workflow:discovery-artifact",batchId:"pr-workflow",laneId:expectedWorkflowLane,agent:"explorer",role:"explorer",digest:"0".repeat(64),text:canonicalText,artifact_status:"ok",source:"collect_lane_results",produced_at:"1970-01-01T00:00:00.000Z"},{accept_partial:!1,accept_degraded:!1,degraded:!1,row_format_version:1,producer:"swarm-pr-review",expected_family:fallbackFamily,...fallbackFamily==="base_explorer"?{expected_lane:expectedWorkflowLane,expected_lanes:[...ownedWorkflowLanes]}:{expected_micro_lane:expectedWorkflowLane,expected_micro_lanes:[...ownedWorkflowLanes]}});if(parsed.error)appendBoundedCandidateIssue(issues,parsed.error);for(let detail of parsed.diagnostics.parse_error_details)appendBoundedCandidateIssue(issues,`row ${detail.row_index+1} field ${detail.field}: ${detail.message}`);let hasParseFailure=Boolean(parsed.error)||parsed.diagnostics.parse_error_details.length>0,extractedCandidateIds=parseCanonicalCandidateRows(canonicalText,fallbackFamily).rows.map((row)=>row.candidateId);if(new Set(extractedCandidateIds).size!==extractedCandidateIds.length)return{covered:!1,evidence:null,issues,salvaged,repairKinds,failurePredicate:"discovery.row"};let matchingCandidate=parsed.candidates.find((candidate)=>(candidate.lane??candidate.micro_lane)===expectedWorkflowLane);if(matchingCandidate)return{covered:!0,evidence:[matchingCandidate.severity,matchingCandidate.category,matchingCandidate.file_line,matchingCandidate.claim,matchingCandidate.evidence_summary,matchingCandidate.impact_context??matchingCandidate.invariant_violated,matchingCandidate.confidence].join("\x00"),issues,salvaged,repairKinds};let clean=parsed.clean_attestation;if(clean&&(clean.row_format_family==="base_explorer"?clean.lane:clean.micro_lane)===expectedWorkflowLane)return{covered:!0,evidence:`${clean.coverage_scope}\x00${clean.evidence}`,issues,salvaged,repairKinds};return{covered:!1,evidence:null,issues,salvaged,repairKinds,failurePredicate:hasParseFailure?"discovery.row":"discovery.coverage"}}function validatePrReviewDiscoveryLaneCompletion(input){let ownedWorkflowLanes=input.expected.ownedWorkflowLanes?.length?[...input.expected.ownedWorkflowLanes]:[input.expected.workflowLane],recordIntegrity=analyzeLaneRecordResultIntegrity({record:input.record,result:input.result,expected:{mode:input.expected.mode,workflowLane:input.expected.workflowLane,ownedWorkflowLanes,prHeadSha:input.expected.prHeadSha,gitHead:input.expected.gitHead,checkWorkflowLane:input.expected.checkWorkflowLane??!0},requireCompleted:!1});if(!recordIntegrity.ok)return recordIntegrity;let artifactIntegrity=analyzeLaneArtifactIntegrity({record:input.record,result:input.result,artifact:input.artifact,expected:{mode:input.expected.mode,workflowLane:input.expected.workflowLane,prHeadSha:input.expected.prHeadSha,gitHead:input.expected.gitHead,revisionDigest:input.expected.revisionDigest,reviewScope:input.expected.reviewScope}});if(!artifactIntegrity.ok)return artifactIntegrity;let artifact=input.artifact,analyses=ownedWorkflowLanes.map((workflowLane)=>({workflowLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,workflowLane,ownedWorkflowLanes,input.expected.mode)})),salvagedLanes=[];for(let{workflowLane,analysis}of analyses){if(!analysis.covered)continue;if(!analysis.salvaged&&analysis.issues.length===0)continue;salvagedLanes.push(workflowLane);let reason=analysis.repairKinds.length>0?`structural repairs applied: ${analysis.repairKinds.join(", ")}`:"one or more rows were dropped as malformed or out-of-ownership";warn(`[pr-workflow-gate] discovery artifact salvaged: batch=${input.record.batchId??"(missing)"} lane=${input.record.laneId??"(missing)"} workflow_lane=${workflowLane} — ${reason}; retained coverage from the valid rows. Dropped-row diagnostics: ${analysis.issues.join("; ")||"(none)"}`)}let failedCoverage=analyses.find(({analysis})=>!analysis.covered);if(failedCoverage)return failedLaneValidation(failedCoverage.analysis.failurePredicate??"discovery.coverage",`one valid ${input.expected.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane"} [CANDIDATE] row or [CLEAN] attestation for ${failedCoverage.workflowLane}`,failedCoverage.analysis.issues.join("; ")||"no matching lane row");if(ownedWorkflowLanes.length>1){let seenEvidence=new Map;for(let{workflowLane,analysis}of analyses){if(analysis.evidence===null)continue;let priorLane=seenEvidence.get(analysis.evidence);if(priorLane)return failedLaneValidation("discovery.duplicate_evidence","distinct evidence for every owned workflow lane",`${priorLane} and ${workflowLane} share evidence`);seenEvidence.set(analysis.evidence,workflowLane)}}return salvagedLanes.length>0?{ok:!0,salvaged:salvagedLanes}:{ok:!0}}function prReviewDiscoveryArtifactCoversLane(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes,mode).covered}function extractLaneCoverageEvidenceText(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes,mode).evidence}function parseReviewerVerdictFields(text,itemId){let rows=text.split(/\r?\n/).map((line)=>pipeFieldsCapped(line,10)).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 fields}function reviewerVerdictRowDigest(fields){return createHash8("sha256").update(fields.join("\x00")).digest("hex")}function parseLaneItemVerdicts(text,itemIds,phase,reviewerClaims){let parsed=new Map;for(let itemId of itemIds){if(phase==="reviewer"){let fields=parseReviewerVerdictFields(text,itemId);if(!fields)continue;parsed.set(itemId,{classification:fields[2],severity:fields[4],rowDigest:reviewerVerdictRowDigest(fields)});continue}let verdict=parseCriticVerdict(text,itemId,reviewerClaims?.get(itemId)?.severity);if(!verdict)continue;parsed.set(itemId,{classification:verdict.status,severity:verdict.severity})}return parsed}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=text.split(/\r?\n/).map((line)=>pipeFieldsCapped(line,6)).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((line)=>pipeFieldsCapped(line,4)).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 pipeFieldsCapped(line,expectedFieldCount){let fields=pipeFields(line);if(fields.length<=expectedFieldCount)return fields;let capped=[...fields.slice(0,expectedFieldCount-1),fields.slice(expectedFieldCount-1).join("|")];return warn(`[pr-workflow-gate] verdict row pipe tail-merge applied (expected ${expectedFieldCount} fields, received ${fields.length}); leading machine fields preserved, trailing prose fields merged: ${line.slice(0,120)}`),capped}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((line)=>pipeFieldsCapped(line,4)).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])})}function readSettledFeedbackClassifications(directory,state){let classifications=new Map;for(let record2 of state.prFeedbackVerifications??[])for(let ownership of record2.ownership){let ref=findByBatchId(directory,record2.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===ownership.laneId)?.result?.outputRef?.trim(),loaded=ref?readLaneOutput(directory,ref):null;if(!loaded)continue;for(let line of loaded.artifact.text.split(/\r?\n/)){let fields=pipeFieldsCapped(line,4);if(fields[0]!=="[FEEDBACK-VERIFIED]"||fields.length!==4||!fields.slice(1,4).every(Boolean)||!FEEDBACK_CLASSIFICATIONS.has(fields[2]))continue;if(!classifications.has(fields[1]))classifications.set(fields[1],fields[2])}}return classifications}async function persistState(directory,state){let validated=PrWorkflowGateStateSchema.parse(state);await withSessionStateMutation(directory,validated.sessionID,async()=>{let nextState=await writeStateWhileLocked(directory,validated);Object.assign(state,nextState)})}async function writeStateWhileLocked(directory,state,options={}){let validated=PrWorkflowGateStateSchema.parse(state),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");if(current?.workflowInstanceId&&validated.workflowInstanceId!==current.workflowInstanceId&&options.replaceWorkflowInstanceId!==current.workflowInstanceId)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");let nextState=PrWorkflowGateStateSchema.parse({...validated,revision:validated.revision+1}),filePath=workflowGateStatePath(directory,validated.sessionID);return await writeAtomicJson2(directory,filePath,nextState),rememberState(directory,nextState),nextState}function workflowCheckoutMutationLockRelativePath(){return path15.join(WORKFLOW_GATE_DIR,"checkout.lock")}function workflowCheckoutMutationLockPath(directory){return validateSwarmPath(directory,workflowCheckoutMutationLockRelativePath())}function openCheckoutLockFile(lockPath){return fsp3.open(lockPath,"wx")}function removeCheckoutLockFile(lockPath){return fsp3.rm(lockPath)}function checkoutMutationProjectKey(directory){return normalizeComparableFsPath(directory)}async function withCheckoutMutationDeadline(promise2,phase){let timeout;try{return await Promise.race([promise2,new Promise((resolve10)=>{timeout=setTimeout(()=>{resolve10({status:"timeout",error:new PrWorkflowCheckoutMutationTimeoutError(phase)})},_test_exports.checkoutMutationActionTimeoutMs)})])}finally{if(timeout)clearTimeout(timeout)}}async function withPrWorkflowCheckoutMutationLock(directory,action){let key=checkoutMutationProjectKey(directory),previous=pendingCheckoutMutationsByProject.get(key)??Promise.resolve(),release,current=new Promise((resolve10)=>{release=resolve10}),queued=previous.then(()=>current);pendingCheckoutMutationsByProject.set(key,queued);let previousResult=await withCheckoutMutationDeadline(previous.then(()=>({status:"ready"})),"queue");if(previousResult.status==="timeout")throw release(),queued.then(()=>{if(pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}),previousResult.error;let lock;try{lock=await acquireCheckoutMutationLock(directory)}catch(error49){if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key);throw error49}let actionOutcome=Promise.resolve().then(action).then((value)=>({status:"fulfilled",value}),(error49)=>({status:"rejected",error:error49})),outcome=await withCheckoutMutationDeadline(actionOutcome,"action");if(outcome.status==="timeout")throw actionOutcome.then(async()=>{try{await releaseCheckoutMutationLock(lock)}catch{}finally{if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}}),outcome.error;try{if(outcome.status==="rejected")throw outcome.error;return outcome.value}finally{try{await releaseCheckoutMutationLock(lock)}finally{if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}}}async function acquireCheckoutMutationLock(directory){let lockPath=workflowCheckoutMutationLockPath(directory),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await _test_exports.openCheckoutLock(lockPath),lock={ownerToken:randomUUID3(),pid:process.pid,createdAtMs:_test_exports.nowMs()},lockIdentity,writeError;try{let openedStat=await handle.stat({bigint:!0});lockIdentity={dev:openedStat.dev,ino:openedStat.ino},lockIdentity=await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow checkout mutation lock"),await _test_exports.beforeCheckoutLockWrite?.(),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError){if(lockIdentity)await removeCheckoutMutationLockByIdentity(directory,lockPath,lockIdentity,verifiedParent);throw writeError}return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedCheckoutMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow checkout mutation is being handled by another process; retry after that checkout settles")}async function releaseCheckoutMutationLock(lock){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++){try{if(await removeCheckoutMutationLockIfOwned(lock.path,lock.ownerToken)){completedCheckoutLockOwners.delete(lock.path);return}lastError=Error("PR workflow checkout mutation lock ownership changed before release")}catch(error49){lastError=error49}if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}throw rememberCompletedCheckoutLockOwner(lock.path,lock.ownerToken),lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock release failed")}async function reclaimAbandonedCheckoutMutationLock(lockPath){let lock=await readCheckoutMutationLock(lockPath);if(lock){if(lock.pid===process.pid&&completedCheckoutLockOwners.get(lockPath)===lock.ownerToken){let removed=await removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken);if(removed)completedCheckoutLockOwners.delete(lockPath);return removed}if(_test_exports.isProcessAlive(lock.pid))return!1;return removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp3.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp3.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readCheckoutMutationLock(lockPath){let raw;try{raw=await fsp3.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 removeCheckoutMutationLockIfOwned(lockPath,ownerToken){let lock=await readCheckoutMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await _test_exports.removeCheckoutLock(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}async function removeCheckoutMutationLockByIdentity(directory,lockPath,identity,verifiedParent){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await assertClosedSwarmFileIdentity(directory,lockPath,identity,verifiedParent,"PR workflow checkout mutation lock"),await _test_exports.removeCheckoutLock(lockPath);return}catch(error49){if(error49.code==="ENOENT")return;if(lastError=error49,attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock cleanup failed")}function rememberCompletedCheckoutLockOwner(lockPath,ownerToken){completedCheckoutLockOwners.delete(lockPath),completedCheckoutLockOwners.set(lockPath,ownerToken);while(completedCheckoutLockOwners.size>MAX_COMPLETED_CHECKOUT_LOCK_OWNERS){let oldest=completedCheckoutLockOwners.keys().next().value;if(oldest===void 0)break;completedCheckoutLockOwners.delete(oldest)}}async function withSessionStateMutation(directory,sessionID,action){let key=stateCacheKey(directory,sessionID),previous=pendingStateMutationsByProjectSession.get(key)??Promise.resolve(),release,current=new Promise((resolve10)=>{release=resolve10}),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),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await fsp3.open(lockPath,"wx"),lock={ownerToken:randomUUID3(),pid:process.pid,createdAtMs:_test_exports.nowMs()},writeError;try{await _test_exports.beforeSessionStateLockWrite?.(),await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow state mutation lock"),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError)throw await removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken),writeError;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 fsp3.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp3.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp3.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 fsp3.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);return readPrWorkflowGateStateFileFromDisk(filePath,sessionID)}async function readPrWorkflowGateStateFileFromDisk(filePath,stateLabel){let raw;try{raw=await fsp3.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 "${stateLabel}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(!parsed.success)throw Error(`BLOCKED: PR workflow gate state for session "${stateLabel}" is invalid`);return parsed.data}function boundSalvagedSchemaError(message){return message.length<=MAX_SALVAGED_SCHEMA_ERROR_CHARS?message:`${message.slice(0,MAX_SALVAGED_SCHEMA_ERROR_CHARS-1)}…`}async function readPrWorkflowGateStateForRecovery(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),filePath=workflowGateStatePath(directory,normalizedSessionID),raw;try{raw=await fsp3.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 "${normalizedSessionID}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(parsed.success)return{state:parsed.data,salvaged:!1,schemaErrors:[],revisionSalvageable:!0,armedShapeUnreadable:!1};let invalidError=Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid`);if(typeof parsedJson!=="object"||parsedJson===null||Array.isArray(parsedJson))throw invalidError;let rawRecord=parsedJson,salvagedSessionID=exports_external.string().min(1).safeParse(rawRecord.sessionID),salvagedMode=exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]).safeParse(rawRecord.mode);if(!salvagedSessionID.success||!salvagedMode.success)throw invalidError;let salvagedRevision=exports_external.number().int().nonnegative().safeParse(rawRecord.revision),salvagedHead=exports_external.string().min(1).safeParse(rawRecord.prHeadSha),salvagedActivatedAt=exports_external.string().min(1).safeParse(rawRecord.activatedAt),salvagedUpdatedAt=exports_external.string().min(1).safeParse(rawRecord.updatedAt),armedKeyPresent=rawRecord.prFeedbackReadyToPublish!==void 0,salvagedArmed=PrFeedbackReadyToPublishRecordSchema.safeParse(rawRecord.prFeedbackReadyToPublish),salvagedCheckoutRecovery=PrWorkflowCheckoutRecoveryRecordSchema.safeParse(rawRecord.checkoutRecovery),armedShapeUnreadable=armedKeyPresent&&!salvagedArmed.success,schemaErrors=parsed.error.issues.slice(0,MAX_SALVAGED_SCHEMA_ERRORS).map((issue2)=>boundSalvagedSchemaError(`${issue2.path.join(".")||"(root)"}: ${issue2.message}`)),disclosure=`DEGRADED: PR workflow gate state for session "${normalizedSessionID}" failed schema validation and was SALVAGED for recovery only (abort/status; write and completion paths still refuse it). Schema errors: ${schemaErrors.join("; ")}.`+(salvagedRevision.success?"":" state revision unsalvageable.")+(armedShapeUnreadable?" prFeedbackReadyToPublish is present but unreadable; treated as ARMED (fail-closed).":"");return{state:{schemaVersion:GATE_SCHEMA_VERSION,revision:salvagedRevision.success?salvagedRevision.data:0,sessionID:salvagedSessionID.data,mode:salvagedMode.data,activatedAt:salvagedActivatedAt.success?salvagedActivatedAt.data:isoNow(),updatedAt:salvagedUpdatedAt.success?salvagedUpdatedAt.data:isoNow(),...salvagedHead.success?{prHeadSha:salvagedHead.data}:{},...salvagedArmed.success?{prFeedbackReadyToPublish:salvagedArmed.data}:{},...salvagedCheckoutRecovery.success?{checkoutRecovery:salvagedCheckoutRecovery.data}:{}},salvaged:!0,schemaErrors,disclosure,revisionSalvageable:salvagedRevision.success,armedShapeUnreadable}}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=path15.normalize(path15.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 path15.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path15.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=createHash8("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 ensurePrWorkflowSafeParentDirectory(directory,filePath){let swarmRoot=path15.resolve(directory,".swarm"),parentPath=path15.dirname(path15.resolve(filePath)),relativeParent=path15.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path15.sep}`)||path15.isAbsolute(relativeParent))throw Error("BLOCKED: PR workflow atomic destination escapes the project .swarm directory");await fsp3.mkdir(swarmRoot,{recursive:!0});let currentPath=swarmRoot,currentIdentity=await assertSafeDirectory(currentPath,void 0);for(let segment of relativeParent.split(path15.sep).filter(Boolean)){let nextPath=path15.join(currentPath,segment);await _test_exports.beforeSafeDirectoryCreate?.(currentPath,nextPath),await assertSafeDirectory(currentPath,currentIdentity);try{await fsp3.mkdir(nextPath)}catch(error49){if(error49.code!=="EEXIST")throw error49}await assertSafeDirectory(currentPath,currentIdentity);let nextIdentity=await assertSafeDirectory(nextPath,void 0),[realCurrent,realNext]=await Promise.all([fsp3.realpath(currentPath),fsp3.realpath(nextPath)]);if(normalizeComparableFsPath(path15.dirname(realNext))!==normalizeComparableFsPath(realCurrent))throw Error("BLOCKED: PR workflow directory creation escaped the project .swarm tree");currentPath=nextPath,currentIdentity=nextIdentity}let realRoot=await fsp3.realpath(swarmRoot),realParent=await fsp3.realpath(parentPath),relativeRealParent=path15.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path15.sep}`)||path15.isAbsolute(relativeRealParent))throw Error("BLOCKED: PR workflow atomic parent escapes the project .swarm directory");return realParent}async function assertSafeDirectory(directoryPath,expectedIdentity){let stat6=await fsp3.lstat(directoryPath,{bigint:!0});if(stat6.isSymbolicLink()||!stat6.isDirectory()||expectedIdentity&&!sameBigIntFileIdentity(stat6,expectedIdentity))throw Error("BLOCKED: PR workflow .swarm path must be a real directory and must not change during the operation");return{dev:stat6.dev,ino:stat6.ino}}async function assertOpenedSwarmFileIdentity(directory,filePath,handle,expectedParent,label){let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile())throw Error(`BLOCKED: ${label} is not a file`);return await assertClosedSwarmFileIdentity(directory,filePath,openedStat,expectedParent,label),{dev:openedStat.dev,ino:openedStat.ino}}async function assertClosedSwarmFileIdentity(directory,filePath,expectedIdentity,expectedParent,label){if(!expectedIdentity)throw Error(`BLOCKED: ${label} has no identity`);let[stat6,realRoot,realFile,realParent]=await Promise.all([fsp3.lstat(filePath,{bigint:!0}),fsp3.realpath(path15.resolve(directory,".swarm")),fsp3.realpath(filePath),fsp3.realpath(path15.dirname(filePath))]),relativeFile=path15.relative(realRoot,realFile);if(stat6.isSymbolicLink()||!stat6.isFile()||!sameBigIntFileIdentity(stat6,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path15.sep}`)||path15.isAbsolute(relativeFile))throw Error(`BLOCKED: ${label} changed or escaped .swarm`)}async function writeAtomicJson2(directory,filePath,value){let safeParent=await ensurePrWorkflowSafeParentDirectory(directory,filePath),tempPath=`${filePath}.tmp.${process.pid}.${randomUUID3()}`,tempIdentity,lastError;try{let handle=await fsp3.open(tempPath,"wx");try{await _test_exports.beforeAtomicTempWrite?.(),tempIdentity=await assertOpenedSwarmFileIdentity(directory,tempPath,handle,safeParent,"PR workflow atomic temporary file"),await handle.writeFile(JSON.stringify(value,null,2),"utf-8"),await handle.sync()}finally{await handle.close()}await _test_exports.beforeAtomicRename?.(),await assertClosedSwarmFileIdentity(directory,tempPath,tempIdentity,safeParent,"PR workflow atomic temporary file");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;await assertClosedSwarmFileIdentity(directory,filePath,tempIdentity,safeParent,"PR workflow atomic destination file")}finally{try{await fsp3.rm(tempPath,{force:!0})}catch{}}}async function writePrWorkflowAtomicJson(directory,filePath,value){await writeAtomicJson2(directory,filePath,value)}function isoNow(){return new Date().toISOString()}function delay(ms){return new Promise((resolve10)=>setTimeout(resolve10,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_TIER_L_CONSOLIDATED_LANE_FLOOR,PR_REVIEW_MICRO_LANE_FLOORS,GATE_SCHEMA_VERSION=1,MAX_TRACKED_SESSIONS=200,MAX_WORKFLOW_BATCHES=128,MAX_RETIRED_REVIEWER_SESSION_IDS=1024,MAX_RETIRED_CONSOLIDATED_LANES=64,MAX_RETIRED_FEEDBACK_ITEM_OWNERS=4096,MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS=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,MAX_COMPLETED_CHECKOUT_LOCK_OWNERS=64,CHECKOUT_MUTATION_ACTION_TIMEOUT_MS=300000,MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES,MAX_CANDIDATE_ISSUES_PER_ARTIFACT=8,MAX_BASE_COVERAGE_DIAGNOSTICS=8,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS=1000,MAX_LANE_VALIDATION_VALUE_CHARS=240,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",WORKFLOW_GATE_DIR="pr-workflow-gates",trackedStatesByProjectSession,pendingStateMutationsByProjectSession,pendingCheckoutMutationsByProject,completedCheckoutLockOwners,PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrFeedbackInventoryAmendmentRecordSchema,PrReviewValidationBatchRecordSchema,PrReviewBatchCoherenceRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowCheckoutRecoveryRecordSchema,PrFeedbackReviewHandoffRecordSchema,PrWorkflowGateStateSchema,PR_WORKFLOW_STALE_LANE_TIMEOUT_MS,MAX_DISCLOSED_LANE_IDS=10,PR_WORKFLOW_SWEEPABLE_LANE_STATUSES,CAS_ESCAPE_DISCLOSURE="state revision unsalvageable; cleared without compare-and-swap",TERMINAL_FAILED_DELEGATION_STATUSES,MAX_COVER_UNIVERSE_BITS=12,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN,PR_REVIEW_HANDOFF_MAX_BYTES=131072,PR_REVIEW_FINDINGS_MAX_BYTES=10485760,PrReviewFeedbackHandoffArtifactSchema,PrReviewFindingProjectionSchema,_test_exports,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,PR_WORKFLOW_CD_PREFIX_PATTERN,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,PR_WORKFLOW_MAX_CD_PREFIX_STRIPS=3,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN,MAX_COMPOSITION_DIAGNOSTICS=16,MAX_UNCLAIMED_ITEMS_IN_MESSAGE=50,REVIEWER_CLASSIFICATIONS,REVIEWER_EVIDENCE_TYPES,REVIEW_SEVERITIES,CRITIC_STATUSES,FEEDBACK_CLASSIFICATIONS,FEEDBACK_NO_CHANGE_CLASSIFICATIONS,PrWorkflowCheckoutMutationTimeoutError,MAX_SALVAGED_SCHEMA_ERRORS=10,MAX_SALVAGED_SCHEMA_ERROR_CHARS=240;var init_pr_workflow_gate=__esm(()=>{init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_pr_workflow_state();init_tool_metadata();init_logger();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=PR_REVIEW_REQUIRED_TRIGGER_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS={smallMaxChangedLines:100,smallMaxChangedFiles:5,mediumMaxChangedLines:1500,mediumMaxChangedFiles:50},PR_REVIEW_BASE_LANE_FLOORS={S:1,M:3,L:PR_REVIEW_BASE_DIMENSION_IDS.length},PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR=PR_REVIEW_BASE_LANE_FLOORS.M+1,PR_REVIEW_MICRO_LANE_FLOORS={S:1,M:6,L:PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length};MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES=MAX_TRACKED_SESSIONS*2+1,trackedStatesByProjectSession=new Map,pendingStateMutationsByProjectSession=new Map,pendingCheckoutMutationsByProject=new Map,completedCheckoutLockOwners=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),proofKind:exports_external.enum(["defect","metadata","source-proof","conflict","ci","user-decision"]).optional()}).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(),PrFeedbackInventoryAmendmentRecordSchema=exports_external.object({entry:exports_external.string().min(1),amendedAt:exports_external.string().min(1),batch:exports_external.number().int().positive()}).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(),PrReviewBatchCoherenceRecordSchema=exports_external.object({validatedInventory:exports_external.array(exports_external.string().min(1)),reviewerItemBindings:exports_external.record(exports_external.string().min(1),exports_external.string().regex(/^[0-9a-f]{64}$/)).optional()}).passthrough(),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(),PrWorkflowCheckoutRecoveryRecordSchema=exports_external.object({code:exports_external.enum(["UNMERGED_INDEX","GIT_OPERATION_IN_PROGRESS","DIRTY_SUBMODULE","SWARM_STATE_TRACKING_ERROR","GIT_STATE_INDETERMINATE"]),retryable:exports_external.literal(!1),requiredAction:exports_external.string().min(1).max(2000),evidence:exports_external.object({worktreeRoot:exports_external.string().nullable(),gitDir:exports_external.string().nullable(),operations:exports_external.array(exports_external.string().min(1)).max(16),unmergedCodes:exports_external.array(exports_external.string().min(1)).max(16),paths:exports_external.array(exports_external.string()).max(20),trackedCount:exports_external.number().int().nonnegative(),untrackedCount:exports_external.number().int().nonnegative(),pathsTruncated:exports_external.boolean(),detail:exports_external.string().max(1000).optional()}).strict(),detectedAt:exports_external.string().min(1)}).strict(),PrFeedbackReviewHandoffRecordSchema=exports_external.object({path:exports_external.string().min(1).max(512),runId:exports_external.string().min(1).max(128),sourcePrHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),prUrl:exports_external.string().url().max(2000),findingIds:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),digest:exports_external.string().regex(/^[0-9a-f]{64}$/),sourceWorkflowInstanceId:exports_external.string().min(1).max(128),provenance:exports_external.enum(["active-review-v1","external-v1"])}).strict(),PrWorkflowGateStateSchema=exports_external.object({schemaVersion:exports_external.literal(GATE_SCHEMA_VERSION),revision:exports_external.number().int().nonnegative().default(0),workflowInstanceId:exports_external.string().min(1).max(128).optional(),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(),prReviewTriggerLedger:exports_external.array(PrReviewInlineTriggerRowSchema).length(PR_REVIEW_REQUIRED_TRIGGER_IDS.length).optional(),prReviewTriggerEvalPath:exports_external.string().min(1).optional(),prReviewTriggerEvalRunId:exports_external.string().min(1).optional(),prReviewValidationBatches:exports_external.array(PrReviewValidationBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBatchCoherence:exports_external.record(exports_external.string().min(1),PrReviewBatchCoherenceRecordSchema).refine((entries)=>Object.keys(entries).length<=MAX_WORKFLOW_BATCHES,`prReviewBatchCoherence may not exceed ${MAX_WORKFLOW_BATCHES} entries`).optional(),prReviewRetiredReviewerSessionIds:exports_external.array(exports_external.string().min(1)).max(MAX_RETIRED_REVIEWER_SESSION_IDS).optional(),prReviewRetiredConsolidatedLanes:exports_external.array(exports_external.string().min(1)).max(MAX_RETIRED_CONSOLIDATED_LANES).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(),checkoutRecovery:PrWorkflowCheckoutRecoveryRecordSchema.optional(),prFeedbackTargetUrl:exports_external.string().url().max(2000).optional(),prFeedbackReviewHandoff:PrFeedbackReviewHandoffRecordSchema.optional(),prFeedbackInventory:exports_external.array(exports_external.string().min(1)).min(1).optional(),prFeedbackInventoryAmendments:exports_external.array(PrFeedbackInventoryAmendmentRecordSchema).max(MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS).optional(),prFeedbackVerifications:exports_external.array(PrFeedbackVerificationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackRetiredItemOwnership:exports_external.record(exports_external.string().min(1),exports_external.string().min(1)).refine((entries)=>Object.keys(entries).length<=MAX_RETIRED_FEEDBACK_ITEM_OWNERS,`prFeedbackRetiredItemOwnership may not exceed ${MAX_RETIRED_FEEDBACK_ITEM_OWNERS} entries`).optional(),prFeedbackVerification:PrFeedbackVerificationRecordSchema.optional(),prFeedbackStageA:PrFeedbackStageARecordSchema.optional(),prFeedbackGateBatches:exports_external.array(PrFeedbackGateBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackReadyToPublish:PrFeedbackReadyToPublishRecordSchema.optional(),prFeedbackRebindCount:exports_external.number().int().nonnegative().optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();PR_WORKFLOW_STALE_LANE_TIMEOUT_MS=DEFAULT_STALE_DELEGATION_TIMEOUT_MS,PR_WORKFLOW_SWEEPABLE_LANE_STATUSES=new Set(["pending","running"]);TERMINAL_FAILED_DELEGATION_STATUSES=new Set(["completed","error","cancelled","stale"]);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"};PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN=/^pr-review\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/feedback-handoff\.json$/,PrReviewFeedbackHandoffArtifactSchema=exports_external.object({schema_version:exports_external.literal(1),run_id:exports_external.string().min(1).max(128),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),created_at:exports_external.string().datetime(),pr_url:exports_external.string().url().max(2000),finding_ids:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),summary:exports_external.string().min(1).max(20000),provenance:exports_external.array(exports_external.string().min(1).max(4000)).min(1).max(1000)}).strict();PrReviewFindingProjectionSchema=exports_external.object({finding_id:exports_external.string().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"])}).passthrough();_test_exports={minimumConsolidatedLaneCover,analyzePrReviewBatchRecordIntegrity,MAX_COVER_UNIVERSE_BITS,extractCandidateIds,parseCanonicalCandidateRows,resolvePrReviewRowFamily,pipeFieldsCapped,reviewerVerdictRowDigest,workflowGateStateRelativePath,workflowGateStateLockRelativePath,workflowCheckoutMutationLockRelativePath,withPrWorkflowCheckoutMutationLock,resetTrackedStateCache:()=>{trackedStatesByProjectSession.clear(),pendingStateMutationsByProjectSession.clear(),pendingCheckoutMutationsByProject.clear(),completedCheckoutLockOwners.clear(),_test_exports.beforeTerminalClear=void 0,_test_exports.beforeAbortClear=void 0,_test_exports.beforePrFeedbackTransitionLock=void 0,_test_exports.beforePrFeedbackTrackingSwitch=void 0,_test_exports.afterPrFeedbackTrackingSwitch=void 0,_test_exports.beforePrFeedbackTrackingPersist=void 0,_test_exports.beforeBoundedSwarmFileOpen=void 0,_test_exports.beforeSessionStateLockWrite=void 0,_test_exports.beforeCheckoutLockWrite=void 0,_test_exports.beforeSafeDirectoryCreate=void 0,_test_exports.beforeAtomicTempWrite=void 0,_test_exports.beforeAtomicRename=void 0,_test_exports.openCheckoutLock=openCheckoutLockFile,_test_exports.removeCheckoutLock=removeCheckoutLockFile,_test_exports.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,_test_exports.classifyPrWorkflowGitStateAsync=classifyPrWorkflowGitState},beforeTerminalClear:void 0,beforeAbortClear:void 0,beforePrFeedbackTransitionLock:void 0,beforePrFeedbackTrackingSwitch:void 0,afterPrFeedbackTrackingSwitch:void 0,beforePrFeedbackTrackingPersist:void 0,beforeBoundedSwarmFileOpen:void 0,beforeSessionStateLockWrite:void 0,beforeCheckoutLockWrite:void 0,beforeSafeDirectoryCreate:void 0,beforeAtomicTempWrite:void 0,beforeAtomicRename:void 0,openCheckoutLock:openCheckoutLockFile,removeCheckoutLock:removeCheckoutLockFile,checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,classifyPrWorkflowGitStateAsync:classifyPrWorkflowGitState,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,MAX_WORKFLOW_BATCHES,MAX_RETIRED_REVIEWER_SESSION_IDS,MAX_RETIRED_CONSOLIDATED_LANES,MAX_RETIRED_FEEDBACK_ITEM_OWNERS,resolvePrWorkflowRevisionDigestDetailed,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,composePrReviewPhaseVerdicts:async(directory,sessionID,phase)=>{let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext(directory,state);return composePrReviewPhaseVerdicts(directory,state,phase,ctx)},assertSettledPhaseHasAuthoritativeVerdicts,derivePrReviewCriticInventoryForCoverageGate:async(directory,sessionID,origin="_test_exports")=>{let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext(directory,state);return derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,origin)},derivePrReviewCandidateInventory:async(directory,sessionID)=>{let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext(directory,state);return derivePrReviewCandidateInventory(directory,state,ctx)},isProcessAlive,isSafeStandaloneGitCommit,rename:fsp3.rename,nowMs:()=>Date.now()};PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","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","list","lsp","open","read","search","skill","tree","view","web_fetch","web_search","webfetch","websearch"]);PR_WORKFLOW_CD_PREFIX_PATTERN=/^cd\s+(?:\/d\s+)?(?:"[A-Za-z0-9 _.\\/:~+-]+"|'[A-Za-z0-9 _.\\/:~+-]+'|[A-Za-z0-9_.\\/:~+-]+)\s*&&\s*/i,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN=/\s+2>&1\s*$/,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt](?: -C (?:"[^"]+"|'[^']+'|\S+))* (.+)$/,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt] -C /;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"]),FEEDBACK_NO_CHANGE_CLASSIFICATIONS=new Set(["DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"]);PrWorkflowCheckoutMutationTimeoutError=class PrWorkflowCheckoutMutationTimeoutError extends Error{phase;code="PR_WORKFLOW_CHECKOUT_MUTATION_TIMEOUT";retryable=!1;constructor(phase){super(phase==="queue"?"BLOCKED: timed out waiting for the active PR workflow checkout mutation; the existing owner still holds serialization and must settle before retrying":"BLOCKED: PR workflow checkout mutation exceeded its execution deadline; serialization remains held until the in-flight action actually settles");this.phase=phase;this.name="PrWorkflowCheckoutMutationTimeoutError"}}});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,explicitReason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500);if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
|
|
198
200
|
|
|
199
201
|
${USAGE}`;if(!sessionID?.trim())return`Error: abort-pr-workflow requires an active sessionID.
|
|
200
202
|
|
|
@@ -1957,8 +1959,8 @@ Usage:
|
|
|
1957
1959
|
`)}async function buildEvidenceSummary(directory,currentPhase){log("[EvidenceSummary] Building summary for directory",{directory});let plan=await loadPlanJsonOnly(directory);if(!plan)return log("[EvidenceSummary] No plan found, skipping summary generation"),null;let phasesToProcess=currentPhase!==void 0?plan.phases.filter((p)=>p.id<=currentPhase):plan.phases,phaseSummaries=[],totalTasks=0,completedTasks=0;for(let phase of phasesToProcess){let summary=await _internals100.buildPhaseSummary(directory,phase);phaseSummaries.push(summary),totalTasks+=summary.totalTasks,completedTasks+=summary.completedTasks}let overallCompletionRatio=totalTasks>0?completedTasks/totalTasks:0,overallBlockers=[];for(let phase of phaseSummaries)if(phase.phaseStatus!=="complete")overallBlockers.push(...phase.blockers);let artifact={schema_version:EVIDENCE_SUMMARY_VERSION,generated_at:new Date().toISOString(),planTitle:plan.title,currentPhase:currentPhase??plan.current_phase??1,phaseSummaries,overallCompletionRatio,overallBlockers,summaryText:""};return artifact.summaryText=_internals100.generateSummaryText(artifact),log("[EvidenceSummary] Summary built",{phases:phaseSummaries.length,totalTasks,completedTasks,completionRatio:overallCompletionRatio,blockers:overallBlockers.length}),artifact}function isAutoSummaryEnabled(automationConfig){if(!automationConfig)return!1;if(automationConfig.mode==="manual")return!1;return automationConfig.capabilities?.evidence_auto_summaries===!0}var VALID_EVIDENCE_TYPES2,REQUIRED_EVIDENCE_TYPES,EVIDENCE_SUMMARY_VERSION="1.0.0",_internals100;var init_evidence_summary_service=__esm(()=>{init_gate_bridge();init_manager2();init_manager();init_utils();VALID_EVIDENCE_TYPES2=new Set(["review","test","diff","approval","note","retrospective"]);REQUIRED_EVIDENCE_TYPES=["review","test"];_internals100={buildEvidenceSummary,isAutoSummaryEnabled,normalizeBundleEntries,getTaskStatus,evidenceCompleteFromEntries,isEvidenceComplete,getTaskBlockers,buildTaskSummary,buildPhaseSummary,generateSummaryText}});function getVerdictIcon(verdict){switch(verdict){case"pass":case"approved":return"✅";case"fail":case"rejected":return"❌";case"info":return"ℹ️";default:return""}}function formatEvidenceEntry(index,entry){let details={};if(entry.type==="review"){let reviewEntry=entry;details.risk=reviewEntry.risk,details.issues=reviewEntry.issues?.length}else if(entry.type==="test"){let testEntry=entry;details.tests_passed=testEntry.tests_passed,details.tests_failed=testEntry.tests_failed}return{index,entry,type:entry.type,verdict:entry.verdict,verdictIcon:getVerdictEmoji(entry.verdict),agent:entry.agent??"",summary:entry.summary,timestamp:entry.timestamp,details}}function getVerdictEmoji(verdict){return getVerdictIcon(verdict)}async function getTaskEvidenceData(directory,taskId){let result=await _internals101.loadEvidence(directory,taskId);if(result.status!=="found")return{hasEvidence:!1,taskId,createdAt:"",updatedAt:"",entries:[]};let entries=[];for(let i=0;i<result.bundle.entries.length;i++)entries.push(formatEvidenceEntry(i+1,result.bundle.entries[i]));return{hasEvidence:!0,taskId,createdAt:result.bundle.created_at,updatedAt:result.bundle.updated_at,entries}}async function getEvidenceListData(directory){let taskIds=await _internals101.listEvidenceTaskIds(directory);if(taskIds.length===0)return{hasEvidence:!1,tasks:[]};let tasks=[];for(let taskId of taskIds){let result=await _internals101.loadEvidence(directory,taskId);if(result.status==="found")tasks.push({taskId,entryCount:result.bundle.entries.length,lastUpdated:result.bundle.updated_at});else tasks.push({taskId,entryCount:0,lastUpdated:"unknown"})}return{hasEvidence:!0,tasks}}function formatEvidenceListMarkdown(list){if(!list.hasEvidence||list.tasks.length===0)return"No evidence bundles found.";let tableLines=["## Evidence Bundles","","| Task | Entries | Last Updated |","|------|---------|-------------|"];for(let task of list.tasks)tableLines.push(`| ${task.taskId} | ${task.entryCount} | ${task.lastUpdated} |`);return tableLines.join(`
|
|
1958
1960
|
`)}function formatTaskEvidenceMarkdown(evidence2){if(!evidence2.hasEvidence)return`No evidence found for task ${evidence2.taskId}.`;let lines=[`## Evidence for Task ${evidence2.taskId}`,"",`**Created**: ${evidence2.createdAt}`,`**Updated**: ${evidence2.updatedAt}`,`**Entries**: ${evidence2.entries.length}`];if(evidence2.entries.length>0)lines.push("");for(let entry of evidence2.entries)lines.push(...formatEntryMarkdown(entry));return lines.join(`
|
|
1959
1961
|
`)}function formatEntryMarkdown(entryData){let lines=[];if(lines.push(`### Entry ${entryData.index}: ${entryData.type} (${entryData.verdict}) ${entryData.verdictIcon}`),lines.push(`- **Agent**: ${entryData.agent}`),lines.push(`- **Summary**: ${entryData.summary}`),lines.push(`- **Time**: ${entryData.timestamp}`),entryData.type==="review"){if(lines.push(`- **Risk Level**: ${entryData.details.risk}`),entryData.details.issues&&Number(entryData.details.issues)>0)lines.push(`- **Issues**: ${entryData.details.issues}`)}else if(entryData.type==="test")lines.push(`- **Tests**: ${entryData.details.tests_passed} passed, ${entryData.details.tests_failed} failed`);return lines.push(""),lines}async function handleEvidenceCommand(directory,args2){if(args2.length===0){let listData=await getEvidenceListData(directory);return formatEvidenceListMarkdown(listData)}let taskId=args2[0],evidenceData=await getTaskEvidenceData(directory,taskId);return formatTaskEvidenceMarkdown(evidenceData)}async function handleEvidenceSummaryCommand(directory){let{buildEvidenceSummary:buildEvidenceSummary2}=await Promise.resolve().then(() => (init_evidence_summary_service(),exports_evidence_summary_service)),artifact=await buildEvidenceSummary2(directory);if(!artifact)return"No plan found. Run `/swarm plan` to check plan status.";let lines=["## Evidence Summary","",`**Generated**: ${artifact.generated_at}`,`**Overall Completion**: ${Math.round(artifact.overallCompletionRatio*100)}%`,""];for(let phase of artifact.phaseSummaries){if(lines.push(`### Phase ${phase.phaseId}: ${phase.phaseName}`),lines.push(`- Completion: ${Math.round(phase.completionRatio*100)}%`),phase.blockers.length>0)lines.push(`- Blockers: ${phase.blockers.map((b)=>`[${b.severity}] ${b.reason}`).join("; ")}`);lines.push("")}if(artifact.overallBlockers.length>0){lines.push("### Blockers");for(let blocker of artifact.overallBlockers)lines.push(`- [${blocker.severity}] ${blocker.reason} (Task ${blocker.taskId})`);lines.push("")}else lines.push("### Blockers"),lines.push("None — all completed tasks have required evidence."),lines.push("");return lines.join(`
|
|
1960
|
-
`)}var _internals101;var init_evidence_service=__esm(()=>{init_manager2();_internals101={loadEvidence,listEvidenceTaskIds}});var init_evidence=__esm(()=>{init_evidence_service()});async function getExportData(directory){let planStructured=await loadPlanJsonOnly(directory),planContent=await readSwarmFileAsync(directory,"plan.md"),contextContent=await readSwarmFileAsync(directory,"context.md");return{version:
|
|
1961
|
-
`)}async function handleExportCommand(directory,_args){let exportData=await getExportData(directory);return formatExportMarkdown(exportData)}var init_export_service=__esm(()=>{init_utils2();init_manager()});var init_export=__esm(()=>{init_export_service()});function isValidMode(value){return VALID_MODES.includes(value)}async function handleFullAutoCommand(directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Full-Auto Mode requires an active session. Use /swarm-full-auto from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Full-Auto Mode requires an active session to operate.";let arg=args2[0]?.toLowerCase();if(arg==="status")return buildStatusReport(directory,sessionID,session.fullAutoMode);let newFullAutoMode,modeOverride;if(arg==="on"){newFullAutoMode=!0;let modeArg=args2[1]?.toLowerCase();if(modeArg){if(!isValidMode(modeArg))return`Error: invalid Full-Auto mode '${args2[1]}'. Valid modes: ${VALID_MODES.join(", ")}.`;modeOverride=modeArg}}else if(arg==="off")newFullAutoMode=!1;else if(arg&&isValidMode(arg))newFullAutoMode=!0,modeOverride=arg;else newFullAutoMode=!session.fullAutoMode;let v2Status="unavailable",modeLabel="supervised",denialMaxConsecutive=3,denialMaxTotal=20,failClosed=!0,durableError,criticModelAdvisory="";try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory),fullAutoConfig=config3.full_auto;if(newFullAutoMode&&configHadErrors)return"Error: Full-Auto Mode cannot be enabled — a swarm plugin config file exists but could not be loaded, so full_auto.locked cannot be verified. Fix the config file (see warnings above) and retry.";if(newFullAutoMode&&fullAutoConfig?.locked===!0)return"Error: Full-Auto Mode is locked for this project (full_auto.locked is true in the swarm plugin config). Runtime activation is disabled by configuration; remove the lock to use /swarm full-auto on.";let effectiveMode=modeOverride??fullAutoConfig?.mode??"supervised";if(modeLabel=effectiveMode,denialMaxConsecutive=fullAutoConfig?.denials?.max_consecutive??3,denialMaxTotal=fullAutoConfig?.denials?.max_total??20,failClosed=fullAutoConfig?.fail_closed!==!1,newFullAutoMode){startFullAutoRun(directory,sessionID,fullAutoConfig?{...fullAutoConfig,mode:effectiveMode}:void 0),v2Status="running";let criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model,architectModel=config3.agents?.architect?.model;if(criticModel&&architectModel&&criticModel===architectModel)criticModelAdvisory=" WARNING: critic model matches architect model — set full_auto.critic_model (or agents.critic.model) to a different model for independent oversight."}else{if(!disarmFullAutoRun(directory,sessionID,"/swarm full-auto off"))terminateFullAutoRun(directory,sessionID,"never started");v2Status="idle"}}catch(error93){durableError=error93 instanceof Error?error93.message:String(error93),error48(`[full-auto] durable run-state write failed: ${durableError}`)}if(newFullAutoMode&&durableError)return["Error: Full-Auto Mode could NOT be enabled — durable run-state write failed.",`Reason: ${durableError}.`,"Inspect .swarm/ permissions and disk space, then retry."].join(" ");if(session.fullAutoMode=newFullAutoMode,!newFullAutoMode)session.fullAutoInteractionCount=0,session.fullAutoDeadlockCount=0,session.fullAutoLastQuestionHash=null;if(!newFullAutoMode)return["Full-Auto Mode disabled",`(v2 run-state: ${v2Status}; mode=${modeLabel})`].join(" ");return["Full-Auto Mode enabled",`(v2 mode=${modeLabel}, fail_closed=${failClosed},`,`denials max ${denialMaxConsecutive} consecutive / ${denialMaxTotal} total)`].join(" ")+criticModelAdvisory}function buildStatusReport(directory,sessionID,sessionFlag){let lines=[];lines.push(`Full-Auto session flag: ${sessionFlag?"on":"off"}`);try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory);if(configHadErrors)lines.push("Config: UNREADABLE (a config file exists but could not be loaded; `full_auto.locked` cannot be verified, so runtime activation refuses by fail-closed default). Fix the config file to restore normal status.");if(config3.full_auto?.locked===!0)lines.push("Config: locked (runtime activation disabled via full_auto.locked)")}catch{}try{let runState=loadFullAutoRunState(directory,sessionID),stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable)lines.push(`Durable run-state: UNREADABLE (${stateHealth.reason}). Non-read-only tools are blocked fail-closed until .swarm/full-auto-state.json (or .bak) is restored or deleted.`);else if(!runState)lines.push("Durable run-state: none (no Full-Auto run for this session)");else{if(lines.push(`Durable run-state: ${runState.status} (mode=${runState.mode})`),runState.pauseReason)lines.push(`Pause reason: ${runState.pauseReason}`);if(runState.terminateReason)lines.push(`Terminate reason: ${runState.terminateReason}`);if(lines.push(`Counters: ${runState.counters.toolCalls} tool calls, ${runState.counters.architectTurns} architect turns, ${runState.counters.oversightChecks} oversight checks`),lines.push(`Denials: ${runState.denialCounters.consecutive} consecutive / ${runState.denialCounters.total} total`),runState.lastOversightVerdict)lines.push(`Last oversight verdict: ${runState.lastOversightVerdict}${runState.lastOversightAt?` at ${runState.lastOversightAt}`:""}`)}}catch(error93){lines.push(`Durable run-state: unreadable (${error93 instanceof Error?error93.message:String(error93)})`)}return lines.join(`
|
|
1962
|
+
`)}var _internals101;var init_evidence_service=__esm(()=>{init_manager2();_internals101={loadEvidence,listEvidenceTaskIds}});var init_evidence=__esm(()=>{init_evidence_service()});async function getExportData(directory){let planStructured=await loadPlanJsonOnly(directory),planContent=await readSwarmFileAsync(directory,"plan.md"),contextContent=await readSwarmFileAsync(directory,"context.md");return{version:package_default.version,exported:new Date().toISOString(),plan:planStructured||planContent,context:contextContent,execution_profile:planStructured?.execution_profile??null}}function formatExportMarkdown(exportData){return["## Swarm Export","","```json",JSON.stringify(exportData,null,2),"```"].join(`
|
|
1963
|
+
`)}async function handleExportCommand(directory,_args){let exportData=await getExportData(directory);return formatExportMarkdown(exportData)}var init_export_service=__esm(()=>{init_package();init_utils2();init_manager()});var init_export=__esm(()=>{init_export_service()});function isValidMode(value){return VALID_MODES.includes(value)}async function handleFullAutoCommand(directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Full-Auto Mode requires an active session. Use /swarm-full-auto from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Full-Auto Mode requires an active session to operate.";let arg=args2[0]?.toLowerCase();if(arg==="status")return buildStatusReport(directory,sessionID,session.fullAutoMode);let newFullAutoMode,modeOverride;if(arg==="on"){newFullAutoMode=!0;let modeArg=args2[1]?.toLowerCase();if(modeArg){if(!isValidMode(modeArg))return`Error: invalid Full-Auto mode '${args2[1]}'. Valid modes: ${VALID_MODES.join(", ")}.`;modeOverride=modeArg}}else if(arg==="off")newFullAutoMode=!1;else if(arg&&isValidMode(arg))newFullAutoMode=!0,modeOverride=arg;else newFullAutoMode=!session.fullAutoMode;let v2Status="unavailable",modeLabel="supervised",denialMaxConsecutive=3,denialMaxTotal=20,failClosed=!0,durableError,criticModelAdvisory="";try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory),fullAutoConfig=config3.full_auto;if(newFullAutoMode&&configHadErrors)return"Error: Full-Auto Mode cannot be enabled — a swarm plugin config file exists but could not be loaded, so full_auto.locked cannot be verified. Fix the config file (see warnings above) and retry.";if(newFullAutoMode&&fullAutoConfig?.locked===!0)return"Error: Full-Auto Mode is locked for this project (full_auto.locked is true in the swarm plugin config). Runtime activation is disabled by configuration; remove the lock to use /swarm full-auto on.";let effectiveMode=modeOverride??fullAutoConfig?.mode??"supervised";if(modeLabel=effectiveMode,denialMaxConsecutive=fullAutoConfig?.denials?.max_consecutive??3,denialMaxTotal=fullAutoConfig?.denials?.max_total??20,failClosed=fullAutoConfig?.fail_closed!==!1,newFullAutoMode){startFullAutoRun(directory,sessionID,fullAutoConfig?{...fullAutoConfig,mode:effectiveMode}:void 0),v2Status="running";let criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model,architectModel=config3.agents?.architect?.model;if(criticModel&&architectModel&&criticModel===architectModel)criticModelAdvisory=" WARNING: critic model matches architect model — set full_auto.critic_model (or agents.critic.model) to a different model for independent oversight."}else{if(!disarmFullAutoRun(directory,sessionID,"/swarm full-auto off"))terminateFullAutoRun(directory,sessionID,"never started");v2Status="idle"}}catch(error93){durableError=error93 instanceof Error?error93.message:String(error93),error48(`[full-auto] durable run-state write failed: ${durableError}`)}if(newFullAutoMode&&durableError)return["Error: Full-Auto Mode could NOT be enabled — durable run-state write failed.",`Reason: ${durableError}.`,"Inspect .swarm/ permissions and disk space, then retry."].join(" ");if(session.fullAutoMode=newFullAutoMode,!newFullAutoMode)session.fullAutoInteractionCount=0,session.fullAutoDeadlockCount=0,session.fullAutoLastQuestionHash=null;if(!newFullAutoMode)return["Full-Auto Mode disabled",`(v2 run-state: ${v2Status}; mode=${modeLabel})`].join(" ");return["Full-Auto Mode enabled",`(v2 mode=${modeLabel}, fail_closed=${failClosed},`,`denials max ${denialMaxConsecutive} consecutive / ${denialMaxTotal} total)`].join(" ")+criticModelAdvisory}function buildStatusReport(directory,sessionID,sessionFlag){let lines=[];lines.push(`Full-Auto session flag: ${sessionFlag?"on":"off"}`);try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory);if(configHadErrors)lines.push("Config: UNREADABLE (a config file exists but could not be loaded; `full_auto.locked` cannot be verified, so runtime activation refuses by fail-closed default). Fix the config file to restore normal status.");if(config3.full_auto?.locked===!0)lines.push("Config: locked (runtime activation disabled via full_auto.locked)")}catch{}try{let runState=loadFullAutoRunState(directory,sessionID),stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable)lines.push(`Durable run-state: UNREADABLE (${stateHealth.reason}). Non-read-only tools are blocked fail-closed until .swarm/full-auto-state.json (or .bak) is restored or deleted.`);else if(!runState)lines.push("Durable run-state: none (no Full-Auto run for this session)");else{if(lines.push(`Durable run-state: ${runState.status} (mode=${runState.mode})`),runState.pauseReason)lines.push(`Pause reason: ${runState.pauseReason}`);if(runState.terminateReason)lines.push(`Terminate reason: ${runState.terminateReason}`);if(lines.push(`Counters: ${runState.counters.toolCalls} tool calls, ${runState.counters.architectTurns} architect turns, ${runState.counters.oversightChecks} oversight checks`),lines.push(`Denials: ${runState.denialCounters.consecutive} consecutive / ${runState.denialCounters.total} total`),runState.lastOversightVerdict)lines.push(`Last oversight verdict: ${runState.lastOversightVerdict}${runState.lastOversightAt?` at ${runState.lastOversightAt}`:""}`)}}catch(error93){lines.push(`Durable run-state: unreadable (${error93 instanceof Error?error93.message:String(error93)})`)}return lines.join(`
|
|
1962
1964
|
`)}var VALID_MODES;var init_full_auto=__esm(()=>{init_config();init_state3();init_state2();init_logger();VALID_MODES=["assisted","supervised","strict"]});import*as fs66 from"node:fs";import*as path131 from"node:path";function resolveTier1FixtureRoot(packageRoot){return resolveContainedExistingPath(packageRoot,"evaluation-fixtures/tier1")}function listTier1FixtureManifests(packageRoot){let root=resolveTier1FixtureRoot(packageRoot),expected=new Set(TIER1_FIXTURE_IDS),actual=fs66.readdirSync(root,{withFileTypes:!0}).filter((entry)=>entry.isDirectory()&&expected.has(entry.name)).map((entry)=>entry.name).sort();if(actual.length!==TIER1_FIXTURE_IDS.length)throw Error(`Tier-1 evaluation fixture package is incomplete: expected ${TIER1_FIXTURE_IDS.length}, found ${actual.length}`);return actual.map((id)=>resolveContainedExistingPath(root,path131.join(id,"manifest.json")))}async function loadTier1EvaluationTasks(packageRoot){return Promise.all(listTier1FixtureManifests(packageRoot).map(async(manifestPath)=>{let raw=JSON.parse(fs66.readFileSync(manifestPath,"utf8")),id=raw.id;if(typeof id!=="string"||!TIER1_FIXTURE_IDS.includes(id))throw Error(`Unknown Tier-1 fixture id in ${manifestPath}`);let prefix=path131.posix.join("evaluation-fixtures","tier1",id),instructionPath=raw.instructionPath,environment=raw.environment,scorer=raw.scorer;if(typeof instructionPath!=="string"||typeof environment?.path!=="string")throw Error(`Malformed Tier-1 fixture paths in ${manifestPath}`);let rebased={...raw,instructionPath:path131.posix.join(prefix,instructionPath),environment:{...environment,path:path131.posix.join(prefix,environment.path)},scorer:scorer?.kind==="project"&&Array.isArray(scorer.argv)?{...scorer,argv:[path131.posix.join(prefix,String(scorer.argv[0])),...scorer.argv.slice(1)]}:scorer},task=EvaluationTaskV1Schema.parse(rebased);if(await computeTaskInputContentHash(packageRoot,task)!==task.contentHash)throw Error(`Tier-1 fixture ${id} failed its content hash`);return task}))}var TIER1_FIXTURE_IDS;var init_fixtures=__esm(()=>{init_contracts();init_hashing();TIER1_FIXTURE_IDS=["mutation-off-by-one","null-substitution","operator-swap","guard-removal","branch-swap","side-effect-deletion","curated-off-by-one","missing-await","swallowed-error","injection-prone-string","missing-auth-check","boundary-error"]});class Node{value;next;constructor(value){this.value=value}}var Queue;var init_yocto_queue=__esm(()=>{Queue=class Queue{#head;#tail;#size;constructor(){this.clear()}enqueue(value){let node=new Node(value);if(this.#head)this.#tail.next=node,this.#tail=node;else this.#head=node,this.#tail=node;this.#size++}dequeue(){let current=this.#head;if(!current)return;if(this.#head=this.#head.next,this.#size--,!this.#head)this.#tail=void 0;return current.value}peek(){if(!this.#head)return;return this.#head.value}clear(){this.#head=void 0,this.#tail=void 0,this.#size=0}get size(){return this.#size}*[Symbol.iterator](){let current=this.#head;while(current)yield current.value,current=current.next}*drain(){while(this.#head)yield this.dequeue()}}});function pLimit(concurrency){let rejectOnClear=!1;if(typeof concurrency==="object")({concurrency,rejectOnClear=!1}=concurrency);if(validateConcurrency(concurrency),typeof rejectOnClear!=="boolean")throw TypeError("Expected `rejectOnClear` to be a boolean");let queue=new Queue,activeCount=0,resumeNext=()=>{if(activeCount<concurrency&&queue.size>0)activeCount++,queue.dequeue().run()},next=()=>{activeCount--,resumeNext()},run=async(function_,resolve55,arguments_)=>{let result=(async()=>function_(...arguments_))();resolve55(result);try{await result}catch{}next()},enqueue=(function_,resolve55,reject,arguments_)=>{let queueItem={reject};if(new Promise((internalResolve)=>{queueItem.run=internalResolve,queue.enqueue(queueItem)}).then(run.bind(void 0,function_,resolve55,arguments_)),activeCount<concurrency)resumeNext()},generator=(function_,...arguments_)=>new Promise((resolve55,reject)=>{enqueue(function_,resolve55,reject,arguments_)});return Object.defineProperties(generator,{activeCount:{get:()=>activeCount},pendingCount:{get:()=>queue.size},clearQueue:{value(){if(!rejectOnClear){queue.clear();return}let abortError=AbortSignal.abort().reason;while(queue.size>0)queue.dequeue().reject(abortError)}},concurrency:{get:()=>concurrency,set(newConcurrency){validateConcurrency(newConcurrency),concurrency=newConcurrency,queueMicrotask(()=>{while(activeCount<concurrency&&queue.size>0)resumeNext()})}},map:{async value(iterable,function_){let promises8=Array.from(iterable,(value,index)=>this(function_,value,index));return Promise.all(promises8)}}}),generator}function validateConcurrency(concurrency){if(!((Number.isInteger(concurrency)||concurrency===Number.POSITIVE_INFINITY)&&concurrency>0))throw TypeError("Expected `concurrency` to be a number from 1 and up")}var init_p_limit=__esm(()=>{init_yocto_queue()});function isStaticallyEquivalent(originalCode,mutatedCode){let stripCode=(code)=>{let inMultiLineComment=!1,afterMultiLine=[];for(let line of code.split(`
|
|
1963
1965
|
`))if(!inMultiLineComment){let openIndex=line.indexOf("/*");if(openIndex!==-1){let closeIndex=line.indexOf("*/",openIndex+2);if(closeIndex!==-1)afterMultiLine.push(line.substring(0,openIndex)+line.substring(closeIndex+2));else afterMultiLine.push(line.substring(0,openIndex)),inMultiLineComment=!0}else afterMultiLine.push(line)}else{let closeIndex=line.indexOf("*/");if(closeIndex!==-1)afterMultiLine.push(line.substring(closeIndex+2)),inMultiLineComment=!1}let afterSingleLine=[];for(let line of afterMultiLine){let inString=null,commentStart=-1;for(let i=0;i<line.length;i++){let ch=line[i];if(inString){if(ch==="\\"){i++;continue}if(ch===inString)inString=null}else if(ch==="'"||ch==='"'||ch==="`")inString=ch;else if(ch==="/"&&i+1<line.length&&line[i+1]==="/"){commentStart=i;break}}let processed=commentStart>=0?line.substring(0,commentStart):line;processed=processed.trimEnd(),afterSingleLine.push(processed)}return afterSingleLine.filter((line)=>{let trimmedLower=line.toLowerCase().trim();if(/^console\.(log|debug)\s*(\(|$)/.test(trimmedLower))return!1;if(trimmedLower==="debugger;")return!1;return!0}).filter((line)=>line.trim()!=="").join(`
|
|
1964
1966
|
`)},strippedOriginal=stripCode(originalCode),strippedMutated=stripCode(mutatedCode);return strippedOriginal===strippedMutated}async function checkEquivalence(patch2,originalCode,mutatedCode,llmJudge){if(isStaticallyEquivalent(originalCode,mutatedCode))return{patchId:patch2.id,isEquivalent:!0,method:"static",confidence:1,reason:"Mutated code is identical to original after stripping comments, logging, and whitespace"};if(llmJudge){let context=`File: ${patch2.filePath}
|
|
@@ -2155,8 +2157,8 @@ ${stderr}`:stdout||stderr||"",passed=0,failed=0,skipped=0,total,coveragePercent;
|
|
|
2155
2157
|
`)){let trimmed=line.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))continue;try{let parsed=JSON.parse(trimmed),testResults=parseJestLikeJsonTestResults(parsed);if(testResults.length>0)return testResults}catch{}}if(framework==="bun")return parseBunJsonLines(output);return[]}function parseTestOutput2(framework,output){let totals={passed:0,failed:0,skipped:0,total:0},coveragePercent;switch(framework){case"vitest":case"jest":case"bun":{let jsonMatch=output.match(/\{[\s\S]*"testResults"[\s\S]*\}/);if(jsonMatch)try{let parsed=JSON.parse(jsonMatch[0]);if(parsed.numTotalTests!==void 0)totals.passed=parsed.numPassedTests||0,totals.failed=parsed.numFailedTests||0,totals.skipped=parsed.numPendingTests||0,totals.total=parsed.numTotalTests||0;if(parsed.coverage!==void 0)coveragePercent=parsed.coverage}catch{}if(totals.total===0){let passMatch=output.match(/(\d+)\s+pass(ing|ed)?/),failMatch=output.match(/(\d+)\s+fail(ing|ed)?/),skipMatch=output.match(/(\d+)\s+skip(ping|ped)?/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped}let coverageMatch=output.match(/All files[^\d]*(\d+\.?\d*)\s*%/);if(!coveragePercent&&coverageMatch)coveragePercent=parseFloat(coverageMatch[1]);break}case"mocha":{let passMatch=output.match(/(\d+)\s+passing/),failMatch=output.match(/(\d+)\s+failing/),pendingMatch=output.match(/(\d+)\s+pending/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(pendingMatch)totals.skipped=parseInt(pendingMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"pytest":{let passMatch=output.match(/(\d+)\s+passed/),failMatch=output.match(/(\d+)\s+failed/),skipMatch=output.match(/(\d+)\s+skipped/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;let coverageMatch=output.match(/TOTAL\s+(\d+\.?\d*)\s*%/);if(coverageMatch)coveragePercent=parseFloat(coverageMatch[1]);break}case"cargo":{let passMatch=output.match(/test result: ok\. (\d+) passed/),failMatch=output.match(/test result: FAILED\. (\d+) passed; (\d+) failed/);if(failMatch)totals.passed=parseInt(failMatch[1],10),totals.failed=parseInt(failMatch[2],10);else if(passMatch)totals.passed=parseInt(passMatch[1],10);totals.total=totals.passed+totals.failed;break}case"pester":{let passMatch=output.match(/Passed:\s*(\d+)/),failMatch=output.match(/Failed:\s*(\d+)/),skipMatch=output.match(/Skipped:\s*(\d+)/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"go-test":{let passMatches=[...output.matchAll(/--- PASS:/g)],failMatches=[...output.matchAll(/--- FAIL:/g)],skipMatches=[...output.matchAll(/--- SKIP:/g)];totals.passed=passMatches.length,totals.failed=failMatches.length,totals.skipped=skipMatches.length,totals.total=totals.passed+totals.failed+totals.skipped;let covMatch=output.match(/coverage:\s*(\d+\.?\d*)\s*%/);if(covMatch)coveragePercent=parseFloat(covMatch[1]);break}case"maven":{let mavenMatch=output.match(/Tests run:\s*(\d+),\s*Failures:\s*(\d+),\s*Errors:\s*(\d+),\s*Skipped:\s*(\d+)/);if(mavenMatch){let total=parseInt(mavenMatch[1],10),failures=parseInt(mavenMatch[2],10),errors5=parseInt(mavenMatch[3],10),skipped=parseInt(mavenMatch[4],10);totals.failed=failures+errors5,totals.skipped=skipped,totals.passed=total-totals.failed-skipped,totals.total=total}break}case"gradle":{let gradleMatch=output.match(/(\d+) tests? completed(?:,\s*(\d+) failed)?(?:,\s*(\d+) skipped)?/);if(gradleMatch)totals.total=parseInt(gradleMatch[1],10),totals.failed=gradleMatch[2]?parseInt(gradleMatch[2],10):0,totals.skipped=gradleMatch[3]?parseInt(gradleMatch[3],10):0,totals.passed=totals.total-totals.failed-totals.skipped;break}case"dotnet-test":{let passMatch=output.match(/Passed[!:]?\s*(\d+)/i),failMatch=output.match(/Failed[!:]?\s*(\d+)/i),skipMatch=output.match(/Skipped[!:]?\s*(\d+)/i);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"ctest":{let disabledCount=[...output.matchAll(/\*{3}Not Run\s+\(Disabled\)/gi)].length;totals.skipped=disabledCount;let ctestMatch=output.match(/(\d+) tests? failed out of (\d+)/);if(ctestMatch){totals.failed=parseInt(ctestMatch[1],10);let executedTotal=parseInt(ctestMatch[2],10);totals.total=executedTotal+disabledCount,totals.passed=executedTotal-totals.failed}else{let allPassMatch=output.match(/100% tests passed.*?(\d+) tests?/);if(allPassMatch){let executedTotal=parseInt(allPassMatch[1],10);totals.total=executedTotal+disabledCount,totals.passed=executedTotal}else if(disabledCount>0)totals.total=disabledCount}break}case"swift-test":{let swiftMatch=output.match(/Executed (\d+) tests?,\s*with (\d+) failures?/);if(swiftMatch)totals.total=parseInt(swiftMatch[1],10),totals.failed=parseInt(swiftMatch[2],10),totals.passed=totals.total-totals.failed;break}case"dart-test":{let dartPassMatch=output.match(/\+(\d+):\s*All tests passed/),dartMixMatch=output.match(/\+(\d+)\s+-(\d+):/);if(dartPassMatch)totals.passed=parseInt(dartPassMatch[1],10),totals.total=totals.passed;else if(dartMixMatch)totals.passed=parseInt(dartMixMatch[1],10),totals.failed=parseInt(dartMixMatch[2],10),totals.total=totals.passed+totals.failed;break}case"rspec":{let rspecMatch=output.match(/(\d+) examples?,\s*(\d+) failures?(?:,\s*(\d+) pending)?/);if(rspecMatch)totals.total=parseInt(rspecMatch[1],10),totals.failed=parseInt(rspecMatch[2],10),totals.skipped=rspecMatch[3]?parseInt(rspecMatch[3],10):0,totals.passed=totals.total-totals.failed-totals.skipped;break}case"minitest":{let minitestMatch=output.match(/(\d+) runs?,\s*\d+ assertions?,\s*(\d+) failures?,\s*(\d+) errors?,\s*(\d+) skips?/);if(minitestMatch)totals.total=parseInt(minitestMatch[1],10),totals.failed=parseInt(minitestMatch[2],10)+parseInt(minitestMatch[3],10),totals.skipped=parseInt(minitestMatch[4],10),totals.passed=totals.total-totals.failed-totals.skipped;break}case"pest":case"phpunit":case"php-artisan":{let phpunitMatch=output.match(/Tests:\s*(\d+),\s*Assertions:\s*\d+(?:,\s*Failures:\s*(\d+))?(?:,\s*Errors:\s*(\d+))?(?:,\s*Skipped:\s*(\d+))?/),okMatch=output.match(/OK\s*\((\d+)\s+tests?/);if(phpunitMatch){totals.total=parseInt(phpunitMatch[1],10);let failures=phpunitMatch[2]?parseInt(phpunitMatch[2],10):0,errors5=phpunitMatch[3]?parseInt(phpunitMatch[3],10):0;totals.skipped=phpunitMatch[4]?parseInt(phpunitMatch[4],10):0,totals.failed=failures+errors5,totals.passed=totals.total-totals.failed-totals.skipped}else if(okMatch)totals.total=parseInt(okMatch[1],10),totals.passed=totals.total;break}default:break}return{totals,coveragePercent}}async function readBoundedStream2(stream,maxBytes){let reader=stream.getReader(),chunks=[],totalBytes=0,truncated=!1;try{while(!0){let{done,value}=await reader.read();if(done)break;if(totalBytes+value.length>maxBytes){let remaining=maxBytes-totalBytes;if(remaining>0)chunks.push(value.slice(0,remaining));totalBytes=maxBytes,truncated=!0,reader.cancel().catch(()=>{});break}chunks.push(value),totalBytes+=value.length}}catch{}finally{try{reader.releaseLock()}catch{}}let decoder=new TextDecoder("utf-8",{fatal:!1}),combined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)combined.set(chunk,offset),offset+=chunk.length;return{text:decoder.decode(combined),truncated}}function formatPassingMessage(framework,totals,coveragePercent){let message=totals.total>0&&totals.passed===0&&totals.failed===0&&totals.skipped===totals.total?`${framework} tests completed with ${totals.skipped} skipped (${totals.total} total)`:`${framework} tests passed (${totals.passed}/${totals.total})`;if(coveragePercent!==void 0)message+=` with ${coveragePercent}% coverage`;return message}function formatNativeHistoryTestFile(target,historyPath){return`native:${target.framework}:path=${encodeURIComponent(historyPath)}#name=${encodeURIComponent(target.name)}`}async function runTests(framework,scope,files,coverage,timeout_ms,cwd,bail,targets,nativeTarget){let executionCwd=cwd,resolvedNativeTarget=nativeTarget;if(scope==="target"&&!nativeTarget||scope!=="target"&&nativeTarget!==void 0||nativeTarget!==void 0&&nativeTarget.framework!==framework)return{success:!1,framework,scope,error:"Invalid native target pairing; refusing broad test fallback",message:'scope "target" requires one matching native target, and native targets are not valid with other scopes.',outcome:"error"};if(scope==="target"){if(files.length>0||coverage||bail)return{success:!1,framework,scope,error:'scope "target" cannot be combined with files, coverage, or bail',message:"Native target mode runs one exact framework-native name only. Omit files and leave coverage and bail disabled.",outcome:"error"};let nativeTargetError=validateNativeTargetInput(nativeTarget);if(nativeTargetError)return{success:!1,framework,scope,error:nativeTargetError,outcome:"error"};let resolvedTarget=resolveNativeTarget(nativeTarget,cwd);if(!resolvedTarget.success)return{success:!1,framework,scope,error:resolvedTarget.error,outcome:"error"};resolvedNativeTarget=resolvedTarget.target,executionCwd=resolvedTarget.executionDirectory}if(scope!=="all"&&scope!=="target"&&files.length>0&&!(targets&&targets.length>0)){let unsupportedReason=getTargetedExecutionUnsupportedReason(framework);if(unsupportedReason)return{success:!1,framework,scope,error:`Framework "${framework}" does not support targeted test-file execution`,message:`The resolved test selection cannot be run safely because ${unsupportedReason}. Use a framework-native selector manually or let the architect handle the broader sweep.`,outcome:"error"}}let command=process.env.SWARM_LANG_BACKEND!=="legacy"?await buildTestCommandViaDispatch(framework,scope,files,coverage,executionCwd,bail,targets,resolvedNativeTarget)??buildTestCommand2(framework,scope,files,coverage,executionCwd,bail,targets,resolvedNativeTarget):buildTestCommand2(framework,scope,files,coverage,executionCwd,bail,targets,resolvedNativeTarget);if(!command)return{success:!1,framework,scope,error:`No test command available for framework: ${framework}`,message:"Install a supported test framework to run tests",outcome:"error"};if(command.join(" ").length>MAX_COMMAND_LENGTH2)return{success:!1,framework,scope,command,error:"Command exceeds maximum allowed length",outcome:"error"};let startTime=Date.now(),vitestJsonOutputPath=framework==="vitest"?path164.join(executionCwd,".swarm","cache","test-runner-vitest.json"):void 0,proc,timeoutHandle,timedOutByDeadline=!1;try{if(vitestJsonOutputPath)try{if(fs86.mkdirSync(path164.dirname(vitestJsonOutputPath),{recursive:!0}),fs86.existsSync(vitestJsonOutputPath))fs86.unlinkSync(vitestJsonOutputPath)}catch{}let timeoutPromise=new Promise((resolve67)=>{timeoutHandle=setTimeout(()=>{resolve67({kind:"timeout"})},timeout_ms)});proc=_internals129.bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:executionCwd,timeout:timeout_ms,killProcessTree:!0});let stdoutPromise=readBoundedStream2(proc.stdout,MAX_OUTPUT_BYTES4),stderrPromise=readBoundedStream2(proc.stderr,MAX_OUTPUT_BYTES4),raceResult=await Promise.race([proc.exited.then((exitCode2)=>({kind:"exit",exitCode:exitCode2})),timeoutPromise]);if(timedOutByDeadline=raceResult.kind==="timeout",timeoutHandle!==void 0)clearTimeout(timeoutHandle),timeoutHandle=void 0;let[stdoutResult,stderrResult]=await Promise.all([stdoutPromise,stderrPromise]),exitCode=raceResult.kind==="timeout"?-1:raceResult.exitCode,duration_ms=Date.now()-startTime,output=stdoutResult.text;if(stderrResult.text)output+=(output?`
|
|
2156
2158
|
`:"")+stderrResult.text;if(vitestJsonOutputPath)try{if(fs86.existsSync(vitestJsonOutputPath)){let vitestJsonOutput=fs86.readFileSync(vitestJsonOutputPath,"utf-8");if(vitestJsonOutput.trim().length>0)output+=(output?`
|
|
2157
2159
|
`:"")+vitestJsonOutput}}catch{}if(stdoutResult.truncated||stderrResult.truncated)output+=`
|
|
2158
|
-
... (output truncated at stream read limit)`;let parsed=process.env.SWARM_LANG_BACKEND!=="legacy"?await parseTestOutputViaDispatch(framework,output,executionCwd)??parseTestOutput2(framework,output):parseTestOutput2(framework,output),parsedTestCases=parseFrameworkJsonTestResults(framework,output),totals={...parsed.totals},{coveragePercent}=parsed;if(totals.total===0&&parsedTestCases.length>0){for(let entry of parsedTestCases)if(entry.result==="pass")totals.passed++;else if(entry.result==="fail")totals.failed++;else totals.skipped++;totals.total=parsedTestCases.length}let isTimeout=timedOutByDeadline,nativeTargetObserved=resolvedNativeTarget?didExecuteNativeTarget(resolvedNativeTarget,output):!0;if(exitCode===0&&!isTimeout&&totals.failed===0&&nativeTargetObserved){let result={success:!0,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,outcome:"pass",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;return result.message=formatPassingMessage(framework,totals,coveragePercent),result}else{let result={success:!1,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,error:isTimeout?`Tests timed out after ${timeout_ms}ms`:!nativeTargetObserved?`Native target "${resolvedNativeTarget?.name}" did not execute`:`Tests failed with ${totals.failed} failures`,message:isTimeout?`${framework} tests timed out after ${timeout_ms}ms`:!nativeTargetObserved?`${framework} did not report the exact requested native target; refusing a false-green 0/0 result`:`${framework} tests failed (${totals.failed}/${totals.total} failed)`,outcome:isTimeout?"error":"regression",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;return result}}catch(error93){let duration_ms=Date.now()-startTime;return{success:!1,framework,scope,command,timeout_ms,duration_ms,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error",outcome:"error"}}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(proc?.exitCode===null&&!timedOutByDeadline)try{if(proc.killTree)await proc.killTree("SIGKILL");else proc.kill("SIGKILL")}catch{}}}function escapeRegexForMatch(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function didExecuteNativeTarget(target,output){if(target.framework==="go-test")return[...output.matchAll(/^\s*--- (?:PASS|FAIL|SKIP):\s+(.+?)(?:\s+\(|$)/gm)].some((match)=>match[1]===target.name);let exactName=escapeRegexForMatch(target.name);return new RegExp(`(?:Start\\s+\\d+:\\s*|Test\\s+#\\d+:\\s*)${exactName}(?=\\s|$)`,"m").test(output)}function normalizeHistoryTestFile(testFile,workingDir){let normalized=testFile.replace(/\\/g,"/");if(!path164.isAbsolute(testFile))return normalized;let relative35=path164.relative(workingDir,testFile);if(relative35.startsWith("..")||path164.isAbsolute(relative35))return normalized;return relative35.replace(/\\/g,"/")}function combineAggregateResult(current,next){if(current==="fail"||next==="fail")return"fail";if(current==="pass"||next==="pass")return"pass";return"skip"}function recordAndAnalyzeResults(result,testFiles,workingDir,sourceFiles,parsedTestCases){if(!result.totals||result.totals.total===0)return;let now2=new Date().toISOString(),changedFiles=(sourceFiles!==void 0?sourceFiles:testFiles).map((f)=>f.replace(/\\/g,"/")),aggregateResultsByFile=new Map,validParsedCases=parsedTestCases?.filter((parsedCase)=>parsedCase.testFile.length>0&&parsedCase.testName.length>0)??[],allRecords=[];for(let parsedCase of validParsedCases){let normalizedTestFile=normalizeHistoryTestFile(parsedCase.testFile,workingDir);allRecords.push({timestamp:now2,taskId:"auto",testFile:normalizedTestFile,testName:parsedCase.testName,result:parsedCase.result,durationMs:parsedCase.durationMs,errorMessage:parsedCase.errorMessage,stackPrefix:parsedCase.stackPrefix,changedFiles}),aggregateResultsByFile.set(normalizedTestFile,combineAggregateResult(aggregateResultsByFile.get(normalizedTestFile),parsedCase.result))}if(aggregateResultsByFile.size===0){let aggregateResult=result.success?"pass":"fail";for(let testFile of testFiles)aggregateResultsByFile.set(testFile.replace(/\\/g,"/"),aggregateResult)}for(let[testFile,aggregateResult]of aggregateResultsByFile)allRecords.push({timestamp:now2,taskId:"auto",testFile,testName:AGGREGATE_TEST_NAME,result:aggregateResult,durationMs:result.duration_ms||0,changedFiles});try{batchAppendTestRuns(allRecords,workingDir)}catch{}}function selectHistoryForAnalysis(history){let filesWithIndividualRecords=new Set;for(let record3 of history)if(record3.testName!==AGGREGATE_TEST_NAME)filesWithIndividualRecords.add(record3.testFile.toLowerCase());if(filesWithIndividualRecords.size===0)return history;return history.filter((record3)=>record3.testName!==AGGREGATE_TEST_NAME||!filesWithIndividualRecords.has(record3.testFile.toLowerCase()))}function analyzeFailures(workingDir){let report={flakyTests:[],failureClusters:[],quarantinedFailures:[]};try{let history=selectHistoryForAnalysis(getAllHistory(workingDir));if(history.length===0)return report;report.flakyTests=detectFlakyTests(history);let failingResults=history.filter((r)=>r.result==="fail");if(failingResults.length>0){let{clusters}=classifyAndCluster(failingResults,history);report.failureClusters=clusters.map((c)=>({rootCause:c.rootCause,affectedFiles:c.affectedTestFiles,classification:c.classification}))}for(let entry of report.flakyTests)if(entry.isQuarantined)report.quarantinedFailures.push(`${entry.testFile}: ${entry.testName}`)}catch{}return report}var MAX_OUTPUT_BYTES4=512000,MAX_COMMAND_LENGTH2=500,DEFAULT_TIMEOUT_MS3=60000,MAX_TIMEOUT_MS3=300000,MAX_SAFE_TEST_FILES=50,MAX_SAFE_SOURCE_FILES=1,AGGREGATE_TEST_NAME="(aggregate)",VITEST_JSON_OUTPUT_RELATIVE_PATH=".swarm/cache/test-runner-vitest.json",POWERSHELL_METACHARACTERS,SHELL_METACHARACTERS2,DISPATCH_FRAMEWORK_MAP,COMPOUND_TEST_EXTENSIONS,TEST_DIRECTORY_NAMES,SOURCE_EXTENSIONS,test_runner,_internals129;var init_test_runner=__esm(()=>{init_zod();init_discovery();init_default_backend();init_analyzer();init_failure_classifier();init_history_store();init_bun_compat();init_path_security();init_create_tool();init_resolve_working_directory();POWERSHELL_METACHARACTERS=/[|;&`$(){}[\]<>"'#*?\x00-\x1f]/;SHELL_METACHARACTERS2=/[;&`$(){}<>"'\x00-\x1f]/;DISPATCH_FRAMEWORK_MAP={bun:"bun",vitest:"vitest",jest:"jest",mocha:"mocha",pytest:"pytest",cargo:"cargo",pester:"pester","go-test":"go-test",maven:"maven",gradle:"gradle","dotnet-test":"dotnet-test",ctest:"ctest","swift-test":"swift-test","dart-test":"dart-test",rspec:"rspec",minitest:"minitest",pest:"pest",phpunit:"phpunit","php-artisan":"php-artisan","bun:test":"bun","xcodebuild-test":"swift-test","flutter test":"dart-test","dart test":"dart-test",Pest:"pest",PHPUnit:"phpunit"};COMPOUND_TEST_EXTENSIONS=[".test.ts",".test.tsx",".test.js",".test.jsx",".tests.ps1",".spec.ts",".spec.tsx",".spec.js",".spec.jsx",".test.ps1",".spec.ps1"],TEST_DIRECTORY_NAMES=["__tests__","tests","test","spec"];SOURCE_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".ps1",".psm1",".go",".java",".kt",".kts",".cs",".c",".h",".cpp",".hpp",".cc",".cxx",".php",".swift",".dart",".rb",".pyi"]);test_runner=createSwarmTool({description:'Run project tests with automatic framework detection for bun, vitest, jest, mocha, pytest, cargo, pester, go test, maven, gradle, dotnet test, ctest, swift test, dart test, rspec, minitest, pest, phpunit, or php-artisan. Returns JSON with success, framework, scope, command, timeout_ms, duration_ms, totals, outcome, and optional coveragePercent, rawOutput, testCases, and message fields. Scope "target" runs one exact Go test/subtest or CTest name via native_target using a workspace-relative package/build directory, with no broad fallback, coverage, or bail. The "targets" array passes framework-native test name patterns to cargo, go-test, maven, gradle, dotnet-test, ctest, and swift-test.',args:{scope:exports_external.enum(["all","convention","graph","impact","target"]).optional().describe('Test scope: "all" runs the full suite, "convention"/"graph"/"impact" resolve files, and "target" runs one exact Go or CTest native name without file fallback.'),native_target:exports_external.object({framework:exports_external.enum(["go-test","ctest"]),name:exports_external.string(),path:exports_external.string()}).optional().describe('For scope "target": exact framework-native test name plus a workspace-relative package/build directory. Absolute paths, traversal, coverage, bail, and broad fallback are rejected.'),files:exports_external.array(exports_external.string()).optional().describe('Specific files to test. For "convention", pass source files or direct test files. For "graph" and "impact", pass source files only.'),targets:exports_external.array(exports_external.string()).optional().describe("Framework-native test names or patterns to filter which tests run. Supported by cargo, go-test, maven, gradle, dotnet-test, ctest, and swift-test. Each entry is passed as-is to the framework's native filter flag."),coverage:exports_external.boolean().optional().describe("Enable coverage reporting if supported"),bail:exports_external.boolean().optional().describe("Stop running tests after the first failure. Default false. Note: coverage may be incomplete when bail=true with coverage=true."),timeout_ms:exports_external.number().optional().describe("Timeout in milliseconds (default 60000, max 300000)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, tests run relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let workingDirInput;if(args2&&typeof args2==="object"){let obj=args2;workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={success:!1,framework:"none",scope:"all",error:dirResult.message,outcome:"error"};return JSON.stringify(errorResult,null,2)}let workingDir=dirResult.directory;if(workingDir.length>4096)return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(/^[/\\]{2}/.test(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsControlChars(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsPathTraversal(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(!validateArgs2(args2))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid arguments",message:'scope must be "all", "convention", "graph", "impact", or "target"; files and targets must be string arrays with safe values; target scope requires one valid native_target and cannot be combined with files, coverage, or bail',outcome:"error"},null,2);let scope=args2.scope||"all",nativeTarget,nativeExecutionDirectory=workingDir,nativeHistoryPath;if(scope==="target"){let resolvedTarget=resolveNativeTarget(args2.native_target,workingDir);if(!resolvedTarget.success)return JSON.stringify({success:!1,framework:args2.native_target.framework,scope,error:resolvedTarget.error,outcome:"error"},null,2);nativeTarget=resolvedTarget.target,nativeExecutionDirectory=resolvedTarget.executionDirectory,nativeHistoryPath=resolvedTarget.historyPath}if(scope==="all"){if(!process.env.SWARM_ALLOW_FULL_SUITE)return JSON.stringify({success:!1,framework:"none",scope:"all",error:'scope "all" is blocked for agent use. Use scope "convention" with specific test files, or scope "graph" with exactly one source file.',message:'The full test suite is blocked in agent context. Use scope "convention" with specific test files, or scope "graph" with exactly one source file. Example: { scope: "convention", files: ["src/tools/test-runner.ts"] }',outcome:"error"},null,2)}if((scope==="convention"||scope==="graph"||scope==="impact")&&(!args2.files||args2.files.length===0)&&(!args2.targets||args2.targets.length===0))return JSON.stringify({success:!1,framework:"none",scope,error:'scope "convention" and "graph" require explicit files or targets array - omitting both causes unsafe full-project discovery',message:'When using scope "convention" or "graph", you must provide a non-empty "files" or "targets" array. Use scope "all" for full project test suite without specifying files.',outcome:"error"},null,2);let _files=args2.files||[],coverage=args2.coverage||!1,bail=args2.bail||!1,timeout_ms=Math.min(args2.timeout_ms||DEFAULT_TIMEOUT_MS3,MAX_TIMEOUT_MS3),useDispatch=process.env.SWARM_LANG_BACKEND!=="legacy",framework;if(nativeTarget)framework=nativeTarget.framework;else if(useDispatch){if(framework=await detectTestFrameworkViaDispatch(workingDir),framework==="none")framework=await detectTestFramework(workingDir)}else framework=await detectTestFramework(workingDir);if(framework==="none")return JSON.stringify({success:!1,framework:"none",scope,error:"No test framework detected",message:"No supported test framework found. Install bun, vitest, jest, mocha, pytest, cargo, pester, or a supported language test runner (go test, maven, gradle, dotnet test, ctest, swift test, dart test, rspec, minitest).",totals:{passed:0,failed:0,skipped:0,total:0},outcome:"error"},null,2);let testFiles=[],graphFallbackReason,effectiveScope=scope;if(scope==="target");else if(scope==="all");else if(scope==="convention"){let directTestFiles=args2.files.filter((file3)=>isConventionTestFilePath(file3)),sourceFiles=args2.files.filter((file3)=>{if(directTestFiles.includes(file3))return!1;let ext=path164.extname(file3).toLowerCase();return SOURCE_EXTENSIONS.has(ext)}),invalidFiles=args2.files.filter((file3)=>!directTestFiles.includes(file3)&&!sourceFiles.includes(file3));if(directTestFiles.length===0&&sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no recognized source files or direct test files",message:"The files array must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.) or a direct test file in a supported test location/naming convention.",outcome:"error"},null,2);if(invalidFiles.length>0){let errorResult={success:!1,framework,scope,error:"Provided files include entries that are neither recognized source files nor direct test files",message:`These files are not valid for targeted test discovery: ${invalidFiles.join(", ")}`,outcome:"error"};return JSON.stringify(errorResult,null,2)}if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "convention" accepts at most ${MAX_SAFE_SOURCE_FILES} source file for discovery (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "convention" discovery (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or pass direct test file paths instead of source files.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}testFiles=[...directTestFiles,...getTestFilesFromConvention(sourceFiles,workingDir)].filter((file3,index,items)=>items.indexOf(file3)===index)}else if(scope==="graph"){let sourceFiles=args2.files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path164.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)});if(sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "graph" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error"},null,2);if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "graph" accepts at most ${MAX_SAFE_SOURCE_FILES} source file (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "graph" (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or use scope "convention" with direct test file paths.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let estimate=await estimateFanOut(sourceFiles,workingDir);if(estimate.estimatedCount>MAX_SAFE_TEST_FILES){let errorResult={success:!1,framework,scope,error:"Estimated test file count exceeds safe maximum",message:`Scope "graph" resolution would produce approximately ${estimate.estimatedCount} test files, which exceeds the safe limit of ${MAX_SAFE_TEST_FILES}. Break the source files into smaller batches and retry.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}else if(scope==="impact"){let sourceFiles=args2.files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path164.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)});if(sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "impact" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error"},null,2);if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "impact" accepts at most ${MAX_SAFE_SOURCE_FILES} source file (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "impact" (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or use scope "convention" with direct test file paths.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let estimate=await estimateFanOut(sourceFiles,workingDir);if(estimate.estimatedCount>MAX_SAFE_TEST_FILES){let errorResult={success:!1,framework,scope,error:"Estimated test file count exceeds safe maximum",message:`Scope "impact" resolution would produce approximately ${estimate.estimatedCount} test files, which exceeds the safe limit of ${MAX_SAFE_TEST_FILES}. Break the source files into smaller batches and retry.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}try{let impactResult=await _internals129.analyzeImpact(sourceFiles,workingDir,MAX_SAFE_TEST_FILES);if(impactResult.budgetExceeded){let errorResult={success:!1,framework,scope,error:"Budget exceeded during impact analysis",message:`Impact analysis exceeded safe budget of ${MAX_SAFE_TEST_FILES} test files.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}if(impactResult.impactedTests.length>0)testFiles=impactResult.impactedTests.map((absPath)=>{let relativePath2=path164.relative(workingDir,absPath);return path164.isAbsolute(relativePath2)?absPath:relativePath2});else{graphFallbackReason="no impacted tests found via impact analysis, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}}catch{graphFallbackReason="impact analysis failed, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}}if(scope!=="all"&&scope!=="target"&&testFiles.length===0&&!(args2.targets&&args2.targets.length>0)){let errorResult={success:!1,framework,scope:effectiveScope,error:"Provided source files resolved to zero test files",message:graphFallbackReason?`No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/). (${graphFallbackReason})`:"No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/).",outcome:"skip",...scope==="graph"&&{attempted_scope:"graph"},...scope==="impact"&&{attempted_scope:"graph"}};return JSON.stringify(errorResult,null,2)}if(scope!=="all"&&scope!=="target"&&testFiles.length>MAX_SAFE_TEST_FILES){let sampleFiles=testFiles.slice(0,5),errorResult={success:!1,framework,scope:effectiveScope,error:`Resolved test file count (${testFiles.length}) exceeds safe maximum (${MAX_SAFE_TEST_FILES})`,message:`Too many test files resolved (${testFiles.length}). Maximum allowed is ${MAX_SAFE_TEST_FILES}. Treat this as SKIP without retry. Provide more specific source files to narrow down test scope. First few resolved: ${sampleFiles.join(", ")}`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let result=await runTests(framework,effectiveScope,testFiles,coverage,timeout_ms,nativeExecutionDirectory,bail,args2.targets,nativeTarget),historyTestFiles=nativeTarget?[formatNativeHistoryTestFile(nativeTarget,nativeHistoryPath)]:testFiles;recordAndAnalyzeResults(result,historyTestFiles,workingDir,nativeTarget?[]:_files.length>0?_files:void 0,result.testCases);let historyReport;if(!result.success&&result.totals&&result.totals.failed>0){if(historyReport=analyzeFailures(workingDir),historyReport.quarantinedFailures.length>0)result.message=(result.message||"")+` | QUARANTINED (flaky): ${historyReport.quarantinedFailures.join(", ")}`;if(historyReport.failureClusters.length>0){let clusterSummary=historyReport.failureClusters.slice(0,3).map((c)=>`${c.classification}: ${c.rootCause.substring(0,80)}`).join("; ");result.message=`${result.message||""} | FAILURE ANALYSIS: ${clusterSummary}`}}if(graphFallbackReason&&result.message)result.message=`${result.message} (${graphFallbackReason})`;if(bail&&coverage&&result.message)result.message=`${result.message} (coverage may be incomplete: bail=true stopped early)`;return JSON.stringify(result,null,2)}}),_internals129={analyzeImpact,loadImpactMap,isCommandAvailable,existsSync:fs86.existsSync,readdirSync:fs86.readdirSync,readFileSync:fs86.readFileSync,bunSpawn,buildNativeTargetCommand,formatNativeHistoryTestFile,selectHistoryForAnalysis,AGGREGATE_TEST_NAME}});import*as fs87 from"node:fs";import*as path165 from"node:path";function formatSecretscanIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function validateDirectoryPath(dir){if(!dir||typeof dir!=="string")throw Error("Directory path is required");if(dir.includes(".."))throw Error("Directory path must not contain path traversal sequences");let normalized=path165.normalize(dir);return path165.isAbsolute(normalized)?normalized:path165.resolve(normalized)}function validateTimeout(timeoutMs,defaultValue){if(timeoutMs===void 0)return defaultValue;if(typeof timeoutMs!=="number"||!Number.isFinite(timeoutMs))throw Error("Timeout must be a finite number");if(timeoutMs<=0)throw Error("Timeout must be greater than 0");if(timeoutMs<MIN_CHECK_TIMEOUT_MS)throw Error(`Timeout must be at least ${MIN_CHECK_TIMEOUT_MS}ms (5 seconds)`);if(timeoutMs>MAX_CHECK_TIMEOUT_MS)throw Error(`Timeout must not exceed ${MAX_CHECK_TIMEOUT_MS}ms (5 minutes)`);return timeoutMs}function getPackageVersion(dir){try{let packagePath=path165.join(dir,"package.json");if(fs87.existsSync(packagePath)){let content=fs87.readFileSync(packagePath,"utf-8");return JSON.parse(content).version??null}}catch{}return null}function getChangelogVersion(dir){try{let changelogPath=path165.join(dir,"CHANGELOG.md");if(fs87.existsSync(changelogPath)){let match=fs87.readFileSync(changelogPath,"utf-8").match(/^##\s*\[?(\d+\.\d+\.\d+)\]?/m);if(match)return match[1]}}catch{}return null}function getVersionFileVersion(dir){let possibleFiles=["VERSION.txt","version.txt","VERSION","version"];for(let file3 of possibleFiles){let filePath=path165.join(dir,file3);if(fs87.existsSync(filePath))try{let match=fs87.readFileSync(filePath,"utf-8").trim().match(/(\d+\.\d+\.\d+)/);if(match)return match[1]}catch{}}return null}async function runVersionCheck2(dir,_timeoutMs){let startTime=Date.now();try{let packageVersion=_internals130.getPackageVersion(dir),changelogVersion=_internals130.getChangelogVersion(dir),versionFileVersion=_internals130.getVersionFileVersion(dir),versions3=[];if(packageVersion)versions3.push(`package.json: ${packageVersion}`);if(changelogVersion)versions3.push(`CHANGELOG.md: ${changelogVersion}`);if(versionFileVersion)versions3.push(`version file: ${versionFileVersion}`);if(new Set([packageVersion,changelogVersion,versionFileVersion].filter(Boolean)).size<=1){if(versions3.length===0)return{type:"version",status:"skip",message:"No version information found to check",details:{},durationMs:Date.now()-startTime};return{type:"version",status:"pass",message:`Version consistent: ${versions3.join(", ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}return{type:"version",status:"fail",message:`Version mismatch: ${versions3.join("; ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}catch(error93){return{type:"version",status:"error",message:`Version check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runLintCheck(dir,linter,timeoutMs){let startTime=Date.now();try{let lintPromise=runLint(linter,"check",dir),timeoutId,timeoutPromise=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(Error(`Lint check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([lintPromise,timeoutPromise]).finally(()=>clearTimeout(timeoutId));if(!result.success)return{type:"lint",status:"error",message:result.error??"Lint check failed",details:{linter,success:result.success},durationMs:Date.now()-startTime};if(result.exitCode!==0){let issueMatch=result.output.match(/(\d+)\s+(issues?|errors?)/i),issueCount=issueMatch?parseInt(issueMatch[1],10):void 0;return{type:"lint",status:"fail",message:issueCount?`Lint found ${issueCount} issue(s)`:"Lint found issues",details:{linter,exitCode:result.exitCode,issueCount,hasOutput:result.output.length>0},durationMs:Date.now()-startTime}}return{type:"lint",status:"pass",message:"Lint check passed",details:{linter,exitCode:result.exitCode},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))return{type:"lint",status:"error",message:error93.message,details:{linter},durationMs:Date.now()-startTime};return{type:"lint",status:"error",message:`Lint check failed: ${error93 instanceof Error?error93.message:String(error93)}`,details:{linter},durationMs:Date.now()-startTime}}}async function runTestsCheck(_dir,scope,timeoutMs){let startTime=Date.now();try{let result=await runTests("none",scope,[],!1,timeoutMs,_dir,!1);if(!result.success)return{type:"tests",status:"error",message:result.error??"Tests check failed",details:{framework:result.framework,scope,success:result.success},durationMs:Date.now()-startTime};if(result.totals.failed>0)return{type:"tests",status:"fail",message:`Tests failed: ${result.totals.failed}/${result.totals.total} failed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime};if(result.totals.total===0)return{type:"tests",status:"skip",message:"No tests found to run",details:{framework:result.framework,scope},durationMs:Date.now()-startTime};return{type:"tests",status:"pass",message:`Tests passed: ${result.totals.passed} passed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&(error93.message.includes("timeout")||error93.message.includes("ETIMEDOUT")))return{type:"tests",status:"error",message:`Tests check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"tests",status:"error",message:`Tests check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runSecretsCheck(dir,timeoutMs){let startTime=Date.now();try{let secretsPromise=_internals130.runSecretscan(dir),timeoutPromise=new Promise((_,reject)=>{setTimeout(()=>{reject(Error(`Secrets check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([secretsPromise,timeoutPromise]);if("error"in result)return{type:"secrets",status:"fail",message:`Secrets check failed: ${result.error}`,details:{error:result.error,filesScanned:result.files_scanned,incompleteFiles:0,incompletePaths:[]},durationMs:Date.now()-startTime};let findingsCount=Math.max(result.count,result.findings.length);if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{type:"secrets",status:"fail",message:"Secrets check failed: scanner returned incomplete coverage metadata",details:{filesScanned:result.files_scanned},durationMs:Date.now()-startTime};let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=result,hasCountMismatch=result.count!==result.findings.length,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasZeroCoverage=result.files_scanned===0,failures=[];if(findingsCount>0){let critical=result.findings.filter((f)=>f.severity==="critical").length,high=result.findings.filter((f)=>f.severity==="high").length;failures.push(`Found ${findingsCount} secret(s): ${critical} critical, ${high} high`)}if(hasIncompleteCoverage){let incompleteSummary=incompletePaths.length>0?`; incomplete paths: ${formatSecretscanIncompletePaths(incompletePaths)}`:"";failures.push(`${incompleteFiles} incomplete file(s)${incompleteSummary}`)}if(hasCountMismatch)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(hasZeroCoverage)failures.push("zero requested files scanned");if(failures.length>0)return{type:"secrets",status:"fail",message:`Secrets check failed: ${failures.join("; ")}`,details:{count:findingsCount,reportedCount:result.count,critical:result.findings.filter((f)=>f.severity==="critical").length,high:result.findings.filter((f)=>f.severity==="high").length,filesScanned:result.files_scanned,skippedFiles:result.skipped_files,incompleteFiles,incompletePaths},durationMs:Date.now()-startTime};return{type:"secrets",status:"pass",message:"No secrets detected",details:{filesScanned:result.files_scanned,skippedFiles:result.skipped_files,incompleteFiles,incompletePaths},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.name==="AbortError")return{type:"secrets",status:"error",message:`Secrets check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"secrets",status:"error",message:`Secrets check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runEvidenceCheck(dir){let startTime=Date.now();try{let plan=await loadPlan(dir);if(!plan)return{type:"evidence",status:"skip",message:"No plan found to check evidence against",details:{},durationMs:Date.now()-startTime};let completedTaskIds=[];for(let phase of plan.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.push(task.id);if(completedTaskIds.length===0)return{type:"evidence",status:"skip",message:"No completed tasks yet",details:{completedTasks:0},durationMs:Date.now()-startTime};let evidenceTaskIds=new Set(await listEvidenceTaskIds(dir)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(dir,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}let completedWithEvidence=completedTaskIds.length-missingEvidence.length;if(missingEvidence.length>0)return{type:"evidence",status:"fail",message:`${missingEvidence.length} completed task(s) missing evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence,missingTasks:missingEvidence.slice(0,10),missingCount:missingEvidence.length},durationMs:Date.now()-startTime};return{type:"evidence",status:"pass",message:`All ${completedTaskIds.length} completed tasks have evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence},durationMs:Date.now()-startTime}}catch(error93){return{type:"evidence",status:"error",message:`Evidence check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runRequirementCoverageCheck(dir,currentPhase){let startTime=Date.now();try{if(readEffectiveSpecSync(dir)===null)return{type:"req_coverage",status:"skip",message:"No effective spec found, requirement coverage not required",details:{},durationMs:Date.now()-startTime};let coverage=await checkRequirementCoverage(currentPhase,dir);if(coverage.exists)return{type:"req_coverage",status:"pass",message:"Requirement coverage report found",details:{path:coverage.path},durationMs:Date.now()-startTime};return{type:"req_coverage",status:"fail",message:"Requirement coverage report missing but effective spec exists",details:{expectedPath:coverage.path},durationMs:Date.now()-startTime}}catch(error93){return{type:"req_coverage",status:"error",message:`Requirement coverage check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runPreflight(dir,phase,config3){let startTime=Date.now(),reportId=`preflight-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,validatedDir;try{validatedDir=_internals130.validateDirectoryPath(dir)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid directory: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid directory"}}let validatedTimeout;try{validatedTimeout=_internals130.validateTimeout(config3?.checkTimeoutMs,DEFAULT_CONFIG.checkTimeoutMs)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid config: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid configuration"}}let cfg={checkTimeoutMs:validatedTimeout,skipTests:config3?.skipTests??DEFAULT_CONFIG.skipTests,skipSecrets:config3?.skipSecrets??DEFAULT_CONFIG.skipSecrets,skipEvidence:config3?.skipEvidence??DEFAULT_CONFIG.skipEvidence,skipVersion:config3?.skipVersion??DEFAULT_CONFIG.skipVersion,testScope:config3?.testScope??DEFAULT_CONFIG.testScope,linter:config3?.linter??DEFAULT_CONFIG.linter};log("[Preflight] Starting preflight checks",{reportId,phase,config:{skipTests:cfg.skipTests,skipSecrets:cfg.skipSecrets,skipEvidence:cfg.skipEvidence,skipVersion:cfg.skipVersion,testScope:cfg.testScope,linter:cfg.linter}});let checks5=[];log("[Preflight] Running lint check...");let lintResult=await _internals130.runLintCheck(validatedDir,cfg.linter,cfg.checkTimeoutMs);if(checks5.push(lintResult),log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`),!cfg.skipTests){log("[Preflight] Running tests check...");let testsResult=await _internals130.runTestsCheck(validatedDir,cfg.testScope,cfg.checkTimeoutMs);checks5.push(testsResult),log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`)}else checks5.push({type:"tests",status:"skip",message:"Tests check skipped by configuration"});if(!cfg.skipSecrets){log("[Preflight] Running secrets check...");let secretsResult=await _internals130.runSecretsCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(secretsResult),log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`)}else checks5.push({type:"secrets",status:"skip",message:"Secrets check skipped by configuration"});if(!cfg.skipEvidence){log("[Preflight] Running evidence check...");let evidenceResult=await _internals130.runEvidenceCheck(validatedDir);checks5.push(evidenceResult),log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`)}else checks5.push({type:"evidence",status:"skip",message:"Evidence check skipped by configuration"});log("[Preflight] Running requirement coverage check...");let reqCoverageResult=await _internals130.runRequirementCoverageCheck(validatedDir,phase);if(checks5.push(reqCoverageResult),log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`),!cfg.skipVersion){log("[Preflight] Running version check...");let versionResult=await _internals130.runVersionCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(versionResult),log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`)}else checks5.push({type:"version",status:"skip",message:"Version check skipped by configuration"});let totalDurationMs=Date.now()-startTime,failedChecks=checks5.filter((c)=>c.status==="fail").length,errorChecks=checks5.filter((c)=>c.status==="error").length,skippedChecks=checks5.filter((c)=>c.status==="skip").length,overall,message;if(errorChecks>0)overall="fail",message=`Preflight failed with ${errorChecks} error(s)`;else if(failedChecks>0)overall="fail",message=`Preflight failed: ${failedChecks} check(s) failed`;else if(skippedChecks===checks5.length)overall="skipped",message="All checks were skipped";else overall="pass",message="Preflight passed all checks";return log(`[Preflight] Complete: ${overall} ${message}`),{id:reportId,timestamp:startTime,phase,overall,checks:checks5,totalDurationMs,message}}function formatPreflightMarkdown(report){let lines=["## Preflight Report","",`**Phase**: ${report.phase}`,`**Overall**: ${report.overall==="pass"?"✅ PASS":report.overall==="fail"?"❌ FAIL":"⏭️ SKIPPED"}`,`**Duration**: ${(report.totalDurationMs/1000).toFixed(2)}s`,"","### Checks",""];for(let check3 of report.checks){let icon=check3.status==="pass"?"✅":check3.status==="fail"?"❌":check3.status==="error"?"⚠️":"⏭️";lines.push(`- ${icon} **${check3.type}**: ${check3.message}`)}return lines.push(""),lines.push(report.message),lines.join(`
|
|
2159
|
-
`)}async function handlePreflightCommand(directory,_args){let phase=(await loadPlan(directory))?.current_phase??1,report=await _internals130.runPreflight(directory,phase);return _internals130.formatPreflightMarkdown(report)}var MIN_CHECK_TIMEOUT_MS=5000,MAX_CHECK_TIMEOUT_MS=300000,DEFAULT_CONFIG,_internals130;var init_preflight_service=__esm(()=>{init_gate_bridge();init_manager2();init_manager();init_effective_spec();init_lint();init_secretscan();init_test_runner();init_utils();DEFAULT_CONFIG={checkTimeoutMs:60000,skipTests:!1,skipSecrets:!1,skipEvidence:!1,skipVersion:!1,testScope:"convention",linter:"biome"};_internals130={runPreflight,formatPreflightMarkdown,handlePreflightCommand,validateDirectoryPath,validateTimeout,getPackageVersion,getChangelogVersion,getVersionFileVersion,runVersionCheck:runVersionCheck2,runLintCheck,runTestsCheck,runSecretscan,runSecretsCheck,runEvidenceCheck,runRequirementCoverageCheck}});var init_preflight=__esm(()=>{init_preflight_service()});function parsePromoteArgs(args2){let category,lessonId,lessonText,force=!1,reason,actionable={};for(let i=0;i<args2.length;i++){let arg=args2[i],actionabilityField=ACTIONABILITY_LIST_FLAGS.get(arg);if(arg==="--category"&&i+1<args2.length)category=args2[i+1],i++;else if(arg==="--from-swarm"&&i+1<args2.length)lessonId=args2[i+1],i++;else if(arg==="--force")force=!0;else if(arg==="--reason"&&i+1<args2.length)reason=args2[i+1],i++;else if(actionabilityField!==void 0&&i+1<args2.length){let supplied=args2[i+1].split(",").map((v)=>v.trim()).filter((v)=>v.length>0);actionable[actionabilityField]=dedupeCapped([...actionable[actionabilityField]??[],...supplied],{cap:ACTIONABILITY_FIELD_CAP}),i++}else if(!arg.startsWith("--")){lessonText=args2.slice(i).join(" ");break}}return{category,lessonId,lessonText,force,reason,actionable}}async function handlePromoteCommand(directory,args2){let{category,lessonId,lessonText,force,reason,actionable}=parsePromoteArgs(args2);if(!lessonText&&!lessonId)return`Usage: /swarm promote "<lesson text>" or /swarm promote --from-swarm <id>
|
|
2160
|
+
... (output truncated at stream read limit)`;let parsed=process.env.SWARM_LANG_BACKEND!=="legacy"?await parseTestOutputViaDispatch(framework,output,executionCwd)??parseTestOutput2(framework,output):parseTestOutput2(framework,output),parsedTestCases=parseFrameworkJsonTestResults(framework,output),totals={...parsed.totals},{coveragePercent}=parsed;if(totals.total===0&&parsedTestCases.length>0){for(let entry of parsedTestCases)if(entry.result==="pass")totals.passed++;else if(entry.result==="fail")totals.failed++;else totals.skipped++;totals.total=parsedTestCases.length}let isTimeout=timedOutByDeadline,nativeTargetObserved=resolvedNativeTarget?didExecuteNativeTarget(resolvedNativeTarget,output):!0;if(exitCode===0&&!isTimeout&&totals.failed===0&&nativeTargetObserved){let result={success:!0,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,outcome:"pass",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;return result.message=formatPassingMessage(framework,totals,coveragePercent),result}else{let result={success:!1,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,error:isTimeout?`Tests timed out after ${timeout_ms}ms`:!nativeTargetObserved?`Native target "${resolvedNativeTarget?.name}" did not execute`:`Tests failed with ${totals.failed} failures`,message:isTimeout?`${framework} tests timed out after ${timeout_ms}ms`:!nativeTargetObserved?`${framework} did not report the exact requested native target; refusing a false-green 0/0 result`:`${framework} tests failed (${totals.failed}/${totals.total} failed)`,outcome:isTimeout?"error":"regression",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;return result}}catch(error93){let duration_ms=Date.now()-startTime;return{success:!1,framework,scope,command,timeout_ms,duration_ms,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error",outcome:"error"}}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(proc?.exitCode===null&&!timedOutByDeadline)try{if(proc.killTree)await proc.killTree("SIGKILL");else proc.kill("SIGKILL")}catch{}}}function escapeRegexForMatch(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function didExecuteNativeTarget(target,output){if(target.framework==="go-test")return[...output.matchAll(/^\s*--- (?:PASS|FAIL|SKIP):\s+(.+?)(?:\s+\(|$)/gm)].some((match)=>match[1]===target.name);let exactName=escapeRegexForMatch(target.name);return new RegExp(`(?:Start\\s+\\d+:\\s*|Test\\s+#\\d+:\\s*)${exactName}(?=\\s|$)`,"m").test(output)}function normalizeHistoryTestFile(testFile,workingDir){let normalized=testFile.replace(/\\/g,"/");if(!path164.isAbsolute(testFile))return normalized;let relative35=path164.relative(workingDir,testFile);if(relative35.startsWith("..")||path164.isAbsolute(relative35))return normalized;return relative35.replace(/\\/g,"/")}function combineAggregateResult(current,next){if(current==="fail"||next==="fail")return"fail";if(current==="pass"||next==="pass")return"pass";return"skip"}function recordAndAnalyzeResults(result,testFiles,workingDir,sourceFiles,parsedTestCases){if(!result.totals||result.totals.total===0)return;let now2=new Date().toISOString(),changedFiles=(sourceFiles!==void 0?sourceFiles:testFiles).map((f)=>f.replace(/\\/g,"/")),aggregateResultsByFile=new Map,validParsedCases=parsedTestCases?.filter((parsedCase)=>parsedCase.testFile.length>0&&parsedCase.testName.length>0)??[],allRecords=[];for(let parsedCase of validParsedCases){let normalizedTestFile=normalizeHistoryTestFile(parsedCase.testFile,workingDir);allRecords.push({timestamp:now2,taskId:"auto",testFile:normalizedTestFile,testName:parsedCase.testName,result:parsedCase.result,durationMs:parsedCase.durationMs,errorMessage:parsedCase.errorMessage,stackPrefix:parsedCase.stackPrefix,changedFiles}),aggregateResultsByFile.set(normalizedTestFile,combineAggregateResult(aggregateResultsByFile.get(normalizedTestFile),parsedCase.result))}if(aggregateResultsByFile.size===0){let aggregateResult=result.success?"pass":"fail";for(let testFile of testFiles)aggregateResultsByFile.set(testFile.replace(/\\/g,"/"),aggregateResult)}for(let[testFile,aggregateResult]of aggregateResultsByFile)allRecords.push({timestamp:now2,taskId:"auto",testFile,testName:AGGREGATE_TEST_NAME,result:aggregateResult,durationMs:result.duration_ms||0,changedFiles});try{batchAppendTestRuns(allRecords,workingDir)}catch{}}function selectHistoryForAnalysis(history){let filesWithIndividualRecords=new Set;for(let record3 of history)if(record3.testName!==AGGREGATE_TEST_NAME)filesWithIndividualRecords.add(record3.testFile.toLowerCase());if(filesWithIndividualRecords.size===0)return history;return history.filter((record3)=>record3.testName!==AGGREGATE_TEST_NAME||!filesWithIndividualRecords.has(record3.testFile.toLowerCase()))}function analyzeFailures(workingDir){let report={flakyTests:[],failureClusters:[],quarantinedFailures:[]};try{let history=selectHistoryForAnalysis(getAllHistory(workingDir));if(history.length===0)return report;report.flakyTests=detectFlakyTests(history);let failingResults=history.filter((r)=>r.result==="fail");if(failingResults.length>0){let{clusters}=classifyAndCluster(failingResults,history);report.failureClusters=clusters.map((c)=>({rootCause:c.rootCause,affectedFiles:c.affectedTestFiles,classification:c.classification}))}for(let entry of report.flakyTests)if(entry.isQuarantined)report.quarantinedFailures.push(`${entry.testFile}: ${entry.testName}`)}catch{}return report}var MAX_OUTPUT_BYTES4=512000,MAX_COMMAND_LENGTH2=500,DEFAULT_TIMEOUT_MS3=60000,MAX_TIMEOUT_MS3=300000,MAX_SAFE_TEST_FILES=50,MAX_SAFE_SOURCE_FILES=1,AGGREGATE_TEST_NAME="(aggregate)",VITEST_JSON_OUTPUT_RELATIVE_PATH=".swarm/cache/test-runner-vitest.json",POWERSHELL_METACHARACTERS,SHELL_METACHARACTERS2,DISPATCH_FRAMEWORK_MAP,COMPOUND_TEST_EXTENSIONS,TEST_DIRECTORY_NAMES,SOURCE_EXTENSIONS,test_runner,_internals129;var init_test_runner=__esm(()=>{init_zod();init_discovery();init_default_backend();init_analyzer();init_failure_classifier();init_history_store();init_bun_compat();init_path_security();init_create_tool();init_resolve_working_directory();POWERSHELL_METACHARACTERS=/[|;&`$(){}[\]<>"'#*?\x00-\x1f]/;SHELL_METACHARACTERS2=/[;&`$(){}<>"'\x00-\x1f]/;DISPATCH_FRAMEWORK_MAP={bun:"bun",vitest:"vitest",jest:"jest",mocha:"mocha",pytest:"pytest",cargo:"cargo",pester:"pester","go-test":"go-test",maven:"maven",gradle:"gradle","dotnet-test":"dotnet-test",ctest:"ctest","swift-test":"swift-test","dart-test":"dart-test",rspec:"rspec",minitest:"minitest",pest:"pest",phpunit:"phpunit","php-artisan":"php-artisan","bun:test":"bun","xcodebuild-test":"swift-test","flutter test":"dart-test","dart test":"dart-test",Pest:"pest",PHPUnit:"phpunit"};COMPOUND_TEST_EXTENSIONS=[".test.ts",".test.tsx",".test.js",".test.jsx",".tests.ps1",".spec.ts",".spec.tsx",".spec.js",".spec.jsx",".test.ps1",".spec.ps1"],TEST_DIRECTORY_NAMES=["__tests__","tests","test","spec"];SOURCE_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".ps1",".psm1",".go",".java",".kt",".kts",".cs",".c",".h",".cpp",".hpp",".cc",".cxx",".php",".swift",".dart",".rb",".pyi"]);test_runner=createSwarmTool({description:'Run project tests with automatic framework detection for bun, vitest, jest, mocha, pytest, cargo, pester, go test, maven, gradle, dotnet test, ctest, swift test, dart test, rspec, minitest, pest, phpunit, or php-artisan. Returns JSON with success, framework, scope, command, timeout_ms, duration_ms, totals, outcome, and optional coveragePercent, rawOutput, testCases, and message fields. Scope "target" runs one exact Go test/subtest or CTest name via native_target using a workspace-relative package/build directory, with no broad fallback, coverage, or bail. The "targets" array passes framework-native test name patterns to cargo, go-test, maven, gradle, dotnet-test, ctest, and swift-test.',args:{scope:exports_external.enum(["all","convention","graph","impact","target"]).optional().describe('Test scope: "all" runs the full suite, "convention"/"graph"/"impact" resolve files, and "target" runs one exact Go or CTest native name without file fallback.'),native_target:exports_external.object({framework:exports_external.enum(["go-test","ctest"]),name:exports_external.string(),path:exports_external.string()}).optional().describe('For scope "target": exact framework-native test name plus a workspace-relative package/build directory. Absolute paths, traversal, coverage, bail, and broad fallback are rejected.'),files:exports_external.array(exports_external.string()).optional().describe('Specific files to test. For "convention", pass source files or direct test files. For "graph" and "impact", pass source files only.'),targets:exports_external.array(exports_external.string()).optional().describe("Framework-native test names or patterns to filter which tests run. Supported by cargo, go-test, maven, gradle, dotnet-test, ctest, and swift-test. Each entry is passed as-is to the framework's native filter flag."),coverage:exports_external.boolean().optional().describe("Enable coverage reporting if supported"),bail:exports_external.boolean().optional().describe("Stop running tests after the first failure. Default false. Note: coverage may be incomplete when bail=true with coverage=true."),timeout_ms:exports_external.number().optional().describe("Timeout in milliseconds (default 60000, max 300000)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, tests run relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let workingDirInput;if(args2&&typeof args2==="object"){let obj=args2;workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={success:!1,framework:"none",scope:"all",error:dirResult.message,outcome:"error"};return JSON.stringify(errorResult,null,2)}let workingDir=dirResult.directory;if(workingDir.length>4096)return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(/^[/\\]{2}/.test(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsControlChars(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsPathTraversal(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(!validateArgs2(args2))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid arguments",message:'scope must be "all", "convention", "graph", "impact", or "target"; files and targets must be string arrays with safe values; target scope requires one valid native_target and cannot be combined with files, coverage, or bail',outcome:"error"},null,2);let scope=args2.scope||"all",nativeTarget,nativeExecutionDirectory=workingDir,nativeHistoryPath;if(scope==="target"){let resolvedTarget=resolveNativeTarget(args2.native_target,workingDir);if(!resolvedTarget.success)return JSON.stringify({success:!1,framework:args2.native_target.framework,scope,error:resolvedTarget.error,outcome:"error"},null,2);nativeTarget=resolvedTarget.target,nativeExecutionDirectory=resolvedTarget.executionDirectory,nativeHistoryPath=resolvedTarget.historyPath}if(scope==="all"){if(!process.env.SWARM_ALLOW_FULL_SUITE)return JSON.stringify({success:!1,framework:"none",scope:"all",error:'scope "all" is blocked for agent use. Use scope "convention" with specific test files, or scope "graph" with exactly one source file.',message:'The full test suite is blocked in agent context. Use scope "convention" with specific test files, or scope "graph" with exactly one source file. Example: { scope: "convention", files: ["src/tools/test-runner.ts"] }',outcome:"error"},null,2)}if((scope==="convention"||scope==="graph"||scope==="impact")&&(!args2.files||args2.files.length===0)&&(!args2.targets||args2.targets.length===0))return JSON.stringify({success:!1,framework:"none",scope,error:'scope "convention" and "graph" require explicit files or targets array - omitting both causes unsafe full-project discovery',message:'When using scope "convention" or "graph", you must provide a non-empty "files" or "targets" array. Use scope "all" for full project test suite without specifying files.',outcome:"error"},null,2);let _files=args2.files||[],coverage=args2.coverage||!1,bail=args2.bail||!1,timeout_ms=Math.min(args2.timeout_ms||DEFAULT_TIMEOUT_MS3,MAX_TIMEOUT_MS3),useDispatch=process.env.SWARM_LANG_BACKEND!=="legacy",framework;if(nativeTarget)framework=nativeTarget.framework;else if(useDispatch){if(framework=await detectTestFrameworkViaDispatch(workingDir),framework==="none")framework=await detectTestFramework(workingDir)}else framework=await detectTestFramework(workingDir);if(framework==="none")return JSON.stringify({success:!1,framework:"none",scope,error:"No test framework detected",message:"No supported test framework found. Install bun, vitest, jest, mocha, pytest, cargo, pester, or a supported language test runner (go test, maven, gradle, dotnet test, ctest, swift test, dart test, rspec, minitest).",totals:{passed:0,failed:0,skipped:0,total:0},outcome:"error"},null,2);let testFiles=[],graphFallbackReason,effectiveScope=scope;if(scope==="target");else if(scope==="all");else if(scope==="convention"){let directTestFiles=args2.files.filter((file3)=>isConventionTestFilePath(file3)),sourceFiles=args2.files.filter((file3)=>{if(directTestFiles.includes(file3))return!1;let ext=path164.extname(file3).toLowerCase();return SOURCE_EXTENSIONS.has(ext)}),invalidFiles=args2.files.filter((file3)=>!directTestFiles.includes(file3)&&!sourceFiles.includes(file3));if(directTestFiles.length===0&&sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no recognized source files or direct test files",message:"The files array must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.) or a direct test file in a supported test location/naming convention.",outcome:"error"},null,2);if(invalidFiles.length>0){let errorResult={success:!1,framework,scope,error:"Provided files include entries that are neither recognized source files nor direct test files",message:`These files are not valid for targeted test discovery: ${invalidFiles.join(", ")}`,outcome:"error"};return JSON.stringify(errorResult,null,2)}if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "convention" accepts at most ${MAX_SAFE_SOURCE_FILES} source file for discovery (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "convention" discovery (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or pass direct test file paths instead of source files.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}testFiles=[...directTestFiles,...getTestFilesFromConvention(sourceFiles,workingDir)].filter((file3,index,items)=>items.indexOf(file3)===index)}else if(scope==="graph"){let sourceFiles=args2.files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path164.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)});if(sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "graph" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error"},null,2);if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "graph" accepts at most ${MAX_SAFE_SOURCE_FILES} source file (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "graph" (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or use scope "convention" with direct test file paths.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let estimate=await estimateFanOut(sourceFiles,workingDir);if(estimate.estimatedCount>MAX_SAFE_TEST_FILES){let errorResult={success:!1,framework,scope,error:"Estimated test file count exceeds safe maximum",message:`Scope "graph" resolution would produce approximately ${estimate.estimatedCount} test files, which exceeds the safe limit of ${MAX_SAFE_TEST_FILES}. Break the source files into smaller batches and retry.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}else if(scope==="impact"){let sourceFiles=args2.files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path164.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)});if(sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "impact" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error"},null,2);if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "impact" accepts at most ${MAX_SAFE_SOURCE_FILES} source file (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "impact" (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or use scope "convention" with direct test file paths.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let estimate=await estimateFanOut(sourceFiles,workingDir);if(estimate.estimatedCount>MAX_SAFE_TEST_FILES){let errorResult={success:!1,framework,scope,error:"Estimated test file count exceeds safe maximum",message:`Scope "impact" resolution would produce approximately ${estimate.estimatedCount} test files, which exceeds the safe limit of ${MAX_SAFE_TEST_FILES}. Break the source files into smaller batches and retry.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}try{let impactResult=await _internals129.analyzeImpact(sourceFiles,workingDir,MAX_SAFE_TEST_FILES);if(impactResult.budgetExceeded){let errorResult={success:!1,framework,scope,error:"Budget exceeded during impact analysis",message:`Impact analysis exceeded safe budget of ${MAX_SAFE_TEST_FILES} test files.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}if(impactResult.impactedTests.length>0)testFiles=impactResult.impactedTests.map((absPath)=>{let relativePath2=path164.relative(workingDir,absPath);return path164.isAbsolute(relativePath2)?absPath:relativePath2});else{graphFallbackReason="no impacted tests found via impact analysis, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}}catch{graphFallbackReason="impact analysis failed, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}}if(scope!=="all"&&scope!=="target"&&testFiles.length===0&&!(args2.targets&&args2.targets.length>0)){let errorResult={success:!1,framework,scope:effectiveScope,error:"Provided source files resolved to zero test files",message:graphFallbackReason?`No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/). (${graphFallbackReason})`:"No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/).",outcome:"skip",...scope==="graph"&&{attempted_scope:"graph"},...scope==="impact"&&{attempted_scope:"graph"}};return JSON.stringify(errorResult,null,2)}if(scope!=="all"&&scope!=="target"&&testFiles.length>MAX_SAFE_TEST_FILES){let sampleFiles=testFiles.slice(0,5),errorResult={success:!1,framework,scope:effectiveScope,error:`Resolved test file count (${testFiles.length}) exceeds safe maximum (${MAX_SAFE_TEST_FILES})`,message:`Too many test files resolved (${testFiles.length}). Maximum allowed is ${MAX_SAFE_TEST_FILES}. Treat this as SKIP without retry. Provide more specific source files to narrow down test scope. First few resolved: ${sampleFiles.join(", ")}`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let result=await runTests(framework,effectiveScope,testFiles,coverage,timeout_ms,nativeExecutionDirectory,bail,args2.targets,nativeTarget),historyTestFiles=nativeTarget?[formatNativeHistoryTestFile(nativeTarget,nativeHistoryPath)]:testFiles;recordAndAnalyzeResults(result,historyTestFiles,workingDir,nativeTarget?[]:_files.length>0?_files:void 0,result.testCases);let historyReport;if(!result.success&&result.totals&&result.totals.failed>0){if(historyReport=analyzeFailures(workingDir),historyReport.quarantinedFailures.length>0)result.message=(result.message||"")+` | QUARANTINED (flaky): ${historyReport.quarantinedFailures.join(", ")}`;if(historyReport.failureClusters.length>0){let clusterSummary=historyReport.failureClusters.slice(0,3).map((c)=>`${c.classification}: ${c.rootCause.substring(0,80)}`).join("; ");result.message=`${result.message||""} | FAILURE ANALYSIS: ${clusterSummary}`}}if(graphFallbackReason&&result.message)result.message=`${result.message} (${graphFallbackReason})`;if(bail&&coverage&&result.message)result.message=`${result.message} (coverage may be incomplete: bail=true stopped early)`;return JSON.stringify(result,null,2)}}),_internals129={analyzeImpact,loadImpactMap,isCommandAvailable,existsSync:fs86.existsSync,readdirSync:fs86.readdirSync,readFileSync:fs86.readFileSync,bunSpawn,buildNativeTargetCommand,formatNativeHistoryTestFile,selectHistoryForAnalysis,AGGREGATE_TEST_NAME}});import*as fs87 from"node:fs";import*as path165 from"node:path";function formatSecretscanIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function validateDirectoryPath(dir){if(!dir||typeof dir!=="string")throw Error("Directory path is required");if(dir.includes(".."))throw Error("Directory path must not contain path traversal sequences");let normalized=path165.normalize(dir);return path165.isAbsolute(normalized)?normalized:path165.resolve(normalized)}function validateTimeout(timeoutMs,defaultValue){if(timeoutMs===void 0)return defaultValue;if(typeof timeoutMs!=="number"||!Number.isFinite(timeoutMs))throw Error("Timeout must be a finite number");if(timeoutMs<=0)throw Error("Timeout must be greater than 0");if(timeoutMs<MIN_CHECK_TIMEOUT_MS)throw Error(`Timeout must be at least ${MIN_CHECK_TIMEOUT_MS}ms (5 seconds)`);if(timeoutMs>MAX_CHECK_TIMEOUT_MS)throw Error(`Timeout must not exceed ${MAX_CHECK_TIMEOUT_MS}ms (5 minutes)`);return timeoutMs}function getPackageVersion(dir){try{let packagePath=path165.join(dir,"package.json");if(fs87.existsSync(packagePath)){let content=fs87.readFileSync(packagePath,"utf-8");return JSON.parse(content).version??null}}catch{}return null}function getChangelogVersion(dir){try{let changelogPath=path165.join(dir,"CHANGELOG.md");if(fs87.existsSync(changelogPath)){let match=fs87.readFileSync(changelogPath,"utf-8").match(/^##\s*\[?(\d+\.\d+\.\d+)\]?/m);if(match)return match[1]}}catch{}return null}function getVersionFileVersion(dir){let possibleFiles=["VERSION.txt","version.txt","VERSION","version"];for(let file3 of possibleFiles){let filePath=path165.join(dir,file3);if(fs87.existsSync(filePath))try{let match=fs87.readFileSync(filePath,"utf-8").trim().match(/(\d+\.\d+\.\d+)/);if(match)return match[1]}catch{}}return null}async function runVersionCheck2(dir,_timeoutMs){let startTime=Date.now();try{let packageVersion=_internals130.getPackageVersion(dir),changelogVersion=_internals130.getChangelogVersion(dir),versionFileVersion=_internals130.getVersionFileVersion(dir),versions3=[];if(packageVersion)versions3.push(`package.json: ${packageVersion}`);if(changelogVersion)versions3.push(`CHANGELOG.md: ${changelogVersion}`);if(versionFileVersion)versions3.push(`version file: ${versionFileVersion}`);if(new Set([packageVersion,changelogVersion,versionFileVersion].filter(Boolean)).size<=1){if(versions3.length===0)return{type:"version",status:"skip",message:"No version information found to check",details:{},durationMs:Date.now()-startTime};return{type:"version",status:"pass",message:`Version consistent: ${versions3.join(", ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}return{type:"version",status:"fail",message:`Version mismatch: ${versions3.join("; ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}catch(error93){return{type:"version",status:"error",message:`Version check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runLintCheck(dir,linter,timeoutMs){let startTime=Date.now();try{let lintPromise=runLint(linter,"check",dir),timeoutId,timeoutPromise=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(Error(`Lint check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([lintPromise,timeoutPromise]).finally(()=>clearTimeout(timeoutId));if(!result.success)return{type:"lint",status:"error",message:result.error??"Lint check failed",details:{linter,success:result.success},durationMs:Date.now()-startTime};if(result.exitCode!==0){let issueMatch=result.output.match(/(\d+)\s+(issues?|errors?)/i),issueCount=issueMatch?parseInt(issueMatch[1],10):void 0;return{type:"lint",status:"fail",message:issueCount?`Lint found ${issueCount} issue(s)`:"Lint found issues",details:{linter,exitCode:result.exitCode,issueCount,hasOutput:result.output.length>0},durationMs:Date.now()-startTime}}return{type:"lint",status:"pass",message:"Lint check passed",details:{linter,exitCode:result.exitCode},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))return{type:"lint",status:"error",message:error93.message,details:{linter},durationMs:Date.now()-startTime};return{type:"lint",status:"error",message:`Lint check failed: ${error93 instanceof Error?error93.message:String(error93)}`,details:{linter},durationMs:Date.now()-startTime}}}async function runTestsCheck(_dir,scope,timeoutMs){let startTime=Date.now();try{let result=await runTests("none",scope,[],!1,timeoutMs,_dir,!1);if(!result.success)return{type:"tests",status:"error",message:result.error??"Tests check failed",details:{framework:result.framework,scope,success:result.success},durationMs:Date.now()-startTime};if(result.totals.failed>0)return{type:"tests",status:"fail",message:`Tests failed: ${result.totals.failed}/${result.totals.total} failed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime};if(result.totals.total===0)return{type:"tests",status:"skip",message:"No tests found to run",details:{framework:result.framework,scope},durationMs:Date.now()-startTime};return{type:"tests",status:"pass",message:`Tests passed: ${result.totals.passed} passed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&(error93.message.includes("timeout")||error93.message.includes("ETIMEDOUT")))return{type:"tests",status:"error",message:`Tests check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"tests",status:"error",message:`Tests check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runSecretsCheck(dir,timeoutMs){let startTime=Date.now();try{let secretsPromise=_internals130.runSecretscan(dir),timeoutPromise=new Promise((_,reject)=>{setTimeout(()=>{reject(Error(`Secrets check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([secretsPromise,timeoutPromise]);if("error"in result)return{type:"secrets",status:"fail",message:`Secrets check failed: ${result.error}`,details:{error:result.error,filesScanned:result.files_scanned,incompleteFiles:0,incompletePaths:[]},durationMs:Date.now()-startTime};let findingsCount=Math.max(result.count,result.findings.length);if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{type:"secrets",status:"fail",message:"Secrets check failed: scanner returned incomplete coverage metadata",details:{filesScanned:result.files_scanned},durationMs:Date.now()-startTime};let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=result,hasCountMismatch=result.count!==result.findings.length,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasZeroCoverage=result.files_scanned===0,failures=[];if(findingsCount>0){let critical=result.findings.filter((f)=>f.severity==="critical").length,high=result.findings.filter((f)=>f.severity==="high").length;failures.push(`Found ${findingsCount} secret(s): ${critical} critical, ${high} high`)}if(hasIncompleteCoverage){let incompleteSummary=incompletePaths.length>0?`; incomplete paths: ${formatSecretscanIncompletePaths(incompletePaths)}`:"";failures.push(`${incompleteFiles} incomplete file(s)${incompleteSummary}`)}if(hasCountMismatch)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(hasZeroCoverage)failures.push("zero requested files scanned");if(failures.length>0)return{type:"secrets",status:"fail",message:`Secrets check failed: ${failures.join("; ")}`,details:{count:findingsCount,reportedCount:result.count,critical:result.findings.filter((f)=>f.severity==="critical").length,high:result.findings.filter((f)=>f.severity==="high").length,filesScanned:result.files_scanned,skippedFiles:result.skipped_files,incompleteFiles,incompletePaths},durationMs:Date.now()-startTime};return{type:"secrets",status:"pass",message:"No secrets detected",details:{filesScanned:result.files_scanned,skippedFiles:result.skipped_files,incompleteFiles,incompletePaths},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.name==="AbortError")return{type:"secrets",status:"error",message:`Secrets check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"secrets",status:"error",message:`Secrets check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runEvidenceCheck(dir){let startTime=Date.now();try{let plan=await loadPlan(dir);if(!plan)return{type:"evidence",status:"skip",message:"No plan found to check evidence against",details:{},durationMs:Date.now()-startTime};let completedTaskIds=[];for(let phase of plan.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.push(task.id);if(completedTaskIds.length===0)return{type:"evidence",status:"skip",message:"No completed tasks yet",details:{completedTasks:0},durationMs:Date.now()-startTime};let evidenceTaskIds=new Set(await listEvidenceTaskIds(dir)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(dir,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}let completedWithEvidence=completedTaskIds.length-missingEvidence.length;if(missingEvidence.length>0)return{type:"evidence",status:"fail",message:`${missingEvidence.length} completed task(s) missing evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence,missingTasks:missingEvidence.slice(0,10),missingCount:missingEvidence.length},durationMs:Date.now()-startTime};return{type:"evidence",status:"pass",message:`All ${completedTaskIds.length} completed tasks have evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence},durationMs:Date.now()-startTime}}catch(error93){return{type:"evidence",status:"error",message:`Evidence check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runRequirementCoverageCheck(dir,currentPhase){let startTime=Date.now();try{if(readEffectiveSpecSync(dir)===null)return{type:"req_coverage",status:"skip",message:"No effective spec found, requirement coverage not required",details:{},durationMs:Date.now()-startTime};let coverage=await checkRequirementCoverage(currentPhase,dir);if(!coverage.exists)return{type:"req_coverage",status:"fail",message:"Requirement coverage report missing but effective spec exists",details:{expectedPath:coverage.path},durationMs:Date.now()-startTime};let raw;try{let stat16=await fs87.promises.stat(coverage.path);if(stat16.size>REQ_COVERAGE_MAX_JSON_BYTES)return{type:"req_coverage",status:"fail",message:`Requirement coverage report exceeds ${REQ_COVERAGE_MAX_JSON_BYTES} byte cap and cannot be validated`,details:{path:coverage.path,sizeBytes:stat16.size},durationMs:Date.now()-startTime};raw=await fs87.promises.readFile(coverage.path,"utf-8")}catch(readError){return{type:"req_coverage",status:"fail",message:`Requirement coverage report unreadable: ${readError instanceof Error?readError.message:String(readError)}`,details:{path:coverage.path},durationMs:Date.now()-startTime}}let trimmed=raw.trim();if(trimmed.length===0)return{type:"req_coverage",status:"fail",message:"Requirement coverage report is empty",details:{path:coverage.path},durationMs:Date.now()-startTime};let parsed;try{parsed=JSON.parse(trimmed)}catch(parseError){return{type:"req_coverage",status:"fail",message:`Requirement coverage report is not valid JSON: ${parseError instanceof Error?parseError.message:String(parseError)}`,details:{path:coverage.path},durationMs:Date.now()-startTime}}let report=ReqCoverageReportSchema.safeParse(parsed);if(!report.success)return{type:"req_coverage",status:"fail",message:"Requirement coverage report does not match the expected report shape",details:{path:coverage.path},durationMs:Date.now()-startTime};let{success:success3,phase,totalRequirements,coveredCount,missingCount,requirements}=report.data;if(!success3)return{type:"req_coverage",status:"fail",message:"Requirement coverage report indicates the coverage run itself failed (success: false)",details:{path:coverage.path},durationMs:Date.now()-startTime};if(phase!==currentPhase)return{type:"req_coverage",status:"fail",message:`Requirement coverage report phase (${phase}) does not match the current phase (${currentPhase})`,details:{path:coverage.path,reportPhase:phase,currentPhase},durationMs:Date.now()-startTime};if(totalRequirements===0)return{type:"req_coverage",status:"fail",message:"Requirement coverage report contains no requirements (totalRequirements is 0) but effective spec exists",details:{path:coverage.path,totalRequirements},durationMs:Date.now()-startTime};if(coveredCount+missingCount!==totalRequirements)return{type:"req_coverage",status:"fail",message:`Requirement coverage report counts are inconsistent: coveredCount (${coveredCount}) + missingCount (${missingCount}) !== totalRequirements (${totalRequirements})`,details:{path:coverage.path,totalRequirements,coveredCount,missingCount},durationMs:Date.now()-startTime};if(requirements.length!==totalRequirements)return{type:"req_coverage",status:"fail",message:`Requirement coverage report requirements array length (${requirements.length}) does not match totalRequirements (${totalRequirements})`,details:{path:coverage.path,totalRequirements,requirementsLength:requirements.length},durationMs:Date.now()-startTime};if(missingCount>0)return{type:"req_coverage",status:"fail",message:`Requirement coverage report has ${missingCount} uncovered requirement(s)`,details:{path:coverage.path,totalRequirements,coveredCount,missingCount},durationMs:Date.now()-startTime};return{type:"req_coverage",status:"pass",message:`Requirement coverage report found: ${coveredCount}/${totalRequirements} requirement(s) covered`,details:{path:coverage.path,totalRequirements,coveredCount,missingCount},durationMs:Date.now()-startTime}}catch(error93){return{type:"req_coverage",status:"error",message:`Requirement coverage check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runPreflight(dir,phase,config3){let startTime=Date.now(),reportId=`preflight-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,validatedDir;try{validatedDir=_internals130.validateDirectoryPath(dir)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid directory: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid directory"}}let validatedTimeout;try{validatedTimeout=_internals130.validateTimeout(config3?.checkTimeoutMs,DEFAULT_CONFIG.checkTimeoutMs)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid config: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid configuration"}}let cfg={checkTimeoutMs:validatedTimeout,skipTests:config3?.skipTests??DEFAULT_CONFIG.skipTests,skipSecrets:config3?.skipSecrets??DEFAULT_CONFIG.skipSecrets,skipEvidence:config3?.skipEvidence??DEFAULT_CONFIG.skipEvidence,skipVersion:config3?.skipVersion??DEFAULT_CONFIG.skipVersion,testScope:config3?.testScope??DEFAULT_CONFIG.testScope,linter:config3?.linter??DEFAULT_CONFIG.linter};log("[Preflight] Starting preflight checks",{reportId,phase,config:{skipTests:cfg.skipTests,skipSecrets:cfg.skipSecrets,skipEvidence:cfg.skipEvidence,skipVersion:cfg.skipVersion,testScope:cfg.testScope,linter:cfg.linter}});let checks5=[];log("[Preflight] Running lint check...");let lintResult=await _internals130.runLintCheck(validatedDir,cfg.linter,cfg.checkTimeoutMs);if(checks5.push(lintResult),log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`),!cfg.skipTests){log("[Preflight] Running tests check...");let testsResult=await _internals130.runTestsCheck(validatedDir,cfg.testScope,cfg.checkTimeoutMs);checks5.push(testsResult),log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`)}else checks5.push({type:"tests",status:"skip",message:"Tests check skipped by configuration"});if(!cfg.skipSecrets){log("[Preflight] Running secrets check...");let secretsResult=await _internals130.runSecretsCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(secretsResult),log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`)}else checks5.push({type:"secrets",status:"skip",message:"Secrets check skipped by configuration"});if(!cfg.skipEvidence){log("[Preflight] Running evidence check...");let evidenceResult=await _internals130.runEvidenceCheck(validatedDir);checks5.push(evidenceResult),log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`)}else checks5.push({type:"evidence",status:"skip",message:"Evidence check skipped by configuration"});log("[Preflight] Running requirement coverage check...");let reqCoverageResult=await _internals130.runRequirementCoverageCheck(validatedDir,phase);if(checks5.push(reqCoverageResult),log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`),!cfg.skipVersion){log("[Preflight] Running version check...");let versionResult=await _internals130.runVersionCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(versionResult),log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`)}else checks5.push({type:"version",status:"skip",message:"Version check skipped by configuration"});let totalDurationMs=Date.now()-startTime,failedChecks=checks5.filter((c)=>c.status==="fail").length,errorChecks=checks5.filter((c)=>c.status==="error").length,skippedChecks=checks5.filter((c)=>c.status==="skip").length,overall,message;if(errorChecks>0)overall="fail",message=`Preflight failed with ${errorChecks} error(s)`;else if(failedChecks>0)overall="fail",message=`Preflight failed: ${failedChecks} check(s) failed`;else if(skippedChecks===checks5.length)overall="skipped",message="All checks were skipped";else overall="pass",message="Preflight passed all checks";return log(`[Preflight] Complete: ${overall} ${message}`),{id:reportId,timestamp:startTime,phase,overall,checks:checks5,totalDurationMs,message}}function formatPreflightMarkdown(report){let lines=["## Preflight Report","",`**Phase**: ${report.phase}`,`**Overall**: ${report.overall==="pass"?"✅ PASS":report.overall==="fail"?"❌ FAIL":"⏭️ SKIPPED"}`,`**Duration**: ${(report.totalDurationMs/1000).toFixed(2)}s`,"","### Checks",""];for(let check3 of report.checks){let icon=check3.status==="pass"?"✅":check3.status==="fail"?"❌":check3.status==="error"?"⚠️":"⏭️";lines.push(`- ${icon} **${check3.type}**: ${check3.message}`)}return lines.push(""),lines.push(report.message),lines.join(`
|
|
2161
|
+
`)}async function handlePreflightCommand(directory,_args){let phase=(await loadPlan(directory))?.current_phase??1,report=await _internals130.runPreflight(directory,phase);return _internals130.formatPreflightMarkdown(report)}var MIN_CHECK_TIMEOUT_MS=5000,MAX_CHECK_TIMEOUT_MS=300000,DEFAULT_CONFIG,ReqCoverageReportSchema,REQ_COVERAGE_MAX_JSON_BYTES=512000,_internals130;var init_preflight_service=__esm(()=>{init_zod();init_gate_bridge();init_manager2();init_manager();init_effective_spec();init_lint();init_secretscan();init_test_runner();init_utils();DEFAULT_CONFIG={checkTimeoutMs:60000,skipTests:!1,skipSecrets:!1,skipEvidence:!1,skipVersion:!1,testScope:"convention",linter:"biome"};ReqCoverageReportSchema=exports_external.object({success:exports_external.boolean(),phase:exports_external.number().int().nonnegative(),totalRequirements:exports_external.number().int().nonnegative(),coveredCount:exports_external.number().int().nonnegative(),missingCount:exports_external.number().int().nonnegative(),requirements:exports_external.array(exports_external.unknown())});_internals130={runPreflight,formatPreflightMarkdown,handlePreflightCommand,validateDirectoryPath,validateTimeout,getPackageVersion,getChangelogVersion,getVersionFileVersion,runVersionCheck:runVersionCheck2,runLintCheck,runTestsCheck,runSecretscan,runSecretsCheck,runEvidenceCheck,runRequirementCoverageCheck}});var init_preflight=__esm(()=>{init_preflight_service()});function parsePromoteArgs(args2){let category,lessonId,lessonText,force=!1,reason,actionable={};for(let i=0;i<args2.length;i++){let arg=args2[i],actionabilityField=ACTIONABILITY_LIST_FLAGS.get(arg);if(arg==="--category"&&i+1<args2.length)category=args2[i+1],i++;else if(arg==="--from-swarm"&&i+1<args2.length)lessonId=args2[i+1],i++;else if(arg==="--force")force=!0;else if(arg==="--reason"&&i+1<args2.length)reason=args2[i+1],i++;else if(actionabilityField!==void 0&&i+1<args2.length){let supplied=args2[i+1].split(",").map((v)=>v.trim()).filter((v)=>v.length>0);actionable[actionabilityField]=dedupeCapped([...actionable[actionabilityField]??[],...supplied],{cap:ACTIONABILITY_FIELD_CAP}),i++}else if(!arg.startsWith("--")){lessonText=args2.slice(i).join(" ");break}}return{category,lessonId,lessonText,force,reason,actionable}}async function handlePromoteCommand(directory,args2){let{category,lessonId,lessonText,force,reason,actionable}=parsePromoteArgs(args2);if(!lessonText&&!lessonId)return`Usage: /swarm promote "<lesson text>" or /swarm promote --from-swarm <id>
|
|
2160
2162
|
Options: --category <cat>, --force --reason "<why>" (audited policy override)
|
|
2161
2163
|
Actionability (direct text only; required unless knowledge.promotion_require_actionable=false):
|
|
2162
2164
|
--applies-to-tools <a,b>, --applies-to-agents <a,b>,
|
|
@@ -6375,7 +6377,7 @@ When all tasks are complete, signal completion.`}async _withStateLock(fn2){let c
|
|
|
6375
6377
|
`)){let line=rawLine.trim();if(!line)continue;let record3;try{record3=JSON.parse(line)}catch{throw Error("BLOCKED: PR workflow lane registry is malformed; cannot safely prepare checkout")}if(typeof record3!=="object"||record3===null||typeof record3.correlationId!=="string"||typeof record3.parentSessionId!=="string"||typeof record3.status!=="string")throw Error("BLOCKED: PR workflow lane registry is invalid; cannot safely prepare checkout");let typed=record3;if(typed.parentSessionId===sessionID&&typeof typed.mode!=="string")throw Error("BLOCKED: active-session lane metadata is invalid; cannot safely prepare checkout");latestByCorrelationID.set(typed.correlationId,typed)}return[...latestByCorrelationID.values()].filter((record3)=>record3.parentSessionId===sessionID&&typeof record3.mode==="string"&&record3.mode.startsWith("swarm-pr-")&&(record3.status==="pending"||record3.status==="running")).length}async function assertExactDirtyPathSet(directory,requestedPaths){let status=await readPorcelainStatus(directory);if(status.untrackedPaths.length>0)throw Error(`BLOCKED: checkout preparation refuses untracked paths (${status.untrackedPaths.slice(0,5).join(", ")}); move or remove them before checkout`);if(status.renameOrCopy)throw Error("BLOCKED: checkout preparation refuses rename or copy changes; resolve them manually before checkout");let dirtySet=new Set(status.dirtyTrackedPaths),requestedSet=new Set(requestedPaths),omitted=[...dirtySet].filter((candidate2)=>!requestedSet.has(candidate2)),notDirty=requestedPaths.filter((candidate2)=>!dirtySet.has(candidate2));if(omitted.length>0||notDirty.length>0)throw Error(`BLOCKED: checkout preparation paths must exactly cover every dirty tracked path (omitted: ${omitted.length?omitted.join(", "):"none"}; not dirty: ${notDirty.length?notDirty.join(", "):"none"})`)}async function assertCleanWorkingTree2(directory,stashOid,options={}){let status;try{status=await readPorcelainStatus(directory)}catch(error93){throw Error(`BLOCKED: stash ${stashOid} was created, but the post-stash working-tree status could not be verified (${error93 instanceof Error?error93.message:String(error93)}). Do not continue; ${manualRecoveryInstruction(stashOid)} and resolve manually.`)}if(status.dirtyTrackedPaths.length>0||status.untrackedPaths.length>0||status.renameOrCopy){if(options.discovery){let remaining=[...status.dirtyTrackedPaths,...status.untrackedPaths].slice(0,5),remainingText=remaining.length>0?remaining.map((entry)=>boundUntrustedPath(entry)).join(", "):"rename/copy changes only";throw Error(`BLOCKED: stash ${stashOid} was created, but the checkout is still not clean (remaining: ${remainingText}). Submodule pointer changes are not preserved by --include-untracked and must be resolved manually. Do not continue; ${manualRecoveryInstruction(stashOid)} and resolve manually.`)}throw Error(`BLOCKED: stash ${stashOid} was created, but the checkout is still not clean. Do not continue; ${manualRecoveryInstruction(stashOid)} and resolve manually.`)}}async function readPorcelainStatus(directory){let result=await _internals184.runGit(directory,["status","--porcelain=v1","-z","--untracked-files=all"],{captureStdout:!0});if(result.exitCode!==0)throw Error("BLOCKED: unable to inspect the full working-tree status safely");let dirtyTrackedPaths=[],untrackedPaths=[],renameOrCopy=!1,records=result.stdout.split("\x00");for(let index=0;index<records.length;index++){let record3=records[index];if(!record3)continue;if(record3.length<4||record3[2]!==" ")throw Error("BLOCKED: working-tree status is malformed; cannot safely prepare checkout");let xy=record3.slice(0,2),filePath=record3.slice(3);if(!filePath)throw Error("BLOCKED: working-tree status contains an empty path; cannot safely prepare checkout");if(xy==="??"){untrackedPaths.push(filePath);continue}if(xy==="!!")continue;if(xy.includes("R")||xy.includes("C"))renameOrCopy=!0,index++;dirtyTrackedPaths.push(filePath)}return{dirtyTrackedPaths,untrackedPaths,renameOrCopy}}async function captureCheckoutIdentity(directory){let head2=await _internals184.runGit(directory,["rev-parse","--verify","HEAD^0"],{captureStdout:!0}),originalHead=head2.stdout.trim().toLowerCase();if(head2.exitCode!==0||!/^[0-9a-f]{40,64}$/i.test(originalHead))throw Error("BLOCKED: unable to capture the original checkout HEAD; no stash was created");let branch=await _internals184.runGit(directory,["symbolic-ref","--quiet","--short","HEAD"],{captureStdout:!0});if(branch.exitCode!==0&&branch.exitCode!==1)throw Error("BLOCKED: unable to capture the original checkout branch; no stash was created");let originalBranch=branch.exitCode===0?branch.stdout.trim():null;if(originalBranch!==null&&!isSafeRecordedBranch(originalBranch))throw Error("BLOCKED: original checkout branch identity is unsafe; no stash was created");return{originalHead,originalBranch}}async function runGit7(directory,args2,options={}){let literalPathspecs=options.literalPathspecs??!0,proc=bunSpawn(["git",...literalPathspecs?["--literal-pathspecs"]:[],...args2],{cwd:directory,stdin:"ignore",stdout:options.captureStdout?"pipe":"ignore",stderr:"ignore",timeout:GIT_TIMEOUT_MS9});try{let[exitCode,stdout]=await Promise.all([proc.exited,options.captureStdout?readBoundedGitStdout(proc.stdout,()=>{try{proc.kill()}catch{}}):Promise.resolve("")]);return{exitCode,stdout}}finally{try{proc.kill()}catch{}}}async function readBoundedGitStdout(stream,onOverflow){let reader=stream.getReader(),chunks=[],totalBytes=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=MAX_GIT_STDOUT_BYTES-totalBytes;if(value.byteLength>remaining)throw onOverflow(),Error("BLOCKED: Git output exceeded the safe capture limit");chunks.push(value),totalBytes+=value.byteLength}}finally{try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}let joined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)joined.set(chunk,offset),offset+=chunk.byteLength;return new TextDecoder().decode(joined)}async function findUniqueMarkedStashOid(directory,stashMarker,notFoundMessage){let list=await _internals184.runGit(directory,["stash","list","--format=%H%x00%gs"],{captureStdout:!0});if(list.exitCode!==0)throw Error("BLOCKED: unable to identify the checkout-preparation stash safely");let matching=list.stdout.split(`
|
|
6376
6378
|
`).map((line)=>line.split("\x00")).filter((parts)=>parts.length===2&&/^[0-9a-f]{40,64}$/i.test(parts[0])&&parts[1].includes(stashMarker));if(matching.length!==1)throw Error(notFoundMessage);return matching[0][0]}async function resolveMarkedStashOid(directory,stashMarker,paths){let stashOid=await findUniqueMarkedStashOid(directory,stashMarker,"BLOCKED: Git did not expose one uniquely identifiable checkout-preparation stash; do not continue to checkout until the requested changes are preserved manually"),changed2=await _internals184.runGit(directory,["stash","show","--name-only","--format=","-z",stashOid],{captureStdout:!0}),changedPaths2=changed2.stdout.split("\x00").filter(Boolean).sort(),expectedPaths=[...paths].sort();if(changed2.exitCode!==0||changedPaths2.length!==expectedPaths.length||changedPaths2.some((value,index)=>value!==expectedPaths[index]))throw Error(`BLOCKED: stash ${stashOid} does not contain exactly the requested checkout-preparation paths; do not continue. ${manualRecoveryInstruction(stashOid)} and resolve manually.`);return stashOid}async function resolveMarkedStashOidByMarker(directory,stashMarker){return findUniqueMarkedStashOid(directory,stashMarker,"BLOCKED: Git did not expose one uniquely identifiable checkout-preparation stash; do not continue to checkout until the discovered changes are preserved manually")}async function countOutstandingReceipts(directory,sessionID){let receipts=await listCheckoutReceiptPaths(directory,sessionID);if(receipts.length===0)return 0;let parsed=await Promise.all(receipts.map(async(entry)=>({...entry,receipt:await readCheckoutRestoreReceipt(directory,entry.receiptPath,sessionID,entry.stashOid)}))),pending=parsed.filter((entry)=>entry.receipt.restoreState!=="applied");if(pending.length>0){let activeStashOids;try{activeStashOids=await readCurrentStashOids(directory)}catch{throw Error("BLOCKED: unable to inspect checkout-preparation receipts safely")}let missing=pending.filter((entry)=>!activeStashOids.has(entry.stashOid));if(missing.length>0)throw new CheckoutRestoreError("CHECKOUT_RESTORE_STASH_MISSING",`BLOCKED: ${missing.length} existing checkout receipt(s) reference missing preserved stashes; no new checkout stash was created`)}return parsed.length}async function readCurrentStashOids(directory){let list=await _internals184.runGit(directory,["stash","list","--format=%H"],{captureStdout:!0});if(list.exitCode!==0)throw Error("BLOCKED: unable to inspect checkout-preparation stashes safely");return new Set(list.stdout.split(/\r?\n/).map((value)=>value.trim().toLowerCase()).filter((value)=>/^[0-9a-f]{40,64}$/i.test(value)))}async function listCheckoutReceiptPaths(directory,sessionID){let receiptDirectory=validateSwarmPath(directory,path246.join(RECEIPT_DIR,prWorkflowSessionFileStem(sessionID))),handle;try{handle=await fsp7.opendir(receiptDirectory)}catch(error93){if(error93.code==="ENOENT")return[];throw new CheckoutRestoreError("CHECKOUT_RESTORE_RECEIPT_READ_FAILED","BLOCKED: unable to inspect checkout-restoration receipts safely")}let receiptNames=[],entriesRead=0,directoryMissing=!1,scanError,closeError;try{for(;;){let entry=await handle.read();if(!entry)break;if(entriesRead+=1,entriesRead>MAX_RECEIPT_DIRECTORY_ENTRIES)throw new CheckoutRestoreError("CHECKOUT_RESTORE_RECEIPT_LIMIT",`BLOCKED: checkout-restoration receipt directory exceeds the ${MAX_RECEIPT_DIRECTORY_ENTRIES}-entry bounded scan`);if(!entry.isFile()||!/^[0-9a-f]{40,64}\.json$/i.test(entry.name))continue;if(receiptNames.push(entry.name),receiptNames.length>MAX_CHECKOUT_RECEIPTS)throw new CheckoutRestoreError("CHECKOUT_RESTORE_RECEIPT_LIMIT",`BLOCKED: more than ${MAX_CHECKOUT_RECEIPTS} checkout-restoration receipts exist for this session; reduce the receipt set through explicit manual recovery`)}}catch(error93){if(entriesRead===0&&error93.code==="ENOENT")directoryMissing=!0;else scanError=error93}finally{try{await handle.close()}catch(error93){if(error93.code!=="ERR_DIR_CLOSED"&&error93.code!=="ERR_INVALID_STATE")closeError=error93}}if(directoryMissing)return[];if(scanError!==void 0){if(scanError instanceof CheckoutRestoreError)throw scanError;throw new CheckoutRestoreError("CHECKOUT_RESTORE_RECEIPT_READ_FAILED","BLOCKED: unable to inspect checkout-restoration receipts safely")}if(closeError!==void 0)throw new CheckoutRestoreError("CHECKOUT_RESTORE_RECEIPT_READ_FAILED","BLOCKED: unable to close checkout-restoration receipt inventory safely");return receiptNames.sort((left,right)=>left.localeCompare(right)).map((name)=>({stashOid:name.replace(/\.json$/i,"").toLowerCase(),receiptPath:validateSwarmPath(directory,path246.join(RECEIPT_DIR,prWorkflowSessionFileStem(sessionID),name))}))}async function readBoundedReceiptFile(receiptPath){let handle=await fsp7.open(receiptPath,"r");try{let buffer=new Uint8Array(MAX_RECEIPT_BYTES+1),{bytesRead}=await handle.read(buffer,0,buffer.byteLength,0);if(bytesRead>MAX_RECEIPT_BYTES)throw Error("receipt exceeds safe size limit");return new TextDecoder().decode(buffer.subarray(0,bytesRead))}finally{await handle.close()}}async function readCheckoutRestoreReceipt(directory,receiptPath,expectedSessionID,expectedStashOid){let value;try{value=JSON.parse(await readBoundedReceiptFile(receiptPath))}catch{throw new CheckoutRestoreError("CHECKOUT_RESTORE_RECEIPT_INVALID","BLOCKED: checkout-restoration receipt is unreadable or malformed; preserve the stash and recover manually")}if(!value||typeof value!=="object")throw new CheckoutRestoreError("CHECKOUT_RESTORE_RECEIPT_INVALID","BLOCKED: checkout-restoration receipt is not an object; preserve the stash and recover manually");let receipt=value;if(receipt.schemaVersion!==1||receipt.sessionID!==expectedSessionID||typeof receipt.stashOid!=="string"||receipt.stashOid.toLowerCase()!==expectedStashOid||!Array.isArray(receipt.paths)||receipt.paths.length>MAX_RECEIPT_PATHS||receipt.paths.some((value2)=>typeof value2!=="string"||value2.length===0||value2.length>MAX_RECEIPT_PATH_LEN)||typeof receipt.preparedAt!=="string"||receipt.preparedAt.length===0||receipt.preparedAt.length>64||receipt.mode!=="PR_REVIEW"&&receipt.mode!=="PR_FEEDBACK"||!Number.isInteger(receipt.gateRevision)||receipt.gateRevision<0||typeof receipt.gateActivatedAt!=="string"||receipt.gateActivatedAt.length===0||receipt.gateActivatedAt.length>64||receipt.discovered!==void 0&&typeof receipt.discovered!=="boolean"||receipt.includedUntracked!==void 0&&typeof receipt.includedUntracked!=="boolean"||receipt.pathsTruncated!==void 0&&typeof receipt.pathsTruncated!=="boolean"||receipt.originalHead!==void 0&&(typeof receipt.originalHead!=="string"||!/^[0-9a-f]{40,64}$/i.test(receipt.originalHead))||receipt.originalBranch!==void 0&&receipt.originalBranch!==null&&(typeof receipt.originalBranch!=="string"||!isSafeRecordedBranch(receipt.originalBranch))||receipt.restoreState!==void 0&&receipt.restoreState!=="applied"||receipt.restoreAppliedAt!==void 0&&(typeof receipt.restoreAppliedAt!=="string"||receipt.restoreAppliedAt.length===0||receipt.restoreAppliedAt.length>64)||receipt.restoreVerifiedAt!==void 0&&(typeof receipt.restoreVerifiedAt!=="string"||receipt.restoreVerifiedAt.length===0||receipt.restoreVerifiedAt.length>64)||receipt.restoreVerifiedAt!==void 0&&receipt.restoreState!=="applied"||receipt.restoredHead!==void 0&&(typeof receipt.restoredHead!=="string"||!/^[0-9a-f]{40,64}$/i.test(receipt.restoredHead))||receipt.restoredBranch!==void 0&&receipt.restoredBranch!==null&&(typeof receipt.restoredBranch!=="string"||!isSafeRecordedBranch(receipt.restoredBranch))||receipt.restoreState==="applied"&&(typeof receipt.restoreAppliedAt!=="string"||typeof receipt.restoredHead!=="string"||receipt.restoredBranch===void 0))throw new CheckoutRestoreError("CHECKOUT_RESTORE_RECEIPT_INVALID","BLOCKED: checkout-restoration receipt failed identity validation; preserve the stash and recover manually");if(typeof receipt.originalHead!=="string"||receipt.originalBranch===void 0)return deriveLegacyCheckoutIdentity(directory,receipt,expectedStashOid);return receipt}async function deriveLegacyCheckoutIdentity(directory,receipt,stashOid){let parent=await _internals184.runGit(directory,["rev-parse","--verify",`${stashOid}^1`],{captureStdout:!0}),originalHead=parent.stdout.trim().toLowerCase(),type=await _internals184.runGit(directory,["cat-file","-t",originalHead],{captureStdout:!0});if(parent.exitCode!==0||!/^[0-9a-f]{40,64}$/i.test(originalHead)||type.exitCode!==0||type.stdout.trim()!=="commit")throw new CheckoutRestoreError("CHECKOUT_RESTORE_LEGACY_IDENTITY_UNRESOLVED","BLOCKED: the legacy receipt's stash parent could not be resolved as a commit; preserve the stash and recover manually");let refs=await _internals184.runGit(directory,["for-each-ref","--format=%(refname:short)%00%(objectname)","refs/heads/"],{captureStdout:!0}),matchingBranches=refs.exitCode===0?refs.stdout.split(/\r?\n/).map((line)=>line.split("\x00")).filter((parts)=>parts.length===2&&parts[1].toLowerCase()===originalHead&&isSafeRecordedBranch(parts[0])).map((parts)=>parts[0]):[];return{...receipt,originalHead,originalBranch:matchingBranches.length===1?matchingBranches[0]:null,legacyIdentityDerived:!0}}async function resolveRestoreDestination(directory,receipt){let head2=await _internals184.runGit(directory,["rev-parse","--verify",`${receipt.originalHead}^0`],{captureStdout:!0}),type=await _internals184.runGit(directory,["cat-file","-t",receipt.originalHead],{captureStdout:!0});if(head2.exitCode!==0||head2.stdout.trim().toLowerCase()!==receipt.originalHead.toLowerCase()||type.exitCode!==0||type.stdout.trim()!=="commit")throw new CheckoutRestoreError("CHECKOUT_RESTORE_ORIGINAL_HEAD_MISSING","BLOCKED: the original checkout commit no longer resolves exactly; no checkout mutation was attempted");if(receipt.originalBranch){let branch=await _internals184.runGit(directory,["rev-parse","--verify",`refs/heads/${receipt.originalBranch}^0`],{captureStdout:!0}),branchHead=branch.stdout.trim().toLowerCase();if(branch.exitCode!==0||!/^[0-9a-f]{40,64}$/i.test(branchHead))throw new CheckoutRestoreError("CHECKOUT_RESTORE_BRANCH_DRIFT",`BLOCKED: original branch ${boundUntrustedPath(receipt.originalBranch)} no longer resolves safely; no checkout mutation was attempted`);if(branchHead!==receipt.originalHead.toLowerCase()){if(receipt.mode!=="PR_FEEDBACK")throw new CheckoutRestoreError("CHECKOUT_RESTORE_BRANCH_DRIFT",`BLOCKED: original branch ${boundUntrustedPath(receipt.originalBranch)} no longer points to the recorded original HEAD; no checkout mutation was attempted`);if((await _internals184.runGit(directory,["merge-base","--is-ancestor",receipt.originalHead,`refs/heads/${receipt.originalBranch}`])).exitCode!==0)throw new CheckoutRestoreError("CHECKOUT_RESTORE_BRANCH_DRIFT",`BLOCKED: PR_FEEDBACK branch ${boundUntrustedPath(receipt.originalBranch)} did not advance as a descendant of the recorded original HEAD; no checkout mutation was attempted`)}return{head:branchHead,branch:receipt.originalBranch}}return{head:receipt.originalHead.toLowerCase(),branch:null}}function sameRestoreDestination(left,right){return left.head===right.head&&left.branch===right.branch}async function markReceiptApplied(directory,receiptPath,receipt,destination){let applied={...receipt,restoreState:"applied",restoreAppliedAt:new Date().toISOString(),restoredHead:destination.head,restoredBranch:destination.branch};return assertRestoreReceiptWithinByteBudget(applied),await writePrWorkflowAtomicJson(directory,receiptPath,applied),applied}async function markReceiptVerified(directory,receiptPath,receipt){let verified={...receipt,restoreVerifiedAt:new Date().toISOString()};return assertRestoreReceiptWithinByteBudget(verified),await writePrWorkflowAtomicJson(directory,receiptPath,verified),verified}async function appendRestoreEvent(directory,sessionID,receipt){try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp7.appendFile(eventsPath,`${JSON.stringify({type:"pr_workflow_checkout_restored",timestamp:new Date().toISOString(),sessionID,mode:receipt.mode,stashOid:receipt.stashOid,originalHead:receipt.originalHead,originalBranch:receipt.originalBranch})}
|
|
6377
6379
|
`,"utf8")}catch{}}async function removeCheckoutRestoreReceipt(receiptPath){await fsp7.rm(receiptPath)}async function restorePrWorkflowCheckout(directory,rawSessionID,requestedStashOid){let sessionID=normalizeSessionID3(rawSessionID);try{return await withInactivePrWorkflowCheckoutRestoreLock(directory,sessionID,async()=>{let receipts=await listCheckoutReceiptPaths(directory,sessionID);if(receipts.length===0)return{kind:"already_restored"};let normalizedRequested=requestedStashOid?.toLowerCase();if(normalizedRequested&&receipts.filter((entry)=>entry.stashOid===normalizedRequested).length!==1){let available=receipts.slice(0,MAX_CHECKOUT_RECEIPTS).map((entry)=>entry.stashOid);throw new CheckoutRestoreError("CHECKOUT_RESTORE_RECEIPT_AMBIGUOUS",`BLOCKED: no unique checkout receipt exists for stash ${normalizedRequested}; available stash_oid values: ${available.join(", ")}`)}let targets=await Promise.all(receipts.map(async(target)=>({...target,receipt:await readCheckoutRestoreReceipt(directory,target.receiptPath,sessionID,target.stashOid)})));targets.sort((left,right)=>left.receipt.preparedAt.localeCompare(right.receipt.preparedAt)||left.stashOid.localeCompare(right.stashOid));let verifiedCleanup=targets.filter((entry)=>entry.receipt.restoreState==="applied"&&typeof entry.receipt.restoreVerifiedAt==="string"),restoreTargets=targets.filter((entry)=>entry.receipt.restoreState!=="applied"||typeof entry.receipt.restoreVerifiedAt!=="string"),applied=restoreTargets.filter((entry)=>entry.receipt.restoreState==="applied"),pending=restoreTargets.filter((entry)=>entry.receipt.restoreState!=="applied"),observedStashes=null;try{observedStashes=await readCurrentStashOids(directory)}catch{}let receiptCleanupPending=!1;for(let target of verifiedCleanup)try{await _internals184.removeCheckoutRestoreReceipt(target.receiptPath)}catch{receiptCleanupPending=!0}if(restoreTargets.length===0){let first2=verifiedCleanup[0].receipt;return{kind:"restored",stashOids:targets.map((entry)=>entry.stashOid),retainedStashOids:observedStashes?targets.filter((entry)=>observedStashes.has(entry.stashOid)).map((entry)=>entry.stashOid):[],stashRetentionVerified:observedStashes!==null,originalHead:first2.originalHead,originalBranch:first2.originalBranch,restoredHead:first2.restoredHead,receiptCleanupPending}}let pendingDestinations=await Promise.all(pending.map((entry)=>resolveRestoreDestination(directory,entry.receipt))),destinations=[...applied.map((entry)=>({head:entry.receipt.restoredHead,branch:entry.receipt.restoredBranch})),...pendingDestinations],destination=destinations[0];if(destinations.some((candidate2)=>!sameRestoreDestination(destination,candidate2)))throw new CheckoutRestoreError("CHECKOUT_RESTORE_DESTINATION_AMBIGUOUS","BLOCKED: checkout receipts target different original checkouts; no switch or stash apply was attempted");if(pending.length>0){let activeStashes=observedStashes??await readCurrentStashOids(directory),missing=pending.filter((entry)=>!activeStashes.has(entry.stashOid));if(missing.length>0)throw new CheckoutRestoreError("CHECKOUT_RESTORE_STASH_MISSING",`BLOCKED: ${missing.length} preserved checkout stash(es) are missing; no checkout mutation was attempted`)}if(applied.length>0){let currentIdentity;try{currentIdentity=await captureCheckoutIdentity(directory)}catch{throw new CheckoutRestoreError("CHECKOUT_RESTORE_VERIFY_FAILED","BLOCKED: an applied checkout restoration could not be verified; its durable receipt remains for retry or manual recovery")}if(currentIdentity.originalHead!==destination.head||currentIdentity.originalBranch!==destination.branch)throw new CheckoutRestoreError("CHECKOUT_RESTORE_VERIFY_FAILED","BLOCKED: an applied checkout restoration no longer matches its recorded destination; its durable receipt remains for manual recovery")}else if(applied.length===0){let status;try{status=await readPorcelainStatus(directory)}catch{throw new CheckoutRestoreError("CHECKOUT_RESTORE_STATUS_FAILED","BLOCKED: unable to verify a clean destination checkout; no restore was attempted")}if(status.dirtyTrackedPaths.length>0||status.untrackedPaths.length>0||status.renameOrCopy)throw new CheckoutRestoreError("CHECKOUT_RESTORE_NOT_CLEAN","BLOCKED: checkout restoration requires a clean destination working tree; no switch or stash apply was attempted");if((await _internals184.runGit(directory,destination.branch?["switch","--",destination.branch]:["switch","--detach",destination.head])).exitCode!==0)throw new CheckoutRestoreError("CHECKOUT_RESTORE_SWITCH_FAILED","BLOCKED: Git could not return to the recorded original checkout; the stash and receipt remain intact")}for(let target of pending){if((await _internals184.runGit(directory,["stash","apply","--index",target.stashOid])).exitCode!==0)throw new CheckoutRestoreError("CHECKOUT_RESTORE_APPLY_FAILED",`BLOCKED: Git could not reapply preserved stash ${target.stashOid}; its receipt and immutable stash remain for explicit manual recovery`);let appliedReceipt;try{appliedReceipt=await markReceiptApplied(directory,target.receiptPath,target.receipt,destination)}catch{throw new CheckoutRestoreError("CHECKOUT_RESTORE_APPLIED_STATE_WRITE_FAILED",`BLOCKED: preserved stash ${target.stashOid} was applied, but durable applied-state recording failed; inspect the working tree and retained stash manually`)}target.receipt=appliedReceipt}let restoredIdentity;try{restoredIdentity=await captureCheckoutIdentity(directory)}catch{throw new CheckoutRestoreError("CHECKOUT_RESTORE_VERIFY_FAILED","BLOCKED: checkout restoration completed but its final identity could not be verified; inspect the working tree and retained applied-state receipts manually")}if(restoredIdentity.originalHead!==destination.head||restoredIdentity.originalBranch!==destination.branch)throw new CheckoutRestoreError("CHECKOUT_RESTORE_VERIFY_FAILED","BLOCKED: checkout restoration completed but its final identity could not be verified; inspect the working tree and retained applied-state receipts manually");for(let target of restoreTargets){if(!target.receipt.restoreVerifiedAt)try{target.receipt=await markReceiptVerified(directory,target.receiptPath,target.receipt)}catch{throw new CheckoutRestoreError("CHECKOUT_RESTORE_VERIFIED_STATE_WRITE_FAILED","BLOCKED: checkout restoration was verified, but durable verified-state recording failed; retained applied-state receipts remain for retry")}await appendRestoreEvent(directory,sessionID,target.receipt);try{await _internals184.removeCheckoutRestoreReceipt(target.receiptPath)}catch{receiptCleanupPending=!0}}let finalStashes=null;try{finalStashes=await readCurrentStashOids(directory)}catch{}let first=restoreTargets[0].receipt;return{kind:"restored",stashOids:targets.map((entry)=>entry.stashOid),retainedStashOids:finalStashes?targets.filter((entry)=>finalStashes.has(entry.stashOid)).map((entry)=>entry.stashOid):[],stashRetentionVerified:finalStashes!==null,originalHead:first.originalHead,originalBranch:first.originalBranch,restoredHead:destination.head,receiptCleanupPending}})}catch(error93){if(error93 instanceof Error&&error93.message.includes("checkout restoration is allowed only after"))throw new CheckoutRestoreError("CHECKOUT_RESTORE_GATE_ACTIVE",error93.message);if(error93 instanceof Error&&error93.message.includes("checkout restoration cannot mutate this project while session"))throw new CheckoutRestoreError("CHECKOUT_RESTORE_OTHER_SESSION_ACTIVE",error93.message);throw error93}}async function listPendingPrWorkflowCheckoutRestores(directory,sessionID){let receipts=await listCheckoutReceiptPaths(directory,normalizeSessionID3(sessionID));if(receipts.length===0)return[];let activeStashes=null;try{activeStashes=await readCurrentStashOids(directory)}catch{}return receipts.map((receipt)=>({stash_oid:receipt.stashOid,stash_present:activeStashes?.has(receipt.stashOid)??null}))}async function writeReceipt(directory,sessionID,preparation){let receiptPath=validateSwarmPath(directory,path246.join(RECEIPT_DIR,prWorkflowSessionFileStem(sessionID),`${preparation.stashOid}.json`));assertReceiptWithinByteBudget(sessionID,preparation),await writePrWorkflowAtomicJson(directory,receiptPath,buildReceiptDocument(sessionID,preparation))}async function appendPreparationEvent(directory,sessionID,preparation){try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp7.appendFile(eventsPath,`${JSON.stringify({type:"pr_workflow_checkout_prepared",timestamp:preparation.preparedAt,sessionID,mode:preparation.mode,gateRevision:preparation.gateRevision,stashOid:preparation.stashOid,paths:preparation.paths})}
|
|
6378
|
-
`,"utf-8")}catch{}}var _internals184={runGit:runGit7,readBoundedGitStdout,classifyGitState:classifyPrWorkflowGitState,removeCheckoutRestoreReceipt};function boundUntrustedPath(value){let cleaned="";for(let ch of value){let code=ch.codePointAt(0)??0,strip=code<=31||code>=127&&code<=159||code>=8234&&code<=8238||code>=8294&&code<=8297||ch==="`"||ch==="<"||ch===">";cleaned+=strip?" ":ch}return cleaned=cleaned.replace(/\s+/g," ").trim(),cleaned.length>MAX_ECHOED_PATH_LEN?`${cleaned.slice(0,MAX_ECHOED_PATH_LEN)}…`:cleaned}function structuredRestoreInstruction(stashOid){return`After complete_pr_workflow or abort_pr_workflow clears the gate, call prepare_pr_workflow_checkout with operation=restore; stash_oid=${stashOid} may be supplied as an exact receipt assertion`}function manualRecoveryInstruction(stashOid){return`manual recovery required: git stash apply --index ${stashOid}`}var prepare_pr_workflow_checkout=createSwarmTool({description:"Prepare or restore an auditable PR workflow checkout. Before binding, operation=prepare (the default) preserves dirty working-tree changes, records the original branch/HEAD and exact stash OID, and refuses unsafe state. After complete_pr_workflow or abort_pr_workflow clears the gate, one operation=restore call returns to the common recorded checkout and reapplies every pending receipt by immutable stash OID under the checkout mutation lock. Restored stashes remain as explicit safety backups because Git exposes no atomic identity-bound deletion for a non-top stash; the response lists retained_stash_oids. A PR_FEEDBACK branch may advance only as a descendant of its recorded commit; PR_REVIEW and detached identities remain exact. Legacy receipts derive the original commit from the stash and use a uniquely matching local branch when available. It refuses dirty, missing-stash, cross-session, divergent, or mixed-destination state without reset/clean. stash_oid is an optional exact receipt assertion, not a selector that leaves other receipts stranded. This tool never permits arbitrary stash commands.",args:{operation:PreparePrWorkflowCheckoutArgsSchema.shape.operation,paths:PreparePrWorkflowCheckoutArgsSchema.shape.paths,stash_oid:PreparePrWorkflowCheckoutArgsSchema.shape.stash_oid},execute:executePreparePrWorkflowCheckout});var AbortPrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]).optional(),kind:exports_external.literal("recovery"),reason:exports_external.string().trim().min(1).max(500)}).strict();async function executeAbortPrWorkflow(args2,directory,context={}){let parsed=AbortPrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow abort: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow abort requires an active sessionID"});try{let summary=await abortPrWorkflow(directory,context.sessionID,{kind:parsed.data.kind,reason:parsed.data.reason,...parsed.data.mode?{expectedMode:parsed.data.mode}:{}}),checkoutRestoreRequired=!0,checkoutRestoreReceipts=[];try{checkoutRestoreReceipts=await listPendingPrWorkflowCheckoutRestores(directory,context.sessionID),checkoutRestoreRequired=checkoutRestoreReceipts.length>0}catch{}return JSON.stringify({success:!0,mode:summary.mode,...summary.prHeadSha?{pr_head_sha:summary.prHeadSha}:{},open_lanes:summary.openLanes,gate_cleared:!0,checkout_restore_required:checkoutRestoreRequired,checkout_restore_receipts:checkoutRestoreReceipts})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var abort_pr_workflow=createSwarmTool({description:'Abort an active PR_REVIEW or PR_FEEDBACK mechanical gate and clear its durable session state, stopping the auto-resume loop. Requires kind: "recovery" and a one-line `reason`. Use after bounded recovery is exhausted, including a bound review or feedback workflow; do NOT use as a shortcut while useful recovery work remains. Refuses to abort while the workflow is armed for publication (call complete_pr_workflow instead) or while PR workflow lanes are still in flight (collect their results first). Reports checkout_restore_required when preserved pre-workflow changes remain. Records a best-effort audit event to .swarm/events.jsonl.',args:{mode:AbortPrWorkflowArgsSchema.shape.mode,kind:AbortPrWorkflowArgsSchema.shape.kind,reason:AbortPrWorkflowArgsSchema.shape.reason},execute:executeAbortPrWorkflow});init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs138 from"node:fs";import*as path247 from"node:path";var ACTIONLINT_TIMEOUT_MS=15000,ACTIONLINT_MAX_STDOUT_BYTES=4194304,ACTIONLINT_MAX_STDERR_BYTES=131072,DEFAULT_MAX_RESULTS=200,HARD_CAP_RESULTS=2000,MAX_WORKFLOW_FILES=500,MAX_WORKFLOW_DIRS=200,MAX_WORKFLOW_DEPTH=20;function resolveActionlintBinary(){return _internals185.resolveExecutableFromPath(["actionlint"])}function normalizeRelativeWorkflowFile(file3,workspace){if(!file3||containsControlChars(file3)||containsPathTraversal(file3))return null;if(path247.isAbsolute(file3)||/^[A-Za-z]:[/\\]/.test(file3))return null;let normalizedInput=file3.split(/[\\/]+/).filter(Boolean).join(path247.sep);if(!/\.(ya?ml)$/i.test(normalizedInput))return null;try{let realWorkspace=fs138.realpathSync(workspace),resolved=path247.resolve(realWorkspace,normalizedInput),realFile=fs138.realpathSync(resolved),relative57=path247.relative(realWorkspace,realFile);if(!relative57||relative57.startsWith("..")||path247.isAbsolute(relative57))return null;return relative57.split(path247.sep).join("/")}catch{return null}}function discoverWorkflowFiles(workspace){let root=path247.join(workspace,".github","workflows");if(!fs138.existsSync(root))return{files:[],truncated:!1};let files=[],dirCount=0,truncated=!1,visit=(dir,depth=0)=>{if(files.length>=MAX_WORKFLOW_FILES||dirCount>=MAX_WORKFLOW_DIRS||depth>MAX_WORKFLOW_DEPTH){truncated=!0;return}dirCount++;let entries;try{entries=fs138.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(files.length>=MAX_WORKFLOW_FILES||dirCount>=MAX_WORKFLOW_DIRS){truncated=!0;break}let full=path247.join(dir,entry.name);if(entry.isDirectory())visit(full,depth+1);else if(entry.isFile()&&/\.(ya?ml)$/i.test(entry.name)){let rel=normalizeRelativeWorkflowFile(path247.relative(workspace,full),workspace);if(rel)files.push(rel)}}};return visit(root),{files,truncated}}function parseActionlintOutput(stdout,workspace,maxResults){let findings=[],total=0;for(let line of stdout.split(`
|
|
6380
|
+
`,"utf-8")}catch{}}var _internals184={runGit:runGit7,readBoundedGitStdout,classifyGitState:classifyPrWorkflowGitState,removeCheckoutRestoreReceipt};function boundUntrustedPath(value){let cleaned="";for(let ch of value){let code=ch.codePointAt(0)??0,strip=code<=31||code>=127&&code<=159||code>=8234&&code<=8238||code>=8294&&code<=8297||ch==="`"||ch==="<"||ch===">";cleaned+=strip?" ":ch}return cleaned=cleaned.replace(/\s+/g," ").trim(),cleaned.length>MAX_ECHOED_PATH_LEN?`${cleaned.slice(0,MAX_ECHOED_PATH_LEN)}…`:cleaned}function structuredRestoreInstruction(stashOid){return`After complete_pr_workflow or abort_pr_workflow clears the gate, call prepare_pr_workflow_checkout with operation=restore; stash_oid=${stashOid} may be supplied as an exact receipt assertion`}function manualRecoveryInstruction(stashOid){return`manual recovery required: git stash apply --index ${stashOid}`}var prepare_pr_workflow_checkout=createSwarmTool({description:"Prepare or restore an auditable PR workflow checkout. Before binding, operation=prepare (the default) preserves dirty working-tree changes, records the original branch/HEAD and exact stash OID, and refuses unsafe state. After complete_pr_workflow or abort_pr_workflow clears the gate, one operation=restore call returns to the common recorded checkout and reapplies every pending receipt by immutable stash OID under the checkout mutation lock. Restored stashes remain as explicit safety backups because Git exposes no atomic identity-bound deletion for a non-top stash; the response lists retained_stash_oids. A PR_FEEDBACK branch may advance only as a descendant of its recorded commit; PR_REVIEW and detached identities remain exact. Legacy receipts derive the original commit from the stash and use a uniquely matching local branch when available. It refuses dirty, missing-stash, cross-session, divergent, or mixed-destination state without reset/clean. stash_oid is an optional exact receipt assertion, not a selector that leaves other receipts stranded. This tool never permits arbitrary stash commands.",args:{operation:PreparePrWorkflowCheckoutArgsSchema.shape.operation,paths:PreparePrWorkflowCheckoutArgsSchema.shape.paths,stash_oid:PreparePrWorkflowCheckoutArgsSchema.shape.stash_oid},execute:executePreparePrWorkflowCheckout});var AbortPrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]).optional(),kind:exports_external.literal("recovery"),reason:exports_external.string().trim().min(1).max(500)}).strict();async function executeAbortPrWorkflow(args2,directory,context={}){let parsed=AbortPrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow abort: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow abort requires an active sessionID"});try{let summary=await abortPrWorkflow(directory,context.sessionID,{kind:parsed.data.kind,reason:parsed.data.reason,...parsed.data.mode?{expectedMode:parsed.data.mode}:{}}),checkoutRestoreRequired=!0,checkoutRestoreReceipts=[];try{checkoutRestoreReceipts=await listPendingPrWorkflowCheckoutRestores(directory,context.sessionID),checkoutRestoreRequired=checkoutRestoreReceipts.length>0}catch{}return JSON.stringify({success:!0,mode:summary.mode,...summary.prHeadSha?{pr_head_sha:summary.prHeadSha}:{},open_lanes:summary.openLanes,...summary.presumedStaleLanes?.length?{presumed_stale_lanes:summary.presumedStaleLanes,presumed_stale_disclosure:summary.presumedStaleDisclosure}:{},...summary.stateSalvaged?{state_salvaged:!0,state_salvage_disclosure:summary.stateSalvageDisclosure}:{},...summary.casEscapeDisclosure?{cas_escape_disclosure:summary.casEscapeDisclosure}:{},gate_cleared:!0,checkout_restore_required:checkoutRestoreRequired,checkout_restore_receipts:checkoutRestoreReceipts})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var abort_pr_workflow=createSwarmTool({description:'Abort an active PR_REVIEW or PR_FEEDBACK mechanical gate and clear its durable session state, stopping the auto-resume loop. Requires kind: "recovery" and a one-line `reason`. Use after bounded recovery is exhausted, including a bound review or feedback workflow; do NOT use as a shortcut while useful recovery work remains. Refuses to abort while the workflow is armed for publication (call complete_pr_workflow instead) or while PR workflow lanes are still in flight (collect their results first). Reports checkout_restore_required when preserved pre-workflow changes remain. Reports state_salvaged with state_salvage_disclosure when the durable gate state was schema-invalid and had to be salvaged to clear it, and cas_escape_disclosure when the state revision was unsalvageable and the gate was therefore cleared without its compare-and-swap guard — treat either as a signal to re-verify the workflow before proceeding. Records a best-effort audit event to .swarm/events.jsonl.',args:{mode:AbortPrWorkflowArgsSchema.shape.mode,kind:AbortPrWorkflowArgsSchema.shape.kind,reason:AbortPrWorkflowArgsSchema.shape.reason},execute:executeAbortPrWorkflow});init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs138 from"node:fs";import*as path247 from"node:path";var ACTIONLINT_TIMEOUT_MS=15000,ACTIONLINT_MAX_STDOUT_BYTES=4194304,ACTIONLINT_MAX_STDERR_BYTES=131072,DEFAULT_MAX_RESULTS=200,HARD_CAP_RESULTS=2000,MAX_WORKFLOW_FILES=500,MAX_WORKFLOW_DIRS=200,MAX_WORKFLOW_DEPTH=20;function resolveActionlintBinary(){return _internals185.resolveExecutableFromPath(["actionlint"])}function normalizeRelativeWorkflowFile(file3,workspace){if(!file3||containsControlChars(file3)||containsPathTraversal(file3))return null;if(path247.isAbsolute(file3)||/^[A-Za-z]:[/\\]/.test(file3))return null;let normalizedInput=file3.split(/[\\/]+/).filter(Boolean).join(path247.sep);if(!/\.(ya?ml)$/i.test(normalizedInput))return null;try{let realWorkspace=fs138.realpathSync(workspace),resolved=path247.resolve(realWorkspace,normalizedInput),realFile=fs138.realpathSync(resolved),relative57=path247.relative(realWorkspace,realFile);if(!relative57||relative57.startsWith("..")||path247.isAbsolute(relative57))return null;return relative57.split(path247.sep).join("/")}catch{return null}}function discoverWorkflowFiles(workspace){let root=path247.join(workspace,".github","workflows");if(!fs138.existsSync(root))return{files:[],truncated:!1};let files=[],dirCount=0,truncated=!1,visit=(dir,depth=0)=>{if(files.length>=MAX_WORKFLOW_FILES||dirCount>=MAX_WORKFLOW_DIRS||depth>MAX_WORKFLOW_DEPTH){truncated=!0;return}dirCount++;let entries;try{entries=fs138.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(files.length>=MAX_WORKFLOW_FILES||dirCount>=MAX_WORKFLOW_DIRS){truncated=!0;break}let full=path247.join(dir,entry.name);if(entry.isDirectory())visit(full,depth+1);else if(entry.isFile()&&/\.(ya?ml)$/i.test(entry.name)){let rel=normalizeRelativeWorkflowFile(path247.relative(workspace,full),workspace);if(rel)files.push(rel)}}};return visit(root),{files,truncated}}function parseActionlintOutput(stdout,workspace,maxResults){let findings=[],total=0;for(let line of stdout.split(`
|
|
6379
6381
|
`)){if(!line.trim())continue;try{let entry=JSON.parse(line),file3=typeof entry.filepath==="string"?normalizeRelativeWorkflowFile(path247.isAbsolute(entry.filepath)?path247.relative(workspace,entry.filepath):entry.filepath,workspace):null;if(!file3)continue;if(total++,findings.length>=maxResults)continue;findings.push({file:file3,line:typeof entry.line==="number"?entry.line:1,column:typeof entry.column==="number"?entry.column:1,kind:typeof entry.kind==="string"?entry.kind:"unknown",message:typeof entry.message==="string"?entry.message:"",endColumn:typeof entry.end_column==="number"?entry.end_column:void 0})}catch{}}return{findings,total}}function sanitizeMaxResults(value){let numeric=typeof value==="number"&&Number.isFinite(value)?value:DEFAULT_MAX_RESULTS;return Math.min(Math.max(0,numeric),HARD_CAP_RESULTS)}var actionlint_scan=createSwarmTool({description:"Run actionlint against GitHub Actions workflow YAML files and return structured findings. Read-only; resolves actionlint lazily.",args:{files:exports_external.array(exports_external.string()).optional().describe("Optional workspace-relative workflow YAML files. Defaults to .github/workflows/**/*.yml,yaml."),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS).describe("Maximum findings to return")},execute:async(args2,directory)=>{let obj=typeof args2==="object"&&args2!==null?args2:{},maxResults=sanitizeMaxResults(obj.max_results),requestedFiles=Array.isArray(obj.files)?obj.files:void 0;if(requestedFiles?.some((f)=>typeof f!=="string"))return JSON.stringify({error:!0,type:"invalid-input",message:"files must be an array of strings"},null,2);let discovery=requestedFiles?{files:requestedFiles.map((f)=>normalizeRelativeWorkflowFile(f,directory)).filter((f)=>Boolean(f)),truncated:!1}:_internals185.discoverWorkflowFiles(directory),files=discovery.files;if(requestedFiles&&files.length!==requestedFiles.length)return JSON.stringify({error:!0,type:"path-escape",message:"files must be existing workspace-relative GitHub Actions YAML files"},null,2);let uniqueFiles=Array.from(new Set(files)),cappedFiles=uniqueFiles.slice(0,MAX_WORKFLOW_FILES),discoveryTruncated=discovery.truncated||uniqueFiles.length>cappedFiles.length;if(files=cappedFiles,files.length===0)return JSON.stringify({clean:!discoveryTruncated,findings:[],total:0,truncated:discoveryTruncated,files:[],command:["actionlint","-format","{{json .}}"],note:discoveryTruncated?`Workflow discovery was truncated at ${MAX_WORKFLOW_FILES} files, ${MAX_WORKFLOW_DIRS} directories, or depth ${MAX_WORKFLOW_DEPTH}; result is incomplete.`:"No GitHub Actions workflow YAML files found"},null,2);let executable=_internals185.resolveActionlintBinary();if(!executable)return JSON.stringify({error:!0,type:"actionlint-not-found",message:"actionlint executable not found. Install actionlint and ensure it is on PATH."},null,2);let lintArgs=["-format","{{json .}}",...files.map((file3)=>`./${file3}`)],run=await _internals185.runExternalTool({executable,args:lintArgs,cwd:directory,timeoutMs:ACTIONLINT_TIMEOUT_MS,maxStdoutBytes:ACTIONLINT_MAX_STDOUT_BYTES,maxStderrBytes:ACTIONLINT_MAX_STDERR_BYTES});if(run.status==="timeout")return JSON.stringify({error:!0,type:"timeout",message:`actionlint timed out after ${ACTIONLINT_TIMEOUT_MS}ms`},null,2);if(run.status==="spawn-error")return JSON.stringify({error:!0,type:"unknown",message:run.message??"actionlint failed to start"},null,2);let{findings,total}=parseActionlintOutput(run.stdout,directory,maxResults);if(run.exitCode!==0&&findings.length===0&&run.stderr)return JSON.stringify({error:!0,type:"unknown",message:run.stderr.split(`
|
|
6380
6382
|
`)[0]},null,2);return JSON.stringify({findings,total,truncated:discoveryTruncated||total>maxResults||run.stdoutTruncated||run.stderrTruncated,files,command:["actionlint",...lintArgs],outputTruncated:run.stdoutTruncated||run.stderrTruncated,clean:findings.length===0&&total===0&&!discoveryTruncated&&!run.stdoutTruncated&&!run.stderrTruncated,note:discoveryTruncated?`Workflow discovery was truncated at ${MAX_WORKFLOW_FILES} files, ${MAX_WORKFLOW_DIRS} directories, or depth ${MAX_WORKFLOW_DEPTH}; result is incomplete.`:void 0},null,2)}}),_internals185={resolveExecutableFromPath,resolveActionlintBinary,runExternalTool,discoverWorkflowFiles,parseActionlintOutput};init_zod();init_config();import{existsSync as existsSync124,mkdirSync as mkdirSync62,mkdtempSync as mkdtempSync4,readFileSync as readFileSync95,realpathSync as realpathSync38,renameSync as renameSync38,rmdirSync as rmdirSync2,unlinkSync as unlinkSync39,writeFileSync as writeFileSync43}from"node:fs";import*as path248 from"node:path";class SequenceMatcher{a;b;isJunk;autoJunk;b2j=new Map;popularSet=new Set;matchingBlocks=null;constructor(isJunk,a,b,autoJunk=!0){this.a=a,this.b=b,this.isJunk=isJunk,this.autoJunk=autoJunk,this.chainB()}setSeqs(a,b){this.a=a,this.b=b,this.matchingBlocks=null,this.chainB()}chainB(){let b=this.b,b2j=new Map;for(let i=0;i<b.length;i++){let ch=b[i],positions=b2j.get(ch);if(positions===void 0)b2j.set(ch,[i]);else positions.push(i)}if(this.isJunk){let junk=[];for(let ch of b2j.keys())if(this.isJunk(ch))junk.push(ch);for(let ch of junk)b2j.delete(ch)}if(this.popularSet=new Set,this.autoJunk&&b.length>=200){let threshold=b.length*0.01+0.5,popular=[];for(let[ch,indices]of b2j)if(indices.length>threshold)popular.push(ch);for(let ch of popular)this.popularSet.add(ch),b2j.delete(ch)}this.b2j=b2j}findLongestMatch(alo,ahi,blo,bhi){let a=this.a,b=this.b,b2j=this.b2j,bestI=alo,bestJ=blo,bestSize=0,j2len=new Map;for(let i=alo;i<ahi;i++){let ch=a[i],positions=b2j.get(ch);if(positions===void 0){j2len.clear();continue}let newJ2len=new Map;for(let j of positions){if(j<blo)continue;if(j>=bhi)break;let size=(j2len.get(j-1)??0)+1;if(newJ2len.set(j,size),size>bestSize)bestI=i-size+1,bestJ=j-size+1,bestSize=size}j2len.clear();for(let[k,v]of newJ2len)j2len.set(k,v)}while(bestI>alo&&bestJ>blo&&a[bestI-1]===b[bestJ-1])bestI--,bestJ--,bestSize++;while(bestI+bestSize<ahi&&bestJ+bestSize<bhi&&a[bestI+bestSize]===b[bestJ+bestSize])bestSize++;return{a:bestI,b:bestJ,size:bestSize}}getMatchingBlocks(){if(this.matchingBlocks!==null)return this.matchingBlocks;let la=this.a.length,lb=this.b.length,matches=[],stack=[[0,la,0,lb]];while(stack.length>0){let[alo,ahi,blo,bhi]=stack.pop(),m=this.findLongestMatch(alo,ahi,blo,bhi),{a:i,b:j,size}=m;if(size>0){if(matches.push(m),alo<i&&blo<j)stack.push([alo,i,blo,j]);if(i+size<ahi&&j+size<bhi)stack.push([i+size,ahi,j+size,bhi])}}return matches.sort((x,y)=>x.a-y.a||x.b-y.b),matches.push({a:la,b:lb,size:0}),this.matchingBlocks=matches,matches}ratio(){let matches=this.getMatchingBlocks(),m=0;for(let block of matches)m+=block.size;let t=this.a.length+this.b.length;if(t===0)return 1;return 2*m/t}getOpcodes(){let blocks=this.getMatchingBlocks(),opcodes=[],i=0,j=0;for(let block of blocks){let{a:ai,b:bj,size}=block;if(i<ai&&j<bj)opcodes.push({tag:"replace",i1:i,i2:ai,j1:j,j2:bj});else if(i<ai)opcodes.push({tag:"delete",i1:i,i2:ai,j1:j,j2:bj});else if(j<bj)opcodes.push({tag:"insert",i1:i,i2:ai,j1:j,j2:bj});if(size>0)opcodes.push({tag:"equal",i1:ai,i2:ai+size,j1:bj,j2:bj+size});i=ai+size,j=bj+size}return opcodes}}var UNICODE_MAP={"“":'"',"”":'"',"‘":"'","’":"'","—":"--","–":"-","…":"..."," ":" "};function unicodeNormalize(text){let out=text;for(let[char,repl]of Object.entries(UNICODE_MAP))out=out.split(char).join(repl);return out}function leadingWhitespace(line){let i=0;while(i<line.length&&(line[i]===" "||line[i]==="\t"))i++;return line.slice(0,i)}function firstMeaningfulLine(text){for(let line of text.split(`
|
|
6381
6383
|
`))if(line.trim())return line;return null}function fuzzyFindAndReplace(content,oldString,newString,replaceAll=!1,options={}){if(!oldString)return{content,matchCount:0,strategy:null,error:"old_string cannot be empty"};if(oldString===newString)return{content,matchCount:0,strategy:null,error:"old_string and new_string are identical"};let strategies=[["exact",strategyExact],["line_trimmed",strategyLineTrimmed],["whitespace_normalized",strategyWhitespaceNormalized],["indentation_flexible",strategyIndentationFlexible],["escape_normalized",strategyEscapeNormalized],["trimmed_boundary",strategyTrimmedBoundary],["unicode_normalized",strategyUnicodeNormalized],["block_anchor",strategyBlockAnchor]];if(options.includeContextAware!==!1)strategies.push(["context_aware",strategyContextAware]);for(let[strategyName,strategyFn]of strategies){let matches=strategyFn(content,oldString);if(matches.length===0)continue;if(matches.length>1&&!replaceAll)return{content,matchCount:0,strategy:null,error:`Found ${matches.length} matches for old_string. Provide more context to make it unique, or use replace_all=true.`};if(strategyName!=="exact"){let driftErr=detectEscapeDrift(content,matches,oldString,newString);if(driftErr)return{content,matchCount:0,strategy:null,error:driftErr}}let effectiveNew=maybeUnescapeNewString(newString,content,matches);if(strategyName==="unicode_normalized"||strategyName==="block_anchor"||strategyName==="context_aware")effectiveNew=preserveUnicodeInReplacement(content,matches,oldString,effectiveNew);return{content:applyReplacements(content,matches,effectiveNew,strategyName!=="exact"?oldString:null),matchCount:matches.length,strategy:strategyName,error:null}}return{content,matchCount:0,strategy:null,error:"Could not find a match for old_string in the file"}}function detectEscapeDrift(content,matches,oldString,newString){if(!newString.includes("\\'")&&!newString.includes("\\\""))return null;let matchedRegions="";for(let[start,end]of matches)matchedRegions+=content.slice(start,end);for(let suspect of["\\'","\\\""])if(newString.includes(suspect)&&oldString.includes(suspect)&&!matchedRegions.includes(suspect)){let plain=suspect[1];return`Escape-drift detected: old_string and new_string contain the literal sequence ${JSON.stringify(suspect)} but the matched region of the file does not. This is almost always a tool-call serialization artifact where an apostrophe or quote got prefixed with a spurious backslash. Re-read the file with read_file and pass old_string/new_string without backslash-escaping ${JSON.stringify(plain)} characters.`}return null}function maybeUnescapeNewString(newString,content,matches){if(!newString.includes("\\t")&&!newString.includes("\\r"))return newString;let matchedRegions="";for(let[start,end]of matches)matchedRegions+=content.slice(start,end);let out=newString;if(out.includes("\\t")&&matchedRegions.includes("\t"))out=out.split("\\t").join("\t");if(out.includes("\\r")&&matchedRegions.includes("\r"))out=out.split("\\r").join("\r");return out}function reindentReplacement(fileRegion,oldString,newString){if(!newString)return newString;let oldFirst=firstMeaningfulLine(oldString),fileFirst=firstMeaningfulLine(fileRegion);if(oldFirst===null||fileFirst===null)return newString;let oldIndent=leadingWhitespace(oldFirst),fileIndent=leadingWhitespace(fileFirst);if(oldIndent===fileIndent)return newString;let outLines=[];for(let line of newString.split(`
|
|
@@ -6430,7 +6432,7 @@ ${hint}`}]}return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0
|
|
|
6430
6432
|
`)){if(!line.trim())continue;try{let entry=JSON.parse(line),relativePath2=typeof entry.file==="string"?toWorkspaceRelativePath(entry.file,workspace):null;if(!relativePath2)continue;if(total++,matches.length>=maxResults)continue;let start=entry.range?.start??{},end=entry.range?.end??{};matches.push({file:relativePath2,lineNumber:typeof start.line==="number"?start.line+1:1,column:typeof start.column==="number"?start.column+1:1,endLineNumber:typeof end.line==="number"?end.line+1:1,endColumn:typeof end.column==="number"?end.column+1:1,text:typeof entry.text==="string"?entry.text:"",lines:typeof entry.lines==="string"?entry.lines.trimEnd():"",language:typeof entry.language==="string"?entry.language:void 0,metaVariables:entry.metaVariables&&typeof entry.metaVariables==="object"?entry.metaVariables:void 0})}catch{}}return{matches,total}}function validateGlobArg(kind,value){if(!value)return null;if(containsControlChars(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains invalid control characters`};if(containsPathTraversal(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains path traversal sequence`};return null}var ast_grep=createSwarmTool({description:"Read-only structural AST search using ast-grep. Searches code patterns with optional language and glob filters; does not rewrite files.",args:{pattern:exports_external.string().describe("ast-grep pattern to search for"),language:exports_external.string().optional().describe("Optional ast-grep language, e.g. ts, tsx, js, py, rust"),include:exports_external.string().optional().describe("Comma-separated include globs, passed to ast-grep --globs"),exclude:exports_external.string().optional().describe("Comma-separated exclude globs, passed to ast-grep as !glob"),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS2).describe("Maximum number of matches to return")},execute:async(args2,directory)=>{let pattern,language,include,exclude,maxResults=DEFAULT_MAX_RESULTS2;try{let obj=args2;pattern=typeof obj.pattern==="string"?obj.pattern:"",language=typeof obj.language==="string"?obj.language:void 0,include=typeof obj.include==="string"?obj.include:void 0,exclude=typeof obj.exclude==="string"?obj.exclude:void 0;let rawMaxResults=typeof obj.max_results==="number"?obj.max_results:DEFAULT_MAX_RESULTS2,sanitizedMaxResults=Number.isFinite(rawMaxResults)?rawMaxResults:DEFAULT_MAX_RESULTS2;maxResults=Math.min(Math.max(0,sanitizedMaxResults),HARD_CAP_RESULTS2)}catch{return JSON.stringify({error:!0,type:"invalid-pattern",message:"Could not parse ast_grep arguments"},null,2)}if(!pattern||pattern.trim()==="")return JSON.stringify({error:!0,type:"invalid-pattern",message:"Pattern cannot be empty"},null,2);if(pattern.length>MAX_PATTERN_LENGTH||containsControlChars(pattern))return JSON.stringify({error:!0,type:"invalid-pattern",message:`Pattern is invalid or exceeds ${MAX_PATTERN_LENGTH} characters`},null,2);if(language&&!/^[A-Za-z0-9_-]+$/.test(language))return JSON.stringify({error:!0,type:"invalid-pattern",message:"Language must contain only letters, numbers, _ or -"},null,2);let includeError=validateGlobArg("Include",include);if(includeError)return JSON.stringify(includeError,null,2);let excludeError=validateGlobArg("Exclude",exclude);if(excludeError)return JSON.stringify(excludeError,null,2);if(!fs139.existsSync(directory))return JSON.stringify({error:!0,type:"unknown",message:"Workspace directory does not exist"},null,2);let executable=_internals187.resolveAstGrepBinary();if(!executable)return JSON.stringify({error:!0,type:"ast-grep-not-found",message:"ast-grep executable not found. Install ast-grep and ensure ast-grep or sg is on PATH."},null,2);let sgArgs=["run","--pattern",pattern,"--json=stream","--color","never"];if(language)sgArgs.push("--lang",language);for(let glob of splitGlobPatterns(include))sgArgs.push("--globs",glob);for(let glob of splitGlobPatterns(exclude))sgArgs.push("--globs",`!${glob}`);sgArgs.push(".");let run=await _internals187.runExternalTool({executable,args:sgArgs,cwd:directory,timeoutMs:AST_GREP_TIMEOUT_MS,maxStdoutBytes:AST_GREP_MAX_STDOUT_BYTES,maxStderrBytes:AST_GREP_MAX_STDERR_BYTES});if(run.status==="timeout")return JSON.stringify({error:!0,type:"timeout",message:`ast-grep timed out after ${AST_GREP_TIMEOUT_MS}ms`},null,2);if(run.status==="spawn-error")return JSON.stringify({error:!0,type:"unknown",message:run.message??"ast-grep failed to start"},null,2);if(run.exitCode!==0&&run.stderr)return JSON.stringify({error:!0,type:"invalid-pattern",message:run.stderr.split(`
|
|
6431
6433
|
`)[0]},null,2);let{matches,total}=parseAstGrepStream(run.stdout,directory,maxResults);return JSON.stringify({matches,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,total,pattern,language,maxResults,outputTruncated:run.stdoutTruncated||run.stderrTruncated},null,2)}}),_internals187={resolveExecutableFromPath,resolveAstGrepBinary,runExternalTool,parseAstGrepStream};init_dist();init_create_tool();import*as fs140 from"node:fs";import*as path250 from"node:path";init_path_security();var WINDOWS_RESERVED_NAMES4=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks3(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES4.test(part))return!0;return!1}function isPathInWorkspace2(filePath,workspace){try{let resolvedPath=path250.resolve(workspace,filePath);if(!fs140.existsSync(resolvedPath))return!0;let realWorkspace=fs140.realpathSync(workspace),realResolvedPath=fs140.realpathSync(resolvedPath),relativePath2=path250.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path250.isAbsolute(relativePath2))return!1;return!0}catch{return!1}}function processFile(file3,cwd,exportedOnly){let ext=path250.extname(file3);if(containsControlChars(file3))return{file:file3,success:!1,error:"Path contains invalid control characters",errorType:"invalid-path"};if(containsPathTraversal(file3))return{file:file3,success:!1,error:"Path contains path traversal sequence",errorType:"path-traversal"};if(containsWindowsAttacks3(file3))return{file:file3,success:!1,error:"Path contains invalid Windows-specific sequence",errorType:"invalid-path"};if(!isPathInWorkspace2(file3,cwd))return{file:file3,success:!1,error:"Path is outside workspace",errorType:"path-outside-workspace"};let fullPath=path250.join(cwd,file3);if(!fs140.existsSync(fullPath))return{file:file3,success:!1,error:`File not found: ${file3}`,errorType:"file-not-found"};let syms;switch(ext){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(file3,cwd);break;case".py":case".pyw":syms=extractPythonSymbols(file3,cwd);break;case".rs":syms=extractRustSymbols(file3,cwd);break;case".go":syms=extractGoSymbols(file3,cwd);break;default:return{file:file3,success:!1,error:`Unsupported file extension: ${ext}. Supported: .ts, .tsx, .js, .jsx, .mjs, .cjs, .py, .pyw, .rs, .go`,errorType:"unsupported-language"}}let isEmptyFile=!1;try{if(fs140.statSync(fullPath).size===0)isEmptyFile=!0}catch{}if(syms.length===0)try{if(fs140.readFileSync(fullPath,"utf-8").trim().length===0)isEmptyFile=!0}catch{}if(isEmptyFile)return{file:file3,success:!0,symbols:[],error:"empty-file",errorType:"empty-file"};if(exportedOnly)syms=syms.filter((s)=>s.exported);return{file:file3,success:!0,symbols:syms}}var batch_symbols=createSwarmTool({description:"Extract symbols from multiple files in a single batch call. Accepts an array of file paths and returns per-file symbol summaries. One bad file does not crash the batch. Use for surveying a module when you need symbol information from multiple files at once.",args:{files:tool.schema.array(tool.schema.string()).describe("Array of file paths to extract symbols from"),exported_only:tool.schema.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols.")},execute:async(args2,directory)=>{let files,exportedOnly=!0;try{let obj=args2;if(!Array.isArray(obj.files))return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: files must be an array"},null,2);files=obj.files.map((f)=>String(f)),exportedOnly=obj.exported_only!==!1}catch{return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: could not extract files array"},null,2)}let cwd=directory,results=[];for(let file3 of files){let result=processFile(file3,cwd,exportedOnly);results.push(result)}let successCount=results.filter((r)=>r.success).length,failureCount=results.filter((r)=>!r.success).length,batchResult={results,totalFiles:files.length,successCount,failureCount};return JSON.stringify(batchResult,null,2)}});init_zod();init_discovery();init_manager2();init_bun_compat();init_logger();init_create_tool();var DEFAULT_TIMEOUT_MS4=300000,MAX_OUTPUT_BYTES6=10240,MAX_OUTPUT_LINES=100;function truncateOutput(output,maxLines=MAX_OUTPUT_LINES,maxBytes=MAX_OUTPUT_BYTES6){if(!output)return"";let truncated=output;if(truncated.length>maxBytes)truncated=truncated.slice(-maxBytes);let lines=truncated.split(`
|
|
6432
6434
|
`);if(lines.length>maxLines)return lines.slice(-maxLines).join(`
|
|
6433
|
-
`);return truncated}function getCommandKind(command){let lower=command.toLowerCase();if(lower.includes("typecheck")||lower.includes("check")||lower.includes("analyze")||lower.includes("lint"))return"typecheck";if(lower.includes("test")||lower.includes("spec")||lower.includes("jest")||lower.includes("vitest")||lower.includes("mocha")||lower.includes("pytest"))return"test";return"build"}function filterByMode(commands,mode){if(mode==="both")return commands;return commands.filter((cmd)=>getCommandKind(cmd.command)===mode)}async function executeCommand(command){let startTime=Date.now(),kind=getCommandKind(command.command),isWindows=process.platform==="win32",cmd,args2;if(isWindows&&!command.command.includes(" "))cmd=[command.command],args2=[];else if(isWindows)cmd=["cmd","/c",command.command],args2=[];else cmd=["/bin/sh"],args2=["-c",command.command];let result=bunSpawn([...cmd,...args2],{cwd:command.cwd,stdout:"pipe",stderr:"pipe",timeout:DEFAULT_TIMEOUT_MS4}),[exitCode,stdout,stderr]=await Promise.all([result.exited,result.stdout.text(),result.stderr.text()]),duration_ms=Date.now()-startTime;return{kind,command:command.command,cwd:command.cwd,exit_code:exitCode??-1,duration_ms,stdout_tail:truncateOutput(stdout),stderr_tail:truncateOutput(stderr)}}async function runBuildCheck(workingDir,input){let scope=input.scope??"all",mode=input.mode??"both",changedFiles=input.changed_files??[],discoveryResult=await discoverBuildCommands(workingDir,{scope,changedFiles}),commands=filterByMode(discoveryResult.commands,mode),runs=[],failedCount=0;for(let cmd of commands)try{let run=await executeCommand(cmd);if(runs.push(run),run.exit_code!==0)failedCount++}catch(error93){runs.push({kind:getCommandKind(cmd.command),command:cmd.command,cwd:cmd.cwd,exit_code:-1,duration_ms:0,stdout_tail:"",stderr_tail:error93 instanceof Error?error93.message:"Unknown error"}),failedCount++}let verdict,skipped_reason;if(runs.length===0)if(verdict="info",discoveryResult.skipped.length>0)skipped_reason=discoveryResult.skipped.map((s)=>`${s.ecosystem}: ${s.reason}`).join("; ");else skipped_reason="No build commands discovered (no toolchains found)";else if(failedCount>0)verdict="fail";else verdict="pass";return{verdict,runs,summary:{files_scanned:changedFiles.length,runs_count:runs.length,failed_count:failedCount,skipped_reason}}}var build_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Discover and run build commands for various ecosystems in a project directory. Supports build, typecheck, and test commands.",args:{scope:exports_external.enum(["changed","all"]).describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changed_files:exports_external.array(exports_external.string()).optional().describe('List of changed files when scope is "changed"'),mode:exports_external.enum(["build","typecheck","both"]).optional().describe('Mode: "build" for build commands, "typecheck" for type checking, "both" for all (default: both)')},async execute(args2,directory){let obj=args2,scope=obj.scope??"all",changedFiles=obj.changed_files??[],mode=obj.mode??"both",workingDir=directory,result=await runBuildCheck(workingDir,{scope,changed_files:changedFiles,mode}),evidence2={task_id:"build",type:"build",timestamp:new Date().toISOString(),agent:"build_check",verdict:result.verdict,summary:`${result.runs.length} build command(s) executed, ${result.summary.failed_count} failed`,runs:result.runs,files_scanned:result.summary.files_scanned,runs_count:result.summary.runs_count,failed_count:result.summary.failed_count,skipped_reason:result.summary.skipped_reason};try{await saveEvidence(workingDir,"build",evidence2)}catch(error93){log("Failed to save build evidence:",error93 instanceof Error?error93.message:String(error93))}return JSON.stringify(result,null,2)}});init_zod();init_manager2();init_task_id();init_create_tool();init_resolve_working_directory();import*as fs141 from"node:fs";import*as path251 from"node:path";var EVIDENCE_DIR=".swarm/evidence";function isValidTaskId4(taskId){return isStrictTaskId2(taskId)}function isPathWithinSwarm(filePath,workspaceRoot){let normalizedWorkspace=path251.resolve(workspaceRoot),swarmPath3=path251.join(normalizedWorkspace,".swarm","evidence");return path251.resolve(filePath).startsWith(swarmPath3)}function readEvidenceFile(evidencePath){if(!fs141.existsSync(evidencePath))return null;let content;try{content=fs141.readFileSync(evidencePath,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(content)}catch{return null}if(parsed&&typeof parsed==="object"&&Array.isArray(parsed.required_gates)&&typeof parsed.gates==="object"&&parsed.gates!==null)return parsed;return null}var check_gate_status=createSwarmTool({description:"Read-only tool to check the gate status of a specific task. Reads .swarm/evidence/{taskId}.json and returns structured JSON describing required, passed, and missing gates.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "1.2.3", "1.2.3.4")').describe('The task ID to check gate status for (e.g., "1.1", "2.3.1")'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/evidence/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let taskIdInput,workingDirInput;try{if(args2&&typeof args2==="object"){let obj=args2;taskIdInput=typeof obj.task_id==="string"?obj.task_id:void 0,workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}}catch{}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={taskId:taskIdInput??"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:dirResult.message,todo_scan:null};return JSON.stringify(errorResult,null,2)}if(directory=dirResult.directory,!taskIdInput)return JSON.stringify({taskId:"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid task_id: task_id is required",todo_scan:null},null,2);if(!isValidTaskId4(taskIdInput)){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`Invalid task_id format: "${taskIdInput}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3", "1.2.3.4")`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let evidencePath=path251.join(directory,EVIDENCE_DIR,`${taskIdInput}.json`);if(!isPathWithinSwarm(evidencePath,directory))return JSON.stringify({taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid path: evidence path validation failed",todo_scan:null},null,2);let evidenceData=readEvidenceFile(evidencePath);if(!evidenceData){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`No evidence file found for task "${taskIdInput}" at ${evidencePath}. Evidence file may be missing or invalid.`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let requiredGates=evidenceData.required_gates||[],gatesMap=evidenceData.gates||{},passedGates=[],missingGates=[];for(let requiredGate of requiredGates)if(gatesMap[requiredGate])passedGates.push(requiredGate);else missingGates.push(requiredGate);let status=missingGates.length===0?"all_passed":"incomplete",message;if(status==="all_passed")message=`All required gates have passed for task "${taskIdInput}".`;else message=`Task "${taskIdInput}" is incomplete. Missing gates: ${missingGates.join(", ")}.`;let secretscanVerdict="not_run";try{let evidenceResult=await loadEvidence(directory,taskIdInput);if(evidenceResult.status==="found"){let secretscanEntries=evidenceResult.bundle.entries.filter((entry)=>entry.type==="secretscan");if(secretscanEntries.length>0){let lastSecretscan=secretscanEntries[secretscanEntries.length-1];if(isSecretscanEvidence(lastSecretscan)){let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=lastSecretscan,findingsCount=lastSecretscan.findings_count??0,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasFindings=findingsCount>0,hasZeroCoverage=lastSecretscan.files_scanned===0;if(hasIncompleteCoverage||hasFindings||hasZeroCoverage||lastSecretscan.verdict==="fail"||lastSecretscan.verdict==="rejected")if(secretscanVerdict="fail",hasIncompleteCoverage&&!hasFindings){if(missingGates.push("secretscan (BLOCKED — incomplete coverage)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan incomplete coverage in prior scan. ${message}`}else if(hasFindings&&hasIncompleteCoverage){if(missingGates.push("secretscan (BLOCKED — secrets detected; incomplete coverage)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan found secrets and incomplete coverage in prior scan. ${message}`}else if(hasFindings){if(missingGates.push("secretscan (BLOCKED — secrets detected)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan found secrets in prior scan. ${message}`}else{if(missingGates.push("secretscan (BLOCKED — zero coverage)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan scanned zero files in prior scan. ${message}`}else if(lastSecretscan.verdict==="pass"||lastSecretscan.verdict==="approved"||lastSecretscan.verdict==="info")secretscanVerdict="pass"}}else message+=" Advisory: No secretscan evidence found for this task. Consider running secretscan."}else if(evidenceResult.status==="invalid_schema")secretscanVerdict="fail",missingGates.push("secretscan (BLOCKED — invalid evidence)"),status="incomplete",message=`BLOCKED: Secretscan evidence is invalid and cannot prove complete coverage. ${message}`}catch{}let todoScan=evidenceData.todo_scan;return JSON.stringify({taskId:taskIdInput,status,required_gates:requiredGates,passed_gates:passedGates,missing_gates:missingGates,gates:gatesMap,message,todo_scan:todoScan??null,secretscan_verdict:secretscanVerdict},null,2)}});init_checkpoint();init_co_change_analyzer();init_zod();init_pr_workflow_gate();init_create_tool();var CompletePrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),pr_head_sha:exports_external.string().trim().min(1).max(80)}).strict();async function executeCompletePrWorkflow(args2,directory,context={}){let parsed=CompletePrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow completion: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow completion requires an active sessionID"});try{let status=await _internals188.completePrWorkflow(directory,context.sessionID,parsed.data.mode,parsed.data.pr_head_sha),checkoutRestoreRequired=!1,checkoutRestoreReceipts=[];if(status==="completed")try{checkoutRestoreReceipts=await _internals188.listPendingPrWorkflowCheckoutRestores(directory,context.sessionID),checkoutRestoreRequired=checkoutRestoreReceipts.length>0}catch{checkoutRestoreRequired=!0}return JSON.stringify({success:!0,mode:parsed.data.mode,pr_head_sha:parsed.data.pr_head_sha,status,ready_to_publish:status==="ready-to-publish",verified_no_change:status==="verified-no-change",gate_cleared:status==="completed"||status==="verified-no-change",checkout_restore_required:checkoutRestoreRequired,checkout_restore_receipts:checkoutRestoreReceipts})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var complete_pr_workflow=createSwarmTool({description:"Validate terminal PR workflow coverage. After the ordered PR_FEEDBACK gates permit one standalone commit, the first call requires a clean tree and a non-merge direct child of intake HEAD, then binds its structured upstream target; the second clears only after both the local tracking ref and an actual-remote query point to that exact commit. A cleared result reports checkout_restore_required when preserved pre-workflow changes must be restored.",args:{mode:CompletePrWorkflowArgsSchema.shape.mode,pr_head_sha:CompletePrWorkflowArgsSchema.shape.pr_head_sha},execute:executeCompletePrWorkflow}),_internals188={completePrWorkflow,listPendingPrWorkflowCheckoutRestores};init_zod();init_utils2();init_state2();init_swarm_artifact_cache();init_create_tool();init_resolve_working_directory();import*as fs142 from"node:fs";import*as path252 from"node:path";function extractMatches(regex,text){return Array.from(text.matchAll(regex))}function parseIdentifiers(description){let identifiers=new Set,backtickRegex=/`([^`]+)`/g;for(let match of extractMatches(backtickRegex,description))identifiers.add(match[1]);let camelCaseRegex=/\b([a-z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(camelCaseRegex,description)){let word=match[1];if(word==="the"||word==="and"||word==="for"||word==="have"||word==="this"||word==="with"||word==="from"||word==="they"||word==="been"||word==="will"||word==="your"||word==="also")continue;identifiers.add(word)}let pascalCaseRegex=/\b([A-Z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(pascalCaseRegex,description))identifiers.add(match[1]);let configKeyRegex=/\b([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+)\b/g;for(let match of extractMatches(configKeyRegex,description))identifiers.add(match[1]);let quotedPathRegex=/['"](\.{0,3}(?:src|lib|test)[/\\][^'"]+)['"]/g;for(let match of extractMatches(quotedPathRegex,description))identifiers.add(match[1]);return Array.from(identifiers)}function parseFilePaths(description,filesTouched){if(filesTouched&&Array.isArray(filesTouched)&&filesTouched.length>0)return filesTouched;let filePaths=[],srcPathRegex=/\b(?:src|lib|test|app|packages?)[/\\][a-zA-Z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)\b/g;for(let match of extractMatches(srcPathRegex,description))filePaths.push(match[0]);let genericPathRegex=/\b[a-zA-Z0-9_./-]+[/\\][a-zA-Z0-9_./-]+\.[a-zA-Z0-9]+(?=\s|$|[.,;])/g;for(let match of extractMatches(genericPathRegex,description)){let pathStr=match[0];if(pathStr.includes("src/")||pathStr.includes("src\\")||pathStr.includes("lib/")||pathStr.includes("lib\\")||pathStr.includes("test/")||pathStr.includes("test\\"))filePaths.push(pathStr)}return filePaths}function buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked){if(tasksBlocked>0)return`Blocked: ${tasksBlocked} task(s) with missing identifiers`;let verified=tasksChecked-tasksSkipped;if(tasksSkipped===tasksChecked)return`All ${tasksChecked} completed task(s) skipped — research/inventory tasks`;if(tasksSkipped>0)return`${verified} task(s) verified, ${tasksSkipped} skipped (research tasks)`;return`All ${tasksChecked} completed tasks verified successfully`}async function executeCompletionVerify(args2,directory){let phase=Number(args2.phase);if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase))return JSON.stringify({success:!1,phase,status:"blocked",reason:"Invalid phase number",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);if(hasActiveTurboMode(args2.sessionID))return JSON.stringify({success:!0,phase,status:"passed",reason:"Turbo Mode active — completion verification bypassed",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);let plan;try{let planPath=validateSwarmPath(directory,"plan.json"),planRaw=fs142.readFileSync(planPath,"utf-8");plan=JSON.parse(planRaw)}catch{return JSON.stringify({success:!0,phase,status:"passed",reason:"Cannot verify without plan.json",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let targetPhase=plan.phases.find((p)=>p.id===phase);if(!targetPhase){let result2={success:!1,phase,status:"blocked",reason:`Phase ${phase} not found in plan.json`,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]};return JSON.stringify(result2,null,2)}let tasksChecked=0,tasksSkipped=0,tasksBlocked=0,blockedTasks=[];for(let task2 of targetPhase.tasks){if(task2.status!=="completed")continue;tasksChecked++;let fileTargets=parseFilePaths(task2.description,task2.files_touched),identifiers=parseIdentifiers(task2.description);if(fileTargets.length===0){tasksSkipped++;continue}if(identifiers.length===0){blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers — cannot verify completion without identifiers"}),tasksBlocked++;continue}let foundIdentifiers=new Set,hasFileReadFailure=!1;for(let filePath of fileTargets){let normalizedPath2=filePath.replace(/\\/g,"/"),resolvedPath=path252.resolve(directory,normalizedPath2),projectRoot=path252.resolve(directory),relative61=path252.relative(projectRoot,resolvedPath);if(!(relative61===""||!relative61.startsWith("..")&&!path252.isAbsolute(relative61))){blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File path '${filePath}' escapes the project directory — cannot verify completion`}),hasFileReadFailure=!0;continue}let fileContent;try{fileContent=fs142.readFileSync(resolvedPath,"utf-8")}catch{blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File '${filePath}' not found — cannot verify completion`}),hasFileReadFailure=!0;continue}for(let identifier of identifiers)if(fileContent.includes(identifier))foundIdentifiers.add(identifier)}let foundCount=foundIdentifiers.size;if(hasFileReadFailure||foundCount===0){if(!hasFileReadFailure)blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers found in target files"});tasksBlocked++}}let now2=new Date().toISOString(),result={success:tasksBlocked===0,phase,status:tasksBlocked===0?"passed":"blocked",reason:tasksBlocked>0?`COMPLETION_INCOMPLETE: ${tasksBlocked} task(s) blocked — missing identifiers or target files`:void 0,tasksChecked,tasksSkipped,tasksBlocked,blockedTasks};try{let evidenceDir=path252.join(directory,".swarm","evidence",`${phase}`),evidencePath=path252.join(evidenceDir,"completion-verify.json");fs142.mkdirSync(evidenceDir,{recursive:!0});let evidenceBundle={schema_version:"1.0.0",task_id:"completion-verify",created_at:now2,entries:[{task_id:"completion-verify",type:"completion_verify",timestamp:now2,agent:"completion_verify",verdict:tasksBlocked===0?"pass":"fail",summary:buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked),phase,tasks_checked:tasksChecked,tasks_skipped:tasksSkipped,tasks_blocked:tasksBlocked,blocked_tasks:blockedTasks}]};fs142.writeFileSync(evidencePath,JSON.stringify(evidenceBundle,null,2),"utf-8"),invalidateCachedArtifact(evidencePath)}catch{}return JSON.stringify(result,null,2)}var completion_verify=createSwarmTool({description:"Deterministic pre-check verifying that plan task identifiers exist in their target source files before phase completion. Blocks if obviously incomplete.",args:{phase:exports_external.number().describe("The phase number to check"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},execute:async(args2,directory)=>{let parsedArgs;try{if(args2&&typeof args2==="object"){let obj=args2;parsedArgs={phase:typeof obj.phase==="number"?obj.phase:typeof obj.phase==="string"?Number(obj.phase):0,sessionID:typeof obj.sessionID==="string"?obj.sessionID:void 0,working_directory:typeof obj.working_directory==="string"?obj.working_directory:void 0}}else parsedArgs={phase:0}}catch{return JSON.stringify({success:!1,phase:0,status:"blocked",reason:"Invalid arguments",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let dirResult=resolveWorkingDirectory(parsedArgs.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:parsedArgs.phase,status:"blocked",reason:dirResult.message,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);return executeCompletionVerify(parsedArgs,dirResult.directory)}});init_zod();init_metrics();init_bun_compat();init_create_tool();init_path_security();import*as fs143 from"node:fs";import*as path253 from"node:path";var MAX_FILE_SIZE_BYTES5=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N2=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N2,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}async function getGitChurn(days,directory){let churnMap=new Map,proc=bunSpawn(["git","log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",cwd:directory}),[stdout]=await Promise.all([proc.stdout.text(),proc.exited]),lines=stdout.split(/\r?\n/);for(let line of lines){let normalizedPath2=line.replace(/\\/g,"/");if(!normalizedPath2||normalizedPath2.trim()==="")continue;if(normalizedPath2.includes("node_modules")||normalizedPath2.includes("/.git/")||normalizedPath2.includes("/dist/")||normalizedPath2.includes("/build/")||normalizedPath2.includes("__tests__"))continue;if(normalizedPath2.includes(".test.")||normalizedPath2.includes(".spec."))continue;churnMap.set(normalizedPath2,(churnMap.get(normalizedPath2)||0)+1)}return churnMap}function getComplexityForFile2(filePath){try{if(fs143.statSync(filePath).size>MAX_FILE_SIZE_BYTES5)return null;let content=fs143.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory){let churnMap=await getGitChurn(days,directory),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count]of churnMap){let ext=path253.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs143.existsSync(fullPath))fullPath=path253.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_schema();init_miner();init_miner();init_store3();async function mineAndStoreConsensusV1(options){let priorFingerprints=options.deps.priorFingerprints??await listConsensusProposalFingerprints(options.directory),result=await mineConsensus(options.directory,options.request,{...options.deps,priorFingerprints}),report=await writeConsensusReport(options.directory,result.report);return{...result,report}}init_store3();init_memory();init_recommendation_ledger();init_state2();init_logger();init_create_tool();var MAX_FILTER_ENTRIES=200,FilterListSchema=exports_external.array(exports_external.string().min(1).max(512)).max(MAX_FILTER_ENTRIES),MAX_INLINE_ATTRIBUTES=25;function countSummaries(attributes,inlineLimit){let total=0,shown=0;for(let[index,attribute]of attributes.entries()){if(attribute.llmSummary===void 0)continue;if(total+=1,index<inlineLimit)shown+=1}return{total,hidden:total-shown}}function buildMinerRecommendationCandidates(report,sessionId){return report.proposals.map((proposal)=>({kind:"miner",target:proposal.target,statement:proposal.intent,scopeKeys:[],provenance:{mechanism:"consensus_mine",sourceEvidenceRefs:proposal.evidenceRefs,sourceRunIds:proposal.provenance.sourceRunIds,sourceModelIds:proposal.provenance.sourceModelIds,sourceTaskIds:proposal.provenance.sourceTaskIds},origin:{agentRole:"consensus_mine",...sessionId?{sessionId}:{},producedAt:report.generatedAt}}))}var MIRRORED_PROPOSAL_KIND="todo";async function mirrorProposalsToMemory(options){if(options.memoryConfig?.enabled!==!0)return{enabled:!1,attempted:0,proposed:0,rejected:0,failed:0};let proposals=options.report.proposals;if(proposals.length===0)return{enabled:!0,attempted:0,proposed:0,rejected:0,failed:0};let gateway;try{gateway=_internals189.createMemoryGateway({directory:options.directory,...options.sessionId?{sessionID:options.sessionId,runId:options.sessionId}:{},agentRole:"consensus_mine"},{config:options.memoryConfig})}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[consensus_mine] memory mirror unavailable (fail-open): ${message}`),{enabled:!0,attempted:proposals.length,proposed:0,rejected:0,failed:proposals.length,error:message}}let proposed=0,rejected=0,failed=0,error93;try{for(let proposal of proposals)try{if((await gateway.propose({operation:"add",kind:MIRRORED_PROPOSAL_KIND,text:proposal.intent,rationale:`consensus_mine proposal from report ${options.report.reportId}, attribute ${proposal.sourceAttributeId} (target ${proposal.target}, confidence ${proposal.confidence})`,evidenceRefs:proposal.evidenceRefs})).status==="rejected")rejected+=1;else proposed+=1}catch(err){failed+=1,error93??=err instanceof Error?err.message:String(err)}}finally{try{await gateway.dispose()}catch(err){warn(`[consensus_mine] memory gateway dispose failed: ${err instanceof Error?err.message:String(err)}`)}}if(error93!==void 0)warn(`[consensus_mine] memory mirror partially failed: ${error93}`);return{enabled:!0,attempted:proposals.length,proposed,rejected,failed,...error93?{error:error93}:{}}}var _internals189={createMemoryGateway};var consensus_mine=createSwarmTool({description:"Mine cross-run consensus from existing .swarm evidence — evaluation runs, gate audits, gate "+"ground truth, task trajectories, PRM sessions, skill usage, knowledge outcomes, evidence "+"bundles, and curated failures (nine sources) — and persist an immutable report of "+`agreed-upon attributes plus proposals-only recommendations. It never activates a skill, writes a knowledge entry, admits a durable memory record, edits a project file, or mutates any evidence it reads. It is NOT otherwise write-minimal, so plan for these effects: it DELETES its own older reports past consensus.report_retention (default 50) on every run; it rewrites the shared recommendation dedup ledger whole, with FIFO eviction that can drop another producer's oldest entries; it leaves one never-removed lock sentinel per report id under .swarm/locks/; when memory.enabled is true it mirrors each proposal into a PENDING swarm-memory proposal (curator review still required); and when consensus.llm_summarization_enabled is true (the default) it issues up to ${MAX_LLM_SUMMARIES} session.create plus session.prompt calls. Under a knowledge or memory link the ledger and the memory store resolve to the shared cohort root, outside this project's .swarm/.`,args:{run_ids:FilterListSchema.optional().describe("Restrict mining to these run ids (raw or namespaced). Omit for all runs."),task_categories:FilterListSchema.optional().describe("Restrict to these evaluation task categories. Omit for all categories."),agent_roles:FilterListSchema.optional().describe("Restrict to these agent roles. Omit for all roles."),model_ids:FilterListSchema.optional().describe("Restrict to these model ids. Omit for all models."),min_support:exports_external.number().int().min(1).max(1e4).optional().describe("Distinct runs required to emit an attribute. Defaults to consensus.default_min_support."),min_successful_runs:exports_external.number().int().min(0).max(1e4).optional().describe("Successful runs required. Defaults to consensus.default_min_successful_runs."),max_evidence_items:exports_external.number().int().min(1).max(1e4).optional().describe("Cap on corpus observations read. Defaults to consensus.default_max_evidence_items.")},execute:async(args2,directory,ctx)=>{let input=args2??{},loaded=loadPluginConfigWithMeta(directory),config3=ConsensusConfigSchema.parse(loaded.config.consensus??{});if(!config3.enabled)return JSON.stringify({success:!1,disabled:!0,message:"Consensus mining is disabled (consensus.enabled = false). No report was written."},null,2);let request={...input.run_ids?{runIds:input.run_ids}:{},...input.task_categories?{taskCategories:input.task_categories}:{},...input.agent_roles?{agentRoles:input.agent_roles}:{},...input.model_ids?{modelIds:input.model_ids}:{},minSupport:input.min_support??config3.default_min_support,minSuccessfulRuns:input.min_successful_runs??config3.default_min_successful_runs,maxEvidenceItems:input.max_evidence_items??config3.default_max_evidence_items},client=swarmState.opencodeClient,dispatcher=config3.llm_summarization_enabled&&client?createEvaluationModelDispatcher(client):void 0,result=await mineAndStoreConsensusV1({directory,request,deps:{config:config3,...dispatcher?{dispatcher}:{},...ctx?.sessionID?{sessionId:ctx.sessionID}:{},agentRole:"consensus_mine"}}),report=result.report,ledger=await recordEmittedRecommendations(directory,buildMinerRecommendationCandidates(report,ctx?.sessionID),{producedAt:report.generatedAt});if(ledger.degraded)warn("[consensus_mine] recommendation ledger write degraded; proposals were not recorded for cross-producer dedup");let memoryMirror=await mirrorProposalsToMemory({directory,memoryConfig:loaded.config.memory,report,...ctx?.sessionID?{sessionId:ctx.sessionID}:{}}),pruned=await pruneConsensusReports(directory,config3.report_retention),pruningEnabled=config3.report_retention>0,summaries=countSummaries(report.attributes,MAX_INLINE_ATTRIBUTES);return JSON.stringify({success:!0,report_id:report.reportId,report_path:`.swarm/evolution/consensus/${report.reportId}.json`,generated_at:report.generatedAt,integrity_hash:report.integrityHash,config_hash:report.configHash,redaction_policy_version:report.redactionPolicyVersion,thresholds:{min_support:request.minSupport,min_successful_runs:request.minSuccessfulRuns,max_evidence_items:request.maxEvidenceItems,min_task_diversity:MIN_TASK_DIVERSITY_FOR_PROPOSAL,min_support_for_proposal:MIN_SUPPORT_FOR_PROPOSAL},input_run_count:report.inputIds.length,corpus:report.corpusHashes.map((entry)=>({source:entry.source,observations:entry.observations})),corpus_truncated:result.truncated,truncation:{corpus:report.truncation.corpus,observations_tallied:report.truncation.observations,input_ids_truncated:report.truncation.inputIds,total_input_ids:report.truncation.totalInputIds,attributes_dropped:report.truncation.attributesDropped},unreadable_sources:result.unreadableSources,attribute_count:report.attributes.length,investigation_note_count:result.investigationNoteCount,proposal_count:report.proposals.length,deduped_proposal_count:result.dedupedProposalCount,recommendation_ledger:{recorded:ledger.recorded,duplicate_recommendation_count:ledger.suppressed,evicted:ledger.evicted,degraded:ledger.degraded},memory_mirror:memoryMirror,summarized_count:summaries.total,summarized_but_not_shown:summaries.hidden,restatements_accepted_this_run:result.summarizedCount,...result.summarizationSkippedReason?{summarization_skipped_reason:result.summarizationSkippedReason}:{},attributes:report.attributes.slice(0,MAX_INLINE_ATTRIBUTES).map((attribute)=>({id:attribute.id,statement:attribute.statement,...attribute.llmSummary?{llm_summary:attribute.llmSummary}:{},support:attribute.support,success_support:attribute.successSupport,failure_support:attribute.failureSupport,task_diversity:attribute.taskDiversity,model_diversity:attribute.modelDiversity,confidence:attribute.confidence,proposed_target:attribute.proposedTarget,counterexample_count:attribute.counterexampleRefs.length})),attributes_truncated:report.attributes.length>MAX_INLINE_ATTRIBUTES,retention:pruningEnabled?{configured:config3.report_retention,pruning_enabled:!0,deleted:pruned.deleted.length,retained:pruned.retained.length,failed:pruned.failed.length,corrupt:pruned.corrupt.length}:{configured:config3.report_retention,pruning_enabled:!1,deleted:0,failed:0},guarantees:["proposals only — no skill activation, no knowledge write, no durable memory record, and no mutation of any evidence read",'model_diversity 0 means "not measurable from this corpus", never "measured as none"',`attributes below task diversity ${MIN_TASK_DIVERSITY_FOR_PROPOSAL} or below support ${MIN_SUPPORT_FOR_PROPOSAL} are investigation notes, never proposals`,"an attribute counting failing runs always carries counterexample refs (schema-enforced)","truncation is not biased toward successes, but it is still a cut: it balances per source, and drops whole sources once the budget is spent","statement is deterministic; llm_summary is an optional restatement excluded from integrity_hash","reproducible: identical corpus, request, config_hash, and prior proposals yield the same integrity_hash and report_id; model wording never moves it",'truncation is declared on the report; read failure_support 0 on a truncated report as "none survived the cut"']},null,2)}});init_config();init_model_limits();init_utils2();init_state2();init_create_tool();var _internals190={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={},liveContextLimit,modelIdentity){let{modelID,providerID}=modelIdentity??extractModelInfo(messages),modelLimit=resolveModelLimit(modelID,providerID,modelLimitsConfig,liveContextLimit),totalTokens=0;for(let message of messages){if(!message?.parts)continue;for(let part of message.parts)if(part?.type==="text"&&part.text)totalTokens+=estimateTokens(part.text)}let usagePercent=totalTokens/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:totalTokens,modelLimit,usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Report current context-window headroom for the active session. Returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only — no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",args:{},async execute(_args,directory,ctx){let config3=_internals190.loadPluginConfig(directory),warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,modelLimitsConfig=config3.context_budget?.model_limits??{},messages=[];if(ctx?.sessionID){let sessionMessages=await _internals190.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let{modelID,providerID}=getLiveContextModelIdentity(ctx?.sessionID)??extractModelInfo(messages),headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig,getLiveContextWindow(ctx?.sessionID,{modelID,providerID}),{modelID,providerID});return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;pushAdvisory(session,`${header}
|
|
6435
|
+
`);return truncated}function getCommandKind(command){let lower=command.toLowerCase();if(lower.includes("typecheck")||lower.includes("check")||lower.includes("analyze")||lower.includes("lint"))return"typecheck";if(lower.includes("test")||lower.includes("spec")||lower.includes("jest")||lower.includes("vitest")||lower.includes("mocha")||lower.includes("pytest"))return"test";return"build"}function filterByMode(commands,mode){if(mode==="both")return commands;return commands.filter((cmd)=>getCommandKind(cmd.command)===mode)}async function executeCommand(command){let startTime=Date.now(),kind=getCommandKind(command.command),isWindows=process.platform==="win32",cmd,args2;if(isWindows&&!command.command.includes(" "))cmd=[command.command],args2=[];else if(isWindows)cmd=["cmd","/c",command.command],args2=[];else cmd=["/bin/sh"],args2=["-c",command.command];let result=bunSpawn([...cmd,...args2],{cwd:command.cwd,stdout:"pipe",stderr:"pipe",timeout:DEFAULT_TIMEOUT_MS4}),[exitCode,stdout,stderr]=await Promise.all([result.exited,result.stdout.text(),result.stderr.text()]),duration_ms=Date.now()-startTime;return{kind,command:command.command,cwd:command.cwd,exit_code:exitCode??-1,duration_ms,stdout_tail:truncateOutput(stdout),stderr_tail:truncateOutput(stderr)}}async function runBuildCheck(workingDir,input){let scope=input.scope??"all",mode=input.mode??"both",changedFiles=input.changed_files??[],discoveryResult=await discoverBuildCommands(workingDir,{scope,changedFiles}),commands=filterByMode(discoveryResult.commands,mode),runs=[],failedCount=0;for(let cmd of commands)try{let run=await executeCommand(cmd);if(runs.push(run),run.exit_code!==0)failedCount++}catch(error93){runs.push({kind:getCommandKind(cmd.command),command:cmd.command,cwd:cmd.cwd,exit_code:-1,duration_ms:0,stdout_tail:"",stderr_tail:error93 instanceof Error?error93.message:"Unknown error"}),failedCount++}let verdict,skipped_reason;if(runs.length===0)if(verdict="info",discoveryResult.skipped.length>0)skipped_reason=discoveryResult.skipped.map((s)=>`${s.ecosystem}: ${s.reason}`).join("; ");else skipped_reason="No build commands discovered (no toolchains found)";else if(failedCount>0)verdict="fail";else verdict="pass";return{verdict,runs,summary:{files_scanned:changedFiles.length,runs_count:runs.length,failed_count:failedCount,skipped_reason}}}var build_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Discover and run build commands for various ecosystems in a project directory. Supports build, typecheck, and test commands.",args:{scope:exports_external.enum(["changed","all"]).describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changed_files:exports_external.array(exports_external.string()).optional().describe('List of changed files when scope is "changed"'),mode:exports_external.enum(["build","typecheck","both"]).optional().describe('Mode: "build" for build commands, "typecheck" for type checking, "both" for all (default: both)')},async execute(args2,directory){let obj=args2,scope=obj.scope??"all",changedFiles=obj.changed_files??[],mode=obj.mode??"both",workingDir=directory,result=await runBuildCheck(workingDir,{scope,changed_files:changedFiles,mode}),evidence2={task_id:"build",type:"build",timestamp:new Date().toISOString(),agent:"build_check",verdict:result.verdict,summary:`${result.runs.length} build command(s) executed, ${result.summary.failed_count} failed`,runs:result.runs,files_scanned:result.summary.files_scanned,runs_count:result.summary.runs_count,failed_count:result.summary.failed_count,skipped_reason:result.summary.skipped_reason};try{await saveEvidence(workingDir,"build",evidence2)}catch(error93){log("Failed to save build evidence:",error93 instanceof Error?error93.message:String(error93))}return JSON.stringify(result,null,2)}});init_zod();init_manager2();init_task_id();init_create_tool();init_resolve_working_directory();import*as fs141 from"node:fs";import*as path251 from"node:path";var EVIDENCE_DIR=".swarm/evidence";function isValidTaskId4(taskId){return isStrictTaskId2(taskId)}function isPathWithinSwarm(filePath,workspaceRoot){let normalizedWorkspace=path251.resolve(workspaceRoot),swarmPath3=path251.join(normalizedWorkspace,".swarm","evidence");return path251.resolve(filePath).startsWith(swarmPath3)}function readEvidenceFile(evidencePath){if(!fs141.existsSync(evidencePath))return null;let content;try{content=fs141.readFileSync(evidencePath,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(content)}catch{return null}if(parsed&&typeof parsed==="object"&&Array.isArray(parsed.required_gates)&&typeof parsed.gates==="object"&&parsed.gates!==null)return parsed;return null}var check_gate_status=createSwarmTool({description:"Read-only tool to check the gate status of a specific task. Reads .swarm/evidence/{taskId}.json and returns structured JSON describing required, passed, and missing gates.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "1.2.3", "1.2.3.4")').describe('The task ID to check gate status for (e.g., "1.1", "2.3.1")'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/evidence/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let taskIdInput,workingDirInput;try{if(args2&&typeof args2==="object"){let obj=args2;taskIdInput=typeof obj.task_id==="string"?obj.task_id:void 0,workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}}catch{}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={taskId:taskIdInput??"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:dirResult.message,todo_scan:null};return JSON.stringify(errorResult,null,2)}if(directory=dirResult.directory,!taskIdInput)return JSON.stringify({taskId:"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid task_id: task_id is required",todo_scan:null},null,2);if(!isValidTaskId4(taskIdInput)){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`Invalid task_id format: "${taskIdInput}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3", "1.2.3.4")`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let evidencePath=path251.join(directory,EVIDENCE_DIR,`${taskIdInput}.json`);if(!isPathWithinSwarm(evidencePath,directory))return JSON.stringify({taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid path: evidence path validation failed",todo_scan:null},null,2);let evidenceData=readEvidenceFile(evidencePath);if(!evidenceData){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`No evidence file found for task "${taskIdInput}" at ${evidencePath}. Evidence file may be missing or invalid.`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let requiredGates=evidenceData.required_gates||[],gatesMap=evidenceData.gates||{},passedGates=[],missingGates=[];for(let requiredGate of requiredGates)if(gatesMap[requiredGate])passedGates.push(requiredGate);else missingGates.push(requiredGate);let status=missingGates.length===0?"all_passed":"incomplete",message;if(status==="all_passed")message=`All required gates have passed for task "${taskIdInput}".`;else message=`Task "${taskIdInput}" is incomplete. Missing gates: ${missingGates.join(", ")}.`;let secretscanVerdict="not_run";try{let evidenceResult=await loadEvidence(directory,taskIdInput);if(evidenceResult.status==="found"){let secretscanEntries=evidenceResult.bundle.entries.filter((entry)=>entry.type==="secretscan");if(secretscanEntries.length>0){let lastSecretscan=secretscanEntries[secretscanEntries.length-1];if(isSecretscanEvidence(lastSecretscan)){let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=lastSecretscan,findingsCount=lastSecretscan.findings_count??0,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasFindings=findingsCount>0,hasZeroCoverage=lastSecretscan.files_scanned===0;if(hasIncompleteCoverage||hasFindings||hasZeroCoverage||lastSecretscan.verdict==="fail"||lastSecretscan.verdict==="rejected")if(secretscanVerdict="fail",hasIncompleteCoverage&&!hasFindings){if(missingGates.push("secretscan (BLOCKED — incomplete coverage)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan incomplete coverage in prior scan. ${message}`}else if(hasFindings&&hasIncompleteCoverage){if(missingGates.push("secretscan (BLOCKED — secrets detected; incomplete coverage)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan found secrets and incomplete coverage in prior scan. ${message}`}else if(hasFindings){if(missingGates.push("secretscan (BLOCKED — secrets detected)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan found secrets in prior scan. ${message}`}else{if(missingGates.push("secretscan (BLOCKED — zero coverage)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan scanned zero files in prior scan. ${message}`}else if(lastSecretscan.verdict==="pass"||lastSecretscan.verdict==="approved"||lastSecretscan.verdict==="info")secretscanVerdict="pass"}}else message+=" Advisory: No secretscan evidence found for this task. Consider running secretscan."}else if(evidenceResult.status==="invalid_schema")secretscanVerdict="fail",missingGates.push("secretscan (BLOCKED — invalid evidence)"),status="incomplete",message=`BLOCKED: Secretscan evidence is invalid and cannot prove complete coverage. ${message}`}catch{}let todoScan=evidenceData.todo_scan;return JSON.stringify({taskId:taskIdInput,status,required_gates:requiredGates,passed_gates:passedGates,missing_gates:missingGates,gates:gatesMap,message,todo_scan:todoScan??null,secretscan_verdict:secretscanVerdict},null,2)}});init_checkpoint();init_co_change_analyzer();init_zod();init_pr_workflow_gate();init_create_tool();var CompletePrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),pr_head_sha:exports_external.string().trim().min(1).max(80)}).strict();async function executeCompletePrWorkflow(args2,directory,context={}){let parsed=CompletePrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow completion: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow completion requires an active sessionID"});let staleDisclosure={};try{let settlement=await _internals188.settlePresumedStalePrWorkflowLanes(directory,context.sessionID);if(settlement.presumedStaleLaneIds.length>0)staleDisclosure={presumed_stale_lanes:settlement.presumedStaleLaneIds,presumed_stale_disclosure:settlement.disclosure}}catch{}let amendmentDisclosure={};try{let gateState=await _internals188.readPrWorkflowGateState(directory,context.sessionID);if(gateState?.prFeedbackInventoryAmendments?.length)amendmentDisclosure={inventory_amendments:gateState.prFeedbackInventoryAmendments}}catch{}try{let status=await _internals188.completePrWorkflow(directory,context.sessionID,parsed.data.mode,parsed.data.pr_head_sha),checkoutRestoreRequired=!1,checkoutRestoreReceipts=[];if(status==="completed")try{checkoutRestoreReceipts=await _internals188.listPendingPrWorkflowCheckoutRestores(directory,context.sessionID),checkoutRestoreRequired=checkoutRestoreReceipts.length>0}catch{checkoutRestoreRequired=!0}return JSON.stringify({success:!0,mode:parsed.data.mode,pr_head_sha:parsed.data.pr_head_sha,status,ready_to_publish:status==="ready-to-publish",verified_no_change:status==="verified-no-change",gate_cleared:status==="completed"||status==="verified-no-change",checkout_restore_required:checkoutRestoreRequired,checkout_restore_receipts:checkoutRestoreReceipts,...staleDisclosure,...amendmentDisclosure})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93),...staleDisclosure,...amendmentDisclosure})}}var complete_pr_workflow=createSwarmTool({description:"Validate terminal PR workflow coverage. After the ordered PR_FEEDBACK gates permit one standalone commit, the first call requires a clean tree and a non-merge direct child of intake HEAD, then binds its structured upstream target; the second clears only after both the local tracking ref and an actual-remote query point to that exact commit. A cleared result reports checkout_restore_required when preserved pre-workflow changes must be restored.",args:{mode:CompletePrWorkflowArgsSchema.shape.mode,pr_head_sha:CompletePrWorkflowArgsSchema.shape.pr_head_sha},execute:executeCompletePrWorkflow}),_internals188={completePrWorkflow,listPendingPrWorkflowCheckoutRestores,readPrWorkflowGateState,settlePresumedStalePrWorkflowLanes};init_zod();init_utils2();init_state2();init_swarm_artifact_cache();init_create_tool();init_resolve_working_directory();import*as fs142 from"node:fs";import*as path252 from"node:path";function extractMatches(regex,text){return Array.from(text.matchAll(regex))}function parseIdentifiers(description){let identifiers=new Set,backtickRegex=/`([^`]+)`/g;for(let match of extractMatches(backtickRegex,description))identifiers.add(match[1]);let camelCaseRegex=/\b([a-z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(camelCaseRegex,description)){let word=match[1];if(word==="the"||word==="and"||word==="for"||word==="have"||word==="this"||word==="with"||word==="from"||word==="they"||word==="been"||word==="will"||word==="your"||word==="also")continue;identifiers.add(word)}let pascalCaseRegex=/\b([A-Z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(pascalCaseRegex,description))identifiers.add(match[1]);let configKeyRegex=/\b([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+)\b/g;for(let match of extractMatches(configKeyRegex,description))identifiers.add(match[1]);let quotedPathRegex=/['"](\.{0,3}(?:src|lib|test)[/\\][^'"]+)['"]/g;for(let match of extractMatches(quotedPathRegex,description))identifiers.add(match[1]);return Array.from(identifiers)}function parseFilePaths(description,filesTouched){if(filesTouched&&Array.isArray(filesTouched)&&filesTouched.length>0)return filesTouched;let filePaths=[],srcPathRegex=/\b(?:src|lib|test|app|packages?)[/\\][a-zA-Z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)\b/g;for(let match of extractMatches(srcPathRegex,description))filePaths.push(match[0]);let genericPathRegex=/\b[a-zA-Z0-9_./-]+[/\\][a-zA-Z0-9_./-]+\.[a-zA-Z0-9]+(?=\s|$|[.,;])/g;for(let match of extractMatches(genericPathRegex,description)){let pathStr=match[0];if(pathStr.includes("src/")||pathStr.includes("src\\")||pathStr.includes("lib/")||pathStr.includes("lib\\")||pathStr.includes("test/")||pathStr.includes("test\\"))filePaths.push(pathStr)}return filePaths}function buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked){if(tasksBlocked>0)return`Blocked: ${tasksBlocked} task(s) with missing identifiers`;let verified=tasksChecked-tasksSkipped;if(tasksSkipped===tasksChecked)return`All ${tasksChecked} completed task(s) skipped — research/inventory tasks`;if(tasksSkipped>0)return`${verified} task(s) verified, ${tasksSkipped} skipped (research tasks)`;return`All ${tasksChecked} completed tasks verified successfully`}async function executeCompletionVerify(args2,directory){let phase=Number(args2.phase);if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase))return JSON.stringify({success:!1,phase,status:"blocked",reason:"Invalid phase number",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);if(hasActiveTurboMode(args2.sessionID))return JSON.stringify({success:!0,phase,status:"passed",reason:"Turbo Mode active — completion verification bypassed",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);let plan;try{let planPath=validateSwarmPath(directory,"plan.json"),planRaw=fs142.readFileSync(planPath,"utf-8");plan=JSON.parse(planRaw)}catch{return JSON.stringify({success:!0,phase,status:"passed",reason:"Cannot verify without plan.json",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let targetPhase=plan.phases.find((p)=>p.id===phase);if(!targetPhase){let result2={success:!1,phase,status:"blocked",reason:`Phase ${phase} not found in plan.json`,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]};return JSON.stringify(result2,null,2)}let tasksChecked=0,tasksSkipped=0,tasksBlocked=0,blockedTasks=[];for(let task2 of targetPhase.tasks){if(task2.status!=="completed")continue;tasksChecked++;let fileTargets=parseFilePaths(task2.description,task2.files_touched),identifiers=parseIdentifiers(task2.description);if(fileTargets.length===0){tasksSkipped++;continue}if(identifiers.length===0){blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers — cannot verify completion without identifiers"}),tasksBlocked++;continue}let foundIdentifiers=new Set,hasFileReadFailure=!1;for(let filePath of fileTargets){let normalizedPath2=filePath.replace(/\\/g,"/"),resolvedPath=path252.resolve(directory,normalizedPath2),projectRoot=path252.resolve(directory),relative61=path252.relative(projectRoot,resolvedPath);if(!(relative61===""||!relative61.startsWith("..")&&!path252.isAbsolute(relative61))){blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File path '${filePath}' escapes the project directory — cannot verify completion`}),hasFileReadFailure=!0;continue}let fileContent;try{fileContent=fs142.readFileSync(resolvedPath,"utf-8")}catch{blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File '${filePath}' not found — cannot verify completion`}),hasFileReadFailure=!0;continue}for(let identifier of identifiers)if(fileContent.includes(identifier))foundIdentifiers.add(identifier)}let foundCount=foundIdentifiers.size;if(hasFileReadFailure||foundCount===0){if(!hasFileReadFailure)blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers found in target files"});tasksBlocked++}}let now2=new Date().toISOString(),result={success:tasksBlocked===0,phase,status:tasksBlocked===0?"passed":"blocked",reason:tasksBlocked>0?`COMPLETION_INCOMPLETE: ${tasksBlocked} task(s) blocked — missing identifiers or target files`:void 0,tasksChecked,tasksSkipped,tasksBlocked,blockedTasks};try{let evidenceDir=path252.join(directory,".swarm","evidence",`${phase}`),evidencePath=path252.join(evidenceDir,"completion-verify.json");fs142.mkdirSync(evidenceDir,{recursive:!0});let evidenceBundle={schema_version:"1.0.0",task_id:"completion-verify",created_at:now2,entries:[{task_id:"completion-verify",type:"completion_verify",timestamp:now2,agent:"completion_verify",verdict:tasksBlocked===0?"pass":"fail",summary:buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked),phase,tasks_checked:tasksChecked,tasks_skipped:tasksSkipped,tasks_blocked:tasksBlocked,blocked_tasks:blockedTasks}]};fs142.writeFileSync(evidencePath,JSON.stringify(evidenceBundle,null,2),"utf-8"),invalidateCachedArtifact(evidencePath)}catch{}return JSON.stringify(result,null,2)}var completion_verify=createSwarmTool({description:"Deterministic pre-check verifying that plan task identifiers exist in their target source files before phase completion. Blocks if obviously incomplete.",args:{phase:exports_external.number().describe("The phase number to check"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},execute:async(args2,directory)=>{let parsedArgs;try{if(args2&&typeof args2==="object"){let obj=args2;parsedArgs={phase:typeof obj.phase==="number"?obj.phase:typeof obj.phase==="string"?Number(obj.phase):0,sessionID:typeof obj.sessionID==="string"?obj.sessionID:void 0,working_directory:typeof obj.working_directory==="string"?obj.working_directory:void 0}}else parsedArgs={phase:0}}catch{return JSON.stringify({success:!1,phase:0,status:"blocked",reason:"Invalid arguments",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let dirResult=resolveWorkingDirectory(parsedArgs.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:parsedArgs.phase,status:"blocked",reason:dirResult.message,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);return executeCompletionVerify(parsedArgs,dirResult.directory)}});init_zod();init_metrics();init_bun_compat();init_create_tool();init_path_security();import*as fs143 from"node:fs";import*as path253 from"node:path";var MAX_FILE_SIZE_BYTES5=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N2=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N2,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}async function getGitChurn(days,directory){let churnMap=new Map,proc=bunSpawn(["git","log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",cwd:directory}),[stdout]=await Promise.all([proc.stdout.text(),proc.exited]),lines=stdout.split(/\r?\n/);for(let line of lines){let normalizedPath2=line.replace(/\\/g,"/");if(!normalizedPath2||normalizedPath2.trim()==="")continue;if(normalizedPath2.includes("node_modules")||normalizedPath2.includes("/.git/")||normalizedPath2.includes("/dist/")||normalizedPath2.includes("/build/")||normalizedPath2.includes("__tests__"))continue;if(normalizedPath2.includes(".test.")||normalizedPath2.includes(".spec."))continue;churnMap.set(normalizedPath2,(churnMap.get(normalizedPath2)||0)+1)}return churnMap}function getComplexityForFile2(filePath){try{if(fs143.statSync(filePath).size>MAX_FILE_SIZE_BYTES5)return null;let content=fs143.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory){let churnMap=await getGitChurn(days,directory),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count]of churnMap){let ext=path253.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs143.existsSync(fullPath))fullPath=path253.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_schema();init_miner();init_miner();init_store3();async function mineAndStoreConsensusV1(options){let priorFingerprints=options.deps.priorFingerprints??await listConsensusProposalFingerprints(options.directory),result=await mineConsensus(options.directory,options.request,{...options.deps,priorFingerprints}),report=await writeConsensusReport(options.directory,result.report);return{...result,report}}init_store3();init_memory();init_recommendation_ledger();init_state2();init_logger();init_create_tool();var MAX_FILTER_ENTRIES=200,FilterListSchema=exports_external.array(exports_external.string().min(1).max(512)).max(MAX_FILTER_ENTRIES),MAX_INLINE_ATTRIBUTES=25;function countSummaries(attributes,inlineLimit){let total=0,shown=0;for(let[index,attribute]of attributes.entries()){if(attribute.llmSummary===void 0)continue;if(total+=1,index<inlineLimit)shown+=1}return{total,hidden:total-shown}}function buildMinerRecommendationCandidates(report,sessionId){return report.proposals.map((proposal)=>({kind:"miner",target:proposal.target,statement:proposal.intent,scopeKeys:[],provenance:{mechanism:"consensus_mine",sourceEvidenceRefs:proposal.evidenceRefs,sourceRunIds:proposal.provenance.sourceRunIds,sourceModelIds:proposal.provenance.sourceModelIds,sourceTaskIds:proposal.provenance.sourceTaskIds},origin:{agentRole:"consensus_mine",...sessionId?{sessionId}:{},producedAt:report.generatedAt}}))}var MIRRORED_PROPOSAL_KIND="todo";async function mirrorProposalsToMemory(options){if(options.memoryConfig?.enabled!==!0)return{enabled:!1,attempted:0,proposed:0,rejected:0,failed:0};let proposals=options.report.proposals;if(proposals.length===0)return{enabled:!0,attempted:0,proposed:0,rejected:0,failed:0};let gateway;try{gateway=_internals189.createMemoryGateway({directory:options.directory,...options.sessionId?{sessionID:options.sessionId,runId:options.sessionId}:{},agentRole:"consensus_mine"},{config:options.memoryConfig})}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[consensus_mine] memory mirror unavailable (fail-open): ${message}`),{enabled:!0,attempted:proposals.length,proposed:0,rejected:0,failed:proposals.length,error:message}}let proposed=0,rejected=0,failed=0,error93;try{for(let proposal of proposals)try{if((await gateway.propose({operation:"add",kind:MIRRORED_PROPOSAL_KIND,text:proposal.intent,rationale:`consensus_mine proposal from report ${options.report.reportId}, attribute ${proposal.sourceAttributeId} (target ${proposal.target}, confidence ${proposal.confidence})`,evidenceRefs:proposal.evidenceRefs})).status==="rejected")rejected+=1;else proposed+=1}catch(err){failed+=1,error93??=err instanceof Error?err.message:String(err)}}finally{try{await gateway.dispose()}catch(err){warn(`[consensus_mine] memory gateway dispose failed: ${err instanceof Error?err.message:String(err)}`)}}if(error93!==void 0)warn(`[consensus_mine] memory mirror partially failed: ${error93}`);return{enabled:!0,attempted:proposals.length,proposed,rejected,failed,...error93?{error:error93}:{}}}var _internals189={createMemoryGateway};var consensus_mine=createSwarmTool({description:"Mine cross-run consensus from existing .swarm evidence — evaluation runs, gate audits, gate "+"ground truth, task trajectories, PRM sessions, skill usage, knowledge outcomes, evidence "+"bundles, and curated failures (nine sources) — and persist an immutable report of "+`agreed-upon attributes plus proposals-only recommendations. It never activates a skill, writes a knowledge entry, admits a durable memory record, edits a project file, or mutates any evidence it reads. It is NOT otherwise write-minimal, so plan for these effects: it DELETES its own older reports past consensus.report_retention (default 50) on every run; it rewrites the shared recommendation dedup ledger whole, with FIFO eviction that can drop another producer's oldest entries; it leaves one never-removed lock sentinel per report id under .swarm/locks/; when memory.enabled is true it mirrors each proposal into a PENDING swarm-memory proposal (curator review still required); and when consensus.llm_summarization_enabled is true (the default) it issues up to ${MAX_LLM_SUMMARIES} session.create plus session.prompt calls. Under a knowledge or memory link the ledger and the memory store resolve to the shared cohort root, outside this project's .swarm/.`,args:{run_ids:FilterListSchema.optional().describe("Restrict mining to these run ids (raw or namespaced). Omit for all runs."),task_categories:FilterListSchema.optional().describe("Restrict to these evaluation task categories. Omit for all categories."),agent_roles:FilterListSchema.optional().describe("Restrict to these agent roles. Omit for all roles."),model_ids:FilterListSchema.optional().describe("Restrict to these model ids. Omit for all models."),min_support:exports_external.number().int().min(1).max(1e4).optional().describe("Distinct runs required to emit an attribute. Defaults to consensus.default_min_support."),min_successful_runs:exports_external.number().int().min(0).max(1e4).optional().describe("Successful runs required. Defaults to consensus.default_min_successful_runs."),max_evidence_items:exports_external.number().int().min(1).max(1e4).optional().describe("Cap on corpus observations read. Defaults to consensus.default_max_evidence_items.")},execute:async(args2,directory,ctx)=>{let input=args2??{},loaded=loadPluginConfigWithMeta(directory),config3=ConsensusConfigSchema.parse(loaded.config.consensus??{});if(!config3.enabled)return JSON.stringify({success:!1,disabled:!0,message:"Consensus mining is disabled (consensus.enabled = false). No report was written."},null,2);let request={...input.run_ids?{runIds:input.run_ids}:{},...input.task_categories?{taskCategories:input.task_categories}:{},...input.agent_roles?{agentRoles:input.agent_roles}:{},...input.model_ids?{modelIds:input.model_ids}:{},minSupport:input.min_support??config3.default_min_support,minSuccessfulRuns:input.min_successful_runs??config3.default_min_successful_runs,maxEvidenceItems:input.max_evidence_items??config3.default_max_evidence_items},client=swarmState.opencodeClient,dispatcher=config3.llm_summarization_enabled&&client?createEvaluationModelDispatcher(client):void 0,result=await mineAndStoreConsensusV1({directory,request,deps:{config:config3,...dispatcher?{dispatcher}:{},...ctx?.sessionID?{sessionId:ctx.sessionID}:{},agentRole:"consensus_mine"}}),report=result.report,ledger=await recordEmittedRecommendations(directory,buildMinerRecommendationCandidates(report,ctx?.sessionID),{producedAt:report.generatedAt});if(ledger.degraded)warn("[consensus_mine] recommendation ledger write degraded; proposals were not recorded for cross-producer dedup");let memoryMirror=await mirrorProposalsToMemory({directory,memoryConfig:loaded.config.memory,report,...ctx?.sessionID?{sessionId:ctx.sessionID}:{}}),pruned=await pruneConsensusReports(directory,config3.report_retention),pruningEnabled=config3.report_retention>0,summaries=countSummaries(report.attributes,MAX_INLINE_ATTRIBUTES);return JSON.stringify({success:!0,report_id:report.reportId,report_path:`.swarm/evolution/consensus/${report.reportId}.json`,generated_at:report.generatedAt,integrity_hash:report.integrityHash,config_hash:report.configHash,redaction_policy_version:report.redactionPolicyVersion,thresholds:{min_support:request.minSupport,min_successful_runs:request.minSuccessfulRuns,max_evidence_items:request.maxEvidenceItems,min_task_diversity:MIN_TASK_DIVERSITY_FOR_PROPOSAL,min_support_for_proposal:MIN_SUPPORT_FOR_PROPOSAL},input_run_count:report.inputIds.length,corpus:report.corpusHashes.map((entry)=>({source:entry.source,observations:entry.observations})),corpus_truncated:result.truncated,truncation:{corpus:report.truncation.corpus,observations_tallied:report.truncation.observations,input_ids_truncated:report.truncation.inputIds,total_input_ids:report.truncation.totalInputIds,attributes_dropped:report.truncation.attributesDropped},unreadable_sources:result.unreadableSources,attribute_count:report.attributes.length,investigation_note_count:result.investigationNoteCount,proposal_count:report.proposals.length,deduped_proposal_count:result.dedupedProposalCount,recommendation_ledger:{recorded:ledger.recorded,duplicate_recommendation_count:ledger.suppressed,evicted:ledger.evicted,degraded:ledger.degraded},memory_mirror:memoryMirror,summarized_count:summaries.total,summarized_but_not_shown:summaries.hidden,restatements_accepted_this_run:result.summarizedCount,...result.summarizationSkippedReason?{summarization_skipped_reason:result.summarizationSkippedReason}:{},attributes:report.attributes.slice(0,MAX_INLINE_ATTRIBUTES).map((attribute)=>({id:attribute.id,statement:attribute.statement,...attribute.llmSummary?{llm_summary:attribute.llmSummary}:{},support:attribute.support,success_support:attribute.successSupport,failure_support:attribute.failureSupport,task_diversity:attribute.taskDiversity,model_diversity:attribute.modelDiversity,confidence:attribute.confidence,proposed_target:attribute.proposedTarget,counterexample_count:attribute.counterexampleRefs.length})),attributes_truncated:report.attributes.length>MAX_INLINE_ATTRIBUTES,retention:pruningEnabled?{configured:config3.report_retention,pruning_enabled:!0,deleted:pruned.deleted.length,retained:pruned.retained.length,failed:pruned.failed.length,corrupt:pruned.corrupt.length}:{configured:config3.report_retention,pruning_enabled:!1,deleted:0,failed:0},guarantees:["proposals only — no skill activation, no knowledge write, no durable memory record, and no mutation of any evidence read",'model_diversity 0 means "not measurable from this corpus", never "measured as none"',`attributes below task diversity ${MIN_TASK_DIVERSITY_FOR_PROPOSAL} or below support ${MIN_SUPPORT_FOR_PROPOSAL} are investigation notes, never proposals`,"an attribute counting failing runs always carries counterexample refs (schema-enforced)","truncation is not biased toward successes, but it is still a cut: it balances per source, and drops whole sources once the budget is spent","statement is deterministic; llm_summary is an optional restatement excluded from integrity_hash","reproducible: identical corpus, request, config_hash, and prior proposals yield the same integrity_hash and report_id; model wording never moves it",'truncation is declared on the report; read failure_support 0 on a truncated report as "none survived the cut"']},null,2)}});init_config();init_model_limits();init_utils2();init_state2();init_create_tool();var _internals190={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={},liveContextLimit,modelIdentity){let{modelID,providerID}=modelIdentity??extractModelInfo(messages),modelLimit=resolveModelLimit(modelID,providerID,modelLimitsConfig,liveContextLimit),totalTokens=0;for(let message of messages){if(!message?.parts)continue;for(let part of message.parts)if(part?.type==="text"&&part.text)totalTokens+=estimateTokens(part.text)}let usagePercent=totalTokens/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:totalTokens,modelLimit,usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Report current context-window headroom for the active session. Returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only — no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",args:{},async execute(_args,directory,ctx){let config3=_internals190.loadPluginConfig(directory),warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,modelLimitsConfig=config3.context_budget?.model_limits??{},messages=[];if(ctx?.sessionID){let sessionMessages=await _internals190.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let{modelID,providerID}=getLiveContextModelIdentity(ctx?.sessionID)??extractModelInfo(messages),headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig,getLiveContextWindow(ctx?.sessionID,{modelID,providerID}),{modelID,providerID});return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;pushAdvisory(session,`${header}
|
|
6434
6436
|
${body}`,{dedupeKey:dedupKey})}init_zod();init_task_file();init_gate_evidence();init_project_boundary();import{existsSync as existsSync129,mkdirSync as mkdirSync64,readFileSync as readFileSync100}from"node:fs";import{join as join202}from"node:path";var EVIDENCE_DIR2=".swarm/evidence",VALID_TASK_ID=/^\d+\.\d+(\.\d+)*$/,COUNCIL_GATE_NAME="council",COUNCIL_AGENT_ID="architect",EvidenceFileSchema=exports_external.record(exports_external.string(),exports_external.unknown()),_internals191={withTaskEvidenceLock},FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);function safeAssignOwnProps(target,source){for(let key of Object.keys(source)){if(FORBIDDEN_KEYS.has(key))continue;let value=source[key];if(value!==null&&typeof value==="object"&&!Array.isArray(value)){let nested=Object.create(null);safeAssignOwnProps(nested,value),target[key]=nested}else if(Array.isArray(value))target[key]=value.map((item)=>{if(item!==null&&typeof item==="object"&&!Array.isArray(item)){let nested=Object.create(null);return safeAssignOwnProps(nested,item),nested}return item});else target[key]=value}return target}async function writeCouncilEvidence(workingDir,synthesis,attemptId,expectedGeneration){if(!VALID_TASK_ID.test(synthesis.taskId))throw Error(`writeCouncilEvidence: invalid taskId "${synthesis.taskId}" — must match N.M or N.M.P format`);let dir=join202(workingDir,EVIDENCE_DIR2);assertProjectRoot(workingDir),mkdirSync64(dir,{recursive:!0});let filePath=taskEvidencePath(workingDir,synthesis.taskId);await _internals191.withTaskEvidenceLock(workingDir,synthesis.taskId,COUNCIL_AGENT_ID,async()=>{assertTaskEvidenceWriteAllowed(workingDir,synthesis.taskId);let existingRoot=Object.create(null);if(existsSync129(filePath))try{let raw=readFileSync100(filePath,"utf-8");if(expectedGeneration!==void 0){let exactEvidence=parseTaskEvidence(raw,synthesis.taskId),workflow=getTaskWorkflowSnapshot(exactEvidence);if(!workflow.authoritative||workflow.generation!==expectedGeneration||workflow.state!=="pre_check_passed")throw Error(`TASK_COUNCIL_GENERATION_MISMATCH: expected pre_check_passed@${expectedGeneration}, found ${workflow.state}@${workflow.generation}`)}let parsed=EvidenceFileSchema.parse(JSON.parse(raw));safeAssignOwnProps(existingRoot,parsed)}catch(error93){if(expectedGeneration!==void 0)throw error93}else if(expectedGeneration!==void 0)throw Error(`TASK_COUNCIL_GENERATION_MISMATCH: no exact evidence exists for generation ${expectedGeneration}`);let existingGatesRaw=existingRoot.gates,mergedGates=Object.create(null);if(existingGatesRaw&&typeof existingGatesRaw==="object"&&!Array.isArray(existingGatesRaw))safeAssignOwnProps(mergedGates,existingGatesRaw);mergedGates[COUNCIL_GATE_NAME]={sessionId:synthesis.swarmId,timestamp:synthesis.timestamp,agent:COUNCIL_AGENT_ID,verdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,quorumSize:synthesis.quorumSize,...expectedGeneration!==void 0?{workflowGeneration:expectedGeneration}:{},...attemptId?{attemptId}:{}};let updated=Object.create(null);if(safeAssignOwnProps(updated,existingRoot),updated.gates=mergedGates,!updated.taskId)updated.taskId=synthesis.taskId;if(!Array.isArray(updated.required_gates))updated.required_gates=[];await atomicWriteFile(filePath,JSON.stringify(updated,null,2))})}function hasCouncilEvidenceAttempt(workingDir,taskId,attemptId,roundNumber){if(!VALID_TASK_ID.test(taskId))return!1;try{let council=EvidenceFileSchema.parse(JSON.parse(readFileSync100(taskEvidencePath(workingDir,taskId),"utf-8"))).gates?.[COUNCIL_GATE_NAME];return council?.attemptId===attemptId&&council.roundNumber===roundNumber}catch{return!1}}init_lock();init_task_file();import{createHash as createHash50,randomUUID as randomUUID27}from"node:crypto";import{closeSync as closeSync21,existsSync as existsSync130,fsyncSync as fsyncSync7,mkdirSync as mkdirSync65,openSync as openSync21,readFileSync as readFileSync101,readSync as readSync14,statSync as statSync53,writeSync as writeSync2}from"node:fs";import{dirname as dirname103,join as join203}from"node:path";var VERSION=1,MAX_ROUND=10,MAX_AUDIT_TAIL=262144,STATE_AGENT="council-round-state";class CouncilRoundStateUncertainError extends Error{constructor(message){super(message);this.name="CouncilRoundStateUncertainError"}}function sha2564(value){return createHash50("sha256").update(value).digest("hex")}var UUID_PATTERN2=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,DIGEST_PATTERN=/^[a-f0-9]{64}$/;function isUuid2(value){return typeof value==="string"&&UUID_PATTERN2.test(value)}function isDigest(value){return typeof value==="string"&&DIGEST_PATTERN.test(value)}function isRound(value){return Number.isInteger(value)&&Number(value)>=1&&Number(value)<=MAX_ROUND}function isDisposition(value){return typeof value==="string"&&value.length>0&&value.length<=80}function isEvidenceRef(value){return typeof value==="string"&&value.length>0&&value.length<=240&&value.startsWith(".swarm/")&&!value.includes("..")}function scopeToken(scope){if(scope.kind==="task"){if(!/^\d+\.\d+(\.\d+)*$/.test(scope.taskId))throw Error("invalid task council scope");return`task-${sha2564(scope.taskId)}`}if(scope.kind==="phase"){if(!Number.isInteger(scope.phaseNumber)||scope.phaseNumber<1||scope.phaseNumber>1000)throw Error("invalid phase council scope");return`phase-${scope.phaseNumber}`}if(typeof scope.generation!=="string"||scope.generation.length===0||scope.generation.length>256)throw Error("invalid final council scope");return`final-${sha2564(scope.generation)}`}function auditScope(scope){if(scopeToken(scope),scope.kind==="task")return{kind:"task",scopeHash:sha2564(scope.taskId)};if(scope.kind==="phase")return{kind:"phase",phaseNumber:scope.phaseNumber};return{kind:"final",scopeHash:sha2564(scope.generation)}}function sameAuditScope(left,right){if(left.kind!==right.kind)return!1;if(left.kind==="phase"&&right.kind==="phase")return left.phaseNumber===right.phaseNumber;if(left.kind!=="phase"&&right.kind!=="phase")return left.scopeHash===right.scopeHash;return!1}function councilRoundStatePaths(directory,scope){let token=scopeToken(scope);return{state:join203(directory,".swarm","council","round-state",`${token}.json`),audit:join203(directory,".swarm","council","attempts",`${token}.jsonl`),lock:join203("council","round-state",`${token}.json`)}}function canonicalize2(value){if(Array.isArray(value))return value.map(canonicalize2);if(value&&typeof value==="object"){let result=Object.create(null);for(let key of Object.keys(value).sort()){if(key==="working_directory"||key==="roundNumber"||key==="provenanceAgentName"||key==="provenanceSessionId")continue;result[key]=canonicalize2(value[key])}return result}return value}function councilRequestDigest(request,round){return sha2564(JSON.stringify({round,request:canonicalize2(request)}))}function isSnapshot(value){if(!value||typeof value!=="object")return!1;let state=value;return state.version===VERSION&&isRound(state.currentRound)&&(state.status==="open"||state.status==="closed")&&typeof state.maxRoundsExhausted==="boolean"&&(state.lastAttemptId===void 0||isUuid2(state.lastAttemptId))&&(state.lastDigest===void 0||isDigest(state.lastDigest))&&state.lastAttemptId===void 0===(state.lastDigest===void 0)}function isTransition(value){return value==="stay"||value==="advance"||value==="close"}function isGateEffect(value){return value==="none"||value==="blocked"||value==="allowed"}function isVerdict(value){return value==="APPROVE"||value==="CONCERNS"||value==="REJECT"}function auditTransitionIsConsistent(record3){if(!record3.nextState||!record3.transition)return!1;if(record3.transition==="close")return record3.nextState.status==="closed"&&record3.nextState.currentRound===record3.authoritativeRound;if(record3.transition==="stay"){if(record3.nextState.status==="closed"&&!["duplicate_submission","council_round_closed","council_round_mismatch"].includes(record3.disposition))return!1;return(record3.nextState.status==="open"||record3.nextState.status==="closed")&&record3.nextState.currentRound===record3.authoritativeRound}return record3.nextState.status==="open"&&(record3.nextState.currentRound===record3.authoritativeRound+1&&record3.nextState.maxRoundsExhausted===!1||record3.nextState.currentRound===record3.authoritativeRound&&record3.nextState.maxRoundsExhausted===!0)}function recoverAuditHistory(tail2){let current=tail2.truncated?void 0:initialState(),awaiting,sawTransition=!1;for(let record3 of tail2.records){if(record3.event==="received"){if(awaiting)throw new CouncilRoundStateUncertainError("council audit contains overlapping attempts");if(current&&record3.authoritativeRound!==current.currentRound||!current&&!tail2.truncated&&record3.authoritativeRound!==1)throw new CouncilRoundStateUncertainError("council audit round history is not monotonic");awaiting=record3;continue}if(!record3.nextState||!record3.transition)throw new CouncilRoundStateUncertainError("council audit transition is incomplete");if(awaiting){if(awaiting.attemptId!==record3.attemptId||awaiting.digest!==record3.digest||awaiting.authoritativeRound!==record3.authoritativeRound)throw new CouncilRoundStateUncertainError("council audit attempt pairing is inconsistent");awaiting=void 0}else if(!tail2.truncated||sawTransition)throw new CouncilRoundStateUncertainError("council audit transition has no matching received record");if(current){if(record3.authoritativeRound!==current.currentRound)throw new CouncilRoundStateUncertainError("council audit transition regresses the authoritative round");if(record3.transition==="stay"&&record3.nextState.status!==current.status)throw new CouncilRoundStateUncertainError("council audit stay transition changes scope status");if((record3.transition==="stay"||record3.transition==="close")&&record3.nextState.maxRoundsExhausted!==current.maxRoundsExhausted)throw new CouncilRoundStateUncertainError("council audit changes exhaustion without advancing");if(current.status==="closed"&&(record3.transition!=="stay"||record3.nextState.status!=="closed"))throw new CouncilRoundStateUncertainError("council audit reopens a closed scope")}current=record3.nextState,sawTransition=!0}if(awaiting)throw new CouncilRoundStateUncertainError("council audit ends with an unresolved received attempt");return current}function pendingMatchesParent(state,pending){if(state.status!=="open"||pending.round!==state.currentRound)return!1;if(pending.nextState.lastAttemptId!==pending.attemptId||pending.nextState.lastDigest!==pending.digest)return!1;if(pending.transition==="stay")return pending.nextState.status==="open"&&pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===state.maxRoundsExhausted;if(pending.transition==="close")return pending.nextState.status==="closed"&&pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===state.maxRoundsExhausted;return pending.nextState.status==="open"&&(pending.nextState.currentRound===state.currentRound+1&&pending.nextState.maxRoundsExhausted===!1||pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===!0)}function parseState(raw){let value;try{value=JSON.parse(raw)}catch{throw new CouncilRoundStateUncertainError("council round state is corrupt")}if(!isSnapshot(value))throw new CouncilRoundStateUncertainError("council round state is invalid");let state=value;if(state.pending){let pending=state.pending;if(!isUuid2(pending.attemptId)||!isDigest(pending.digest)||!isRound(pending.round)||!isSnapshot(pending.nextState)||!isTransition(pending.transition)||!isDisposition(pending.disposition)||!isGateEffect(pending.gateEffect)||typeof pending.evidenceExpected!=="boolean"||pending.evidenceExpected!==(pending.evidenceRef!==void 0)||pending.evidenceRef!==void 0&&!isEvidenceRef(pending.evidenceRef)||pending.verdict!==void 0&&!isVerdict(pending.verdict)||pending.quorumSize!==void 0&&(!Number.isInteger(pending.quorumSize)||pending.quorumSize<0||pending.quorumSize>5)||pending.verdict===void 0!==(pending.quorumSize===void 0)||!pendingMatchesParent(state,pending))throw new CouncilRoundStateUncertainError("pending council state is invalid")}return state}function parseAuditRecord(line,expectedScope){try{let record3=JSON.parse(line);if(record3.version!==VERSION||!["received","finalized","recovered"].includes(record3.event)||!isUuid2(record3.attemptId)||typeof record3.timestamp!=="string"||record3.timestamp.length>40||!Number.isFinite(Date.parse(record3.timestamp))||!sameAuditScope(record3.scope,expectedScope)||record3.clientRound!==void 0&&!isRound(record3.clientRound)||!isRound(record3.authoritativeRound)||!isDigest(record3.digest)||record3.sessionHash!==void 0&&!isDigest(record3.sessionHash)||!isDisposition(record3.disposition)||!Number.isInteger(record3.verdictCount)||record3.verdictCount<0||record3.verdictCount>5||!Array.isArray(record3.members)||record3.members.length>5||record3.members.some((member)=>typeof member!=="string"||member.length===0||member.length>32)||new Set(record3.members).size!==record3.members.length)throw Error("invalid");if(record3.event==="received"){if(record3.disposition!=="received"||record3.transition!==void 0||record3.gateEffect!==void 0||record3.nextState!==void 0||record3.evidenceRef!==void 0)throw Error("invalid")}else if(!isTransition(record3.transition)||!isGateEffect(record3.gateEffect)||!isSnapshot(record3.nextState)||record3.nextState.lastAttemptId!==record3.attemptId||record3.nextState.lastDigest!==record3.digest||!auditTransitionIsConsistent(record3))throw Error("invalid");if(record3.verdict!==void 0&&!isVerdict(record3.verdict))throw Error("invalid");if(record3.quorumSize!==void 0&&(!Number.isInteger(record3.quorumSize)||record3.quorumSize<0||record3.quorumSize>5))throw Error("invalid");if(record3.verdict===void 0!==(record3.quorumSize===void 0))throw Error("invalid");if(record3.evidenceRef!==void 0&&!isEvidenceRef(record3.evidenceRef))throw Error("invalid");return record3}catch{throw new CouncilRoundStateUncertainError("council attempt audit is corrupt")}}function appendAudit2(path254,record3){mkdirSync65(dirname103(path254),{recursive:!0});let descriptor=openSync21(path254,"a");try{writeSync2(descriptor,`${JSON.stringify(record3)}
|
|
6435
6437
|
`,void 0,"utf8"),fsyncSync7(descriptor)}finally{closeSync21(descriptor)}}function readAuditTail(path254,scope){if(!existsSync130(path254))return{records:[],truncated:!1};let size=statSync53(path254).size;if(size===0)return{records:[],truncated:!1};let offset=Math.max(0,size-MAX_AUDIT_TAIL),length=size-offset,descriptor=openSync21(path254,"r"),buffer=Buffer.alloc(length);try{readSync14(descriptor,buffer,0,length,offset)}finally{closeSync21(descriptor)}let text=buffer.toString("utf8");if(!text.endsWith(`
|
|
6436
6438
|
`))throw new CouncilRoundStateUncertainError("council attempt audit has a partial tail");if(offset>0){let firstNewline=text.indexOf(`
|
|
@@ -6453,7 +6455,7 @@ ${memberLines}`,`**Rounds:** ${roundsCompleted}`,"","### Consensus",consensusBlo
|
|
|
6453
6455
|
`);for(let line of contractDiffLines){for(let pattern of CONTRACT_PATTERNS)if(pattern.test(line)){hasContractChanges2=!0;break}if(hasContractChanges2)break}}catch{hasContractChanges2=!0}let result2={files,contractChanges:[],hasContractChanges:hasContractChanges2,summary:`${files.length} files changed (summary only)`};return JSON.stringify(result2,null,2)}let fullDiffOutput=child_process12.execFileSync("git",fullDiffArgs,{encoding:"utf-8",timeout:DIFF_TIMEOUT_MS,maxBuffer:MAX_BUFFER_BYTES,cwd:directory,stdio:["ignore","pipe","pipe"]}),contractChanges=[],diffLines=fullDiffOutput.split(`
|
|
6454
6456
|
`),currentFile="";for(let line of diffLines){let gitLineMatch=line.match(/^diff --git.* b\/(.+)$/);if(gitLineMatch)currentFile=gitLineMatch[1];for(let pattern of CONTRACT_PATTERNS)if(pattern.test(line)){let trimmed=line.trim();if(currentFile)contractChanges.push(`[${currentFile}] ${trimmed}`);else contractChanges.push(trimmed);break}}let hasContractChanges=contractChanges.length>0,fileCount=files.length,astDiffs=[],filesForAST=files.slice(0,MAX_AST_FILES);for(let file3 of filesForAST)try{let oldContent,newContent;if(base==="staged"){let oldRef=`HEAD:${file3.path}`;oldContent=fileExistsInRef(oldRef)?getContentFromRef(oldRef):"",newContent=getContentFromRef(`:${file3.path}`)}else if(base==="unstaged"){let oldRef=`:${file3.path}`;oldContent=fileExistsInRef(oldRef)?getContentFromRef(oldRef):"",newContent=fs146.readFileSync(path256.join(directory,file3.path),"utf-8")}else{let oldRef=`${base}:${file3.path}`;oldContent=fileExistsInRef(oldRef)?getContentFromRef(oldRef):"",newContent=getContentFromRef(`HEAD:${file3.path}`)}let astResult=await computeASTDiff(file3.path,oldContent,newContent);if(astResult&&(astResult.changes.length>0||astResult.error))astDiffs.push(astResult)}catch(e){if(e&&typeof e==="object"&&"code"in e){if(e.code==="ENOENT")throw e}astDiffs.push({filePath:file3.path,language:null,changes:[{type:"modified",category:"other",name:"(parse failed)",lineStart:0,lineEnd:0}],durationMs:0,usedAST:!1,error:"AST parse unavailable — tree-sitter analysis failed for this file"})}let semanticSummary;if(astDiffs.length>0)try{let classifiedChanges=classifyChanges(astDiffs);semanticSummary=generateSummary(classifiedChanges)}catch{}let markdownSummary;if(semanticSummary)try{markdownSummary=generateSummaryMarkdown(semanticSummary)}catch{}let astSkippedCount=files.length>MAX_AST_FILES?files.length-MAX_AST_FILES:0,summary=diffLines.length>MAX_DIFF_LINES?`${fileCount} files changed. Contract changes: ${hasContractChanges?"YES":"NO"}. (truncated to ${MAX_DIFF_LINES} lines)`:`${fileCount} files changed. Contract changes: ${hasContractChanges?"YES":"NO"}`,result={files,contractChanges,hasContractChanges,summary,...astDiffs.length>0?{astDiffs}:{},...semanticSummary?{semanticSummary}:{},...markdownSummary?{markdownSummary}:{},...astSkippedCount>0?{astSkippedCount}:{}};return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`git diff failed: ${e.message}`:"git diff failed: unknown error",files:[],contractChanges:[],hasContractChanges:!1};return JSON.stringify(errorResult,null,2)}}});init_zod();init_ast_diff();init_semantic_classifier();import*as child_process13 from"node:child_process";import*as fs147 from"node:fs";import*as path257 from"node:path";init_git_binary_missing_error();init_create_tool();init_resolve_working_directory();async function execGit2(workingDir,args2,options){try{return await new Promise((resolve106,reject2)=>{let execOpts={encoding:"utf-8",cwd:workingDir,timeout:options?.timeout,maxBuffer:options?.maxBuffer,stdio:["ignore","pipe","pipe"]};child_process13.execFile("git",args2,execOpts,(error93,output,_stderr)=>{if(error93){reject2(error93);return}resolve106(output??"")})})}catch(err){if(isGitBinaryMissing(err))throw new GitBinaryMissingError("git binary is not available",{cause:err});throw err}}var diff_summary=createSwarmTool({description:"Generate a filtered semantic diff summary from AST analysis. Returns SemanticDiffSummary with optional filtering by classification or riskLevel.",args:{files:exports_external.array(exports_external.string()).describe("Array of file paths to analyze"),classification:exports_external.string().optional().describe("Filter results to only this ChangeCategory"),riskLevel:exports_external.string().optional().describe("Filter results to only this RiskLevel")},async execute(args2,directory,_ctx){let typedArgs=args2;try{if(!typedArgs.files||!Array.isArray(typedArgs.files)||typedArgs.files.length===0)return JSON.stringify({error:"files must be a non-empty array of file paths",success:!1},null,2);let resolved=resolveWorkingDirectory(void 0,directory);if(!resolved.success)return JSON.stringify({success:!1,error:resolved.message},null,2);let workingDir=resolved.directory,astDiffs=[];for(let filePath of typedArgs.files){let astResult=null,fileExistsInHead=!1;try{await execGit2(workingDir,["cat-file","-e",`HEAD:${filePath}`],{timeout:3000}),fileExistsInHead=!0}catch(e){if(e instanceof GitBinaryMissingError)throw e}try{let oldContent,newContent=await fs147.promises.readFile(path257.join(workingDir,filePath),"utf-8");if(fileExistsInHead)oldContent=await execGit2(workingDir,["show",`HEAD:${filePath}`],{timeout:5000,maxBuffer:5242880});else oldContent="";astResult=await computeASTDiff(filePath,oldContent,newContent)}catch(e){if(e instanceof GitBinaryMissingError)throw e;astResult=null}if(astResult&&(astResult.changes.length>0||astResult.error!==void 0))astDiffs.push(astResult)}let filteredChanges=classifyChanges(astDiffs);if(typedArgs.classification)filteredChanges=filteredChanges.filter((change)=>change.category===typedArgs.classification);if(typedArgs.riskLevel)filteredChanges=filteredChanges.filter((change)=>change.riskLevel===typedArgs.riskLevel);let summary=generateSummary(filteredChanges);return JSON.stringify(summary,null,2)}catch(e){let errorResult={error:e instanceof Error?`diff_summary failed: ${e.message}`:"diff_summary failed: unknown error",success:!1};return JSON.stringify(errorResult,null,2)}}});init_p_limit();init_zod();init_candidate_contract();import{createHash as createHash51}from"node:crypto";init_lane_output_store();import*as fs148 from"node:fs";import*as path258 from"node:path";var LANE_DELIVERY_CACHE_FILENAME="lane-delivery-cache.json",MAX_DELIVERED_LANE_OUTPUT_KEYS=1024,MAX_TRACKED_SESSIONS10=16,MAX_TRACKED_DIRECTORIES=16,CORRUPT_SUFFIX=".corrupt",directoryBuckets=new Map;function bucketKey(directory){return directory?path258.normalize(path258.resolve(directory)):""}function emptyBucket(){return{order:[],sessions:new Map,total:0}}function cacheFilePath(directory){return path258.join(directory,".swarm",LANE_DELIVERY_CACHE_FILENAME)}function isValidCacheFile(value){if(!value||typeof value!=="object"||value.version!==1)return!1;let{order,sessions}=value;if(!Array.isArray(order)||order.some((id)=>typeof id!=="string"))return!1;if(!sessions||typeof sessions!=="object")return!1;return Object.values(sessions).every((keys)=>Array.isArray(keys)&&keys.every((key)=>typeof key==="string"))}function loadBucketFromDisk(directory){let file3=cacheFilePath(directory),raw;try{raw=fs148.readFileSync(file3,"utf-8")}catch{return emptyBucket()}let parsed;try{parsed=JSON.parse(raw)}catch{parsed=null}if(!isValidCacheFile(parsed)){try{let corruptPath=`${file3}${CORRUPT_SUFFIX}`,lastRenameError;for(let attempt=0;attempt<3;attempt++)try{fs148.renameSync(file3,corruptPath),lastRenameError=void 0;break}catch(err){lastRenameError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break}if(lastRenameError)throw lastRenameError}catch{}return emptyBucket()}let bucket=emptyBucket(),seen=new Set;for(let sessionID of parsed.order){if(seen.has(sessionID))continue;let keys=parsed.sessions[sessionID];if(!keys||keys.length===0)continue;seen.add(sessionID),bucket.order.push(sessionID),bucket.sessions.set(sessionID,[...keys]),bucket.total+=keys.length}return bucket}function persistBucket(directory,bucket){let file3={version:1,order:bucket.order,sessions:Object.fromEntries(bucket.sessions)};try{writeAtomicJson(cacheFilePath(directory),file3)}catch{}}function evictOverflow(bucket){while(bucket.total>MAX_DELIVERED_LANE_OUTPUT_KEYS){let evicted=!1;for(let sessionID of bucket.order){let keys=bucket.sessions.get(sessionID);if(!keys||keys.length===0)continue;if(keys.shift(),bucket.total-=1,keys.length===0)bucket.sessions.delete(sessionID),bucket.order=bucket.order.filter((id)=>id!==sessionID);evicted=!0;break}if(!evicted)break}}function bucketFor(directory){let key=bucketKey(directory),existing=directoryBuckets.get(key);if(existing)return existing;while(directoryBuckets.size>=MAX_TRACKED_DIRECTORIES){let oldestDirectory=directoryBuckets.keys().next().value;if(oldestDirectory===void 0)break;directoryBuckets.delete(oldestDirectory)}let bucket=directory?loadBucketFromDisk(directory):emptyBucket();return directoryBuckets.set(key,bucket),bucket}function sessionKeys(bucket,sessionID){let key=sessionID??"",keys=bucket.sessions.get(key);if(!keys){while(bucket.order.length>=MAX_TRACKED_SESSIONS10){let oldest=bucket.order.shift();if(oldest===void 0)break;let oldestKeys=bucket.sessions.get(oldest);bucket.sessions.delete(oldest),bucket.total-=oldestKeys?.length??0}keys=[],bucket.sessions.set(key,keys),bucket.order.push(key)}return keys}function hasLaneOutputBeenDelivered(directory,sessionID,key){if(!key)return!1;return bucketFor(directory).sessions.get(sessionID??"")?.includes(key)??!1}function markLaneOutputDelivered(directory,sessionID,key){if(!key)return;let bucket=bucketFor(directory),keys=sessionKeys(bucket,sessionID);if(keys.includes(key))return;if(keys.push(key),bucket.total+=1,evictOverflow(bucket),directory)persistBucket(directory,bucket)}init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_pr_workflow_gate();init_p_limit();function createParallelDispatcher(config3){let limit=pLimit(config3.maxConcurrentTasks),activeSlots=new Map,slotCounter=0,shutdownCalled=!1;return{config:config3,dispatch(taskId){if(!config3.enabled)return{action:"reject",reason:"dispatcher_disabled"};if(shutdownCalled)return{action:"reject",reason:"dispatcher_shutdown"};if(activeSlots.size>=config3.maxConcurrentTasks)return{action:"defer",reason:"max_concurrent_tasks_reached"};let slotId=`slot-${++slotCounter}`,runId=`run-${taskId}-${slotId}`,slot={slotId,taskId,runId,startedAt:Date.now()};return activeSlots.set(slotId,slot),limit(async()=>{}),{action:"dispatch",reason:"slot_available",slot}},handles(){return[...activeSlots.values()].map((slot)=>({slotId:slot.slotId,taskId:slot.taskId,runId:slot.runId,cancel:()=>{activeSlots.delete(slot.slotId)}}))},releaseSlot(slotId){activeSlots.delete(slotId)},shutdown(){shutdownCalled=!0,activeSlots.clear(),limit.clearQueue()}}}init_state2();init_ephemeral_session_teardown();init_logger();init_create_tool();var MAX_LANES=8,MAX_PROMPT_CHARS=80000,COMMON_PROMPT_SEPARATOR=`
|
|
6455
6457
|
|
|
6456
|
-
`,DEFAULT_TIMEOUT_MS5=300000,DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS=30000,MAX_TIMEOUT_MS4=1800000,MAX_LANE_OUTPUT_CHARS=20000,ASYNC_MESSAGE_FETCH_LIMIT=50,MAX_ERROR_CHARS=200,ERROR_TRUNCATION_SUFFIX="...",MAX_BATCH_ID_CHARS=120,DEFAULT_ASYNC_STALE_TIMEOUT_MS=
|
|
6458
|
+
`,DEFAULT_TIMEOUT_MS5=300000,DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS=30000,MAX_TIMEOUT_MS4=1800000,MAX_LANE_OUTPUT_CHARS=20000,ASYNC_MESSAGE_FETCH_LIMIT=50,MAX_ERROR_CHARS=200,ERROR_TRUNCATION_SUFFIX="...",MAX_BATCH_ID_CHARS=120,DEFAULT_ASYNC_STALE_TIMEOUT_MS=DEFAULT_STALE_DELEGATION_TIMEOUT_MS,DEFAULT_COLLECT_TIMEOUT_MS=DEFAULT_ASYNC_STALE_TIMEOUT_MS,MAX_COLLECT_TIMEOUT_MS=3600000,COLLECT_POLL_INTERVAL_MS=500,MAX_COLLECT_POLL_INTERVAL_MS=1e4,MAX_ZOD_ISSUES_LISTED=20,MAX_SESSION_CREATE_GENERATIONS=2,MAX_CREATE_FAILURE_WALK_NODES=64,MAX_CREATE_FAILURE_WALK_DEPTH=6,MAX_CREATE_FAILURE_SIGNAL_CHARS=8192,TRANSIENT_CREATE_STATUS_CODES=new Set([408,429,500,502,503,504,529]),TRANSIENT_CREATE_SIGNAL_PATTERN=/\b(?:408|429|500|502|503|504|529)\b|rate.?limit|timeout|timed.?out|overloaded|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(?:refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,PERMANENT_CREATE_SIGNAL_PATTERN=/authentication|unauthori[sz]ed|forbidden|invalid[_\s-]?(?:api[_\s-]?key|token|credential|configuration|config|agent|model)|unknown[_\s-]?(?:agent|model)|unsupported[_\s-]?(?:agent|model)|model.?not.?found|agent.?not.?found|permission.?denied|access.?denied|quota|usage.?limit|insufficient.?(?:quota|credits?)|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i,PERMANENT_CREATE_STATUS_CODES=new Set([400,401,402,403,404,405,409,410,413,422]),CREATE_FAILURE_FIELD_KEYS=["status","statusCode","status_code","httpStatus","http_status","code","errorCode","error_code","message","detail","reason","cause","error","response","data","body","details","errors","isRetryable","retryable"],CREATE_FAILURE_SCALAR_KEYS=new Set(CREATE_FAILURE_FIELD_KEYS),CREATE_FAILURE_STATUS_KEYS=new Set(["status","statusCode","status_code","httpStatus","http_status","code","errorCode","error_code","response"]),AGENT_NAME_SEPARATORS=["_","-"," "];function boundZodIssues(issues){let formatted=issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`);if(formatted.length<=MAX_ZOD_ISSUES_LISTED)return formatted;let shown=formatted.slice(0,MAX_ZOD_ISSUES_LISTED);return shown.push(`... and ${formatted.length-MAX_ZOD_ISSUES_LISTED} more`),shown}var PR_WORKFLOW_LANE_CHECKLISTS={"intent-architecture":"obligations, claimed versus actual behavior, design fit, callers, consumers, sibling patterns, and documentation","correctness-state":"control flow, boundary conditions, error paths, invariants, state transitions, persistence, and rollback behavior","tests-falsifiability":"assertion strength, negative paths, fixtures and mocks, isolation, CI behavior, and falsification probes","security-trust":"authentication, authorization, untrusted inputs, secrets, injection sinks, privilege, and write authority","reliability-performance":"timeouts, retries, concurrency, cleanup, resource bounds, failure recovery, and performance regressions","compatibility-delivery":"public contracts, schemas, migrations, platform portability, dependencies, packaging, deployment, and release behavior","auth-identity-secrets":"identity, session, permission, authentication, authorization, secret, and cryptographic boundaries","untrusted-input-boundaries":"parsing, serialization, query, template, filesystem, and network sources through every reachable sink","subprocess-platform":"array-form execution, cwd, stdin, timeout, output bounds, kill paths, quoting, and OS/runtime portability","concurrency-state":"locks, queues, caches, transactions, retries, races, session isolation, eviction, and state-machine transitions","dependencies-build-release":"manifests, lockfiles, installers, build scripts, CI, artifacts, provenance, packaging, deployment, and release hygiene","api-schema-migrations":"public APIs, wire/config/storage schemas, compatibility, defaults, migrations, flags, and rollback paths","test-infrastructure":"test validity, isolation, mock leakage, fixtures, harnesses, coverage claims, and CI matrices","ui-accessibility-i18n":"user interaction, rendering, keyboard and screen-reader access, focus, localization, and error states","privacy-observability":"logs, telemetry, analytics, traces, diagnostics, retention, redaction, and sensitive-data exposure","generated-provenance":"generated, vendored, binary, model-produced, codegen, and checked-in artifact source and reproducibility","unclassified-risk":"every changed artifact or behavior not fully covered by another lane, with conservative escalation of ambiguity","stage-b-reviewer":"every feedback item against the exact diff, fix correctness, adjacent regressions, repository contracts, and evidence quality","stage-b-test":"every feedback item with independent targeted negative-path and regression probes on the Stage-A-bound revision","closeout-reviewer":"the complete feedback inventory, final diff, tests, docs, release artifacts, scope, and unresolved risk","closeout-critic":"challenge the closeout evidence, omissions, false confidence, severity, scope, and publication readiness"},EXPLORER_CANDIDATE_COMMON_RULES=`
|
|
6457
6459
|
|
|
6458
6460
|
IMPORTANT — OUTPUT FORMAT REQUIREMENT:
|
|
6459
6461
|
You MUST emit findings as a pipe-delimited [CANDIDATE] table. The FIRST
|
|
@@ -6597,7 +6599,7 @@ Advisory notes: ${advisoryNotes.join("; ")}`:"";return{blocked:!0,reason:"PHASE_
|
|
|
6597
6599
|
${jsdocContent}`;else if(line.includes("*/"))break;else if(functionKeywords.test(line)||line.startsWith("function ")){_foundFunction=!0;break}else if(line.length>0&&!line.startsWith("//")&&!line.startsWith("*"))break}if(jsdocContent){if(/@returns\s*(?:\{[^}]*\})?\s*(?:undefined|[A-Za-z_]\w*)/i.test(jsdocContent))return!0}let braceCount=0,inFunction=!1;for(let i=currentLineIdx;i>=0;i--){let line=lines[i];for(let char of line)if(char==="{")braceCount++,inFunction=!0;else if(char==="}")braceCount--;if(inFunction&&braceCount===0&&i<currentLineIdx)break}let errorReturnPattern=/return\s+["'`][[:ascii:]]*["'`]\s*;/;for(let i=currentLineIdx-1;i>=0&&i>=currentLineIdx-MAX_SEARCH_LINES;i--){let line=lines[i].trim();if(functionKeywords.test(line)||line.startsWith("function "))break;if(errorReturnPattern.test(line))return!0}return!1}function scanWithRegex(content,filePath,denyPatterns,addedLines){let findings=[],lines=content.split(`
|
|
6598
6600
|
`),filterByAddedLines=addedLines!==void 0;for(let i=0;i<lines.length;i++){let line=lines[i],lineNumber=i+1;if(filterByAddedLines&&!addedLines.has(lineNumber))continue;let lineCommentMatch=line.match(/(?:\/\/|#|<!--)\s*(.*)$/);if(lineCommentMatch){let commentText=lineCommentMatch[1];for(let{pattern,rule_id}of denyPatterns.comment)if(pattern.test(commentText)){findings.push({path:filePath,line:lineNumber,kind:"comment",excerpt:line.substring(0,100),rule_id});break}}let blockCommentMatch=line.match(/\/\*([\s\S]*?)\*\//);if(blockCommentMatch){let commentText=blockCommentMatch[1];for(let{pattern,rule_id}of denyPatterns.comment)if(pattern.test(commentText)){findings.push({path:filePath,line:lineNumber,kind:"comment",excerpt:line.substring(0,100),rule_id});break}}let stringMatches=line.match(/(["'`])(?:(?!\1)[^\\]|\\.)*\1/g);if(stringMatches){for(let stringContent of stringMatches)for(let{pattern,rule_id}of denyPatterns.string)if(pattern.test(stringContent)){findings.push({path:filePath,line:lineNumber,kind:"string",excerpt:line.substring(0,100),rule_id});break}}for(let{pattern,rule_id}of denyPatterns.code)if(!(line.includes("describe(")||line.includes("it(")||line.includes("test(")||line.includes("expect("))&&pattern.test(line)){if(rule_id==="placeholder/code-stub-return"&&/return\s+undefined\s*;/.test(line)){if(isValidationPattern(lines,i))continue}findings.push({path:filePath,line:lineNumber,kind:"function_body",excerpt:line.substring(0,100),rule_id})}}return findings}async function scanWithParser(content,filePath,denyPatterns,addedLines){let findings=[],regexFindings=scanWithRegex(content,filePath,denyPatterns,addedLines);findings.push(...regexFindings);let parser=await getParserForFile(filePath);if(!parser)return findings;try{let walkNode=function(node){let{type:nodeType,text:nodeText}=node,lineNum=node.startPosition.row+1;if(filterByAddedLines?addedLines.has(lineNum):!0){if(nodeType==="comment"||nodeType==="line_comment"||nodeType==="block_comment"||nodeType==="documentation_comment"||nodeType==="doc_comment")for(let{pattern,rule_id}of denyPatterns.comment){let key=`${lineNum}:${rule_id}`;if(!seenKeys.has(key)&&pattern.test(nodeText))seenKeys.add(key),findings.push({path:filePath,line:lineNum,kind:"comment",excerpt:nodeText.substring(0,100),rule_id})}if(nodeType==="string"||nodeType==="template_string"||nodeType==="string_literal"||nodeType==="string_fragment")for(let{pattern,rule_id}of denyPatterns.string){let key=`${lineNum}:${rule_id}`;if(!seenKeys.has(key)&&pattern.test(nodeText))seenKeys.add(key),findings.push({path:filePath,line:lineNum,kind:"string",excerpt:nodeText.substring(0,100),rule_id})}}if(node.children)for(let child of node.children)walkNode(child)},tree=parser.parse(content);if(!tree||!tree.rootNode)return findings;let seenKeys=new Set;for(let f of findings)seenKeys.add(`${f.line}:${f.rule_id}`);let filterByAddedLines=addedLines!==void 0;walkNode(tree.rootNode),tree.delete()}catch{}return findings}async function placeholderScan(input,directory){let{changed_files,allow_globs,deny_patterns,added_lines,sentinel_allowlist,allow_sentinels}=input,sentinelPatterns=[...DEFAULT_SENTINEL_ALLOWLIST,...sentinel_allowlist??allow_sentinels??[]].map((sentinel)=>new RegExp(escapeRegex2(sentinel),"i"));function isSentinelAllowed(excerpt){for(let pattern of sentinelPatterns)if(pattern.test(excerpt))return!0;return!1}let commentPatterns=DEFAULT_COMMENT_PATTERNS,stringPatterns=DEFAULT_STRING_PATTERNS,codePatterns=DEFAULT_CODE_PATTERNS;if(deny_patterns&&deny_patterns.length>0)commentPatterns=deny_patterns.map((p)=>({pattern:new RegExp(`\\b${escapeRegex2(p)}\\b`,"i"),rule_id:`placeholder/custom-${p.toLowerCase()}`})),stringPatterns=[],codePatterns=[];let denyPatterns={comment:commentPatterns,string:stringPatterns,code:codePatterns},findings=[],filesScanned=0,filesWithFindings=new Set;for(let filePath of changed_files){let fullPath=path283.isAbsolute(filePath)?filePath:path283.resolve(directory,filePath),resolvedDirectory=path283.resolve(directory);if(!fullPath.startsWith(resolvedDirectory+path283.sep)&&fullPath!==resolvedDirectory)continue;if(!fs170.existsSync(fullPath))continue;if(isAllowedByGlobs(filePath,allow_globs))continue;let relativeFilePath=path283.relative(directory,fullPath).replace(/\\/g,"/");if(FILE_ALLOWLIST.some((allowed)=>relativeFilePath.endsWith(allowed)))continue;let content;try{if(fs170.statSync(fullPath).size>MAX_FILE_SIZE)continue;content=fs170.readFileSync(fullPath,"utf-8")}catch{continue}if(content.includes("\x00"))continue;let isScaffold=isScaffoldFile(filePath);if(isTestFile2(filePath)&&!isScaffold)continue;filesScanned++;let addedLinesForFile=normalizeAddedLines(added_lines?.[relativeFilePath]??added_lines?.[filePath]),fileFindings;if(isPlanFile(filePath))fileFindings=scanPlanFileForPlaceholders(content,filePath,addedLinesForFile);else if(isParserSupported(filePath))fileFindings=await scanWithParser(content,filePath,denyPatterns,addedLinesForFile);else fileFindings=scanWithRegex(content,filePath,denyPatterns,addedLinesForFile);let filteredFindings=sentinelPatterns.length>0?fileFindings.filter((f)=>!isSentinelAllowed(f.excerpt)):fileFindings;if(filteredFindings.length>0)findings.push(...filteredFindings),filesWithFindings.add(filePath)}let verdict=findings.length>0?"fail":"pass";return await saveEvidence(directory,"placeholder_scan",{task_id:"placeholder_scan",type:"placeholder",timestamp:new Date().toISOString(),agent:"placeholder_scan",verdict,summary:`Scanned ${filesScanned} files, found ${findings.length} placeholder(s)`,files_scanned:filesScanned,findings_count:findings.length,files_with_findings:filesWithFindings.size,findings}),{verdict,findings,summary:{files_scanned:filesScanned,findings_count:findings.length,files_with_findings:filesWithFindings.size}}}var placeholder_scan=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Scan source files for placeholder content (TODO/FIXME comments, stub implementations, unimplemented functions). Returns JSON with findings grouped by file and rule.",args:{changed_files:exports_external.array(exports_external.string()).describe("Files to scan for placeholders"),allow_globs:exports_external.array(exports_external.string()).optional().describe("Globs to allow (skip scanning)"),deny_patterns:exports_external.array(exports_external.string()).optional().describe("Custom deny patterns to search for"),added_lines:exports_external.record(exports_external.string(),exports_external.array(exports_external.number().int().positive())).optional().describe("Optional map of file path to PR-added line numbers"),sentinel_allowlist:exports_external.array(exports_external.string()).optional().describe("Intentional sentinel strings that suppress matching findings"),allow_sentinels:exports_external.array(exports_external.string()).optional().describe("Deprecated alias for sentinel_allowlist")},async execute(args2,directory){let result=await placeholderScan(args2,directory);return JSON.stringify(result)}});init_zod();init_manager();init_parallel_verdict();init_cochange_source();init_create_tool();var plan_conflict_check_args={task_ids:exports_external.array(exports_external.string().min(1)).min(2,"plan_conflict_check requires at least 2 task ids to compare").max(MAX_PARALLEL_VERDICT_TASKS,`plan_conflict_check accepts at most ${MAX_PARALLEL_VERDICT_TASKS} task ids`).describe('The N proposed parallel task group ids (e.g. ["4.1","4.2","4.3"]). '+"Minimum 2 — fewer than 2 tasks cannot conflict."),use_cochange:exports_external.boolean().optional().describe("When true, fold git co-change signal (from `git log`) into the verdict. "+'Off by default — the path-only verdict is sufficient for the v8 "provably '+'disjoint" gate. Opt in for richer signal on tightly-coupled codebases.'),phase_id:exports_external.string().optional().describe("Optional: scope the check to a phase. Currently informational — task_ids "+"are checked as-is regardless of phase. Reserved for future validation.")};async function executePlanConflictCheck(args2,directory){let useCochange=args2.use_cochange===!0,planLoaded=!1,knownTaskIds=new Set;try{let plan=await loadPlanJsonOnly(directory);if(plan){planLoaded=!0;for(let phase of plan.phases)for(let task2 of phase.tasks)knownTaskIds.add(task2.id)}}catch{planLoaded=!1}let requestedIds=args2.task_ids,unknownToPlan=planLoaded?requestedIds.filter((id)=>!knownTaskIds.has(id)):[],cochangePairs;if(useCochange)try{cochangePairs=await getCoChangePairs(directory)}catch{cochangePairs=void 0}let verdict=computeParallelVerdict(directory,requestedIds,{useCochange,cochangePairs});return{verdict:verdict.verdict,pairs:verdict.pairs,suggested_serial_order:verdict.suggestedSerialOrder,unknown_scope_tasks:verdict.unknownScopeTasks,used_cochange:useCochange&&cochangePairs!==void 0&&cochangePairs.length>0,plan_loaded:planLoaded,...unknownToPlan.length>0?{unknown_to_plan:unknownToPlan}:{}}}var plan_conflict_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes (`.swarm/scopes/scope-<taskId>.json`) and optional git co-change signal. Returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization "+"order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via "+"the same helper. Use this BEFORE attempting parallel dispatch to confirm disjointness.",args:plan_conflict_check_args,execute:async(args2,directory)=>{let result=await executePlanConflictCheck(args2,directory);return JSON.stringify(result,null,2)}});init_workspace_snapshot();init_pr_workflow_state();init_pr_workflow_gate();init_utils2();init_bun_compat();init_create_tool();import*as fsp8 from"node:fs/promises";import*as path284 from"node:path";var GIT_TIMEOUT_MS10=5000,GIT_MAX_STDOUT_BYTES=524288,MAX_DIRTY_FILES=50,MAX_REMOTES=20,MAX_REMOTE_URL_LEN=200,MAX_FIELD_LEN=240,RECEIPT_DIR2="pr-workflow-checkouts",utf8Encoder=new TextEncoder,utf8Decoder=new TextDecoder("utf-8",{fatal:!1});function truncateToByteBudget(value,maxBytes){let encoded=utf8Encoder.encode(value);if(encoded.length<=maxBytes)return value;return utf8Decoder.decode(encoded.subarray(0,maxBytes))}function boundUntrusted(value,maxLen){let cleaned=value.replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim();return cleaned.length>maxLen?`${cleaned.slice(0,maxLen)}…`:cleaned}async function runGitCapture2(directory,args2){let proc=bunSpawn(["git",...args2],{cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:GIT_TIMEOUT_MS10});try{let[exitCode,stdout]=await Promise.all([proc.exited,proc.stdout.text()]);if(exitCode!==0)return null;return truncateToByteBudget(stdout,GIT_MAX_STDOUT_BYTES)}catch{return null}finally{try{proc.kill()}catch{}}}async function resolveBranch(directory){let raw=await _internals215.runGitCapture(directory,["rev-parse","--abbrev-ref","HEAD"]);if(raw===null)return{branch:null,detached:null};let value=raw.trim();if(!value||value==="HEAD")return{branch:null,detached:!0};return{branch:boundUntrusted(value,MAX_FIELD_LEN),detached:!1}}function parseDirtyFiles(porcelain){if(!porcelain)return{dirtyFiles:[],dirtyFileCount:0,dirtyFilesTruncated:!1};let lines=porcelain.split(`
|
|
6599
6601
|
`).filter((line)=>line.length>=4),dirtyFiles=[];for(let line of lines){if(dirtyFiles.length>=MAX_DIRTY_FILES)break;let status=line.slice(0,2).trim()||"??",rawPath=line.slice(3);dirtyFiles.push({status:boundUntrusted(status,4),path:boundUntrusted(rawPath,MAX_FIELD_LEN)})}return{dirtyFiles,dirtyFileCount:lines.length,dirtyFilesTruncated:lines.length>dirtyFiles.length}}function parseRemotes(remoteOutput){if(!remoteOutput)return{remotes:[],remotesTruncated:!1};let byName=new Map;for(let line of remoteOutput.split(`
|
|
6600
|
-
`)){let trimmed=line.trim();if(!trimmed)continue;let[name,rest]=trimmed.split(/\s+/,2);if(!name||!rest||byName.has(name))continue;let url3=rest.replace(/\s+\((?:fetch|push)\)\s*$/i,"");byName.set(boundUntrusted(name,64),boundUntrusted(url3,MAX_REMOTE_URL_LEN))}let entries=[...byName.entries()],remotes=entries.slice(0,MAX_REMOTES).map(([name,url3])=>({name,url:url3}));return{remotes,remotesTruncated:entries.length>remotes.length}}async function countCheckoutReceiptFiles(directory,sessionID){try{let receiptDirectory=validateSwarmPath(directory,path284.join(RECEIPT_DIR2,prWorkflowSessionFileStem(sessionID)));return(await fsp8.readdir(receiptDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&/^[0-9a-f]{40,64}\.json$/i.test(entry.name)).length}catch(error93){if(error93.code==="ENOENT")return 0;return null}}function describeNextStep(gate,git2,checkout){if(checkout.kind==="recovery-required"||checkout.kind==="indeterminate")return`Manual Git recovery required. code=${checkout.code} retryable=false required_action=${checkout.requiredAction}`;if(!gate.active)return"No active PR workflow gate for this session. Activate with `/swarm pr-review <pr-ref>` or `/swarm pr-feedback <pr-ref>` before PR-workflow tool calls are admitted.";if(!gate.prHeadBound)return gate.mode==="PR_FEEDBACK"?"PR_FEEDBACK gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes). Prefer the intended exact tracking checkout, then bind; if this workflow inherited an already-detached exact intake head, bind it directly and the controller will attach the unique exact local/remote tracking ref. Ambiguity or an existing mismatched upstream fails closed.":"PR_REVIEW gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes), then bind the exact detached PR head.";if(git2.isClean===!1)return`${gate.mode} gate active and head bound, but the working tree is dirty. Read-only observation only; the gate keeps writes and non-tracking fetches fail-closed.`;if(git2.isClean===null)return`${gate.mode} gate active and head bound, but this session could not determine whether the working tree is clean (git status failed). Treat the tree state as unknown and verify manually before assuming it is clean; read-only observation only.`;return`${gate.mode} gate active and head bound. Continue read-only review using the admitted observe/validate tools (diff, gh_evidence, repo_map, lint check, etc.).`}function summarizeGate(state,receiptFiles){if(!state)return{active:!1,reason:"no-active-gate"};return{active:!0,mode:state.mode,prHeadBound:Boolean(state.prHeadSha),prHeadSha:state.prHeadSha??null,prFeedbackTargetUrl:state.prFeedbackTargetUrl?boundUntrusted(state.prFeedbackTargetUrl,MAX_FIELD_LEN):null,prReviewBaseRef:state.prReviewBaseRef?boundUntrusted(state.prReviewBaseRef,MAX_FIELD_LEN):null,prReviewBaseSha:state.prReviewBaseSha??null,prReviewDepthTier:state.prReviewDepthTier??null,baseDispatchBatches:state.prReviewBaseDispatches?.length??0,validationBatches:state.prReviewValidationBatches?.length??0,feedbackVerificationBatches:state.prFeedbackVerifications?.length??0,checkoutReceiptFiles:receiptFiles,activatedAt:state.activatedAt,updatedAt:state.updatedAt,revision:state.revision}}async function executePrWorkflowStatus(directory,rawSessionID){let sessionID=rawSessionID?.trim()?rawSessionID.trim():null,[head2,isClean,branchInfo,porcelain,remoteOutput,liveCheckout]=await Promise.all([_internals215.resolveCurrentGitHeadAsync(directory),_internals215.resolveIsWorkingTreeCleanAsync(directory),resolveBranch(directory),_internals215.runGitCapture(directory,["status","--porcelain=v1","--untracked-files=all"]),_internals215.runGitCapture(directory,["remote","-v"]),_internals215.classifyGitState(directory)]),dirty=parseDirtyFiles(porcelain),{remotes,remotesTruncated}=parseRemotes(remoteOutput),git2={head:head2,branch:branchInfo.branch,detached:branchInfo.detached,isClean,dirtyFileCount:dirty.dirtyFileCount,dirtyFiles:dirty.dirtyFiles,dirtyFilesTruncated:dirty.dirtyFilesTruncated,remotes,remotesTruncated},gate,activeState=null;if(!sessionID)gate={active:!1,reason:"no-session-context"};else{activeState=await _internals215.readPrWorkflowGateState(directory,sessionID);let receiptFiles=activeState?await countCheckoutReceiptFiles(directory,sessionID):null;gate=summarizeGate(activeState,receiptFiles)}let recovery=activeState?.checkoutRecovery,checkout=recovery?{kind:recovery.code==="GIT_STATE_INDETERMINATE"?"indeterminate":"recovery-required",code:recovery.code,retryable:!1,requiredAction:recovery.requiredAction,evidence:recovery.evidence}:liveCheckout,result={success:!0,sessionID,git:git2,checkout,gate,nextStep:describeNextStep(gate,git2,checkout)};return JSON.stringify(result,null,2)}var pr_workflow_status=createSwarmTool({description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary (mode, bound PR head, base ref/sha, depth tier, dispatch/validation batch counts). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",args:{},execute:async(_args,directory,ctx)=>executePrWorkflowStatus(directory,ctx?.sessionID)}),_internals215={readPrWorkflowGateState,resolveCurrentGitHeadAsync,resolveIsWorkingTreeCleanAsync,runGitCapture:runGitCapture2,classifyGitState:classifyPrWorkflowGitState,truncateToByteBudget};init_p_limit();init_zod();init_manager2();init_utils();init_external_tool_runner();init_project_boundary();init_create_tool();init_lint();init_quality_budget();init_sast_scan();init_secretscan();import*as path285 from"node:path";var TOOL_TIMEOUT_MS=60000,MAX_COMBINED_BYTES=500000,MAX_COMPACT_ERROR_BYTES=4096,CANCELLATION_SETTLEMENT_GRACE_MS=1000,MAX_CONCURRENT=4,MAX_FILES=100,GIT_TIMEOUT_MS11=1e4,GIT_MAX_OUTPUT_BYTES=2000000,ALL_LINES_CHANGED=-1,MAX_CHANGED_LINE_ENTRIES=200000,_internals216={qualityBudget,runLintWrapped,runSecretscanWrapped,runSastScanWrapped,runQualityBudgetWrapped,runWithTimeout:runWithTimeout2,getChangedLineRanges,saveEvidence,runExternalTool,detectResolvedLinter,runLintOnFiles,platform:()=>process.platform,serializePreCheckResult,MAX_COMBINED_BYTES};function formatIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function evaluateSecretscanGate(toolResult,requestedFiles){if(toolResult.error)return{passed:!1,summary:`Secretscan wrapper error: ${toolResult.error}`,findingsCount:0};if(!toolResult.ran||!toolResult.result)return{passed:!1,summary:"Secretscan did not return a result",findingsCount:0};if("error"in toolResult.result)return{passed:!1,summary:`Secretscan error: ${toolResult.result.error}`,findingsCount:0};let result=toolResult.result;if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{passed:!1,summary:"Secretscan failed: scanner returned incomplete coverage metadata",result,findingsCount:Math.max(result.count,result.findings.length)};let findingsCount=Math.max(result.count,result.findings.length),failures=[];if(findingsCount>0)failures.push(`${findingsCount} secret finding(s)`);if(result.incomplete_files>0||result.incomplete_paths.length>0){let incompletePaths=result.incomplete_paths.length>0?`; incomplete paths: ${formatIncompletePaths(result.incomplete_paths)}`:"";failures.push(`${result.incomplete_files} incomplete file(s)${incompletePaths}`)}if(result.count!==result.findings.length)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(requestedFiles>0&&result.files_scanned===0)failures.push("zero requested files scanned");let statistics=`Secretscan: ${findingsCount} finding(s), ${result.files_scanned} files scanned, ${result.skipped_files} skipped`;return{passed:failures.length===0,summary:failures.length>0?`${statistics}; failed: ${failures.join("; ")}`:statistics,result,findingsCount}}function truncateUtf8(value,maxBytes){if(Buffer.byteLength(value,"utf8")<=maxBytes)return value;let marker="... (truncated)",budget=Math.max(0,maxBytes-Buffer.byteLength(marker,"utf8")),result="",usedBytes=0;for(let character of value){let characterBytes=Buffer.byteLength(character,"utf8");if(usedBytes+characterBytes>budget)break;result+=character,usedBytes+=characterBytes}return`${result}${marker}`}function compactToolResult(toolResult){return{ran:toolResult.ran,duration_ms:toolResult.duration_ms,...toolResult.error!==void 0&&{error:truncateUtf8(toolResult.error,MAX_COMPACT_ERROR_BYTES)},...toolResult.error===void 0&&toolResult.result!==void 0&&{result_omitted:!0}}}function serializePreCheckResult(result){let serialized3=JSON.stringify(result,null,2);if(Buffer.byteLength(serialized3,"utf8")<=MAX_COMBINED_BYTES)return serialized3;let compact={batch_status:result.batch_status,gates_passed:result.gates_passed,lint:compactToolResult(result.lint),secretscan:compactToolResult(result.secretscan),sast_scan:compactToolResult(result.sast_scan),quality_budget:compactToolResult(result.quality_budget),total_duration_ms:result.total_duration_ms,output_truncated:!0};return JSON.stringify(compact,null,2)}function isWindowsAbsolutePath(inputPath){return/^[A-Za-z]:[/\\]/.test(inputPath)}function validatePath(inputPath,baseDir,workspaceDir){if(typeof inputPath!=="string")return"path must be a string";if(!inputPath||inputPath.trim().length===0)return"path is required";let resolved,isWinAbs=isWindowsAbsolutePath(inputPath);if(isWinAbs)resolved=path285.win32.resolve(inputPath);else if(path285.isAbsolute(inputPath))resolved=path285.resolve(inputPath);else resolved=path285.resolve(baseDir,inputPath);let workspaceResolved=isWindowsAbsolutePath(workspaceDir)?path285.win32.resolve(workspaceDir):path285.resolve(workspaceDir),relative69;if(isWinAbs)relative69=path285.win32.relative(workspaceResolved,resolved);else relative69=path285.relative(workspaceResolved,resolved);if(relative69.startsWith(".."))return"path traversal detected";return null}function isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitBoundary){let pathApi=platform==="win32"?path285.win32:path285,directoryKey=pathApi.resolve(dir).replace(/\\/g,"/"),workspaceKey=pathApi.resolve(workspaceDir).replace(/\\/g,"/"),normalizedDirectoryKey=platform==="win32"?directoryKey.toLowerCase():directoryKey,normalizedWorkspaceKey=platform==="win32"?workspaceKey.toLowerCase():workspaceKey;if(normalizedDirectoryKey===normalizedWorkspaceKey)return!0;let relative69=pathApi.relative(workspaceDir,dir);return relative69!==""&&relative69!==".."&&!relative69.startsWith(`..${pathApi.sep}`)&&!pathApi.isAbsolute(relative69)&&hasExplicitBoundary}function validateDirectory2(dir,workspaceDir){if(!dir||dir.length===0)return"directory is required";if(dir.length>500)return"directory path too long";let traversalCheck=validatePath(dir,workspaceDir,workspaceDir);if(traversalCheck)return traversalCheck;let platform=_internals216.platform();if(!isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitProjectBoundary(dir)))return"directory must resolve to the project root";return null}async function runWithTimeout2(operation,timeoutMs,parentSignal,waitForCancellationSettlement=!1){let controller=new AbortController,timeoutHandle,parentAbortListener;if(parentSignal?.aborted)throw Error("Tool execution cancelled");let parentAbortPromise=new Promise((_,reject2)=>{if(!parentSignal)return;if(parentAbortListener=()=>{reject2(Error("Tool execution cancelled")),controller.abort()},parentSignal.addEventListener("abort",parentAbortListener,{once:!0}),parentSignal.aborted)parentAbortListener()});if(controller.signal.aborted)return await parentAbortPromise;let operationPromise=operation(controller.signal);try{let timeoutPromise=new Promise((_,reject2)=>{timeoutHandle=setTimeout(()=>{reject2(Error(`Timeout after ${timeoutMs}ms`)),controller.abort()},timeoutMs)});return await Promise.race([operationPromise,timeoutPromise,parentAbortPromise])}catch(error93){if(controller.signal.aborted&&waitForCancellationSettlement){let settlementTimer;try{await Promise.race([operationPromise.then(()=>{return},()=>{return}),new Promise((resolve117)=>{settlementTimer=setTimeout(resolve117,CANCELLATION_SETTLEMENT_GRACE_MS)})])}finally{if(settlementTimer!==void 0)clearTimeout(settlementTimer)}}throw error93}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(parentAbortListener&&parentSignal)parentSignal.removeEventListener("abort",parentAbortListener)}}async function runLintWrapped(files,directory,_config,abortSignal){let start=process.hrtime.bigint();try{let resolvedLinter=await _internals216.detectResolvedLinter(directory,abortSignal);if(!resolvedLinter)return{ran:!1,error:"No linter found (biome or eslint)",duration_ms:Number(process.hrtime.bigint()-start)/1e6};if(files&&files.length>0)return{ran:!0,result:await _internals216.runLintOnFiles(resolvedLinter,files,directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await _internals121.runResolvedLint(resolvedLinter,"check",directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runLintOnFiles(resolvedLinter,files,workspaceDir,abortSignal){if(resolvedLinter.source==="legacy-test-probe")return _internals121.runResolvedLint(resolvedLinter,"check",workspaceDir,abortSignal);let validatedFiles=[];for(let file3 of files){if(typeof file3!=="string")continue;let resolvedPath=path285.resolve(file3);if(validatePath(resolvedPath,workspaceDir,workspaceDir))continue;validatedFiles.push(resolvedPath)}if(validatedFiles.length===0)return{success:!1,mode:"check",linter:resolvedLinter.linter,command:[],error:"No valid files after security validation"};let args2;if(resolvedLinter.linter==="biome")args2=[...resolvedLinter.argsPrefix,"check",...validatedFiles];else args2=[...resolvedLinter.argsPrefix,...validatedFiles];let command=[...resolvedLinter.displayPrefix,...args2];try{let execution=await _internals216.runExternalTool({executable:resolvedLinter.executable,args:args2,cwd:workspaceDir,timeoutMs:TOOL_TIMEOUT_MS,maxStdoutBytes:512000,maxStderrBytes:512000,abortSignal});if(execution.status!=="completed")return{success:!1,mode:"check",linter:resolvedLinter.linter,command,error:execution.message??`Execution ${execution.status}`};let exitCode=execution.exitCode??1,output=execution.stdout;if(execution.stderr)output+=(output?`
|
|
6602
|
+
`)){let trimmed=line.trim();if(!trimmed)continue;let[name,rest]=trimmed.split(/\s+/,2);if(!name||!rest||byName.has(name))continue;let url3=rest.replace(/\s+\((?:fetch|push)\)\s*$/i,"");byName.set(boundUntrusted(name,64),boundUntrusted(url3,MAX_REMOTE_URL_LEN))}let entries=[...byName.entries()],remotes=entries.slice(0,MAX_REMOTES).map(([name,url3])=>({name,url:url3}));return{remotes,remotesTruncated:entries.length>remotes.length}}async function countCheckoutReceiptFiles(directory,sessionID){try{let receiptDirectory=validateSwarmPath(directory,path284.join(RECEIPT_DIR2,prWorkflowSessionFileStem(sessionID)));return(await fsp8.readdir(receiptDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&/^[0-9a-f]{40,64}\.json$/i.test(entry.name)).length}catch(error93){if(error93.code==="ENOENT")return 0;return null}}function describeNextStep(gate,git2,checkout){if(checkout.kind==="recovery-required"||checkout.kind==="indeterminate")return`Manual Git recovery required. code=${checkout.code} retryable=false required_action=${checkout.requiredAction}`;if(!gate.active)return"No active PR workflow gate for this session. Activate with `/swarm pr-review <pr-ref>` or `/swarm pr-feedback <pr-ref>` before PR-workflow tool calls are admitted.";if(!gate.prHeadBound)return gate.mode==="PR_FEEDBACK"?"PR_FEEDBACK gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes). Prefer the intended exact tracking checkout, then bind; if this workflow inherited an already-detached exact intake head, bind it directly and the controller will attach the unique exact local/remote tracking ref. Ambiguity or an existing mismatched upstream fails closed.":"PR_REVIEW gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes), then bind the exact detached PR head.";if(git2.isClean===!1)return`${gate.mode} gate active and head bound, but the working tree is dirty. Read-only observation only; the gate keeps writes and non-tracking fetches fail-closed.`;if(git2.isClean===null)return`${gate.mode} gate active and head bound, but this session could not determine whether the working tree is clean (git status failed). Treat the tree state as unknown and verify manually before assuming it is clean; read-only observation only.`;return`${gate.mode} gate active and head bound. Continue read-only review using the admitted observe/validate tools (diff, gh_evidence, repo_map, lint check, etc.).`}function summarizeGate(state,receiptFiles,salvage){if(!state)return{active:!1,reason:"no-active-gate"};return{active:!0,...salvage?.salvaged?{stateSalvaged:!0,stateSalvageDisclosure:salvage.disclosure}:{},mode:state.mode,prHeadBound:Boolean(state.prHeadSha),prHeadSha:state.prHeadSha??null,prFeedbackTargetUrl:state.prFeedbackTargetUrl?boundUntrusted(state.prFeedbackTargetUrl,MAX_FIELD_LEN):null,prReviewBaseRef:state.prReviewBaseRef?boundUntrusted(state.prReviewBaseRef,MAX_FIELD_LEN):null,prReviewBaseSha:state.prReviewBaseSha??null,prReviewDepthTier:state.prReviewDepthTier??null,baseDispatchBatches:state.prReviewBaseDispatches?.length??0,validationBatches:state.prReviewValidationBatches?.length??0,feedbackVerificationBatches:state.prFeedbackVerifications?.length??0,...state.prFeedbackInventoryAmendments?.length?{inventoryAmendments:state.prFeedbackInventoryAmendments}:{},checkoutReceiptFiles:receiptFiles,activatedAt:state.activatedAt,updatedAt:state.updatedAt,revision:state.revision}}async function executePrWorkflowStatus(directory,rawSessionID){let sessionID=rawSessionID?.trim()?rawSessionID.trim():null,[head2,isClean,branchInfo,porcelain,remoteOutput,liveCheckout]=await Promise.all([_internals215.resolveCurrentGitHeadAsync(directory),_internals215.resolveIsWorkingTreeCleanAsync(directory),resolveBranch(directory),_internals215.runGitCapture(directory,["status","--porcelain=v1","--untracked-files=all"]),_internals215.runGitCapture(directory,["remote","-v"]),_internals215.classifyGitState(directory)]),dirty=parseDirtyFiles(porcelain),{remotes,remotesTruncated}=parseRemotes(remoteOutput),git2={head:head2,branch:branchInfo.branch,detached:branchInfo.detached,isClean,dirtyFileCount:dirty.dirtyFileCount,dirtyFiles:dirty.dirtyFiles,dirtyFilesTruncated:dirty.dirtyFilesTruncated,remotes,remotesTruncated},gate,activeState=null;if(!sessionID)gate={active:!1,reason:"no-session-context"};else{let recovery2=await _internals215.readPrWorkflowGateStateForRecovery(directory,sessionID);activeState=recovery2?.state??null;let receiptFiles=activeState?await countCheckoutReceiptFiles(directory,sessionID):null;gate=summarizeGate(activeState,receiptFiles,recovery2?{salvaged:recovery2.salvaged,disclosure:recovery2.disclosure}:void 0)}let recovery=activeState?.checkoutRecovery,checkout=recovery?{kind:recovery.code==="GIT_STATE_INDETERMINATE"?"indeterminate":"recovery-required",code:recovery.code,retryable:!1,requiredAction:recovery.requiredAction,evidence:recovery.evidence}:liveCheckout,result={success:!0,sessionID,git:git2,checkout,gate,nextStep:describeNextStep(gate,git2,checkout)};return JSON.stringify(result,null,2)}var pr_workflow_status=createSwarmTool({description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary (mode, bound PR head, base ref/sha, depth tier, dispatch/validation batch counts). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",args:{},execute:async(_args,directory,ctx)=>executePrWorkflowStatus(directory,ctx?.sessionID)}),_internals215={readPrWorkflowGateStateForRecovery,resolveCurrentGitHeadAsync,resolveIsWorkingTreeCleanAsync,runGitCapture:runGitCapture2,classifyGitState:classifyPrWorkflowGitState,truncateToByteBudget};init_p_limit();init_zod();init_manager2();init_utils();init_external_tool_runner();init_project_boundary();init_create_tool();init_lint();init_quality_budget();init_sast_scan();init_secretscan();import*as path285 from"node:path";var TOOL_TIMEOUT_MS=60000,MAX_COMBINED_BYTES=500000,MAX_COMPACT_ERROR_BYTES=4096,CANCELLATION_SETTLEMENT_GRACE_MS=1000,MAX_CONCURRENT=4,MAX_FILES=100,GIT_TIMEOUT_MS11=1e4,GIT_MAX_OUTPUT_BYTES=2000000,ALL_LINES_CHANGED=-1,MAX_CHANGED_LINE_ENTRIES=200000,_internals216={qualityBudget,runLintWrapped,runSecretscanWrapped,runSastScanWrapped,runQualityBudgetWrapped,runWithTimeout:runWithTimeout2,getChangedLineRanges,saveEvidence,runExternalTool,detectResolvedLinter,runLintOnFiles,platform:()=>process.platform,serializePreCheckResult,MAX_COMBINED_BYTES};function formatIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function evaluateSecretscanGate(toolResult,requestedFiles){if(toolResult.error)return{passed:!1,summary:`Secretscan wrapper error: ${toolResult.error}`,findingsCount:0};if(!toolResult.ran||!toolResult.result)return{passed:!1,summary:"Secretscan did not return a result",findingsCount:0};if("error"in toolResult.result)return{passed:!1,summary:`Secretscan error: ${toolResult.result.error}`,findingsCount:0};let result=toolResult.result;if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{passed:!1,summary:"Secretscan failed: scanner returned incomplete coverage metadata",result,findingsCount:Math.max(result.count,result.findings.length)};let findingsCount=Math.max(result.count,result.findings.length),failures=[];if(findingsCount>0)failures.push(`${findingsCount} secret finding(s)`);if(result.incomplete_files>0||result.incomplete_paths.length>0){let incompletePaths=result.incomplete_paths.length>0?`; incomplete paths: ${formatIncompletePaths(result.incomplete_paths)}`:"";failures.push(`${result.incomplete_files} incomplete file(s)${incompletePaths}`)}if(result.count!==result.findings.length)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(requestedFiles>0&&result.files_scanned===0)failures.push("zero requested files scanned");let statistics=`Secretscan: ${findingsCount} finding(s), ${result.files_scanned} files scanned, ${result.skipped_files} skipped`;return{passed:failures.length===0,summary:failures.length>0?`${statistics}; failed: ${failures.join("; ")}`:statistics,result,findingsCount}}function truncateUtf8(value,maxBytes){if(Buffer.byteLength(value,"utf8")<=maxBytes)return value;let marker="... (truncated)",budget=Math.max(0,maxBytes-Buffer.byteLength(marker,"utf8")),result="",usedBytes=0;for(let character of value){let characterBytes=Buffer.byteLength(character,"utf8");if(usedBytes+characterBytes>budget)break;result+=character,usedBytes+=characterBytes}return`${result}${marker}`}function compactToolResult(toolResult){return{ran:toolResult.ran,duration_ms:toolResult.duration_ms,...toolResult.error!==void 0&&{error:truncateUtf8(toolResult.error,MAX_COMPACT_ERROR_BYTES)},...toolResult.error===void 0&&toolResult.result!==void 0&&{result_omitted:!0}}}function serializePreCheckResult(result){let serialized3=JSON.stringify(result,null,2);if(Buffer.byteLength(serialized3,"utf8")<=MAX_COMBINED_BYTES)return serialized3;let compact={batch_status:result.batch_status,gates_passed:result.gates_passed,lint:compactToolResult(result.lint),secretscan:compactToolResult(result.secretscan),sast_scan:compactToolResult(result.sast_scan),quality_budget:compactToolResult(result.quality_budget),total_duration_ms:result.total_duration_ms,output_truncated:!0};return JSON.stringify(compact,null,2)}function isWindowsAbsolutePath(inputPath){return/^[A-Za-z]:[/\\]/.test(inputPath)}function validatePath(inputPath,baseDir,workspaceDir){if(typeof inputPath!=="string")return"path must be a string";if(!inputPath||inputPath.trim().length===0)return"path is required";let resolved,isWinAbs=isWindowsAbsolutePath(inputPath);if(isWinAbs)resolved=path285.win32.resolve(inputPath);else if(path285.isAbsolute(inputPath))resolved=path285.resolve(inputPath);else resolved=path285.resolve(baseDir,inputPath);let workspaceResolved=isWindowsAbsolutePath(workspaceDir)?path285.win32.resolve(workspaceDir):path285.resolve(workspaceDir),relative69;if(isWinAbs)relative69=path285.win32.relative(workspaceResolved,resolved);else relative69=path285.relative(workspaceResolved,resolved);if(relative69.startsWith(".."))return"path traversal detected";return null}function isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitBoundary){let pathApi=platform==="win32"?path285.win32:path285,directoryKey=pathApi.resolve(dir).replace(/\\/g,"/"),workspaceKey=pathApi.resolve(workspaceDir).replace(/\\/g,"/"),normalizedDirectoryKey=platform==="win32"?directoryKey.toLowerCase():directoryKey,normalizedWorkspaceKey=platform==="win32"?workspaceKey.toLowerCase():workspaceKey;if(normalizedDirectoryKey===normalizedWorkspaceKey)return!0;let relative69=pathApi.relative(workspaceDir,dir);return relative69!==""&&relative69!==".."&&!relative69.startsWith(`..${pathApi.sep}`)&&!pathApi.isAbsolute(relative69)&&hasExplicitBoundary}function validateDirectory2(dir,workspaceDir){if(!dir||dir.length===0)return"directory is required";if(dir.length>500)return"directory path too long";let traversalCheck=validatePath(dir,workspaceDir,workspaceDir);if(traversalCheck)return traversalCheck;let platform=_internals216.platform();if(!isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitProjectBoundary(dir)))return"directory must resolve to the project root";return null}async function runWithTimeout2(operation,timeoutMs,parentSignal,waitForCancellationSettlement=!1){let controller=new AbortController,timeoutHandle,parentAbortListener;if(parentSignal?.aborted)throw Error("Tool execution cancelled");let parentAbortPromise=new Promise((_,reject2)=>{if(!parentSignal)return;if(parentAbortListener=()=>{reject2(Error("Tool execution cancelled")),controller.abort()},parentSignal.addEventListener("abort",parentAbortListener,{once:!0}),parentSignal.aborted)parentAbortListener()});if(controller.signal.aborted)return await parentAbortPromise;let operationPromise=operation(controller.signal);try{let timeoutPromise=new Promise((_,reject2)=>{timeoutHandle=setTimeout(()=>{reject2(Error(`Timeout after ${timeoutMs}ms`)),controller.abort()},timeoutMs)});return await Promise.race([operationPromise,timeoutPromise,parentAbortPromise])}catch(error93){if(controller.signal.aborted&&waitForCancellationSettlement){let settlementTimer;try{await Promise.race([operationPromise.then(()=>{return},()=>{return}),new Promise((resolve117)=>{settlementTimer=setTimeout(resolve117,CANCELLATION_SETTLEMENT_GRACE_MS)})])}finally{if(settlementTimer!==void 0)clearTimeout(settlementTimer)}}throw error93}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(parentAbortListener&&parentSignal)parentSignal.removeEventListener("abort",parentAbortListener)}}async function runLintWrapped(files,directory,_config,abortSignal){let start=process.hrtime.bigint();try{let resolvedLinter=await _internals216.detectResolvedLinter(directory,abortSignal);if(!resolvedLinter)return{ran:!1,error:"No linter found (biome or eslint)",duration_ms:Number(process.hrtime.bigint()-start)/1e6};if(files&&files.length>0)return{ran:!0,result:await _internals216.runLintOnFiles(resolvedLinter,files,directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await _internals121.runResolvedLint(resolvedLinter,"check",directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runLintOnFiles(resolvedLinter,files,workspaceDir,abortSignal){if(resolvedLinter.source==="legacy-test-probe")return _internals121.runResolvedLint(resolvedLinter,"check",workspaceDir,abortSignal);let validatedFiles=[];for(let file3 of files){if(typeof file3!=="string")continue;let resolvedPath=path285.resolve(file3);if(validatePath(resolvedPath,workspaceDir,workspaceDir))continue;validatedFiles.push(resolvedPath)}if(validatedFiles.length===0)return{success:!1,mode:"check",linter:resolvedLinter.linter,command:[],error:"No valid files after security validation"};let args2;if(resolvedLinter.linter==="biome")args2=[...resolvedLinter.argsPrefix,"check",...validatedFiles];else args2=[...resolvedLinter.argsPrefix,...validatedFiles];let command=[...resolvedLinter.displayPrefix,...args2];try{let execution=await _internals216.runExternalTool({executable:resolvedLinter.executable,args:args2,cwd:workspaceDir,timeoutMs:TOOL_TIMEOUT_MS,maxStdoutBytes:512000,maxStderrBytes:512000,abortSignal});if(execution.status!=="completed")return{success:!1,mode:"check",linter:resolvedLinter.linter,command,error:execution.message??`Execution ${execution.status}`};let exitCode=execution.exitCode??1,output=execution.stdout;if(execution.stderr)output+=(output?`
|
|
6601
6603
|
`:"")+execution.stderr;if(execution.stdoutTruncated||execution.stderrTruncated)output+=`
|
|
6602
6604
|
... (output truncated)`;let result={success:!0,mode:"check",linter:resolvedLinter.linter,command,exitCode,output};if(exitCode===0)result.message=`${resolvedLinter.linter} check completed successfully with no issues`;else result.message=`${resolvedLinter.linter} check found issues (exit code ${exitCode}).`;return result}catch(error93){return{success:!1,mode:"check",linter:resolvedLinter.linter,command,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error"}}}async function runSecretscanWrapped(files,directory,_config,abortSignal){let start=process.hrtime.bigint();try{if(files&&files.length>0)return{ran:!0,result:await runWithTimeout2(()=>runSecretscanOnFiles(files,directory),TOOL_TIMEOUT_MS,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await runWithTimeout2(()=>runSecretscan(directory),TOOL_TIMEOUT_MS,abortSignal,!0),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runSastScanWrapped(changedFiles,directory,severityThreshold,config3,phase,abortSignal){let start=process.hrtime.bigint();try{return{ran:!0,result:await runWithTimeout2((signal2)=>sastScan({changed_files:changedFiles,severity_threshold:severityThreshold,phase,abort_signal:signal2},directory,config3),TOOL_TIMEOUT_MS,abortSignal,!0),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runQualityBudgetWrapped(changedFiles,directory,config3,abortSignal){let start=process.hrtime.bigint();try{return{ran:!0,result:await runWithTimeout2((signal2)=>_internals216.qualityBudget({changed_files:changedFiles,config:config3?.gates?.quality_budget},directory,signal2),TOOL_TIMEOUT_MS,abortSignal,!0),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}var GATE_SEVERITIES=new Set(["high","critical"]),SEVERITY_ORDER_PCB={low:0,medium:1,high:2,critical:3};function meetsThresholdForTriage(severity,threshold){return(SEVERITY_ORDER_PCB[severity]??0)>=(SEVERITY_ORDER_PCB[threshold]??1)}async function runGit8(args2,directory,abortSignal){let result=await _internals216.runExternalTool({executable:"git",args:args2,cwd:directory,timeoutMs:GIT_TIMEOUT_MS11,maxStdoutBytes:GIT_MAX_OUTPUT_BYTES,maxStderrBytes:64000,abortSignal});if(result.status!=="completed"||result.exitCode!==0||result.stdoutTruncated)return null;return result.stdout}function decodeGitQuotedPath(value){if(!value.startsWith('"'))return value;if(!value.endsWith('"'))return null;let bytes=[],appendText=(text)=>{bytes.push(...Buffer.from(text,"utf8"))};for(let index=1;index<value.length-1;index++){let codePoint=value.codePointAt(index);if(codePoint===void 0)return null;let char=String.fromCodePoint(codePoint);if(char!=="\\"){if(appendText(char),char.length===2)index++;continue}if(index++,index>=value.length-1)return null;let escaped=value[index],simple={"\\":"\\",'"':'"',t:"\t",n:`
|
|
6603
6605
|
`,r:"\r",b:"\b",f:"\f",v:"\v"};if(simple[escaped]!==void 0){appendText(simple[escaped]);continue}if(/[0-7]/.test(escaped)){let octal=escaped;for(let count=0;count<2;count++){let next=value[index+1];if(!next||!/[0-7]/.test(next))break;octal+=next,index++}bytes.push(Number.parseInt(octal,8));continue}return null}return Buffer.from(bytes).toString("utf8")}function normalizeRepoPathKey(repoPath){let normalized=repoPath.replace(/\\/g,"/");return _internals216.platform()==="win32"||_internals216.platform()==="darwin"?normalized.toLowerCase():normalized}function normalizeDiffPath(rawPath){let pathToken=rawPath.startsWith('"')?rawPath:rawPath.split("\t",1)[0],decoded=decodeGitQuotedPath(pathToken);if(decoded===null||decoded==="/dev/null"||decoded.trim().length===0)return null;return normalizeRepoPathKey(decoded)}function parseDiffLineRangesChecked(diffOutput,requireGitFileHeaders){let result=new Map,currentFile=null,inGitFile=!1,expectingDestination=!1,destinationSeen=!1,destinationNeedsHunk=!1,collectedLines=0;for(let rawLine of diffOutput.split(/\r?\n/)){let line=rawLine.endsWith("\r")?rawLine.slice(0,-1):rawLine;if(line.startsWith("diff --git ")){if(expectingDestination||destinationNeedsHunk)return null;inGitFile=!0,currentFile=null,expectingDestination=!1,destinationSeen=!1;continue}if(line.startsWith("--- ")&&(inGitFile||!requireGitFileHeaders)){if(expectingDestination||destinationNeedsHunk)return null;expectingDestination=!0;continue}if(line.startsWith("+++ ")){if(requireGitFileHeaders&&(!inGitFile||!expectingDestination))return null;let rawDestination=line.slice(4);if(currentFile=normalizeDiffPath(rawDestination),currentFile===null&&rawDestination.trim()!=="/dev/null")return null;if(expectingDestination=!1,destinationSeen=!0,destinationNeedsHunk=!0,!currentFile)continue;if(!result.has(currentFile))result.set(currentFile,new Set);continue}if(!line.startsWith("@@"))continue;if(expectingDestination||requireGitFileHeaders&&(!inGitFile||!destinationSeen))return null;let match=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);if(!match)return null;let start=Number.parseInt(match[1],10),count=match[2]!==void 0?Number.parseInt(match[2],10):1;if(!Number.isSafeInteger(start)||!Number.isSafeInteger(count)||count<0||count>0&&start<1||count>MAX_CHANGED_LINE_ENTRIES||start+count-1>Number.MAX_SAFE_INTEGER||collectedLines+count>MAX_CHANGED_LINE_ENTRIES)return null;if(destinationNeedsHunk=!1,!currentFile)continue;let lines=result.get(currentFile);if(!lines)return null;for(let index=0;index<count;index++)lines.add(start+index);collectedLines+=count}if(expectingDestination||destinationNeedsHunk)return null;return result}function mergeChangedLines(target,source){for(let[file3,sourceLines]of source){let targetLines=target.get(file3)??new Set;for(let line of sourceLines)targetLines.add(line);target.set(file3,targetLines)}}function parseUntrackedStatus(output){if(output.length>0&&!output.endsWith("\x00"))return null;let untracked=[],records=output.split("\x00");for(let index=0;index<records.length-1;index++){let record3=records[index];if(!record3||record3.length<4||record3[2]!==" ")return null;let status=record3.slice(0,2),filePath=record3.slice(3);if(!filePath||!isKnownPorcelainStatus(status))return null;if(status==="??"||status==="!!")untracked.push(normalizeRepoPathKey(filePath));if(/[RC]/.test(status)){let sourcePath=records[++index];if(!sourcePath||looksLikePorcelainStatusRecord(sourcePath))return null}}return untracked}function isKnownPorcelainStatus(status){if(status==="??"||status==="!!")return!0;if(/U/.test(status))return new Set(["DD","AU","UD","UA","DU","AA","UU"]).has(status);return status!==" "&&/^[ MTADRC]{2}$/.test(status)}function looksLikePorcelainStatusRecord(value){return value.length>=4&&value[2]===" "&&isKnownPorcelainStatus(value.slice(0,2))}async function getChangedLineRanges(directory,abortSignal,requestedFiles=[]){let mergeBase=null;for(let baseBranch of["zaxbyhub/main","upstream/main","origin/main","main","origin/master","master"]){let candidate2=(await runGit8(["merge-base",baseBranch,"HEAD"],directory,abortSignal))?.trim();if(candidate2&&/^[0-9a-f]{40,64}$/i.test(candidate2)){mergeBase=candidate2;break}}if(!mergeBase)return null;let commonDiffArgs=["-c","core.quotePath=false","diff","--no-ext-diff","--no-color","--no-prefix","-U0"],requestedPathspecs=requestedFiles.map((file3)=>path285.relative(directory,file3).replace(/\\/g,"/")).filter((file3)=>file3.length>0&&file3!==".."&&!file3.startsWith("../")),statusArgs=["-c","core.quotePath=false","status","--porcelain=v1","-z","--untracked-files=all",...requestedPathspecs.length>0?["--ignored=matching"]:[],...requestedPathspecs.length>0?["--",...requestedPathspecs]:[]],[committed,staged,unstaged,status]=await Promise.all([runGit8([...commonDiffArgs,`${mergeBase}..HEAD`,"--"],directory,abortSignal),runGit8([...commonDiffArgs,"--cached","HEAD","--"],directory,abortSignal),runGit8([...commonDiffArgs,"--"],directory,abortSignal),runGit8(statusArgs,directory,abortSignal)]);if(committed===null||staged===null||unstaged===null||status===null)return null;let committedLines=parseDiffLineRangesChecked(committed,!0),stagedLines=parseDiffLineRangesChecked(staged,!0),unstagedLines=parseDiffLineRangesChecked(unstaged,!0);if(!committedLines||!stagedLines||!unstagedLines)return null;let result=new Map;mergeChangedLines(result,committedLines),mergeChangedLines(result,stagedLines),mergeChangedLines(result,unstagedLines);let untracked=parseUntrackedStatus(status);if(untracked===null)return null;let requestedKeys=requestedPathspecs.map(normalizeRepoPathKey);for(let file3 of untracked)if(result.set(file3,new Set([ALL_LINES_CHANGED])),file3.endsWith("/")){for(let requestedFile of requestedKeys)if(requestedFile.startsWith(file3))result.set(requestedFile,new Set([ALL_LINES_CHANGED]))}return result}function classifySastFindings(findings,changedLineRanges,directory){if(!changedLineRanges)return{newFindings:findings,preexistingFindings:[]};let newFindings=[],preexistingFindings=[],pathApi=_internals216.platform()==="win32"?path285.win32:path285.posix,resolvedDirectory=pathApi.resolve(directory);for(let finding of findings){let filePath=finding.location.file,normalised;try{if(typeof filePath!=="string"||filePath.length===0||filePath.includes("\x00")){newFindings.push(finding);continue}let resolvedFinding=pathApi.isAbsolute(filePath)?pathApi.resolve(filePath):pathApi.resolve(resolvedDirectory,filePath),relative69=pathApi.relative(resolvedDirectory,resolvedFinding);if(pathApi.isAbsolute(relative69)||relative69===".."||relative69.startsWith(`..${pathApi.sep}`)){newFindings.push(finding);continue}normalised=normalizeRepoPathKey(relative69)}catch{newFindings.push(finding);continue}let changedLines=changedLineRanges.get(normalised);if(changedLines?.has(ALL_LINES_CHANGED)||changedLines?.has(finding.location.line))newFindings.push(finding);else preexistingFindings.push(finding)}return{newFindings,preexistingFindings}}async function runPreCheckBatch(input,workspaceDir,contextDir,abortSignal){let effectiveWorkspaceDir=workspaceDir||input.directory||contextDir,{files,directory,sast_threshold="medium",config:config3,phase}=input,dirError=validateDirectory2(directory,effectiveWorkspaceDir);if(dirError)return warn(`pre_check_batch: Invalid directory: ${dirError}`),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0};if(!files||files.length===0)return warn("pre_check_batch: No files provided, skipping all tools (fail-closed)"),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};let changedFiles=[];for(let file3 of files){if(typeof file3!=="string"){warn(`pre_check_batch: Non-string file entry rejected: ${String(file3)}`);continue}if(validatePath(file3,directory,effectiveWorkspaceDir)){warn(`pre_check_batch: Invalid file path: ${file3}`);continue}changedFiles.push(path285.resolve(directory,file3))}if(changedFiles.length===0)return warn("pre_check_batch: No valid files after validation, skipping all tools (fail-closed)"),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};try{assertProjectRoot(directory)}catch(error93){let rootError=error93 instanceof Error?error93.message:String(error93);return warn(`pre_check_batch: Project-root validation failed: ${rootError}`),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:rootError,duration_ms:0},secretscan:{ran:!1,error:rootError,duration_ms:0},sast_scan:{ran:!1,error:rootError,duration_ms:0},quality_budget:{ran:!1,error:rootError,duration_ms:0},total_duration_ms:0}}if(changedFiles.length>MAX_FILES)throw Error(`Input exceeds maximum file count: ${changedFiles.length} > ${MAX_FILES}`);let limit=pLimit(MAX_CONCURRENT),[lintResult,secretscanResult,sastScanResult,qualityBudgetResult]=await Promise.all([limit(()=>_internals216.runLintWrapped(changedFiles,directory,config3,abortSignal)),limit(()=>_internals216.runSecretscanWrapped(changedFiles,directory,config3,abortSignal)),limit(()=>_internals216.runSastScanWrapped(changedFiles,directory,sast_threshold,config3,phase,abortSignal)),limit(()=>_internals216.runQualityBudgetWrapped(changedFiles,directory,config3,abortSignal))]),totalDuration=lintResult.duration_ms+secretscanResult.duration_ms+sastScanResult.duration_ms+qualityBudgetResult.duration_ms,gatesPassed=!0;if(lintResult.ran&&lintResult.result){let lintRes=lintResult.result;if("success"in lintRes&&lintRes.success===!1)warn("pre_check_batch: Lint found issues (informational only)")}else if(lintResult.error)warn(`pre_check_batch: Lint error (informational only): ${lintResult.error}`);let secretscanDecision=evaluateSecretscanGate(secretscanResult,changedFiles.length);if(!secretscanDecision.passed)gatesPassed=!1,warn(`pre_check_batch: ${secretscanDecision.summary} - GATE FAILED`);if(secretscanResult.ran||secretscanResult.error)try{let scanResult=secretscanDecision.result,secretscanEvidence={task_id:"secretscan",type:"secretscan",timestamp:new Date().toISOString(),agent:"pre_check_batch",verdict:secretscanDecision.passed?"pass":"fail",summary:secretscanDecision.summary,findings_count:secretscanDecision.findingsCount,scan_directory:scanResult?.scan_dir??directory,files_scanned:scanResult?.files_scanned??0,skipped_files:scanResult?.skipped_files??0,incomplete_files:scanResult?.incomplete_files??changedFiles.length,incomplete_paths:scanResult?.incomplete_paths??[{path:".",reason:"missing_coverage_metadata"}]};await _internals216.saveEvidence(directory,"secretscan",secretscanEvidence,abortSignal)}catch(e){let persistError=`Failed to persist secretscan evidence: ${e instanceof Error?e.message:String(e)}`;secretscanResult.error=persistError,gatesPassed=!1,warn(`pre_check_batch: ${persistError} - GATE FAILED`)}let sastPreexistingFindings;if(sastScanResult.ran&&sastScanResult.result){let sastResult=sastScanResult.result;if(sastResult.error)gatesPassed=!1,warn(`pre_check_batch: SAST scan error (${sastResult.error}) - GATE FAILED`);else if(sastResult.baseline_used){if(sastResult.pre_existing_findings&&sastResult.pre_existing_findings.length>0){if(sastPreexistingFindings=sastResult.pre_existing_findings.filter((f)=>meetsThresholdForTriage(f.severity,sast_threshold)),sastPreexistingFindings.length>0)warn(`pre_check_batch: SAST baseline diff found ${sastPreexistingFindings.length} pre-existing finding(s) - passing to reviewer for triage`)}if(sastResult.verdict==="fail")gatesPassed=!1,warn("pre_check_batch: SAST scan found new findings above threshold - GATE FAILED")}else if(sastResult.verdict==="fail"){let gateFindings=sastResult.findings.filter((f)=>GATE_SEVERITIES.has(f.severity));if(gateFindings.length>0){let changedLineRanges=await _internals216.getChangedLineRanges(directory,abortSignal,changedFiles),{newFindings,preexistingFindings}=classifySastFindings(gateFindings,changedLineRanges,directory);if(newFindings.length>0)gatesPassed=!1,warn(`pre_check_batch: SAST scan found ${newFindings.length} new HIGH/CRITICAL finding(s) on changed lines - GATE FAILED`);else if(preexistingFindings.length>0)sastPreexistingFindings=preexistingFindings,warn(`pre_check_batch: SAST scan found ${preexistingFindings.length} pre-existing HIGH/CRITICAL finding(s) on unchanged lines - passing to reviewer for triage`)}else gatesPassed=!1,warn("pre_check_batch: SAST scan found vulnerabilities - GATE FAILED")}}else if(sastScanResult.error)gatesPassed=!1,warn(`pre_check_batch: SAST scan error - GATE FAILED: ${sastScanResult.error}`);if(qualityBudgetResult.ran&&qualityBudgetResult.result){if(qualityBudgetResult.result.verdict==="fail")warn("pre_check_batch: Quality budget exceeded (informational only)")}else if(qualityBudgetResult.error)warn(`pre_check_batch: Quality budget error (informational only): ${qualityBudgetResult.error}`);return{batch_status:[lintResult,secretscanResult,sastScanResult,qualityBudgetResult].every((toolResult)=>toolResult.ran===!1)?"skipped":"completed",gates_passed:gatesPassed,lint:lintResult,secretscan:secretscanResult,sast_scan:sastScanResult,quality_budget:qualityBudgetResult,total_duration_ms:Math.round(totalDuration),...sastPreexistingFindings&&sastPreexistingFindings.length>0&&{sast_preexisting_findings:sastPreexistingFindings}}}var pre_check_batch=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Run multiple verification tools in parallel: lint, secretscan, SAST scan, and quality budget. Returns unified result with gates_passed status. Security tools (secretscan, sast_scan) are HARD GATES - failures block merging.",args:{files:exports_external.array(exports_external.string()).optional().describe("Specific files to check (optional, scans directory if not provided)"),directory:exports_external.string().describe("Project root directory — ordinary workspace subdirectories are rejected; direct .git or .opencode project boundaries are accepted"),sast_threshold:exports_external.enum(["low","medium","high","critical"]).optional().describe("Minimum severity for SAST findings to cause failure (default: medium)"),phase:exports_external.number().int().min(1).optional().describe("Current phase number (positive integer >= 1). When provided, enables SAST baseline diffing: only findings absent from the phase-scoped baseline fail the gate.")},async execute(args2,directory,ctx){if(!args2||typeof args2!=="object")return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"Invalid arguments",duration_ms:0},secretscan:{ran:!1,error:"Invalid arguments",duration_ms:0},sast_scan:{ran:!1,error:"Invalid arguments",duration_ms:0},quality_budget:{ran:!1,error:"Invalid arguments",duration_ms:0},total_duration_ms:0});if(!directory||typeof directory!=="string"||directory.trim()==="")return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},secretscan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},sast_scan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},quality_budget:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},total_duration_ms:0});let typedArgs=args2;if(!typedArgs.directory)return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"directory is required",duration_ms:0},secretscan:{ran:!1,error:"directory is required",duration_ms:0},sast_scan:{ran:!1,error:"directory is required",duration_ms:0},quality_budget:{ran:!1,error:"directory is required",duration_ms:0},total_duration_ms:0});let resolvedDirectory=path285.resolve(typedArgs.directory),workspaceAnchor=path285.resolve(directory);if(isStrictPathDescendant(resolvedDirectory,workspaceAnchor)&&!hasExplicitProjectBoundary(resolvedDirectory)){let subDirError=`directory "${typedArgs.directory}" is a subdirectory of the project root — pre_check_batch requires the project root directory "${workspaceAnchor}"`;return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:subDirError,duration_ms:0},secretscan:{ran:!1,error:subDirError,duration_ms:0},sast_scan:{ran:!1,error:subDirError,duration_ms:0},quality_budget:{ran:!1,error:subDirError,duration_ms:0},total_duration_ms:0})}let dirError=validateDirectory2(resolvedDirectory,workspaceAnchor);if(dirError)return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0});try{let rawPhase=typedArgs.phase,safePhase=typeof rawPhase==="number"&&Number.isInteger(rawPhase)&&rawPhase>=1?rawPhase:void 0,result=await runPreCheckBatch({files:typedArgs.files,directory:resolvedDirectory,sast_threshold:typedArgs.sast_threshold,config:typedArgs.config,phase:safePhase},workspaceAnchor,directory,ctx?.abort);return serializePreCheckResult(result)}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:errorMessage3,duration_ms:0},secretscan:{ran:!1,error:errorMessage3,duration_ms:0},sast_scan:{ran:!1,error:errorMessage3,duration_ms:0},quality_budget:{ran:!1,error:errorMessage3,duration_ms:0},total_duration_ms:0})}}});init_zod();init_guardrails2();init_pr_workflow_gate();init_scope_binding();init_create_tool();var PreparePrFeedbackScopeArgsSchema=exports_external.object({task_id:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/,"task_id must use N.M notation"),files:exports_external.array(exports_external.string().min(1).max(4096)).min(1).max(1e4)}).strict();function failure(message){return JSON.stringify({success:!1,message},null,2)}async function executePreparePrFeedbackScope(args2,directory,context={}){let parsed=PreparePrFeedbackScopeArgsSchema.safeParse(args2);if(!parsed.success)return failure(`Invalid PR-feedback scope: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure("PR-feedback scope requires an active session");let files=normalizeScopeFiles(parsed.data.files);if(!files)return failure("PR-feedback scope contains an unsafe file path");for(let file3 of files){let symlinkBlock=checkWriteTargetForSymlink(file3,directory);if(symlinkBlock)return failure(symlinkBlock)}try{await declarePrFeedbackScope(directory,sessionID,parsed.data.task_id,files)}catch(error93){return failure(error93 instanceof Error?error93.message:String(error93))}return JSON.stringify({success:!0,task_id:parsed.data.task_id,files,message:"Scope is bound to the verified PR-feedback revision and will authorize only the next matching coder Task."},null,2)}var prepare_pr_feedback_scope=createSwarmTool({description:"Prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles.",args:{task_id:PreparePrFeedbackScopeArgsSchema.shape.task_id,files:PreparePrFeedbackScopeArgsSchema.shape.files},execute:executePreparePrFeedbackScope});init_quality_budget();init_zod();init_pr_workflow_gate();init_create_tool();var RebindPrFeedbackHeadArgsSchema=exports_external.object({pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{40}$/i)}).strict();async function executeRebindPrFeedbackHead(args2,directory,context={}){let parsed=RebindPrFeedbackHeadArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR feedback rebind: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR feedback rebind requires an active sessionID"});try{let state=await rebindPrFeedbackHead(directory,context.sessionID,parsed.data.pr_head_sha);return JSON.stringify({success:!0,pr_head_sha:state.prHeadSha,rebind_count:state.prFeedbackRebindCount??1,message:"Rebound the PR_FEEDBACK intake head; every Stage A / verification / gate receipt is invalidated — re-run the full mechanical ladder on the new ancestry."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var rebind_pr_feedback_head=createSwarmTool({description:"Rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair (base-sync). Use ONLY when the history genuinely changed to repair base drift or conflicts: it refuses a no-op rebind to the current intake head, refuses while publication is armed, and refuses while lanes are in flight. It invalidates every ancestry-bound receipt (Stage A, verification, ordered gates) so the full mechanical ladder re-runs on the new ancestry. Requires the full 40-char new PR head SHA; the current checkout must equal it.",args:{pr_head_sha:RebindPrFeedbackHeadArgsSchema.shape.pr_head_sha},execute:executeRebindPrFeedbackHead});init_zod();init_utils2();init_create_tool();import*as fs171 from"node:fs";import*as path286 from"node:path";var RecordImplementationReviewArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),reviewerVerdict:exports_external.enum(["APPROVE","NEEDS_REVISION","BLOCKED"]),criticVerdict:exports_external.enum(["APPROVE","NEEDS_REVISION","BLOCKED"]),diffBase:exports_external.string().trim().regex(/^[0-9a-f]{7,40}$/i),diffHead:exports_external.string().trim().regex(/^[0-9a-f]{7,40}$/i),notes:exports_external.string().trim().min(8).max(4000)}).strict();async function executeRecordImplementationReview(args2,directory,context={}){let parsed=RecordImplementationReviewArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid implementation review receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.reviewerVerdict!=="APPROVE"||data.criticVerdict!=="APPROVE")return JSON.stringify({success:!1,message:"A satisfying implementation-review receipt requires BOTH the reviewer and the critic to have delivered APPROVE; record non-approving verdicts in the working notes and fix the findings instead."});let receipt={issueNumber:data.issueNumber,reviewerVerdict:data.reviewerVerdict,criticVerdict:data.criticVerdict,diffBase:data.diffBase,diffHead:data.diffHead,notes:data.notes,timestamp:new Date().toISOString()};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"implementation-review.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{let dir=path286.dirname(validatedPath);await fs171.promises.mkdir(dir,{recursive:!0});let tmpPath=path286.join(dir,".implementation-review.json.tmp");return await fs171.promises.writeFile(tmpPath,JSON.stringify(receipt,null,2),"utf-8"),await fs171.promises.rename(tmpPath,validatedPath),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/implementation-review.json",message:`Implementation review recorded for issue #${data.issueNumber} (reviewer APPROVE + critic APPROVE); the trace may now satisfy its review gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_implementation_review=createSwarmTool({description:"Record the independent implementation review for the current traced issue (issue #2131 residual B): dispatch FRESH-context reviewer and critic passes over the implementation diff (separate contexts from the implementer), and once BOTH approve call this with the issue number, both APPROVE verdicts, the reviewed diff base/head SHAs, and notes. The /swarm issue --trace workflow will not hand off to commit-pr until this receipt exists. Non-approving verdicts cannot be recorded here — fix the findings and re-review.",args:{issueNumber:RecordImplementationReviewArgsSchema.shape.issueNumber,reviewerVerdict:RecordImplementationReviewArgsSchema.shape.reviewerVerdict,criticVerdict:RecordImplementationReviewArgsSchema.shape.criticVerdict,diffBase:RecordImplementationReviewArgsSchema.shape.diffBase,diffHead:RecordImplementationReviewArgsSchema.shape.diffHead,notes:RecordImplementationReviewArgsSchema.shape.notes},execute:executeRecordImplementationReview});init_zod();init_utils2();init_create_tool();import*as fs172 from"node:fs";import*as path287 from"node:path";var RecordIssuePublicationArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),prNumber:exports_external.number().int().min(1),prUrl:exports_external.string().url().regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+/,"prUrl must be a canonical GitHub PR URL (https://github.com/<owner>/<repo>/pull/<number>)"),headSha:exports_external.string().min(1).optional()}).strict();async function executeRecordIssuePublication(args2,directory){let parsed=RecordIssuePublicationArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid publication receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let{issueNumber,prNumber,prUrl,headSha}=parsed.data,receipt={published:!0,issueNumber,prNumber,prUrl,publishedAt:new Date().toISOString()};if(headSha)receipt.headSha=headSha;let validatedPath;try{validatedPath=validateSwarmPath(directory,"issue-publication.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{let dir=path287.dirname(validatedPath);await fs172.promises.mkdir(dir,{recursive:!0});let tmpPath=path287.join(dir,".issue-publication.json.tmp");return await fs172.promises.writeFile(tmpPath,JSON.stringify(receipt,null,2),"utf-8"),await fs172.promises.rename(tmpPath,validatedPath),JSON.stringify({success:!0,issueNumber,prNumber,prUrl,path:".swarm/issue-publication.json",message:`Publication receipt recorded for issue #${issueNumber} (PR #${prNumber}); the issue-trace workflow will transition to its terminal published state.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_issue_publication=createSwarmTool({description:'Record that the traced issue has been published (PR created/updated) so the /swarm issue --trace workflow can reach its terminal published state. The trace stops at publication_handoff (the commit-pr directive) until this receipt is observed — publication_handoff is NOT "issue resolved". commit-pr calls this after the PR is created/updated. Supply the traced issue number, the exact PR number, the canonical GitHub PR URL, and (optionally) the published HEAD sha. The receipt is issue-bound.',args:{issueNumber:RecordIssuePublicationArgsSchema.shape.issueNumber,prNumber:RecordIssuePublicationArgsSchema.shape.prNumber,prUrl:RecordIssuePublicationArgsSchema.shape.prUrl,headSha:RecordIssuePublicationArgsSchema.shape.headSha},execute:executeRecordIssuePublication});init_zod();init_utils2();init_create_tool();import*as fs173 from"node:fs";import*as path288 from"node:path";var RecordIssueReproductionArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),performed:exports_external.boolean(),commands:exports_external.array(exports_external.string().min(1)).min(1).optional(),output_summary:exports_external.string().min(1).optional()}).strict();async function executeRecordIssueReproduction(args2,directory,context={}){let parsed=RecordIssueReproductionArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid reproduction receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let{issueNumber,performed,commands,output_summary}=parsed.data;if(performed&&(!commands||commands.length===0||!output_summary))return JSON.stringify({success:!1,message:"A performed=true reproduction receipt requires non-empty commands and output_summary."});let receipt={performed,issueNumber,timestamp:new Date().toISOString()};if(commands)receipt.commands=commands;if(output_summary)receipt.output_summary=output_summary;if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"reproduction.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{let dir=path288.dirname(validatedPath);await fs173.promises.mkdir(dir,{recursive:!0});let tmpPath=path288.join(dir,".reproduction.json.tmp");return await fs173.promises.writeFile(tmpPath,JSON.stringify(receipt,null,2),"utf-8"),await fs173.promises.rename(tmpPath,validatedPath),JSON.stringify({success:!0,issueNumber,performed,path:".swarm/reproduction.json",message:performed?`Reproduction receipt recorded for issue #${issueNumber}; the trace may now transition to PLAN.`:`Reproduction receipt recorded (performed=false) for issue #${issueNumber}; it does NOT satisfy the reproduction gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_issue_reproduction=createSwarmTool({description:"Record the reproduction outcome for the current traced issue. The /swarm issue --trace workflow requires reproduction evidence (or a typed --no-repro waiver) before it can leave localization and transition to PLAN. Call this with performed=true, the exact commands run, and a concrete output_summary after attempting a minimal reproduction; the receipt binds to issueNumber (and records the calling session) and is read by the issue-trace engine. A performed=true receipt MUST include commands and output_summary. A performed=false receipt is recorded but does NOT satisfy the gate.",args:{issueNumber:RecordIssueReproductionArgsSchema.shape.issueNumber,performed:RecordIssueReproductionArgsSchema.shape.performed,commands:RecordIssueReproductionArgsSchema.shape.commands,output_summary:RecordIssueReproductionArgsSchema.shape.output_summary},execute:executeRecordIssueReproduction});init_zod();init_utils2();init_create_tool();import*as fs174 from"node:fs";import*as path289 from"node:path";var DispositionSchema=exports_external.object({ref:exports_external.string().trim().min(1).max(500),disposition:exports_external.enum(["FIX","FALSE_POSITIVE","OUT_OF_CLASS","DEFERRED_WITH_USER_APPROVAL"]),note:exports_external.string().trim().max(1000).optional()}).strict(),GuardrailSchema=exports_external.object({kind:exports_external.enum(["lint-static-analysis","type-level","runtime-assertion","ci-check","documented-invariant-plus-regression-test"]),description:exports_external.string().trim().min(8).max(2000),proof:exports_external.string().trim().min(8).max(4000)}).strict(),RecordRecurrenceSweepArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),defectClass:exports_external.string().trim().min(1).max(1000),justification:exports_external.string().trim().min(1).max(1000).optional(),predicates:exports_external.array(exports_external.string().trim().min(1).max(500)).min(1).max(32).optional(),dispositions:exports_external.array(DispositionSchema).max(200).optional(),guardrail:GuardrailSchema.optional()}).strict();async function executeRecordRecurrenceSweep(args2,directory,context={}){let parsed=RecordRecurrenceSweepArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recurrence sweep receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data,noDefectClass=data.defectClass==="no defect class";if(noDefectClass){if(!data.justification)return JSON.stringify({success:!1,message:'The "no defect class" fast path requires a one-line justification.'})}else if(!data.predicates||data.predicates.length===0||!data.dispositions||!data.guardrail)return JSON.stringify({success:!1,message:"A defect-class sweep requires search predicates, a disposition for every hit, and a guardrail with proof it catches the original defect."});let receipt={issueNumber:data.issueNumber,defectClass:data.defectClass,timestamp:new Date().toISOString()};if(data.justification)receipt.justification=data.justification;if(data.predicates)receipt.predicates=data.predicates;if(data.dispositions)receipt.dispositions=data.dispositions;if(data.guardrail)receipt.guardrail=data.guardrail;if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"recurrence-sweep.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{let dir=path289.dirname(validatedPath);await fs174.promises.mkdir(dir,{recursive:!0});let tmpPath=path289.join(dir,".recurrence-sweep.json.tmp");return await fs174.promises.writeFile(tmpPath,JSON.stringify(receipt,null,2),"utf-8"),await fs174.promises.rename(tmpPath,validatedPath),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/recurrence-sweep.json",message:noDefectClass?`Recurrence sweep recorded for issue #${data.issueNumber} (no defect class fast path).`:`Recurrence sweep recorded for issue #${data.issueNumber}; the trace may now satisfy its recurrence gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_recurrence_sweep=createSwarmTool({description:'Record the recurrence sweep for the current traced issue (issue #2131 residual B). The /swarm issue --trace workflow will not hand off to commit-pr until this receipt exists. For a real defect class supply: defectClass (one-sentence characterization), predicates (the exact search predicates), dispositions (every hit as FIX / FALSE_POSITIVE / OUT_OF_CLASS / DEFERRED_WITH_USER_APPROVAL), and a guardrail (kind + description + proof it catches the original defect). If the change corrects no incorrect behavior, use the literal defectClass "no defect class" with a one-line justification.',args:{issueNumber:RecordRecurrenceSweepArgsSchema.shape.issueNumber,defectClass:RecordRecurrenceSweepArgsSchema.shape.defectClass,justification:RecordRecurrenceSweepArgsSchema.shape.justification,predicates:RecordRecurrenceSweepArgsSchema.shape.predicates,dispositions:RecordRecurrenceSweepArgsSchema.shape.dispositions,guardrail:RecordRecurrenceSweepArgsSchema.shape.guardrail},execute:executeRecordRecurrenceSweep});init_zod();init_loader();init_schema();init_path_security();init_create_tool();import*as path290 from"node:path";var VALID_ACTIONS=["build","importers","dependencies","blast_radius","localization","key_files","ontology","package_boundaries","preflight_packet","callers","dead_exports","context_pack","graph_health","ask"],MAX_FILE_PATH_LENGTH3=500,MAX_SYMBOL_LENGTH2=256,MAX_QUESTION_LENGTH=500,REPO_GRAPH_DISABLED_NOTICE="Repository graph is disabled by configuration (repo_graph.enabled=false).",_internals217={loadPluginConfigWithMeta,probeFreshness,updateGraphForFiles,writeFingerprint};function validateFile(p){if(!p||typeof p!=="string")return"file is required";if(p.length===0)return"file is empty";if(p.length>MAX_FILE_PATH_LENGTH3)return`file exceeds maximum length of ${MAX_FILE_PATH_LENGTH3}`;if(containsControlChars(p))return"file contains control characters";if(containsPathTraversal(p))return"file contains path traversal";if(path290.isAbsolute(p)||/^[a-zA-Z]:[\\/]/.test(p))return"file must be a workspace-relative path, not absolute";return null}function validateSymbol(s){if(s.length===0)return"symbol is empty";if(s.length>MAX_SYMBOL_LENGTH2)return`symbol exceeds maximum length of ${MAX_SYMBOL_LENGTH2}`;if(containsControlChars(s))return"symbol contains control characters";return null}function validateQuestion(q){if(!q||q.trim().length===0)return"question is empty";if(q.length>MAX_QUESTION_LENGTH)return`question exceeds maximum length of ${MAX_QUESTION_LENGTH}`;if(containsControlChars(q))return"question contains control characters";return null}function err(action,message){return JSON.stringify({success:!1,action,error:message},null,2)}function ok(action,payload){return JSON.stringify({success:!0,action,...payload},null,2)}function resolveRepoGraphConfig(directory){try{let{config:config3}=_internals217.loadPluginConfigWithMeta(directory);return RepoGraphConfigSchema.parse(config3.repo_graph??{})}catch{return RepoGraphConfigSchema.parse({})}}function freshnessOptions(config3){return{maxFiles:config3.max_files,walkBudgetMs:config3.walk_budget_ms,excludeDirs:config3.exclude_dirs}}function uniqueDriftPaths(probe2){return[...new Set([...probe2.changed,...probe2.removed])]}function metadataForProbe(probe2,detectedFiles,refreshedFiles,freshnessNote){return{stale:probe2.state==="drifted"||probe2.state==="no-fingerprint",probeState:probe2.state,changedFiles:detectedFiles,refreshedFiles,...freshnessNote?{freshnessNote}:{}}}function toRelativeGraphPath(input,workspaceRoot){let normalized=input.replace(/\\/g,"/");if(path290.isAbsolute(normalized)){let rel=path290.relative(workspaceRoot,normalized).replace(/\\/g,"/");return normalizeGraphPath(rel)}return normalizeGraphPath(normalized)}async function loadOrError(directory,action){try{let graph=await loadGraph(directory);if(!graph)return{ok:!1,response:err(action,'No repo graph found at .swarm/repo-graph.json. Run repo_map with action="build" first.')};return{ok:!0,graph}}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return{ok:!1,response:err(action,`failed to load repo graph: ${message}`)}}}var repo_map=createSwarmTool({description:'Query the repository code graph for structural awareness before editing. Actions: "build" (build/refresh .swarm/repo-graph.json), "importers" (who imports a file), "dependencies" (what a file imports), "blast_radius" (transitive dependents + risk), "localization" (compact context block for a target file), "key_files" (top-N most-imported files), "ontology" (file roles/routes/data/security/findings), "package_boundaries" (inferred package/layer boundaries), "preflight_packet" (bounded ontology packet for planning), "callers" (files that reference an exported symbol, call-site granularity; needs file+symbol), "dead_exports" (advisory: exported symbols with no detected in-repo reference; results are review candidates, not delete directives), '+'"context_pack" (token-budgeted slice of source spans for a target symbol — definition + transitive callers/callees; advisory/conservative; needs file+symbol; uses max_depth for traversal depth, top_n for span cap; set include_source=true to embed source text in spans), '+'"graph_health" (freshness and bounded extraction diagnostics; no file required), '+'"ask" (zero-LLM file localization: pass a natural-language question to rank files by relevance via vocabulary expansion + IDF + PageRank; orientation only — read the located files before asserting anything about them). '+'Use this before refactoring shared modules to avoid breaking unseen consumers. Note: "callers"/"dead_exports"/"context_pack" use conservative regex analysis (TS/JS/Python) and cannot see dynamic dispatch or namespace/barrel re-export usage; "dead_exports" results are review candidates, not delete directives.',args:{action:exports_external.enum(["build","importers","dependencies","blast_radius","localization","key_files","ontology","package_boundaries","preflight_packet","callers","dead_exports","context_pack","graph_health","ask"]).describe('Query action: "build" | "importers" | "dependencies" | "blast_radius" | "localization" | "key_files" | "ontology" | "package_boundaries" | "preflight_packet" | "callers" | "dead_exports" | "context_pack" | "graph_health" | "ask"'),file:exports_external.string().optional().describe("Target file (workspace-relative or absolute). Required for importers/dependencies/localization/ontology. Optional for preflight_packet."),files:exports_external.array(exports_external.string()).optional().describe("Multiple target files for blast_radius/preflight_packet. If omitted, falls back to `file`."),symbol:exports_external.string().optional().describe('Exported symbol name. Restricts consumers on action="importers"; required for action="callers"/"context_pack".'),top_n:exports_external.number().int().min(1).max(100).optional().describe('For action="key_files"/"package_boundaries": entries to return (default 10). For action="dead_exports": max candidates (default 100). For action="context_pack": max spans returned (default ~40 via token budget).'),max_depth:exports_external.number().int().min(1).max(10).optional().describe('For action="blast_radius": max BFS depth (default 3). For action="context_pack": traversal depth (default 2).'),question:exports_external.string().optional().describe('Natural-language question for action="ask". Orientation only — read the located files before asserting anything about them.'),include_source:exports_external.boolean().optional().describe('For action="context_pack": embed source text in spans (default false).')},async execute(args2,directory,_ctx){let a=args2??{},action=String(a.action??"");if(!VALID_ACTIONS.includes(action))return err(action||"(none)",`unknown action; expected one of: ${VALID_ACTIONS.join(", ")}`);let repoGraphConfig=resolveRepoGraphConfig(directory);if(!repoGraphConfig.enabled)return err(action,REPO_GRAPH_DISABLED_NOTICE);let probeOptions=freshnessOptions(repoGraphConfig);if(action==="build")try{let start=Date.now(),graph2=await buildWorkspaceGraphAsync(directory,probeOptions);await saveGraph(directory,graph2);let fingerprintWritten=await _internals217.writeFingerprint(directory,graph2,probeOptions),elapsedMs=Date.now()-start,fileCount=Object.keys(graph2.nodes).length,edgeCount=graph2.edges.length,ontologyFileCount=Object.values(graph2.nodes).filter((node)=>node.ontology!==void 0).length;return ok(action,{fileCount,edgeCount,ontologyFileCount,buildTimestamp:graph2.metadata.generatedAt,elapsedMs,truncated:graph2.diagnostics?.walkTruncated===!0,fingerprintWritten,path:".swarm/repo-graph.json"})}catch(e){let message=e instanceof Error?e.message:String(e);return err(action,`build failed: ${message}`)}if(action==="graph_health")try{let graph2=await loadGraph(directory),probe3=await _internals217.probeFreshness(directory,probeOptions);return ok(action,{...getGraphHealth(graph2,directory,probe3)})}catch(e){let message=e instanceof Error?e.message:String(e);return err(action,`failed to load repo graph: ${message}`)}let loaded=await loadOrError(directory,action);if(!loaded.ok)return loaded.response;let graph=loaded.graph,probe2=await _internals217.probeFreshness(directory,probeOptions),driftPaths=uniqueDriftPaths(probe2),detectedFiles=driftPaths.length,refreshedFiles=0,freshnessNote;if(probe2.state==="drifted"&&detectedFiles>0)if(driftPaths.some(isGraphWideInputPath))freshnessNote="Graph-wide package manifest drift requires a full repo_map build; the stale graph was served without mutation.";else if(repoGraphConfig.refresh_cap>0&&detectedFiles<=repoGraphConfig.refresh_cap)try{if(graph=await _internals217.updateGraphForFiles(directory,driftPaths,{buildOptions:probeOptions}),refreshedFiles=detectedFiles,probe2=await _internals217.probeFreshness(directory,probeOptions),probe2.state!=="clean")freshnessNote="Incremental refresh completed, but the follow-up probe did not certify a clean graph."}catch(error93){freshnessNote=`Incremental refresh failed; serving the stale graph: ${error93 instanceof Error?error93.message:String(error93)}`}else freshnessNote=repoGraphConfig.refresh_cap===0?"Automatic read-time refresh is disabled by repo_graph.refresh_cap=0; serving the stale graph.":`Detected ${detectedFiles} changed files, above repo_graph.refresh_cap=${repoGraphConfig.refresh_cap}; serving the stale graph.`;else if(probe2.state==="no-fingerprint")freshnessNote='No matching repository-graph fingerprint is available; run repo_map action="build" to certify the graph.';else if(probe2.state==="inconclusive")freshnessNote="Workspace freshness is unknown because the bounded probe did not complete; the existing graph was served without refresh or deletion.";let freshness=metadataForProbe(probe2,detectedFiles,refreshedFiles,freshnessNote);if(action==="key_files"){let topN=a.top_n??10,nodes=getKeyFiles(graph,topN),totalFiles=Object.keys(graph.nodes).length,inDegrees=nodes.map((n)=>getImporters(graph,n.moduleName).length),maxInDegree=Math.max(1,...inDegrees),reverseCounts=nodes.map((n,i)=>({file:n.moduleName,language:n.language,exports:n.exports.length,roles:n.ontology?.roles??[],findings:n.ontology?.findings.length??0,inDegree:inDegrees[i],hubScore:Math.round(inDegrees[i]/maxInDegree*1e4)/1e4,community:n.ontology?.packageBoundary??inferPackageBoundary(n.moduleName)}));return ok(action,{count:reverseCounts.length,files:reverseCounts,budget:{returned:reverseCounts.length,dropped:Math.max(0,totalFiles-reverseCounts.length)},...freshness})}if(action==="package_boundaries"){let topN=a.top_n??10,boundaries=getPackageBoundaries(graph,topN),maxDepOnBy=Math.max(1,...boundaries.map((b)=>b.dependedOnBy.length)),enriched=boundaries.map((b)=>({...b,hubScore:Math.round(b.dependedOnBy.length/maxDepOnBy*1e4)/1e4,community:b.name})),totalBoundaries=new Set(Object.values(graph.nodes).map((n)=>n.ontology?.packageBoundary??inferPackageBoundary(n.moduleName))).size;return ok(action,{count:enriched.length,boundaries:enriched,budget:{returned:enriched.length,dropped:Math.max(0,totalBoundaries-enriched.length)},...freshness})}if(action==="dead_exports"){let result=getDeadExports(graph,{maxCandidates:a.top_n??100});return ok(action,{...result,budget:{returned:result.candidates.length},...freshness})}if(action==="preflight_packet"){let inputs=a.files&&a.files.length>0?a.files:a.file?[a.file]:[];for(let f of inputs){let v=validateFile(f);if(v)return err(action,`invalid file: ${v}`)}let targets=inputs.map((f)=>toRelativeGraphPath(f,directory));return ok(action,{packet:buildOntologyPreflightPacket(graph,targets,{maxFiles:a.top_n??12,maxBoundaries:10}),...freshness})}if(action==="ask"){if(!a.question)return err(action,"ask requires `question`");let qErr=validateQuestion(a.question);if(qErr)return err(action,`invalid question: ${qErr}`);let topN=Math.min(a.top_n??8,25),result=askGraph(graph,a.question,{topN});return ok(action,{...result,...freshness})}if(action==="blast_radius"){let inputs=a.files&&a.files.length>0?a.files:a.file?[a.file]:null;if(!inputs)return err(action,"blast_radius requires `file` or `files`");for(let f of inputs){let v=validateFile(f);if(v)return err(action,`invalid file: ${v}`)}let targets=inputs.map((f)=>toRelativeGraphPath(f,directory)),result=getBlastRadius(graph,targets,a.max_depth??3);return ok(action,{...result,...freshness})}if(!a.file)return err(action,`${action} requires \`file\``);let fileErr=validateFile(a.file);if(fileErr)return err(action,`invalid file: ${fileErr}`);let target=toRelativeGraphPath(a.file,directory);if(action==="importers"){if(a.symbol!==void 0){let sErr=validateSymbol(a.symbol);if(sErr)return err(action,`invalid symbol: ${sErr}`);let consumers=getSymbolConsumers(graph,target,a.symbol);return ok(action,{target,symbol:a.symbol,count:consumers.length,consumers,...freshness})}let importers=getImporters(graph,target);return ok(action,{target,count:importers.length,importers,...freshness})}if(action==="callers"){if(a.symbol===void 0)return err(action,"callers requires `symbol` (the exported name)");let sErr=validateSymbol(a.symbol);if(sErr)return err(action,`invalid symbol: ${sErr}`);let callers=getCallers(graph,target,a.symbol);return ok(action,{target,symbol:a.symbol,count:callers.length,callers,...freshness})}if(action==="context_pack"){if(a.symbol===void 0)return err(action,"context_pack requires `symbol` (the exported name)");let sErr=validateSymbol(a.symbol);if(sErr)return err(action,`invalid symbol: ${sErr}`);let raw=getContextPack(graph,target,a.symbol,{maxDepth:a.max_depth??2,maxTokens:4000,includeSource:a.include_source??!1,directory}),toRel=(p)=>{if(!path290.isAbsolute(p))return p.replace(/\\/g,"/");try{return path290.relative(directory,p).replace(/\\/g,"/")}catch{return p}},normalizedTarget={...raw.target,file:toRel(raw.target.file)},normalizedSpans=raw.spans.map((s)=>({...s,file:toRel(s.file)})).filter((s)=>s.file.length>0),truncated=raw.truncated||a.top_n!==void 0&&normalizedSpans.length>a.top_n,cappedSpans=a.top_n!==void 0?normalizedSpans.slice(0,a.top_n):normalizedSpans;return ok(action,{target:normalizedTarget,spans:cappedSpans,truncated,estimatedTokens:raw.estimatedTokens,budget:{returned:cappedSpans.length,dropped:Math.max(0,normalizedSpans.length-cappedSpans.length)},...freshness,schemaSupported:raw.schemaSupported,...raw.note?{note:raw.note}:{},...raw.sourceIncluded?{sourceIncluded:!0}:{}})}if(action==="dependencies"){let deps=getDependencies(graph,target);return ok(action,{target,count:deps.length,dependencies:deps,...freshness})}if(action==="localization"){let ctx=getLocalizationContext(graph,target,{maxDepth:a.max_depth});return ok(action,{...ctx,...freshness})}if(action==="ontology"){let ontology=getFileOntology(graph,target);if(!ontology)return err(action,`No ontology facts found for ${target}. Rebuild the graph if the file was recently added.`);return ok(action,{target,ontology,...freshness})}return err(action,"unhandled action")}});init_zod();init_effective_spec();init_logger();init_swarm_artifact_cache();init_create_tool();import*as fs175 from"node:fs";import*as path291 from"node:path";var EVIDENCE_DIR4=".swarm/evidence",OBLIGATION_KEYWORDS2=["MUST","SHOULD","SHALL"],MAX_FILE_SIZE_BYTES8=1048576;function extractRequirements(specContent){let requirements=[],lines=specContent.split(`
|
|
@@ -6688,8 +6690,8 @@ ${scopeWarning}`:scopeWarning}}function recoverTaskStateFromDelegations(taskId,d
|
|
|
6688
6690
|
`).trim(),text=bodyText.length>MAX_TEXT_LENGTH2?`${bodyText.slice(0,MAX_TEXT_LENGTH2)}…`:bodyText,textTruncated=outcome.truncated||bodyText.length>MAX_TEXT_LENGTH2,evidence2=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:evidence2};return JSON.stringify(ok2,null,2)}});async function captureFetchEvidence(directory,url3,title,text){try{let written=await _internals228.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 _internals228={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,now2=new Date){let originalQuery=rawQuery,query=rawQuery.trim().replace(/\s+/g," "),currentYear=now2.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}),evidence2=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:evidence2.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:evidence2.stored,path:evidence2.path,refs:evidence2.refs,error:evidence2.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 _internals229.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 _internals229={writeEvidenceDocuments};init_zod();init_loader();init_schema();init_curator_llm_factory();init_knowledge_curator();init_skill_generator();init_schema3();init_store4();init_create_tool();init_resolve_working_directory();import*as path307 from"node:path";var FindingSchema3=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(FindingSchema3).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(FindingSchema3).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,path307.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 fs188 from"node:fs";import path308 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_swarm_artifact_cache();init_create_tool();function buildApprovedPreflightFailure(phase,failure3){return JSON.stringify({success:!1,phase,reason:failure3.reason,message:failure3.message,recovery_guidance:failure3.recovery_guidance},null,2)}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=_internals230.normalizeVerdict2(args2.verdict),approvedPlan=null,snapshotInfo,qaProfileLocked;if(normalizedVerdict==="approved"){if(approvedPlan=await loadPlanJsonOnly(directory),!approvedPlan)return buildApprovedPreflightFailure(phase,{reason:"plan_required_for_approval",message:"PLAN_REQUIRED_FOR_APPROVAL: plan.json must exist before APPROVED drift evidence can be persisted.",recovery_guidance:"Restore the current .swarm/plan.json and ensure the exact plan identity is available before retrying write_drift_evidence."});let profileLookup=getProfileLookupForIdentity(directory,approvedPlan);if(profileLookup.kind==="missing")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_selection_required",message:"QA_GATE_SELECTION_REQUIRED: no durable QA gate selection exists for this exact plan identity.",recovery_guidance:`Call set_qa_gates with swarm_id=${JSON.stringify(approvedPlan.swarm)} and plan_title=${JSON.stringify(approvedPlan.title)} before retrying write_drift_evidence with the identical identity.`});if(profileLookup.kind==="unbound_legacy")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_identity_unbound",message:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",recovery_guidance:formatLegacyQaBindingRecovery({swarm:approvedPlan.swarm,title:approvedPlan.title},"retry write_drift_evidence with the identical identity")});try{let lockAnchor=await takeSnapshotEvent(directory,approvedPlan,{source:"drift_approval_prelock"}),planId=derivePlanId(approvedPlan),locked=_internals230.lockProfileForIdentity(directory,approvedPlan,lockAnchor.seq),lockedBySnapshotSeq=locked.locked_by_snapshot_seq??lockAnchor.seq,approvedSnapshot=await takeSnapshotEvent(directory,approvedPlan,{source:"critic_approved",approvalMetadata:{phase,verdict:"APPROVED",summary:summary.trim(),approved_at:new Date().toISOString(),locked_by_snapshot_seq:lockedBySnapshotSeq}});snapshotInfo={seq:approvedSnapshot.seq,timestamp:approvedSnapshot.timestamp,locked_by_snapshot_seq:lockedBySnapshotSeq},qaProfileLocked={plan_id:planId,locked_at:locked.locked_at??"",locked_by_snapshot_seq:locked.locked_by_snapshot_seq??-1}}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return log("[write_drift_evidence] critic-approved persistence failed:",message),buildApprovedPreflightFailure(phase,{reason:"approval_persistence_failed",message:`APPROVAL_PERSISTENCE_FAILED: QA gate profile lock or critic-approved snapshot failed: ${message}`,recovery_guidance:"Resolve the ledger or QA profile persistence failure, then rerun write_drift_evidence. A completed profile lock is idempotent, and no visible approval is published until both persistence steps succeed."})}}let 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=path308.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=path308.dirname(validatedPath);try{await fs188.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path308.join(evidenceDir,`.${filename}.tmp`);return await fs188.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs188.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Drift evidence written to .swarm/evidence/${phase}/drift-verifier.json`,approvedSnapshot:snapshotInfo,qaProfileLocked},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals230={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2,lockProfileForIdentity},write_drift_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,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 fs189 from"node:fs";import path309 from"node:path";init_lock();init_utils2();init_config2();init_gateway();init_reward_capture();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();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"}function invalidResponse3(issues){return JSON.stringify({success:!1,reason:"invalid arguments",errors:issues.map((issue3)=>({path:issue3.path.join("."),message:issue3.message}))},null,2)}async function executeWriteFinalCouncilEvidence(args2,directory,ctx){let parsed=ArgsSchema9.safeParse(args2);if(!parsed.success)return await recordUnscopedCouncilAttempt(directory,"final","invalid_arguments",args2,parsed.error.issues.map((issue3)=>({path:issue3.path,code:issue3.code})),ctx?.sessionID)??invalidResponse3(parsed.error.issues);let input=parsed.data,config3=loadPluginConfig(directory),plan=null;try{plan=await loadPlan(directory)}catch{}let planHash=plan?computePlanHash(plan):void 0,planId=plan?derivePlanId(plan):void 0,planIdentityHash=plan?derivePlanIdentityHash(plan):void 0,membersVoted=[...new Set(input.verdicts.map((v)=>v.agent))],membersAbsent=FINAL_COUNCIL_MEMBERS.filter((member)=>!membersVoted.includes(member));return runCouncilAttempt({directory,scope:{kind:"final",generation:planHash??"missing-plan"},clientRound:input.roundNumber,maxRounds:config3.council?.maxRounds??3,sessionID:ctx?.sessionID,request:input,verdictCount:input.verdicts.length,members:membersVoted,probePendingEvidence:async(attemptId,round)=>hasFinalEvidenceAttempt(directory,attemptId,round),evaluate:async(authoritativeRound)=>{if(membersVoted.length<FINAL_COUNCIL_MEMBERS.length)return{disposition:"insufficient_quorum",response:{success:!1,reason:"insufficient_quorum",message:`Final council quorum not met: ${membersVoted.length} of ${FINAL_COUNCIL_MEMBERS.length} 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:FINAL_COUNCIL_MEMBERS.length},transition:"stay",gateEffect:"none"};let synthesis=synthesizeFinalCouncilAdvisory(input.projectSummary.trim(),input.verdicts,authoritativeRound,config3.council);if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return{disposition:"blocking_concerns_unresolved",response:{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.`},transition:"advance",gateEffect:"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize};if(!plan)return{disposition:"plan_not_found",response:{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"},transition:"stay",gateEffect:"none"};let 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},validatedPath;try{validatedPath=_internals231.validateSwarmPath(directory,path309.join("evidence","final-council.json"))}catch(error93){return{disposition:"invalid_evidence_path",response:{success:!1,phase:input.phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},transition:"stay",gateEffect:"none"}}let evidenceDir=path309.dirname(validatedPath),accepted=synthesis.overallVerdict==="APPROVE"||synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount===0;return{disposition:`evaluated_${synthesis.overallVerdict.toLowerCase()}`,response:{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"},transition:accepted?"close":"advance",gateEffect:accepted?"allowed":"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,evidence:{reference:synthesis.evidencePath,commit:async(attemptId)=>{await withEvidenceLock(directory,path309.join("evidence","final-council.json"),"write-final-council-evidence",attemptId,async()=>{let currentPlan=await loadPlan(directory);if(!currentPlan||computePlanHash(currentPlan)!==planHash)throw Error("final council plan changed before evidence publication");await fs189.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path309.join(evidenceDir,`.final-council.${attemptId}.tmp`);try{await fs189.promises.writeFile(tempPath,JSON.stringify({entries:[{...evidenceEntry,attemptId}]},null,2),"utf-8"),await fs189.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath)}finally{await fs189.promises.rm(tempPath,{force:!0}).catch(()=>{})}})}},afterCommit:async()=>{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)}`)}}}}})}var write_final_council_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,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 the current server round."),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)=>executeWriteFinalCouncilEvidence(args2,directory,ctx)});function hasFinalEvidenceAttempt(directory,attemptId,round){try{let evidencePath=validateSwarmPath(directory,path309.join("evidence","final-council.json")),parsed=JSON.parse(fs189.readFileSync(evidencePath,"utf8"));return Boolean(parsed.entries?.some((entry)=>entry.type==="final-council"&&entry.attemptId===attemptId&&entry.roundNumber===round))}catch{return!1}}var _internals231={validateSwarmPath};init_zod();import fs190 from"node:fs";import path310 from"node:path";init_utils2();init_swarm_artifact_cache();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=_internals232.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=path310.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=path310.dirname(validatedPath);try{await fs190.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path310.join(evidenceDir,`.${filename}.tmp`);return await fs190.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs190.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(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 _internals232={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2},write_hallucination_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,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 fs191 from"node:fs";import path311 from"node:path";init_utils2();init_swarm_artifact_cache();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=_internals233.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=path311.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=path311.dirname(validatedPath);try{await fs191.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path311.join(evidenceDir,`.${filename}.tmp`);return await fs191.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs191.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(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 _internals233={normalizeVerdict4,VERDICT_SET_4,isAcceptedVerdict4},write_mutation_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,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_candidate_contract();init_pr_workflow_gate();init_utils2();init_create_tool();import{randomUUID as randomUUID31}from"node:crypto";import*as fs192 from"node:fs";import*as path312 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"),FindingSchema4=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(CANDIDATE_SEVERITIES).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(FindingSchema4).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 stat21=await fs192.promises.stat(filePath);if(!stat21.isFile()||stat21.size>10485760)throw Error("findings artifact is not a bounded regular file");return(await fs192.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 fs192.promises.mkdir(path312.dirname(filePath),{recursive:!0});let tempPath=path312.join(path312.dirname(filePath),`.${path312.basename(filePath)}.${randomUUID31()}.tmp`);try{await fs192.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"}),await fs192.promises.rename(tempPath,filePath)}finally{await fs192.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=path312.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(`
|
|
6689
6691
|
`)+(allRecords.length>0?`
|
|
6690
6692
|
`:""));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(path312.sep).join("/"),findingIds,handoffRequired),JSON.stringify({success:!0,path:relativeFindingsPath.split(path312.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=path312.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)}
|
|
6691
|
-
`),await markPrReviewHandoffComplete(directory,sessionID,parsed.data.run_id,relativeHandoffPath.split(path312.sep).join("/")),JSON.stringify({success:!0,path:relativeHandoffPath.split(path312.sep).join("/"),finding_count:actionableIds.length},null,2)}var write_pr_review_artifact=createSwarmTool({allowWorkingDirectoryOverride:!0,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(FindingSchema4).min(1).max(1000).optional(),handoff:HandoffSchema.optional()},execute:executeWritePrReviewArtifact});init_zod();init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_pr_workflow_gate();init_utils2();init_create_tool();init_pr_review_trigger_contract();import{randomUUID as randomUUID32}from"node:crypto";import fs193 from"node:fs";import path313 from"node:path";var _internals234={resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,resolveMergeBase:resolveExactMergeBase};async function resolveCurrentRevisionDigest(directory,prHeadSha){if(_internals234.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _internals234.resolvePrWorkflowRevisionDigest(directory,prHeadSha);return _internals234.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha)}var 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(PrReviewWriterInputRowSchema).min(1)}).strict();function failure4(message){return JSON.stringify({success:!1,message},null,2)}async function executeWritePrReviewTriggerEval(args2,directory,context={}){let writerLedger;try{writerLedger=validatePrReviewWriterInputLedger(typeof args2==="object"&&args2!==null?args2.rows:void 0)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}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 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}`);if(gateState.prReviewArtifactRunId&&gateState.prReviewArtifactRunId!==parsed.data.run_id)return failure4(`PR_REVIEW trigger evaluation run_id must match the findings artifact run "${gateState.prReviewArtifactRunId}"`);if(gateState.prReviewTriggerEvalRunId&&gateState.prReviewTriggerEvalRunId!==parsed.data.run_id)return failure4(`PR_REVIEW trigger evaluation is already bound to run "${gateState.prReviewTriggerEvalRunId}"`);try{await assertPrReviewBaseCoverageSettled(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(!gateState.prReviewTriggerLedger)return failure4("PR_REVIEW trigger evaluation requires the canonical ledger frozen by the first micro dispatch");let frozenLedger;try{frozenLedger=validatePrReviewInlineTriggerLedger(gateState.prReviewTriggerLedger)}catch(error93){return failure4(`Persisted PR_REVIEW trigger ledger is invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}let classificationDrift=frozenLedger.rows.filter((row,index)=>writerLedger.rows[index]?.result!==row.result).map((row)=>row.trigger_id);if(classificationDrift.length>0)return failure4(`PR_REVIEW trigger classification drift from the canonical ledger frozen across micro dispatches: ${classificationDrift.join(", ")}`);let triggerLedger;try{triggerLedger=validatePrReviewPersistedInputLedger(frozenLedger.rows.map((frozenRow,index)=>{let writerRow=writerLedger.rows[index];if(frozenRow.result==="NOT_TRIGGERED")return frozenRow;if(!writerRow||writerRow.result!=="MATCHED")throw Error(`missing MATCHED provenance for ${frozenRow.trigger_id}`);return{...frozenRow,source_batch_id:writerRow.source_batch_id,source_lane_id:writerRow.source_lane_id}}))}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let validatedRows=triggerLedger.rows,currentRevisionDigest=await resolveCurrentRevisionDigest(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,coverageDegradations=[];for(let row of validatedRows){if(row.result!=="MATCHED")continue;let record3=findByBatchId(directory,row.source_batch_id,{parentSessionId:sessionID}).find((candidate2)=>candidate2.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.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||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 verifiable micro-lane provenance chain`);let degradationReasons=[];if(record3.status!=="completed")degradationReasons.push(`lane status ${record3.status}`);if(record3.result?.outputDegraded===!0)degradationReasons.push("output degraded");if(record3.result?.transcriptIncomplete===!0)degradationReasons.push("transcript incomplete");if(record3.result?.truncated===!0)degradationReasons.push("output truncated");if((record3.result?.chars??0)<=0)degradationReasons.push("empty output");if(!prReviewDiscoveryArtifactCoversLane(outputArtifact.artifact.text,row.trigger_id,recordOwnedLanes,record3.mode))degradationReasons.push(`no covered candidate or clean row for: ${row.trigger_id}`);for(let reason of degradationReasons)coverageDegradations.push({trigger_id:row.trigger_id,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id,reason})}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(", ")}`)}let matchedFamilySet=new Set(triggerLedger.matchedIds),citedOwnershipSet=new Set(citedLaneEntries.flatMap(([,owned])=>owned)),ownershipOutsideMatchedLedger=[...citedOwnershipSet].filter((family)=>!matchedFamilySet.has(family)),matchedWithoutOwnedLane=[...matchedFamilySet].filter((family)=>!citedOwnershipSet.has(family));if(ownershipOutsideMatchedLedger.length>0||matchedWithoutOwnedLane.length>0)return failure4(`PR_REVIEW cited lane ownership must equal the MATCHED trigger set; owned but NOT_TRIGGERED/unlisted: ${ownershipOutsideMatchedLedger.join(", ")||"(none)"}; MATCHED without cited ownership: ${matchedWithoutOwnedLane.join(", ")||"(none)"}`);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=_internals234.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 matchedCount=validatedRows.filter((row)=>row.result==="MATCHED").length,dispatchedMicroLaneCount2=new Set(validatedRows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size,microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[gateState.prReviewDepthTier??"L"],matchedCount);if(dispatchedMicroLaneCount2<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 ${matchedCount} matched families to only ${dispatchedMicroLaneCount2}`);let artifact=buildPrReviewTriggerReceiptV2({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(),dispatched_micro_lane_count:dispatchedMicroLaneCount2,rows:validatedRows,coverage_degradations:coverageDegradations}),relativePath2=path313.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))}if(fs193.existsSync(destination))return failure4(`PR_REVIEW trigger evaluation receipt already exists for run "${parsed.data.run_id}" and cannot be overwritten; abort the workflow with abort_pr_workflow to restart`);let parent=path313.dirname(destination),tempPath=path313.join(parent,`.trigger-eval.${randomUUID32()}.tmp`);try{await fs193.promises.mkdir(parent,{recursive:!0}),await fs193.promises.writeFile(tempPath,`${JSON.stringify(artifact,null,2)}
|
|
6692
|
-
`,{encoding:"utf-8",flag:"wx"}),await fs193.promises.rename(tempPath,destination)}catch(error93){return failure4(`Failed to persist trigger evaluation: ${error93 instanceof Error?error93.message:String(error93)}`)}finally{await fs193.promises.rm(tempPath,{force:!0}).catch(()=>{return})}return await markPrReviewTriggerEvaluationComplete(directory,sessionID,parsed.data.run_id,relativePath2.split(path313.sep).join("/")),JSON.stringify({success:!0,path:relativePath2.split(path313.sep).join("/"),trigger_count:artifact.trigger_count,matched_count:artifact.matched_count,not_triggered_count:artifact.not_triggered_count,no_match_count:artifact.no_match_count,dispatched_micro_lane_count:dispatchedMicroLaneCount2,coverage_degradation_count:coverageDegradations.length,...coverageDegradations.length>0?{coverage_degradations:coverageDegradations,note:"degraded families recorded on the receipt; disclose them in the final review report"}:{}},null,2)}var write_pr_review_trigger_eval=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Persist the complete, exact-set PR-review trigger receipt after every MATCHED family has completed. Supply classifications and MATCHED provenance; evidence is optional and non-authoritative because the receipt reuses evidence frozen by the first micro dispatch. NOT_TRIGGERED families remain provenance-free.",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,approve_plan_critic:()=>approve_plan_critic,prepare_pr_workflow_checkout:()=>prepare_pr_workflow_checkout,record_implementation_review:()=>record_implementation_review,record_issue_publication:()=>record_issue_publication,record_issue_reproduction:()=>record_issue_reproduction,record_recurrence_sweep:()=>record_recurrence_sweep,rebind_pr_feedback_head:()=>rebind_pr_feedback_head,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,plan_conflict_check:()=>plan_conflict_check,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,consensus_mine:()=>consensus_mine,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,pr_workflow_status:()=>pr_workflow_status,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,reviewModelDispatcher,generatedAgentNames=Object.keys(agents),reviewAgentModelRegistry,getActiveAgentName){let tools={},reviewAgentNames=Object.freeze([...generatedAgentNames]),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,reviewModelDispatcher,config3?.auto_review,reviewAgentModelRegistry,getActiveAgentName),tools.phase_complete=createPhaseCompleteTool({reviewModelDispatcher,generatedAgentNames:reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName}),tools.lean_turbo_review=createLeanTurboReviewTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_run_phase=createLeanTurboRunPhaseTool(reviewAgentNames),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(`
|
|
6693
|
+
`),await markPrReviewHandoffComplete(directory,sessionID,parsed.data.run_id,relativeHandoffPath.split(path312.sep).join("/")),JSON.stringify({success:!0,path:relativeHandoffPath.split(path312.sep).join("/"),finding_count:actionableIds.length},null,2)}var write_pr_review_artifact=createSwarmTool({allowWorkingDirectoryOverride:!0,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(FindingSchema4).min(1).max(1000).optional(),handoff:HandoffSchema.optional()},execute:executeWritePrReviewArtifact});init_zod();init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_pr_workflow_gate();init_utils2();init_logger();init_create_tool();init_pr_review_trigger_contract();import{randomUUID as randomUUID32}from"node:crypto";import fs193 from"node:fs";import path313 from"node:path";var _internals234={resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,resolveMergeBase:resolveExactMergeBase,resolveMergeBaseAsync:resolveExactMergeBaseAsync};async function resolveCurrentRevisionDigest(directory,prHeadSha){if(_internals234.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _internals234.resolvePrWorkflowRevisionDigest(directory,prHeadSha);return _internals234.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha)}var REVISION_DIGEST_RESOLUTION_ATTEMPTS=2;async function resolveCurrentRevisionDigestWithRetry(directory,prHeadSha){for(let attempt=1;attempt<=REVISION_DIGEST_RESOLUTION_ATTEMPTS;attempt+=1){let digest3=await resolveCurrentRevisionDigest(directory,prHeadSha);if(digest3)return digest3}return null}async function resolveReviewMergeBase(directory,baseRef,prHeadSha){if(_internals234.resolveMergeBase!==resolveExactMergeBase)return _internals234.resolveMergeBase(directory,baseRef,prHeadSha);return _internals234.resolveMergeBaseAsync(directory,baseRef,prHeadSha)}var 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(PrReviewWriterInputRowSchema).min(1)}).strict();function failure4(message){return JSON.stringify({success:!1,message},null,2)}async function executeWritePrReviewTriggerEval(args2,directory,context={}){let writerLedger;try{writerLedger=validatePrReviewWriterInputLedger(typeof args2==="object"&&args2!==null?args2.rows:void 0)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}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 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}`);if(gateState.prReviewArtifactRunId&&gateState.prReviewArtifactRunId!==parsed.data.run_id)return failure4(`PR_REVIEW trigger evaluation run_id must match the findings artifact run "${gateState.prReviewArtifactRunId}"`);if(gateState.prReviewTriggerEvalRunId&&gateState.prReviewTriggerEvalRunId!==parsed.data.run_id)return failure4(`PR_REVIEW trigger evaluation is already bound to run "${gateState.prReviewTriggerEvalRunId}"`);try{await assertPrReviewBaseCoverageSettled(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(!gateState.prReviewTriggerLedger)return failure4("PR_REVIEW trigger evaluation requires the canonical ledger frozen by the first micro dispatch");let frozenLedger;try{frozenLedger=validatePrReviewInlineTriggerLedger(gateState.prReviewTriggerLedger)}catch(error93){return failure4(`Persisted PR_REVIEW trigger ledger is invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}let classificationDrift=frozenLedger.rows.filter((row,index)=>writerLedger.rows[index]?.result!==row.result).map((row)=>row.trigger_id);if(classificationDrift.length>0)return failure4(`PR_REVIEW trigger classification drift from the canonical ledger frozen across micro dispatches: ${classificationDrift.join(", ")}`);let triggerLedger;try{triggerLedger=validatePrReviewPersistedInputLedger(frozenLedger.rows.map((frozenRow,index)=>{let writerRow=writerLedger.rows[index];if(frozenRow.result==="NOT_TRIGGERED")return frozenRow;if(!writerRow||writerRow.result!=="MATCHED")throw Error(`missing MATCHED provenance for ${frozenRow.trigger_id}`);return{...frozenRow,source_batch_id:writerRow.source_batch_id,source_lane_id:writerRow.source_lane_id}}))}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let validatedRows=triggerLedger.rows,currentRevisionDigest=await resolveCurrentRevisionDigestWithRetry(directory,parsed.data.pr_head_sha);if(!currentRevisionDigest)return failure4(`Active PR_REVIEW trigger evaluation could not bind the current exact revision digest for pr_head_sha "${parsed.data.pr_head_sha}" after ${REVISION_DIGEST_RESOLUTION_ATTEMPTS} attempts. A null digest collapses several causes: the bounded git call timed out, the git process failed to spawn, the working tree could not be read, or pr_head_sha was rejected as an unsafe revision token. This fails closed on purpose and has no bound-value fallback — no independently-bound durable PR_REVIEW revision digest exists to compare against, so accepting an unresolved digest would let a lane artifact self-certify its own revision. Nothing was persisted, so this call is retryable as-is. Recovery: confirm the checkout is readable and pr_head_sha exists here (git rev-parse), retry once the environment settles, or restart with abort_pr_workflow (kind "recovery").`);let citedLaneOwnership=new Map,coverageDegradations=[];for(let row of validatedRows){if(row.result!=="MATCHED")continue;let record3=findByBatchId(directory,row.source_batch_id,{parentSessionId:sessionID}).find((candidate2)=>candidate2.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.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||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 verifiable micro-lane provenance chain`);let degradationReasons=[];if(record3.status!=="completed")degradationReasons.push(`lane status ${record3.status}`);if(record3.result?.outputDegraded===!0)degradationReasons.push("output degraded");if(record3.result?.transcriptIncomplete===!0)degradationReasons.push("transcript incomplete");if(record3.result?.truncated===!0)degradationReasons.push("output truncated");if((record3.result?.chars??0)<=0)degradationReasons.push("empty output");if(!prReviewDiscoveryArtifactCoversLane(outputArtifact.artifact.text,row.trigger_id,recordOwnedLanes,record3.mode))degradationReasons.push(`no covered candidate or clean row for: ${row.trigger_id}`);for(let reason of degradationReasons)coverageDegradations.push({trigger_id:row.trigger_id,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id,reason})}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(", ")}`)}let matchedFamilySet=new Set(triggerLedger.matchedIds),citedOwnershipSet=new Set(citedLaneEntries.flatMap(([,owned])=>owned)),ownershipOutsideMatchedLedger=[...citedOwnershipSet].filter((family)=>!matchedFamilySet.has(family)),matchedWithoutOwnedLane=[...matchedFamilySet].filter((family)=>!citedOwnershipSet.has(family));if(ownershipOutsideMatchedLedger.length>0||matchedWithoutOwnedLane.length>0)return failure4(`PR_REVIEW cited lane ownership must equal the MATCHED trigger set; owned but NOT_TRIGGERED/unlisted: ${ownershipOutsideMatchedLedger.join(", ")||"(none)"}; MATCHED without cited ownership: ${matchedWithoutOwnedLane.join(", ")||"(none)"}`);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");if(!gateState.prReviewBaseRef||!gateState.prReviewBaseSha)return failure4('Active PR_REVIEW trigger evaluation requires a durably bound review base; the active PR_REVIEW gate has no bound base_ref/base_sha, so the received scope cannot be verified against anything. Re-bind the review scope by dispatching the review lanes for this PR, or restart with abort_pr_workflow (kind "recovery").');let resolvedMergeBase=await resolveReviewMergeBase(directory,parsed.data.base_ref,parsed.data.pr_head_sha),baseVerification="live";if(resolvedMergeBase){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}`)}else if(parsed.data.base_ref===gateState.prReviewBaseRef&&parsed.data.base_sha.toLowerCase()===gateState.prReviewBaseSha)baseVerification="bound_fallback",criticalWarn(`PR_REVIEW trigger evaluation could not re-derive the merge base for base_ref "${parsed.data.base_ref}" at pr_head_sha "${parsed.data.pr_head_sha}"; proceeding on the durably bound, bind-time-verified review scope (${gateState.prReviewBaseRef} at ${gateState.prReviewBaseSha}). The receipt discloses base_verification: bound_fallback and the final review report must disclose it too.`);else return failure4(`Active PR_REVIEW trigger evaluation could not resolve the exact merge base from base_ref "${parsed.data.base_ref}" and pr_head_sha "${parsed.data.pr_head_sha}", and the received scope does not equal the durably bound review scope (${gateState.prReviewBaseRef} at ${gateState.prReviewBaseSha}), so the bound-scope fallback does not apply. A null resolution collapses several causes: the bounded git call timed out, the git process failed to spawn, base_ref is not resolvable in this checkout, or base_ref/pr_head_sha was rejected as an unsafe revision token. Recovery: verify both revisions exist here (git rev-parse), retry once the environment settles, or restart with abort_pr_workflow (kind "recovery").`);let matchedCount=validatedRows.filter((row)=>row.result==="MATCHED").length,dispatchedMicroLaneCount2=new Set(validatedRows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size,microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[gateState.prReviewDepthTier??"L"],matchedCount);if(dispatchedMicroLaneCount2<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 ${matchedCount} matched families to only ${dispatchedMicroLaneCount2}`);let artifact=buildPrReviewTriggerReceiptV2({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(),dispatched_micro_lane_count:dispatchedMicroLaneCount2,rows:validatedRows,coverage_degradations:coverageDegradations,base_verification:baseVerification}),relativePath2=path313.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))}if(fs193.existsSync(destination))return failure4(`PR_REVIEW trigger evaluation receipt already exists for run "${parsed.data.run_id}" and cannot be overwritten; abort the workflow with abort_pr_workflow to restart`);let parent=path313.dirname(destination),tempPath=path313.join(parent,`.trigger-eval.${randomUUID32()}.tmp`);try{await fs193.promises.mkdir(parent,{recursive:!0}),await fs193.promises.writeFile(tempPath,`${JSON.stringify(artifact,null,2)}
|
|
6694
|
+
`,{encoding:"utf-8",flag:"wx"}),await fs193.promises.rename(tempPath,destination)}catch(error93){return failure4(`Failed to persist trigger evaluation: ${error93 instanceof Error?error93.message:String(error93)}`)}finally{await fs193.promises.rm(tempPath,{force:!0}).catch(()=>{return})}return await markPrReviewTriggerEvaluationComplete(directory,sessionID,parsed.data.run_id,relativePath2.split(path313.sep).join("/")),JSON.stringify({success:!0,path:relativePath2.split(path313.sep).join("/"),trigger_count:artifact.trigger_count,matched_count:artifact.matched_count,not_triggered_count:artifact.not_triggered_count,no_match_count:artifact.no_match_count,dispatched_micro_lane_count:dispatchedMicroLaneCount2,base_verification:baseVerification,...baseVerification==="bound_fallback"?{base_verification_note:"live merge-base re-derivation was unavailable; the bound review scope was used and MUST be disclosed in the final review report"}:{},coverage_degradation_count:coverageDegradations.length,...coverageDegradations.length>0?{coverage_degradations:coverageDegradations,note:"degraded families recorded on the receipt; disclose them in the final review report"}:{}},null,2)}var write_pr_review_trigger_eval=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Persist the complete, exact-set PR-review trigger receipt after every MATCHED family has completed. Supply classifications and MATCHED provenance; evidence is optional and non-authoritative because the receipt reuses evidence frozen by the first micro dispatch. NOT_TRIGGERED families remain provenance-free.",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,approve_plan_critic:()=>approve_plan_critic,prepare_pr_workflow_checkout:()=>prepare_pr_workflow_checkout,record_implementation_review:()=>record_implementation_review,record_issue_publication:()=>record_issue_publication,record_issue_reproduction:()=>record_issue_reproduction,record_recurrence_sweep:()=>record_recurrence_sweep,rebind_pr_feedback_head:()=>rebind_pr_feedback_head,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,plan_conflict_check:()=>plan_conflict_check,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,consensus_mine:()=>consensus_mine,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,pr_workflow_status:()=>pr_workflow_status,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,reviewModelDispatcher,generatedAgentNames=Object.keys(agents),reviewAgentModelRegistry,getActiveAgentName){let tools={},reviewAgentNames=Object.freeze([...generatedAgentNames]),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,reviewModelDispatcher,config3?.auto_review,reviewAgentModelRegistry,getActiveAgentName),tools.phase_complete=createPhaseCompleteTool({reviewModelDispatcher,generatedAgentNames:reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName}),tools.lean_turbo_review=createLeanTurboReviewTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_run_phase=createLeanTurboRunPhaseTool(reviewAgentNames),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(`
|
|
6693
6695
|
`);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(`
|
|
6694
6696
|
`)}
|
|
6695
6697
|
${tailContent.join(`
|